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.

3391 lines
119KB

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