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.

3369 lines
118KB

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