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.

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