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.

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