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.

3344 lines
117KB

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