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.

3162 lines
108KB

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