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.

3171 lines
109KB

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