You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3370 lines
118KB

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