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.

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