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.

3348 lines
117KB

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