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.

3759 lines
133KB

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