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.

3370 lines
118KB

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