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.

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