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.

3816 lines
134KB

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