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.

3152 lines
108KB

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