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.

3471 lines
123KB

  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. if ( ist
  720. && format_video_sync == VSYNC_CFR
  721. && input_files[ist->file_index]->ctx->nb_streams == 1
  722. && input_files[ist->file_index]->input_ts_offset == 0) {
  723. format_video_sync = VSYNC_VSCFR;
  724. }
  725. }
  726. switch (format_video_sync) {
  727. case VSYNC_VSCFR:
  728. if (ost->frame_number == 0 && delta - duration >= 0.5) {
  729. av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta - duration));
  730. delta = duration;
  731. ost->sync_opts = lrint(sync_ipts);
  732. }
  733. case VSYNC_CFR:
  734. // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
  735. if (delta < -1.1)
  736. nb_frames = 0;
  737. else if (delta > 1.1)
  738. nb_frames = lrintf(delta);
  739. break;
  740. case VSYNC_VFR:
  741. if (delta <= -0.6)
  742. nb_frames = 0;
  743. else if (delta > 0.6)
  744. ost->sync_opts = lrint(sync_ipts);
  745. break;
  746. case VSYNC_DROP:
  747. case VSYNC_PASSTHROUGH:
  748. ost->sync_opts = lrint(sync_ipts);
  749. break;
  750. default:
  751. av_assert0(0);
  752. }
  753. nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
  754. if (nb_frames == 0) {
  755. nb_frames_drop++;
  756. av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
  757. return;
  758. } else if (nb_frames > 1) {
  759. if (nb_frames > dts_error_threshold * 30) {
  760. av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
  761. nb_frames_drop++;
  762. return;
  763. }
  764. nb_frames_dup += nb_frames - 1;
  765. av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
  766. }
  767. /* duplicates frame if needed */
  768. for (i = 0; i < nb_frames; i++) {
  769. av_init_packet(&pkt);
  770. pkt.data = NULL;
  771. pkt.size = 0;
  772. in_picture->pts = ost->sync_opts;
  773. #if 1
  774. if (!check_recording_time(ost))
  775. #else
  776. if (ost->frame_number >= ost->max_frames)
  777. #endif
  778. return;
  779. if (s->oformat->flags & AVFMT_RAWPICTURE &&
  780. enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
  781. /* raw pictures are written as AVPicture structure to
  782. avoid any copies. We support temporarily the older
  783. method. */
  784. enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
  785. enc->coded_frame->top_field_first = in_picture->top_field_first;
  786. if (enc->coded_frame->interlaced_frame)
  787. enc->field_order = enc->coded_frame->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
  788. else
  789. enc->field_order = AV_FIELD_PROGRESSIVE;
  790. pkt.data = (uint8_t *)in_picture;
  791. pkt.size = sizeof(AVPicture);
  792. pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
  793. pkt.flags |= AV_PKT_FLAG_KEY;
  794. video_size += pkt.size;
  795. write_frame(s, &pkt, ost);
  796. } else {
  797. int got_packet, forced_keyframe = 0;
  798. double pts_time;
  799. if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME) &&
  800. ost->top_field_first >= 0)
  801. in_picture->top_field_first = !!ost->top_field_first;
  802. if (in_picture->interlaced_frame) {
  803. if (enc->codec->id == AV_CODEC_ID_MJPEG)
  804. enc->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
  805. else
  806. enc->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
  807. } else
  808. enc->field_order = AV_FIELD_PROGRESSIVE;
  809. in_picture->quality = ost->st->codec->global_quality;
  810. if (!enc->me_threshold)
  811. in_picture->pict_type = 0;
  812. pts_time = in_picture->pts != AV_NOPTS_VALUE ?
  813. in_picture->pts * av_q2d(enc->time_base) : NAN;
  814. if (ost->forced_kf_index < ost->forced_kf_count &&
  815. in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
  816. ost->forced_kf_index++;
  817. forced_keyframe = 1;
  818. } else if (ost->forced_keyframes_pexpr) {
  819. double res;
  820. ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
  821. res = av_expr_eval(ost->forced_keyframes_pexpr,
  822. ost->forced_keyframes_expr_const_values, NULL);
  823. av_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
  824. ost->forced_keyframes_expr_const_values[FKF_N],
  825. ost->forced_keyframes_expr_const_values[FKF_N_FORCED],
  826. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],
  827. ost->forced_keyframes_expr_const_values[FKF_T],
  828. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],
  829. res);
  830. if (res) {
  831. forced_keyframe = 1;
  832. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =
  833. ost->forced_keyframes_expr_const_values[FKF_N];
  834. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =
  835. ost->forced_keyframes_expr_const_values[FKF_T];
  836. ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;
  837. }
  838. ost->forced_keyframes_expr_const_values[FKF_N] += 1;
  839. }
  840. if (forced_keyframe) {
  841. in_picture->pict_type = AV_PICTURE_TYPE_I;
  842. av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
  843. }
  844. update_benchmark(NULL);
  845. ret = avcodec_encode_video2(enc, &pkt, in_picture, &got_packet);
  846. update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
  847. if (ret < 0) {
  848. av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
  849. exit_program(1);
  850. }
  851. if (got_packet) {
  852. if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
  853. pkt.pts = ost->sync_opts;
  854. if (pkt.pts != AV_NOPTS_VALUE)
  855. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  856. if (pkt.dts != AV_NOPTS_VALUE)
  857. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  858. if (debug_ts) {
  859. av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
  860. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
  861. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
  862. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
  863. }
  864. frame_size = pkt.size;
  865. video_size += pkt.size;
  866. write_frame(s, &pkt, ost);
  867. av_free_packet(&pkt);
  868. /* if two pass, output log */
  869. if (ost->logfile && enc->stats_out) {
  870. fprintf(ost->logfile, "%s", enc->stats_out);
  871. }
  872. }
  873. }
  874. ost->sync_opts++;
  875. /*
  876. * For video, number of frames in == number of packets out.
  877. * But there may be reordering, so we can't throw away frames on encoder
  878. * flush, we need to limit them here, before they go into encoder.
  879. */
  880. ost->frame_number++;
  881. if (vstats_filename && frame_size)
  882. do_video_stats(ost, frame_size);
  883. }
  884. }
  885. static double psnr(double d)
  886. {
  887. return -10.0 * log(d) / log(10.0);
  888. }
  889. static void do_video_stats(OutputStream *ost, int frame_size)
  890. {
  891. AVCodecContext *enc;
  892. int frame_number;
  893. double ti1, bitrate, avg_bitrate;
  894. /* this is executed just the first time do_video_stats is called */
  895. if (!vstats_file) {
  896. vstats_file = fopen(vstats_filename, "w");
  897. if (!vstats_file) {
  898. perror("fopen");
  899. exit_program(1);
  900. }
  901. }
  902. enc = ost->st->codec;
  903. if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  904. frame_number = ost->st->nb_frames;
  905. fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
  906. if (enc->flags&CODEC_FLAG_PSNR)
  907. fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
  908. fprintf(vstats_file,"f_size= %6d ", frame_size);
  909. /* compute pts value */
  910. ti1 = ost->st->pts.val * av_q2d(enc->time_base);
  911. if (ti1 < 0.01)
  912. ti1 = 0.01;
  913. bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
  914. avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
  915. fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
  916. (double)video_size / 1024, ti1, bitrate, avg_bitrate);
  917. fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
  918. }
  919. }
  920. /**
  921. * Get and encode new output from any of the filtergraphs, without causing
  922. * activity.
  923. *
  924. * @return 0 for success, <0 for severe errors
  925. */
  926. static int reap_filters(void)
  927. {
  928. AVFrame *filtered_frame = NULL;
  929. int i;
  930. int64_t frame_pts;
  931. /* Reap all buffers present in the buffer sinks */
  932. for (i = 0; i < nb_output_streams; i++) {
  933. OutputStream *ost = output_streams[i];
  934. OutputFile *of = output_files[ost->file_index];
  935. int ret = 0;
  936. if (!ost->filter)
  937. continue;
  938. if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
  939. return AVERROR(ENOMEM);
  940. } else
  941. avcodec_get_frame_defaults(ost->filtered_frame);
  942. filtered_frame = ost->filtered_frame;
  943. while (1) {
  944. ret = av_buffersink_get_frame_flags(ost->filter->filter, filtered_frame,
  945. AV_BUFFERSINK_FLAG_NO_REQUEST);
  946. if (ret < 0) {
  947. if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
  948. av_log(NULL, AV_LOG_WARNING,
  949. "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));
  950. }
  951. break;
  952. }
  953. frame_pts = AV_NOPTS_VALUE;
  954. if (filtered_frame->pts != AV_NOPTS_VALUE) {
  955. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  956. filtered_frame->pts = frame_pts = av_rescale_q(filtered_frame->pts,
  957. ost->filter->filter->inputs[0]->time_base,
  958. ost->st->codec->time_base) -
  959. av_rescale_q(start_time,
  960. AV_TIME_BASE_Q,
  961. ost->st->codec->time_base);
  962. }
  963. //if (ost->source_index >= 0)
  964. // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
  965. switch (ost->filter->filter->inputs[0]->type) {
  966. case AVMEDIA_TYPE_VIDEO:
  967. filtered_frame->pts = frame_pts;
  968. if (!ost->frame_aspect_ratio.num)
  969. ost->st->codec->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
  970. do_video_out(of->ctx, ost, filtered_frame);
  971. break;
  972. case AVMEDIA_TYPE_AUDIO:
  973. filtered_frame->pts = frame_pts;
  974. if (!(ost->st->codec->codec->capabilities & CODEC_CAP_PARAM_CHANGE) &&
  975. ost->st->codec->channels != av_frame_get_channels(filtered_frame)) {
  976. av_log(NULL, AV_LOG_ERROR,
  977. "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
  978. break;
  979. }
  980. do_audio_out(of->ctx, ost, filtered_frame);
  981. break;
  982. default:
  983. // TODO support subtitle filters
  984. av_assert0(0);
  985. }
  986. av_frame_unref(filtered_frame);
  987. }
  988. }
  989. return 0;
  990. }
  991. static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
  992. {
  993. char buf[1024];
  994. AVBPrint buf_script;
  995. OutputStream *ost;
  996. AVFormatContext *oc;
  997. int64_t total_size;
  998. AVCodecContext *enc;
  999. int frame_number, vid, i;
  1000. double bitrate;
  1001. int64_t pts = INT64_MIN;
  1002. static int64_t last_time = -1;
  1003. static int qp_histogram[52];
  1004. int hours, mins, secs, us;
  1005. if (!print_stats && !is_last_report && !progress_avio)
  1006. return;
  1007. if (!is_last_report) {
  1008. if (last_time == -1) {
  1009. last_time = cur_time;
  1010. return;
  1011. }
  1012. if ((cur_time - last_time) < 500000)
  1013. return;
  1014. last_time = cur_time;
  1015. }
  1016. oc = output_files[0]->ctx;
  1017. total_size = avio_size(oc->pb);
  1018. if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
  1019. total_size = avio_tell(oc->pb);
  1020. buf[0] = '\0';
  1021. vid = 0;
  1022. av_bprint_init(&buf_script, 0, 1);
  1023. for (i = 0; i < nb_output_streams; i++) {
  1024. float q = -1;
  1025. ost = output_streams[i];
  1026. enc = ost->st->codec;
  1027. if (!ost->stream_copy && enc->coded_frame)
  1028. q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
  1029. if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1030. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
  1031. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  1032. ost->file_index, ost->index, q);
  1033. }
  1034. if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1035. float fps, t = (cur_time-timer_start) / 1000000.0;
  1036. frame_number = ost->frame_number;
  1037. fps = t > 1 ? frame_number / t : 0;
  1038. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
  1039. frame_number, fps < 9.95, fps, q);
  1040. av_bprintf(&buf_script, "frame=%d\n", frame_number);
  1041. av_bprintf(&buf_script, "fps=%.1f\n", fps);
  1042. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  1043. ost->file_index, ost->index, q);
  1044. if (is_last_report)
  1045. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
  1046. if (qp_hist) {
  1047. int j;
  1048. int qp = lrintf(q);
  1049. if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
  1050. qp_histogram[qp]++;
  1051. for (j = 0; j < 32; j++)
  1052. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
  1053. }
  1054. if ((enc->flags&CODEC_FLAG_PSNR) && (enc->coded_frame || is_last_report)) {
  1055. int j;
  1056. double error, error_sum = 0;
  1057. double scale, scale_sum = 0;
  1058. double p;
  1059. char type[3] = { 'Y','U','V' };
  1060. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
  1061. for (j = 0; j < 3; j++) {
  1062. if (is_last_report) {
  1063. error = enc->error[j];
  1064. scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
  1065. } else {
  1066. error = enc->coded_frame->error[j];
  1067. scale = enc->width * enc->height * 255.0 * 255.0;
  1068. }
  1069. if (j)
  1070. scale /= 4;
  1071. error_sum += error;
  1072. scale_sum += scale;
  1073. p = psnr(error / scale);
  1074. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
  1075. av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
  1076. ost->file_index, ost->index, type[j] | 32, p);
  1077. }
  1078. p = psnr(error_sum / scale_sum);
  1079. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
  1080. av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
  1081. ost->file_index, ost->index, p);
  1082. }
  1083. vid = 1;
  1084. }
  1085. /* compute min output value */
  1086. if ((is_last_report || !ost->finished) && ost->st->pts.val != AV_NOPTS_VALUE)
  1087. pts = FFMAX(pts, av_rescale_q(ost->st->pts.val,
  1088. ost->st->time_base, AV_TIME_BASE_Q));
  1089. }
  1090. secs = pts / AV_TIME_BASE;
  1091. us = pts % AV_TIME_BASE;
  1092. mins = secs / 60;
  1093. secs %= 60;
  1094. hours = mins / 60;
  1095. mins %= 60;
  1096. bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
  1097. if (total_size < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1098. "size=N/A time=");
  1099. else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1100. "size=%8.0fkB time=", total_size / 1024.0);
  1101. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1102. "%02d:%02d:%02d.%02d ", hours, mins, secs,
  1103. (100 * us) / AV_TIME_BASE);
  1104. if (bitrate < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1105. "bitrate=N/A");
  1106. else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1107. "bitrate=%6.1fkbits/s", bitrate);
  1108. if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
  1109. else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
  1110. av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
  1111. av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
  1112. hours, mins, secs, us);
  1113. if (nb_frames_dup || nb_frames_drop)
  1114. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
  1115. nb_frames_dup, nb_frames_drop);
  1116. av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
  1117. av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
  1118. if (print_stats || is_last_report) {
  1119. if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
  1120. fprintf(stderr, "%s \r", buf);
  1121. } else
  1122. av_log(NULL, AV_LOG_INFO, "%s \r", buf);
  1123. fflush(stderr);
  1124. }
  1125. if (progress_avio) {
  1126. av_bprintf(&buf_script, "progress=%s\n",
  1127. is_last_report ? "end" : "continue");
  1128. avio_write(progress_avio, buf_script.str,
  1129. FFMIN(buf_script.len, buf_script.size - 1));
  1130. avio_flush(progress_avio);
  1131. av_bprint_finalize(&buf_script, NULL);
  1132. if (is_last_report) {
  1133. avio_close(progress_avio);
  1134. progress_avio = NULL;
  1135. }
  1136. }
  1137. if (is_last_report) {
  1138. int64_t raw= audio_size + video_size + subtitle_size + extra_size;
  1139. av_log(NULL, AV_LOG_INFO, "\n");
  1140. av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0f global headers:%1.0fkB muxing overhead %f%%\n",
  1141. video_size / 1024.0,
  1142. audio_size / 1024.0,
  1143. subtitle_size / 1024.0,
  1144. extra_size / 1024.0,
  1145. 100.0 * (total_size - raw) / raw
  1146. );
  1147. if(video_size + audio_size + subtitle_size + extra_size == 0){
  1148. av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
  1149. }
  1150. }
  1151. }
  1152. static void flush_encoders(void)
  1153. {
  1154. int i, ret;
  1155. for (i = 0; i < nb_output_streams; i++) {
  1156. OutputStream *ost = output_streams[i];
  1157. AVCodecContext *enc = ost->st->codec;
  1158. AVFormatContext *os = output_files[ost->file_index]->ctx;
  1159. int stop_encoding = 0;
  1160. if (!ost->encoding_needed)
  1161. continue;
  1162. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
  1163. continue;
  1164. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
  1165. continue;
  1166. for (;;) {
  1167. int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
  1168. const char *desc;
  1169. int64_t *size;
  1170. switch (ost->st->codec->codec_type) {
  1171. case AVMEDIA_TYPE_AUDIO:
  1172. encode = avcodec_encode_audio2;
  1173. desc = "Audio";
  1174. size = &audio_size;
  1175. break;
  1176. case AVMEDIA_TYPE_VIDEO:
  1177. encode = avcodec_encode_video2;
  1178. desc = "Video";
  1179. size = &video_size;
  1180. break;
  1181. default:
  1182. stop_encoding = 1;
  1183. }
  1184. if (encode) {
  1185. AVPacket pkt;
  1186. int got_packet;
  1187. av_init_packet(&pkt);
  1188. pkt.data = NULL;
  1189. pkt.size = 0;
  1190. update_benchmark(NULL);
  1191. ret = encode(enc, &pkt, NULL, &got_packet);
  1192. update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
  1193. if (ret < 0) {
  1194. av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
  1195. exit_program(1);
  1196. }
  1197. *size += pkt.size;
  1198. if (ost->logfile && enc->stats_out) {
  1199. fprintf(ost->logfile, "%s", enc->stats_out);
  1200. }
  1201. if (!got_packet) {
  1202. stop_encoding = 1;
  1203. break;
  1204. }
  1205. if (pkt.pts != AV_NOPTS_VALUE)
  1206. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  1207. if (pkt.dts != AV_NOPTS_VALUE)
  1208. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  1209. if (pkt.duration > 0)
  1210. pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
  1211. write_frame(os, &pkt, ost);
  1212. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
  1213. do_video_stats(ost, pkt.size);
  1214. }
  1215. }
  1216. if (stop_encoding)
  1217. break;
  1218. }
  1219. }
  1220. }
  1221. /*
  1222. * Check whether a packet from ist should be written into ost at this time
  1223. */
  1224. static int check_output_constraints(InputStream *ist, OutputStream *ost)
  1225. {
  1226. OutputFile *of = output_files[ost->file_index];
  1227. int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
  1228. if (ost->source_index != ist_index)
  1229. return 0;
  1230. if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
  1231. return 0;
  1232. return 1;
  1233. }
  1234. static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
  1235. {
  1236. OutputFile *of = output_files[ost->file_index];
  1237. InputFile *f = input_files [ist->file_index];
  1238. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  1239. int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
  1240. int64_t ist_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ist->st->time_base);
  1241. AVPicture pict;
  1242. AVPacket opkt;
  1243. av_init_packet(&opkt);
  1244. if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
  1245. !ost->copy_initial_nonkeyframes)
  1246. return;
  1247. if (pkt->pts == AV_NOPTS_VALUE) {
  1248. if (!ost->frame_number && ist->pts < start_time &&
  1249. !ost->copy_prior_start)
  1250. return;
  1251. } else {
  1252. if (!ost->frame_number && pkt->pts < ist_tb_start_time &&
  1253. !ost->copy_prior_start)
  1254. return;
  1255. }
  1256. if (of->recording_time != INT64_MAX &&
  1257. ist->pts >= of->recording_time + start_time) {
  1258. close_output_stream(ost);
  1259. return;
  1260. }
  1261. if (f->recording_time != INT64_MAX) {
  1262. start_time = f->ctx->start_time;
  1263. if (f->start_time != AV_NOPTS_VALUE)
  1264. start_time += f->start_time;
  1265. if (ist->pts >= f->recording_time + start_time) {
  1266. close_output_stream(ost);
  1267. return;
  1268. }
  1269. }
  1270. /* force the input stream PTS */
  1271. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  1272. audio_size += pkt->size;
  1273. else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1274. video_size += pkt->size;
  1275. ost->sync_opts++;
  1276. } else if (ost->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  1277. subtitle_size += pkt->size;
  1278. }
  1279. if (pkt->pts != AV_NOPTS_VALUE)
  1280. opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
  1281. else
  1282. opkt.pts = AV_NOPTS_VALUE;
  1283. if (pkt->dts == AV_NOPTS_VALUE)
  1284. opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
  1285. else
  1286. opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
  1287. opkt.dts -= ost_tb_start_time;
  1288. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
  1289. int duration = av_get_audio_frame_duration(ist->st->codec, pkt->size);
  1290. if(!duration)
  1291. duration = ist->st->codec->frame_size;
  1292. opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
  1293. (AVRational){1, ist->st->codec->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
  1294. ost->st->time_base) - ost_tb_start_time;
  1295. }
  1296. opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
  1297. opkt.flags = pkt->flags;
  1298. // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
  1299. if ( ost->st->codec->codec_id != AV_CODEC_ID_H264
  1300. && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
  1301. && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
  1302. && ost->st->codec->codec_id != AV_CODEC_ID_VC1
  1303. ) {
  1304. if (av_parser_change(ost->parser, ost->st->codec,
  1305. &opkt.data, &opkt.size,
  1306. pkt->data, pkt->size,
  1307. pkt->flags & AV_PKT_FLAG_KEY)) {
  1308. opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
  1309. if (!opkt.buf)
  1310. exit_program(1);
  1311. }
  1312. } else {
  1313. opkt.data = pkt->data;
  1314. opkt.size = pkt->size;
  1315. }
  1316. av_copy_packet_side_data(&opkt, pkt);
  1317. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
  1318. /* store AVPicture in AVPacket, as expected by the output format */
  1319. avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
  1320. opkt.data = (uint8_t *)&pict;
  1321. opkt.size = sizeof(AVPicture);
  1322. opkt.flags |= AV_PKT_FLAG_KEY;
  1323. }
  1324. write_frame(of->ctx, &opkt, ost);
  1325. ost->st->codec->frame_number++;
  1326. }
  1327. int guess_input_channel_layout(InputStream *ist)
  1328. {
  1329. AVCodecContext *dec = ist->st->codec;
  1330. if (!dec->channel_layout) {
  1331. char layout_name[256];
  1332. if (dec->channels > ist->guess_layout_max)
  1333. return 0;
  1334. dec->channel_layout = av_get_default_channel_layout(dec->channels);
  1335. if (!dec->channel_layout)
  1336. return 0;
  1337. av_get_channel_layout_string(layout_name, sizeof(layout_name),
  1338. dec->channels, dec->channel_layout);
  1339. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
  1340. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
  1341. }
  1342. return 1;
  1343. }
  1344. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
  1345. {
  1346. AVFrame *decoded_frame, *f;
  1347. AVCodecContext *avctx = ist->st->codec;
  1348. int i, ret, err = 0, resample_changed;
  1349. AVRational decoded_frame_tb;
  1350. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  1351. return AVERROR(ENOMEM);
  1352. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  1353. return AVERROR(ENOMEM);
  1354. decoded_frame = ist->decoded_frame;
  1355. update_benchmark(NULL);
  1356. ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
  1357. update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
  1358. if (ret >= 0 && avctx->sample_rate <= 0) {
  1359. av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
  1360. ret = AVERROR_INVALIDDATA;
  1361. }
  1362. if (*got_output || ret<0 || pkt->size)
  1363. decode_error_stat[ret<0] ++;
  1364. if (!*got_output || ret < 0) {
  1365. if (!pkt->size) {
  1366. for (i = 0; i < ist->nb_filters; i++)
  1367. #if 1
  1368. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  1369. #else
  1370. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  1371. #endif
  1372. }
  1373. return ret;
  1374. }
  1375. #if 1
  1376. /* increment next_dts to use for the case where the input stream does not
  1377. have timestamps or there are multiple frames in the packet */
  1378. ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1379. avctx->sample_rate;
  1380. ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1381. avctx->sample_rate;
  1382. #endif
  1383. resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
  1384. ist->resample_channels != avctx->channels ||
  1385. ist->resample_channel_layout != decoded_frame->channel_layout ||
  1386. ist->resample_sample_rate != decoded_frame->sample_rate;
  1387. if (resample_changed) {
  1388. char layout1[64], layout2[64];
  1389. if (!guess_input_channel_layout(ist)) {
  1390. av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
  1391. "layout for Input Stream #%d.%d\n", ist->file_index,
  1392. ist->st->index);
  1393. exit_program(1);
  1394. }
  1395. decoded_frame->channel_layout = avctx->channel_layout;
  1396. av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
  1397. ist->resample_channel_layout);
  1398. av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
  1399. decoded_frame->channel_layout);
  1400. av_log(NULL, AV_LOG_INFO,
  1401. "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",
  1402. ist->file_index, ist->st->index,
  1403. ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
  1404. ist->resample_channels, layout1,
  1405. decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
  1406. avctx->channels, layout2);
  1407. ist->resample_sample_fmt = decoded_frame->format;
  1408. ist->resample_sample_rate = decoded_frame->sample_rate;
  1409. ist->resample_channel_layout = decoded_frame->channel_layout;
  1410. ist->resample_channels = avctx->channels;
  1411. for (i = 0; i < nb_filtergraphs; i++)
  1412. if (ist_in_filtergraph(filtergraphs[i], ist)) {
  1413. FilterGraph *fg = filtergraphs[i];
  1414. int j;
  1415. if (configure_filtergraph(fg) < 0) {
  1416. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1417. exit_program(1);
  1418. }
  1419. for (j = 0; j < fg->nb_outputs; j++) {
  1420. OutputStream *ost = fg->outputs[j]->ost;
  1421. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  1422. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  1423. av_buffersink_set_frame_size(ost->filter->filter,
  1424. ost->st->codec->frame_size);
  1425. }
  1426. }
  1427. }
  1428. /* if the decoder provides a pts, use it instead of the last packet pts.
  1429. the decoder could be delaying output by a packet or more. */
  1430. if (decoded_frame->pts != AV_NOPTS_VALUE) {
  1431. ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
  1432. decoded_frame_tb = avctx->time_base;
  1433. } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
  1434. decoded_frame->pts = decoded_frame->pkt_pts;
  1435. pkt->pts = AV_NOPTS_VALUE;
  1436. decoded_frame_tb = ist->st->time_base;
  1437. } else if (pkt->pts != AV_NOPTS_VALUE) {
  1438. decoded_frame->pts = pkt->pts;
  1439. pkt->pts = AV_NOPTS_VALUE;
  1440. decoded_frame_tb = ist->st->time_base;
  1441. }else {
  1442. decoded_frame->pts = ist->dts;
  1443. decoded_frame_tb = AV_TIME_BASE_Q;
  1444. }
  1445. if (decoded_frame->pts != AV_NOPTS_VALUE)
  1446. decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
  1447. (AVRational){1, ist->st->codec->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
  1448. (AVRational){1, ist->st->codec->sample_rate});
  1449. for (i = 0; i < ist->nb_filters; i++) {
  1450. if (i < ist->nb_filters - 1) {
  1451. f = ist->filter_frame;
  1452. err = av_frame_ref(f, decoded_frame);
  1453. if (err < 0)
  1454. break;
  1455. } else
  1456. f = decoded_frame;
  1457. err = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f,
  1458. AV_BUFFERSRC_FLAG_PUSH);
  1459. if (err == AVERROR_EOF)
  1460. err = 0; /* ignore */
  1461. if (err < 0)
  1462. break;
  1463. }
  1464. decoded_frame->pts = AV_NOPTS_VALUE;
  1465. av_frame_unref(ist->filter_frame);
  1466. av_frame_unref(decoded_frame);
  1467. return err < 0 ? err : ret;
  1468. }
  1469. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
  1470. {
  1471. AVFrame *decoded_frame, *f;
  1472. int i, ret = 0, err = 0, resample_changed;
  1473. int64_t best_effort_timestamp;
  1474. AVRational *frame_sample_aspect;
  1475. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  1476. return AVERROR(ENOMEM);
  1477. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  1478. return AVERROR(ENOMEM);
  1479. decoded_frame = ist->decoded_frame;
  1480. pkt->dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
  1481. update_benchmark(NULL);
  1482. ret = avcodec_decode_video2(ist->st->codec,
  1483. decoded_frame, got_output, pkt);
  1484. update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
  1485. if (*got_output || ret<0 || pkt->size)
  1486. decode_error_stat[ret<0] ++;
  1487. if (!*got_output || ret < 0) {
  1488. if (!pkt->size) {
  1489. for (i = 0; i < ist->nb_filters; i++)
  1490. #if 1
  1491. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  1492. #else
  1493. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  1494. #endif
  1495. }
  1496. return ret;
  1497. }
  1498. if(ist->top_field_first>=0)
  1499. decoded_frame->top_field_first = ist->top_field_first;
  1500. best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
  1501. if(best_effort_timestamp != AV_NOPTS_VALUE)
  1502. ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
  1503. if (debug_ts) {
  1504. av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
  1505. "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d \n",
  1506. ist->st->index, av_ts2str(decoded_frame->pts),
  1507. av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
  1508. best_effort_timestamp,
  1509. av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
  1510. decoded_frame->key_frame, decoded_frame->pict_type);
  1511. }
  1512. pkt->size = 0;
  1513. if (ist->st->sample_aspect_ratio.num)
  1514. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  1515. resample_changed = ist->resample_width != decoded_frame->width ||
  1516. ist->resample_height != decoded_frame->height ||
  1517. ist->resample_pix_fmt != decoded_frame->format;
  1518. if (resample_changed) {
  1519. av_log(NULL, AV_LOG_INFO,
  1520. "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
  1521. ist->file_index, ist->st->index,
  1522. ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
  1523. decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
  1524. ist->resample_width = decoded_frame->width;
  1525. ist->resample_height = decoded_frame->height;
  1526. ist->resample_pix_fmt = decoded_frame->format;
  1527. for (i = 0; i < nb_filtergraphs; i++) {
  1528. if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
  1529. configure_filtergraph(filtergraphs[i]) < 0) {
  1530. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1531. exit_program(1);
  1532. }
  1533. }
  1534. }
  1535. frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
  1536. for (i = 0; i < ist->nb_filters; i++) {
  1537. if (!frame_sample_aspect->num)
  1538. *frame_sample_aspect = ist->st->sample_aspect_ratio;
  1539. if (i < ist->nb_filters - 1) {
  1540. f = ist->filter_frame;
  1541. err = av_frame_ref(f, decoded_frame);
  1542. if (err < 0)
  1543. break;
  1544. } else
  1545. f = decoded_frame;
  1546. ret = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f, AV_BUFFERSRC_FLAG_PUSH);
  1547. if (ret == AVERROR_EOF) {
  1548. ret = 0; /* ignore */
  1549. } else if (ret < 0) {
  1550. av_log(NULL, AV_LOG_FATAL,
  1551. "Failed to inject frame into filter network: %s\n", av_err2str(ret));
  1552. exit_program(1);
  1553. }
  1554. }
  1555. av_frame_unref(ist->filter_frame);
  1556. av_frame_unref(decoded_frame);
  1557. return err < 0 ? err : ret;
  1558. }
  1559. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
  1560. {
  1561. AVSubtitle subtitle;
  1562. int i, ret = avcodec_decode_subtitle2(ist->st->codec,
  1563. &subtitle, got_output, pkt);
  1564. if (*got_output || ret<0 || pkt->size)
  1565. decode_error_stat[ret<0] ++;
  1566. if (ret < 0 || !*got_output) {
  1567. if (!pkt->size)
  1568. sub2video_flush(ist);
  1569. return ret;
  1570. }
  1571. if (ist->fix_sub_duration) {
  1572. if (ist->prev_sub.got_output) {
  1573. int end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
  1574. 1000, AV_TIME_BASE);
  1575. if (end < ist->prev_sub.subtitle.end_display_time) {
  1576. av_log(ist->st->codec, AV_LOG_DEBUG,
  1577. "Subtitle duration reduced from %d to %d\n",
  1578. ist->prev_sub.subtitle.end_display_time, end);
  1579. ist->prev_sub.subtitle.end_display_time = end;
  1580. }
  1581. }
  1582. FFSWAP(int, *got_output, ist->prev_sub.got_output);
  1583. FFSWAP(int, ret, ist->prev_sub.ret);
  1584. FFSWAP(AVSubtitle, subtitle, ist->prev_sub.subtitle);
  1585. }
  1586. sub2video_update(ist, &subtitle);
  1587. if (!*got_output || !subtitle.num_rects)
  1588. return ret;
  1589. for (i = 0; i < nb_output_streams; i++) {
  1590. OutputStream *ost = output_streams[i];
  1591. if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
  1592. continue;
  1593. do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle);
  1594. }
  1595. avsubtitle_free(&subtitle);
  1596. return ret;
  1597. }
  1598. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  1599. static int output_packet(InputStream *ist, const AVPacket *pkt)
  1600. {
  1601. int ret = 0, i;
  1602. int got_output = 0;
  1603. AVPacket avpkt;
  1604. if (!ist->saw_first_ts) {
  1605. 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;
  1606. ist->pts = 0;
  1607. if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
  1608. ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
  1609. ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
  1610. }
  1611. ist->saw_first_ts = 1;
  1612. }
  1613. if (ist->next_dts == AV_NOPTS_VALUE)
  1614. ist->next_dts = ist->dts;
  1615. if (ist->next_pts == AV_NOPTS_VALUE)
  1616. ist->next_pts = ist->pts;
  1617. if (pkt == NULL) {
  1618. /* EOF handling */
  1619. av_init_packet(&avpkt);
  1620. avpkt.data = NULL;
  1621. avpkt.size = 0;
  1622. goto handle_eof;
  1623. } else {
  1624. avpkt = *pkt;
  1625. }
  1626. if (pkt->dts != AV_NOPTS_VALUE) {
  1627. ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1628. if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
  1629. ist->next_pts = ist->pts = ist->dts;
  1630. }
  1631. // while we have more to decode or while the decoder did output something on EOF
  1632. while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
  1633. int duration;
  1634. handle_eof:
  1635. ist->pts = ist->next_pts;
  1636. ist->dts = ist->next_dts;
  1637. if (avpkt.size && avpkt.size != pkt->size) {
  1638. av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
  1639. "Multiple frames in a packet from stream %d\n", pkt->stream_index);
  1640. ist->showed_multi_packet_warning = 1;
  1641. }
  1642. switch (ist->st->codec->codec_type) {
  1643. case AVMEDIA_TYPE_AUDIO:
  1644. ret = decode_audio (ist, &avpkt, &got_output);
  1645. break;
  1646. case AVMEDIA_TYPE_VIDEO:
  1647. ret = decode_video (ist, &avpkt, &got_output);
  1648. if (avpkt.duration) {
  1649. duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
  1650. } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
  1651. int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
  1652. duration = ((int64_t)AV_TIME_BASE *
  1653. ist->st->codec->time_base.num * ticks) /
  1654. ist->st->codec->time_base.den;
  1655. } else
  1656. duration = 0;
  1657. if(ist->dts != AV_NOPTS_VALUE && duration) {
  1658. ist->next_dts += duration;
  1659. }else
  1660. ist->next_dts = AV_NOPTS_VALUE;
  1661. if (got_output)
  1662. ist->next_pts += duration; //FIXME the duration is not correct in some cases
  1663. break;
  1664. case AVMEDIA_TYPE_SUBTITLE:
  1665. ret = transcode_subtitles(ist, &avpkt, &got_output);
  1666. break;
  1667. default:
  1668. return -1;
  1669. }
  1670. if (ret < 0)
  1671. return ret;
  1672. avpkt.dts=
  1673. avpkt.pts= AV_NOPTS_VALUE;
  1674. // touch data and size only if not EOF
  1675. if (pkt) {
  1676. if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  1677. ret = avpkt.size;
  1678. avpkt.data += ret;
  1679. avpkt.size -= ret;
  1680. }
  1681. if (!got_output) {
  1682. continue;
  1683. }
  1684. }
  1685. /* handle stream copy */
  1686. if (!ist->decoding_needed) {
  1687. ist->dts = ist->next_dts;
  1688. switch (ist->st->codec->codec_type) {
  1689. case AVMEDIA_TYPE_AUDIO:
  1690. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
  1691. ist->st->codec->sample_rate;
  1692. break;
  1693. case AVMEDIA_TYPE_VIDEO:
  1694. if (ist->framerate.num) {
  1695. // TODO: Remove work-around for c99-to-c89 issue 7
  1696. AVRational time_base_q = AV_TIME_BASE_Q;
  1697. int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
  1698. ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
  1699. } else if (pkt->duration) {
  1700. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  1701. } else if(ist->st->codec->time_base.num != 0) {
  1702. int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
  1703. ist->next_dts += ((int64_t)AV_TIME_BASE *
  1704. ist->st->codec->time_base.num * ticks) /
  1705. ist->st->codec->time_base.den;
  1706. }
  1707. break;
  1708. }
  1709. ist->pts = ist->dts;
  1710. ist->next_pts = ist->next_dts;
  1711. }
  1712. for (i = 0; pkt && i < nb_output_streams; i++) {
  1713. OutputStream *ost = output_streams[i];
  1714. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  1715. continue;
  1716. do_streamcopy(ist, ost, pkt);
  1717. }
  1718. return 0;
  1719. }
  1720. static void print_sdp(void)
  1721. {
  1722. char sdp[16384];
  1723. int i;
  1724. AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
  1725. if (!avc)
  1726. exit_program(1);
  1727. for (i = 0; i < nb_output_files; i++)
  1728. avc[i] = output_files[i]->ctx;
  1729. av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
  1730. printf("SDP:\n%s\n", sdp);
  1731. fflush(stdout);
  1732. av_freep(&avc);
  1733. }
  1734. static int init_input_stream(int ist_index, char *error, int error_len)
  1735. {
  1736. int ret;
  1737. InputStream *ist = input_streams[ist_index];
  1738. if (ist->decoding_needed) {
  1739. AVCodec *codec = ist->dec;
  1740. if (!codec) {
  1741. snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
  1742. avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
  1743. return AVERROR(EINVAL);
  1744. }
  1745. av_opt_set_int(ist->st->codec, "refcounted_frames", 1, 0);
  1746. if (!av_dict_get(ist->opts, "threads", NULL, 0))
  1747. av_dict_set(&ist->opts, "threads", "auto", 0);
  1748. if ((ret = avcodec_open2(ist->st->codec, codec, &ist->opts)) < 0) {
  1749. char errbuf[128];
  1750. if (ret == AVERROR_EXPERIMENTAL)
  1751. abort_codec_experimental(codec, 0);
  1752. av_strerror(ret, errbuf, sizeof(errbuf));
  1753. snprintf(error, error_len,
  1754. "Error while opening decoder for input stream "
  1755. "#%d:%d : %s",
  1756. ist->file_index, ist->st->index, errbuf);
  1757. return ret;
  1758. }
  1759. assert_avoptions(ist->opts);
  1760. }
  1761. ist->next_pts = AV_NOPTS_VALUE;
  1762. ist->next_dts = AV_NOPTS_VALUE;
  1763. ist->is_start = 1;
  1764. return 0;
  1765. }
  1766. static InputStream *get_input_stream(OutputStream *ost)
  1767. {
  1768. if (ost->source_index >= 0)
  1769. return input_streams[ost->source_index];
  1770. return NULL;
  1771. }
  1772. static int compare_int64(const void *a, const void *b)
  1773. {
  1774. int64_t va = *(int64_t *)a, vb = *(int64_t *)b;
  1775. return va < vb ? -1 : va > vb ? +1 : 0;
  1776. }
  1777. static void parse_forced_key_frames(char *kf, OutputStream *ost,
  1778. AVCodecContext *avctx)
  1779. {
  1780. char *p;
  1781. int n = 1, i, size, index = 0;
  1782. int64_t t, *pts;
  1783. for (p = kf; *p; p++)
  1784. if (*p == ',')
  1785. n++;
  1786. size = n;
  1787. pts = av_malloc(sizeof(*pts) * size);
  1788. if (!pts) {
  1789. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  1790. exit_program(1);
  1791. }
  1792. p = kf;
  1793. for (i = 0; i < n; i++) {
  1794. char *next = strchr(p, ',');
  1795. if (next)
  1796. *next++ = 0;
  1797. if (!memcmp(p, "chapters", 8)) {
  1798. AVFormatContext *avf = output_files[ost->file_index]->ctx;
  1799. int j;
  1800. if (avf->nb_chapters > INT_MAX - size ||
  1801. !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
  1802. sizeof(*pts)))) {
  1803. av_log(NULL, AV_LOG_FATAL,
  1804. "Could not allocate forced key frames array.\n");
  1805. exit_program(1);
  1806. }
  1807. t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
  1808. t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1809. for (j = 0; j < avf->nb_chapters; j++) {
  1810. AVChapter *c = avf->chapters[j];
  1811. av_assert1(index < size);
  1812. pts[index++] = av_rescale_q(c->start, c->time_base,
  1813. avctx->time_base) + t;
  1814. }
  1815. } else {
  1816. t = parse_time_or_die("force_key_frames", p, 1);
  1817. av_assert1(index < size);
  1818. pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1819. }
  1820. p = next;
  1821. }
  1822. av_assert0(index == size);
  1823. qsort(pts, size, sizeof(*pts), compare_int64);
  1824. ost->forced_kf_count = size;
  1825. ost->forced_kf_pts = pts;
  1826. }
  1827. static void report_new_stream(int input_index, AVPacket *pkt)
  1828. {
  1829. InputFile *file = input_files[input_index];
  1830. AVStream *st = file->ctx->streams[pkt->stream_index];
  1831. if (pkt->stream_index < file->nb_streams_warn)
  1832. return;
  1833. av_log(file->ctx, AV_LOG_WARNING,
  1834. "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
  1835. av_get_media_type_string(st->codec->codec_type),
  1836. input_index, pkt->stream_index,
  1837. pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
  1838. file->nb_streams_warn = pkt->stream_index + 1;
  1839. }
  1840. static int transcode_init(void)
  1841. {
  1842. int ret = 0, i, j, k;
  1843. AVFormatContext *oc;
  1844. AVCodecContext *codec;
  1845. OutputStream *ost;
  1846. InputStream *ist;
  1847. char error[1024];
  1848. int want_sdp = 1;
  1849. for (i = 0; i < nb_filtergraphs; i++) {
  1850. FilterGraph *fg = filtergraphs[i];
  1851. for (j = 0; j < fg->nb_outputs; j++) {
  1852. OutputFilter *ofilter = fg->outputs[j];
  1853. if (!ofilter->ost || ofilter->ost->source_index >= 0)
  1854. continue;
  1855. if (fg->nb_inputs != 1)
  1856. continue;
  1857. for (k = nb_input_streams-1; k >= 0 ; k--)
  1858. if (fg->inputs[0]->ist == input_streams[k])
  1859. break;
  1860. ofilter->ost->source_index = k;
  1861. }
  1862. }
  1863. /* init framerate emulation */
  1864. for (i = 0; i < nb_input_files; i++) {
  1865. InputFile *ifile = input_files[i];
  1866. if (ifile->rate_emu)
  1867. for (j = 0; j < ifile->nb_streams; j++)
  1868. input_streams[j + ifile->ist_index]->start = av_gettime();
  1869. }
  1870. /* output stream init */
  1871. for (i = 0; i < nb_output_files; i++) {
  1872. oc = output_files[i]->ctx;
  1873. if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
  1874. av_dump_format(oc, i, oc->filename, 1);
  1875. av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
  1876. return AVERROR(EINVAL);
  1877. }
  1878. }
  1879. /* init complex filtergraphs */
  1880. for (i = 0; i < nb_filtergraphs; i++)
  1881. if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
  1882. return ret;
  1883. /* for each output stream, we compute the right encoding parameters */
  1884. for (i = 0; i < nb_output_streams; i++) {
  1885. AVCodecContext *icodec = NULL;
  1886. ost = output_streams[i];
  1887. oc = output_files[ost->file_index]->ctx;
  1888. ist = get_input_stream(ost);
  1889. if (ost->attachment_filename)
  1890. continue;
  1891. codec = ost->st->codec;
  1892. if (ist) {
  1893. icodec = ist->st->codec;
  1894. ost->st->disposition = ist->st->disposition;
  1895. codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
  1896. codec->chroma_sample_location = icodec->chroma_sample_location;
  1897. } else {
  1898. for (j=0; j<oc->nb_streams; j++) {
  1899. AVStream *st = oc->streams[j];
  1900. if (st != ost->st && st->codec->codec_type == codec->codec_type)
  1901. break;
  1902. }
  1903. if (j == oc->nb_streams)
  1904. if (codec->codec_type == AVMEDIA_TYPE_AUDIO || codec->codec_type == AVMEDIA_TYPE_VIDEO)
  1905. ost->st->disposition = AV_DISPOSITION_DEFAULT;
  1906. }
  1907. if (ost->stream_copy) {
  1908. AVRational sar;
  1909. uint64_t extra_size;
  1910. av_assert0(ist && !ost->filter);
  1911. extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
  1912. if (extra_size > INT_MAX) {
  1913. return AVERROR(EINVAL);
  1914. }
  1915. /* if stream_copy is selected, no need to decode or encode */
  1916. codec->codec_id = icodec->codec_id;
  1917. codec->codec_type = icodec->codec_type;
  1918. if (!codec->codec_tag) {
  1919. unsigned int codec_tag;
  1920. if (!oc->oformat->codec_tag ||
  1921. av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
  1922. !av_codec_get_tag2(oc->oformat->codec_tag, icodec->codec_id, &codec_tag))
  1923. codec->codec_tag = icodec->codec_tag;
  1924. }
  1925. codec->bit_rate = icodec->bit_rate;
  1926. codec->rc_max_rate = icodec->rc_max_rate;
  1927. codec->rc_buffer_size = icodec->rc_buffer_size;
  1928. codec->field_order = icodec->field_order;
  1929. codec->extradata = av_mallocz(extra_size);
  1930. if (!codec->extradata) {
  1931. return AVERROR(ENOMEM);
  1932. }
  1933. memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
  1934. codec->extradata_size= icodec->extradata_size;
  1935. codec->bits_per_coded_sample = icodec->bits_per_coded_sample;
  1936. codec->time_base = ist->st->time_base;
  1937. /*
  1938. * Avi is a special case here because it supports variable fps but
  1939. * having the fps and timebase differe significantly adds quite some
  1940. * overhead
  1941. */
  1942. if(!strcmp(oc->oformat->name, "avi")) {
  1943. if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
  1944. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
  1945. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(icodec->time_base)
  1946. && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(icodec->time_base) < 1.0/500
  1947. || copy_tb==2){
  1948. codec->time_base.num = ist->st->r_frame_rate.den;
  1949. codec->time_base.den = 2*ist->st->r_frame_rate.num;
  1950. codec->ticks_per_frame = 2;
  1951. } else if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
  1952. && av_q2d(ist->st->time_base) < 1.0/500
  1953. || copy_tb==0){
  1954. codec->time_base = icodec->time_base;
  1955. codec->time_base.num *= icodec->ticks_per_frame;
  1956. codec->time_base.den *= 2;
  1957. codec->ticks_per_frame = 2;
  1958. }
  1959. } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
  1960. && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
  1961. && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
  1962. && strcmp(oc->oformat->name, "f4v")
  1963. ) {
  1964. if( copy_tb<0 && icodec->time_base.den
  1965. && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
  1966. && av_q2d(ist->st->time_base) < 1.0/500
  1967. || copy_tb==0){
  1968. codec->time_base = icodec->time_base;
  1969. codec->time_base.num *= icodec->ticks_per_frame;
  1970. }
  1971. }
  1972. if ( codec->codec_tag == AV_RL32("tmcd")
  1973. && icodec->time_base.num < icodec->time_base.den
  1974. && icodec->time_base.num > 0
  1975. && 121LL*icodec->time_base.num > icodec->time_base.den) {
  1976. codec->time_base = icodec->time_base;
  1977. }
  1978. if (ist && !ost->frame_rate.num)
  1979. ost->frame_rate = ist->framerate;
  1980. if(ost->frame_rate.num)
  1981. codec->time_base = av_inv_q(ost->frame_rate);
  1982. av_reduce(&codec->time_base.num, &codec->time_base.den,
  1983. codec->time_base.num, codec->time_base.den, INT_MAX);
  1984. ost->parser = av_parser_init(codec->codec_id);
  1985. switch (codec->codec_type) {
  1986. case AVMEDIA_TYPE_AUDIO:
  1987. if (audio_volume != 256) {
  1988. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
  1989. exit_program(1);
  1990. }
  1991. codec->channel_layout = icodec->channel_layout;
  1992. codec->sample_rate = icodec->sample_rate;
  1993. codec->channels = icodec->channels;
  1994. codec->frame_size = icodec->frame_size;
  1995. codec->audio_service_type = icodec->audio_service_type;
  1996. codec->block_align = icodec->block_align;
  1997. if((codec->block_align == 1 || codec->block_align == 1152 || codec->block_align == 576) && codec->codec_id == AV_CODEC_ID_MP3)
  1998. codec->block_align= 0;
  1999. if(codec->codec_id == AV_CODEC_ID_AC3)
  2000. codec->block_align= 0;
  2001. break;
  2002. case AVMEDIA_TYPE_VIDEO:
  2003. codec->pix_fmt = icodec->pix_fmt;
  2004. codec->width = icodec->width;
  2005. codec->height = icodec->height;
  2006. codec->has_b_frames = icodec->has_b_frames;
  2007. if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
  2008. sar =
  2009. av_mul_q(ost->frame_aspect_ratio,
  2010. (AVRational){ codec->height, codec->width });
  2011. av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
  2012. "with stream copy may produce invalid files\n");
  2013. }
  2014. else if (ist->st->sample_aspect_ratio.num)
  2015. sar = ist->st->sample_aspect_ratio;
  2016. else
  2017. sar = icodec->sample_aspect_ratio;
  2018. ost->st->sample_aspect_ratio = codec->sample_aspect_ratio = sar;
  2019. ost->st->avg_frame_rate = ist->st->avg_frame_rate;
  2020. break;
  2021. case AVMEDIA_TYPE_SUBTITLE:
  2022. codec->width = icodec->width;
  2023. codec->height = icodec->height;
  2024. break;
  2025. case AVMEDIA_TYPE_DATA:
  2026. case AVMEDIA_TYPE_ATTACHMENT:
  2027. break;
  2028. default:
  2029. abort();
  2030. }
  2031. } else {
  2032. if (!ost->enc)
  2033. ost->enc = avcodec_find_encoder(codec->codec_id);
  2034. if (!ost->enc) {
  2035. /* should only happen when a default codec is not present. */
  2036. snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
  2037. avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
  2038. ret = AVERROR(EINVAL);
  2039. goto dump_format;
  2040. }
  2041. if (ist)
  2042. ist->decoding_needed++;
  2043. ost->encoding_needed = 1;
  2044. if (!ost->filter &&
  2045. (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  2046. codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
  2047. FilterGraph *fg;
  2048. fg = init_simple_filtergraph(ist, ost);
  2049. if (configure_filtergraph(fg)) {
  2050. av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
  2051. exit_program(1);
  2052. }
  2053. }
  2054. if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  2055. if (ost->filter && !ost->frame_rate.num)
  2056. ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
  2057. if (ist && !ost->frame_rate.num)
  2058. ost->frame_rate = ist->framerate;
  2059. if (ist && !ost->frame_rate.num)
  2060. ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
  2061. // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
  2062. if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
  2063. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
  2064. ost->frame_rate = ost->enc->supported_framerates[idx];
  2065. }
  2066. }
  2067. switch (codec->codec_type) {
  2068. case AVMEDIA_TYPE_AUDIO:
  2069. codec->sample_fmt = ost->filter->filter->inputs[0]->format;
  2070. codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
  2071. codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
  2072. codec->channels = avfilter_link_get_channels(ost->filter->filter->inputs[0]);
  2073. codec->time_base = (AVRational){ 1, codec->sample_rate };
  2074. break;
  2075. case AVMEDIA_TYPE_VIDEO:
  2076. codec->time_base = av_inv_q(ost->frame_rate);
  2077. if (ost->filter && !(codec->time_base.num && codec->time_base.den))
  2078. codec->time_base = ost->filter->filter->inputs[0]->time_base;
  2079. if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
  2080. && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
  2081. av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
  2082. "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
  2083. }
  2084. for (j = 0; j < ost->forced_kf_count; j++)
  2085. ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
  2086. AV_TIME_BASE_Q,
  2087. codec->time_base);
  2088. codec->width = ost->filter->filter->inputs[0]->w;
  2089. codec->height = ost->filter->filter->inputs[0]->h;
  2090. codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  2091. ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
  2092. av_mul_q(ost->frame_aspect_ratio, (AVRational){ codec->height, codec->width }) :
  2093. ost->filter->filter->inputs[0]->sample_aspect_ratio;
  2094. if (!strncmp(ost->enc->name, "libx264", 7) &&
  2095. codec->pix_fmt == AV_PIX_FMT_NONE &&
  2096. ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
  2097. av_log(NULL, AV_LOG_WARNING,
  2098. "No pixel format specified, %s for H.264 encoding chosen.\n"
  2099. "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
  2100. av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
  2101. if (!strncmp(ost->enc->name, "mpeg2video", 10) &&
  2102. codec->pix_fmt == AV_PIX_FMT_NONE &&
  2103. ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
  2104. av_log(NULL, AV_LOG_WARNING,
  2105. "No pixel format specified, %s for MPEG-2 encoding chosen.\n"
  2106. "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
  2107. av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
  2108. codec->pix_fmt = ost->filter->filter->inputs[0]->format;
  2109. if (!icodec ||
  2110. codec->width != icodec->width ||
  2111. codec->height != icodec->height ||
  2112. codec->pix_fmt != icodec->pix_fmt) {
  2113. codec->bits_per_raw_sample = frame_bits_per_raw_sample;
  2114. }
  2115. if (ost->forced_keyframes) {
  2116. if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
  2117. ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
  2118. forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
  2119. if (ret < 0) {
  2120. av_log(NULL, AV_LOG_ERROR,
  2121. "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
  2122. return ret;
  2123. }
  2124. ost->forced_keyframes_expr_const_values[FKF_N] = 0;
  2125. ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
  2126. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
  2127. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
  2128. } else {
  2129. parse_forced_key_frames(ost->forced_keyframes, ost, ost->st->codec);
  2130. }
  2131. }
  2132. break;
  2133. case AVMEDIA_TYPE_SUBTITLE:
  2134. codec->time_base = (AVRational){1, 1000};
  2135. if (!codec->width) {
  2136. codec->width = input_streams[ost->source_index]->st->codec->width;
  2137. codec->height = input_streams[ost->source_index]->st->codec->height;
  2138. }
  2139. break;
  2140. default:
  2141. abort();
  2142. break;
  2143. }
  2144. /* two pass mode */
  2145. if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
  2146. char logfilename[1024];
  2147. FILE *f;
  2148. snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
  2149. ost->logfile_prefix ? ost->logfile_prefix :
  2150. DEFAULT_PASS_LOGFILENAME_PREFIX,
  2151. i);
  2152. if (!strcmp(ost->enc->name, "libx264")) {
  2153. av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
  2154. } else {
  2155. if (codec->flags & CODEC_FLAG_PASS2) {
  2156. char *logbuffer;
  2157. size_t logbuffer_size;
  2158. if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
  2159. av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
  2160. logfilename);
  2161. exit_program(1);
  2162. }
  2163. codec->stats_in = logbuffer;
  2164. }
  2165. if (codec->flags & CODEC_FLAG_PASS1) {
  2166. f = av_fopen_utf8(logfilename, "wb");
  2167. if (!f) {
  2168. av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
  2169. logfilename, strerror(errno));
  2170. exit_program(1);
  2171. }
  2172. ost->logfile = f;
  2173. }
  2174. }
  2175. }
  2176. }
  2177. }
  2178. /* open each encoder */
  2179. for (i = 0; i < nb_output_streams; i++) {
  2180. ost = output_streams[i];
  2181. if (ost->encoding_needed) {
  2182. AVCodec *codec = ost->enc;
  2183. AVCodecContext *dec = NULL;
  2184. if ((ist = get_input_stream(ost)))
  2185. dec = ist->st->codec;
  2186. if (dec && dec->subtitle_header) {
  2187. /* ASS code assumes this buffer is null terminated so add extra byte. */
  2188. ost->st->codec->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
  2189. if (!ost->st->codec->subtitle_header) {
  2190. ret = AVERROR(ENOMEM);
  2191. goto dump_format;
  2192. }
  2193. memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  2194. ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
  2195. }
  2196. if (!av_dict_get(ost->opts, "threads", NULL, 0))
  2197. av_dict_set(&ost->opts, "threads", "auto", 0);
  2198. if ((ret = avcodec_open2(ost->st->codec, codec, &ost->opts)) < 0) {
  2199. if (ret == AVERROR_EXPERIMENTAL)
  2200. abort_codec_experimental(codec, 1);
  2201. snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
  2202. ost->file_index, ost->index);
  2203. goto dump_format;
  2204. }
  2205. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  2206. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  2207. av_buffersink_set_frame_size(ost->filter->filter,
  2208. ost->st->codec->frame_size);
  2209. assert_avoptions(ost->opts);
  2210. if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
  2211. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  2212. " It takes bits/s as argument, not kbits/s\n");
  2213. extra_size += ost->st->codec->extradata_size;
  2214. } else {
  2215. av_opt_set_dict(ost->st->codec, &ost->opts);
  2216. }
  2217. }
  2218. /* init input streams */
  2219. for (i = 0; i < nb_input_streams; i++)
  2220. if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
  2221. for (i = 0; i < nb_output_streams; i++) {
  2222. ost = output_streams[i];
  2223. avcodec_close(ost->st->codec);
  2224. }
  2225. goto dump_format;
  2226. }
  2227. /* discard unused programs */
  2228. for (i = 0; i < nb_input_files; i++) {
  2229. InputFile *ifile = input_files[i];
  2230. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  2231. AVProgram *p = ifile->ctx->programs[j];
  2232. int discard = AVDISCARD_ALL;
  2233. for (k = 0; k < p->nb_stream_indexes; k++)
  2234. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
  2235. discard = AVDISCARD_DEFAULT;
  2236. break;
  2237. }
  2238. p->discard = discard;
  2239. }
  2240. }
  2241. /* open files and write file headers */
  2242. for (i = 0; i < nb_output_files; i++) {
  2243. oc = output_files[i]->ctx;
  2244. oc->interrupt_callback = int_cb;
  2245. if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
  2246. char errbuf[128];
  2247. av_strerror(ret, errbuf, sizeof(errbuf));
  2248. snprintf(error, sizeof(error),
  2249. "Could not write header for output file #%d "
  2250. "(incorrect codec parameters ?): %s",
  2251. i, errbuf);
  2252. ret = AVERROR(EINVAL);
  2253. goto dump_format;
  2254. }
  2255. // assert_avoptions(output_files[i]->opts);
  2256. if (strcmp(oc->oformat->name, "rtp")) {
  2257. want_sdp = 0;
  2258. }
  2259. }
  2260. dump_format:
  2261. /* dump the file output parameters - cannot be done before in case
  2262. of stream copy */
  2263. for (i = 0; i < nb_output_files; i++) {
  2264. av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
  2265. }
  2266. /* dump the stream mapping */
  2267. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  2268. for (i = 0; i < nb_input_streams; i++) {
  2269. ist = input_streams[i];
  2270. for (j = 0; j < ist->nb_filters; j++) {
  2271. if (ist->filters[j]->graph->graph_desc) {
  2272. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  2273. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
  2274. ist->filters[j]->name);
  2275. if (nb_filtergraphs > 1)
  2276. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  2277. av_log(NULL, AV_LOG_INFO, "\n");
  2278. }
  2279. }
  2280. }
  2281. for (i = 0; i < nb_output_streams; i++) {
  2282. ost = output_streams[i];
  2283. if (ost->attachment_filename) {
  2284. /* an attached file */
  2285. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  2286. ost->attachment_filename, ost->file_index, ost->index);
  2287. continue;
  2288. }
  2289. if (ost->filter && ost->filter->graph->graph_desc) {
  2290. /* output from a complex graph */
  2291. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  2292. if (nb_filtergraphs > 1)
  2293. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  2294. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  2295. ost->index, ost->enc ? ost->enc->name : "?");
  2296. continue;
  2297. }
  2298. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  2299. input_streams[ost->source_index]->file_index,
  2300. input_streams[ost->source_index]->st->index,
  2301. ost->file_index,
  2302. ost->index);
  2303. if (ost->sync_ist != input_streams[ost->source_index])
  2304. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  2305. ost->sync_ist->file_index,
  2306. ost->sync_ist->st->index);
  2307. if (ost->stream_copy)
  2308. av_log(NULL, AV_LOG_INFO, " (copy)");
  2309. else
  2310. av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
  2311. input_streams[ost->source_index]->dec->name : "?",
  2312. ost->enc ? ost->enc->name : "?");
  2313. av_log(NULL, AV_LOG_INFO, "\n");
  2314. }
  2315. if (ret) {
  2316. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  2317. return ret;
  2318. }
  2319. if (want_sdp) {
  2320. print_sdp();
  2321. }
  2322. return 0;
  2323. }
  2324. /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
  2325. static int need_output(void)
  2326. {
  2327. int i;
  2328. for (i = 0; i < nb_output_streams; i++) {
  2329. OutputStream *ost = output_streams[i];
  2330. OutputFile *of = output_files[ost->file_index];
  2331. AVFormatContext *os = output_files[ost->file_index]->ctx;
  2332. if (ost->finished ||
  2333. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  2334. continue;
  2335. if (ost->frame_number >= ost->max_frames) {
  2336. int j;
  2337. for (j = 0; j < of->ctx->nb_streams; j++)
  2338. close_output_stream(output_streams[of->ost_index + j]);
  2339. continue;
  2340. }
  2341. return 1;
  2342. }
  2343. return 0;
  2344. }
  2345. /**
  2346. * Select the output stream to process.
  2347. *
  2348. * @return selected output stream, or NULL if none available
  2349. */
  2350. static OutputStream *choose_output(void)
  2351. {
  2352. int i;
  2353. int64_t opts_min = INT64_MAX;
  2354. OutputStream *ost_min = NULL;
  2355. for (i = 0; i < nb_output_streams; i++) {
  2356. OutputStream *ost = output_streams[i];
  2357. int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
  2358. AV_TIME_BASE_Q);
  2359. if (!ost->unavailable && !ost->finished && opts < opts_min) {
  2360. opts_min = opts;
  2361. ost_min = ost;
  2362. }
  2363. }
  2364. return ost_min;
  2365. }
  2366. static int check_keyboard_interaction(int64_t cur_time)
  2367. {
  2368. int i, ret, key;
  2369. static int64_t last_time;
  2370. if (received_nb_signals)
  2371. return AVERROR_EXIT;
  2372. /* read_key() returns 0 on EOF */
  2373. if(cur_time - last_time >= 100000 && !run_as_daemon){
  2374. key = read_key();
  2375. last_time = cur_time;
  2376. }else
  2377. key = -1;
  2378. if (key == 'q')
  2379. return AVERROR_EXIT;
  2380. if (key == '+') av_log_set_level(av_log_get_level()+10);
  2381. if (key == '-') av_log_set_level(av_log_get_level()-10);
  2382. if (key == 's') qp_hist ^= 1;
  2383. if (key == 'h'){
  2384. if (do_hex_dump){
  2385. do_hex_dump = do_pkt_dump = 0;
  2386. } else if(do_pkt_dump){
  2387. do_hex_dump = 1;
  2388. } else
  2389. do_pkt_dump = 1;
  2390. av_log_set_level(AV_LOG_DEBUG);
  2391. }
  2392. if (key == 'c' || key == 'C'){
  2393. char buf[4096], target[64], command[256], arg[256] = {0};
  2394. double time;
  2395. int k, n = 0;
  2396. fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
  2397. i = 0;
  2398. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  2399. if (k > 0)
  2400. buf[i++] = k;
  2401. buf[i] = 0;
  2402. if (k > 0 &&
  2403. (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
  2404. av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
  2405. target, time, command, arg);
  2406. for (i = 0; i < nb_filtergraphs; i++) {
  2407. FilterGraph *fg = filtergraphs[i];
  2408. if (fg->graph) {
  2409. if (time < 0) {
  2410. ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
  2411. key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
  2412. fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
  2413. } else if (key == 'c') {
  2414. fprintf(stderr, "Queing commands only on filters supporting the specific command is unsupported\n");
  2415. ret = AVERROR_PATCHWELCOME;
  2416. } else {
  2417. ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
  2418. }
  2419. }
  2420. }
  2421. } else {
  2422. av_log(NULL, AV_LOG_ERROR,
  2423. "Parse error, at least 3 arguments were expected, "
  2424. "only %d given in string '%s'\n", n, buf);
  2425. }
  2426. }
  2427. if (key == 'd' || key == 'D'){
  2428. int debug=0;
  2429. if(key == 'D') {
  2430. debug = input_streams[0]->st->codec->debug<<1;
  2431. if(!debug) debug = 1;
  2432. while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
  2433. debug += debug;
  2434. }else
  2435. if(scanf("%d", &debug)!=1)
  2436. fprintf(stderr,"error parsing debug value\n");
  2437. for(i=0;i<nb_input_streams;i++) {
  2438. input_streams[i]->st->codec->debug = debug;
  2439. }
  2440. for(i=0;i<nb_output_streams;i++) {
  2441. OutputStream *ost = output_streams[i];
  2442. ost->st->codec->debug = debug;
  2443. }
  2444. if(debug) av_log_set_level(AV_LOG_DEBUG);
  2445. fprintf(stderr,"debug=%d\n", debug);
  2446. }
  2447. if (key == '?'){
  2448. fprintf(stderr, "key function\n"
  2449. "? show this help\n"
  2450. "+ increase verbosity\n"
  2451. "- decrease verbosity\n"
  2452. "c Send command to first matching filter supporting it\n"
  2453. "C Send/Que command to all matching filters\n"
  2454. "D cycle through available debug modes\n"
  2455. "h dump packets/hex press to cycle through the 3 states\n"
  2456. "q quit\n"
  2457. "s Show QP histogram\n"
  2458. );
  2459. }
  2460. return 0;
  2461. }
  2462. #if HAVE_PTHREADS
  2463. static void *input_thread(void *arg)
  2464. {
  2465. InputFile *f = arg;
  2466. int ret = 0;
  2467. while (!transcoding_finished && ret >= 0) {
  2468. AVPacket pkt;
  2469. ret = av_read_frame(f->ctx, &pkt);
  2470. if (ret == AVERROR(EAGAIN)) {
  2471. av_usleep(10000);
  2472. ret = 0;
  2473. continue;
  2474. } else if (ret < 0)
  2475. break;
  2476. pthread_mutex_lock(&f->fifo_lock);
  2477. while (!av_fifo_space(f->fifo))
  2478. pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
  2479. av_dup_packet(&pkt);
  2480. av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
  2481. pthread_mutex_unlock(&f->fifo_lock);
  2482. }
  2483. f->finished = 1;
  2484. return NULL;
  2485. }
  2486. static void free_input_threads(void)
  2487. {
  2488. int i;
  2489. if (nb_input_files == 1)
  2490. return;
  2491. transcoding_finished = 1;
  2492. for (i = 0; i < nb_input_files; i++) {
  2493. InputFile *f = input_files[i];
  2494. AVPacket pkt;
  2495. if (!f->fifo || f->joined)
  2496. continue;
  2497. pthread_mutex_lock(&f->fifo_lock);
  2498. while (av_fifo_size(f->fifo)) {
  2499. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2500. av_free_packet(&pkt);
  2501. }
  2502. pthread_cond_signal(&f->fifo_cond);
  2503. pthread_mutex_unlock(&f->fifo_lock);
  2504. pthread_join(f->thread, NULL);
  2505. f->joined = 1;
  2506. while (av_fifo_size(f->fifo)) {
  2507. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2508. av_free_packet(&pkt);
  2509. }
  2510. av_fifo_free(f->fifo);
  2511. }
  2512. }
  2513. static int init_input_threads(void)
  2514. {
  2515. int i, ret;
  2516. if (nb_input_files == 1)
  2517. return 0;
  2518. for (i = 0; i < nb_input_files; i++) {
  2519. InputFile *f = input_files[i];
  2520. if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
  2521. return AVERROR(ENOMEM);
  2522. pthread_mutex_init(&f->fifo_lock, NULL);
  2523. pthread_cond_init (&f->fifo_cond, NULL);
  2524. if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
  2525. return AVERROR(ret);
  2526. }
  2527. return 0;
  2528. }
  2529. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
  2530. {
  2531. int ret = 0;
  2532. pthread_mutex_lock(&f->fifo_lock);
  2533. if (av_fifo_size(f->fifo)) {
  2534. av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
  2535. pthread_cond_signal(&f->fifo_cond);
  2536. } else {
  2537. if (f->finished)
  2538. ret = AVERROR_EOF;
  2539. else
  2540. ret = AVERROR(EAGAIN);
  2541. }
  2542. pthread_mutex_unlock(&f->fifo_lock);
  2543. return ret;
  2544. }
  2545. #endif
  2546. static int get_input_packet(InputFile *f, AVPacket *pkt)
  2547. {
  2548. if (f->rate_emu) {
  2549. int i;
  2550. for (i = 0; i < f->nb_streams; i++) {
  2551. InputStream *ist = input_streams[f->ist_index + i];
  2552. int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
  2553. int64_t now = av_gettime() - ist->start;
  2554. if (pts > now)
  2555. return AVERROR(EAGAIN);
  2556. }
  2557. }
  2558. #if HAVE_PTHREADS
  2559. if (nb_input_files > 1)
  2560. return get_input_packet_mt(f, pkt);
  2561. #endif
  2562. return av_read_frame(f->ctx, pkt);
  2563. }
  2564. static int got_eagain(void)
  2565. {
  2566. int i;
  2567. for (i = 0; i < nb_output_streams; i++)
  2568. if (output_streams[i]->unavailable)
  2569. return 1;
  2570. return 0;
  2571. }
  2572. static void reset_eagain(void)
  2573. {
  2574. int i;
  2575. for (i = 0; i < nb_input_files; i++)
  2576. input_files[i]->eagain = 0;
  2577. for (i = 0; i < nb_output_streams; i++)
  2578. output_streams[i]->unavailable = 0;
  2579. }
  2580. /*
  2581. * Return
  2582. * - 0 -- one packet was read and processed
  2583. * - AVERROR(EAGAIN) -- no packets were available for selected file,
  2584. * this function should be called again
  2585. * - AVERROR_EOF -- this function should not be called again
  2586. */
  2587. static int process_input(int file_index)
  2588. {
  2589. InputFile *ifile = input_files[file_index];
  2590. AVFormatContext *is;
  2591. InputStream *ist;
  2592. AVPacket pkt;
  2593. int ret, i, j;
  2594. is = ifile->ctx;
  2595. ret = get_input_packet(ifile, &pkt);
  2596. if (ret == AVERROR(EAGAIN)) {
  2597. ifile->eagain = 1;
  2598. return ret;
  2599. }
  2600. if (ret < 0) {
  2601. if (ret != AVERROR_EOF) {
  2602. print_error(is->filename, ret);
  2603. if (exit_on_error)
  2604. exit_program(1);
  2605. }
  2606. ifile->eof_reached = 1;
  2607. for (i = 0; i < ifile->nb_streams; i++) {
  2608. ist = input_streams[ifile->ist_index + i];
  2609. if (ist->decoding_needed)
  2610. output_packet(ist, NULL);
  2611. /* mark all outputs that don't go through lavfi as finished */
  2612. for (j = 0; j < nb_output_streams; j++) {
  2613. OutputStream *ost = output_streams[j];
  2614. if (ost->source_index == ifile->ist_index + i &&
  2615. (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
  2616. close_output_stream(ost);
  2617. }
  2618. }
  2619. return AVERROR(EAGAIN);
  2620. }
  2621. reset_eagain();
  2622. if (do_pkt_dump) {
  2623. av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
  2624. is->streams[pkt.stream_index]);
  2625. }
  2626. /* the following test is needed in case new streams appear
  2627. dynamically in stream : we ignore them */
  2628. if (pkt.stream_index >= ifile->nb_streams) {
  2629. report_new_stream(file_index, &pkt);
  2630. goto discard_packet;
  2631. }
  2632. ist = input_streams[ifile->ist_index + pkt.stream_index];
  2633. if (ist->discard)
  2634. goto discard_packet;
  2635. if (debug_ts) {
  2636. av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
  2637. "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",
  2638. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
  2639. av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
  2640. av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
  2641. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  2642. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  2643. av_ts2str(input_files[ist->file_index]->ts_offset),
  2644. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  2645. }
  2646. if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
  2647. int64_t stime, stime2;
  2648. // Correcting starttime based on the enabled streams
  2649. // 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.
  2650. // so we instead do it here as part of discontinuity handling
  2651. if ( ist->next_dts == AV_NOPTS_VALUE
  2652. && ifile->ts_offset == -is->start_time
  2653. && (is->iformat->flags & AVFMT_TS_DISCONT)) {
  2654. int64_t new_start_time = INT64_MAX;
  2655. for (i=0; i<is->nb_streams; i++) {
  2656. AVStream *st = is->streams[i];
  2657. if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
  2658. continue;
  2659. new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
  2660. }
  2661. if (new_start_time > is->start_time) {
  2662. av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
  2663. ifile->ts_offset = -new_start_time;
  2664. }
  2665. }
  2666. stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
  2667. stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
  2668. ist->wrap_correction_done = 1;
  2669. if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  2670. pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
  2671. ist->wrap_correction_done = 0;
  2672. }
  2673. if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  2674. pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
  2675. ist->wrap_correction_done = 0;
  2676. }
  2677. }
  2678. if (pkt.dts != AV_NOPTS_VALUE)
  2679. pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2680. if (pkt.pts != AV_NOPTS_VALUE)
  2681. pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2682. if (pkt.pts != AV_NOPTS_VALUE)
  2683. pkt.pts *= ist->ts_scale;
  2684. if (pkt.dts != AV_NOPTS_VALUE)
  2685. pkt.dts *= ist->ts_scale;
  2686. if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
  2687. && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
  2688. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2689. int64_t delta = pkt_dts - ifile->last_ts;
  2690. if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  2691. (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
  2692. ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)){
  2693. ifile->ts_offset -= delta;
  2694. av_log(NULL, AV_LOG_DEBUG,
  2695. "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  2696. delta, ifile->ts_offset);
  2697. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2698. if (pkt.pts != AV_NOPTS_VALUE)
  2699. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2700. }
  2701. }
  2702. if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
  2703. !copy_ts) {
  2704. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2705. int64_t delta = pkt_dts - ist->next_dts;
  2706. if (is->iformat->flags & AVFMT_TS_DISCONT) {
  2707. if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  2708. (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
  2709. ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
  2710. pkt_dts + AV_TIME_BASE/10 < ist->pts){
  2711. ifile->ts_offset -= delta;
  2712. av_log(NULL, AV_LOG_DEBUG,
  2713. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  2714. delta, ifile->ts_offset);
  2715. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2716. if (pkt.pts != AV_NOPTS_VALUE)
  2717. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2718. }
  2719. } else {
  2720. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  2721. (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
  2722. ) {
  2723. av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
  2724. pkt.dts = AV_NOPTS_VALUE;
  2725. }
  2726. if (pkt.pts != AV_NOPTS_VALUE){
  2727. int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
  2728. delta = pkt_pts - ist->next_dts;
  2729. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  2730. (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
  2731. ) {
  2732. av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
  2733. pkt.pts = AV_NOPTS_VALUE;
  2734. }
  2735. }
  2736. }
  2737. }
  2738. if (pkt.dts != AV_NOPTS_VALUE)
  2739. ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2740. if (debug_ts) {
  2741. 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",
  2742. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
  2743. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  2744. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  2745. av_ts2str(input_files[ist->file_index]->ts_offset),
  2746. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  2747. }
  2748. sub2video_heartbeat(ist, pkt.pts);
  2749. ret = output_packet(ist, &pkt);
  2750. if (ret < 0) {
  2751. char buf[128];
  2752. av_strerror(ret, buf, sizeof(buf));
  2753. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
  2754. ist->file_index, ist->st->index, buf);
  2755. if (exit_on_error)
  2756. exit_program(1);
  2757. }
  2758. discard_packet:
  2759. av_free_packet(&pkt);
  2760. return 0;
  2761. }
  2762. /**
  2763. * Perform a step of transcoding for the specified filter graph.
  2764. *
  2765. * @param[in] graph filter graph to consider
  2766. * @param[out] best_ist input stream where a frame would allow to continue
  2767. * @return 0 for success, <0 for error
  2768. */
  2769. static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
  2770. {
  2771. int i, ret;
  2772. int nb_requests, nb_requests_max = 0;
  2773. InputFilter *ifilter;
  2774. InputStream *ist;
  2775. *best_ist = NULL;
  2776. ret = avfilter_graph_request_oldest(graph->graph);
  2777. if (ret >= 0)
  2778. return reap_filters();
  2779. if (ret == AVERROR_EOF) {
  2780. ret = reap_filters();
  2781. for (i = 0; i < graph->nb_outputs; i++)
  2782. close_output_stream(graph->outputs[i]->ost);
  2783. return ret;
  2784. }
  2785. if (ret != AVERROR(EAGAIN))
  2786. return ret;
  2787. for (i = 0; i < graph->nb_inputs; i++) {
  2788. ifilter = graph->inputs[i];
  2789. ist = ifilter->ist;
  2790. if (input_files[ist->file_index]->eagain ||
  2791. input_files[ist->file_index]->eof_reached)
  2792. continue;
  2793. nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
  2794. if (nb_requests > nb_requests_max) {
  2795. nb_requests_max = nb_requests;
  2796. *best_ist = ist;
  2797. }
  2798. }
  2799. if (!*best_ist)
  2800. for (i = 0; i < graph->nb_outputs; i++)
  2801. graph->outputs[i]->ost->unavailable = 1;
  2802. return 0;
  2803. }
  2804. /**
  2805. * Run a single step of transcoding.
  2806. *
  2807. * @return 0 for success, <0 for error
  2808. */
  2809. static int transcode_step(void)
  2810. {
  2811. OutputStream *ost;
  2812. InputStream *ist;
  2813. int ret;
  2814. ost = choose_output();
  2815. if (!ost) {
  2816. if (got_eagain()) {
  2817. reset_eagain();
  2818. av_usleep(10000);
  2819. return 0;
  2820. }
  2821. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
  2822. return AVERROR_EOF;
  2823. }
  2824. if (ost->filter) {
  2825. if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
  2826. return ret;
  2827. if (!ist)
  2828. return 0;
  2829. } else {
  2830. av_assert0(ost->source_index >= 0);
  2831. ist = input_streams[ost->source_index];
  2832. }
  2833. ret = process_input(ist->file_index);
  2834. if (ret == AVERROR(EAGAIN)) {
  2835. if (input_files[ist->file_index]->eagain)
  2836. ost->unavailable = 1;
  2837. return 0;
  2838. }
  2839. if (ret < 0)
  2840. return ret == AVERROR_EOF ? 0 : ret;
  2841. return reap_filters();
  2842. }
  2843. /*
  2844. * The following code is the main loop of the file converter
  2845. */
  2846. static int transcode(void)
  2847. {
  2848. int ret, i;
  2849. AVFormatContext *os;
  2850. OutputStream *ost;
  2851. InputStream *ist;
  2852. int64_t timer_start;
  2853. ret = transcode_init();
  2854. if (ret < 0)
  2855. goto fail;
  2856. if (stdin_interaction) {
  2857. av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
  2858. }
  2859. timer_start = av_gettime();
  2860. #if HAVE_PTHREADS
  2861. if ((ret = init_input_threads()) < 0)
  2862. goto fail;
  2863. #endif
  2864. while (!received_sigterm) {
  2865. int64_t cur_time= av_gettime();
  2866. /* if 'q' pressed, exits */
  2867. if (stdin_interaction)
  2868. if (check_keyboard_interaction(cur_time) < 0)
  2869. break;
  2870. /* check if there's any stream where output is still needed */
  2871. if (!need_output()) {
  2872. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  2873. break;
  2874. }
  2875. ret = transcode_step();
  2876. if (ret < 0) {
  2877. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  2878. continue;
  2879. av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
  2880. break;
  2881. }
  2882. /* dump report by using the output first video and audio streams */
  2883. print_report(0, timer_start, cur_time);
  2884. }
  2885. #if HAVE_PTHREADS
  2886. free_input_threads();
  2887. #endif
  2888. /* at the end of stream, we must flush the decoder buffers */
  2889. for (i = 0; i < nb_input_streams; i++) {
  2890. ist = input_streams[i];
  2891. if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
  2892. output_packet(ist, NULL);
  2893. }
  2894. }
  2895. flush_encoders();
  2896. term_exit();
  2897. /* write the trailer if needed and close file */
  2898. for (i = 0; i < nb_output_files; i++) {
  2899. os = output_files[i]->ctx;
  2900. av_write_trailer(os);
  2901. }
  2902. /* dump report by using the first video and audio streams */
  2903. print_report(1, timer_start, av_gettime());
  2904. /* close each encoder */
  2905. for (i = 0; i < nb_output_streams; i++) {
  2906. ost = output_streams[i];
  2907. if (ost->encoding_needed) {
  2908. av_freep(&ost->st->codec->stats_in);
  2909. avcodec_close(ost->st->codec);
  2910. }
  2911. }
  2912. /* close each decoder */
  2913. for (i = 0; i < nb_input_streams; i++) {
  2914. ist = input_streams[i];
  2915. if (ist->decoding_needed) {
  2916. avcodec_close(ist->st->codec);
  2917. }
  2918. }
  2919. /* finished ! */
  2920. ret = 0;
  2921. fail:
  2922. #if HAVE_PTHREADS
  2923. free_input_threads();
  2924. #endif
  2925. if (output_streams) {
  2926. for (i = 0; i < nb_output_streams; i++) {
  2927. ost = output_streams[i];
  2928. if (ost) {
  2929. if (ost->stream_copy)
  2930. av_freep(&ost->st->codec->extradata);
  2931. if (ost->logfile) {
  2932. fclose(ost->logfile);
  2933. ost->logfile = NULL;
  2934. }
  2935. av_freep(&ost->st->codec->subtitle_header);
  2936. av_freep(&ost->forced_kf_pts);
  2937. av_freep(&ost->apad);
  2938. av_dict_free(&ost->opts);
  2939. av_dict_free(&ost->swr_opts);
  2940. av_dict_free(&ost->resample_opts);
  2941. }
  2942. }
  2943. }
  2944. return ret;
  2945. }
  2946. static int64_t getutime(void)
  2947. {
  2948. #if HAVE_GETRUSAGE
  2949. struct rusage rusage;
  2950. getrusage(RUSAGE_SELF, &rusage);
  2951. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  2952. #elif HAVE_GETPROCESSTIMES
  2953. HANDLE proc;
  2954. FILETIME c, e, k, u;
  2955. proc = GetCurrentProcess();
  2956. GetProcessTimes(proc, &c, &e, &k, &u);
  2957. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  2958. #else
  2959. return av_gettime();
  2960. #endif
  2961. }
  2962. static int64_t getmaxrss(void)
  2963. {
  2964. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  2965. struct rusage rusage;
  2966. getrusage(RUSAGE_SELF, &rusage);
  2967. return (int64_t)rusage.ru_maxrss * 1024;
  2968. #elif HAVE_GETPROCESSMEMORYINFO
  2969. HANDLE proc;
  2970. PROCESS_MEMORY_COUNTERS memcounters;
  2971. proc = GetCurrentProcess();
  2972. memcounters.cb = sizeof(memcounters);
  2973. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  2974. return memcounters.PeakPagefileUsage;
  2975. #else
  2976. return 0;
  2977. #endif
  2978. }
  2979. static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
  2980. {
  2981. }
  2982. int main(int argc, char **argv)
  2983. {
  2984. int ret;
  2985. int64_t ti;
  2986. register_exit(ffmpeg_cleanup);
  2987. setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
  2988. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  2989. parse_loglevel(argc, argv, options);
  2990. if(argc>1 && !strcmp(argv[1], "-d")){
  2991. run_as_daemon=1;
  2992. av_log_set_callback(log_callback_null);
  2993. argc--;
  2994. argv++;
  2995. }
  2996. avcodec_register_all();
  2997. #if CONFIG_AVDEVICE
  2998. avdevice_register_all();
  2999. #endif
  3000. avfilter_register_all();
  3001. av_register_all();
  3002. avformat_network_init();
  3003. show_banner(argc, argv, options);
  3004. term_init();
  3005. /* parse options and open all input/output files */
  3006. ret = ffmpeg_parse_options(argc, argv);
  3007. if (ret < 0)
  3008. exit_program(1);
  3009. if (nb_output_files <= 0 && nb_input_files == 0) {
  3010. show_usage();
  3011. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  3012. exit_program(1);
  3013. }
  3014. /* file converter / grab */
  3015. if (nb_output_files <= 0) {
  3016. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
  3017. exit_program(1);
  3018. }
  3019. // if (nb_input_files == 0) {
  3020. // av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
  3021. // exit_program(1);
  3022. // }
  3023. current_time = ti = getutime();
  3024. if (transcode() < 0)
  3025. exit_program(1);
  3026. ti = getutime() - ti;
  3027. if (do_benchmark) {
  3028. printf("bench: utime=%0.3fs\n", ti / 1000000.0);
  3029. }
  3030. av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
  3031. decode_error_stat[0], decode_error_stat[1]);
  3032. if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
  3033. exit_program(69);
  3034. exit_program(received_nb_signals ? 255 : 0);
  3035. return 0;
  3036. }