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.

3375 lines
119KB

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