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.

3851 lines
136KB

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