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.

3756 lines
132KB

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