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.

3817 lines
134KB

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