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.

3371 lines
117KB

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