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.

3547 lines
125KB

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