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.

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