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.

3397 lines
119KB

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