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.

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