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.

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