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.

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