2 * Copyright (c) 2000-2003 Fabrice Bellard
4 * This file is part of FFmpeg.
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.
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.
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
23 * multimedia converter based on the FFmpeg libraries
44 #include "libavformat/avformat.h"
45 #include "libavdevice/avdevice.h"
46 #include "libswresample/swresample.h"
47 #include "libavutil/opt.h"
48 #include "libavutil/channel_layout.h"
49 #include "libavutil/parseutils.h"
50 #include "libavutil/samplefmt.h"
51 #include "libavutil/fifo.h"
52 #include "libavutil/internal.h"
53 #include "libavutil/intreadwrite.h"
54 #include "libavutil/dict.h"
55 #include "libavutil/mathematics.h"
56 #include "libavutil/pixdesc.h"
57 #include "libavutil/avstring.h"
58 #include "libavutil/libm.h"
59 #include "libavutil/imgutils.h"
60 #include "libavutil/timestamp.h"
61 #include "libavutil/bprint.h"
62 #include "libavutil/time.h"
63 #include "libavutil/threadmessage.h"
64 #include "libavcodec/mathops.h"
65 #include "libavformat/os_support.h"
67 # include "libavfilter/avcodec.h"
68 # include "libavfilter/avfilter.h"
69 # include "libavfilter/buffersrc.h"
70 # include "libavfilter/buffersink.h"
72 #if HAVE_SYS_RESOURCE_H
74 #include <sys/types.h>
75 #include <sys/resource.h>
76 #elif HAVE_GETPROCESSTIMES
79 #if HAVE_GETPROCESSMEMORYINFO
83 #if HAVE_SETCONSOLECTRLHANDLER
89 #include <sys/select.h>
94 #include <sys/ioctl.h>
108 #include "cmdutils.h"
110 #include "libavutil/avassert.h"
112 const char program_name[] = "ffmpeg";
113 const int program_birth_year = 2000;
115 static FILE *vstats_file;
117 const char *const forced_keyframes_const_names[] = {
126 static void do_video_stats(OutputStream *ost, int frame_size);
127 static int64_t getutime(void);
128 static int64_t getmaxrss(void);
130 static int run_as_daemon = 0;
131 static int nb_frames_dup = 0;
132 static int nb_frames_drop = 0;
133 static int64_t decode_error_stat[2];
135 static int current_time;
136 AVIOContext *progress_avio = NULL;
138 static uint8_t *subtitle_out;
140 InputStream **input_streams = NULL;
141 int nb_input_streams = 0;
142 InputFile **input_files = NULL;
143 int nb_input_files = 0;
145 OutputStream **output_streams = NULL;
146 int nb_output_streams = 0;
147 OutputFile **output_files = NULL;
148 int nb_output_files = 0;
150 FilterGraph **filtergraphs;
155 /* init terminal so that we can grab keys */
156 static struct termios oldtty;
157 static int restore_tty;
161 static void free_input_threads(void);
165 Convert subtitles to video with alpha to insert them in filter graphs.
166 This is a temporary solution until libavfilter gets real subtitles support.
169 static int sub2video_get_blank_frame(InputStream *ist)
172 AVFrame *frame = ist->sub2video.frame;
174 av_frame_unref(frame);
175 ist->sub2video.frame->width = ist->sub2video.w;
176 ist->sub2video.frame->height = ist->sub2video.h;
177 ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
178 if ((ret = av_frame_get_buffer(frame, 32)) < 0)
180 memset(frame->data[0], 0, frame->height * frame->linesize[0]);
184 static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
187 uint32_t *pal, *dst2;
191 if (r->type != SUBTITLE_BITMAP) {
192 av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
195 if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
196 av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle overflowing\n");
200 dst += r->y * dst_linesize + r->x * 4;
201 src = r->pict.data[0];
202 pal = (uint32_t *)r->pict.data[1];
203 for (y = 0; y < r->h; y++) {
204 dst2 = (uint32_t *)dst;
206 for (x = 0; x < r->w; x++)
207 *(dst2++) = pal[*(src2++)];
209 src += r->pict.linesize[0];
213 static void sub2video_push_ref(InputStream *ist, int64_t pts)
215 AVFrame *frame = ist->sub2video.frame;
218 av_assert1(frame->data[0]);
219 ist->sub2video.last_pts = frame->pts = pts;
220 for (i = 0; i < ist->nb_filters; i++)
221 av_buffersrc_add_frame_flags(ist->filters[i]->filter, frame,
222 AV_BUFFERSRC_FLAG_KEEP_REF |
223 AV_BUFFERSRC_FLAG_PUSH);
226 static void sub2video_update(InputStream *ist, AVSubtitle *sub)
228 int w = ist->sub2video.w, h = ist->sub2video.h;
229 AVFrame *frame = ist->sub2video.frame;
233 int64_t pts, end_pts;
238 pts = av_rescale_q(sub->pts + sub->start_display_time * 1000LL,
239 AV_TIME_BASE_Q, ist->st->time_base);
240 end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000LL,
241 AV_TIME_BASE_Q, ist->st->time_base);
242 num_rects = sub->num_rects;
244 pts = ist->sub2video.end_pts;
248 if (sub2video_get_blank_frame(ist) < 0) {
249 av_log(ist->dec_ctx, AV_LOG_ERROR,
250 "Impossible to get a blank canvas.\n");
253 dst = frame->data [0];
254 dst_linesize = frame->linesize[0];
255 for (i = 0; i < num_rects; i++)
256 sub2video_copy_rect(dst, dst_linesize, w, h, sub->rects[i]);
257 sub2video_push_ref(ist, pts);
258 ist->sub2video.end_pts = end_pts;
261 static void sub2video_heartbeat(InputStream *ist, int64_t pts)
263 InputFile *infile = input_files[ist->file_index];
267 /* When a frame is read from a file, examine all sub2video streams in
268 the same file and send the sub2video frame again. Otherwise, decoded
269 video frames could be accumulating in the filter graph while a filter
270 (possibly overlay) is desperately waiting for a subtitle frame. */
271 for (i = 0; i < infile->nb_streams; i++) {
272 InputStream *ist2 = input_streams[infile->ist_index + i];
273 if (!ist2->sub2video.frame)
275 /* subtitles seem to be usually muxed ahead of other streams;
276 if not, subtracting a larger time here is necessary */
277 pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
278 /* do not send the heartbeat frame if the subtitle is already ahead */
279 if (pts2 <= ist2->sub2video.last_pts)
281 if (pts2 >= ist2->sub2video.end_pts || !ist2->sub2video.frame->data[0])
282 sub2video_update(ist2, NULL);
283 for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
284 nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
286 sub2video_push_ref(ist2, pts2);
290 static void sub2video_flush(InputStream *ist)
294 if (ist->sub2video.end_pts < INT64_MAX)
295 sub2video_update(ist, NULL);
296 for (i = 0; i < ist->nb_filters; i++)
297 av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
300 /* end of sub2video hack */
302 static void term_exit_sigsafe(void)
306 tcsetattr (0, TCSANOW, &oldtty);
312 av_log(NULL, AV_LOG_QUIET, "%s", "");
316 static volatile int received_sigterm = 0;
317 static volatile int received_nb_signals = 0;
318 static volatile int transcode_init_done = 0;
319 static volatile int ffmpeg_exited = 0;
320 static int main_return_code = 0;
323 sigterm_handler(int sig)
325 received_sigterm = sig;
326 received_nb_signals++;
328 if(received_nb_signals > 3) {
329 write(2/*STDERR_FILENO*/, "Received > 3 system signals, hard exiting\n",
330 strlen("Received > 3 system signals, hard exiting\n"));
336 #if HAVE_SETCONSOLECTRLHANDLER
337 static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
339 av_log(NULL, AV_LOG_DEBUG, "\nReceived windows signal %ld\n", fdwCtrlType);
344 case CTRL_BREAK_EVENT:
345 sigterm_handler(SIGINT);
348 case CTRL_CLOSE_EVENT:
349 case CTRL_LOGOFF_EVENT:
350 case CTRL_SHUTDOWN_EVENT:
351 sigterm_handler(SIGTERM);
352 /* Basically, with these 3 events, when we return from this method the
353 process is hard terminated, so stall as long as we need to
354 to try and let the main thread(s) clean up and gracefully terminate
355 (we have at most 5 seconds, but should be done far before that). */
356 while (!ffmpeg_exited) {
362 av_log(NULL, AV_LOG_ERROR, "Received unknown windows signal %ld\n", fdwCtrlType);
375 istty = isatty(0) && isatty(2);
377 if (istty && tcgetattr (0, &tty) == 0) {
381 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
382 |INLCR|IGNCR|ICRNL|IXON);
383 tty.c_oflag |= OPOST;
384 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
385 tty.c_cflag &= ~(CSIZE|PARENB);
390 tcsetattr (0, TCSANOW, &tty);
392 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
396 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
397 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
399 signal(SIGXCPU, sigterm_handler);
401 #if HAVE_SETCONSOLECTRLHANDLER
402 SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
406 /* read a key without blocking */
407 static int read_key(void)
419 n = select(1, &rfds, NULL, NULL, &tv);
428 # if HAVE_PEEKNAMEDPIPE
430 static HANDLE input_handle;
433 input_handle = GetStdHandle(STD_INPUT_HANDLE);
434 is_pipe = !GetConsoleMode(input_handle, &dw);
437 if (stdin->_cnt > 0) {
442 /* When running under a GUI, you will end here. */
443 if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
444 // input pipe may have been closed by the program that ran ffmpeg
462 static int decode_interrupt_cb(void *ctx)
464 return received_nb_signals > transcode_init_done;
467 const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
469 static void ffmpeg_cleanup(int ret)
474 int maxrss = getmaxrss() / 1024;
475 av_log(NULL, AV_LOG_INFO, "bench: maxrss=%ikB\n", maxrss);
478 for (i = 0; i < nb_filtergraphs; i++) {
479 FilterGraph *fg = filtergraphs[i];
480 avfilter_graph_free(&fg->graph);
481 for (j = 0; j < fg->nb_inputs; j++) {
482 av_freep(&fg->inputs[j]->name);
483 av_freep(&fg->inputs[j]);
485 av_freep(&fg->inputs);
486 for (j = 0; j < fg->nb_outputs; j++) {
487 av_freep(&fg->outputs[j]->name);
488 av_freep(&fg->outputs[j]);
490 av_freep(&fg->outputs);
491 av_freep(&fg->graph_desc);
493 av_freep(&filtergraphs[i]);
495 av_freep(&filtergraphs);
497 av_freep(&subtitle_out);
500 for (i = 0; i < nb_output_files; i++) {
501 OutputFile *of = output_files[i];
506 if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE))
508 avformat_free_context(s);
509 av_dict_free(&of->opts);
511 av_freep(&output_files[i]);
513 for (i = 0; i < nb_output_streams; i++) {
514 OutputStream *ost = output_streams[i];
515 AVBitStreamFilterContext *bsfc;
520 bsfc = ost->bitstream_filters;
522 AVBitStreamFilterContext *next = bsfc->next;
523 av_bitstream_filter_close(bsfc);
526 ost->bitstream_filters = NULL;
527 av_frame_free(&ost->filtered_frame);
528 av_frame_free(&ost->last_frame);
530 av_parser_close(ost->parser);
532 av_freep(&ost->forced_keyframes);
533 av_expr_free(ost->forced_keyframes_pexpr);
534 av_freep(&ost->avfilter);
535 av_freep(&ost->logfile_prefix);
537 av_freep(&ost->audio_channels_map);
538 ost->audio_channels_mapped = 0;
540 avcodec_free_context(&ost->enc_ctx);
542 av_freep(&output_streams[i]);
545 free_input_threads();
547 for (i = 0; i < nb_input_files; i++) {
548 avformat_close_input(&input_files[i]->ctx);
549 av_freep(&input_files[i]);
551 for (i = 0; i < nb_input_streams; i++) {
552 InputStream *ist = input_streams[i];
554 av_frame_free(&ist->decoded_frame);
555 av_frame_free(&ist->filter_frame);
556 av_dict_free(&ist->decoder_opts);
557 avsubtitle_free(&ist->prev_sub.subtitle);
558 av_frame_free(&ist->sub2video.frame);
559 av_freep(&ist->filters);
560 av_freep(&ist->hwaccel_device);
562 avcodec_free_context(&ist->dec_ctx);
564 av_freep(&input_streams[i]);
569 av_freep(&vstats_filename);
571 av_freep(&input_streams);
572 av_freep(&input_files);
573 av_freep(&output_streams);
574 av_freep(&output_files);
578 avformat_network_deinit();
580 if (received_sigterm) {
581 av_log(NULL, AV_LOG_INFO, "Exiting normally, received signal %d.\n",
582 (int) received_sigterm);
583 } else if (ret && transcode_init_done) {
584 av_log(NULL, AV_LOG_INFO, "Conversion failed!\n");
590 void remove_avoptions(AVDictionary **a, AVDictionary *b)
592 AVDictionaryEntry *t = NULL;
594 while ((t = av_dict_get(b, "", t, AV_DICT_IGNORE_SUFFIX))) {
595 av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
599 void assert_avoptions(AVDictionary *m)
601 AVDictionaryEntry *t;
602 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
603 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
608 static void abort_codec_experimental(AVCodec *c, int encoder)
613 static void update_benchmark(const char *fmt, ...)
615 if (do_benchmark_all) {
616 int64_t t = getutime();
622 vsnprintf(buf, sizeof(buf), fmt, va);
624 av_log(NULL, AV_LOG_INFO, "bench: %8"PRIu64" %s \n", t - current_time, buf);
630 static void close_all_output_streams(OutputStream *ost, OSTFinished this_stream, OSTFinished others)
633 for (i = 0; i < nb_output_streams; i++) {
634 OutputStream *ost2 = output_streams[i];
635 ost2->finished |= ost == ost2 ? this_stream : others;
639 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
641 AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
642 AVCodecContext *avctx = ost->encoding_needed ? ost->enc_ctx : ost->st->codec;
645 if (!ost->st->codec->extradata_size && ost->enc_ctx->extradata_size) {
646 ost->st->codec->extradata = av_mallocz(ost->enc_ctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
647 if (ost->st->codec->extradata) {
648 memcpy(ost->st->codec->extradata, ost->enc_ctx->extradata, ost->enc_ctx->extradata_size);
649 ost->st->codec->extradata_size = ost->enc_ctx->extradata_size;
653 if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
654 (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
655 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
658 * Audio encoders may split the packets -- #frames in != #packets out.
659 * But there is no reordering, so we can limit the number of output packets
660 * by simply dropping them here.
661 * Counting encoded video frames needs to be done separately because of
662 * reordering, see do_video_out()
664 if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
665 if (ost->frame_number >= ost->max_frames) {
671 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
672 uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_FACTOR,
674 ost->quality = sd ? *(int *)sd : -1;
678 av_packet_split_side_data(pkt);
681 AVPacket new_pkt = *pkt;
682 AVDictionaryEntry *bsf_arg = av_dict_get(ost->bsf_args,
685 int a = av_bitstream_filter_filter(bsfc, avctx,
686 bsf_arg ? bsf_arg->value : NULL,
687 &new_pkt.data, &new_pkt.size,
688 pkt->data, pkt->size,
689 pkt->flags & AV_PKT_FLAG_KEY);
690 if(a == 0 && new_pkt.data != pkt->data && new_pkt.destruct) {
691 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
693 memcpy(t, new_pkt.data, new_pkt.size);
694 memset(t + new_pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
702 pkt->side_data = NULL;
703 pkt->side_data_elems = 0;
705 new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,
706 av_buffer_default_free, NULL, 0);
711 av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
712 bsfc->filter->name, pkt->stream_index,
713 avctx->codec ? avctx->codec->name : "copy");
723 if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
724 if (pkt->dts != AV_NOPTS_VALUE &&
725 pkt->pts != AV_NOPTS_VALUE &&
726 pkt->dts > pkt->pts) {
727 av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d, replacing by guess\n",
729 ost->file_index, ost->st->index);
731 pkt->dts = pkt->pts + pkt->dts + ost->last_mux_dts + 1
732 - FFMIN3(pkt->pts, pkt->dts, ost->last_mux_dts + 1)
733 - FFMAX3(pkt->pts, pkt->dts, ost->last_mux_dts + 1);
736 (avctx->codec_type == AVMEDIA_TYPE_AUDIO || avctx->codec_type == AVMEDIA_TYPE_VIDEO) &&
737 pkt->dts != AV_NOPTS_VALUE &&
738 ost->last_mux_dts != AV_NOPTS_VALUE) {
739 int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
740 if (pkt->dts < max) {
741 int loglevel = max - pkt->dts > 2 || avctx->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
742 av_log(s, loglevel, "Non-monotonous DTS in output stream "
743 "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
744 ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
746 av_log(NULL, AV_LOG_FATAL, "aborting.\n");
749 av_log(s, loglevel, "changing to %"PRId64". This may result "
750 "in incorrect timestamps in the output file.\n",
752 if(pkt->pts >= pkt->dts)
753 pkt->pts = FFMAX(pkt->pts, max);
758 ost->last_mux_dts = pkt->dts;
760 ost->data_size += pkt->size;
761 ost->packets_written++;
763 pkt->stream_index = ost->index;
766 av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
767 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
768 av_get_media_type_string(ost->enc_ctx->codec_type),
769 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
770 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
775 ret = av_interleaved_write_frame(s, pkt);
777 print_error("av_interleaved_write_frame()", ret);
778 main_return_code = 1;
779 close_all_output_streams(ost, MUXER_FINISHED | ENCODER_FINISHED, ENCODER_FINISHED);
784 static void close_output_stream(OutputStream *ost)
786 OutputFile *of = output_files[ost->file_index];
788 ost->finished |= ENCODER_FINISHED;
790 int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, AV_TIME_BASE_Q);
791 of->recording_time = FFMIN(of->recording_time, end);
795 static int check_recording_time(OutputStream *ost)
797 OutputFile *of = output_files[ost->file_index];
799 if (of->recording_time != INT64_MAX &&
800 av_compare_ts(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, of->recording_time,
801 AV_TIME_BASE_Q) >= 0) {
802 close_output_stream(ost);
808 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
811 AVCodecContext *enc = ost->enc_ctx;
815 av_init_packet(&pkt);
819 if (!check_recording_time(ost))
822 if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
823 frame->pts = ost->sync_opts;
824 ost->sync_opts = frame->pts + frame->nb_samples;
825 ost->samples_encoded += frame->nb_samples;
826 ost->frames_encoded++;
828 av_assert0(pkt.size || !pkt.data);
829 update_benchmark(NULL);
831 av_log(NULL, AV_LOG_INFO, "encoder <- type:audio "
832 "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
833 av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
834 enc->time_base.num, enc->time_base.den);
837 if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
838 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
841 update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
844 av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
847 av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
848 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
849 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
850 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
853 write_frame(s, &pkt, ost);
857 static void do_subtitle_out(AVFormatContext *s,
862 int subtitle_out_max_size = 1024 * 1024;
863 int subtitle_out_size, nb, i;
868 if (sub->pts == AV_NOPTS_VALUE) {
869 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
878 subtitle_out = av_malloc(subtitle_out_max_size);
880 av_log(NULL, AV_LOG_FATAL, "Failed to allocate subtitle_out\n");
885 /* Note: DVB subtitle need one packet to draw them and one other
886 packet to clear them */
887 /* XXX: signal it in the codec context ? */
888 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
893 /* shift timestamp to honor -ss and make check_recording_time() work with -t */
895 if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)
896 pts -= output_files[ost->file_index]->start_time;
897 for (i = 0; i < nb; i++) {
898 unsigned save_num_rects = sub->num_rects;
900 ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
901 if (!check_recording_time(ost))
905 // start_display_time is required to be 0
906 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
907 sub->end_display_time -= sub->start_display_time;
908 sub->start_display_time = 0;
912 ost->frames_encoded++;
914 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
915 subtitle_out_max_size, sub);
917 sub->num_rects = save_num_rects;
918 if (subtitle_out_size < 0) {
919 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
923 av_init_packet(&pkt);
924 pkt.data = subtitle_out;
925 pkt.size = subtitle_out_size;
926 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
927 pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
928 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
929 /* XXX: the pts correction is handled here. Maybe handling
930 it in the codec would be better */
932 pkt.pts += 90 * sub->start_display_time;
934 pkt.pts += 90 * sub->end_display_time;
937 write_frame(s, &pkt, ost);
941 static void do_video_out(AVFormatContext *s,
943 AVFrame *next_picture,
946 int ret, format_video_sync;
948 AVCodecContext *enc = ost->enc_ctx;
949 AVCodecContext *mux_enc = ost->st->codec;
950 int nb_frames, nb0_frames, i;
951 double delta, delta0;
954 InputStream *ist = NULL;
955 AVFilterContext *filter = ost->filter->filter;
957 if (ost->source_index >= 0)
958 ist = input_streams[ost->source_index];
960 if (filter->inputs[0]->frame_rate.num > 0 &&
961 filter->inputs[0]->frame_rate.den > 0)
962 duration = 1/(av_q2d(filter->inputs[0]->frame_rate) * av_q2d(enc->time_base));
964 if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
965 duration = FFMIN(duration, 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base)));
967 if (!ost->filters_script &&
971 lrintf(av_frame_get_pkt_duration(next_picture) * av_q2d(ist->st->time_base) / av_q2d(enc->time_base)) > 0) {
972 duration = lrintf(av_frame_get_pkt_duration(next_picture) * av_q2d(ist->st->time_base) / av_q2d(enc->time_base));
977 nb0_frames = nb_frames = mid_pred(ost->last_nb0_frames[0],
978 ost->last_nb0_frames[1],
979 ost->last_nb0_frames[2]);
981 delta0 = sync_ipts - ost->sync_opts;
982 delta = delta0 + duration;
984 /* by default, we output a single frame */
988 format_video_sync = video_sync_method;
989 if (format_video_sync == VSYNC_AUTO) {
990 if(!strcmp(s->oformat->name, "avi")) {
991 format_video_sync = VSYNC_VFR;
993 format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;
995 && format_video_sync == VSYNC_CFR
996 && input_files[ist->file_index]->ctx->nb_streams == 1
997 && input_files[ist->file_index]->input_ts_offset == 0) {
998 format_video_sync = VSYNC_VSCFR;
1000 if (format_video_sync == VSYNC_CFR && copy_ts) {
1001 format_video_sync = VSYNC_VSCFR;
1007 format_video_sync != VSYNC_PASSTHROUGH &&
1008 format_video_sync != VSYNC_DROP) {
1009 double cor = FFMIN(-delta0, duration);
1010 if (delta0 < -0.6) {
1011 av_log(NULL, AV_LOG_WARNING, "Past duration %f too large\n", -delta0);
1013 av_log(NULL, AV_LOG_DEBUG, "Cliping frame in rate conversion by %f\n", -delta0);
1019 switch (format_video_sync) {
1021 if (ost->frame_number == 0 && delta - duration >= 0.5) {
1022 av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta - duration));
1025 ost->sync_opts = lrint(sync_ipts);
1028 // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1029 if (frame_drop_threshold && delta < frame_drop_threshold && ost->frame_number) {
1031 } else if (delta < -1.1)
1033 else if (delta > 1.1) {
1034 nb_frames = lrintf(delta);
1036 nb0_frames = lrintf(delta0 - 0.6);
1042 else if (delta > 0.6)
1043 ost->sync_opts = lrint(sync_ipts);
1046 case VSYNC_PASSTHROUGH:
1047 ost->sync_opts = lrint(sync_ipts);
1054 nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1055 nb0_frames = FFMIN(nb0_frames, nb_frames);
1057 memmove(ost->last_nb0_frames + 1,
1058 ost->last_nb0_frames,
1059 sizeof(ost->last_nb0_frames[0]) * (FF_ARRAY_ELEMS(ost->last_nb0_frames) - 1));
1060 ost->last_nb0_frames[0] = nb0_frames;
1062 if (nb0_frames == 0 && ost->last_droped) {
1064 av_log(NULL, AV_LOG_VERBOSE,
1065 "*** dropping frame %d from stream %d at ts %"PRId64"\n",
1066 ost->frame_number, ost->st->index, ost->last_frame->pts);
1068 if (nb_frames > (nb0_frames && ost->last_droped) + (nb_frames > nb0_frames)) {
1069 if (nb_frames > dts_error_threshold * 30) {
1070 av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
1074 nb_frames_dup += nb_frames - (nb0_frames && ost->last_droped) - (nb_frames > nb0_frames);
1075 av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
1077 ost->last_droped = nb_frames == nb0_frames && next_picture;
1079 /* duplicates frame if needed */
1080 for (i = 0; i < nb_frames; i++) {
1081 AVFrame *in_picture;
1082 av_init_packet(&pkt);
1086 if (i < nb0_frames && ost->last_frame) {
1087 in_picture = ost->last_frame;
1089 in_picture = next_picture;
1094 in_picture->pts = ost->sync_opts;
1097 if (!check_recording_time(ost))
1099 if (ost->frame_number >= ost->max_frames)
1103 if (s->oformat->flags & AVFMT_RAWPICTURE &&
1104 enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
1105 /* raw pictures are written as AVPicture structure to
1106 avoid any copies. We support temporarily the older
1108 if (in_picture->interlaced_frame)
1109 mux_enc->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
1111 mux_enc->field_order = AV_FIELD_PROGRESSIVE;
1112 pkt.data = (uint8_t *)in_picture;
1113 pkt.size = sizeof(AVPicture);
1114 pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
1115 pkt.flags |= AV_PKT_FLAG_KEY;
1117 write_frame(s, &pkt, ost);
1119 int got_packet, forced_keyframe = 0;
1122 if (enc->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME) &&
1123 ost->top_field_first >= 0)
1124 in_picture->top_field_first = !!ost->top_field_first;
1126 if (in_picture->interlaced_frame) {
1127 if (enc->codec->id == AV_CODEC_ID_MJPEG)
1128 mux_enc->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
1130 mux_enc->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
1132 mux_enc->field_order = AV_FIELD_PROGRESSIVE;
1134 in_picture->quality = enc->global_quality;
1135 in_picture->pict_type = 0;
1137 pts_time = in_picture->pts != AV_NOPTS_VALUE ?
1138 in_picture->pts * av_q2d(enc->time_base) : NAN;
1139 if (ost->forced_kf_index < ost->forced_kf_count &&
1140 in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1141 ost->forced_kf_index++;
1142 forced_keyframe = 1;
1143 } else if (ost->forced_keyframes_pexpr) {
1145 ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
1146 res = av_expr_eval(ost->forced_keyframes_pexpr,
1147 ost->forced_keyframes_expr_const_values, NULL);
1148 av_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
1149 ost->forced_keyframes_expr_const_values[FKF_N],
1150 ost->forced_keyframes_expr_const_values[FKF_N_FORCED],
1151 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],
1152 ost->forced_keyframes_expr_const_values[FKF_T],
1153 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],
1156 forced_keyframe = 1;
1157 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =
1158 ost->forced_keyframes_expr_const_values[FKF_N];
1159 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =
1160 ost->forced_keyframes_expr_const_values[FKF_T];
1161 ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;
1164 ost->forced_keyframes_expr_const_values[FKF_N] += 1;
1165 } else if ( ost->forced_keyframes
1166 && !strncmp(ost->forced_keyframes, "source", 6)
1167 && in_picture->key_frame==1) {
1168 forced_keyframe = 1;
1171 if (forced_keyframe) {
1172 in_picture->pict_type = AV_PICTURE_TYPE_I;
1173 av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
1176 update_benchmark(NULL);
1178 av_log(NULL, AV_LOG_INFO, "encoder <- type:video "
1179 "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
1180 av_ts2str(in_picture->pts), av_ts2timestr(in_picture->pts, &enc->time_base),
1181 enc->time_base.num, enc->time_base.den);
1184 ost->frames_encoded++;
1186 ret = avcodec_encode_video2(enc, &pkt, in_picture, &got_packet);
1187 update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
1189 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1195 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
1196 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1197 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
1198 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
1201 if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
1202 pkt.pts = ost->sync_opts;
1204 av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
1207 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
1208 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1209 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
1210 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
1213 frame_size = pkt.size;
1214 write_frame(s, &pkt, ost);
1216 /* if two pass, output log */
1217 if (ost->logfile && enc->stats_out) {
1218 fprintf(ost->logfile, "%s", enc->stats_out);
1224 * For video, number of frames in == number of packets out.
1225 * But there may be reordering, so we can't throw away frames on encoder
1226 * flush, we need to limit them here, before they go into encoder.
1228 ost->frame_number++;
1230 if (vstats_filename && frame_size)
1231 do_video_stats(ost, frame_size);
1234 if (!ost->last_frame)
1235 ost->last_frame = av_frame_alloc();
1236 av_frame_unref(ost->last_frame);
1237 if (next_picture && ost->last_frame)
1238 av_frame_ref(ost->last_frame, next_picture);
1240 av_frame_free(&ost->last_frame);
1243 static double psnr(double d)
1245 return -10.0 * log(d) / log(10.0);
1248 static void do_video_stats(OutputStream *ost, int frame_size)
1250 AVCodecContext *enc;
1252 double ti1, bitrate, avg_bitrate;
1254 /* this is executed just the first time do_video_stats is called */
1256 vstats_file = fopen(vstats_filename, "w");
1264 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1265 frame_number = ost->st->nb_frames;
1266 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number,
1267 ost->quality / (float)FF_QP2LAMBDA);
1269 if (enc->coded_frame && (enc->flags&CODEC_FLAG_PSNR))
1270 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1272 fprintf(vstats_file,"f_size= %6d ", frame_size);
1273 /* compute pts value */
1274 ti1 = av_stream_get_end_pts(ost->st) * av_q2d(ost->st->time_base);
1278 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1279 avg_bitrate = (double)(ost->data_size * 8) / ti1 / 1000.0;
1280 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1281 (double)ost->data_size / 1024, ti1, bitrate, avg_bitrate);
1282 fprintf(vstats_file, "type= %c\n", enc->coded_frame ? av_get_picture_type_char(enc->coded_frame->pict_type) : 'I');
1286 static void finish_output_stream(OutputStream *ost)
1288 OutputFile *of = output_files[ost->file_index];
1291 ost->finished = ENCODER_FINISHED | MUXER_FINISHED;
1294 for (i = 0; i < of->ctx->nb_streams; i++)
1295 output_streams[of->ost_index + i]->finished = ENCODER_FINISHED | MUXER_FINISHED;
1300 * Get and encode new output from any of the filtergraphs, without causing
1303 * @return 0 for success, <0 for severe errors
1305 static int reap_filters(int flush)
1307 AVFrame *filtered_frame = NULL;
1310 /* Reap all buffers present in the buffer sinks */
1311 for (i = 0; i < nb_output_streams; i++) {
1312 OutputStream *ost = output_streams[i];
1313 OutputFile *of = output_files[ost->file_index];
1314 AVFilterContext *filter;
1315 AVCodecContext *enc = ost->enc_ctx;
1320 filter = ost->filter->filter;
1322 if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
1323 return AVERROR(ENOMEM);
1325 filtered_frame = ost->filtered_frame;
1328 double float_pts = AV_NOPTS_VALUE; // this is identical to filtered_frame.pts but with higher precision
1329 ret = av_buffersink_get_frame_flags(filter, filtered_frame,
1330 AV_BUFFERSINK_FLAG_NO_REQUEST);
1332 if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
1333 av_log(NULL, AV_LOG_WARNING,
1334 "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));
1335 } else if (flush && ret == AVERROR_EOF) {
1336 if (filter->inputs[0]->type == AVMEDIA_TYPE_VIDEO)
1337 do_video_out(of->ctx, ost, NULL, AV_NOPTS_VALUE);
1341 if (ost->finished) {
1342 av_frame_unref(filtered_frame);
1345 if (filtered_frame->pts != AV_NOPTS_VALUE) {
1346 int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
1347 AVRational tb = enc->time_base;
1348 int extra_bits = av_clip(29 - av_log2(tb.den), 0, 16);
1350 tb.den <<= extra_bits;
1352 av_rescale_q(filtered_frame->pts, filter->inputs[0]->time_base, tb) -
1353 av_rescale_q(start_time, AV_TIME_BASE_Q, tb);
1354 float_pts /= 1 << extra_bits;
1355 // avoid exact midoints to reduce the chance of rounding differences, this can be removed in case the fps code is changed to work with integers
1356 float_pts += FFSIGN(float_pts) * 1.0 / (1<<17);
1358 filtered_frame->pts =
1359 av_rescale_q(filtered_frame->pts, filter->inputs[0]->time_base, enc->time_base) -
1360 av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);
1362 //if (ost->source_index >= 0)
1363 // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
1365 switch (filter->inputs[0]->type) {
1366 case AVMEDIA_TYPE_VIDEO:
1367 if (!ost->frame_aspect_ratio.num)
1368 enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
1371 av_log(NULL, AV_LOG_INFO, "filter -> pts:%s pts_time:%s exact:%f time_base:%d/%d\n",
1372 av_ts2str(filtered_frame->pts), av_ts2timestr(filtered_frame->pts, &enc->time_base),
1374 enc->time_base.num, enc->time_base.den);
1377 do_video_out(of->ctx, ost, filtered_frame, float_pts);
1379 case AVMEDIA_TYPE_AUDIO:
1380 if (!(enc->codec->capabilities & CODEC_CAP_PARAM_CHANGE) &&
1381 enc->channels != av_frame_get_channels(filtered_frame)) {
1382 av_log(NULL, AV_LOG_ERROR,
1383 "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
1386 do_audio_out(of->ctx, ost, filtered_frame);
1389 // TODO support subtitle filters
1393 av_frame_unref(filtered_frame);
1400 static void print_final_stats(int64_t total_size)
1402 uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
1403 uint64_t subtitle_size = 0;
1404 uint64_t data_size = 0;
1405 float percent = -1.0;
1409 for (i = 0; i < nb_output_streams; i++) {
1410 OutputStream *ost = output_streams[i];
1411 switch (ost->enc_ctx->codec_type) {
1412 case AVMEDIA_TYPE_VIDEO: video_size += ost->data_size; break;
1413 case AVMEDIA_TYPE_AUDIO: audio_size += ost->data_size; break;
1414 case AVMEDIA_TYPE_SUBTITLE: subtitle_size += ost->data_size; break;
1415 default: other_size += ost->data_size; break;
1417 extra_size += ost->enc_ctx->extradata_size;
1418 data_size += ost->data_size;
1419 if ( (ost->enc_ctx->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))
1420 != CODEC_FLAG_PASS1)
1424 if (data_size && total_size>0 && total_size >= data_size)
1425 percent = 100.0 * (total_size - data_size) / data_size;
1427 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: ",
1428 video_size / 1024.0,
1429 audio_size / 1024.0,
1430 subtitle_size / 1024.0,
1431 other_size / 1024.0,
1432 extra_size / 1024.0);
1434 av_log(NULL, AV_LOG_INFO, "%f%%", percent);
1436 av_log(NULL, AV_LOG_INFO, "unknown");
1437 av_log(NULL, AV_LOG_INFO, "\n");
1439 /* print verbose per-stream stats */
1440 for (i = 0; i < nb_input_files; i++) {
1441 InputFile *f = input_files[i];
1442 uint64_t total_packets = 0, total_size = 0;
1444 av_log(NULL, AV_LOG_VERBOSE, "Input file #%d (%s):\n",
1445 i, f->ctx->filename);
1447 for (j = 0; j < f->nb_streams; j++) {
1448 InputStream *ist = input_streams[f->ist_index + j];
1449 enum AVMediaType type = ist->dec_ctx->codec_type;
1451 total_size += ist->data_size;
1452 total_packets += ist->nb_packets;
1454 av_log(NULL, AV_LOG_VERBOSE, " Input stream #%d:%d (%s): ",
1455 i, j, media_type_string(type));
1456 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets read (%"PRIu64" bytes); ",
1457 ist->nb_packets, ist->data_size);
1459 if (ist->decoding_needed) {
1460 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames decoded",
1461 ist->frames_decoded);
1462 if (type == AVMEDIA_TYPE_AUDIO)
1463 av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ist->samples_decoded);
1464 av_log(NULL, AV_LOG_VERBOSE, "; ");
1467 av_log(NULL, AV_LOG_VERBOSE, "\n");
1470 av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) demuxed\n",
1471 total_packets, total_size);
1474 for (i = 0; i < nb_output_files; i++) {
1475 OutputFile *of = output_files[i];
1476 uint64_t total_packets = 0, total_size = 0;
1478 av_log(NULL, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
1479 i, of->ctx->filename);
1481 for (j = 0; j < of->ctx->nb_streams; j++) {
1482 OutputStream *ost = output_streams[of->ost_index + j];
1483 enum AVMediaType type = ost->enc_ctx->codec_type;
1485 total_size += ost->data_size;
1486 total_packets += ost->packets_written;
1488 av_log(NULL, AV_LOG_VERBOSE, " Output stream #%d:%d (%s): ",
1489 i, j, media_type_string(type));
1490 if (ost->encoding_needed) {
1491 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
1492 ost->frames_encoded);
1493 if (type == AVMEDIA_TYPE_AUDIO)
1494 av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->samples_encoded);
1495 av_log(NULL, AV_LOG_VERBOSE, "; ");
1498 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
1499 ost->packets_written, ost->data_size);
1501 av_log(NULL, AV_LOG_VERBOSE, "\n");
1504 av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
1505 total_packets, total_size);
1507 if(video_size + data_size + audio_size + subtitle_size + extra_size == 0){
1508 av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded ");
1510 av_log(NULL, AV_LOG_WARNING, "\n");
1512 av_log(NULL, AV_LOG_WARNING, "(check -ss / -t / -frames parameters if used)\n");
1517 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
1520 AVBPrint buf_script;
1522 AVFormatContext *oc;
1524 AVCodecContext *enc;
1525 int frame_number, vid, i;
1527 int64_t pts = INT64_MIN;
1528 static int64_t last_time = -1;
1529 static int qp_histogram[52];
1530 int hours, mins, secs, us;
1532 if (!print_stats && !is_last_report && !progress_avio)
1535 if (!is_last_report) {
1536 if (last_time == -1) {
1537 last_time = cur_time;
1540 if ((cur_time - last_time) < 500000)
1542 last_time = cur_time;
1546 oc = output_files[0]->ctx;
1548 total_size = avio_size(oc->pb);
1549 if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
1550 total_size = avio_tell(oc->pb);
1554 av_bprint_init(&buf_script, 0, 1);
1555 for (i = 0; i < nb_output_streams; i++) {
1557 ost = output_streams[i];
1559 if (!ost->stream_copy)
1560 q = ost->quality / (float) FF_QP2LAMBDA;
1562 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1563 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1564 av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1565 ost->file_index, ost->index, q);
1567 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1568 float fps, t = (cur_time-timer_start) / 1000000.0;
1570 frame_number = ost->frame_number;
1571 fps = t > 1 ? frame_number / t : 0;
1572 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
1573 frame_number, fps < 9.95, fps, q);
1574 av_bprintf(&buf_script, "frame=%d\n", frame_number);
1575 av_bprintf(&buf_script, "fps=%.1f\n", fps);
1576 av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1577 ost->file_index, ost->index, q);
1579 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1583 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1585 for (j = 0; j < 32; j++)
1586 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
1589 if ((enc->flags&CODEC_FLAG_PSNR) && (enc->coded_frame || is_last_report)) {
1591 double error, error_sum = 0;
1592 double scale, scale_sum = 0;
1594 char type[3] = { 'Y','U','V' };
1595 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1596 for (j = 0; j < 3; j++) {
1597 if (is_last_report) {
1598 error = enc->error[j];
1599 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1601 error = enc->coded_frame->error[j];
1602 scale = enc->width * enc->height * 255.0 * 255.0;
1608 p = psnr(error / scale);
1609 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
1610 av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
1611 ost->file_index, ost->index, type[j] | 32, p);
1613 p = psnr(error_sum / scale_sum);
1614 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1615 av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
1616 ost->file_index, ost->index, p);
1620 /* compute min output value */
1621 if (av_stream_get_end_pts(ost->st) != AV_NOPTS_VALUE)
1622 pts = FFMAX(pts, av_rescale_q(av_stream_get_end_pts(ost->st),
1623 ost->st->time_base, AV_TIME_BASE_Q));
1625 nb_frames_drop += ost->last_droped;
1628 secs = FFABS(pts) / AV_TIME_BASE;
1629 us = FFABS(pts) % AV_TIME_BASE;
1635 bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
1637 if (total_size < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1639 else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1640 "size=%8.0fkB time=", total_size / 1024.0);
1642 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "-");
1643 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1644 "%02d:%02d:%02d.%02d ", hours, mins, secs,
1645 (100 * us) / AV_TIME_BASE);
1648 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),"bitrate=N/A");
1649 av_bprintf(&buf_script, "bitrate=N/A\n");
1651 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),"bitrate=%6.1fkbits/s", bitrate);
1652 av_bprintf(&buf_script, "bitrate=%6.1fkbits/s\n", bitrate);
1655 if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
1656 else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
1657 av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
1658 av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
1659 hours, mins, secs, us);
1661 if (nb_frames_dup || nb_frames_drop)
1662 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1663 nb_frames_dup, nb_frames_drop);
1664 av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
1665 av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
1667 if (print_stats || is_last_report) {
1668 const char end = is_last_report ? '\n' : '\r';
1669 if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
1670 fprintf(stderr, "%s %c", buf, end);
1672 av_log(NULL, AV_LOG_INFO, "%s %c", buf, end);
1677 if (progress_avio) {
1678 av_bprintf(&buf_script, "progress=%s\n",
1679 is_last_report ? "end" : "continue");
1680 avio_write(progress_avio, buf_script.str,
1681 FFMIN(buf_script.len, buf_script.size - 1));
1682 avio_flush(progress_avio);
1683 av_bprint_finalize(&buf_script, NULL);
1684 if (is_last_report) {
1685 avio_closep(&progress_avio);
1690 print_final_stats(total_size);
1693 static void flush_encoders(void)
1697 for (i = 0; i < nb_output_streams; i++) {
1698 OutputStream *ost = output_streams[i];
1699 AVCodecContext *enc = ost->enc_ctx;
1700 AVFormatContext *os = output_files[ost->file_index]->ctx;
1701 int stop_encoding = 0;
1703 if (!ost->encoding_needed)
1706 if (enc->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1708 if (enc->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
1712 int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
1715 switch (enc->codec_type) {
1716 case AVMEDIA_TYPE_AUDIO:
1717 encode = avcodec_encode_audio2;
1720 case AVMEDIA_TYPE_VIDEO:
1721 encode = avcodec_encode_video2;
1732 av_init_packet(&pkt);
1736 update_benchmark(NULL);
1737 ret = encode(enc, &pkt, NULL, &got_packet);
1738 update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
1740 av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
1743 if (ost->logfile && enc->stats_out) {
1744 fprintf(ost->logfile, "%s", enc->stats_out);
1750 if (ost->finished & MUXER_FINISHED) {
1751 av_free_packet(&pkt);
1754 av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
1755 pkt_size = pkt.size;
1756 write_frame(os, &pkt, ost);
1757 if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
1758 do_video_stats(ost, pkt_size);
1769 * Check whether a packet from ist should be written into ost at this time
1771 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1773 OutputFile *of = output_files[ost->file_index];
1774 int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
1776 if (ost->source_index != ist_index)
1782 if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
1788 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1790 OutputFile *of = output_files[ost->file_index];
1791 InputFile *f = input_files [ist->file_index];
1792 int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
1793 int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
1794 int64_t ist_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ist->st->time_base);
1798 av_init_packet(&opkt);
1800 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1801 !ost->copy_initial_nonkeyframes)
1804 if (pkt->pts == AV_NOPTS_VALUE) {
1805 if (!ost->frame_number && ist->pts < start_time &&
1806 !ost->copy_prior_start)
1809 if (!ost->frame_number && pkt->pts < ist_tb_start_time &&
1810 !ost->copy_prior_start)
1814 if (of->recording_time != INT64_MAX &&
1815 ist->pts >= of->recording_time + start_time) {
1816 close_output_stream(ost);
1820 if (f->recording_time != INT64_MAX) {
1821 start_time = f->ctx->start_time;
1822 if (f->start_time != AV_NOPTS_VALUE)
1823 start_time += f->start_time;
1824 if (ist->pts >= f->recording_time + start_time) {
1825 close_output_stream(ost);
1830 /* force the input stream PTS */
1831 if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
1834 if (pkt->pts != AV_NOPTS_VALUE)
1835 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1837 opkt.pts = AV_NOPTS_VALUE;
1839 if (pkt->dts == AV_NOPTS_VALUE)
1840 opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
1842 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1843 opkt.dts -= ost_tb_start_time;
1845 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
1846 int duration = av_get_audio_frame_duration(ist->dec_ctx, pkt->size);
1848 duration = ist->dec_ctx->frame_size;
1849 opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
1850 (AVRational){1, ist->dec_ctx->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
1851 ost->st->time_base) - ost_tb_start_time;
1854 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1855 opkt.flags = pkt->flags;
1857 // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1858 if ( ost->enc_ctx->codec_id != AV_CODEC_ID_H264
1859 && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG1VIDEO
1860 && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG2VIDEO
1861 && ost->enc_ctx->codec_id != AV_CODEC_ID_VC1
1863 if (av_parser_change(ost->parser, ost->st->codec,
1864 &opkt.data, &opkt.size,
1865 pkt->data, pkt->size,
1866 pkt->flags & AV_PKT_FLAG_KEY)) {
1867 opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
1872 opkt.data = pkt->data;
1873 opkt.size = pkt->size;
1875 av_copy_packet_side_data(&opkt, pkt);
1877 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
1878 /* store AVPicture in AVPacket, as expected by the output format */
1879 avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
1880 opkt.data = (uint8_t *)&pict;
1881 opkt.size = sizeof(AVPicture);
1882 opkt.flags |= AV_PKT_FLAG_KEY;
1885 write_frame(of->ctx, &opkt, ost);
1888 int guess_input_channel_layout(InputStream *ist)
1890 AVCodecContext *dec = ist->dec_ctx;
1892 if (!dec->channel_layout) {
1893 char layout_name[256];
1895 if (dec->channels > ist->guess_layout_max)
1897 dec->channel_layout = av_get_default_channel_layout(dec->channels);
1898 if (!dec->channel_layout)
1900 av_get_channel_layout_string(layout_name, sizeof(layout_name),
1901 dec->channels, dec->channel_layout);
1902 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
1903 "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1908 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1910 AVFrame *decoded_frame, *f;
1911 AVCodecContext *avctx = ist->dec_ctx;
1912 int i, ret, err = 0, resample_changed;
1913 AVRational decoded_frame_tb;
1915 if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
1916 return AVERROR(ENOMEM);
1917 if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
1918 return AVERROR(ENOMEM);
1919 decoded_frame = ist->decoded_frame;
1921 update_benchmark(NULL);
1922 ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1923 update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
1925 if (ret >= 0 && avctx->sample_rate <= 0) {
1926 av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
1927 ret = AVERROR_INVALIDDATA;
1930 if (*got_output || ret<0)
1931 decode_error_stat[ret<0] ++;
1933 if (ret < 0 && exit_on_error)
1936 if (!*got_output || ret < 0)
1939 ist->samples_decoded += decoded_frame->nb_samples;
1940 ist->frames_decoded++;
1943 /* increment next_dts to use for the case where the input stream does not
1944 have timestamps or there are multiple frames in the packet */
1945 ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1947 ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1951 resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
1952 ist->resample_channels != avctx->channels ||
1953 ist->resample_channel_layout != decoded_frame->channel_layout ||
1954 ist->resample_sample_rate != decoded_frame->sample_rate;
1955 if (resample_changed) {
1956 char layout1[64], layout2[64];
1958 if (!guess_input_channel_layout(ist)) {
1959 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
1960 "layout for Input Stream #%d.%d\n", ist->file_index,
1964 decoded_frame->channel_layout = avctx->channel_layout;
1966 av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
1967 ist->resample_channel_layout);
1968 av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
1969 decoded_frame->channel_layout);
1971 av_log(NULL, AV_LOG_INFO,
1972 "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",
1973 ist->file_index, ist->st->index,
1974 ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
1975 ist->resample_channels, layout1,
1976 decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
1977 avctx->channels, layout2);
1979 ist->resample_sample_fmt = decoded_frame->format;
1980 ist->resample_sample_rate = decoded_frame->sample_rate;
1981 ist->resample_channel_layout = decoded_frame->channel_layout;
1982 ist->resample_channels = avctx->channels;
1984 for (i = 0; i < nb_filtergraphs; i++)
1985 if (ist_in_filtergraph(filtergraphs[i], ist)) {
1986 FilterGraph *fg = filtergraphs[i];
1987 if (configure_filtergraph(fg) < 0) {
1988 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1994 /* if the decoder provides a pts, use it instead of the last packet pts.
1995 the decoder could be delaying output by a packet or more. */
1996 if (decoded_frame->pts != AV_NOPTS_VALUE) {
1997 ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
1998 decoded_frame_tb = avctx->time_base;
1999 } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
2000 decoded_frame->pts = decoded_frame->pkt_pts;
2001 decoded_frame_tb = ist->st->time_base;
2002 } else if (pkt->pts != AV_NOPTS_VALUE) {
2003 decoded_frame->pts = pkt->pts;
2004 decoded_frame_tb = ist->st->time_base;
2006 decoded_frame->pts = ist->dts;
2007 decoded_frame_tb = AV_TIME_BASE_Q;
2009 pkt->pts = AV_NOPTS_VALUE;
2010 if (decoded_frame->pts != AV_NOPTS_VALUE)
2011 decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
2012 (AVRational){1, avctx->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
2013 (AVRational){1, avctx->sample_rate});
2014 for (i = 0; i < ist->nb_filters; i++) {
2015 if (i < ist->nb_filters - 1) {
2016 f = ist->filter_frame;
2017 err = av_frame_ref(f, decoded_frame);
2022 err = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f,
2023 AV_BUFFERSRC_FLAG_PUSH);
2024 if (err == AVERROR_EOF)
2025 err = 0; /* ignore */
2029 decoded_frame->pts = AV_NOPTS_VALUE;
2031 av_frame_unref(ist->filter_frame);
2032 av_frame_unref(decoded_frame);
2033 return err < 0 ? err : ret;
2036 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
2038 AVFrame *decoded_frame, *f;
2039 int i, ret = 0, err = 0, resample_changed;
2040 int64_t best_effort_timestamp;
2041 AVRational *frame_sample_aspect;
2043 if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
2044 return AVERROR(ENOMEM);
2045 if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
2046 return AVERROR(ENOMEM);
2047 decoded_frame = ist->decoded_frame;
2048 pkt->dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
2050 update_benchmark(NULL);
2051 ret = avcodec_decode_video2(ist->dec_ctx,
2052 decoded_frame, got_output, pkt);
2053 update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
2055 // The following line may be required in some cases where there is no parser
2056 // or the parser does not has_b_frames correctly
2057 if (ist->st->codec->has_b_frames < ist->dec_ctx->has_b_frames) {
2058 if (ist->dec_ctx->codec_id == AV_CODEC_ID_H264) {
2059 ist->st->codec->has_b_frames = ist->dec_ctx->has_b_frames;
2061 av_log_ask_for_sample(
2063 "has_b_frames is larger in decoder than demuxer %d > %d ",
2064 ist->dec_ctx->has_b_frames,
2065 ist->st->codec->has_b_frames
2069 if (*got_output || ret<0)
2070 decode_error_stat[ret<0] ++;
2072 if (ret < 0 && exit_on_error)
2075 if (*got_output && ret >= 0) {
2076 if (ist->dec_ctx->width != decoded_frame->width ||
2077 ist->dec_ctx->height != decoded_frame->height ||
2078 ist->dec_ctx->pix_fmt != decoded_frame->format) {
2079 av_log(NULL, AV_LOG_DEBUG, "Frame parameters mismatch context %d,%d,%d != %d,%d,%d\n",
2080 decoded_frame->width,
2081 decoded_frame->height,
2082 decoded_frame->format,
2083 ist->dec_ctx->width,
2084 ist->dec_ctx->height,
2085 ist->dec_ctx->pix_fmt);
2089 if (!*got_output || ret < 0)
2092 if(ist->top_field_first>=0)
2093 decoded_frame->top_field_first = ist->top_field_first;
2095 ist->frames_decoded++;
2097 if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
2098 err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
2102 ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
2104 best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
2105 if(best_effort_timestamp != AV_NOPTS_VALUE)
2106 ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
2109 av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
2110 "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",
2111 ist->st->index, av_ts2str(decoded_frame->pts),
2112 av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
2113 best_effort_timestamp,
2114 av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
2115 decoded_frame->key_frame, decoded_frame->pict_type,
2116 ist->st->time_base.num, ist->st->time_base.den);
2121 if (ist->st->sample_aspect_ratio.num)
2122 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2124 resample_changed = ist->resample_width != decoded_frame->width ||
2125 ist->resample_height != decoded_frame->height ||
2126 ist->resample_pix_fmt != decoded_frame->format;
2127 if (resample_changed) {
2128 av_log(NULL, AV_LOG_INFO,
2129 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
2130 ist->file_index, ist->st->index,
2131 ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
2132 decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
2134 ist->resample_width = decoded_frame->width;
2135 ist->resample_height = decoded_frame->height;
2136 ist->resample_pix_fmt = decoded_frame->format;
2138 for (i = 0; i < nb_filtergraphs; i++) {
2139 if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
2140 configure_filtergraph(filtergraphs[i]) < 0) {
2141 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2147 frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
2148 for (i = 0; i < ist->nb_filters; i++) {
2149 if (!frame_sample_aspect->num)
2150 *frame_sample_aspect = ist->st->sample_aspect_ratio;
2152 if (i < ist->nb_filters - 1) {
2153 f = ist->filter_frame;
2154 err = av_frame_ref(f, decoded_frame);
2159 ret = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f, AV_BUFFERSRC_FLAG_PUSH);
2160 if (ret == AVERROR_EOF) {
2161 ret = 0; /* ignore */
2162 } else if (ret < 0) {
2163 av_log(NULL, AV_LOG_FATAL,
2164 "Failed to inject frame into filter network: %s\n", av_err2str(ret));
2170 av_frame_unref(ist->filter_frame);
2171 av_frame_unref(decoded_frame);
2172 return err < 0 ? err : ret;
2175 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2177 AVSubtitle subtitle;
2178 int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
2179 &subtitle, got_output, pkt);
2181 if (*got_output || ret<0)
2182 decode_error_stat[ret<0] ++;
2184 if (ret < 0 && exit_on_error)
2187 if (ret < 0 || !*got_output) {
2189 sub2video_flush(ist);
2193 if (ist->fix_sub_duration) {
2195 if (ist->prev_sub.got_output) {
2196 end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
2197 1000, AV_TIME_BASE);
2198 if (end < ist->prev_sub.subtitle.end_display_time) {
2199 av_log(ist->dec_ctx, AV_LOG_DEBUG,
2200 "Subtitle duration reduced from %d to %d%s\n",
2201 ist->prev_sub.subtitle.end_display_time, end,
2202 end <= 0 ? ", dropping it" : "");
2203 ist->prev_sub.subtitle.end_display_time = end;
2206 FFSWAP(int, *got_output, ist->prev_sub.got_output);
2207 FFSWAP(int, ret, ist->prev_sub.ret);
2208 FFSWAP(AVSubtitle, subtitle, ist->prev_sub.subtitle);
2216 sub2video_update(ist, &subtitle);
2218 if (!subtitle.num_rects)
2221 ist->frames_decoded++;
2223 for (i = 0; i < nb_output_streams; i++) {
2224 OutputStream *ost = output_streams[i];
2226 if (!check_output_constraints(ist, ost) || !ost->encoding_needed
2227 || ost->enc->type != AVMEDIA_TYPE_SUBTITLE)
2230 do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle);
2234 avsubtitle_free(&subtitle);
2238 static int send_filter_eof(InputStream *ist)
2241 for (i = 0; i < ist->nb_filters; i++) {
2243 ret = av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
2245 ret = av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
2253 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2254 static int process_input_packet(InputStream *ist, const AVPacket *pkt)
2260 if (!ist->saw_first_ts) {
2261 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;
2263 if (pkt && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
2264 ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2265 ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
2267 ist->saw_first_ts = 1;
2270 if (ist->next_dts == AV_NOPTS_VALUE)
2271 ist->next_dts = ist->dts;
2272 if (ist->next_pts == AV_NOPTS_VALUE)
2273 ist->next_pts = ist->pts;
2277 av_init_packet(&avpkt);
2285 if (pkt->dts != AV_NOPTS_VALUE) {
2286 ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2287 if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
2288 ist->next_pts = ist->pts = ist->dts;
2291 // while we have more to decode or while the decoder did output something on EOF
2292 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2296 ist->pts = ist->next_pts;
2297 ist->dts = ist->next_dts;
2299 if (avpkt.size && avpkt.size != pkt->size &&
2300 !(ist->dec->capabilities & CODEC_CAP_SUBFRAMES)) {
2301 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2302 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2303 ist->showed_multi_packet_warning = 1;
2306 switch (ist->dec_ctx->codec_type) {
2307 case AVMEDIA_TYPE_AUDIO:
2308 ret = decode_audio (ist, &avpkt, &got_output);
2310 case AVMEDIA_TYPE_VIDEO:
2311 ret = decode_video (ist, &avpkt, &got_output);
2312 if (avpkt.duration) {
2313 duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
2314 } else if(ist->dec_ctx->framerate.num != 0 && ist->dec_ctx->framerate.den != 0) {
2315 int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict+1 : ist->dec_ctx->ticks_per_frame;
2316 duration = ((int64_t)AV_TIME_BASE *
2317 ist->dec_ctx->framerate.den * ticks) /
2318 ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
2322 if(ist->dts != AV_NOPTS_VALUE && duration) {
2323 ist->next_dts += duration;
2325 ist->next_dts = AV_NOPTS_VALUE;
2328 ist->next_pts += duration; //FIXME the duration is not correct in some cases
2330 case AVMEDIA_TYPE_SUBTITLE:
2331 ret = transcode_subtitles(ist, &avpkt, &got_output);
2338 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
2339 ist->file_index, ist->st->index, av_err2str(ret));
2346 avpkt.pts= AV_NOPTS_VALUE;
2348 // touch data and size only if not EOF
2350 if(ist->dec_ctx->codec_type != AVMEDIA_TYPE_AUDIO)
2358 if (got_output && !pkt)
2362 /* after flushing, send an EOF on all the filter inputs attached to the stream */
2363 if (!pkt && ist->decoding_needed && !got_output) {
2364 int ret = send_filter_eof(ist);
2366 av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
2371 /* handle stream copy */
2372 if (!ist->decoding_needed) {
2373 ist->dts = ist->next_dts;
2374 switch (ist->dec_ctx->codec_type) {
2375 case AVMEDIA_TYPE_AUDIO:
2376 ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
2377 ist->dec_ctx->sample_rate;
2379 case AVMEDIA_TYPE_VIDEO:
2380 if (ist->framerate.num) {
2381 // TODO: Remove work-around for c99-to-c89 issue 7
2382 AVRational time_base_q = AV_TIME_BASE_Q;
2383 int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
2384 ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
2385 } else if (pkt->duration) {
2386 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
2387 } else if(ist->dec_ctx->framerate.num != 0) {
2388 int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
2389 ist->next_dts += ((int64_t)AV_TIME_BASE *
2390 ist->dec_ctx->framerate.den * ticks) /
2391 ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
2395 ist->pts = ist->dts;
2396 ist->next_pts = ist->next_dts;
2398 for (i = 0; pkt && i < nb_output_streams; i++) {
2399 OutputStream *ost = output_streams[i];
2401 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2404 do_streamcopy(ist, ost, pkt);
2410 static void print_sdp(void)
2415 AVIOContext *sdp_pb;
2416 AVFormatContext **avc = av_malloc_array(nb_output_files, sizeof(*avc));
2420 for (i = 0, j = 0; i < nb_output_files; i++) {
2421 if (!strcmp(output_files[i]->ctx->oformat->name, "rtp")) {
2422 avc[j] = output_files[i]->ctx;
2427 av_sdp_create(avc, j, sdp, sizeof(sdp));
2429 if (!sdp_filename) {
2430 printf("SDP:\n%s\n", sdp);
2433 if (avio_open2(&sdp_pb, sdp_filename, AVIO_FLAG_WRITE, &int_cb, NULL) < 0) {
2434 av_log(NULL, AV_LOG_ERROR, "Failed to open sdp file '%s'\n", sdp_filename);
2436 avio_printf(sdp_pb, "SDP:\n%s", sdp);
2437 avio_closep(&sdp_pb);
2438 av_freep(&sdp_filename);
2445 static const HWAccel *get_hwaccel(enum AVPixelFormat pix_fmt)
2448 for (i = 0; hwaccels[i].name; i++)
2449 if (hwaccels[i].pix_fmt == pix_fmt)
2450 return &hwaccels[i];
2454 static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
2456 InputStream *ist = s->opaque;
2457 const enum AVPixelFormat *p;
2460 for (p = pix_fmts; *p != -1; p++) {
2461 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
2462 const HWAccel *hwaccel;
2464 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
2467 hwaccel = get_hwaccel(*p);
2469 (ist->active_hwaccel_id && ist->active_hwaccel_id != hwaccel->id) ||
2470 (ist->hwaccel_id != HWACCEL_AUTO && ist->hwaccel_id != hwaccel->id))
2473 ret = hwaccel->init(s);
2475 if (ist->hwaccel_id == hwaccel->id) {
2476 av_log(NULL, AV_LOG_FATAL,
2477 "%s hwaccel requested for input stream #%d:%d, "
2478 "but cannot be initialized.\n", hwaccel->name,
2479 ist->file_index, ist->st->index);
2480 return AV_PIX_FMT_NONE;
2484 ist->active_hwaccel_id = hwaccel->id;
2485 ist->hwaccel_pix_fmt = *p;
2492 static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
2494 InputStream *ist = s->opaque;
2496 if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
2497 return ist->hwaccel_get_buffer(s, frame, flags);
2499 return avcodec_default_get_buffer2(s, frame, flags);
2502 static int init_input_stream(int ist_index, char *error, int error_len)
2505 InputStream *ist = input_streams[ist_index];
2507 if (ist->decoding_needed) {
2508 AVCodec *codec = ist->dec;
2510 snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
2511 avcodec_get_name(ist->dec_ctx->codec_id), ist->file_index, ist->st->index);
2512 return AVERROR(EINVAL);
2515 ist->dec_ctx->opaque = ist;
2516 ist->dec_ctx->get_format = get_format;
2517 ist->dec_ctx->get_buffer2 = get_buffer;
2518 ist->dec_ctx->thread_safe_callbacks = 1;
2520 av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
2521 if (ist->dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
2522 (ist->decoding_needed & DECODING_FOR_OST)) {
2523 av_dict_set(&ist->decoder_opts, "compute_edt", "1", AV_DICT_DONT_OVERWRITE);
2524 if (ist->decoding_needed & DECODING_FOR_FILTER)
2525 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");
2528 if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
2529 av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
2530 if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
2531 if (ret == AVERROR_EXPERIMENTAL)
2532 abort_codec_experimental(codec, 0);
2534 snprintf(error, error_len,
2535 "Error while opening decoder for input stream "
2537 ist->file_index, ist->st->index, av_err2str(ret));
2540 assert_avoptions(ist->decoder_opts);
2543 ist->next_pts = AV_NOPTS_VALUE;
2544 ist->next_dts = AV_NOPTS_VALUE;
2549 static InputStream *get_input_stream(OutputStream *ost)
2551 if (ost->source_index >= 0)
2552 return input_streams[ost->source_index];
2556 static int compare_int64(const void *a, const void *b)
2558 int64_t va = *(int64_t *)a, vb = *(int64_t *)b;
2559 return va < vb ? -1 : va > vb ? +1 : 0;
2562 static int init_output_stream(OutputStream *ost, char *error, int error_len)
2566 if (ost->encoding_needed) {
2567 AVCodec *codec = ost->enc;
2568 AVCodecContext *dec = NULL;
2571 if ((ist = get_input_stream(ost)))
2573 if (dec && dec->subtitle_header) {
2574 /* ASS code assumes this buffer is null terminated so add extra byte. */
2575 ost->enc_ctx->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
2576 if (!ost->enc_ctx->subtitle_header)
2577 return AVERROR(ENOMEM);
2578 memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2579 ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
2581 if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
2582 av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
2583 av_dict_set(&ost->encoder_opts, "side_data_only_packets", "1", 0);
2585 if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
2586 if (ret == AVERROR_EXPERIMENTAL)
2587 abort_codec_experimental(codec, 1);
2588 snprintf(error, error_len,
2589 "Error while opening encoder for output stream #%d:%d - "
2590 "maybe incorrect parameters such as bit_rate, rate, width or height",
2591 ost->file_index, ost->index);
2594 if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
2595 !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
2596 av_buffersink_set_frame_size(ost->filter->filter,
2597 ost->enc_ctx->frame_size);
2598 assert_avoptions(ost->encoder_opts);
2599 if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000)
2600 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2601 " It takes bits/s as argument, not kbits/s\n");
2603 ret = avcodec_copy_context(ost->st->codec, ost->enc_ctx);
2605 av_log(NULL, AV_LOG_FATAL,
2606 "Error initializing the output stream codec context.\n");
2610 // copy timebase while removing common factors
2611 ost->st->time_base = av_add_q(ost->enc_ctx->time_base, (AVRational){0, 1});
2612 ost->st->codec->codec= ost->enc_ctx->codec;
2614 ret = av_opt_set_dict(ost->enc_ctx, &ost->encoder_opts);
2616 av_log(NULL, AV_LOG_FATAL,
2617 "Error setting up codec context options.\n");
2620 // copy timebase while removing common factors
2621 ost->st->time_base = av_add_q(ost->st->codec->time_base, (AVRational){0, 1});
2627 static void parse_forced_key_frames(char *kf, OutputStream *ost,
2628 AVCodecContext *avctx)
2631 int n = 1, i, size, index = 0;
2634 for (p = kf; *p; p++)
2638 pts = av_malloc_array(size, sizeof(*pts));
2640 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
2645 for (i = 0; i < n; i++) {
2646 char *next = strchr(p, ',');
2651 if (!memcmp(p, "chapters", 8)) {
2653 AVFormatContext *avf = output_files[ost->file_index]->ctx;
2656 if (avf->nb_chapters > INT_MAX - size ||
2657 !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
2659 av_log(NULL, AV_LOG_FATAL,
2660 "Could not allocate forced key frames array.\n");
2663 t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
2664 t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2666 for (j = 0; j < avf->nb_chapters; j++) {
2667 AVChapter *c = avf->chapters[j];
2668 av_assert1(index < size);
2669 pts[index++] = av_rescale_q(c->start, c->time_base,
2670 avctx->time_base) + t;
2675 t = parse_time_or_die("force_key_frames", p, 1);
2676 av_assert1(index < size);
2677 pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2684 av_assert0(index == size);
2685 qsort(pts, size, sizeof(*pts), compare_int64);
2686 ost->forced_kf_count = size;
2687 ost->forced_kf_pts = pts;
2690 static void report_new_stream(int input_index, AVPacket *pkt)
2692 InputFile *file = input_files[input_index];
2693 AVStream *st = file->ctx->streams[pkt->stream_index];
2695 if (pkt->stream_index < file->nb_streams_warn)
2697 av_log(file->ctx, AV_LOG_WARNING,
2698 "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
2699 av_get_media_type_string(st->codec->codec_type),
2700 input_index, pkt->stream_index,
2701 pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
2702 file->nb_streams_warn = pkt->stream_index + 1;
2705 static void set_encoder_id(OutputFile *of, OutputStream *ost)
2707 AVDictionaryEntry *e;
2709 uint8_t *encoder_string;
2710 int encoder_string_len;
2711 int format_flags = 0;
2712 int codec_flags = 0;
2714 if (av_dict_get(ost->st->metadata, "encoder", NULL, 0))
2717 e = av_dict_get(of->opts, "fflags", NULL, 0);
2719 const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
2722 av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
2724 e = av_dict_get(ost->encoder_opts, "flags", NULL, 0);
2726 const AVOption *o = av_opt_find(ost->enc_ctx, "flags", NULL, 0, 0);
2729 av_opt_eval_flags(ost->enc_ctx, o, e->value, &codec_flags);
2732 encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
2733 encoder_string = av_mallocz(encoder_string_len);
2734 if (!encoder_string)
2737 if (!(format_flags & AVFMT_FLAG_BITEXACT) && !(codec_flags & CODEC_FLAG_BITEXACT))
2738 av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
2740 av_strlcpy(encoder_string, "Lavc ", encoder_string_len);
2741 av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
2742 av_dict_set(&ost->st->metadata, "encoder", encoder_string,
2743 AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
2746 static int transcode_init(void)
2748 int ret = 0, i, j, k;
2749 AVFormatContext *oc;
2752 char error[1024] = {0};
2755 for (i = 0; i < nb_filtergraphs; i++) {
2756 FilterGraph *fg = filtergraphs[i];
2757 for (j = 0; j < fg->nb_outputs; j++) {
2758 OutputFilter *ofilter = fg->outputs[j];
2759 if (!ofilter->ost || ofilter->ost->source_index >= 0)
2761 if (fg->nb_inputs != 1)
2763 for (k = nb_input_streams-1; k >= 0 ; k--)
2764 if (fg->inputs[0]->ist == input_streams[k])
2766 ofilter->ost->source_index = k;
2770 /* init framerate emulation */
2771 for (i = 0; i < nb_input_files; i++) {
2772 InputFile *ifile = input_files[i];
2773 if (ifile->rate_emu)
2774 for (j = 0; j < ifile->nb_streams; j++)
2775 input_streams[j + ifile->ist_index]->start = av_gettime_relative();
2778 /* for each output stream, we compute the right encoding parameters */
2779 for (i = 0; i < nb_output_streams; i++) {
2780 AVCodecContext *enc_ctx;
2781 AVCodecContext *dec_ctx = NULL;
2782 ost = output_streams[i];
2783 oc = output_files[ost->file_index]->ctx;
2784 ist = get_input_stream(ost);
2786 if (ost->attachment_filename)
2789 enc_ctx = ost->stream_copy ? ost->st->codec : ost->enc_ctx;
2792 dec_ctx = ist->dec_ctx;
2794 ost->st->disposition = ist->st->disposition;
2795 enc_ctx->bits_per_raw_sample = dec_ctx->bits_per_raw_sample;
2796 enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
2798 for (j=0; j<oc->nb_streams; j++) {
2799 AVStream *st = oc->streams[j];
2800 if (st != ost->st && st->codec->codec_type == enc_ctx->codec_type)
2803 if (j == oc->nb_streams)
2804 if (enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO || enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
2805 ost->st->disposition = AV_DISPOSITION_DEFAULT;
2808 if (ost->stream_copy) {
2810 uint64_t extra_size;
2812 av_assert0(ist && !ost->filter);
2814 extra_size = (uint64_t)dec_ctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2816 if (extra_size > INT_MAX) {
2817 return AVERROR(EINVAL);
2820 /* if stream_copy is selected, no need to decode or encode */
2821 enc_ctx->codec_id = dec_ctx->codec_id;
2822 enc_ctx->codec_type = dec_ctx->codec_type;
2824 if (!enc_ctx->codec_tag) {
2825 unsigned int codec_tag;
2826 if (!oc->oformat->codec_tag ||
2827 av_codec_get_id (oc->oformat->codec_tag, dec_ctx->codec_tag) == enc_ctx->codec_id ||
2828 !av_codec_get_tag2(oc->oformat->codec_tag, dec_ctx->codec_id, &codec_tag))
2829 enc_ctx->codec_tag = dec_ctx->codec_tag;
2832 enc_ctx->bit_rate = dec_ctx->bit_rate;
2833 enc_ctx->rc_max_rate = dec_ctx->rc_max_rate;
2834 enc_ctx->rc_buffer_size = dec_ctx->rc_buffer_size;
2835 enc_ctx->field_order = dec_ctx->field_order;
2836 if (dec_ctx->extradata_size) {
2837 enc_ctx->extradata = av_mallocz(extra_size);
2838 if (!enc_ctx->extradata) {
2839 return AVERROR(ENOMEM);
2841 memcpy(enc_ctx->extradata, dec_ctx->extradata, dec_ctx->extradata_size);
2843 enc_ctx->extradata_size= dec_ctx->extradata_size;
2844 enc_ctx->bits_per_coded_sample = dec_ctx->bits_per_coded_sample;
2846 enc_ctx->time_base = ist->st->time_base;
2848 * Avi is a special case here because it supports variable fps but
2849 * having the fps and timebase differe significantly adds quite some
2852 if(!strcmp(oc->oformat->name, "avi")) {
2853 if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
2854 && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
2855 && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(dec_ctx->time_base)
2856 && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(dec_ctx->time_base) < 1.0/500
2858 enc_ctx->time_base.num = ist->st->r_frame_rate.den;
2859 enc_ctx->time_base.den = 2*ist->st->r_frame_rate.num;
2860 enc_ctx->ticks_per_frame = 2;
2861 } else if ( copy_tb<0 && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > 2*av_q2d(ist->st->time_base)
2862 && av_q2d(ist->st->time_base) < 1.0/500
2864 enc_ctx->time_base = dec_ctx->time_base;
2865 enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
2866 enc_ctx->time_base.den *= 2;
2867 enc_ctx->ticks_per_frame = 2;
2869 } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
2870 && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
2871 && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
2872 && strcmp(oc->oformat->name, "f4v")
2874 if( copy_tb<0 && dec_ctx->time_base.den
2875 && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > av_q2d(ist->st->time_base)
2876 && av_q2d(ist->st->time_base) < 1.0/500
2878 enc_ctx->time_base = dec_ctx->time_base;
2879 enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
2882 if ( enc_ctx->codec_tag == AV_RL32("tmcd")
2883 && dec_ctx->time_base.num < dec_ctx->time_base.den
2884 && dec_ctx->time_base.num > 0
2885 && 121LL*dec_ctx->time_base.num > dec_ctx->time_base.den) {
2886 enc_ctx->time_base = dec_ctx->time_base;
2889 if (ist && !ost->frame_rate.num)
2890 ost->frame_rate = ist->framerate;
2891 if(ost->frame_rate.num)
2892 enc_ctx->time_base = av_inv_q(ost->frame_rate);
2894 av_reduce(&enc_ctx->time_base.num, &enc_ctx->time_base.den,
2895 enc_ctx->time_base.num, enc_ctx->time_base.den, INT_MAX);
2897 if (ist->st->nb_side_data) {
2898 ost->st->side_data = av_realloc_array(NULL, ist->st->nb_side_data,
2899 sizeof(*ist->st->side_data));
2900 if (!ost->st->side_data)
2901 return AVERROR(ENOMEM);
2903 ost->st->nb_side_data = 0;
2904 for (j = 0; j < ist->st->nb_side_data; j++) {
2905 const AVPacketSideData *sd_src = &ist->st->side_data[j];
2906 AVPacketSideData *sd_dst = &ost->st->side_data[ost->st->nb_side_data];
2908 if (ost->rotate_overridden && sd_src->type == AV_PKT_DATA_DISPLAYMATRIX)
2911 sd_dst->data = av_malloc(sd_src->size);
2913 return AVERROR(ENOMEM);
2914 memcpy(sd_dst->data, sd_src->data, sd_src->size);
2915 sd_dst->size = sd_src->size;
2916 sd_dst->type = sd_src->type;
2917 ost->st->nb_side_data++;
2921 ost->parser = av_parser_init(enc_ctx->codec_id);
2923 switch (enc_ctx->codec_type) {
2924 case AVMEDIA_TYPE_AUDIO:
2925 if (audio_volume != 256) {
2926 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2929 enc_ctx->channel_layout = dec_ctx->channel_layout;
2930 enc_ctx->sample_rate = dec_ctx->sample_rate;
2931 enc_ctx->channels = dec_ctx->channels;
2932 enc_ctx->frame_size = dec_ctx->frame_size;
2933 enc_ctx->audio_service_type = dec_ctx->audio_service_type;
2934 enc_ctx->block_align = dec_ctx->block_align;
2935 enc_ctx->initial_padding = dec_ctx->delay;
2936 #if FF_API_AUDIOENC_DELAY
2937 enc_ctx->delay = dec_ctx->delay;
2939 if((enc_ctx->block_align == 1 || enc_ctx->block_align == 1152 || enc_ctx->block_align == 576) && enc_ctx->codec_id == AV_CODEC_ID_MP3)
2940 enc_ctx->block_align= 0;
2941 if(enc_ctx->codec_id == AV_CODEC_ID_AC3)
2942 enc_ctx->block_align= 0;
2944 case AVMEDIA_TYPE_VIDEO:
2945 enc_ctx->pix_fmt = dec_ctx->pix_fmt;
2946 enc_ctx->width = dec_ctx->width;
2947 enc_ctx->height = dec_ctx->height;
2948 enc_ctx->has_b_frames = dec_ctx->has_b_frames;
2949 if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
2951 av_mul_q(ost->frame_aspect_ratio,
2952 (AVRational){ enc_ctx->height, enc_ctx->width });
2953 av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
2954 "with stream copy may produce invalid files\n");
2956 else if (ist->st->sample_aspect_ratio.num)
2957 sar = ist->st->sample_aspect_ratio;
2959 sar = dec_ctx->sample_aspect_ratio;
2960 ost->st->sample_aspect_ratio = enc_ctx->sample_aspect_ratio = sar;
2961 ost->st->avg_frame_rate = ist->st->avg_frame_rate;
2962 ost->st->r_frame_rate = ist->st->r_frame_rate;
2964 case AVMEDIA_TYPE_SUBTITLE:
2965 enc_ctx->width = dec_ctx->width;
2966 enc_ctx->height = dec_ctx->height;
2968 case AVMEDIA_TYPE_UNKNOWN:
2969 case AVMEDIA_TYPE_DATA:
2970 case AVMEDIA_TYPE_ATTACHMENT:
2977 ost->enc = avcodec_find_encoder(enc_ctx->codec_id);
2979 /* should only happen when a default codec is not present. */
2980 snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
2981 avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
2982 ret = AVERROR(EINVAL);
2986 set_encoder_id(output_files[ost->file_index], ost);
2989 (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
2990 enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO)) {
2992 fg = init_simple_filtergraph(ist, ost);
2993 if (configure_filtergraph(fg)) {
2994 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2999 if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
3000 if (!ost->frame_rate.num)
3001 ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
3002 if (ist && !ost->frame_rate.num)
3003 ost->frame_rate = ist->framerate;
3004 if (ist && !ost->frame_rate.num)
3005 ost->frame_rate = ist->st->r_frame_rate;
3006 if (ist && !ost->frame_rate.num) {
3007 ost->frame_rate = (AVRational){25, 1};
3008 av_log(NULL, AV_LOG_WARNING,
3010 "about the input framerate is available. Falling "
3011 "back to a default value of 25fps for output stream #%d:%d. Use the -r option "
3012 "if you want a different framerate.\n",
3013 ost->file_index, ost->index);
3015 // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
3016 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
3017 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
3018 ost->frame_rate = ost->enc->supported_framerates[idx];
3020 // reduce frame rate for mpeg4 to be within the spec limits
3021 if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
3022 av_reduce(&ost->frame_rate.num, &ost->frame_rate.den,
3023 ost->frame_rate.num, ost->frame_rate.den, 65535);
3027 switch (enc_ctx->codec_type) {
3028 case AVMEDIA_TYPE_AUDIO:
3029 enc_ctx->sample_fmt = ost->filter->filter->inputs[0]->format;
3030 enc_ctx->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
3031 enc_ctx->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
3032 enc_ctx->channels = avfilter_link_get_channels(ost->filter->filter->inputs[0]);
3033 enc_ctx->time_base = (AVRational){ 1, enc_ctx->sample_rate };
3035 case AVMEDIA_TYPE_VIDEO:
3036 enc_ctx->time_base = av_inv_q(ost->frame_rate);
3037 if (!(enc_ctx->time_base.num && enc_ctx->time_base.den))
3038 enc_ctx->time_base = ost->filter->filter->inputs[0]->time_base;
3039 if ( av_q2d(enc_ctx->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
3040 && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
3041 av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
3042 "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3044 for (j = 0; j < ost->forced_kf_count; j++)
3045 ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
3047 enc_ctx->time_base);
3049 enc_ctx->width = ost->filter->filter->inputs[0]->w;
3050 enc_ctx->height = ost->filter->filter->inputs[0]->h;
3051 enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
3052 ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
3053 av_mul_q(ost->frame_aspect_ratio, (AVRational){ enc_ctx->height, enc_ctx->width }) :
3054 ost->filter->filter->inputs[0]->sample_aspect_ratio;
3055 if (!strncmp(ost->enc->name, "libx264", 7) &&
3056 enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&
3057 ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
3058 av_log(NULL, AV_LOG_WARNING,
3059 "No pixel format specified, %s for H.264 encoding chosen.\n"
3060 "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
3061 av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
3062 if (!strncmp(ost->enc->name, "mpeg2video", 10) &&
3063 enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&
3064 ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
3065 av_log(NULL, AV_LOG_WARNING,
3066 "No pixel format specified, %s for MPEG-2 encoding chosen.\n"
3067 "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
3068 av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
3069 enc_ctx->pix_fmt = ost->filter->filter->inputs[0]->format;
3071 ost->st->avg_frame_rate = ost->frame_rate;
3074 enc_ctx->width != dec_ctx->width ||
3075 enc_ctx->height != dec_ctx->height ||
3076 enc_ctx->pix_fmt != dec_ctx->pix_fmt) {
3077 enc_ctx->bits_per_raw_sample = frame_bits_per_raw_sample;
3080 if (ost->forced_keyframes) {
3081 if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
3082 ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
3083 forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
3085 av_log(NULL, AV_LOG_ERROR,
3086 "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
3089 ost->forced_keyframes_expr_const_values[FKF_N] = 0;
3090 ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
3091 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
3092 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
3094 // Don't parse the 'forced_keyframes' in case of 'keep-source-keyframes',
3095 // parse it only for static kf timings
3096 } else if(strncmp(ost->forced_keyframes, "source", 6)) {
3097 parse_forced_key_frames(ost->forced_keyframes, ost, ost->enc_ctx);
3101 case AVMEDIA_TYPE_SUBTITLE:
3102 enc_ctx->time_base = (AVRational){1, 1000};
3103 if (!enc_ctx->width) {
3104 enc_ctx->width = input_streams[ost->source_index]->st->codec->width;
3105 enc_ctx->height = input_streams[ost->source_index]->st->codec->height;
3108 case AVMEDIA_TYPE_DATA:
3116 if (ost->disposition) {
3117 static const AVOption opts[] = {
3118 { "disposition" , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },
3119 { "default" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEFAULT }, .unit = "flags" },
3120 { "dub" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DUB }, .unit = "flags" },
3121 { "original" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ORIGINAL }, .unit = "flags" },
3122 { "comment" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_COMMENT }, .unit = "flags" },
3123 { "lyrics" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_LYRICS }, .unit = "flags" },
3124 { "karaoke" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_KARAOKE }, .unit = "flags" },
3125 { "forced" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_FORCED }, .unit = "flags" },
3126 { "hearing_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_HEARING_IMPAIRED }, .unit = "flags" },
3127 { "visual_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_VISUAL_IMPAIRED }, .unit = "flags" },
3128 { "clean_effects" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CLEAN_EFFECTS }, .unit = "flags" },
3129 { "captions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CAPTIONS }, .unit = "flags" },
3130 { "descriptions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DESCRIPTIONS }, .unit = "flags" },
3131 { "metadata" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_METADATA }, .unit = "flags" },
3134 static const AVClass class = {
3136 .item_name = av_default_item_name,
3138 .version = LIBAVUTIL_VERSION_INT,
3140 const AVClass *pclass = &class;
3142 ret = av_opt_eval_flags(&pclass, &opts[0], ost->disposition, &ost->st->disposition);
3148 /* open each encoder */
3149 for (i = 0; i < nb_output_streams; i++) {
3150 ret = init_output_stream(output_streams[i], error, sizeof(error));
3155 /* init input streams */
3156 for (i = 0; i < nb_input_streams; i++)
3157 if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
3158 for (i = 0; i < nb_output_streams; i++) {
3159 ost = output_streams[i];
3160 avcodec_close(ost->enc_ctx);
3165 /* discard unused programs */
3166 for (i = 0; i < nb_input_files; i++) {
3167 InputFile *ifile = input_files[i];
3168 for (j = 0; j < ifile->ctx->nb_programs; j++) {
3169 AVProgram *p = ifile->ctx->programs[j];
3170 int discard = AVDISCARD_ALL;
3172 for (k = 0; k < p->nb_stream_indexes; k++)
3173 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
3174 discard = AVDISCARD_DEFAULT;
3177 p->discard = discard;
3181 /* open files and write file headers */
3182 for (i = 0; i < nb_output_files; i++) {
3183 oc = output_files[i]->ctx;
3184 oc->interrupt_callback = int_cb;
3185 if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
3186 snprintf(error, sizeof(error),
3187 "Could not write header for output file #%d "
3188 "(incorrect codec parameters ?): %s",
3189 i, av_err2str(ret));
3190 ret = AVERROR(EINVAL);
3193 // assert_avoptions(output_files[i]->opts);
3194 if (strcmp(oc->oformat->name, "rtp")) {
3200 /* dump the file output parameters - cannot be done before in case
3202 for (i = 0; i < nb_output_files; i++) {
3203 av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
3206 /* dump the stream mapping */
3207 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
3208 for (i = 0; i < nb_input_streams; i++) {
3209 ist = input_streams[i];
3211 for (j = 0; j < ist->nb_filters; j++) {
3212 if (ist->filters[j]->graph->graph_desc) {
3213 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
3214 ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
3215 ist->filters[j]->name);
3216 if (nb_filtergraphs > 1)
3217 av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
3218 av_log(NULL, AV_LOG_INFO, "\n");
3223 for (i = 0; i < nb_output_streams; i++) {
3224 ost = output_streams[i];
3226 if (ost->attachment_filename) {
3227 /* an attached file */
3228 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
3229 ost->attachment_filename, ost->file_index, ost->index);
3233 if (ost->filter && ost->filter->graph->graph_desc) {
3234 /* output from a complex graph */
3235 av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
3236 if (nb_filtergraphs > 1)
3237 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
3239 av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
3240 ost->index, ost->enc ? ost->enc->name : "?");
3244 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
3245 input_streams[ost->source_index]->file_index,
3246 input_streams[ost->source_index]->st->index,
3249 if (ost->sync_ist != input_streams[ost->source_index])
3250 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
3251 ost->sync_ist->file_index,
3252 ost->sync_ist->st->index);
3253 if (ost->stream_copy)
3254 av_log(NULL, AV_LOG_INFO, " (copy)");
3256 const AVCodec *in_codec = input_streams[ost->source_index]->dec;
3257 const AVCodec *out_codec = ost->enc;
3258 const char *decoder_name = "?";
3259 const char *in_codec_name = "?";
3260 const char *encoder_name = "?";
3261 const char *out_codec_name = "?";
3262 const AVCodecDescriptor *desc;
3265 decoder_name = in_codec->name;
3266 desc = avcodec_descriptor_get(in_codec->id);
3268 in_codec_name = desc->name;
3269 if (!strcmp(decoder_name, in_codec_name))
3270 decoder_name = "native";
3274 encoder_name = out_codec->name;
3275 desc = avcodec_descriptor_get(out_codec->id);
3277 out_codec_name = desc->name;
3278 if (!strcmp(encoder_name, out_codec_name))
3279 encoder_name = "native";
3282 av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
3283 in_codec_name, decoder_name,
3284 out_codec_name, encoder_name);
3286 av_log(NULL, AV_LOG_INFO, "\n");
3290 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
3294 if (sdp_filename || want_sdp) {
3298 transcode_init_done = 1;
3303 /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
3304 static int need_output(void)
3308 for (i = 0; i < nb_output_streams; i++) {
3309 OutputStream *ost = output_streams[i];
3310 OutputFile *of = output_files[ost->file_index];
3311 AVFormatContext *os = output_files[ost->file_index]->ctx;
3313 if (ost->finished ||
3314 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
3316 if (ost->frame_number >= ost->max_frames) {
3318 for (j = 0; j < of->ctx->nb_streams; j++)
3319 close_output_stream(output_streams[of->ost_index + j]);
3330 * Select the output stream to process.
3332 * @return selected output stream, or NULL if none available
3334 static OutputStream *choose_output(void)
3337 int64_t opts_min = INT64_MAX;
3338 OutputStream *ost_min = NULL;
3340 for (i = 0; i < nb_output_streams; i++) {
3341 OutputStream *ost = output_streams[i];
3342 int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
3344 if (!ost->finished && opts < opts_min) {
3346 ost_min = ost->unavailable ? NULL : ost;
3352 static int check_keyboard_interaction(int64_t cur_time)
3355 static int64_t last_time;
3356 if (received_nb_signals)
3357 return AVERROR_EXIT;
3358 /* read_key() returns 0 on EOF */
3359 if(cur_time - last_time >= 100000 && !run_as_daemon){
3361 last_time = cur_time;
3365 return AVERROR_EXIT;
3366 if (key == '+') av_log_set_level(av_log_get_level()+10);
3367 if (key == '-') av_log_set_level(av_log_get_level()-10);
3368 if (key == 's') qp_hist ^= 1;
3371 do_hex_dump = do_pkt_dump = 0;
3372 } else if(do_pkt_dump){
3376 av_log_set_level(AV_LOG_DEBUG);
3378 if (key == 'c' || key == 'C'){
3379 char buf[4096], target[64], command[256], arg[256] = {0};
3382 fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
3384 while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
3389 (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
3390 av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
3391 target, time, command, arg);
3392 for (i = 0; i < nb_filtergraphs; i++) {
3393 FilterGraph *fg = filtergraphs[i];
3396 ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
3397 key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
3398 fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
3399 } else if (key == 'c') {
3400 fprintf(stderr, "Queing commands only on filters supporting the specific command is unsupported\n");
3401 ret = AVERROR_PATCHWELCOME;
3403 ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
3405 fprintf(stderr, "Queing command failed with error %s\n", av_err2str(ret));
3410 av_log(NULL, AV_LOG_ERROR,
3411 "Parse error, at least 3 arguments were expected, "
3412 "only %d given in string '%s'\n", n, buf);
3415 if (key == 'd' || key == 'D'){
3418 debug = input_streams[0]->st->codec->debug<<1;
3419 if(!debug) debug = 1;
3420 while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
3423 if(scanf("%d", &debug)!=1)
3424 fprintf(stderr,"error parsing debug value\n");
3425 for(i=0;i<nb_input_streams;i++) {
3426 input_streams[i]->st->codec->debug = debug;
3428 for(i=0;i<nb_output_streams;i++) {
3429 OutputStream *ost = output_streams[i];
3430 ost->enc_ctx->debug = debug;
3432 if(debug) av_log_set_level(AV_LOG_DEBUG);
3433 fprintf(stderr,"debug=%d\n", debug);
3436 fprintf(stderr, "key function\n"
3437 "? show this help\n"
3438 "+ increase verbosity\n"
3439 "- decrease verbosity\n"
3440 "c Send command to first matching filter supporting it\n"
3441 "C Send/Que command to all matching filters\n"
3442 "D cycle through available debug modes\n"
3443 "h dump packets/hex press to cycle through the 3 states\n"
3445 "s Show QP histogram\n"
3452 static void *input_thread(void *arg)
3455 unsigned flags = f->non_blocking ? AV_THREAD_MESSAGE_NONBLOCK : 0;
3460 ret = av_read_frame(f->ctx, &pkt);
3462 if (ret == AVERROR(EAGAIN)) {
3467 av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
3470 av_dup_packet(&pkt);
3471 ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
3472 if (flags && ret == AVERROR(EAGAIN)) {
3474 ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
3475 av_log(f->ctx, AV_LOG_WARNING,
3476 "Thread message queue blocking; consider raising the "
3477 "thread_queue_size option (current value: %d)\n",
3478 f->thread_queue_size);
3481 if (ret != AVERROR_EOF)
3482 av_log(f->ctx, AV_LOG_ERROR,
3483 "Unable to send packet to main thread: %s\n",
3485 av_free_packet(&pkt);
3486 av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
3494 static void free_input_threads(void)
3498 for (i = 0; i < nb_input_files; i++) {
3499 InputFile *f = input_files[i];
3502 if (!f || !f->in_thread_queue)
3504 av_thread_message_queue_set_err_send(f->in_thread_queue, AVERROR_EOF);
3505 while (av_thread_message_queue_recv(f->in_thread_queue, &pkt, 0) >= 0)
3506 av_free_packet(&pkt);
3508 pthread_join(f->thread, NULL);
3510 av_thread_message_queue_free(&f->in_thread_queue);
3514 static int init_input_threads(void)
3518 if (nb_input_files == 1)
3521 for (i = 0; i < nb_input_files; i++) {
3522 InputFile *f = input_files[i];
3524 if (f->ctx->pb ? !f->ctx->pb->seekable :
3525 strcmp(f->ctx->iformat->name, "lavfi"))
3526 f->non_blocking = 1;
3527 ret = av_thread_message_queue_alloc(&f->in_thread_queue,
3528 f->thread_queue_size, sizeof(AVPacket));
3532 if ((ret = pthread_create(&f->thread, NULL, input_thread, f))) {
3533 av_log(NULL, AV_LOG_ERROR, "pthread_create failed: %s. Try to increase `ulimit -v` or decrease `ulimit -s`.\n", strerror(ret));
3534 av_thread_message_queue_free(&f->in_thread_queue);
3535 return AVERROR(ret);
3541 static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
3543 return av_thread_message_queue_recv(f->in_thread_queue, pkt,
3545 AV_THREAD_MESSAGE_NONBLOCK : 0);
3549 static int get_input_packet(InputFile *f, AVPacket *pkt)
3553 for (i = 0; i < f->nb_streams; i++) {
3554 InputStream *ist = input_streams[f->ist_index + i];
3555 int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
3556 int64_t now = av_gettime_relative() - ist->start;
3558 return AVERROR(EAGAIN);
3563 if (nb_input_files > 1)
3564 return get_input_packet_mt(f, pkt);
3566 return av_read_frame(f->ctx, pkt);
3569 static int got_eagain(void)
3572 for (i = 0; i < nb_output_streams; i++)
3573 if (output_streams[i]->unavailable)
3578 static void reset_eagain(void)
3581 for (i = 0; i < nb_input_files; i++)
3582 input_files[i]->eagain = 0;
3583 for (i = 0; i < nb_output_streams; i++)
3584 output_streams[i]->unavailable = 0;
3589 * - 0 -- one packet was read and processed
3590 * - AVERROR(EAGAIN) -- no packets were available for selected file,
3591 * this function should be called again
3592 * - AVERROR_EOF -- this function should not be called again
3594 static int process_input(int file_index)
3596 InputFile *ifile = input_files[file_index];
3597 AVFormatContext *is;
3603 ret = get_input_packet(ifile, &pkt);
3605 if (ret == AVERROR(EAGAIN)) {
3610 if (ret != AVERROR_EOF) {
3611 print_error(is->filename, ret);
3616 for (i = 0; i < ifile->nb_streams; i++) {
3617 ist = input_streams[ifile->ist_index + i];
3618 if (ist->decoding_needed) {
3619 ret = process_input_packet(ist, NULL);
3624 /* mark all outputs that don't go through lavfi as finished */
3625 for (j = 0; j < nb_output_streams; j++) {
3626 OutputStream *ost = output_streams[j];
3628 if (ost->source_index == ifile->ist_index + i &&
3629 (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
3630 finish_output_stream(ost);
3634 ifile->eof_reached = 1;
3635 return AVERROR(EAGAIN);
3641 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
3642 is->streams[pkt.stream_index]);
3644 /* the following test is needed in case new streams appear
3645 dynamically in stream : we ignore them */
3646 if (pkt.stream_index >= ifile->nb_streams) {
3647 report_new_stream(file_index, &pkt);
3648 goto discard_packet;
3651 ist = input_streams[ifile->ist_index + pkt.stream_index];
3653 ist->data_size += pkt.size;
3657 goto discard_packet;
3660 av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
3661 "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",
3662 ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
3663 av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
3664 av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
3665 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3666 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3667 av_ts2str(input_files[ist->file_index]->ts_offset),
3668 av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
3671 if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
3672 int64_t stime, stime2;
3673 // Correcting starttime based on the enabled streams
3674 // 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.
3675 // so we instead do it here as part of discontinuity handling
3676 if ( ist->next_dts == AV_NOPTS_VALUE
3677 && ifile->ts_offset == -is->start_time
3678 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
3679 int64_t new_start_time = INT64_MAX;
3680 for (i=0; i<is->nb_streams; i++) {
3681 AVStream *st = is->streams[i];
3682 if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
3684 new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
3686 if (new_start_time > is->start_time) {
3687 av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
3688 ifile->ts_offset = -new_start_time;
3692 stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
3693 stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
3694 ist->wrap_correction_done = 1;
3696 if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
3697 pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
3698 ist->wrap_correction_done = 0;
3700 if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
3701 pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
3702 ist->wrap_correction_done = 0;
3706 /* add the stream-global side data to the first packet */
3707 if (ist->nb_packets == 1) {
3708 if (ist->st->nb_side_data)
3709 av_packet_split_side_data(&pkt);
3710 for (i = 0; i < ist->st->nb_side_data; i++) {
3711 AVPacketSideData *src_sd = &ist->st->side_data[i];
3714 if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
3716 if (ist->autorotate && src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
3719 dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
3723 memcpy(dst_data, src_sd->data, src_sd->size);
3727 if (pkt.dts != AV_NOPTS_VALUE)
3728 pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3729 if (pkt.pts != AV_NOPTS_VALUE)
3730 pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3732 if (pkt.pts != AV_NOPTS_VALUE)
3733 pkt.pts *= ist->ts_scale;
3734 if (pkt.dts != AV_NOPTS_VALUE)
3735 pkt.dts *= ist->ts_scale;
3737 if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
3738 ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
3739 pkt.dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
3740 && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
3741 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3742 int64_t delta = pkt_dts - ifile->last_ts;
3743 if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3744 delta > 1LL*dts_delta_threshold*AV_TIME_BASE){
3745 ifile->ts_offset -= delta;
3746 av_log(NULL, AV_LOG_DEBUG,
3747 "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3748 delta, ifile->ts_offset);
3749 pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3750 if (pkt.pts != AV_NOPTS_VALUE)
3751 pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3755 if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
3756 ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
3757 pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
3759 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3760 int64_t delta = pkt_dts - ist->next_dts;
3761 if (is->iformat->flags & AVFMT_TS_DISCONT) {
3762 if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3763 delta > 1LL*dts_delta_threshold*AV_TIME_BASE ||
3764 pkt_dts + AV_TIME_BASE/10 < FFMAX(ist->pts, ist->dts)) {
3765 ifile->ts_offset -= delta;
3766 av_log(NULL, AV_LOG_DEBUG,
3767 "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3768 delta, ifile->ts_offset);
3769 pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3770 if (pkt.pts != AV_NOPTS_VALUE)
3771 pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3774 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3775 delta > 1LL*dts_error_threshold*AV_TIME_BASE) {
3776 av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
3777 pkt.dts = AV_NOPTS_VALUE;
3779 if (pkt.pts != AV_NOPTS_VALUE){
3780 int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
3781 delta = pkt_pts - ist->next_dts;
3782 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3783 delta > 1LL*dts_error_threshold*AV_TIME_BASE) {
3784 av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3785 pkt.pts = AV_NOPTS_VALUE;
3791 if (pkt.dts != AV_NOPTS_VALUE)
3792 ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3795 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",
3796 ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
3797 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3798 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3799 av_ts2str(input_files[ist->file_index]->ts_offset),
3800 av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
3803 sub2video_heartbeat(ist, pkt.pts);
3805 process_input_packet(ist, &pkt);
3808 av_free_packet(&pkt);
3814 * Perform a step of transcoding for the specified filter graph.
3816 * @param[in] graph filter graph to consider
3817 * @param[out] best_ist input stream where a frame would allow to continue
3818 * @return 0 for success, <0 for error
3820 static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
3823 int nb_requests, nb_requests_max = 0;
3824 InputFilter *ifilter;
3828 ret = avfilter_graph_request_oldest(graph->graph);
3830 return reap_filters(0);
3832 if (ret == AVERROR_EOF) {
3833 ret = reap_filters(1);
3834 for (i = 0; i < graph->nb_outputs; i++)
3835 close_output_stream(graph->outputs[i]->ost);
3838 if (ret != AVERROR(EAGAIN))
3841 for (i = 0; i < graph->nb_inputs; i++) {
3842 ifilter = graph->inputs[i];
3844 if (input_files[ist->file_index]->eagain ||
3845 input_files[ist->file_index]->eof_reached)
3847 nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
3848 if (nb_requests > nb_requests_max) {
3849 nb_requests_max = nb_requests;
3855 for (i = 0; i < graph->nb_outputs; i++)
3856 graph->outputs[i]->ost->unavailable = 1;
3862 * Run a single step of transcoding.
3864 * @return 0 for success, <0 for error
3866 static int transcode_step(void)
3872 ost = choose_output();
3879 av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
3884 if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
3889 av_assert0(ost->source_index >= 0);
3890 ist = input_streams[ost->source_index];
3893 ret = process_input(ist->file_index);
3894 if (ret == AVERROR(EAGAIN)) {
3895 if (input_files[ist->file_index]->eagain)
3896 ost->unavailable = 1;
3901 return ret == AVERROR_EOF ? 0 : ret;
3903 return reap_filters(0);
3907 * The following code is the main loop of the file converter
3909 static int transcode(void)
3912 AVFormatContext *os;
3915 int64_t timer_start;
3917 ret = transcode_init();
3921 if (stdin_interaction) {
3922 av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
3925 timer_start = av_gettime_relative();
3928 if ((ret = init_input_threads()) < 0)
3932 while (!received_sigterm) {
3933 int64_t cur_time= av_gettime_relative();
3935 /* if 'q' pressed, exits */
3936 if (stdin_interaction)
3937 if (check_keyboard_interaction(cur_time) < 0)
3940 /* check if there's any stream where output is still needed */
3941 if (!need_output()) {
3942 av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
3946 ret = transcode_step();
3948 if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN)) {
3952 av_strerror(ret, errbuf, sizeof(errbuf));
3954 av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
3959 /* dump report by using the output first video and audio streams */
3960 print_report(0, timer_start, cur_time);
3963 free_input_threads();
3966 /* at the end of stream, we must flush the decoder buffers */
3967 for (i = 0; i < nb_input_streams; i++) {
3968 ist = input_streams[i];
3969 if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3970 process_input_packet(ist, NULL);
3977 /* write the trailer if needed and close file */
3978 for (i = 0; i < nb_output_files; i++) {
3979 os = output_files[i]->ctx;
3980 av_write_trailer(os);
3983 /* dump report by using the first video and audio streams */
3984 print_report(1, timer_start, av_gettime_relative());
3986 /* close each encoder */
3987 for (i = 0; i < nb_output_streams; i++) {
3988 ost = output_streams[i];
3989 if (ost->encoding_needed) {
3990 av_freep(&ost->enc_ctx->stats_in);
3994 /* close each decoder */
3995 for (i = 0; i < nb_input_streams; i++) {
3996 ist = input_streams[i];
3997 if (ist->decoding_needed) {
3998 avcodec_close(ist->dec_ctx);
3999 if (ist->hwaccel_uninit)
4000 ist->hwaccel_uninit(ist->dec_ctx);
4009 free_input_threads();
4012 if (output_streams) {
4013 for (i = 0; i < nb_output_streams; i++) {
4014 ost = output_streams[i];
4017 fclose(ost->logfile);
4018 ost->logfile = NULL;
4020 av_freep(&ost->forced_kf_pts);
4021 av_freep(&ost->apad);
4022 av_freep(&ost->disposition);
4023 av_dict_free(&ost->encoder_opts);
4024 av_dict_free(&ost->swr_opts);
4025 av_dict_free(&ost->resample_opts);
4026 av_dict_free(&ost->bsf_args);
4034 static int64_t getutime(void)
4037 struct rusage rusage;
4039 getrusage(RUSAGE_SELF, &rusage);
4040 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
4041 #elif HAVE_GETPROCESSTIMES
4043 FILETIME c, e, k, u;
4044 proc = GetCurrentProcess();
4045 GetProcessTimes(proc, &c, &e, &k, &u);
4046 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
4048 return av_gettime_relative();
4052 static int64_t getmaxrss(void)
4054 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
4055 struct rusage rusage;
4056 getrusage(RUSAGE_SELF, &rusage);
4057 return (int64_t)rusage.ru_maxrss * 1024;
4058 #elif HAVE_GETPROCESSMEMORYINFO
4060 PROCESS_MEMORY_COUNTERS memcounters;
4061 proc = GetCurrentProcess();
4062 memcounters.cb = sizeof(memcounters);
4063 GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
4064 return memcounters.PeakPagefileUsage;
4070 static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
4074 int main(int argc, char **argv)
4079 register_exit(ffmpeg_cleanup);
4081 setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
4083 av_log_set_flags(AV_LOG_SKIP_REPEATED);
4084 parse_loglevel(argc, argv, options);
4086 if(argc>1 && !strcmp(argv[1], "-d")){
4088 av_log_set_callback(log_callback_null);
4093 avcodec_register_all();
4095 avdevice_register_all();
4097 avfilter_register_all();
4099 avformat_network_init();
4101 show_banner(argc, argv, options);
4105 /* parse options and open all input/output files */
4106 ret = ffmpeg_parse_options(argc, argv);
4110 if (nb_output_files <= 0 && nb_input_files == 0) {
4112 av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
4116 /* file converter / grab */
4117 if (nb_output_files <= 0) {
4118 av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
4122 // if (nb_input_files == 0) {
4123 // av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
4127 current_time = ti = getutime();
4128 if (transcode() < 0)
4130 ti = getutime() - ti;
4132 av_log(NULL, AV_LOG_INFO, "bench: utime=%0.3fs\n", ti / 1000000.0);
4134 av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
4135 decode_error_stat[0], decode_error_stat[1]);
4136 if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
4139 exit_program(received_nb_signals ? 255 : main_return_code);
4140 return main_return_code;