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.

3367 lines
117KB

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