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.

3955 lines
140KB

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