You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3425 lines
121KB

  1. /*
  2. * Copyright (c) 2000-2003 Fabrice Bellard
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file
  22. * multimedia converter based on the FFmpeg libraries
  23. */
  24. #include "config.h"
  25. #include <ctype.h>
  26. #include <string.h>
  27. #include <math.h>
  28. #include <stdlib.h>
  29. #include <errno.h>
  30. #include <limits.h>
  31. #if HAVE_ISATTY
  32. #if HAVE_IO_H
  33. #include <io.h>
  34. #endif
  35. #if HAVE_UNISTD_H
  36. #include <unistd.h>
  37. #endif
  38. #endif
  39. #include "libavformat/avformat.h"
  40. #include "libavdevice/avdevice.h"
  41. #include "libswscale/swscale.h"
  42. #include "libswresample/swresample.h"
  43. #include "libavutil/opt.h"
  44. #include "libavutil/channel_layout.h"
  45. #include "libavutil/parseutils.h"
  46. #include "libavutil/samplefmt.h"
  47. #include "libavutil/fifo.h"
  48. #include "libavutil/intreadwrite.h"
  49. #include "libavutil/dict.h"
  50. #include "libavutil/mathematics.h"
  51. #include "libavutil/pixdesc.h"
  52. #include "libavutil/avstring.h"
  53. #include "libavutil/libm.h"
  54. #include "libavutil/imgutils.h"
  55. #include "libavutil/timestamp.h"
  56. #include "libavutil/bprint.h"
  57. #include "libavutil/time.h"
  58. #include "libavformat/os_support.h"
  59. #include "libavformat/ffm.h" // not public API
  60. # include "libavfilter/avcodec.h"
  61. # include "libavfilter/avfilter.h"
  62. # include "libavfilter/buffersrc.h"
  63. # include "libavfilter/buffersink.h"
  64. #if HAVE_SYS_RESOURCE_H
  65. #include <sys/time.h>
  66. #include <sys/types.h>
  67. #include <sys/resource.h>
  68. #elif HAVE_GETPROCESSTIMES
  69. #include <windows.h>
  70. #endif
  71. #if HAVE_GETPROCESSMEMORYINFO
  72. #include <windows.h>
  73. #include <psapi.h>
  74. #endif
  75. #if HAVE_SYS_SELECT_H
  76. #include <sys/select.h>
  77. #endif
  78. #if HAVE_TERMIOS_H
  79. #include <fcntl.h>
  80. #include <sys/ioctl.h>
  81. #include <sys/time.h>
  82. #include <termios.h>
  83. #elif HAVE_KBHIT
  84. #include <conio.h>
  85. #endif
  86. #if HAVE_PTHREADS
  87. #include <pthread.h>
  88. #endif
  89. #include <time.h>
  90. #include "ffmpeg.h"
  91. #include "cmdutils.h"
  92. #include "libavutil/avassert.h"
  93. const char program_name[] = "ffmpeg";
  94. const int program_birth_year = 2000;
  95. static FILE *vstats_file;
  96. const char *const forced_keyframes_const_names[] = {
  97. "n",
  98. "n_forced",
  99. "prev_forced_n",
  100. "prev_forced_t",
  101. "t",
  102. NULL
  103. };
  104. static void do_video_stats(OutputStream *ost, int frame_size);
  105. static int64_t getutime(void);
  106. static int64_t getmaxrss(void);
  107. static int run_as_daemon = 0;
  108. static int64_t video_size = 0;
  109. static int64_t audio_size = 0;
  110. static int64_t subtitle_size = 0;
  111. static int64_t extra_size = 0;
  112. static int nb_frames_dup = 0;
  113. static int nb_frames_drop = 0;
  114. static int64_t decode_error_stat[2];
  115. static int current_time;
  116. AVIOContext *progress_avio = NULL;
  117. static uint8_t *subtitle_out;
  118. #if HAVE_PTHREADS
  119. /* signal to input threads that they should exit; set by the main thread */
  120. static int transcoding_finished;
  121. #endif
  122. #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
  123. InputStream **input_streams = NULL;
  124. int nb_input_streams = 0;
  125. InputFile **input_files = NULL;
  126. int nb_input_files = 0;
  127. OutputStream **output_streams = NULL;
  128. int nb_output_streams = 0;
  129. OutputFile **output_files = NULL;
  130. int nb_output_files = 0;
  131. FilterGraph **filtergraphs;
  132. int nb_filtergraphs;
  133. #if HAVE_TERMIOS_H
  134. /* init terminal so that we can grab keys */
  135. static struct termios oldtty;
  136. static int restore_tty;
  137. #endif
  138. static void free_input_threads(void);
  139. /* sub2video hack:
  140. Convert subtitles to video with alpha to insert them in filter graphs.
  141. This is a temporary solution until libavfilter gets real subtitles support.
  142. */
  143. static int sub2video_get_blank_frame(InputStream *ist)
  144. {
  145. int ret;
  146. AVFrame *frame = ist->sub2video.frame;
  147. av_frame_unref(frame);
  148. ist->sub2video.frame->width = ist->sub2video.w;
  149. ist->sub2video.frame->height = ist->sub2video.h;
  150. ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
  151. if ((ret = av_frame_get_buffer(frame, 32)) < 0)
  152. return ret;
  153. memset(frame->data[0], 0, frame->height * frame->linesize[0]);
  154. return 0;
  155. }
  156. static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
  157. AVSubtitleRect *r)
  158. {
  159. uint32_t *pal, *dst2;
  160. uint8_t *src, *src2;
  161. int x, y;
  162. if (r->type != SUBTITLE_BITMAP) {
  163. av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
  164. return;
  165. }
  166. if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
  167. av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle overflowing\n");
  168. return;
  169. }
  170. dst += r->y * dst_linesize + r->x * 4;
  171. src = r->pict.data[0];
  172. pal = (uint32_t *)r->pict.data[1];
  173. for (y = 0; y < r->h; y++) {
  174. dst2 = (uint32_t *)dst;
  175. src2 = src;
  176. for (x = 0; x < r->w; x++)
  177. *(dst2++) = pal[*(src2++)];
  178. dst += dst_linesize;
  179. src += r->pict.linesize[0];
  180. }
  181. }
  182. static void sub2video_push_ref(InputStream *ist, int64_t pts)
  183. {
  184. AVFrame *frame = ist->sub2video.frame;
  185. int i;
  186. av_assert1(frame->data[0]);
  187. ist->sub2video.last_pts = frame->pts = pts;
  188. for (i = 0; i < ist->nb_filters; i++)
  189. av_buffersrc_add_frame_flags(ist->filters[i]->filter, frame,
  190. AV_BUFFERSRC_FLAG_KEEP_REF |
  191. AV_BUFFERSRC_FLAG_PUSH);
  192. }
  193. static void sub2video_update(InputStream *ist, AVSubtitle *sub)
  194. {
  195. int w = ist->sub2video.w, h = ist->sub2video.h;
  196. AVFrame *frame = ist->sub2video.frame;
  197. int8_t *dst;
  198. int dst_linesize;
  199. int num_rects, i;
  200. int64_t pts, end_pts;
  201. if (!frame)
  202. return;
  203. if (sub) {
  204. pts = av_rescale_q(sub->pts + sub->start_display_time * 1000,
  205. AV_TIME_BASE_Q, ist->st->time_base);
  206. end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000,
  207. AV_TIME_BASE_Q, ist->st->time_base);
  208. num_rects = sub->num_rects;
  209. } else {
  210. pts = ist->sub2video.end_pts;
  211. end_pts = INT64_MAX;
  212. num_rects = 0;
  213. }
  214. if (sub2video_get_blank_frame(ist) < 0) {
  215. av_log(ist->st->codec, AV_LOG_ERROR,
  216. "Impossible to get a blank canvas.\n");
  217. return;
  218. }
  219. dst = frame->data [0];
  220. dst_linesize = frame->linesize[0];
  221. for (i = 0; i < num_rects; i++)
  222. sub2video_copy_rect(dst, dst_linesize, w, h, sub->rects[i]);
  223. sub2video_push_ref(ist, pts);
  224. ist->sub2video.end_pts = end_pts;
  225. }
  226. static void sub2video_heartbeat(InputStream *ist, int64_t pts)
  227. {
  228. InputFile *infile = input_files[ist->file_index];
  229. int i, j, nb_reqs;
  230. int64_t pts2;
  231. /* When a frame is read from a file, examine all sub2video streams in
  232. the same file and send the sub2video frame again. Otherwise, decoded
  233. video frames could be accumulating in the filter graph while a filter
  234. (possibly overlay) is desperately waiting for a subtitle frame. */
  235. for (i = 0; i < infile->nb_streams; i++) {
  236. InputStream *ist2 = input_streams[infile->ist_index + i];
  237. if (!ist2->sub2video.frame)
  238. continue;
  239. /* subtitles seem to be usually muxed ahead of other streams;
  240. if not, substracting a larger time here is necessary */
  241. pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
  242. /* do not send the heartbeat frame if the subtitle is already ahead */
  243. if (pts2 <= ist2->sub2video.last_pts)
  244. continue;
  245. if (pts2 >= ist2->sub2video.end_pts || !ist2->sub2video.frame->data[0])
  246. sub2video_update(ist2, NULL);
  247. for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
  248. nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
  249. if (nb_reqs)
  250. sub2video_push_ref(ist2, pts2);
  251. }
  252. }
  253. static void sub2video_flush(InputStream *ist)
  254. {
  255. int i;
  256. for (i = 0; i < ist->nb_filters; i++)
  257. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  258. }
  259. /* end of sub2video hack */
  260. void term_exit(void)
  261. {
  262. av_log(NULL, AV_LOG_QUIET, "%s", "");
  263. #if HAVE_TERMIOS_H
  264. if(restore_tty)
  265. tcsetattr (0, TCSANOW, &oldtty);
  266. #endif
  267. }
  268. static volatile int received_sigterm = 0;
  269. static volatile int received_nb_signals = 0;
  270. static void
  271. sigterm_handler(int sig)
  272. {
  273. received_sigterm = sig;
  274. received_nb_signals++;
  275. term_exit();
  276. if(received_nb_signals > 3)
  277. exit_program(123);
  278. }
  279. void term_init(void)
  280. {
  281. #if HAVE_TERMIOS_H
  282. if(!run_as_daemon){
  283. struct termios tty;
  284. int istty = 1;
  285. #if HAVE_ISATTY
  286. istty = isatty(0) && isatty(2);
  287. #endif
  288. if (istty && tcgetattr (0, &tty) == 0) {
  289. oldtty = tty;
  290. restore_tty = 1;
  291. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
  292. |INLCR|IGNCR|ICRNL|IXON);
  293. tty.c_oflag |= OPOST;
  294. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
  295. tty.c_cflag &= ~(CSIZE|PARENB);
  296. tty.c_cflag |= CS8;
  297. tty.c_cc[VMIN] = 1;
  298. tty.c_cc[VTIME] = 0;
  299. tcsetattr (0, TCSANOW, &tty);
  300. }
  301. signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
  302. }
  303. #endif
  304. avformat_network_deinit();
  305. signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
  306. signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
  307. #ifdef SIGXCPU
  308. signal(SIGXCPU, sigterm_handler);
  309. #endif
  310. }
  311. /* read a key without blocking */
  312. static int read_key(void)
  313. {
  314. unsigned char ch;
  315. #if HAVE_TERMIOS_H
  316. int n = 1;
  317. struct timeval tv;
  318. fd_set rfds;
  319. FD_ZERO(&rfds);
  320. FD_SET(0, &rfds);
  321. tv.tv_sec = 0;
  322. tv.tv_usec = 0;
  323. n = select(1, &rfds, NULL, NULL, &tv);
  324. if (n > 0) {
  325. n = read(0, &ch, 1);
  326. if (n == 1)
  327. return ch;
  328. return n;
  329. }
  330. #elif HAVE_KBHIT
  331. # if HAVE_PEEKNAMEDPIPE
  332. static int is_pipe;
  333. static HANDLE input_handle;
  334. DWORD dw, nchars;
  335. if(!input_handle){
  336. input_handle = GetStdHandle(STD_INPUT_HANDLE);
  337. is_pipe = !GetConsoleMode(input_handle, &dw);
  338. }
  339. if (stdin->_cnt > 0) {
  340. read(0, &ch, 1);
  341. return ch;
  342. }
  343. if (is_pipe) {
  344. /* When running under a GUI, you will end here. */
  345. if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
  346. // input pipe may have been closed by the program that ran ffmpeg
  347. return -1;
  348. }
  349. //Read it
  350. if(nchars != 0) {
  351. read(0, &ch, 1);
  352. return ch;
  353. }else{
  354. return -1;
  355. }
  356. }
  357. # endif
  358. if(kbhit())
  359. return(getch());
  360. #endif
  361. return -1;
  362. }
  363. static int decode_interrupt_cb(void *ctx)
  364. {
  365. return received_nb_signals > 1;
  366. }
  367. const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
  368. static void ffmpeg_cleanup(int ret)
  369. {
  370. int i, j;
  371. if (do_benchmark) {
  372. int maxrss = getmaxrss() / 1024;
  373. printf("bench: maxrss=%ikB\n", maxrss);
  374. }
  375. for (i = 0; i < nb_filtergraphs; i++) {
  376. avfilter_graph_free(&filtergraphs[i]->graph);
  377. for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
  378. av_freep(&filtergraphs[i]->inputs[j]->name);
  379. av_freep(&filtergraphs[i]->inputs[j]);
  380. }
  381. av_freep(&filtergraphs[i]->inputs);
  382. for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
  383. av_freep(&filtergraphs[i]->outputs[j]->name);
  384. av_freep(&filtergraphs[i]->outputs[j]);
  385. }
  386. av_freep(&filtergraphs[i]->outputs);
  387. av_freep(&filtergraphs[i]->graph_desc);
  388. av_freep(&filtergraphs[i]);
  389. }
  390. av_freep(&filtergraphs);
  391. av_freep(&subtitle_out);
  392. /* close files */
  393. for (i = 0; i < nb_output_files; i++) {
  394. AVFormatContext *s = output_files[i]->ctx;
  395. if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE) && s->pb)
  396. avio_close(s->pb);
  397. avformat_free_context(s);
  398. av_dict_free(&output_files[i]->opts);
  399. av_freep(&output_files[i]);
  400. }
  401. for (i = 0; i < nb_output_streams; i++) {
  402. AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
  403. while (bsfc) {
  404. AVBitStreamFilterContext *next = bsfc->next;
  405. av_bitstream_filter_close(bsfc);
  406. bsfc = next;
  407. }
  408. output_streams[i]->bitstream_filters = NULL;
  409. avcodec_free_frame(&output_streams[i]->filtered_frame);
  410. av_freep(&output_streams[i]->forced_keyframes);
  411. av_expr_free(output_streams[i]->forced_keyframes_pexpr);
  412. av_freep(&output_streams[i]->avfilter);
  413. av_freep(&output_streams[i]->logfile_prefix);
  414. av_freep(&output_streams[i]);
  415. }
  416. #if HAVE_PTHREADS
  417. free_input_threads();
  418. #endif
  419. for (i = 0; i < nb_input_files; i++) {
  420. avformat_close_input(&input_files[i]->ctx);
  421. av_freep(&input_files[i]);
  422. }
  423. for (i = 0; i < nb_input_streams; i++) {
  424. av_frame_free(&input_streams[i]->decoded_frame);
  425. av_frame_free(&input_streams[i]->filter_frame);
  426. av_dict_free(&input_streams[i]->opts);
  427. avsubtitle_free(&input_streams[i]->prev_sub.subtitle);
  428. av_frame_free(&input_streams[i]->sub2video.frame);
  429. av_freep(&input_streams[i]->filters);
  430. av_freep(&input_streams[i]);
  431. }
  432. if (vstats_file)
  433. fclose(vstats_file);
  434. av_free(vstats_filename);
  435. av_freep(&input_streams);
  436. av_freep(&input_files);
  437. av_freep(&output_streams);
  438. av_freep(&output_files);
  439. uninit_opts();
  440. avformat_network_deinit();
  441. if (received_sigterm) {
  442. av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
  443. (int) received_sigterm);
  444. }
  445. term_exit();
  446. }
  447. void assert_avoptions(AVDictionary *m)
  448. {
  449. AVDictionaryEntry *t;
  450. if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  451. av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
  452. exit_program(1);
  453. }
  454. }
  455. static void abort_codec_experimental(AVCodec *c, int encoder)
  456. {
  457. exit_program(1);
  458. }
  459. static void update_benchmark(const char *fmt, ...)
  460. {
  461. if (do_benchmark_all) {
  462. int64_t t = getutime();
  463. va_list va;
  464. char buf[1024];
  465. if (fmt) {
  466. va_start(va, fmt);
  467. vsnprintf(buf, sizeof(buf), fmt, va);
  468. va_end(va);
  469. printf("bench: %8"PRIu64" %s \n", t - current_time, buf);
  470. }
  471. current_time = t;
  472. }
  473. }
  474. static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
  475. {
  476. AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
  477. AVCodecContext *avctx = ost->st->codec;
  478. int ret;
  479. if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
  480. (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
  481. pkt->pts = pkt->dts = AV_NOPTS_VALUE;
  482. /*
  483. * Audio encoders may split the packets -- #frames in != #packets out.
  484. * But there is no reordering, so we can limit the number of output packets
  485. * by simply dropping them here.
  486. * Counting encoded video frames needs to be done separately because of
  487. * reordering, see do_video_out()
  488. */
  489. if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
  490. if (ost->frame_number >= ost->max_frames) {
  491. av_free_packet(pkt);
  492. return;
  493. }
  494. ost->frame_number++;
  495. }
  496. while (bsfc) {
  497. AVPacket new_pkt = *pkt;
  498. int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
  499. &new_pkt.data, &new_pkt.size,
  500. pkt->data, pkt->size,
  501. pkt->flags & AV_PKT_FLAG_KEY);
  502. if(a == 0 && new_pkt.data != pkt->data && new_pkt.destruct) {
  503. uint8_t *t = av_malloc(new_pkt.size + FF_INPUT_BUFFER_PADDING_SIZE); //the new should be a subset of the old so cannot overflow
  504. if(t) {
  505. memcpy(t, new_pkt.data, new_pkt.size);
  506. memset(t + new_pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  507. new_pkt.data = t;
  508. new_pkt.buf = NULL;
  509. a = 1;
  510. } else
  511. a = AVERROR(ENOMEM);
  512. }
  513. if (a > 0) {
  514. av_free_packet(pkt);
  515. new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,
  516. av_buffer_default_free, NULL, 0);
  517. if (!new_pkt.buf)
  518. exit_program(1);
  519. } else if (a < 0) {
  520. av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
  521. bsfc->filter->name, pkt->stream_index,
  522. avctx->codec ? avctx->codec->name : "copy");
  523. print_error("", a);
  524. if (exit_on_error)
  525. exit_program(1);
  526. }
  527. *pkt = new_pkt;
  528. bsfc = bsfc->next;
  529. }
  530. if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
  531. (avctx->codec_type == AVMEDIA_TYPE_AUDIO || avctx->codec_type == AVMEDIA_TYPE_VIDEO) &&
  532. pkt->dts != AV_NOPTS_VALUE &&
  533. ost->last_mux_dts != AV_NOPTS_VALUE) {
  534. int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
  535. if (pkt->dts < max) {
  536. int loglevel = max - pkt->dts > 2 || avctx->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
  537. av_log(s, loglevel, "Non-monotonous DTS in output stream "
  538. "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
  539. ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
  540. if (exit_on_error) {
  541. av_log(NULL, AV_LOG_FATAL, "aborting.\n");
  542. exit_program(1);
  543. }
  544. av_log(s, loglevel, "changing to %"PRId64". This may result "
  545. "in incorrect timestamps in the output file.\n",
  546. max);
  547. if(pkt->pts >= pkt->dts)
  548. pkt->pts = FFMAX(pkt->pts, max);
  549. pkt->dts = max;
  550. }
  551. }
  552. ost->last_mux_dts = pkt->dts;
  553. pkt->stream_index = ost->index;
  554. if (debug_ts) {
  555. av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
  556. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
  557. av_get_media_type_string(ost->st->codec->codec_type),
  558. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
  559. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
  560. pkt->size
  561. );
  562. }
  563. ret = av_interleaved_write_frame(s, pkt);
  564. if (ret < 0) {
  565. print_error("av_interleaved_write_frame()", ret);
  566. exit_program(1);
  567. }
  568. }
  569. static void close_output_stream(OutputStream *ost)
  570. {
  571. OutputFile *of = output_files[ost->file_index];
  572. ost->finished = 1;
  573. if (of->shortest) {
  574. int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, AV_TIME_BASE_Q);
  575. of->recording_time = FFMIN(of->recording_time, end);
  576. }
  577. }
  578. static int check_recording_time(OutputStream *ost)
  579. {
  580. OutputFile *of = output_files[ost->file_index];
  581. if (of->recording_time != INT64_MAX &&
  582. av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
  583. AV_TIME_BASE_Q) >= 0) {
  584. close_output_stream(ost);
  585. return 0;
  586. }
  587. return 1;
  588. }
  589. static void do_audio_out(AVFormatContext *s, OutputStream *ost,
  590. AVFrame *frame)
  591. {
  592. AVCodecContext *enc = ost->st->codec;
  593. AVPacket pkt;
  594. int got_packet = 0;
  595. av_init_packet(&pkt);
  596. pkt.data = NULL;
  597. pkt.size = 0;
  598. if (!check_recording_time(ost))
  599. return;
  600. if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
  601. frame->pts = ost->sync_opts;
  602. ost->sync_opts = frame->pts + frame->nb_samples;
  603. av_assert0(pkt.size || !pkt.data);
  604. update_benchmark(NULL);
  605. if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
  606. av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
  607. exit_program(1);
  608. }
  609. update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
  610. if (got_packet) {
  611. if (pkt.pts != AV_NOPTS_VALUE)
  612. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  613. if (pkt.dts != AV_NOPTS_VALUE)
  614. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  615. if (pkt.duration > 0)
  616. pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
  617. if (debug_ts) {
  618. av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
  619. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
  620. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
  621. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
  622. }
  623. audio_size += pkt.size;
  624. write_frame(s, &pkt, ost);
  625. av_free_packet(&pkt);
  626. }
  627. }
  628. static void do_subtitle_out(AVFormatContext *s,
  629. OutputStream *ost,
  630. InputStream *ist,
  631. AVSubtitle *sub)
  632. {
  633. int subtitle_out_max_size = 1024 * 1024;
  634. int subtitle_out_size, nb, i;
  635. AVCodecContext *enc;
  636. AVPacket pkt;
  637. int64_t pts;
  638. if (sub->pts == AV_NOPTS_VALUE) {
  639. av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
  640. if (exit_on_error)
  641. exit_program(1);
  642. return;
  643. }
  644. enc = ost->st->codec;
  645. if (!subtitle_out) {
  646. subtitle_out = av_malloc(subtitle_out_max_size);
  647. }
  648. /* Note: DVB subtitle need one packet to draw them and one other
  649. packet to clear them */
  650. /* XXX: signal it in the codec context ? */
  651. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
  652. nb = 2;
  653. else
  654. nb = 1;
  655. /* shift timestamp to honor -ss and make check_recording_time() work with -t */
  656. pts = sub->pts;
  657. if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)
  658. pts -= output_files[ost->file_index]->start_time;
  659. for (i = 0; i < nb; i++) {
  660. ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
  661. if (!check_recording_time(ost))
  662. return;
  663. sub->pts = pts;
  664. // start_display_time is required to be 0
  665. sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
  666. sub->end_display_time -= sub->start_display_time;
  667. sub->start_display_time = 0;
  668. if (i == 1)
  669. sub->num_rects = 0;
  670. subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
  671. subtitle_out_max_size, sub);
  672. if (subtitle_out_size < 0) {
  673. av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
  674. exit_program(1);
  675. }
  676. av_init_packet(&pkt);
  677. pkt.data = subtitle_out;
  678. pkt.size = subtitle_out_size;
  679. pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
  680. pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
  681. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
  682. /* XXX: the pts correction is handled here. Maybe handling
  683. it in the codec would be better */
  684. if (i == 0)
  685. pkt.pts += 90 * sub->start_display_time;
  686. else
  687. pkt.pts += 90 * sub->end_display_time;
  688. }
  689. subtitle_size += pkt.size;
  690. write_frame(s, &pkt, ost);
  691. }
  692. }
  693. static void do_video_out(AVFormatContext *s,
  694. OutputStream *ost,
  695. AVFrame *in_picture)
  696. {
  697. int ret, format_video_sync;
  698. AVPacket pkt;
  699. AVCodecContext *enc = ost->st->codec;
  700. int nb_frames, i;
  701. double sync_ipts, delta;
  702. double duration = 0;
  703. int frame_size = 0;
  704. InputStream *ist = NULL;
  705. if (ost->source_index >= 0)
  706. ist = input_streams[ost->source_index];
  707. if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
  708. duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));
  709. sync_ipts = in_picture->pts;
  710. delta = sync_ipts - ost->sync_opts + duration;
  711. /* by default, we output a single frame */
  712. nb_frames = 1;
  713. format_video_sync = video_sync_method;
  714. if (format_video_sync == VSYNC_AUTO)
  715. format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;
  716. switch (format_video_sync) {
  717. case VSYNC_CFR:
  718. // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
  719. if (delta < -1.1)
  720. nb_frames = 0;
  721. else if (delta > 1.1)
  722. nb_frames = lrintf(delta);
  723. break;
  724. case VSYNC_VFR:
  725. if (delta <= -0.6)
  726. nb_frames = 0;
  727. else if (delta > 0.6)
  728. ost->sync_opts = lrint(sync_ipts);
  729. break;
  730. case VSYNC_DROP:
  731. case VSYNC_PASSTHROUGH:
  732. ost->sync_opts = lrint(sync_ipts);
  733. break;
  734. default:
  735. av_assert0(0);
  736. }
  737. nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
  738. if (nb_frames == 0) {
  739. nb_frames_drop++;
  740. av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
  741. return;
  742. } else if (nb_frames > 1) {
  743. if (nb_frames > dts_error_threshold * 30) {
  744. av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
  745. nb_frames_drop++;
  746. return;
  747. }
  748. nb_frames_dup += nb_frames - 1;
  749. av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
  750. }
  751. /* duplicates frame if needed */
  752. for (i = 0; i < nb_frames; i++) {
  753. av_init_packet(&pkt);
  754. pkt.data = NULL;
  755. pkt.size = 0;
  756. in_picture->pts = ost->sync_opts;
  757. #if 1
  758. if (!check_recording_time(ost))
  759. #else
  760. if (ost->frame_number >= ost->max_frames)
  761. #endif
  762. return;
  763. if (s->oformat->flags & AVFMT_RAWPICTURE &&
  764. enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
  765. /* raw pictures are written as AVPicture structure to
  766. avoid any copies. We support temporarily the older
  767. method. */
  768. enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
  769. enc->coded_frame->top_field_first = in_picture->top_field_first;
  770. if (enc->coded_frame->interlaced_frame)
  771. enc->field_order = enc->coded_frame->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
  772. else
  773. enc->field_order = AV_FIELD_PROGRESSIVE;
  774. pkt.data = (uint8_t *)in_picture;
  775. pkt.size = sizeof(AVPicture);
  776. pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
  777. pkt.flags |= AV_PKT_FLAG_KEY;
  778. video_size += pkt.size;
  779. write_frame(s, &pkt, ost);
  780. } else {
  781. int got_packet, forced_keyframe = 0;
  782. double pts_time;
  783. if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME) &&
  784. ost->top_field_first >= 0)
  785. in_picture->top_field_first = !!ost->top_field_first;
  786. if (in_picture->interlaced_frame) {
  787. if (enc->codec->id == AV_CODEC_ID_MJPEG)
  788. enc->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
  789. else
  790. enc->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
  791. } else
  792. enc->field_order = AV_FIELD_PROGRESSIVE;
  793. in_picture->quality = ost->st->codec->global_quality;
  794. if (!enc->me_threshold)
  795. in_picture->pict_type = 0;
  796. pts_time = in_picture->pts != AV_NOPTS_VALUE ?
  797. in_picture->pts * av_q2d(enc->time_base) : NAN;
  798. if (ost->forced_kf_index < ost->forced_kf_count &&
  799. in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
  800. ost->forced_kf_index++;
  801. forced_keyframe = 1;
  802. } else if (ost->forced_keyframes_pexpr) {
  803. double res;
  804. ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
  805. res = av_expr_eval(ost->forced_keyframes_pexpr,
  806. ost->forced_keyframes_expr_const_values, NULL);
  807. av_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
  808. ost->forced_keyframes_expr_const_values[FKF_N],
  809. ost->forced_keyframes_expr_const_values[FKF_N_FORCED],
  810. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],
  811. ost->forced_keyframes_expr_const_values[FKF_T],
  812. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],
  813. res);
  814. if (res) {
  815. forced_keyframe = 1;
  816. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =
  817. ost->forced_keyframes_expr_const_values[FKF_N];
  818. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =
  819. ost->forced_keyframes_expr_const_values[FKF_T];
  820. ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;
  821. }
  822. ost->forced_keyframes_expr_const_values[FKF_N] += 1;
  823. }
  824. if (forced_keyframe) {
  825. in_picture->pict_type = AV_PICTURE_TYPE_I;
  826. av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
  827. }
  828. update_benchmark(NULL);
  829. ret = avcodec_encode_video2(enc, &pkt, in_picture, &got_packet);
  830. update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
  831. if (ret < 0) {
  832. av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
  833. exit_program(1);
  834. }
  835. if (got_packet) {
  836. if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
  837. pkt.pts = ost->sync_opts;
  838. if (pkt.pts != AV_NOPTS_VALUE)
  839. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  840. if (pkt.dts != AV_NOPTS_VALUE)
  841. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  842. if (debug_ts) {
  843. av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
  844. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
  845. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
  846. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
  847. }
  848. frame_size = pkt.size;
  849. video_size += pkt.size;
  850. write_frame(s, &pkt, ost);
  851. av_free_packet(&pkt);
  852. /* if two pass, output log */
  853. if (ost->logfile && enc->stats_out) {
  854. fprintf(ost->logfile, "%s", enc->stats_out);
  855. }
  856. }
  857. }
  858. ost->sync_opts++;
  859. /*
  860. * For video, number of frames in == number of packets out.
  861. * But there may be reordering, so we can't throw away frames on encoder
  862. * flush, we need to limit them here, before they go into encoder.
  863. */
  864. ost->frame_number++;
  865. if (vstats_filename && frame_size)
  866. do_video_stats(ost, frame_size);
  867. }
  868. }
  869. static double psnr(double d)
  870. {
  871. return -10.0 * log(d) / log(10.0);
  872. }
  873. static void do_video_stats(OutputStream *ost, int frame_size)
  874. {
  875. AVCodecContext *enc;
  876. int frame_number;
  877. double ti1, bitrate, avg_bitrate;
  878. /* this is executed just the first time do_video_stats is called */
  879. if (!vstats_file) {
  880. vstats_file = fopen(vstats_filename, "w");
  881. if (!vstats_file) {
  882. perror("fopen");
  883. exit_program(1);
  884. }
  885. }
  886. enc = ost->st->codec;
  887. if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  888. frame_number = ost->st->nb_frames;
  889. fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
  890. if (enc->flags&CODEC_FLAG_PSNR)
  891. fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
  892. fprintf(vstats_file,"f_size= %6d ", frame_size);
  893. /* compute pts value */
  894. ti1 = ost->st->pts.val * av_q2d(enc->time_base);
  895. if (ti1 < 0.01)
  896. ti1 = 0.01;
  897. bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
  898. avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
  899. fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
  900. (double)video_size / 1024, ti1, bitrate, avg_bitrate);
  901. fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
  902. }
  903. }
  904. /**
  905. * Get and encode new output from any of the filtergraphs, without causing
  906. * activity.
  907. *
  908. * @return 0 for success, <0 for severe errors
  909. */
  910. static int reap_filters(void)
  911. {
  912. AVFrame *filtered_frame = NULL;
  913. int i;
  914. int64_t frame_pts;
  915. /* Reap all buffers present in the buffer sinks */
  916. for (i = 0; i < nb_output_streams; i++) {
  917. OutputStream *ost = output_streams[i];
  918. OutputFile *of = output_files[ost->file_index];
  919. int ret = 0;
  920. if (!ost->filter)
  921. continue;
  922. if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
  923. return AVERROR(ENOMEM);
  924. } else
  925. avcodec_get_frame_defaults(ost->filtered_frame);
  926. filtered_frame = ost->filtered_frame;
  927. while (1) {
  928. ret = av_buffersink_get_frame_flags(ost->filter->filter, filtered_frame,
  929. AV_BUFFERSINK_FLAG_NO_REQUEST);
  930. if (ret < 0) {
  931. if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
  932. av_log(NULL, AV_LOG_WARNING,
  933. "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));
  934. }
  935. break;
  936. }
  937. frame_pts = AV_NOPTS_VALUE;
  938. if (filtered_frame->pts != AV_NOPTS_VALUE) {
  939. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  940. filtered_frame->pts = frame_pts = av_rescale_q(filtered_frame->pts,
  941. ost->filter->filter->inputs[0]->time_base,
  942. ost->st->codec->time_base) -
  943. av_rescale_q(start_time,
  944. AV_TIME_BASE_Q,
  945. ost->st->codec->time_base);
  946. }
  947. //if (ost->source_index >= 0)
  948. // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
  949. switch (ost->filter->filter->inputs[0]->type) {
  950. case AVMEDIA_TYPE_VIDEO:
  951. filtered_frame->pts = frame_pts;
  952. if (!ost->frame_aspect_ratio.num)
  953. ost->st->codec->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
  954. do_video_out(of->ctx, ost, filtered_frame);
  955. break;
  956. case AVMEDIA_TYPE_AUDIO:
  957. filtered_frame->pts = frame_pts;
  958. if (!(ost->st->codec->codec->capabilities & CODEC_CAP_PARAM_CHANGE) &&
  959. ost->st->codec->channels != av_frame_get_channels(filtered_frame)) {
  960. av_log(NULL, AV_LOG_ERROR,
  961. "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
  962. break;
  963. }
  964. do_audio_out(of->ctx, ost, filtered_frame);
  965. break;
  966. default:
  967. // TODO support subtitle filters
  968. av_assert0(0);
  969. }
  970. av_frame_unref(filtered_frame);
  971. }
  972. }
  973. return 0;
  974. }
  975. static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
  976. {
  977. char buf[1024];
  978. AVBPrint buf_script;
  979. OutputStream *ost;
  980. AVFormatContext *oc;
  981. int64_t total_size;
  982. AVCodecContext *enc;
  983. int frame_number, vid, i;
  984. double bitrate;
  985. int64_t pts = INT64_MIN;
  986. static int64_t last_time = -1;
  987. static int qp_histogram[52];
  988. int hours, mins, secs, us;
  989. if (!print_stats && !is_last_report && !progress_avio)
  990. return;
  991. if (!is_last_report) {
  992. if (last_time == -1) {
  993. last_time = cur_time;
  994. return;
  995. }
  996. if ((cur_time - last_time) < 500000)
  997. return;
  998. last_time = cur_time;
  999. }
  1000. oc = output_files[0]->ctx;
  1001. total_size = avio_size(oc->pb);
  1002. if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
  1003. total_size = avio_tell(oc->pb);
  1004. buf[0] = '\0';
  1005. vid = 0;
  1006. av_bprint_init(&buf_script, 0, 1);
  1007. for (i = 0; i < nb_output_streams; i++) {
  1008. float q = -1;
  1009. ost = output_streams[i];
  1010. enc = ost->st->codec;
  1011. if (!ost->stream_copy && enc->coded_frame)
  1012. q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
  1013. if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1014. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
  1015. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  1016. ost->file_index, ost->index, q);
  1017. }
  1018. if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1019. float fps, t = (cur_time-timer_start) / 1000000.0;
  1020. frame_number = ost->frame_number;
  1021. fps = t > 1 ? frame_number / t : 0;
  1022. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
  1023. frame_number, fps < 9.95, fps, q);
  1024. av_bprintf(&buf_script, "frame=%d\n", frame_number);
  1025. av_bprintf(&buf_script, "fps=%.1f\n", fps);
  1026. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  1027. ost->file_index, ost->index, q);
  1028. if (is_last_report)
  1029. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
  1030. if (qp_hist) {
  1031. int j;
  1032. int qp = lrintf(q);
  1033. if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
  1034. qp_histogram[qp]++;
  1035. for (j = 0; j < 32; j++)
  1036. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
  1037. }
  1038. if ((enc->flags&CODEC_FLAG_PSNR) && (enc->coded_frame || is_last_report)) {
  1039. int j;
  1040. double error, error_sum = 0;
  1041. double scale, scale_sum = 0;
  1042. double p;
  1043. char type[3] = { 'Y','U','V' };
  1044. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
  1045. for (j = 0; j < 3; j++) {
  1046. if (is_last_report) {
  1047. error = enc->error[j];
  1048. scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
  1049. } else {
  1050. error = enc->coded_frame->error[j];
  1051. scale = enc->width * enc->height * 255.0 * 255.0;
  1052. }
  1053. if (j)
  1054. scale /= 4;
  1055. error_sum += error;
  1056. scale_sum += scale;
  1057. p = psnr(error / scale);
  1058. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
  1059. av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
  1060. ost->file_index, ost->index, type[j] | 32, p);
  1061. }
  1062. p = psnr(error_sum / scale_sum);
  1063. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
  1064. av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
  1065. ost->file_index, ost->index, p);
  1066. }
  1067. vid = 1;
  1068. }
  1069. /* compute min output value */
  1070. if ((is_last_report || !ost->finished) && ost->st->pts.val != AV_NOPTS_VALUE)
  1071. pts = FFMAX(pts, av_rescale_q(ost->st->pts.val,
  1072. ost->st->time_base, AV_TIME_BASE_Q));
  1073. }
  1074. secs = pts / AV_TIME_BASE;
  1075. us = pts % AV_TIME_BASE;
  1076. mins = secs / 60;
  1077. secs %= 60;
  1078. hours = mins / 60;
  1079. mins %= 60;
  1080. bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
  1081. if (total_size < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1082. "size=N/A time=");
  1083. else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1084. "size=%8.0fkB time=", total_size / 1024.0);
  1085. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1086. "%02d:%02d:%02d.%02d ", hours, mins, secs,
  1087. (100 * us) / AV_TIME_BASE);
  1088. if (bitrate < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1089. "bitrate=N/A");
  1090. else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1091. "bitrate=%6.1fkbits/s", bitrate);
  1092. if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
  1093. else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
  1094. av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
  1095. av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
  1096. hours, mins, secs, us);
  1097. if (nb_frames_dup || nb_frames_drop)
  1098. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
  1099. nb_frames_dup, nb_frames_drop);
  1100. av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
  1101. av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
  1102. if (print_stats || is_last_report) {
  1103. if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
  1104. fprintf(stderr, "%s \r", buf);
  1105. } else
  1106. av_log(NULL, AV_LOG_INFO, "%s \r", buf);
  1107. fflush(stderr);
  1108. }
  1109. if (progress_avio) {
  1110. av_bprintf(&buf_script, "progress=%s\n",
  1111. is_last_report ? "end" : "continue");
  1112. avio_write(progress_avio, buf_script.str,
  1113. FFMIN(buf_script.len, buf_script.size - 1));
  1114. avio_flush(progress_avio);
  1115. av_bprint_finalize(&buf_script, NULL);
  1116. if (is_last_report) {
  1117. avio_close(progress_avio);
  1118. progress_avio = NULL;
  1119. }
  1120. }
  1121. if (is_last_report) {
  1122. int64_t raw= audio_size + video_size + subtitle_size + extra_size;
  1123. av_log(NULL, AV_LOG_INFO, "\n");
  1124. av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0f global headers:%1.0fkB muxing overhead %f%%\n",
  1125. video_size / 1024.0,
  1126. audio_size / 1024.0,
  1127. subtitle_size / 1024.0,
  1128. extra_size / 1024.0,
  1129. 100.0 * (total_size - raw) / raw
  1130. );
  1131. if(video_size + audio_size + subtitle_size + extra_size == 0){
  1132. av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
  1133. }
  1134. }
  1135. }
  1136. static void flush_encoders(void)
  1137. {
  1138. int i, ret;
  1139. for (i = 0; i < nb_output_streams; i++) {
  1140. OutputStream *ost = output_streams[i];
  1141. AVCodecContext *enc = ost->st->codec;
  1142. AVFormatContext *os = output_files[ost->file_index]->ctx;
  1143. int stop_encoding = 0;
  1144. if (!ost->encoding_needed)
  1145. continue;
  1146. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
  1147. continue;
  1148. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
  1149. continue;
  1150. for (;;) {
  1151. int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
  1152. const char *desc;
  1153. int64_t *size;
  1154. switch (ost->st->codec->codec_type) {
  1155. case AVMEDIA_TYPE_AUDIO:
  1156. encode = avcodec_encode_audio2;
  1157. desc = "Audio";
  1158. size = &audio_size;
  1159. break;
  1160. case AVMEDIA_TYPE_VIDEO:
  1161. encode = avcodec_encode_video2;
  1162. desc = "Video";
  1163. size = &video_size;
  1164. break;
  1165. default:
  1166. stop_encoding = 1;
  1167. }
  1168. if (encode) {
  1169. AVPacket pkt;
  1170. int got_packet;
  1171. av_init_packet(&pkt);
  1172. pkt.data = NULL;
  1173. pkt.size = 0;
  1174. update_benchmark(NULL);
  1175. ret = encode(enc, &pkt, NULL, &got_packet);
  1176. update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
  1177. if (ret < 0) {
  1178. av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
  1179. exit_program(1);
  1180. }
  1181. *size += pkt.size;
  1182. if (ost->logfile && enc->stats_out) {
  1183. fprintf(ost->logfile, "%s", enc->stats_out);
  1184. }
  1185. if (!got_packet) {
  1186. stop_encoding = 1;
  1187. break;
  1188. }
  1189. if (pkt.pts != AV_NOPTS_VALUE)
  1190. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  1191. if (pkt.dts != AV_NOPTS_VALUE)
  1192. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  1193. if (pkt.duration > 0)
  1194. pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
  1195. write_frame(os, &pkt, ost);
  1196. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
  1197. do_video_stats(ost, pkt.size);
  1198. }
  1199. }
  1200. if (stop_encoding)
  1201. break;
  1202. }
  1203. }
  1204. }
  1205. /*
  1206. * Check whether a packet from ist should be written into ost at this time
  1207. */
  1208. static int check_output_constraints(InputStream *ist, OutputStream *ost)
  1209. {
  1210. OutputFile *of = output_files[ost->file_index];
  1211. int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
  1212. if (ost->source_index != ist_index)
  1213. return 0;
  1214. if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
  1215. return 0;
  1216. return 1;
  1217. }
  1218. static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
  1219. {
  1220. OutputFile *of = output_files[ost->file_index];
  1221. InputFile *f = input_files [ist->file_index];
  1222. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  1223. int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
  1224. int64_t ist_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ist->st->time_base);
  1225. AVPicture pict;
  1226. AVPacket opkt;
  1227. av_init_packet(&opkt);
  1228. if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
  1229. !ost->copy_initial_nonkeyframes)
  1230. return;
  1231. if (pkt->pts == AV_NOPTS_VALUE) {
  1232. if (!ost->frame_number && ist->pts < start_time &&
  1233. !ost->copy_prior_start)
  1234. return;
  1235. } else {
  1236. if (!ost->frame_number && pkt->pts < ist_tb_start_time &&
  1237. !ost->copy_prior_start)
  1238. return;
  1239. }
  1240. if (of->recording_time != INT64_MAX &&
  1241. ist->pts >= of->recording_time + start_time) {
  1242. close_output_stream(ost);
  1243. return;
  1244. }
  1245. if (f->recording_time != INT64_MAX) {
  1246. start_time = f->ctx->start_time;
  1247. if (f->start_time != AV_NOPTS_VALUE)
  1248. start_time += f->start_time;
  1249. if (ist->pts >= f->recording_time + start_time) {
  1250. close_output_stream(ost);
  1251. return;
  1252. }
  1253. }
  1254. /* force the input stream PTS */
  1255. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  1256. audio_size += pkt->size;
  1257. else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1258. video_size += pkt->size;
  1259. ost->sync_opts++;
  1260. } else if (ost->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  1261. subtitle_size += pkt->size;
  1262. }
  1263. if (pkt->pts != AV_NOPTS_VALUE)
  1264. opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
  1265. else
  1266. opkt.pts = AV_NOPTS_VALUE;
  1267. if (pkt->dts == AV_NOPTS_VALUE)
  1268. opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
  1269. else
  1270. opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
  1271. opkt.dts -= ost_tb_start_time;
  1272. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
  1273. int duration = av_get_audio_frame_duration(ist->st->codec, pkt->size);
  1274. if(!duration)
  1275. duration = ist->st->codec->frame_size;
  1276. opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
  1277. (AVRational){1, ist->st->codec->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
  1278. ost->st->time_base) - ost_tb_start_time;
  1279. }
  1280. opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
  1281. opkt.flags = pkt->flags;
  1282. // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
  1283. if ( ost->st->codec->codec_id != AV_CODEC_ID_H264
  1284. && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
  1285. && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
  1286. && ost->st->codec->codec_id != AV_CODEC_ID_VC1
  1287. ) {
  1288. if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY)) {
  1289. opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
  1290. if (!opkt.buf)
  1291. exit_program(1);
  1292. }
  1293. } else {
  1294. opkt.data = pkt->data;
  1295. opkt.size = pkt->size;
  1296. }
  1297. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
  1298. /* store AVPicture in AVPacket, as expected by the output format */
  1299. avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
  1300. opkt.data = (uint8_t *)&pict;
  1301. opkt.size = sizeof(AVPicture);
  1302. opkt.flags |= AV_PKT_FLAG_KEY;
  1303. }
  1304. write_frame(of->ctx, &opkt, ost);
  1305. ost->st->codec->frame_number++;
  1306. }
  1307. int guess_input_channel_layout(InputStream *ist)
  1308. {
  1309. AVCodecContext *dec = ist->st->codec;
  1310. if (!dec->channel_layout) {
  1311. char layout_name[256];
  1312. if (dec->channels > ist->guess_layout_max)
  1313. return 0;
  1314. dec->channel_layout = av_get_default_channel_layout(dec->channels);
  1315. if (!dec->channel_layout)
  1316. return 0;
  1317. av_get_channel_layout_string(layout_name, sizeof(layout_name),
  1318. dec->channels, dec->channel_layout);
  1319. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
  1320. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
  1321. }
  1322. return 1;
  1323. }
  1324. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
  1325. {
  1326. AVFrame *decoded_frame, *f;
  1327. AVCodecContext *avctx = ist->st->codec;
  1328. int i, ret, err = 0, resample_changed;
  1329. AVRational decoded_frame_tb;
  1330. if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
  1331. return AVERROR(ENOMEM);
  1332. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  1333. return AVERROR(ENOMEM);
  1334. decoded_frame = ist->decoded_frame;
  1335. update_benchmark(NULL);
  1336. ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
  1337. update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
  1338. if (ret >= 0 && avctx->sample_rate <= 0) {
  1339. av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
  1340. ret = AVERROR_INVALIDDATA;
  1341. }
  1342. if (*got_output || ret<0 || pkt->size)
  1343. decode_error_stat[ret<0] ++;
  1344. if (!*got_output || ret < 0) {
  1345. if (!pkt->size) {
  1346. for (i = 0; i < ist->nb_filters; i++)
  1347. #if 1
  1348. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  1349. #else
  1350. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  1351. #endif
  1352. }
  1353. return ret;
  1354. }
  1355. #if 1
  1356. /* increment next_dts to use for the case where the input stream does not
  1357. have timestamps or there are multiple frames in the packet */
  1358. ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1359. avctx->sample_rate;
  1360. ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1361. avctx->sample_rate;
  1362. #endif
  1363. resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
  1364. ist->resample_channels != avctx->channels ||
  1365. ist->resample_channel_layout != decoded_frame->channel_layout ||
  1366. ist->resample_sample_rate != decoded_frame->sample_rate;
  1367. if (resample_changed) {
  1368. char layout1[64], layout2[64];
  1369. if (!guess_input_channel_layout(ist)) {
  1370. av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
  1371. "layout for Input Stream #%d.%d\n", ist->file_index,
  1372. ist->st->index);
  1373. exit_program(1);
  1374. }
  1375. decoded_frame->channel_layout = avctx->channel_layout;
  1376. av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
  1377. ist->resample_channel_layout);
  1378. av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
  1379. decoded_frame->channel_layout);
  1380. av_log(NULL, AV_LOG_INFO,
  1381. "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d chl:%s to rate:%d fmt:%s ch:%d chl:%s\n",
  1382. ist->file_index, ist->st->index,
  1383. ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
  1384. ist->resample_channels, layout1,
  1385. decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
  1386. avctx->channels, layout2);
  1387. ist->resample_sample_fmt = decoded_frame->format;
  1388. ist->resample_sample_rate = decoded_frame->sample_rate;
  1389. ist->resample_channel_layout = decoded_frame->channel_layout;
  1390. ist->resample_channels = avctx->channels;
  1391. for (i = 0; i < nb_filtergraphs; i++)
  1392. if (ist_in_filtergraph(filtergraphs[i], ist)) {
  1393. FilterGraph *fg = filtergraphs[i];
  1394. int j;
  1395. if (configure_filtergraph(fg) < 0) {
  1396. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1397. exit_program(1);
  1398. }
  1399. for (j = 0; j < fg->nb_outputs; j++) {
  1400. OutputStream *ost = fg->outputs[j]->ost;
  1401. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  1402. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  1403. av_buffersink_set_frame_size(ost->filter->filter,
  1404. ost->st->codec->frame_size);
  1405. }
  1406. }
  1407. }
  1408. /* if the decoder provides a pts, use it instead of the last packet pts.
  1409. the decoder could be delaying output by a packet or more. */
  1410. if (decoded_frame->pts != AV_NOPTS_VALUE) {
  1411. ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
  1412. decoded_frame_tb = avctx->time_base;
  1413. } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
  1414. decoded_frame->pts = decoded_frame->pkt_pts;
  1415. pkt->pts = AV_NOPTS_VALUE;
  1416. decoded_frame_tb = ist->st->time_base;
  1417. } else if (pkt->pts != AV_NOPTS_VALUE) {
  1418. decoded_frame->pts = pkt->pts;
  1419. pkt->pts = AV_NOPTS_VALUE;
  1420. decoded_frame_tb = ist->st->time_base;
  1421. }else {
  1422. decoded_frame->pts = ist->dts;
  1423. decoded_frame_tb = AV_TIME_BASE_Q;
  1424. }
  1425. if (decoded_frame->pts != AV_NOPTS_VALUE)
  1426. decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
  1427. (AVRational){1, ist->st->codec->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
  1428. (AVRational){1, ist->st->codec->sample_rate});
  1429. for (i = 0; i < ist->nb_filters; i++) {
  1430. if (i < ist->nb_filters - 1) {
  1431. f = ist->filter_frame;
  1432. err = av_frame_ref(f, decoded_frame);
  1433. if (err < 0)
  1434. break;
  1435. } else
  1436. f = decoded_frame;
  1437. err = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f,
  1438. AV_BUFFERSRC_FLAG_PUSH);
  1439. if (err == AVERROR_EOF)
  1440. err = 0; /* ignore */
  1441. if (err < 0)
  1442. break;
  1443. }
  1444. decoded_frame->pts = AV_NOPTS_VALUE;
  1445. av_frame_unref(ist->filter_frame);
  1446. av_frame_unref(decoded_frame);
  1447. return err < 0 ? err : ret;
  1448. }
  1449. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
  1450. {
  1451. AVFrame *decoded_frame, *f;
  1452. void *buffer_to_free = NULL;
  1453. int i, ret = 0, err = 0, resample_changed;
  1454. int64_t best_effort_timestamp;
  1455. AVRational *frame_sample_aspect;
  1456. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  1457. return AVERROR(ENOMEM);
  1458. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  1459. return AVERROR(ENOMEM);
  1460. decoded_frame = ist->decoded_frame;
  1461. pkt->dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
  1462. update_benchmark(NULL);
  1463. ret = avcodec_decode_video2(ist->st->codec,
  1464. decoded_frame, got_output, pkt);
  1465. update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
  1466. if (*got_output || ret<0 || pkt->size)
  1467. decode_error_stat[ret<0] ++;
  1468. if (!*got_output || ret < 0) {
  1469. if (!pkt->size) {
  1470. for (i = 0; i < ist->nb_filters; i++)
  1471. #if 1
  1472. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  1473. #else
  1474. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  1475. #endif
  1476. }
  1477. return ret;
  1478. }
  1479. if(ist->top_field_first>=0)
  1480. decoded_frame->top_field_first = ist->top_field_first;
  1481. best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
  1482. if(best_effort_timestamp != AV_NOPTS_VALUE)
  1483. ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
  1484. if (debug_ts) {
  1485. av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
  1486. "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d \n",
  1487. ist->st->index, av_ts2str(decoded_frame->pts),
  1488. av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
  1489. best_effort_timestamp,
  1490. av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
  1491. decoded_frame->key_frame, decoded_frame->pict_type);
  1492. }
  1493. pkt->size = 0;
  1494. if (ist->st->sample_aspect_ratio.num)
  1495. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  1496. resample_changed = ist->resample_width != decoded_frame->width ||
  1497. ist->resample_height != decoded_frame->height ||
  1498. ist->resample_pix_fmt != decoded_frame->format;
  1499. if (resample_changed) {
  1500. av_log(NULL, AV_LOG_INFO,
  1501. "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
  1502. ist->file_index, ist->st->index,
  1503. ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
  1504. decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
  1505. ist->resample_width = decoded_frame->width;
  1506. ist->resample_height = decoded_frame->height;
  1507. ist->resample_pix_fmt = decoded_frame->format;
  1508. for (i = 0; i < nb_filtergraphs; i++) {
  1509. if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
  1510. configure_filtergraph(filtergraphs[i]) < 0) {
  1511. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1512. exit_program(1);
  1513. }
  1514. }
  1515. }
  1516. frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
  1517. for (i = 0; i < ist->nb_filters; i++) {
  1518. if (!frame_sample_aspect->num)
  1519. *frame_sample_aspect = ist->st->sample_aspect_ratio;
  1520. if (i < ist->nb_filters - 1) {
  1521. f = ist->filter_frame;
  1522. err = av_frame_ref(f, decoded_frame);
  1523. if (err < 0)
  1524. break;
  1525. } else
  1526. f = decoded_frame;
  1527. ret = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f, AV_BUFFERSRC_FLAG_PUSH);
  1528. if (ret == AVERROR_EOF) {
  1529. ret = 0; /* ignore */
  1530. } else if (ret < 0) {
  1531. av_log(NULL, AV_LOG_FATAL,
  1532. "Failed to inject frame into filter network: %s\n", av_err2str(ret));
  1533. exit_program(1);
  1534. }
  1535. }
  1536. av_frame_unref(ist->filter_frame);
  1537. av_frame_unref(decoded_frame);
  1538. av_free(buffer_to_free);
  1539. return err < 0 ? err : ret;
  1540. }
  1541. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
  1542. {
  1543. AVSubtitle subtitle;
  1544. int i, ret = avcodec_decode_subtitle2(ist->st->codec,
  1545. &subtitle, got_output, pkt);
  1546. if (*got_output || ret<0 || pkt->size)
  1547. decode_error_stat[ret<0] ++;
  1548. if (ret < 0 || !*got_output) {
  1549. if (!pkt->size)
  1550. sub2video_flush(ist);
  1551. return ret;
  1552. }
  1553. if (ist->fix_sub_duration) {
  1554. if (ist->prev_sub.got_output) {
  1555. int end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
  1556. 1000, AV_TIME_BASE);
  1557. if (end < ist->prev_sub.subtitle.end_display_time) {
  1558. av_log(ist->st->codec, AV_LOG_DEBUG,
  1559. "Subtitle duration reduced from %d to %d\n",
  1560. ist->prev_sub.subtitle.end_display_time, end);
  1561. ist->prev_sub.subtitle.end_display_time = end;
  1562. }
  1563. }
  1564. FFSWAP(int, *got_output, ist->prev_sub.got_output);
  1565. FFSWAP(int, ret, ist->prev_sub.ret);
  1566. FFSWAP(AVSubtitle, subtitle, ist->prev_sub.subtitle);
  1567. }
  1568. sub2video_update(ist, &subtitle);
  1569. if (!*got_output || !subtitle.num_rects)
  1570. return ret;
  1571. for (i = 0; i < nb_output_streams; i++) {
  1572. OutputStream *ost = output_streams[i];
  1573. if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
  1574. continue;
  1575. do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle);
  1576. }
  1577. avsubtitle_free(&subtitle);
  1578. return ret;
  1579. }
  1580. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  1581. static int output_packet(InputStream *ist, const AVPacket *pkt)
  1582. {
  1583. int ret = 0, i;
  1584. int got_output = 0;
  1585. AVPacket avpkt;
  1586. if (!ist->saw_first_ts) {
  1587. ist->dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
  1588. ist->pts = 0;
  1589. if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
  1590. ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
  1591. ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
  1592. }
  1593. ist->saw_first_ts = 1;
  1594. }
  1595. if (ist->next_dts == AV_NOPTS_VALUE)
  1596. ist->next_dts = ist->dts;
  1597. if (ist->next_pts == AV_NOPTS_VALUE)
  1598. ist->next_pts = ist->pts;
  1599. if (pkt == NULL) {
  1600. /* EOF handling */
  1601. av_init_packet(&avpkt);
  1602. avpkt.data = NULL;
  1603. avpkt.size = 0;
  1604. goto handle_eof;
  1605. } else {
  1606. avpkt = *pkt;
  1607. }
  1608. if (pkt->dts != AV_NOPTS_VALUE) {
  1609. ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1610. if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
  1611. ist->next_pts = ist->pts = ist->dts;
  1612. }
  1613. // while we have more to decode or while the decoder did output something on EOF
  1614. while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
  1615. int duration;
  1616. handle_eof:
  1617. ist->pts = ist->next_pts;
  1618. ist->dts = ist->next_dts;
  1619. if (avpkt.size && avpkt.size != pkt->size) {
  1620. av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
  1621. "Multiple frames in a packet from stream %d\n", pkt->stream_index);
  1622. ist->showed_multi_packet_warning = 1;
  1623. }
  1624. switch (ist->st->codec->codec_type) {
  1625. case AVMEDIA_TYPE_AUDIO:
  1626. ret = decode_audio (ist, &avpkt, &got_output);
  1627. break;
  1628. case AVMEDIA_TYPE_VIDEO:
  1629. ret = decode_video (ist, &avpkt, &got_output);
  1630. if (avpkt.duration) {
  1631. duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
  1632. } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
  1633. int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
  1634. duration = ((int64_t)AV_TIME_BASE *
  1635. ist->st->codec->time_base.num * ticks) /
  1636. ist->st->codec->time_base.den;
  1637. } else
  1638. duration = 0;
  1639. if(ist->dts != AV_NOPTS_VALUE && duration) {
  1640. ist->next_dts += duration;
  1641. }else
  1642. ist->next_dts = AV_NOPTS_VALUE;
  1643. if (got_output)
  1644. ist->next_pts += duration; //FIXME the duration is not correct in some cases
  1645. break;
  1646. case AVMEDIA_TYPE_SUBTITLE:
  1647. ret = transcode_subtitles(ist, &avpkt, &got_output);
  1648. break;
  1649. default:
  1650. return -1;
  1651. }
  1652. if (ret < 0)
  1653. return ret;
  1654. avpkt.dts=
  1655. avpkt.pts= AV_NOPTS_VALUE;
  1656. // touch data and size only if not EOF
  1657. if (pkt) {
  1658. if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  1659. ret = avpkt.size;
  1660. avpkt.data += ret;
  1661. avpkt.size -= ret;
  1662. }
  1663. if (!got_output) {
  1664. continue;
  1665. }
  1666. }
  1667. /* handle stream copy */
  1668. if (!ist->decoding_needed) {
  1669. ist->dts = ist->next_dts;
  1670. switch (ist->st->codec->codec_type) {
  1671. case AVMEDIA_TYPE_AUDIO:
  1672. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
  1673. ist->st->codec->sample_rate;
  1674. break;
  1675. case AVMEDIA_TYPE_VIDEO:
  1676. if (ist->framerate.num) {
  1677. // TODO: Remove work-around for c99-to-c89 issue 7
  1678. AVRational time_base_q = AV_TIME_BASE_Q;
  1679. int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
  1680. ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
  1681. } else if (pkt->duration) {
  1682. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  1683. } else if(ist->st->codec->time_base.num != 0) {
  1684. int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
  1685. ist->next_dts += ((int64_t)AV_TIME_BASE *
  1686. ist->st->codec->time_base.num * ticks) /
  1687. ist->st->codec->time_base.den;
  1688. }
  1689. break;
  1690. }
  1691. ist->pts = ist->dts;
  1692. ist->next_pts = ist->next_dts;
  1693. }
  1694. for (i = 0; pkt && i < nb_output_streams; i++) {
  1695. OutputStream *ost = output_streams[i];
  1696. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  1697. continue;
  1698. do_streamcopy(ist, ost, pkt);
  1699. }
  1700. return 0;
  1701. }
  1702. static void print_sdp(void)
  1703. {
  1704. char sdp[16384];
  1705. int i;
  1706. AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
  1707. if (!avc)
  1708. exit_program(1);
  1709. for (i = 0; i < nb_output_files; i++)
  1710. avc[i] = output_files[i]->ctx;
  1711. av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
  1712. printf("SDP:\n%s\n", sdp);
  1713. fflush(stdout);
  1714. av_freep(&avc);
  1715. }
  1716. static int init_input_stream(int ist_index, char *error, int error_len)
  1717. {
  1718. int ret;
  1719. InputStream *ist = input_streams[ist_index];
  1720. if (ist->decoding_needed) {
  1721. AVCodec *codec = ist->dec;
  1722. if (!codec) {
  1723. snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
  1724. avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
  1725. return AVERROR(EINVAL);
  1726. }
  1727. av_opt_set_int(ist->st->codec, "refcounted_frames", 1, 0);
  1728. if (!av_dict_get(ist->opts, "threads", NULL, 0))
  1729. av_dict_set(&ist->opts, "threads", "auto", 0);
  1730. if ((ret = avcodec_open2(ist->st->codec, codec, &ist->opts)) < 0) {
  1731. char errbuf[128];
  1732. if (ret == AVERROR_EXPERIMENTAL)
  1733. abort_codec_experimental(codec, 0);
  1734. av_strerror(ret, errbuf, sizeof(errbuf));
  1735. snprintf(error, error_len,
  1736. "Error while opening decoder for input stream "
  1737. "#%d:%d : %s",
  1738. ist->file_index, ist->st->index, errbuf);
  1739. return ret;
  1740. }
  1741. assert_avoptions(ist->opts);
  1742. }
  1743. ist->next_pts = AV_NOPTS_VALUE;
  1744. ist->next_dts = AV_NOPTS_VALUE;
  1745. ist->is_start = 1;
  1746. return 0;
  1747. }
  1748. static InputStream *get_input_stream(OutputStream *ost)
  1749. {
  1750. if (ost->source_index >= 0)
  1751. return input_streams[ost->source_index];
  1752. return NULL;
  1753. }
  1754. static int compare_int64(const void *a, const void *b)
  1755. {
  1756. int64_t va = *(int64_t *)a, vb = *(int64_t *)b;
  1757. return va < vb ? -1 : va > vb ? +1 : 0;
  1758. }
  1759. static void parse_forced_key_frames(char *kf, OutputStream *ost,
  1760. AVCodecContext *avctx)
  1761. {
  1762. char *p;
  1763. int n = 1, i, size, index = 0;
  1764. int64_t t, *pts;
  1765. for (p = kf; *p; p++)
  1766. if (*p == ',')
  1767. n++;
  1768. size = n;
  1769. pts = av_malloc(sizeof(*pts) * size);
  1770. if (!pts) {
  1771. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  1772. exit_program(1);
  1773. }
  1774. p = kf;
  1775. for (i = 0; i < n; i++) {
  1776. char *next = strchr(p, ',');
  1777. if (next)
  1778. *next++ = 0;
  1779. if (!memcmp(p, "chapters", 8)) {
  1780. AVFormatContext *avf = output_files[ost->file_index]->ctx;
  1781. int j;
  1782. if (avf->nb_chapters > INT_MAX - size ||
  1783. !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
  1784. sizeof(*pts)))) {
  1785. av_log(NULL, AV_LOG_FATAL,
  1786. "Could not allocate forced key frames array.\n");
  1787. exit_program(1);
  1788. }
  1789. t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
  1790. t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1791. for (j = 0; j < avf->nb_chapters; j++) {
  1792. AVChapter *c = avf->chapters[j];
  1793. av_assert1(index < size);
  1794. pts[index++] = av_rescale_q(c->start, c->time_base,
  1795. avctx->time_base) + t;
  1796. }
  1797. } else {
  1798. t = parse_time_or_die("force_key_frames", p, 1);
  1799. av_assert1(index < size);
  1800. pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1801. }
  1802. p = next;
  1803. }
  1804. av_assert0(index == size);
  1805. qsort(pts, size, sizeof(*pts), compare_int64);
  1806. ost->forced_kf_count = size;
  1807. ost->forced_kf_pts = pts;
  1808. }
  1809. static void report_new_stream(int input_index, AVPacket *pkt)
  1810. {
  1811. InputFile *file = input_files[input_index];
  1812. AVStream *st = file->ctx->streams[pkt->stream_index];
  1813. if (pkt->stream_index < file->nb_streams_warn)
  1814. return;
  1815. av_log(file->ctx, AV_LOG_WARNING,
  1816. "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
  1817. av_get_media_type_string(st->codec->codec_type),
  1818. input_index, pkt->stream_index,
  1819. pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
  1820. file->nb_streams_warn = pkt->stream_index + 1;
  1821. }
  1822. static int transcode_init(void)
  1823. {
  1824. int ret = 0, i, j, k;
  1825. AVFormatContext *oc;
  1826. AVCodecContext *codec;
  1827. OutputStream *ost;
  1828. InputStream *ist;
  1829. char error[1024];
  1830. int want_sdp = 1;
  1831. /* init framerate emulation */
  1832. for (i = 0; i < nb_input_files; i++) {
  1833. InputFile *ifile = input_files[i];
  1834. if (ifile->rate_emu)
  1835. for (j = 0; j < ifile->nb_streams; j++)
  1836. input_streams[j + ifile->ist_index]->start = av_gettime();
  1837. }
  1838. /* output stream init */
  1839. for (i = 0; i < nb_output_files; i++) {
  1840. oc = output_files[i]->ctx;
  1841. if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
  1842. av_dump_format(oc, i, oc->filename, 1);
  1843. av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
  1844. return AVERROR(EINVAL);
  1845. }
  1846. }
  1847. /* init complex filtergraphs */
  1848. for (i = 0; i < nb_filtergraphs; i++)
  1849. if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
  1850. return ret;
  1851. /* for each output stream, we compute the right encoding parameters */
  1852. for (i = 0; i < nb_output_streams; i++) {
  1853. AVCodecContext *icodec = NULL;
  1854. ost = output_streams[i];
  1855. oc = output_files[ost->file_index]->ctx;
  1856. ist = get_input_stream(ost);
  1857. if (ost->attachment_filename)
  1858. continue;
  1859. codec = ost->st->codec;
  1860. if (ist) {
  1861. icodec = ist->st->codec;
  1862. ost->st->disposition = ist->st->disposition;
  1863. codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
  1864. codec->chroma_sample_location = icodec->chroma_sample_location;
  1865. }
  1866. if (ost->stream_copy) {
  1867. AVRational sar;
  1868. uint64_t extra_size;
  1869. av_assert0(ist && !ost->filter);
  1870. extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
  1871. if (extra_size > INT_MAX) {
  1872. return AVERROR(EINVAL);
  1873. }
  1874. /* if stream_copy is selected, no need to decode or encode */
  1875. codec->codec_id = icodec->codec_id;
  1876. codec->codec_type = icodec->codec_type;
  1877. if (!codec->codec_tag) {
  1878. unsigned int codec_tag;
  1879. if (!oc->oformat->codec_tag ||
  1880. av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
  1881. !av_codec_get_tag2(oc->oformat->codec_tag, icodec->codec_id, &codec_tag))
  1882. codec->codec_tag = icodec->codec_tag;
  1883. }
  1884. codec->bit_rate = icodec->bit_rate;
  1885. codec->rc_max_rate = icodec->rc_max_rate;
  1886. codec->rc_buffer_size = icodec->rc_buffer_size;
  1887. codec->field_order = icodec->field_order;
  1888. codec->extradata = av_mallocz(extra_size);
  1889. if (!codec->extradata) {
  1890. return AVERROR(ENOMEM);
  1891. }
  1892. memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
  1893. codec->extradata_size= icodec->extradata_size;
  1894. codec->bits_per_coded_sample = icodec->bits_per_coded_sample;
  1895. codec->time_base = ist->st->time_base;
  1896. /*
  1897. * Avi is a special case here because it supports variable fps but
  1898. * having the fps and timebase differe significantly adds quite some
  1899. * overhead
  1900. */
  1901. if(!strcmp(oc->oformat->name, "avi")) {
  1902. if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
  1903. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
  1904. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(icodec->time_base)
  1905. && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(icodec->time_base) < 1.0/500
  1906. || copy_tb==2){
  1907. codec->time_base.num = ist->st->r_frame_rate.den;
  1908. codec->time_base.den = 2*ist->st->r_frame_rate.num;
  1909. codec->ticks_per_frame = 2;
  1910. } else if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
  1911. && av_q2d(ist->st->time_base) < 1.0/500
  1912. || copy_tb==0){
  1913. codec->time_base = icodec->time_base;
  1914. codec->time_base.num *= icodec->ticks_per_frame;
  1915. codec->time_base.den *= 2;
  1916. codec->ticks_per_frame = 2;
  1917. }
  1918. } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
  1919. && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
  1920. && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
  1921. && strcmp(oc->oformat->name, "f4v")
  1922. ) {
  1923. if( copy_tb<0 && icodec->time_base.den
  1924. && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
  1925. && av_q2d(ist->st->time_base) < 1.0/500
  1926. || copy_tb==0){
  1927. codec->time_base = icodec->time_base;
  1928. codec->time_base.num *= icodec->ticks_per_frame;
  1929. }
  1930. }
  1931. if ( codec->codec_tag == AV_RL32("tmcd")
  1932. && icodec->time_base.num < icodec->time_base.den
  1933. && icodec->time_base.num > 0
  1934. && 121LL*icodec->time_base.num > icodec->time_base.den) {
  1935. codec->time_base = icodec->time_base;
  1936. }
  1937. if (ist && !ost->frame_rate.num)
  1938. ost->frame_rate = ist->framerate;
  1939. if(ost->frame_rate.num)
  1940. codec->time_base = av_inv_q(ost->frame_rate);
  1941. av_reduce(&codec->time_base.num, &codec->time_base.den,
  1942. codec->time_base.num, codec->time_base.den, INT_MAX);
  1943. switch (codec->codec_type) {
  1944. case AVMEDIA_TYPE_AUDIO:
  1945. if (audio_volume != 256) {
  1946. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
  1947. exit_program(1);
  1948. }
  1949. codec->channel_layout = icodec->channel_layout;
  1950. codec->sample_rate = icodec->sample_rate;
  1951. codec->channels = icodec->channels;
  1952. codec->frame_size = icodec->frame_size;
  1953. codec->audio_service_type = icodec->audio_service_type;
  1954. codec->block_align = icodec->block_align;
  1955. if((codec->block_align == 1 || codec->block_align == 1152 || codec->block_align == 576) && codec->codec_id == AV_CODEC_ID_MP3)
  1956. codec->block_align= 0;
  1957. if(codec->codec_id == AV_CODEC_ID_AC3)
  1958. codec->block_align= 0;
  1959. break;
  1960. case AVMEDIA_TYPE_VIDEO:
  1961. codec->pix_fmt = icodec->pix_fmt;
  1962. codec->width = icodec->width;
  1963. codec->height = icodec->height;
  1964. codec->has_b_frames = icodec->has_b_frames;
  1965. if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
  1966. sar =
  1967. av_mul_q(ost->frame_aspect_ratio,
  1968. (AVRational){ codec->height, codec->width });
  1969. av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
  1970. "with stream copy may produce invalid files\n");
  1971. }
  1972. else if (ist->st->sample_aspect_ratio.num)
  1973. sar = ist->st->sample_aspect_ratio;
  1974. else
  1975. sar = icodec->sample_aspect_ratio;
  1976. ost->st->sample_aspect_ratio = codec->sample_aspect_ratio = sar;
  1977. ost->st->avg_frame_rate = ist->st->avg_frame_rate;
  1978. break;
  1979. case AVMEDIA_TYPE_SUBTITLE:
  1980. codec->width = icodec->width;
  1981. codec->height = icodec->height;
  1982. break;
  1983. case AVMEDIA_TYPE_DATA:
  1984. case AVMEDIA_TYPE_ATTACHMENT:
  1985. break;
  1986. default:
  1987. abort();
  1988. }
  1989. } else {
  1990. if (!ost->enc)
  1991. ost->enc = avcodec_find_encoder(codec->codec_id);
  1992. if (!ost->enc) {
  1993. /* should only happen when a default codec is not present. */
  1994. snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
  1995. avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
  1996. ret = AVERROR(EINVAL);
  1997. goto dump_format;
  1998. }
  1999. if (ist)
  2000. ist->decoding_needed++;
  2001. ost->encoding_needed = 1;
  2002. if (!ost->filter &&
  2003. (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  2004. codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
  2005. FilterGraph *fg;
  2006. fg = init_simple_filtergraph(ist, ost);
  2007. if (configure_filtergraph(fg)) {
  2008. av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
  2009. exit_program(1);
  2010. }
  2011. }
  2012. if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  2013. if (ost->filter && !ost->frame_rate.num)
  2014. ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
  2015. if (ist && !ost->frame_rate.num)
  2016. ost->frame_rate = ist->framerate;
  2017. if (ist && !ost->frame_rate.num)
  2018. ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
  2019. // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
  2020. if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
  2021. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
  2022. ost->frame_rate = ost->enc->supported_framerates[idx];
  2023. }
  2024. }
  2025. switch (codec->codec_type) {
  2026. case AVMEDIA_TYPE_AUDIO:
  2027. codec->sample_fmt = ost->filter->filter->inputs[0]->format;
  2028. codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
  2029. codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
  2030. codec->channels = avfilter_link_get_channels(ost->filter->filter->inputs[0]);
  2031. codec->time_base = (AVRational){ 1, codec->sample_rate };
  2032. break;
  2033. case AVMEDIA_TYPE_VIDEO:
  2034. codec->time_base = av_inv_q(ost->frame_rate);
  2035. if (ost->filter && !(codec->time_base.num && codec->time_base.den))
  2036. codec->time_base = ost->filter->filter->inputs[0]->time_base;
  2037. if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
  2038. && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
  2039. av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
  2040. "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
  2041. }
  2042. for (j = 0; j < ost->forced_kf_count; j++)
  2043. ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
  2044. AV_TIME_BASE_Q,
  2045. codec->time_base);
  2046. codec->width = ost->filter->filter->inputs[0]->w;
  2047. codec->height = ost->filter->filter->inputs[0]->h;
  2048. codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  2049. ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
  2050. av_mul_q(ost->frame_aspect_ratio, (AVRational){ codec->height, codec->width }) :
  2051. ost->filter->filter->inputs[0]->sample_aspect_ratio;
  2052. if (!strncmp(ost->enc->name, "libx264", 7) &&
  2053. codec->pix_fmt == AV_PIX_FMT_NONE &&
  2054. ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
  2055. av_log(NULL, AV_LOG_WARNING,
  2056. "No pixel format specified, %s for H.264 encoding chosen.\n"
  2057. "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
  2058. av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
  2059. if (!strncmp(ost->enc->name, "mpeg2video", 10) &&
  2060. codec->pix_fmt == AV_PIX_FMT_NONE &&
  2061. ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
  2062. av_log(NULL, AV_LOG_WARNING,
  2063. "No pixel format specified, %s for MPEG-2 encoding chosen.\n"
  2064. "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
  2065. av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
  2066. codec->pix_fmt = ost->filter->filter->inputs[0]->format;
  2067. if (!icodec ||
  2068. codec->width != icodec->width ||
  2069. codec->height != icodec->height ||
  2070. codec->pix_fmt != icodec->pix_fmt) {
  2071. codec->bits_per_raw_sample = frame_bits_per_raw_sample;
  2072. }
  2073. if (ost->forced_keyframes) {
  2074. if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
  2075. ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
  2076. forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
  2077. if (ret < 0) {
  2078. av_log(NULL, AV_LOG_ERROR,
  2079. "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
  2080. return ret;
  2081. }
  2082. ost->forced_keyframes_expr_const_values[FKF_N] = 0;
  2083. ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
  2084. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
  2085. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
  2086. } else {
  2087. parse_forced_key_frames(ost->forced_keyframes, ost, ost->st->codec);
  2088. }
  2089. }
  2090. break;
  2091. case AVMEDIA_TYPE_SUBTITLE:
  2092. codec->time_base = (AVRational){1, 1000};
  2093. if (!codec->width) {
  2094. codec->width = input_streams[ost->source_index]->st->codec->width;
  2095. codec->height = input_streams[ost->source_index]->st->codec->height;
  2096. }
  2097. break;
  2098. default:
  2099. abort();
  2100. break;
  2101. }
  2102. /* two pass mode */
  2103. if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
  2104. char logfilename[1024];
  2105. FILE *f;
  2106. snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
  2107. ost->logfile_prefix ? ost->logfile_prefix :
  2108. DEFAULT_PASS_LOGFILENAME_PREFIX,
  2109. i);
  2110. if (!strcmp(ost->enc->name, "libx264")) {
  2111. av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
  2112. } else {
  2113. if (codec->flags & CODEC_FLAG_PASS2) {
  2114. char *logbuffer;
  2115. size_t logbuffer_size;
  2116. if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
  2117. av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
  2118. logfilename);
  2119. exit_program(1);
  2120. }
  2121. codec->stats_in = logbuffer;
  2122. }
  2123. if (codec->flags & CODEC_FLAG_PASS1) {
  2124. f = fopen(logfilename, "wb");
  2125. if (!f) {
  2126. av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
  2127. logfilename, strerror(errno));
  2128. exit_program(1);
  2129. }
  2130. ost->logfile = f;
  2131. }
  2132. }
  2133. }
  2134. }
  2135. }
  2136. /* open each encoder */
  2137. for (i = 0; i < nb_output_streams; i++) {
  2138. ost = output_streams[i];
  2139. if (ost->encoding_needed) {
  2140. AVCodec *codec = ost->enc;
  2141. AVCodecContext *dec = NULL;
  2142. if ((ist = get_input_stream(ost)))
  2143. dec = ist->st->codec;
  2144. if (dec && dec->subtitle_header) {
  2145. /* ASS code assumes this buffer is null terminated so add extra byte. */
  2146. ost->st->codec->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
  2147. if (!ost->st->codec->subtitle_header) {
  2148. ret = AVERROR(ENOMEM);
  2149. goto dump_format;
  2150. }
  2151. memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  2152. ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
  2153. }
  2154. if (!av_dict_get(ost->opts, "threads", NULL, 0))
  2155. av_dict_set(&ost->opts, "threads", "auto", 0);
  2156. if ((ret = avcodec_open2(ost->st->codec, codec, &ost->opts)) < 0) {
  2157. if (ret == AVERROR_EXPERIMENTAL)
  2158. abort_codec_experimental(codec, 1);
  2159. snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
  2160. ost->file_index, ost->index);
  2161. goto dump_format;
  2162. }
  2163. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  2164. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  2165. av_buffersink_set_frame_size(ost->filter->filter,
  2166. ost->st->codec->frame_size);
  2167. assert_avoptions(ost->opts);
  2168. if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
  2169. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  2170. " It takes bits/s as argument, not kbits/s\n");
  2171. extra_size += ost->st->codec->extradata_size;
  2172. if (ost->st->codec->me_threshold)
  2173. input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
  2174. } else {
  2175. av_opt_set_dict(ost->st->codec, &ost->opts);
  2176. }
  2177. }
  2178. /* init input streams */
  2179. for (i = 0; i < nb_input_streams; i++)
  2180. if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
  2181. for (i = 0; i < nb_output_streams; i++) {
  2182. ost = output_streams[i];
  2183. avcodec_close(ost->st->codec);
  2184. }
  2185. goto dump_format;
  2186. }
  2187. /* discard unused programs */
  2188. for (i = 0; i < nb_input_files; i++) {
  2189. InputFile *ifile = input_files[i];
  2190. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  2191. AVProgram *p = ifile->ctx->programs[j];
  2192. int discard = AVDISCARD_ALL;
  2193. for (k = 0; k < p->nb_stream_indexes; k++)
  2194. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
  2195. discard = AVDISCARD_DEFAULT;
  2196. break;
  2197. }
  2198. p->discard = discard;
  2199. }
  2200. }
  2201. /* open files and write file headers */
  2202. for (i = 0; i < nb_output_files; i++) {
  2203. oc = output_files[i]->ctx;
  2204. oc->interrupt_callback = int_cb;
  2205. if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
  2206. char errbuf[128];
  2207. av_strerror(ret, errbuf, sizeof(errbuf));
  2208. snprintf(error, sizeof(error),
  2209. "Could not write header for output file #%d "
  2210. "(incorrect codec parameters ?): %s",
  2211. i, errbuf);
  2212. ret = AVERROR(EINVAL);
  2213. goto dump_format;
  2214. }
  2215. // assert_avoptions(output_files[i]->opts);
  2216. if (strcmp(oc->oformat->name, "rtp")) {
  2217. want_sdp = 0;
  2218. }
  2219. }
  2220. dump_format:
  2221. /* dump the file output parameters - cannot be done before in case
  2222. of stream copy */
  2223. for (i = 0; i < nb_output_files; i++) {
  2224. av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
  2225. }
  2226. /* dump the stream mapping */
  2227. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  2228. for (i = 0; i < nb_input_streams; i++) {
  2229. ist = input_streams[i];
  2230. for (j = 0; j < ist->nb_filters; j++) {
  2231. if (ist->filters[j]->graph->graph_desc) {
  2232. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  2233. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
  2234. ist->filters[j]->name);
  2235. if (nb_filtergraphs > 1)
  2236. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  2237. av_log(NULL, AV_LOG_INFO, "\n");
  2238. }
  2239. }
  2240. }
  2241. for (i = 0; i < nb_output_streams; i++) {
  2242. ost = output_streams[i];
  2243. if (ost->attachment_filename) {
  2244. /* an attached file */
  2245. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  2246. ost->attachment_filename, ost->file_index, ost->index);
  2247. continue;
  2248. }
  2249. if (ost->filter && ost->filter->graph->graph_desc) {
  2250. /* output from a complex graph */
  2251. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  2252. if (nb_filtergraphs > 1)
  2253. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  2254. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  2255. ost->index, ost->enc ? ost->enc->name : "?");
  2256. continue;
  2257. }
  2258. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  2259. input_streams[ost->source_index]->file_index,
  2260. input_streams[ost->source_index]->st->index,
  2261. ost->file_index,
  2262. ost->index);
  2263. if (ost->sync_ist != input_streams[ost->source_index])
  2264. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  2265. ost->sync_ist->file_index,
  2266. ost->sync_ist->st->index);
  2267. if (ost->stream_copy)
  2268. av_log(NULL, AV_LOG_INFO, " (copy)");
  2269. else
  2270. av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
  2271. input_streams[ost->source_index]->dec->name : "?",
  2272. ost->enc ? ost->enc->name : "?");
  2273. av_log(NULL, AV_LOG_INFO, "\n");
  2274. }
  2275. if (ret) {
  2276. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  2277. return ret;
  2278. }
  2279. if (want_sdp) {
  2280. print_sdp();
  2281. }
  2282. return 0;
  2283. }
  2284. /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
  2285. static int need_output(void)
  2286. {
  2287. int i;
  2288. for (i = 0; i < nb_output_streams; i++) {
  2289. OutputStream *ost = output_streams[i];
  2290. OutputFile *of = output_files[ost->file_index];
  2291. AVFormatContext *os = output_files[ost->file_index]->ctx;
  2292. if (ost->finished ||
  2293. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  2294. continue;
  2295. if (ost->frame_number >= ost->max_frames) {
  2296. int j;
  2297. for (j = 0; j < of->ctx->nb_streams; j++)
  2298. close_output_stream(output_streams[of->ost_index + j]);
  2299. continue;
  2300. }
  2301. return 1;
  2302. }
  2303. return 0;
  2304. }
  2305. /**
  2306. * Select the output stream to process.
  2307. *
  2308. * @return selected output stream, or NULL if none available
  2309. */
  2310. static OutputStream *choose_output(void)
  2311. {
  2312. int i;
  2313. int64_t opts_min = INT64_MAX;
  2314. OutputStream *ost_min = NULL;
  2315. for (i = 0; i < nb_output_streams; i++) {
  2316. OutputStream *ost = output_streams[i];
  2317. int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
  2318. AV_TIME_BASE_Q);
  2319. if (!ost->unavailable && !ost->finished && opts < opts_min) {
  2320. opts_min = opts;
  2321. ost_min = ost;
  2322. }
  2323. }
  2324. return ost_min;
  2325. }
  2326. static int check_keyboard_interaction(int64_t cur_time)
  2327. {
  2328. int i, ret, key;
  2329. static int64_t last_time;
  2330. if (received_nb_signals)
  2331. return AVERROR_EXIT;
  2332. /* read_key() returns 0 on EOF */
  2333. if(cur_time - last_time >= 100000 && !run_as_daemon){
  2334. key = read_key();
  2335. last_time = cur_time;
  2336. }else
  2337. key = -1;
  2338. if (key == 'q')
  2339. return AVERROR_EXIT;
  2340. if (key == '+') av_log_set_level(av_log_get_level()+10);
  2341. if (key == '-') av_log_set_level(av_log_get_level()-10);
  2342. if (key == 's') qp_hist ^= 1;
  2343. if (key == 'h'){
  2344. if (do_hex_dump){
  2345. do_hex_dump = do_pkt_dump = 0;
  2346. } else if(do_pkt_dump){
  2347. do_hex_dump = 1;
  2348. } else
  2349. do_pkt_dump = 1;
  2350. av_log_set_level(AV_LOG_DEBUG);
  2351. }
  2352. if (key == 'c' || key == 'C'){
  2353. char buf[4096], target[64], command[256], arg[256] = {0};
  2354. double time;
  2355. int k, n = 0;
  2356. fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
  2357. i = 0;
  2358. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  2359. if (k > 0)
  2360. buf[i++] = k;
  2361. buf[i] = 0;
  2362. if (k > 0 &&
  2363. (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
  2364. av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
  2365. target, time, command, arg);
  2366. for (i = 0; i < nb_filtergraphs; i++) {
  2367. FilterGraph *fg = filtergraphs[i];
  2368. if (fg->graph) {
  2369. if (time < 0) {
  2370. ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
  2371. key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
  2372. fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
  2373. } else {
  2374. ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
  2375. }
  2376. }
  2377. }
  2378. } else {
  2379. av_log(NULL, AV_LOG_ERROR,
  2380. "Parse error, at least 3 arguments were expected, "
  2381. "only %d given in string '%s'\n", n, buf);
  2382. }
  2383. }
  2384. if (key == 'd' || key == 'D'){
  2385. int debug=0;
  2386. if(key == 'D') {
  2387. debug = input_streams[0]->st->codec->debug<<1;
  2388. if(!debug) debug = 1;
  2389. while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
  2390. debug += debug;
  2391. }else
  2392. if(scanf("%d", &debug)!=1)
  2393. fprintf(stderr,"error parsing debug value\n");
  2394. for(i=0;i<nb_input_streams;i++) {
  2395. input_streams[i]->st->codec->debug = debug;
  2396. }
  2397. for(i=0;i<nb_output_streams;i++) {
  2398. OutputStream *ost = output_streams[i];
  2399. ost->st->codec->debug = debug;
  2400. }
  2401. if(debug) av_log_set_level(AV_LOG_DEBUG);
  2402. fprintf(stderr,"debug=%d\n", debug);
  2403. }
  2404. if (key == '?'){
  2405. fprintf(stderr, "key function\n"
  2406. "? show this help\n"
  2407. "+ increase verbosity\n"
  2408. "- decrease verbosity\n"
  2409. "c Send command to filtergraph\n"
  2410. "D cycle through available debug modes\n"
  2411. "h dump packets/hex press to cycle through the 3 states\n"
  2412. "q quit\n"
  2413. "s Show QP histogram\n"
  2414. );
  2415. }
  2416. return 0;
  2417. }
  2418. #if HAVE_PTHREADS
  2419. static void *input_thread(void *arg)
  2420. {
  2421. InputFile *f = arg;
  2422. int ret = 0;
  2423. while (!transcoding_finished && ret >= 0) {
  2424. AVPacket pkt;
  2425. ret = av_read_frame(f->ctx, &pkt);
  2426. if (ret == AVERROR(EAGAIN)) {
  2427. av_usleep(10000);
  2428. ret = 0;
  2429. continue;
  2430. } else if (ret < 0)
  2431. break;
  2432. pthread_mutex_lock(&f->fifo_lock);
  2433. while (!av_fifo_space(f->fifo))
  2434. pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
  2435. av_dup_packet(&pkt);
  2436. av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
  2437. pthread_mutex_unlock(&f->fifo_lock);
  2438. }
  2439. f->finished = 1;
  2440. return NULL;
  2441. }
  2442. static void free_input_threads(void)
  2443. {
  2444. int i;
  2445. if (nb_input_files == 1)
  2446. return;
  2447. transcoding_finished = 1;
  2448. for (i = 0; i < nb_input_files; i++) {
  2449. InputFile *f = input_files[i];
  2450. AVPacket pkt;
  2451. if (!f->fifo || f->joined)
  2452. continue;
  2453. pthread_mutex_lock(&f->fifo_lock);
  2454. while (av_fifo_size(f->fifo)) {
  2455. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2456. av_free_packet(&pkt);
  2457. }
  2458. pthread_cond_signal(&f->fifo_cond);
  2459. pthread_mutex_unlock(&f->fifo_lock);
  2460. pthread_join(f->thread, NULL);
  2461. f->joined = 1;
  2462. while (av_fifo_size(f->fifo)) {
  2463. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2464. av_free_packet(&pkt);
  2465. }
  2466. av_fifo_free(f->fifo);
  2467. }
  2468. }
  2469. static int init_input_threads(void)
  2470. {
  2471. int i, ret;
  2472. if (nb_input_files == 1)
  2473. return 0;
  2474. for (i = 0; i < nb_input_files; i++) {
  2475. InputFile *f = input_files[i];
  2476. if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
  2477. return AVERROR(ENOMEM);
  2478. pthread_mutex_init(&f->fifo_lock, NULL);
  2479. pthread_cond_init (&f->fifo_cond, NULL);
  2480. if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
  2481. return AVERROR(ret);
  2482. }
  2483. return 0;
  2484. }
  2485. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
  2486. {
  2487. int ret = 0;
  2488. pthread_mutex_lock(&f->fifo_lock);
  2489. if (av_fifo_size(f->fifo)) {
  2490. av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
  2491. pthread_cond_signal(&f->fifo_cond);
  2492. } else {
  2493. if (f->finished)
  2494. ret = AVERROR_EOF;
  2495. else
  2496. ret = AVERROR(EAGAIN);
  2497. }
  2498. pthread_mutex_unlock(&f->fifo_lock);
  2499. return ret;
  2500. }
  2501. #endif
  2502. static int get_input_packet(InputFile *f, AVPacket *pkt)
  2503. {
  2504. if (f->rate_emu) {
  2505. int i;
  2506. for (i = 0; i < f->nb_streams; i++) {
  2507. InputStream *ist = input_streams[f->ist_index + i];
  2508. int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
  2509. int64_t now = av_gettime() - ist->start;
  2510. if (pts > now)
  2511. return AVERROR(EAGAIN);
  2512. }
  2513. }
  2514. #if HAVE_PTHREADS
  2515. if (nb_input_files > 1)
  2516. return get_input_packet_mt(f, pkt);
  2517. #endif
  2518. return av_read_frame(f->ctx, pkt);
  2519. }
  2520. static int got_eagain(void)
  2521. {
  2522. int i;
  2523. for (i = 0; i < nb_output_streams; i++)
  2524. if (output_streams[i]->unavailable)
  2525. return 1;
  2526. return 0;
  2527. }
  2528. static void reset_eagain(void)
  2529. {
  2530. int i;
  2531. for (i = 0; i < nb_input_files; i++)
  2532. input_files[i]->eagain = 0;
  2533. for (i = 0; i < nb_output_streams; i++)
  2534. output_streams[i]->unavailable = 0;
  2535. }
  2536. /*
  2537. * Return
  2538. * - 0 -- one packet was read and processed
  2539. * - AVERROR(EAGAIN) -- no packets were available for selected file,
  2540. * this function should be called again
  2541. * - AVERROR_EOF -- this function should not be called again
  2542. */
  2543. static int process_input(int file_index)
  2544. {
  2545. InputFile *ifile = input_files[file_index];
  2546. AVFormatContext *is;
  2547. InputStream *ist;
  2548. AVPacket pkt;
  2549. int ret, i, j;
  2550. is = ifile->ctx;
  2551. ret = get_input_packet(ifile, &pkt);
  2552. if (ret == AVERROR(EAGAIN)) {
  2553. ifile->eagain = 1;
  2554. return ret;
  2555. }
  2556. if (ret < 0) {
  2557. if (ret != AVERROR_EOF) {
  2558. print_error(is->filename, ret);
  2559. if (exit_on_error)
  2560. exit_program(1);
  2561. }
  2562. ifile->eof_reached = 1;
  2563. for (i = 0; i < ifile->nb_streams; i++) {
  2564. ist = input_streams[ifile->ist_index + i];
  2565. if (ist->decoding_needed)
  2566. output_packet(ist, NULL);
  2567. /* mark all outputs that don't go through lavfi as finished */
  2568. for (j = 0; j < nb_output_streams; j++) {
  2569. OutputStream *ost = output_streams[j];
  2570. if (ost->source_index == ifile->ist_index + i &&
  2571. (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
  2572. close_output_stream(ost);
  2573. }
  2574. }
  2575. return AVERROR(EAGAIN);
  2576. }
  2577. reset_eagain();
  2578. if (do_pkt_dump) {
  2579. av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
  2580. is->streams[pkt.stream_index]);
  2581. }
  2582. /* the following test is needed in case new streams appear
  2583. dynamically in stream : we ignore them */
  2584. if (pkt.stream_index >= ifile->nb_streams) {
  2585. report_new_stream(file_index, &pkt);
  2586. goto discard_packet;
  2587. }
  2588. ist = input_streams[ifile->ist_index + pkt.stream_index];
  2589. if (ist->discard)
  2590. goto discard_packet;
  2591. if (debug_ts) {
  2592. av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
  2593. "next_dts:%s next_dts_time:%s next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
  2594. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
  2595. av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
  2596. av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
  2597. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  2598. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  2599. av_ts2str(input_files[ist->file_index]->ts_offset),
  2600. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  2601. }
  2602. if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
  2603. int64_t stime, stime2;
  2604. // Correcting starttime based on the enabled streams
  2605. // FIXME this ideally should be done before the first use of starttime but we do not know which are the enabled streams at that point.
  2606. // so we instead do it here as part of discontinuity handling
  2607. if ( ist->next_dts == AV_NOPTS_VALUE
  2608. && ifile->ts_offset == -is->start_time
  2609. && (is->iformat->flags & AVFMT_TS_DISCONT)) {
  2610. int64_t new_start_time = INT64_MAX;
  2611. for (i=0; i<is->nb_streams; i++) {
  2612. AVStream *st = is->streams[i];
  2613. if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
  2614. continue;
  2615. new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
  2616. }
  2617. if (new_start_time > is->start_time) {
  2618. av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
  2619. ifile->ts_offset = -new_start_time;
  2620. }
  2621. }
  2622. stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
  2623. stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
  2624. ist->wrap_correction_done = 1;
  2625. if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  2626. pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
  2627. ist->wrap_correction_done = 0;
  2628. }
  2629. if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  2630. pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
  2631. ist->wrap_correction_done = 0;
  2632. }
  2633. }
  2634. if (pkt.dts != AV_NOPTS_VALUE)
  2635. pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2636. if (pkt.pts != AV_NOPTS_VALUE)
  2637. pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2638. if (pkt.pts != AV_NOPTS_VALUE)
  2639. pkt.pts *= ist->ts_scale;
  2640. if (pkt.dts != AV_NOPTS_VALUE)
  2641. pkt.dts *= ist->ts_scale;
  2642. if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
  2643. && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
  2644. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2645. int64_t delta = pkt_dts - ifile->last_ts;
  2646. if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  2647. (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
  2648. ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)){
  2649. ifile->ts_offset -= delta;
  2650. av_log(NULL, AV_LOG_DEBUG,
  2651. "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  2652. delta, ifile->ts_offset);
  2653. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2654. if (pkt.pts != AV_NOPTS_VALUE)
  2655. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2656. }
  2657. }
  2658. if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
  2659. !copy_ts) {
  2660. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2661. int64_t delta = pkt_dts - ist->next_dts;
  2662. if (is->iformat->flags & AVFMT_TS_DISCONT) {
  2663. if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  2664. (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
  2665. ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
  2666. pkt_dts+1<ist->pts){
  2667. ifile->ts_offset -= delta;
  2668. av_log(NULL, AV_LOG_DEBUG,
  2669. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  2670. delta, ifile->ts_offset);
  2671. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2672. if (pkt.pts != AV_NOPTS_VALUE)
  2673. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2674. }
  2675. } else {
  2676. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  2677. (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
  2678. ) {
  2679. av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
  2680. pkt.dts = AV_NOPTS_VALUE;
  2681. }
  2682. if (pkt.pts != AV_NOPTS_VALUE){
  2683. int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
  2684. delta = pkt_pts - ist->next_dts;
  2685. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  2686. (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
  2687. ) {
  2688. av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
  2689. pkt.pts = AV_NOPTS_VALUE;
  2690. }
  2691. }
  2692. }
  2693. }
  2694. if (pkt.dts != AV_NOPTS_VALUE)
  2695. ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2696. if (debug_ts) {
  2697. av_log(NULL, AV_LOG_INFO, "demuxer+ffmpeg -> ist_index:%d type:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
  2698. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
  2699. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  2700. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  2701. av_ts2str(input_files[ist->file_index]->ts_offset),
  2702. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  2703. }
  2704. sub2video_heartbeat(ist, pkt.pts);
  2705. ret = output_packet(ist, &pkt);
  2706. if (ret < 0) {
  2707. char buf[128];
  2708. av_strerror(ret, buf, sizeof(buf));
  2709. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
  2710. ist->file_index, ist->st->index, buf);
  2711. if (exit_on_error)
  2712. exit_program(1);
  2713. }
  2714. discard_packet:
  2715. av_free_packet(&pkt);
  2716. return 0;
  2717. }
  2718. /**
  2719. * Perform a step of transcoding for the specified filter graph.
  2720. *
  2721. * @param[in] graph filter graph to consider
  2722. * @param[out] best_ist input stream where a frame would allow to continue
  2723. * @return 0 for success, <0 for error
  2724. */
  2725. static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
  2726. {
  2727. int i, ret;
  2728. int nb_requests, nb_requests_max = 0;
  2729. InputFilter *ifilter;
  2730. InputStream *ist;
  2731. *best_ist = NULL;
  2732. ret = avfilter_graph_request_oldest(graph->graph);
  2733. if (ret >= 0)
  2734. return reap_filters();
  2735. if (ret == AVERROR_EOF) {
  2736. ret = reap_filters();
  2737. for (i = 0; i < graph->nb_outputs; i++)
  2738. close_output_stream(graph->outputs[i]->ost);
  2739. return ret;
  2740. }
  2741. if (ret != AVERROR(EAGAIN))
  2742. return ret;
  2743. for (i = 0; i < graph->nb_inputs; i++) {
  2744. ifilter = graph->inputs[i];
  2745. ist = ifilter->ist;
  2746. if (input_files[ist->file_index]->eagain ||
  2747. input_files[ist->file_index]->eof_reached)
  2748. continue;
  2749. nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
  2750. if (nb_requests > nb_requests_max) {
  2751. nb_requests_max = nb_requests;
  2752. *best_ist = ist;
  2753. }
  2754. }
  2755. if (!*best_ist)
  2756. for (i = 0; i < graph->nb_outputs; i++)
  2757. graph->outputs[i]->ost->unavailable = 1;
  2758. return 0;
  2759. }
  2760. /**
  2761. * Run a single step of transcoding.
  2762. *
  2763. * @return 0 for success, <0 for error
  2764. */
  2765. static int transcode_step(void)
  2766. {
  2767. OutputStream *ost;
  2768. InputStream *ist;
  2769. int ret;
  2770. ost = choose_output();
  2771. if (!ost) {
  2772. if (got_eagain()) {
  2773. reset_eagain();
  2774. av_usleep(10000);
  2775. return 0;
  2776. }
  2777. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
  2778. return AVERROR_EOF;
  2779. }
  2780. if (ost->filter) {
  2781. if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
  2782. return ret;
  2783. if (!ist)
  2784. return 0;
  2785. } else {
  2786. av_assert0(ost->source_index >= 0);
  2787. ist = input_streams[ost->source_index];
  2788. }
  2789. ret = process_input(ist->file_index);
  2790. if (ret == AVERROR(EAGAIN)) {
  2791. if (input_files[ist->file_index]->eagain)
  2792. ost->unavailable = 1;
  2793. return 0;
  2794. }
  2795. if (ret < 0)
  2796. return ret == AVERROR_EOF ? 0 : ret;
  2797. return reap_filters();
  2798. }
  2799. /*
  2800. * The following code is the main loop of the file converter
  2801. */
  2802. static int transcode(void)
  2803. {
  2804. int ret, i;
  2805. AVFormatContext *os;
  2806. OutputStream *ost;
  2807. InputStream *ist;
  2808. int64_t timer_start;
  2809. ret = transcode_init();
  2810. if (ret < 0)
  2811. goto fail;
  2812. if (stdin_interaction) {
  2813. av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
  2814. }
  2815. timer_start = av_gettime();
  2816. #if HAVE_PTHREADS
  2817. if ((ret = init_input_threads()) < 0)
  2818. goto fail;
  2819. #endif
  2820. while (!received_sigterm) {
  2821. int64_t cur_time= av_gettime();
  2822. /* if 'q' pressed, exits */
  2823. if (stdin_interaction)
  2824. if (check_keyboard_interaction(cur_time) < 0)
  2825. break;
  2826. /* check if there's any stream where output is still needed */
  2827. if (!need_output()) {
  2828. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  2829. break;
  2830. }
  2831. ret = transcode_step();
  2832. if (ret < 0) {
  2833. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  2834. continue;
  2835. av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
  2836. break;
  2837. }
  2838. /* dump report by using the output first video and audio streams */
  2839. print_report(0, timer_start, cur_time);
  2840. }
  2841. #if HAVE_PTHREADS
  2842. free_input_threads();
  2843. #endif
  2844. /* at the end of stream, we must flush the decoder buffers */
  2845. for (i = 0; i < nb_input_streams; i++) {
  2846. ist = input_streams[i];
  2847. if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
  2848. output_packet(ist, NULL);
  2849. }
  2850. }
  2851. flush_encoders();
  2852. term_exit();
  2853. /* write the trailer if needed and close file */
  2854. for (i = 0; i < nb_output_files; i++) {
  2855. os = output_files[i]->ctx;
  2856. av_write_trailer(os);
  2857. }
  2858. /* dump report by using the first video and audio streams */
  2859. print_report(1, timer_start, av_gettime());
  2860. /* close each encoder */
  2861. for (i = 0; i < nb_output_streams; i++) {
  2862. ost = output_streams[i];
  2863. if (ost->encoding_needed) {
  2864. av_freep(&ost->st->codec->stats_in);
  2865. avcodec_close(ost->st->codec);
  2866. }
  2867. }
  2868. /* close each decoder */
  2869. for (i = 0; i < nb_input_streams; i++) {
  2870. ist = input_streams[i];
  2871. if (ist->decoding_needed) {
  2872. avcodec_close(ist->st->codec);
  2873. }
  2874. }
  2875. /* finished ! */
  2876. ret = 0;
  2877. fail:
  2878. #if HAVE_PTHREADS
  2879. free_input_threads();
  2880. #endif
  2881. if (output_streams) {
  2882. for (i = 0; i < nb_output_streams; i++) {
  2883. ost = output_streams[i];
  2884. if (ost) {
  2885. if (ost->stream_copy)
  2886. av_freep(&ost->st->codec->extradata);
  2887. if (ost->logfile) {
  2888. fclose(ost->logfile);
  2889. ost->logfile = NULL;
  2890. }
  2891. av_freep(&ost->st->codec->subtitle_header);
  2892. av_freep(&ost->forced_kf_pts);
  2893. av_freep(&ost->apad);
  2894. av_dict_free(&ost->opts);
  2895. av_dict_free(&ost->swr_opts);
  2896. av_dict_free(&ost->resample_opts);
  2897. }
  2898. }
  2899. }
  2900. return ret;
  2901. }
  2902. static int64_t getutime(void)
  2903. {
  2904. #if HAVE_GETRUSAGE
  2905. struct rusage rusage;
  2906. getrusage(RUSAGE_SELF, &rusage);
  2907. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  2908. #elif HAVE_GETPROCESSTIMES
  2909. HANDLE proc;
  2910. FILETIME c, e, k, u;
  2911. proc = GetCurrentProcess();
  2912. GetProcessTimes(proc, &c, &e, &k, &u);
  2913. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  2914. #else
  2915. return av_gettime();
  2916. #endif
  2917. }
  2918. static int64_t getmaxrss(void)
  2919. {
  2920. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  2921. struct rusage rusage;
  2922. getrusage(RUSAGE_SELF, &rusage);
  2923. return (int64_t)rusage.ru_maxrss * 1024;
  2924. #elif HAVE_GETPROCESSMEMORYINFO
  2925. HANDLE proc;
  2926. PROCESS_MEMORY_COUNTERS memcounters;
  2927. proc = GetCurrentProcess();
  2928. memcounters.cb = sizeof(memcounters);
  2929. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  2930. return memcounters.PeakPagefileUsage;
  2931. #else
  2932. return 0;
  2933. #endif
  2934. }
  2935. static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
  2936. {
  2937. }
  2938. int main(int argc, char **argv)
  2939. {
  2940. int ret;
  2941. int64_t ti;
  2942. register_exit(ffmpeg_cleanup);
  2943. setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
  2944. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  2945. parse_loglevel(argc, argv, options);
  2946. if(argc>1 && !strcmp(argv[1], "-d")){
  2947. run_as_daemon=1;
  2948. av_log_set_callback(log_callback_null);
  2949. argc--;
  2950. argv++;
  2951. }
  2952. avcodec_register_all();
  2953. #if CONFIG_AVDEVICE
  2954. avdevice_register_all();
  2955. #endif
  2956. avfilter_register_all();
  2957. av_register_all();
  2958. avformat_network_init();
  2959. show_banner(argc, argv, options);
  2960. term_init();
  2961. /* parse options and open all input/output files */
  2962. ret = ffmpeg_parse_options(argc, argv);
  2963. if (ret < 0)
  2964. exit_program(1);
  2965. if (nb_output_files <= 0 && nb_input_files == 0) {
  2966. show_usage();
  2967. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  2968. exit_program(1);
  2969. }
  2970. /* file converter / grab */
  2971. if (nb_output_files <= 0) {
  2972. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
  2973. exit_program(1);
  2974. }
  2975. // if (nb_input_files == 0) {
  2976. // av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
  2977. // exit_program(1);
  2978. // }
  2979. current_time = ti = getutime();
  2980. if (transcode() < 0)
  2981. exit_program(1);
  2982. ti = getutime() - ti;
  2983. if (do_benchmark) {
  2984. printf("bench: utime=%0.3fs\n", ti / 1000000.0);
  2985. }
  2986. av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
  2987. decode_error_stat[0], decode_error_stat[1]);
  2988. if (2*decode_error_stat[0] < decode_error_stat[1])
  2989. exit_program(254);
  2990. exit_program(received_nb_signals ? 255 : 0);
  2991. return 0;
  2992. }