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.

3784 lines
134KB

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