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.

3641 lines
128KB

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