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.

3459 lines
122KB

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