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.

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