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.

3470 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. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
  1317. /* store AVPicture in AVPacket, as expected by the output format */
  1318. avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
  1319. opkt.data = (uint8_t *)&pict;
  1320. opkt.size = sizeof(AVPicture);
  1321. opkt.flags |= AV_PKT_FLAG_KEY;
  1322. }
  1323. write_frame(of->ctx, &opkt, ost);
  1324. ost->st->codec->frame_number++;
  1325. }
  1326. int guess_input_channel_layout(InputStream *ist)
  1327. {
  1328. AVCodecContext *dec = ist->st->codec;
  1329. if (!dec->channel_layout) {
  1330. char layout_name[256];
  1331. if (dec->channels > ist->guess_layout_max)
  1332. return 0;
  1333. dec->channel_layout = av_get_default_channel_layout(dec->channels);
  1334. if (!dec->channel_layout)
  1335. return 0;
  1336. av_get_channel_layout_string(layout_name, sizeof(layout_name),
  1337. dec->channels, dec->channel_layout);
  1338. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
  1339. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
  1340. }
  1341. return 1;
  1342. }
  1343. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
  1344. {
  1345. AVFrame *decoded_frame, *f;
  1346. AVCodecContext *avctx = ist->st->codec;
  1347. int i, ret, err = 0, resample_changed;
  1348. AVRational decoded_frame_tb;
  1349. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  1350. return AVERROR(ENOMEM);
  1351. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  1352. return AVERROR(ENOMEM);
  1353. decoded_frame = ist->decoded_frame;
  1354. update_benchmark(NULL);
  1355. ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
  1356. update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
  1357. if (ret >= 0 && avctx->sample_rate <= 0) {
  1358. av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
  1359. ret = AVERROR_INVALIDDATA;
  1360. }
  1361. if (*got_output || ret<0 || pkt->size)
  1362. decode_error_stat[ret<0] ++;
  1363. if (!*got_output || ret < 0) {
  1364. if (!pkt->size) {
  1365. for (i = 0; i < ist->nb_filters; i++)
  1366. #if 1
  1367. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  1368. #else
  1369. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  1370. #endif
  1371. }
  1372. return ret;
  1373. }
  1374. #if 1
  1375. /* increment next_dts to use for the case where the input stream does not
  1376. have timestamps or there are multiple frames in the packet */
  1377. ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1378. avctx->sample_rate;
  1379. ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1380. avctx->sample_rate;
  1381. #endif
  1382. resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
  1383. ist->resample_channels != avctx->channels ||
  1384. ist->resample_channel_layout != decoded_frame->channel_layout ||
  1385. ist->resample_sample_rate != decoded_frame->sample_rate;
  1386. if (resample_changed) {
  1387. char layout1[64], layout2[64];
  1388. if (!guess_input_channel_layout(ist)) {
  1389. av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
  1390. "layout for Input Stream #%d.%d\n", ist->file_index,
  1391. ist->st->index);
  1392. exit_program(1);
  1393. }
  1394. decoded_frame->channel_layout = avctx->channel_layout;
  1395. av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
  1396. ist->resample_channel_layout);
  1397. av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
  1398. decoded_frame->channel_layout);
  1399. av_log(NULL, AV_LOG_INFO,
  1400. "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",
  1401. ist->file_index, ist->st->index,
  1402. ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
  1403. ist->resample_channels, layout1,
  1404. decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
  1405. avctx->channels, layout2);
  1406. ist->resample_sample_fmt = decoded_frame->format;
  1407. ist->resample_sample_rate = decoded_frame->sample_rate;
  1408. ist->resample_channel_layout = decoded_frame->channel_layout;
  1409. ist->resample_channels = avctx->channels;
  1410. for (i = 0; i < nb_filtergraphs; i++)
  1411. if (ist_in_filtergraph(filtergraphs[i], ist)) {
  1412. FilterGraph *fg = filtergraphs[i];
  1413. int j;
  1414. if (configure_filtergraph(fg) < 0) {
  1415. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1416. exit_program(1);
  1417. }
  1418. for (j = 0; j < fg->nb_outputs; j++) {
  1419. OutputStream *ost = fg->outputs[j]->ost;
  1420. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  1421. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  1422. av_buffersink_set_frame_size(ost->filter->filter,
  1423. ost->st->codec->frame_size);
  1424. }
  1425. }
  1426. }
  1427. /* if the decoder provides a pts, use it instead of the last packet pts.
  1428. the decoder could be delaying output by a packet or more. */
  1429. if (decoded_frame->pts != AV_NOPTS_VALUE) {
  1430. ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
  1431. decoded_frame_tb = avctx->time_base;
  1432. } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
  1433. decoded_frame->pts = decoded_frame->pkt_pts;
  1434. pkt->pts = AV_NOPTS_VALUE;
  1435. decoded_frame_tb = ist->st->time_base;
  1436. } else if (pkt->pts != AV_NOPTS_VALUE) {
  1437. decoded_frame->pts = pkt->pts;
  1438. pkt->pts = AV_NOPTS_VALUE;
  1439. decoded_frame_tb = ist->st->time_base;
  1440. }else {
  1441. decoded_frame->pts = ist->dts;
  1442. decoded_frame_tb = AV_TIME_BASE_Q;
  1443. }
  1444. if (decoded_frame->pts != AV_NOPTS_VALUE)
  1445. decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
  1446. (AVRational){1, ist->st->codec->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
  1447. (AVRational){1, ist->st->codec->sample_rate});
  1448. for (i = 0; i < ist->nb_filters; i++) {
  1449. if (i < ist->nb_filters - 1) {
  1450. f = ist->filter_frame;
  1451. err = av_frame_ref(f, decoded_frame);
  1452. if (err < 0)
  1453. break;
  1454. } else
  1455. f = decoded_frame;
  1456. err = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f,
  1457. AV_BUFFERSRC_FLAG_PUSH);
  1458. if (err == AVERROR_EOF)
  1459. err = 0; /* ignore */
  1460. if (err < 0)
  1461. break;
  1462. }
  1463. decoded_frame->pts = AV_NOPTS_VALUE;
  1464. av_frame_unref(ist->filter_frame);
  1465. av_frame_unref(decoded_frame);
  1466. return err < 0 ? err : ret;
  1467. }
  1468. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
  1469. {
  1470. AVFrame *decoded_frame, *f;
  1471. int i, ret = 0, err = 0, resample_changed;
  1472. int64_t best_effort_timestamp;
  1473. AVRational *frame_sample_aspect;
  1474. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  1475. return AVERROR(ENOMEM);
  1476. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  1477. return AVERROR(ENOMEM);
  1478. decoded_frame = ist->decoded_frame;
  1479. pkt->dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
  1480. update_benchmark(NULL);
  1481. ret = avcodec_decode_video2(ist->st->codec,
  1482. decoded_frame, got_output, pkt);
  1483. update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
  1484. if (*got_output || ret<0 || pkt->size)
  1485. decode_error_stat[ret<0] ++;
  1486. if (!*got_output || ret < 0) {
  1487. if (!pkt->size) {
  1488. for (i = 0; i < ist->nb_filters; i++)
  1489. #if 1
  1490. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  1491. #else
  1492. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  1493. #endif
  1494. }
  1495. return ret;
  1496. }
  1497. if(ist->top_field_first>=0)
  1498. decoded_frame->top_field_first = ist->top_field_first;
  1499. best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
  1500. if(best_effort_timestamp != AV_NOPTS_VALUE)
  1501. ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
  1502. if (debug_ts) {
  1503. av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
  1504. "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d \n",
  1505. ist->st->index, av_ts2str(decoded_frame->pts),
  1506. av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
  1507. best_effort_timestamp,
  1508. av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
  1509. decoded_frame->key_frame, decoded_frame->pict_type);
  1510. }
  1511. pkt->size = 0;
  1512. if (ist->st->sample_aspect_ratio.num)
  1513. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  1514. resample_changed = ist->resample_width != decoded_frame->width ||
  1515. ist->resample_height != decoded_frame->height ||
  1516. ist->resample_pix_fmt != decoded_frame->format;
  1517. if (resample_changed) {
  1518. av_log(NULL, AV_LOG_INFO,
  1519. "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
  1520. ist->file_index, ist->st->index,
  1521. ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
  1522. decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
  1523. ist->resample_width = decoded_frame->width;
  1524. ist->resample_height = decoded_frame->height;
  1525. ist->resample_pix_fmt = decoded_frame->format;
  1526. for (i = 0; i < nb_filtergraphs; i++) {
  1527. if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
  1528. configure_filtergraph(filtergraphs[i]) < 0) {
  1529. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1530. exit_program(1);
  1531. }
  1532. }
  1533. }
  1534. frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
  1535. for (i = 0; i < ist->nb_filters; i++) {
  1536. if (!frame_sample_aspect->num)
  1537. *frame_sample_aspect = ist->st->sample_aspect_ratio;
  1538. if (i < ist->nb_filters - 1) {
  1539. f = ist->filter_frame;
  1540. err = av_frame_ref(f, decoded_frame);
  1541. if (err < 0)
  1542. break;
  1543. } else
  1544. f = decoded_frame;
  1545. ret = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f, AV_BUFFERSRC_FLAG_PUSH);
  1546. if (ret == AVERROR_EOF) {
  1547. ret = 0; /* ignore */
  1548. } else if (ret < 0) {
  1549. av_log(NULL, AV_LOG_FATAL,
  1550. "Failed to inject frame into filter network: %s\n", av_err2str(ret));
  1551. exit_program(1);
  1552. }
  1553. }
  1554. av_frame_unref(ist->filter_frame);
  1555. av_frame_unref(decoded_frame);
  1556. return err < 0 ? err : ret;
  1557. }
  1558. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
  1559. {
  1560. AVSubtitle subtitle;
  1561. int i, ret = avcodec_decode_subtitle2(ist->st->codec,
  1562. &subtitle, got_output, pkt);
  1563. if (*got_output || ret<0 || pkt->size)
  1564. decode_error_stat[ret<0] ++;
  1565. if (ret < 0 || !*got_output) {
  1566. if (!pkt->size)
  1567. sub2video_flush(ist);
  1568. return ret;
  1569. }
  1570. if (ist->fix_sub_duration) {
  1571. if (ist->prev_sub.got_output) {
  1572. int end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
  1573. 1000, AV_TIME_BASE);
  1574. if (end < ist->prev_sub.subtitle.end_display_time) {
  1575. av_log(ist->st->codec, AV_LOG_DEBUG,
  1576. "Subtitle duration reduced from %d to %d\n",
  1577. ist->prev_sub.subtitle.end_display_time, end);
  1578. ist->prev_sub.subtitle.end_display_time = end;
  1579. }
  1580. }
  1581. FFSWAP(int, *got_output, ist->prev_sub.got_output);
  1582. FFSWAP(int, ret, ist->prev_sub.ret);
  1583. FFSWAP(AVSubtitle, subtitle, ist->prev_sub.subtitle);
  1584. }
  1585. sub2video_update(ist, &subtitle);
  1586. if (!*got_output || !subtitle.num_rects)
  1587. return ret;
  1588. for (i = 0; i < nb_output_streams; i++) {
  1589. OutputStream *ost = output_streams[i];
  1590. if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
  1591. continue;
  1592. do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle);
  1593. }
  1594. avsubtitle_free(&subtitle);
  1595. return ret;
  1596. }
  1597. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  1598. static int output_packet(InputStream *ist, const AVPacket *pkt)
  1599. {
  1600. int ret = 0, i;
  1601. int got_output = 0;
  1602. AVPacket avpkt;
  1603. if (!ist->saw_first_ts) {
  1604. 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;
  1605. ist->pts = 0;
  1606. if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
  1607. ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
  1608. ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
  1609. }
  1610. ist->saw_first_ts = 1;
  1611. }
  1612. if (ist->next_dts == AV_NOPTS_VALUE)
  1613. ist->next_dts = ist->dts;
  1614. if (ist->next_pts == AV_NOPTS_VALUE)
  1615. ist->next_pts = ist->pts;
  1616. if (pkt == NULL) {
  1617. /* EOF handling */
  1618. av_init_packet(&avpkt);
  1619. avpkt.data = NULL;
  1620. avpkt.size = 0;
  1621. goto handle_eof;
  1622. } else {
  1623. avpkt = *pkt;
  1624. }
  1625. if (pkt->dts != AV_NOPTS_VALUE) {
  1626. ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1627. if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
  1628. ist->next_pts = ist->pts = ist->dts;
  1629. }
  1630. // while we have more to decode or while the decoder did output something on EOF
  1631. while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
  1632. int duration;
  1633. handle_eof:
  1634. ist->pts = ist->next_pts;
  1635. ist->dts = ist->next_dts;
  1636. if (avpkt.size && avpkt.size != pkt->size) {
  1637. av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
  1638. "Multiple frames in a packet from stream %d\n", pkt->stream_index);
  1639. ist->showed_multi_packet_warning = 1;
  1640. }
  1641. switch (ist->st->codec->codec_type) {
  1642. case AVMEDIA_TYPE_AUDIO:
  1643. ret = decode_audio (ist, &avpkt, &got_output);
  1644. break;
  1645. case AVMEDIA_TYPE_VIDEO:
  1646. ret = decode_video (ist, &avpkt, &got_output);
  1647. if (avpkt.duration) {
  1648. duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
  1649. } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
  1650. int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
  1651. duration = ((int64_t)AV_TIME_BASE *
  1652. ist->st->codec->time_base.num * ticks) /
  1653. ist->st->codec->time_base.den;
  1654. } else
  1655. duration = 0;
  1656. if(ist->dts != AV_NOPTS_VALUE && duration) {
  1657. ist->next_dts += duration;
  1658. }else
  1659. ist->next_dts = AV_NOPTS_VALUE;
  1660. if (got_output)
  1661. ist->next_pts += duration; //FIXME the duration is not correct in some cases
  1662. break;
  1663. case AVMEDIA_TYPE_SUBTITLE:
  1664. ret = transcode_subtitles(ist, &avpkt, &got_output);
  1665. break;
  1666. default:
  1667. return -1;
  1668. }
  1669. if (ret < 0)
  1670. return ret;
  1671. avpkt.dts=
  1672. avpkt.pts= AV_NOPTS_VALUE;
  1673. // touch data and size only if not EOF
  1674. if (pkt) {
  1675. if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  1676. ret = avpkt.size;
  1677. avpkt.data += ret;
  1678. avpkt.size -= ret;
  1679. }
  1680. if (!got_output) {
  1681. continue;
  1682. }
  1683. }
  1684. /* handle stream copy */
  1685. if (!ist->decoding_needed) {
  1686. ist->dts = ist->next_dts;
  1687. switch (ist->st->codec->codec_type) {
  1688. case AVMEDIA_TYPE_AUDIO:
  1689. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
  1690. ist->st->codec->sample_rate;
  1691. break;
  1692. case AVMEDIA_TYPE_VIDEO:
  1693. if (ist->framerate.num) {
  1694. // TODO: Remove work-around for c99-to-c89 issue 7
  1695. AVRational time_base_q = AV_TIME_BASE_Q;
  1696. int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
  1697. ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
  1698. } else if (pkt->duration) {
  1699. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  1700. } else if(ist->st->codec->time_base.num != 0) {
  1701. int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
  1702. ist->next_dts += ((int64_t)AV_TIME_BASE *
  1703. ist->st->codec->time_base.num * ticks) /
  1704. ist->st->codec->time_base.den;
  1705. }
  1706. break;
  1707. }
  1708. ist->pts = ist->dts;
  1709. ist->next_pts = ist->next_dts;
  1710. }
  1711. for (i = 0; pkt && i < nb_output_streams; i++) {
  1712. OutputStream *ost = output_streams[i];
  1713. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  1714. continue;
  1715. do_streamcopy(ist, ost, pkt);
  1716. }
  1717. return 0;
  1718. }
  1719. static void print_sdp(void)
  1720. {
  1721. char sdp[16384];
  1722. int i;
  1723. AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
  1724. if (!avc)
  1725. exit_program(1);
  1726. for (i = 0; i < nb_output_files; i++)
  1727. avc[i] = output_files[i]->ctx;
  1728. av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
  1729. printf("SDP:\n%s\n", sdp);
  1730. fflush(stdout);
  1731. av_freep(&avc);
  1732. }
  1733. static int init_input_stream(int ist_index, char *error, int error_len)
  1734. {
  1735. int ret;
  1736. InputStream *ist = input_streams[ist_index];
  1737. if (ist->decoding_needed) {
  1738. AVCodec *codec = ist->dec;
  1739. if (!codec) {
  1740. snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
  1741. avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
  1742. return AVERROR(EINVAL);
  1743. }
  1744. av_opt_set_int(ist->st->codec, "refcounted_frames", 1, 0);
  1745. if (!av_dict_get(ist->opts, "threads", NULL, 0))
  1746. av_dict_set(&ist->opts, "threads", "auto", 0);
  1747. if ((ret = avcodec_open2(ist->st->codec, codec, &ist->opts)) < 0) {
  1748. char errbuf[128];
  1749. if (ret == AVERROR_EXPERIMENTAL)
  1750. abort_codec_experimental(codec, 0);
  1751. av_strerror(ret, errbuf, sizeof(errbuf));
  1752. snprintf(error, error_len,
  1753. "Error while opening decoder for input stream "
  1754. "#%d:%d : %s",
  1755. ist->file_index, ist->st->index, errbuf);
  1756. return ret;
  1757. }
  1758. assert_avoptions(ist->opts);
  1759. }
  1760. ist->next_pts = AV_NOPTS_VALUE;
  1761. ist->next_dts = AV_NOPTS_VALUE;
  1762. ist->is_start = 1;
  1763. return 0;
  1764. }
  1765. static InputStream *get_input_stream(OutputStream *ost)
  1766. {
  1767. if (ost->source_index >= 0)
  1768. return input_streams[ost->source_index];
  1769. return NULL;
  1770. }
  1771. static int compare_int64(const void *a, const void *b)
  1772. {
  1773. int64_t va = *(int64_t *)a, vb = *(int64_t *)b;
  1774. return va < vb ? -1 : va > vb ? +1 : 0;
  1775. }
  1776. static void parse_forced_key_frames(char *kf, OutputStream *ost,
  1777. AVCodecContext *avctx)
  1778. {
  1779. char *p;
  1780. int n = 1, i, size, index = 0;
  1781. int64_t t, *pts;
  1782. for (p = kf; *p; p++)
  1783. if (*p == ',')
  1784. n++;
  1785. size = n;
  1786. pts = av_malloc(sizeof(*pts) * size);
  1787. if (!pts) {
  1788. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  1789. exit_program(1);
  1790. }
  1791. p = kf;
  1792. for (i = 0; i < n; i++) {
  1793. char *next = strchr(p, ',');
  1794. if (next)
  1795. *next++ = 0;
  1796. if (!memcmp(p, "chapters", 8)) {
  1797. AVFormatContext *avf = output_files[ost->file_index]->ctx;
  1798. int j;
  1799. if (avf->nb_chapters > INT_MAX - size ||
  1800. !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
  1801. sizeof(*pts)))) {
  1802. av_log(NULL, AV_LOG_FATAL,
  1803. "Could not allocate forced key frames array.\n");
  1804. exit_program(1);
  1805. }
  1806. t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
  1807. t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1808. for (j = 0; j < avf->nb_chapters; j++) {
  1809. AVChapter *c = avf->chapters[j];
  1810. av_assert1(index < size);
  1811. pts[index++] = av_rescale_q(c->start, c->time_base,
  1812. avctx->time_base) + t;
  1813. }
  1814. } else {
  1815. t = parse_time_or_die("force_key_frames", p, 1);
  1816. av_assert1(index < size);
  1817. pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1818. }
  1819. p = next;
  1820. }
  1821. av_assert0(index == size);
  1822. qsort(pts, size, sizeof(*pts), compare_int64);
  1823. ost->forced_kf_count = size;
  1824. ost->forced_kf_pts = pts;
  1825. }
  1826. static void report_new_stream(int input_index, AVPacket *pkt)
  1827. {
  1828. InputFile *file = input_files[input_index];
  1829. AVStream *st = file->ctx->streams[pkt->stream_index];
  1830. if (pkt->stream_index < file->nb_streams_warn)
  1831. return;
  1832. av_log(file->ctx, AV_LOG_WARNING,
  1833. "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
  1834. av_get_media_type_string(st->codec->codec_type),
  1835. input_index, pkt->stream_index,
  1836. pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
  1837. file->nb_streams_warn = pkt->stream_index + 1;
  1838. }
  1839. static int transcode_init(void)
  1840. {
  1841. int ret = 0, i, j, k;
  1842. AVFormatContext *oc;
  1843. AVCodecContext *codec;
  1844. OutputStream *ost;
  1845. InputStream *ist;
  1846. char error[1024];
  1847. int want_sdp = 1;
  1848. for (i = 0; i < nb_filtergraphs; i++) {
  1849. FilterGraph *fg = filtergraphs[i];
  1850. for (j = 0; j < fg->nb_outputs; j++) {
  1851. OutputFilter *ofilter = fg->outputs[j];
  1852. if (!ofilter->ost || ofilter->ost->source_index >= 0)
  1853. continue;
  1854. if (fg->nb_inputs != 1)
  1855. continue;
  1856. for (k = nb_input_streams-1; k >= 0 ; k--)
  1857. if (fg->inputs[0]->ist == input_streams[k])
  1858. break;
  1859. ofilter->ost->source_index = k;
  1860. }
  1861. }
  1862. /* init framerate emulation */
  1863. for (i = 0; i < nb_input_files; i++) {
  1864. InputFile *ifile = input_files[i];
  1865. if (ifile->rate_emu)
  1866. for (j = 0; j < ifile->nb_streams; j++)
  1867. input_streams[j + ifile->ist_index]->start = av_gettime();
  1868. }
  1869. /* output stream init */
  1870. for (i = 0; i < nb_output_files; i++) {
  1871. oc = output_files[i]->ctx;
  1872. if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
  1873. av_dump_format(oc, i, oc->filename, 1);
  1874. av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
  1875. return AVERROR(EINVAL);
  1876. }
  1877. }
  1878. /* init complex filtergraphs */
  1879. for (i = 0; i < nb_filtergraphs; i++)
  1880. if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
  1881. return ret;
  1882. /* for each output stream, we compute the right encoding parameters */
  1883. for (i = 0; i < nb_output_streams; i++) {
  1884. AVCodecContext *icodec = NULL;
  1885. ost = output_streams[i];
  1886. oc = output_files[ost->file_index]->ctx;
  1887. ist = get_input_stream(ost);
  1888. if (ost->attachment_filename)
  1889. continue;
  1890. codec = ost->st->codec;
  1891. if (ist) {
  1892. icodec = ist->st->codec;
  1893. ost->st->disposition = ist->st->disposition;
  1894. codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
  1895. codec->chroma_sample_location = icodec->chroma_sample_location;
  1896. } else {
  1897. for (j=0; j<oc->nb_streams; j++) {
  1898. AVStream *st = oc->streams[j];
  1899. if (st != ost->st && st->codec->codec_type == codec->codec_type)
  1900. break;
  1901. }
  1902. if (j == oc->nb_streams)
  1903. if (codec->codec_type == AVMEDIA_TYPE_AUDIO || codec->codec_type == AVMEDIA_TYPE_VIDEO)
  1904. ost->st->disposition = AV_DISPOSITION_DEFAULT;
  1905. }
  1906. if (ost->stream_copy) {
  1907. AVRational sar;
  1908. uint64_t extra_size;
  1909. av_assert0(ist && !ost->filter);
  1910. extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
  1911. if (extra_size > INT_MAX) {
  1912. return AVERROR(EINVAL);
  1913. }
  1914. /* if stream_copy is selected, no need to decode or encode */
  1915. codec->codec_id = icodec->codec_id;
  1916. codec->codec_type = icodec->codec_type;
  1917. if (!codec->codec_tag) {
  1918. unsigned int codec_tag;
  1919. if (!oc->oformat->codec_tag ||
  1920. av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
  1921. !av_codec_get_tag2(oc->oformat->codec_tag, icodec->codec_id, &codec_tag))
  1922. codec->codec_tag = icodec->codec_tag;
  1923. }
  1924. codec->bit_rate = icodec->bit_rate;
  1925. codec->rc_max_rate = icodec->rc_max_rate;
  1926. codec->rc_buffer_size = icodec->rc_buffer_size;
  1927. codec->field_order = icodec->field_order;
  1928. codec->extradata = av_mallocz(extra_size);
  1929. if (!codec->extradata) {
  1930. return AVERROR(ENOMEM);
  1931. }
  1932. memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
  1933. codec->extradata_size= icodec->extradata_size;
  1934. codec->bits_per_coded_sample = icodec->bits_per_coded_sample;
  1935. codec->time_base = ist->st->time_base;
  1936. /*
  1937. * Avi is a special case here because it supports variable fps but
  1938. * having the fps and timebase differe significantly adds quite some
  1939. * overhead
  1940. */
  1941. if(!strcmp(oc->oformat->name, "avi")) {
  1942. if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
  1943. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
  1944. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(icodec->time_base)
  1945. && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(icodec->time_base) < 1.0/500
  1946. || copy_tb==2){
  1947. codec->time_base.num = ist->st->r_frame_rate.den;
  1948. codec->time_base.den = 2*ist->st->r_frame_rate.num;
  1949. codec->ticks_per_frame = 2;
  1950. } else if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
  1951. && av_q2d(ist->st->time_base) < 1.0/500
  1952. || copy_tb==0){
  1953. codec->time_base = icodec->time_base;
  1954. codec->time_base.num *= icodec->ticks_per_frame;
  1955. codec->time_base.den *= 2;
  1956. codec->ticks_per_frame = 2;
  1957. }
  1958. } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
  1959. && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
  1960. && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
  1961. && strcmp(oc->oformat->name, "f4v")
  1962. ) {
  1963. if( copy_tb<0 && icodec->time_base.den
  1964. && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
  1965. && av_q2d(ist->st->time_base) < 1.0/500
  1966. || copy_tb==0){
  1967. codec->time_base = icodec->time_base;
  1968. codec->time_base.num *= icodec->ticks_per_frame;
  1969. }
  1970. }
  1971. if ( codec->codec_tag == AV_RL32("tmcd")
  1972. && icodec->time_base.num < icodec->time_base.den
  1973. && icodec->time_base.num > 0
  1974. && 121LL*icodec->time_base.num > icodec->time_base.den) {
  1975. codec->time_base = icodec->time_base;
  1976. }
  1977. if (ist && !ost->frame_rate.num)
  1978. ost->frame_rate = ist->framerate;
  1979. if(ost->frame_rate.num)
  1980. codec->time_base = av_inv_q(ost->frame_rate);
  1981. av_reduce(&codec->time_base.num, &codec->time_base.den,
  1982. codec->time_base.num, codec->time_base.den, INT_MAX);
  1983. ost->parser = av_parser_init(codec->codec_id);
  1984. switch (codec->codec_type) {
  1985. case AVMEDIA_TYPE_AUDIO:
  1986. if (audio_volume != 256) {
  1987. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
  1988. exit_program(1);
  1989. }
  1990. codec->channel_layout = icodec->channel_layout;
  1991. codec->sample_rate = icodec->sample_rate;
  1992. codec->channels = icodec->channels;
  1993. codec->frame_size = icodec->frame_size;
  1994. codec->audio_service_type = icodec->audio_service_type;
  1995. codec->block_align = icodec->block_align;
  1996. if((codec->block_align == 1 || codec->block_align == 1152 || codec->block_align == 576) && codec->codec_id == AV_CODEC_ID_MP3)
  1997. codec->block_align= 0;
  1998. if(codec->codec_id == AV_CODEC_ID_AC3)
  1999. codec->block_align= 0;
  2000. break;
  2001. case AVMEDIA_TYPE_VIDEO:
  2002. codec->pix_fmt = icodec->pix_fmt;
  2003. codec->width = icodec->width;
  2004. codec->height = icodec->height;
  2005. codec->has_b_frames = icodec->has_b_frames;
  2006. if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
  2007. sar =
  2008. av_mul_q(ost->frame_aspect_ratio,
  2009. (AVRational){ codec->height, codec->width });
  2010. av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
  2011. "with stream copy may produce invalid files\n");
  2012. }
  2013. else if (ist->st->sample_aspect_ratio.num)
  2014. sar = ist->st->sample_aspect_ratio;
  2015. else
  2016. sar = icodec->sample_aspect_ratio;
  2017. ost->st->sample_aspect_ratio = codec->sample_aspect_ratio = sar;
  2018. ost->st->avg_frame_rate = ist->st->avg_frame_rate;
  2019. break;
  2020. case AVMEDIA_TYPE_SUBTITLE:
  2021. codec->width = icodec->width;
  2022. codec->height = icodec->height;
  2023. break;
  2024. case AVMEDIA_TYPE_DATA:
  2025. case AVMEDIA_TYPE_ATTACHMENT:
  2026. break;
  2027. default:
  2028. abort();
  2029. }
  2030. } else {
  2031. if (!ost->enc)
  2032. ost->enc = avcodec_find_encoder(codec->codec_id);
  2033. if (!ost->enc) {
  2034. /* should only happen when a default codec is not present. */
  2035. snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
  2036. avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
  2037. ret = AVERROR(EINVAL);
  2038. goto dump_format;
  2039. }
  2040. if (ist)
  2041. ist->decoding_needed++;
  2042. ost->encoding_needed = 1;
  2043. if (!ost->filter &&
  2044. (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  2045. codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
  2046. FilterGraph *fg;
  2047. fg = init_simple_filtergraph(ist, ost);
  2048. if (configure_filtergraph(fg)) {
  2049. av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
  2050. exit_program(1);
  2051. }
  2052. }
  2053. if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  2054. if (ost->filter && !ost->frame_rate.num)
  2055. ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
  2056. if (ist && !ost->frame_rate.num)
  2057. ost->frame_rate = ist->framerate;
  2058. if (ist && !ost->frame_rate.num)
  2059. ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
  2060. // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
  2061. if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
  2062. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
  2063. ost->frame_rate = ost->enc->supported_framerates[idx];
  2064. }
  2065. }
  2066. switch (codec->codec_type) {
  2067. case AVMEDIA_TYPE_AUDIO:
  2068. codec->sample_fmt = ost->filter->filter->inputs[0]->format;
  2069. codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
  2070. codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
  2071. codec->channels = avfilter_link_get_channels(ost->filter->filter->inputs[0]);
  2072. codec->time_base = (AVRational){ 1, codec->sample_rate };
  2073. break;
  2074. case AVMEDIA_TYPE_VIDEO:
  2075. codec->time_base = av_inv_q(ost->frame_rate);
  2076. if (ost->filter && !(codec->time_base.num && codec->time_base.den))
  2077. codec->time_base = ost->filter->filter->inputs[0]->time_base;
  2078. if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
  2079. && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
  2080. av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
  2081. "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
  2082. }
  2083. for (j = 0; j < ost->forced_kf_count; j++)
  2084. ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
  2085. AV_TIME_BASE_Q,
  2086. codec->time_base);
  2087. codec->width = ost->filter->filter->inputs[0]->w;
  2088. codec->height = ost->filter->filter->inputs[0]->h;
  2089. codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  2090. ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
  2091. av_mul_q(ost->frame_aspect_ratio, (AVRational){ codec->height, codec->width }) :
  2092. ost->filter->filter->inputs[0]->sample_aspect_ratio;
  2093. if (!strncmp(ost->enc->name, "libx264", 7) &&
  2094. codec->pix_fmt == AV_PIX_FMT_NONE &&
  2095. ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
  2096. av_log(NULL, AV_LOG_WARNING,
  2097. "No pixel format specified, %s for H.264 encoding chosen.\n"
  2098. "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
  2099. av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
  2100. if (!strncmp(ost->enc->name, "mpeg2video", 10) &&
  2101. codec->pix_fmt == AV_PIX_FMT_NONE &&
  2102. ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
  2103. av_log(NULL, AV_LOG_WARNING,
  2104. "No pixel format specified, %s for MPEG-2 encoding chosen.\n"
  2105. "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
  2106. av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
  2107. codec->pix_fmt = ost->filter->filter->inputs[0]->format;
  2108. if (!icodec ||
  2109. codec->width != icodec->width ||
  2110. codec->height != icodec->height ||
  2111. codec->pix_fmt != icodec->pix_fmt) {
  2112. codec->bits_per_raw_sample = frame_bits_per_raw_sample;
  2113. }
  2114. if (ost->forced_keyframes) {
  2115. if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
  2116. ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
  2117. forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
  2118. if (ret < 0) {
  2119. av_log(NULL, AV_LOG_ERROR,
  2120. "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
  2121. return ret;
  2122. }
  2123. ost->forced_keyframes_expr_const_values[FKF_N] = 0;
  2124. ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
  2125. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
  2126. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
  2127. } else {
  2128. parse_forced_key_frames(ost->forced_keyframes, ost, ost->st->codec);
  2129. }
  2130. }
  2131. break;
  2132. case AVMEDIA_TYPE_SUBTITLE:
  2133. codec->time_base = (AVRational){1, 1000};
  2134. if (!codec->width) {
  2135. codec->width = input_streams[ost->source_index]->st->codec->width;
  2136. codec->height = input_streams[ost->source_index]->st->codec->height;
  2137. }
  2138. break;
  2139. default:
  2140. abort();
  2141. break;
  2142. }
  2143. /* two pass mode */
  2144. if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
  2145. char logfilename[1024];
  2146. FILE *f;
  2147. snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
  2148. ost->logfile_prefix ? ost->logfile_prefix :
  2149. DEFAULT_PASS_LOGFILENAME_PREFIX,
  2150. i);
  2151. if (!strcmp(ost->enc->name, "libx264")) {
  2152. av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
  2153. } else {
  2154. if (codec->flags & CODEC_FLAG_PASS2) {
  2155. char *logbuffer;
  2156. size_t logbuffer_size;
  2157. if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
  2158. av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
  2159. logfilename);
  2160. exit_program(1);
  2161. }
  2162. codec->stats_in = logbuffer;
  2163. }
  2164. if (codec->flags & CODEC_FLAG_PASS1) {
  2165. f = fopen(logfilename, "wb");
  2166. if (!f) {
  2167. av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
  2168. logfilename, strerror(errno));
  2169. exit_program(1);
  2170. }
  2171. ost->logfile = f;
  2172. }
  2173. }
  2174. }
  2175. }
  2176. }
  2177. /* open each encoder */
  2178. for (i = 0; i < nb_output_streams; i++) {
  2179. ost = output_streams[i];
  2180. if (ost->encoding_needed) {
  2181. AVCodec *codec = ost->enc;
  2182. AVCodecContext *dec = NULL;
  2183. if ((ist = get_input_stream(ost)))
  2184. dec = ist->st->codec;
  2185. if (dec && dec->subtitle_header) {
  2186. /* ASS code assumes this buffer is null terminated so add extra byte. */
  2187. ost->st->codec->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
  2188. if (!ost->st->codec->subtitle_header) {
  2189. ret = AVERROR(ENOMEM);
  2190. goto dump_format;
  2191. }
  2192. memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  2193. ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
  2194. }
  2195. if (!av_dict_get(ost->opts, "threads", NULL, 0))
  2196. av_dict_set(&ost->opts, "threads", "auto", 0);
  2197. if ((ret = avcodec_open2(ost->st->codec, codec, &ost->opts)) < 0) {
  2198. if (ret == AVERROR_EXPERIMENTAL)
  2199. abort_codec_experimental(codec, 1);
  2200. snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
  2201. ost->file_index, ost->index);
  2202. goto dump_format;
  2203. }
  2204. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  2205. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  2206. av_buffersink_set_frame_size(ost->filter->filter,
  2207. ost->st->codec->frame_size);
  2208. assert_avoptions(ost->opts);
  2209. if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
  2210. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  2211. " It takes bits/s as argument, not kbits/s\n");
  2212. extra_size += ost->st->codec->extradata_size;
  2213. } else {
  2214. av_opt_set_dict(ost->st->codec, &ost->opts);
  2215. }
  2216. }
  2217. /* init input streams */
  2218. for (i = 0; i < nb_input_streams; i++)
  2219. if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
  2220. for (i = 0; i < nb_output_streams; i++) {
  2221. ost = output_streams[i];
  2222. avcodec_close(ost->st->codec);
  2223. }
  2224. goto dump_format;
  2225. }
  2226. /* discard unused programs */
  2227. for (i = 0; i < nb_input_files; i++) {
  2228. InputFile *ifile = input_files[i];
  2229. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  2230. AVProgram *p = ifile->ctx->programs[j];
  2231. int discard = AVDISCARD_ALL;
  2232. for (k = 0; k < p->nb_stream_indexes; k++)
  2233. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
  2234. discard = AVDISCARD_DEFAULT;
  2235. break;
  2236. }
  2237. p->discard = discard;
  2238. }
  2239. }
  2240. /* open files and write file headers */
  2241. for (i = 0; i < nb_output_files; i++) {
  2242. oc = output_files[i]->ctx;
  2243. oc->interrupt_callback = int_cb;
  2244. if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
  2245. char errbuf[128];
  2246. av_strerror(ret, errbuf, sizeof(errbuf));
  2247. snprintf(error, sizeof(error),
  2248. "Could not write header for output file #%d "
  2249. "(incorrect codec parameters ?): %s",
  2250. i, errbuf);
  2251. ret = AVERROR(EINVAL);
  2252. goto dump_format;
  2253. }
  2254. // assert_avoptions(output_files[i]->opts);
  2255. if (strcmp(oc->oformat->name, "rtp")) {
  2256. want_sdp = 0;
  2257. }
  2258. }
  2259. dump_format:
  2260. /* dump the file output parameters - cannot be done before in case
  2261. of stream copy */
  2262. for (i = 0; i < nb_output_files; i++) {
  2263. av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
  2264. }
  2265. /* dump the stream mapping */
  2266. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  2267. for (i = 0; i < nb_input_streams; i++) {
  2268. ist = input_streams[i];
  2269. for (j = 0; j < ist->nb_filters; j++) {
  2270. if (ist->filters[j]->graph->graph_desc) {
  2271. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  2272. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
  2273. ist->filters[j]->name);
  2274. if (nb_filtergraphs > 1)
  2275. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  2276. av_log(NULL, AV_LOG_INFO, "\n");
  2277. }
  2278. }
  2279. }
  2280. for (i = 0; i < nb_output_streams; i++) {
  2281. ost = output_streams[i];
  2282. if (ost->attachment_filename) {
  2283. /* an attached file */
  2284. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  2285. ost->attachment_filename, ost->file_index, ost->index);
  2286. continue;
  2287. }
  2288. if (ost->filter && ost->filter->graph->graph_desc) {
  2289. /* output from a complex graph */
  2290. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  2291. if (nb_filtergraphs > 1)
  2292. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  2293. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  2294. ost->index, ost->enc ? ost->enc->name : "?");
  2295. continue;
  2296. }
  2297. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  2298. input_streams[ost->source_index]->file_index,
  2299. input_streams[ost->source_index]->st->index,
  2300. ost->file_index,
  2301. ost->index);
  2302. if (ost->sync_ist != input_streams[ost->source_index])
  2303. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  2304. ost->sync_ist->file_index,
  2305. ost->sync_ist->st->index);
  2306. if (ost->stream_copy)
  2307. av_log(NULL, AV_LOG_INFO, " (copy)");
  2308. else
  2309. av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
  2310. input_streams[ost->source_index]->dec->name : "?",
  2311. ost->enc ? ost->enc->name : "?");
  2312. av_log(NULL, AV_LOG_INFO, "\n");
  2313. }
  2314. if (ret) {
  2315. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  2316. return ret;
  2317. }
  2318. if (want_sdp) {
  2319. print_sdp();
  2320. }
  2321. return 0;
  2322. }
  2323. /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
  2324. static int need_output(void)
  2325. {
  2326. int i;
  2327. for (i = 0; i < nb_output_streams; i++) {
  2328. OutputStream *ost = output_streams[i];
  2329. OutputFile *of = output_files[ost->file_index];
  2330. AVFormatContext *os = output_files[ost->file_index]->ctx;
  2331. if (ost->finished ||
  2332. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  2333. continue;
  2334. if (ost->frame_number >= ost->max_frames) {
  2335. int j;
  2336. for (j = 0; j < of->ctx->nb_streams; j++)
  2337. close_output_stream(output_streams[of->ost_index + j]);
  2338. continue;
  2339. }
  2340. return 1;
  2341. }
  2342. return 0;
  2343. }
  2344. /**
  2345. * Select the output stream to process.
  2346. *
  2347. * @return selected output stream, or NULL if none available
  2348. */
  2349. static OutputStream *choose_output(void)
  2350. {
  2351. int i;
  2352. int64_t opts_min = INT64_MAX;
  2353. OutputStream *ost_min = NULL;
  2354. for (i = 0; i < nb_output_streams; i++) {
  2355. OutputStream *ost = output_streams[i];
  2356. int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
  2357. AV_TIME_BASE_Q);
  2358. if (!ost->unavailable && !ost->finished && opts < opts_min) {
  2359. opts_min = opts;
  2360. ost_min = ost;
  2361. }
  2362. }
  2363. return ost_min;
  2364. }
  2365. static int check_keyboard_interaction(int64_t cur_time)
  2366. {
  2367. int i, ret, key;
  2368. static int64_t last_time;
  2369. if (received_nb_signals)
  2370. return AVERROR_EXIT;
  2371. /* read_key() returns 0 on EOF */
  2372. if(cur_time - last_time >= 100000 && !run_as_daemon){
  2373. key = read_key();
  2374. last_time = cur_time;
  2375. }else
  2376. key = -1;
  2377. if (key == 'q')
  2378. return AVERROR_EXIT;
  2379. if (key == '+') av_log_set_level(av_log_get_level()+10);
  2380. if (key == '-') av_log_set_level(av_log_get_level()-10);
  2381. if (key == 's') qp_hist ^= 1;
  2382. if (key == 'h'){
  2383. if (do_hex_dump){
  2384. do_hex_dump = do_pkt_dump = 0;
  2385. } else if(do_pkt_dump){
  2386. do_hex_dump = 1;
  2387. } else
  2388. do_pkt_dump = 1;
  2389. av_log_set_level(AV_LOG_DEBUG);
  2390. }
  2391. if (key == 'c' || key == 'C'){
  2392. char buf[4096], target[64], command[256], arg[256] = {0};
  2393. double time;
  2394. int k, n = 0;
  2395. fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
  2396. i = 0;
  2397. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  2398. if (k > 0)
  2399. buf[i++] = k;
  2400. buf[i] = 0;
  2401. if (k > 0 &&
  2402. (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
  2403. av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
  2404. target, time, command, arg);
  2405. for (i = 0; i < nb_filtergraphs; i++) {
  2406. FilterGraph *fg = filtergraphs[i];
  2407. if (fg->graph) {
  2408. if (time < 0) {
  2409. ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
  2410. key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
  2411. fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
  2412. } else if (key == 'c') {
  2413. fprintf(stderr, "Queing commands only on filters supporting the specific command is unsupported\n");
  2414. ret = AVERROR_PATCHWELCOME;
  2415. } else {
  2416. ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
  2417. }
  2418. }
  2419. }
  2420. } else {
  2421. av_log(NULL, AV_LOG_ERROR,
  2422. "Parse error, at least 3 arguments were expected, "
  2423. "only %d given in string '%s'\n", n, buf);
  2424. }
  2425. }
  2426. if (key == 'd' || key == 'D'){
  2427. int debug=0;
  2428. if(key == 'D') {
  2429. debug = input_streams[0]->st->codec->debug<<1;
  2430. if(!debug) debug = 1;
  2431. while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
  2432. debug += debug;
  2433. }else
  2434. if(scanf("%d", &debug)!=1)
  2435. fprintf(stderr,"error parsing debug value\n");
  2436. for(i=0;i<nb_input_streams;i++) {
  2437. input_streams[i]->st->codec->debug = debug;
  2438. }
  2439. for(i=0;i<nb_output_streams;i++) {
  2440. OutputStream *ost = output_streams[i];
  2441. ost->st->codec->debug = debug;
  2442. }
  2443. if(debug) av_log_set_level(AV_LOG_DEBUG);
  2444. fprintf(stderr,"debug=%d\n", debug);
  2445. }
  2446. if (key == '?'){
  2447. fprintf(stderr, "key function\n"
  2448. "? show this help\n"
  2449. "+ increase verbosity\n"
  2450. "- decrease verbosity\n"
  2451. "c Send command to first matching filter supporting it\n"
  2452. "C Send/Que command to all matching filters\n"
  2453. "D cycle through available debug modes\n"
  2454. "h dump packets/hex press to cycle through the 3 states\n"
  2455. "q quit\n"
  2456. "s Show QP histogram\n"
  2457. );
  2458. }
  2459. return 0;
  2460. }
  2461. #if HAVE_PTHREADS
  2462. static void *input_thread(void *arg)
  2463. {
  2464. InputFile *f = arg;
  2465. int ret = 0;
  2466. while (!transcoding_finished && ret >= 0) {
  2467. AVPacket pkt;
  2468. ret = av_read_frame(f->ctx, &pkt);
  2469. if (ret == AVERROR(EAGAIN)) {
  2470. av_usleep(10000);
  2471. ret = 0;
  2472. continue;
  2473. } else if (ret < 0)
  2474. break;
  2475. pthread_mutex_lock(&f->fifo_lock);
  2476. while (!av_fifo_space(f->fifo))
  2477. pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
  2478. av_dup_packet(&pkt);
  2479. av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
  2480. pthread_mutex_unlock(&f->fifo_lock);
  2481. }
  2482. f->finished = 1;
  2483. return NULL;
  2484. }
  2485. static void free_input_threads(void)
  2486. {
  2487. int i;
  2488. if (nb_input_files == 1)
  2489. return;
  2490. transcoding_finished = 1;
  2491. for (i = 0; i < nb_input_files; i++) {
  2492. InputFile *f = input_files[i];
  2493. AVPacket pkt;
  2494. if (!f->fifo || f->joined)
  2495. continue;
  2496. pthread_mutex_lock(&f->fifo_lock);
  2497. while (av_fifo_size(f->fifo)) {
  2498. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2499. av_free_packet(&pkt);
  2500. }
  2501. pthread_cond_signal(&f->fifo_cond);
  2502. pthread_mutex_unlock(&f->fifo_lock);
  2503. pthread_join(f->thread, NULL);
  2504. f->joined = 1;
  2505. while (av_fifo_size(f->fifo)) {
  2506. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2507. av_free_packet(&pkt);
  2508. }
  2509. av_fifo_free(f->fifo);
  2510. }
  2511. }
  2512. static int init_input_threads(void)
  2513. {
  2514. int i, ret;
  2515. if (nb_input_files == 1)
  2516. return 0;
  2517. for (i = 0; i < nb_input_files; i++) {
  2518. InputFile *f = input_files[i];
  2519. if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
  2520. return AVERROR(ENOMEM);
  2521. pthread_mutex_init(&f->fifo_lock, NULL);
  2522. pthread_cond_init (&f->fifo_cond, NULL);
  2523. if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
  2524. return AVERROR(ret);
  2525. }
  2526. return 0;
  2527. }
  2528. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
  2529. {
  2530. int ret = 0;
  2531. pthread_mutex_lock(&f->fifo_lock);
  2532. if (av_fifo_size(f->fifo)) {
  2533. av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
  2534. pthread_cond_signal(&f->fifo_cond);
  2535. } else {
  2536. if (f->finished)
  2537. ret = AVERROR_EOF;
  2538. else
  2539. ret = AVERROR(EAGAIN);
  2540. }
  2541. pthread_mutex_unlock(&f->fifo_lock);
  2542. return ret;
  2543. }
  2544. #endif
  2545. static int get_input_packet(InputFile *f, AVPacket *pkt)
  2546. {
  2547. if (f->rate_emu) {
  2548. int i;
  2549. for (i = 0; i < f->nb_streams; i++) {
  2550. InputStream *ist = input_streams[f->ist_index + i];
  2551. int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
  2552. int64_t now = av_gettime() - ist->start;
  2553. if (pts > now)
  2554. return AVERROR(EAGAIN);
  2555. }
  2556. }
  2557. #if HAVE_PTHREADS
  2558. if (nb_input_files > 1)
  2559. return get_input_packet_mt(f, pkt);
  2560. #endif
  2561. return av_read_frame(f->ctx, pkt);
  2562. }
  2563. static int got_eagain(void)
  2564. {
  2565. int i;
  2566. for (i = 0; i < nb_output_streams; i++)
  2567. if (output_streams[i]->unavailable)
  2568. return 1;
  2569. return 0;
  2570. }
  2571. static void reset_eagain(void)
  2572. {
  2573. int i;
  2574. for (i = 0; i < nb_input_files; i++)
  2575. input_files[i]->eagain = 0;
  2576. for (i = 0; i < nb_output_streams; i++)
  2577. output_streams[i]->unavailable = 0;
  2578. }
  2579. /*
  2580. * Return
  2581. * - 0 -- one packet was read and processed
  2582. * - AVERROR(EAGAIN) -- no packets were available for selected file,
  2583. * this function should be called again
  2584. * - AVERROR_EOF -- this function should not be called again
  2585. */
  2586. static int process_input(int file_index)
  2587. {
  2588. InputFile *ifile = input_files[file_index];
  2589. AVFormatContext *is;
  2590. InputStream *ist;
  2591. AVPacket pkt;
  2592. int ret, i, j;
  2593. is = ifile->ctx;
  2594. ret = get_input_packet(ifile, &pkt);
  2595. if (ret == AVERROR(EAGAIN)) {
  2596. ifile->eagain = 1;
  2597. return ret;
  2598. }
  2599. if (ret < 0) {
  2600. if (ret != AVERROR_EOF) {
  2601. print_error(is->filename, ret);
  2602. if (exit_on_error)
  2603. exit_program(1);
  2604. }
  2605. ifile->eof_reached = 1;
  2606. for (i = 0; i < ifile->nb_streams; i++) {
  2607. ist = input_streams[ifile->ist_index + i];
  2608. if (ist->decoding_needed)
  2609. output_packet(ist, NULL);
  2610. /* mark all outputs that don't go through lavfi as finished */
  2611. for (j = 0; j < nb_output_streams; j++) {
  2612. OutputStream *ost = output_streams[j];
  2613. if (ost->source_index == ifile->ist_index + i &&
  2614. (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
  2615. close_output_stream(ost);
  2616. }
  2617. }
  2618. return AVERROR(EAGAIN);
  2619. }
  2620. reset_eagain();
  2621. if (do_pkt_dump) {
  2622. av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
  2623. is->streams[pkt.stream_index]);
  2624. }
  2625. /* the following test is needed in case new streams appear
  2626. dynamically in stream : we ignore them */
  2627. if (pkt.stream_index >= ifile->nb_streams) {
  2628. report_new_stream(file_index, &pkt);
  2629. goto discard_packet;
  2630. }
  2631. ist = input_streams[ifile->ist_index + pkt.stream_index];
  2632. if (ist->discard)
  2633. goto discard_packet;
  2634. if (debug_ts) {
  2635. av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
  2636. "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",
  2637. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
  2638. av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
  2639. av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
  2640. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  2641. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  2642. av_ts2str(input_files[ist->file_index]->ts_offset),
  2643. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  2644. }
  2645. if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
  2646. int64_t stime, stime2;
  2647. // Correcting starttime based on the enabled streams
  2648. // 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.
  2649. // so we instead do it here as part of discontinuity handling
  2650. if ( ist->next_dts == AV_NOPTS_VALUE
  2651. && ifile->ts_offset == -is->start_time
  2652. && (is->iformat->flags & AVFMT_TS_DISCONT)) {
  2653. int64_t new_start_time = INT64_MAX;
  2654. for (i=0; i<is->nb_streams; i++) {
  2655. AVStream *st = is->streams[i];
  2656. if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
  2657. continue;
  2658. new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
  2659. }
  2660. if (new_start_time > is->start_time) {
  2661. av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
  2662. ifile->ts_offset = -new_start_time;
  2663. }
  2664. }
  2665. stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
  2666. stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
  2667. ist->wrap_correction_done = 1;
  2668. if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  2669. pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
  2670. ist->wrap_correction_done = 0;
  2671. }
  2672. if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  2673. pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
  2674. ist->wrap_correction_done = 0;
  2675. }
  2676. }
  2677. if (pkt.dts != AV_NOPTS_VALUE)
  2678. pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2679. if (pkt.pts != AV_NOPTS_VALUE)
  2680. pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2681. if (pkt.pts != AV_NOPTS_VALUE)
  2682. pkt.pts *= ist->ts_scale;
  2683. if (pkt.dts != AV_NOPTS_VALUE)
  2684. pkt.dts *= ist->ts_scale;
  2685. if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
  2686. && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
  2687. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2688. int64_t delta = pkt_dts - ifile->last_ts;
  2689. if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  2690. (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
  2691. ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)){
  2692. ifile->ts_offset -= delta;
  2693. av_log(NULL, AV_LOG_DEBUG,
  2694. "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  2695. delta, ifile->ts_offset);
  2696. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2697. if (pkt.pts != AV_NOPTS_VALUE)
  2698. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2699. }
  2700. }
  2701. if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
  2702. !copy_ts) {
  2703. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2704. int64_t delta = pkt_dts - ist->next_dts;
  2705. if (is->iformat->flags & AVFMT_TS_DISCONT) {
  2706. if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  2707. (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
  2708. ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
  2709. pkt_dts + AV_TIME_BASE/10 < ist->pts){
  2710. ifile->ts_offset -= delta;
  2711. av_log(NULL, AV_LOG_DEBUG,
  2712. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  2713. delta, ifile->ts_offset);
  2714. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2715. if (pkt.pts != AV_NOPTS_VALUE)
  2716. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2717. }
  2718. } else {
  2719. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  2720. (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
  2721. ) {
  2722. av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
  2723. pkt.dts = AV_NOPTS_VALUE;
  2724. }
  2725. if (pkt.pts != AV_NOPTS_VALUE){
  2726. int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
  2727. delta = pkt_pts - ist->next_dts;
  2728. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  2729. (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
  2730. ) {
  2731. av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
  2732. pkt.pts = AV_NOPTS_VALUE;
  2733. }
  2734. }
  2735. }
  2736. }
  2737. if (pkt.dts != AV_NOPTS_VALUE)
  2738. ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2739. if (debug_ts) {
  2740. 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",
  2741. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
  2742. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  2743. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  2744. av_ts2str(input_files[ist->file_index]->ts_offset),
  2745. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  2746. }
  2747. sub2video_heartbeat(ist, pkt.pts);
  2748. ret = output_packet(ist, &pkt);
  2749. if (ret < 0) {
  2750. char buf[128];
  2751. av_strerror(ret, buf, sizeof(buf));
  2752. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
  2753. ist->file_index, ist->st->index, buf);
  2754. if (exit_on_error)
  2755. exit_program(1);
  2756. }
  2757. discard_packet:
  2758. av_free_packet(&pkt);
  2759. return 0;
  2760. }
  2761. /**
  2762. * Perform a step of transcoding for the specified filter graph.
  2763. *
  2764. * @param[in] graph filter graph to consider
  2765. * @param[out] best_ist input stream where a frame would allow to continue
  2766. * @return 0 for success, <0 for error
  2767. */
  2768. static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
  2769. {
  2770. int i, ret;
  2771. int nb_requests, nb_requests_max = 0;
  2772. InputFilter *ifilter;
  2773. InputStream *ist;
  2774. *best_ist = NULL;
  2775. ret = avfilter_graph_request_oldest(graph->graph);
  2776. if (ret >= 0)
  2777. return reap_filters();
  2778. if (ret == AVERROR_EOF) {
  2779. ret = reap_filters();
  2780. for (i = 0; i < graph->nb_outputs; i++)
  2781. close_output_stream(graph->outputs[i]->ost);
  2782. return ret;
  2783. }
  2784. if (ret != AVERROR(EAGAIN))
  2785. return ret;
  2786. for (i = 0; i < graph->nb_inputs; i++) {
  2787. ifilter = graph->inputs[i];
  2788. ist = ifilter->ist;
  2789. if (input_files[ist->file_index]->eagain ||
  2790. input_files[ist->file_index]->eof_reached)
  2791. continue;
  2792. nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
  2793. if (nb_requests > nb_requests_max) {
  2794. nb_requests_max = nb_requests;
  2795. *best_ist = ist;
  2796. }
  2797. }
  2798. if (!*best_ist)
  2799. for (i = 0; i < graph->nb_outputs; i++)
  2800. graph->outputs[i]->ost->unavailable = 1;
  2801. return 0;
  2802. }
  2803. /**
  2804. * Run a single step of transcoding.
  2805. *
  2806. * @return 0 for success, <0 for error
  2807. */
  2808. static int transcode_step(void)
  2809. {
  2810. OutputStream *ost;
  2811. InputStream *ist;
  2812. int ret;
  2813. ost = choose_output();
  2814. if (!ost) {
  2815. if (got_eagain()) {
  2816. reset_eagain();
  2817. av_usleep(10000);
  2818. return 0;
  2819. }
  2820. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
  2821. return AVERROR_EOF;
  2822. }
  2823. if (ost->filter) {
  2824. if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
  2825. return ret;
  2826. if (!ist)
  2827. return 0;
  2828. } else {
  2829. av_assert0(ost->source_index >= 0);
  2830. ist = input_streams[ost->source_index];
  2831. }
  2832. ret = process_input(ist->file_index);
  2833. if (ret == AVERROR(EAGAIN)) {
  2834. if (input_files[ist->file_index]->eagain)
  2835. ost->unavailable = 1;
  2836. return 0;
  2837. }
  2838. if (ret < 0)
  2839. return ret == AVERROR_EOF ? 0 : ret;
  2840. return reap_filters();
  2841. }
  2842. /*
  2843. * The following code is the main loop of the file converter
  2844. */
  2845. static int transcode(void)
  2846. {
  2847. int ret, i;
  2848. AVFormatContext *os;
  2849. OutputStream *ost;
  2850. InputStream *ist;
  2851. int64_t timer_start;
  2852. ret = transcode_init();
  2853. if (ret < 0)
  2854. goto fail;
  2855. if (stdin_interaction) {
  2856. av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
  2857. }
  2858. timer_start = av_gettime();
  2859. #if HAVE_PTHREADS
  2860. if ((ret = init_input_threads()) < 0)
  2861. goto fail;
  2862. #endif
  2863. while (!received_sigterm) {
  2864. int64_t cur_time= av_gettime();
  2865. /* if 'q' pressed, exits */
  2866. if (stdin_interaction)
  2867. if (check_keyboard_interaction(cur_time) < 0)
  2868. break;
  2869. /* check if there's any stream where output is still needed */
  2870. if (!need_output()) {
  2871. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  2872. break;
  2873. }
  2874. ret = transcode_step();
  2875. if (ret < 0) {
  2876. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  2877. continue;
  2878. av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
  2879. break;
  2880. }
  2881. /* dump report by using the output first video and audio streams */
  2882. print_report(0, timer_start, cur_time);
  2883. }
  2884. #if HAVE_PTHREADS
  2885. free_input_threads();
  2886. #endif
  2887. /* at the end of stream, we must flush the decoder buffers */
  2888. for (i = 0; i < nb_input_streams; i++) {
  2889. ist = input_streams[i];
  2890. if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
  2891. output_packet(ist, NULL);
  2892. }
  2893. }
  2894. flush_encoders();
  2895. term_exit();
  2896. /* write the trailer if needed and close file */
  2897. for (i = 0; i < nb_output_files; i++) {
  2898. os = output_files[i]->ctx;
  2899. av_write_trailer(os);
  2900. }
  2901. /* dump report by using the first video and audio streams */
  2902. print_report(1, timer_start, av_gettime());
  2903. /* close each encoder */
  2904. for (i = 0; i < nb_output_streams; i++) {
  2905. ost = output_streams[i];
  2906. if (ost->encoding_needed) {
  2907. av_freep(&ost->st->codec->stats_in);
  2908. avcodec_close(ost->st->codec);
  2909. }
  2910. }
  2911. /* close each decoder */
  2912. for (i = 0; i < nb_input_streams; i++) {
  2913. ist = input_streams[i];
  2914. if (ist->decoding_needed) {
  2915. avcodec_close(ist->st->codec);
  2916. }
  2917. }
  2918. /* finished ! */
  2919. ret = 0;
  2920. fail:
  2921. #if HAVE_PTHREADS
  2922. free_input_threads();
  2923. #endif
  2924. if (output_streams) {
  2925. for (i = 0; i < nb_output_streams; i++) {
  2926. ost = output_streams[i];
  2927. if (ost) {
  2928. if (ost->stream_copy)
  2929. av_freep(&ost->st->codec->extradata);
  2930. if (ost->logfile) {
  2931. fclose(ost->logfile);
  2932. ost->logfile = NULL;
  2933. }
  2934. av_freep(&ost->st->codec->subtitle_header);
  2935. av_freep(&ost->forced_kf_pts);
  2936. av_freep(&ost->apad);
  2937. av_dict_free(&ost->opts);
  2938. av_dict_free(&ost->swr_opts);
  2939. av_dict_free(&ost->resample_opts);
  2940. }
  2941. }
  2942. }
  2943. return ret;
  2944. }
  2945. static int64_t getutime(void)
  2946. {
  2947. #if HAVE_GETRUSAGE
  2948. struct rusage rusage;
  2949. getrusage(RUSAGE_SELF, &rusage);
  2950. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  2951. #elif HAVE_GETPROCESSTIMES
  2952. HANDLE proc;
  2953. FILETIME c, e, k, u;
  2954. proc = GetCurrentProcess();
  2955. GetProcessTimes(proc, &c, &e, &k, &u);
  2956. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  2957. #else
  2958. return av_gettime();
  2959. #endif
  2960. }
  2961. static int64_t getmaxrss(void)
  2962. {
  2963. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  2964. struct rusage rusage;
  2965. getrusage(RUSAGE_SELF, &rusage);
  2966. return (int64_t)rusage.ru_maxrss * 1024;
  2967. #elif HAVE_GETPROCESSMEMORYINFO
  2968. HANDLE proc;
  2969. PROCESS_MEMORY_COUNTERS memcounters;
  2970. proc = GetCurrentProcess();
  2971. memcounters.cb = sizeof(memcounters);
  2972. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  2973. return memcounters.PeakPagefileUsage;
  2974. #else
  2975. return 0;
  2976. #endif
  2977. }
  2978. static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
  2979. {
  2980. }
  2981. int main(int argc, char **argv)
  2982. {
  2983. int ret;
  2984. int64_t ti;
  2985. register_exit(ffmpeg_cleanup);
  2986. setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
  2987. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  2988. parse_loglevel(argc, argv, options);
  2989. if(argc>1 && !strcmp(argv[1], "-d")){
  2990. run_as_daemon=1;
  2991. av_log_set_callback(log_callback_null);
  2992. argc--;
  2993. argv++;
  2994. }
  2995. avcodec_register_all();
  2996. #if CONFIG_AVDEVICE
  2997. avdevice_register_all();
  2998. #endif
  2999. avfilter_register_all();
  3000. av_register_all();
  3001. avformat_network_init();
  3002. show_banner(argc, argv, options);
  3003. term_init();
  3004. /* parse options and open all input/output files */
  3005. ret = ffmpeg_parse_options(argc, argv);
  3006. if (ret < 0)
  3007. exit_program(1);
  3008. if (nb_output_files <= 0 && nb_input_files == 0) {
  3009. show_usage();
  3010. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  3011. exit_program(1);
  3012. }
  3013. /* file converter / grab */
  3014. if (nb_output_files <= 0) {
  3015. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
  3016. exit_program(1);
  3017. }
  3018. // if (nb_input_files == 0) {
  3019. // av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
  3020. // exit_program(1);
  3021. // }
  3022. current_time = ti = getutime();
  3023. if (transcode() < 0)
  3024. exit_program(1);
  3025. ti = getutime() - ti;
  3026. if (do_benchmark) {
  3027. printf("bench: utime=%0.3fs\n", ti / 1000000.0);
  3028. }
  3029. av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
  3030. decode_error_stat[0], decode_error_stat[1]);
  3031. if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
  3032. exit_program(69);
  3033. exit_program(received_nb_signals ? 255 : 0);
  3034. return 0;
  3035. }