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.

3356 lines
118KB

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