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.

3770 lines
133KB

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