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.

3887 lines
137KB

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