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.

3772 lines
134KB

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