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.

3387 lines
119KB

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