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.

3927 lines
139KB

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