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.

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