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.

3381 lines
119KB

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