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.

3775 lines
134KB

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