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
41 #include "libavformat/avformat.h"
42 #include "libavdevice/avdevice.h"
43 #include "libswscale/swscale.h"
44 #include "libswresample/swresample.h"
45 #include "libavutil/opt.h"
46 #include "libavutil/channel_layout.h"
47 #include "libavutil/parseutils.h"
48 #include "libavutil/samplefmt.h"
49 #include "libavutil/colorspace.h"
50 #include "libavutil/fifo.h"
51 #include "libavutil/intreadwrite.h"
52 #include "libavutil/dict.h"
53 #include "libavutil/mathematics.h"
54 #include "libavutil/pixdesc.h"
55 #include "libavutil/avstring.h"
56 #include "libavutil/libm.h"
57 #include "libavutil/imgutils.h"
58 #include "libavutil/timestamp.h"
59 #include "libavutil/bprint.h"
60 #include "libavutil/time.h"
61 #include "libavformat/os_support.h"
63 #include "libavformat/ffm.h" // not public API
65 # include "libavfilter/avcodec.h"
66 # include "libavfilter/avfilter.h"
67 # include "libavfilter/avfiltergraph.h"
68 # include "libavfilter/buffersrc.h"
69 # include "libavfilter/buffersink.h"
71 #if HAVE_SYS_RESOURCE_H
73 #include <sys/types.h>
74 #include <sys/resource.h>
75 #elif HAVE_GETPROCESSTIMES
78 #if HAVE_GETPROCESSMEMORYINFO
84 #include <sys/select.h>
89 #include <sys/ioctl.h>
103 #include "cmdutils.h"
105 #include "libavutil/avassert.h"
107 const char program_name[] = "ffmpeg";
108 const int program_birth_year = 2000;
110 static FILE *vstats_file;
112 const char *const forced_keyframes_const_names[] = {
121 static void do_video_stats(OutputStream *ost, int frame_size);
122 static int64_t getutime(void);
123 static int64_t getmaxrss(void);
125 static int run_as_daemon = 0;
126 static int64_t video_size = 0;
127 static int64_t audio_size = 0;
128 static int64_t subtitle_size = 0;
129 static int64_t extra_size = 0;
130 static int nb_frames_dup = 0;
131 static int nb_frames_drop = 0;
133 static int current_time;
134 AVIOContext *progress_avio = NULL;
136 static uint8_t *subtitle_out;
139 /* signal to input threads that they should exit; set by the main thread */
140 static int transcoding_finished;
143 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
145 InputStream **input_streams = NULL;
146 int nb_input_streams = 0;
147 InputFile **input_files = NULL;
148 int nb_input_files = 0;
150 OutputStream **output_streams = NULL;
151 int nb_output_streams = 0;
152 OutputFile **output_files = NULL;
153 int nb_output_files = 0;
155 FilterGraph **filtergraphs;
160 /* init terminal so that we can grab keys */
161 static struct termios oldtty;
162 static int restore_tty;
167 Convert subtitles to video with alpha to insert them in filter graphs.
168 This is a temporary solution until libavfilter gets real subtitles support.
171 static int sub2video_get_blank_frame(InputStream *ist)
174 AVFrame *frame = ist->sub2video.frame;
176 av_frame_unref(frame);
177 ist->sub2video.frame->width = ist->sub2video.w;
178 ist->sub2video.frame->height = ist->sub2video.h;
179 ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
180 if ((ret = av_frame_get_buffer(frame, 32)) < 0)
182 memset(frame->data[0], 0, frame->height * frame->linesize[0]);
186 static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
189 uint32_t *pal, *dst2;
193 if (r->type != SUBTITLE_BITMAP) {
194 av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
197 if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
198 av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle overflowing\n");
202 dst += r->y * dst_linesize + r->x * 4;
203 src = r->pict.data[0];
204 pal = (uint32_t *)r->pict.data[1];
205 for (y = 0; y < r->h; y++) {
206 dst2 = (uint32_t *)dst;
208 for (x = 0; x < r->w; x++)
209 *(dst2++) = pal[*(src2++)];
211 src += r->pict.linesize[0];
215 static void sub2video_push_ref(InputStream *ist, int64_t pts)
217 AVFrame *frame = ist->sub2video.frame;
220 av_assert1(frame->data[0]);
221 ist->sub2video.last_pts = frame->pts = pts;
222 for (i = 0; i < ist->nb_filters; i++)
223 av_buffersrc_add_frame_flags(ist->filters[i]->filter, frame,
224 AV_BUFFERSRC_FLAG_KEEP_REF |
225 AV_BUFFERSRC_FLAG_PUSH);
228 static void sub2video_update(InputStream *ist, AVSubtitle *sub)
230 int w = ist->sub2video.w, h = ist->sub2video.h;
231 AVFrame *frame = ist->sub2video.frame;
235 int64_t pts, end_pts;
240 pts = av_rescale_q(sub->pts + sub->start_display_time * 1000,
241 AV_TIME_BASE_Q, ist->st->time_base);
242 end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000,
243 AV_TIME_BASE_Q, ist->st->time_base);
244 num_rects = sub->num_rects;
246 pts = ist->sub2video.end_pts;
250 if (sub2video_get_blank_frame(ist) < 0) {
251 av_log(ist->st->codec, AV_LOG_ERROR,
252 "Impossible to get a blank canvas.\n");
255 dst = frame->data [0];
256 dst_linesize = frame->linesize[0];
257 for (i = 0; i < num_rects; i++)
258 sub2video_copy_rect(dst, dst_linesize, w, h, sub->rects[i]);
259 sub2video_push_ref(ist, pts);
260 ist->sub2video.end_pts = end_pts;
263 static void sub2video_heartbeat(InputStream *ist, int64_t pts)
265 InputFile *infile = input_files[ist->file_index];
269 /* When a frame is read from a file, examine all sub2video streams in
270 the same file and send the sub2video frame again. Otherwise, decoded
271 video frames could be accumulating in the filter graph while a filter
272 (possibly overlay) is desperately waiting for a subtitle frame. */
273 for (i = 0; i < infile->nb_streams; i++) {
274 InputStream *ist2 = input_streams[infile->ist_index + i];
275 if (!ist2->sub2video.frame)
277 /* subtitles seem to be usually muxed ahead of other streams;
278 if not, substracting a larger time here is necessary */
279 pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
280 /* do not send the heartbeat frame if the subtitle is already ahead */
281 if (pts2 <= ist2->sub2video.last_pts)
283 if (pts2 >= ist2->sub2video.end_pts || !ist2->sub2video.frame->data[0])
284 sub2video_update(ist2, NULL);
285 for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
286 nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
288 sub2video_push_ref(ist2, pts2);
292 static void sub2video_flush(InputStream *ist)
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 */
304 av_log(NULL, AV_LOG_QUIET, "%s", "");
307 tcsetattr (0, TCSANOW, &oldtty);
311 static volatile int received_sigterm = 0;
312 static volatile int received_nb_signals = 0;
315 sigterm_handler(int sig)
317 received_sigterm = sig;
318 received_nb_signals++;
320 if(received_nb_signals > 3)
331 istty = isatty(0) && isatty(2);
333 if (istty && tcgetattr (0, &tty) == 0) {
338 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
339 |INLCR|IGNCR|ICRNL|IXON);
340 tty.c_oflag |= OPOST;
341 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
342 tty.c_cflag &= ~(CSIZE|PARENB);
347 tcsetattr (0, TCSANOW, &tty);
349 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
352 avformat_network_deinit();
354 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
355 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
357 signal(SIGXCPU, sigterm_handler);
361 /* read a key without blocking */
362 static int read_key(void)
374 n = select(1, &rfds, NULL, NULL, &tv);
383 # if HAVE_PEEKNAMEDPIPE
385 static HANDLE input_handle;
388 input_handle = GetStdHandle(STD_INPUT_HANDLE);
389 is_pipe = !GetConsoleMode(input_handle, &dw);
392 if (stdin->_cnt > 0) {
397 /* When running under a GUI, you will end here. */
398 if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
399 // input pipe may have been closed by the program that ran ffmpeg
417 static int decode_interrupt_cb(void *ctx)
419 return received_nb_signals > 1;
422 const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
424 static void exit_program(void)
429 int maxrss = getmaxrss() / 1024;
430 printf("bench: maxrss=%ikB\n", maxrss);
433 for (i = 0; i < nb_filtergraphs; i++) {
434 avfilter_graph_free(&filtergraphs[i]->graph);
435 for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
436 av_freep(&filtergraphs[i]->inputs[j]->name);
437 av_freep(&filtergraphs[i]->inputs[j]);
439 av_freep(&filtergraphs[i]->inputs);
440 for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
441 av_freep(&filtergraphs[i]->outputs[j]->name);
442 av_freep(&filtergraphs[i]->outputs[j]);
444 av_freep(&filtergraphs[i]->outputs);
445 av_freep(&filtergraphs[i]);
447 av_freep(&filtergraphs);
449 av_freep(&subtitle_out);
452 for (i = 0; i < nb_output_files; i++) {
453 AVFormatContext *s = output_files[i]->ctx;
454 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
456 avformat_free_context(s);
457 av_dict_free(&output_files[i]->opts);
458 av_freep(&output_files[i]);
460 for (i = 0; i < nb_output_streams; i++) {
461 AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
463 AVBitStreamFilterContext *next = bsfc->next;
464 av_bitstream_filter_close(bsfc);
467 output_streams[i]->bitstream_filters = NULL;
468 avcodec_free_frame(&output_streams[i]->filtered_frame);
470 av_freep(&output_streams[i]->forced_keyframes);
471 av_expr_free(output_streams[i]->forced_keyframes_pexpr);
472 av_freep(&output_streams[i]->avfilter);
473 av_freep(&output_streams[i]->logfile_prefix);
474 av_freep(&output_streams[i]);
476 for (i = 0; i < nb_input_files; i++) {
477 avformat_close_input(&input_files[i]->ctx);
478 av_freep(&input_files[i]);
480 for (i = 0; i < nb_input_streams; i++) {
481 avcodec_free_frame(&input_streams[i]->decoded_frame);
482 av_dict_free(&input_streams[i]->opts);
483 free_buffer_pool(&input_streams[i]->buffer_pool);
484 avsubtitle_free(&input_streams[i]->prev_sub.subtitle);
485 avcodec_free_frame(&input_streams[i]->sub2video.frame);
486 av_freep(&input_streams[i]->filters);
487 av_freep(&input_streams[i]);
492 av_free(vstats_filename);
494 av_freep(&input_streams);
495 av_freep(&input_files);
496 av_freep(&output_streams);
497 av_freep(&output_files);
502 avformat_network_deinit();
504 if (received_sigterm) {
505 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
506 (int) received_sigterm);
510 void assert_avoptions(AVDictionary *m)
512 AVDictionaryEntry *t;
513 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
514 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
519 static void abort_codec_experimental(AVCodec *c, int encoder)
524 static void update_benchmark(const char *fmt, ...)
526 if (do_benchmark_all) {
527 int64_t t = getutime();
533 vsnprintf(buf, sizeof(buf), fmt, va);
535 printf("bench: %8"PRIu64" %s \n", t - current_time, buf);
541 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
543 AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
544 AVCodecContext *avctx = ost->st->codec;
547 if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
548 (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
549 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
551 if ((avctx->codec_type == AVMEDIA_TYPE_AUDIO || avctx->codec_type == AVMEDIA_TYPE_VIDEO) && pkt->dts != AV_NOPTS_VALUE) {
552 int64_t max = ost->st->cur_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
553 if (ost->st->cur_dts && ost->st->cur_dts != AV_NOPTS_VALUE && max > pkt->dts) {
554 av_log(s, max - pkt->dts > 2 || avctx->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG,
555 "st:%d PTS: %"PRId64" DTS: %"PRId64" < %"PRId64" invalid, clipping\n", pkt->stream_index, pkt->pts, pkt->dts, max);
556 if(pkt->pts >= pkt->dts)
557 pkt->pts = FFMAX(pkt->pts, max);
563 * Audio encoders may split the packets -- #frames in != #packets out.
564 * But there is no reordering, so we can limit the number of output packets
565 * by simply dropping them here.
566 * Counting encoded video frames needs to be done separately because of
567 * reordering, see do_video_out()
569 if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
570 if (ost->frame_number >= ost->max_frames) {
578 AVPacket new_pkt = *pkt;
579 int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
580 &new_pkt.data, &new_pkt.size,
581 pkt->data, pkt->size,
582 pkt->flags & AV_PKT_FLAG_KEY);
583 if(a == 0 && new_pkt.data != pkt->data && new_pkt.destruct) {
584 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
586 memcpy(t, new_pkt.data, new_pkt.size);
587 memset(t + new_pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
596 new_pkt.destruct = av_destruct_packet;
598 av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
599 bsfc->filter->name, pkt->stream_index,
600 avctx->codec ? avctx->codec->name : "copy");
610 pkt->stream_index = ost->index;
613 av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
614 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
615 av_get_media_type_string(ost->st->codec->codec_type),
616 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
617 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
622 ret = av_interleaved_write_frame(s, pkt);
624 print_error("av_interleaved_write_frame()", ret);
629 static void close_output_stream(OutputStream *ost)
631 OutputFile *of = output_files[ost->file_index];
635 int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, AV_TIME_BASE_Q);
636 of->recording_time = FFMIN(of->recording_time, end);
640 static int check_recording_time(OutputStream *ost)
642 OutputFile *of = output_files[ost->file_index];
644 if (of->recording_time != INT64_MAX &&
645 av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
646 AV_TIME_BASE_Q) >= 0) {
647 close_output_stream(ost);
653 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
656 AVCodecContext *enc = ost->st->codec;
660 av_init_packet(&pkt);
664 if (!check_recording_time(ost))
667 if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
668 frame->pts = ost->sync_opts;
669 ost->sync_opts = frame->pts + frame->nb_samples;
671 av_assert0(pkt.size || !pkt.data);
672 update_benchmark(NULL);
673 if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
674 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
677 update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
680 if (pkt.pts != AV_NOPTS_VALUE)
681 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
682 if (pkt.dts != AV_NOPTS_VALUE)
683 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
684 if (pkt.duration > 0)
685 pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
688 av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
689 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
690 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
691 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
694 audio_size += pkt.size;
695 write_frame(s, &pkt, ost);
697 av_free_packet(&pkt);
701 #if FF_API_DEINTERLACE
702 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
706 AVPicture picture_tmp;
709 dec = ist->st->codec;
711 /* deinterlace : must be done before any resize */
712 if (FF_API_DEINTERLACE && do_deinterlace) {
715 /* create temporary picture */
716 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
719 buf = av_malloc(size);
723 picture2 = &picture_tmp;
724 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
726 if (avpicture_deinterlace(picture2, picture,
727 dec->pix_fmt, dec->width, dec->height) < 0) {
728 /* if error, do not deinterlace */
729 av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
738 if (picture != picture2)
739 *picture = *picture2;
744 static void do_subtitle_out(AVFormatContext *s,
749 int subtitle_out_max_size = 1024 * 1024;
750 int subtitle_out_size, nb, i;
755 if (sub->pts == AV_NOPTS_VALUE) {
756 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
762 enc = ost->st->codec;
765 subtitle_out = av_malloc(subtitle_out_max_size);
768 /* Note: DVB subtitle need one packet to draw them and one other
769 packet to clear them */
770 /* XXX: signal it in the codec context ? */
771 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
776 /* shift timestamp to honor -ss and make check_recording_time() work with -t */
777 pts = sub->pts - output_files[ost->file_index]->start_time;
778 for (i = 0; i < nb; i++) {
779 ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
780 if (!check_recording_time(ost))
784 // start_display_time is required to be 0
785 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
786 sub->end_display_time -= sub->start_display_time;
787 sub->start_display_time = 0;
790 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
791 subtitle_out_max_size, sub);
792 if (subtitle_out_size < 0) {
793 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
797 av_init_packet(&pkt);
798 pkt.data = subtitle_out;
799 pkt.size = subtitle_out_size;
800 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
801 pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
802 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
803 /* XXX: the pts correction is handled here. Maybe handling
804 it in the codec would be better */
806 pkt.pts += 90 * sub->start_display_time;
808 pkt.pts += 90 * sub->end_display_time;
810 subtitle_size += pkt.size;
811 write_frame(s, &pkt, ost);
815 static void do_video_out(AVFormatContext *s,
819 int ret, format_video_sync;
821 AVCodecContext *enc = ost->st->codec;
823 double sync_ipts, delta;
826 InputStream *ist = NULL;
828 if (ost->source_index >= 0)
829 ist = input_streams[ost->source_index];
831 if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
832 duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));
834 sync_ipts = in_picture->pts;
835 delta = sync_ipts - ost->sync_opts + duration;
837 /* by default, we output a single frame */
840 format_video_sync = video_sync_method;
841 if (format_video_sync == VSYNC_AUTO)
842 format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;
844 switch (format_video_sync) {
846 // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
849 else if (delta > 1.1)
850 nb_frames = lrintf(delta);
855 else if (delta > 0.6)
856 ost->sync_opts = lrint(sync_ipts);
859 case VSYNC_PASSTHROUGH:
860 ost->sync_opts = lrint(sync_ipts);
866 nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
867 if (nb_frames == 0) {
869 av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
871 } else if (nb_frames > 1) {
872 if (nb_frames > dts_error_threshold * 30) {
873 av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
877 nb_frames_dup += nb_frames - 1;
878 av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
881 /* duplicates frame if needed */
882 for (i = 0; i < nb_frames; i++) {
883 av_init_packet(&pkt);
887 in_picture->pts = ost->sync_opts;
889 if (!check_recording_time(ost))
892 if (s->oformat->flags & AVFMT_RAWPICTURE &&
893 enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
894 /* raw pictures are written as AVPicture structure to
895 avoid any copies. We support temporarily the older
897 enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
898 enc->coded_frame->top_field_first = in_picture->top_field_first;
899 if (enc->coded_frame->interlaced_frame)
900 enc->field_order = enc->coded_frame->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
902 enc->field_order = AV_FIELD_PROGRESSIVE;
903 pkt.data = (uint8_t *)in_picture;
904 pkt.size = sizeof(AVPicture);
905 pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
906 pkt.flags |= AV_PKT_FLAG_KEY;
908 video_size += pkt.size;
909 write_frame(s, &pkt, ost);
911 int got_packet, forced_keyframe = 0;
915 big_picture = *in_picture;
916 /* better than nothing: use input picture interlaced
918 big_picture.interlaced_frame = in_picture->interlaced_frame;
919 if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
920 if (ost->top_field_first == -1)
921 big_picture.top_field_first = in_picture->top_field_first;
923 big_picture.top_field_first = !!ost->top_field_first;
926 if (big_picture.interlaced_frame) {
927 if (enc->codec->id == AV_CODEC_ID_MJPEG)
928 enc->field_order = big_picture.top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
930 enc->field_order = big_picture.top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
932 enc->field_order = AV_FIELD_PROGRESSIVE;
934 big_picture.quality = ost->st->codec->global_quality;
935 if (!enc->me_threshold)
936 big_picture.pict_type = 0;
938 pts_time = big_picture.pts != AV_NOPTS_VALUE ?
939 big_picture.pts * av_q2d(enc->time_base) : NAN;
940 if (ost->forced_kf_index < ost->forced_kf_count &&
941 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
942 ost->forced_kf_index++;
944 } else if (ost->forced_keyframes_pexpr) {
946 ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
947 res = av_expr_eval(ost->forced_keyframes_pexpr,
948 ost->forced_keyframes_expr_const_values, NULL);
949 av_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
950 ost->forced_keyframes_expr_const_values[FKF_N],
951 ost->forced_keyframes_expr_const_values[FKF_N_FORCED],
952 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],
953 ost->forced_keyframes_expr_const_values[FKF_T],
954 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],
958 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =
959 ost->forced_keyframes_expr_const_values[FKF_N];
960 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =
961 ost->forced_keyframes_expr_const_values[FKF_T];
962 ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;
965 ost->forced_keyframes_expr_const_values[FKF_N] += 1;
967 if (forced_keyframe) {
968 big_picture.pict_type = AV_PICTURE_TYPE_I;
969 av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
972 update_benchmark(NULL);
973 ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
974 update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
976 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
981 if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
982 pkt.pts = ost->sync_opts;
984 if (pkt.pts != AV_NOPTS_VALUE)
985 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
986 if (pkt.dts != AV_NOPTS_VALUE)
987 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
990 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
991 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
992 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
993 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
996 frame_size = pkt.size;
997 video_size += pkt.size;
998 write_frame(s, &pkt, ost);
999 av_free_packet(&pkt);
1001 /* if two pass, output log */
1002 if (ost->logfile && enc->stats_out) {
1003 fprintf(ost->logfile, "%s", enc->stats_out);
1009 * For video, number of frames in == number of packets out.
1010 * But there may be reordering, so we can't throw away frames on encoder
1011 * flush, we need to limit them here, before they go into encoder.
1013 ost->frame_number++;
1016 if (vstats_filename && frame_size)
1017 do_video_stats(ost, frame_size);
1020 static double psnr(double d)
1022 return -10.0 * log(d) / log(10.0);
1025 static void do_video_stats(OutputStream *ost, int frame_size)
1027 AVCodecContext *enc;
1029 double ti1, bitrate, avg_bitrate;
1031 /* this is executed just the first time do_video_stats is called */
1033 vstats_file = fopen(vstats_filename, "w");
1040 enc = ost->st->codec;
1041 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1042 frame_number = ost->st->nb_frames;
1043 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1044 if (enc->flags&CODEC_FLAG_PSNR)
1045 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1047 fprintf(vstats_file,"f_size= %6d ", frame_size);
1048 /* compute pts value */
1049 ti1 = ost->st->pts.val * av_q2d(enc->time_base);
1053 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1054 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1055 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1056 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1057 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1062 * Get and encode new output from any of the filtergraphs, without causing
1065 * @return 0 for success, <0 for severe errors
1067 static int reap_filters(void)
1069 AVFilterBufferRef *picref;
1070 AVFrame *filtered_frame = NULL;
1074 /* Reap all buffers present in the buffer sinks */
1075 for (i = 0; i < nb_output_streams; i++) {
1076 OutputStream *ost = output_streams[i];
1077 OutputFile *of = output_files[ost->file_index];
1083 if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
1084 return AVERROR(ENOMEM);
1086 avcodec_get_frame_defaults(ost->filtered_frame);
1087 filtered_frame = ost->filtered_frame;
1090 ret = av_buffersink_get_buffer_ref(ost->filter->filter, &picref,
1091 AV_BUFFERSINK_FLAG_NO_REQUEST);
1093 if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
1095 av_strerror(ret, buf, sizeof(buf));
1096 av_log(NULL, AV_LOG_WARNING,
1097 "Error in av_buffersink_get_buffer_ref(): %s\n", buf);
1101 frame_pts = AV_NOPTS_VALUE;
1102 if (picref->pts != AV_NOPTS_VALUE) {
1103 filtered_frame->pts = frame_pts = av_rescale_q(picref->pts,
1104 ost->filter->filter->inputs[0]->time_base,
1105 ost->st->codec->time_base) -
1106 av_rescale_q(of->start_time,
1108 ost->st->codec->time_base);
1110 if (of->start_time && filtered_frame->pts < 0) {
1111 avfilter_unref_buffer(picref);
1115 //if (ost->source_index >= 0)
1116 // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
1119 switch (ost->filter->filter->inputs[0]->type) {
1120 case AVMEDIA_TYPE_VIDEO:
1121 avfilter_copy_buf_props(filtered_frame, picref);
1122 filtered_frame->pts = frame_pts;
1123 if (!ost->frame_aspect_ratio)
1124 ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;
1126 do_video_out(of->ctx, ost, filtered_frame);
1128 case AVMEDIA_TYPE_AUDIO:
1129 avfilter_copy_buf_props(filtered_frame, picref);
1130 filtered_frame->pts = frame_pts;
1131 if (!(ost->st->codec->codec->capabilities & CODEC_CAP_PARAM_CHANGE) &&
1132 ost->st->codec->channels != av_frame_get_channels(filtered_frame)) {
1133 av_log(NULL, AV_LOG_ERROR,
1134 "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
1137 do_audio_out(of->ctx, ost, filtered_frame);
1140 // TODO support subtitle filters
1144 avfilter_unref_buffer(picref);
1151 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
1154 AVBPrint buf_script;
1156 AVFormatContext *oc;
1158 AVCodecContext *enc;
1159 int frame_number, vid, i;
1161 int64_t pts = INT64_MIN;
1162 static int64_t last_time = -1;
1163 static int qp_histogram[52];
1164 int hours, mins, secs, us;
1166 if (!print_stats && !is_last_report && !progress_avio)
1169 if (!is_last_report) {
1170 if (last_time == -1) {
1171 last_time = cur_time;
1174 if ((cur_time - last_time) < 500000)
1176 last_time = cur_time;
1180 oc = output_files[0]->ctx;
1182 total_size = avio_size(oc->pb);
1183 if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
1184 total_size = avio_tell(oc->pb);
1188 av_bprint_init(&buf_script, 0, 1);
1189 for (i = 0; i < nb_output_streams; i++) {
1191 ost = output_streams[i];
1192 enc = ost->st->codec;
1193 if (!ost->stream_copy && enc->coded_frame)
1194 q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
1195 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1196 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1197 av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1198 ost->file_index, ost->index, q);
1200 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1201 float fps, t = (cur_time-timer_start) / 1000000.0;
1203 frame_number = ost->frame_number;
1204 fps = t > 1 ? frame_number / t : 0;
1205 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
1206 frame_number, fps < 9.95, fps, q);
1207 av_bprintf(&buf_script, "frame=%d\n", frame_number);
1208 av_bprintf(&buf_script, "fps=%.1f\n", fps);
1209 av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1210 ost->file_index, ost->index, q);
1212 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1216 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1218 for (j = 0; j < 32; j++)
1219 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
1221 if ((enc->flags&CODEC_FLAG_PSNR) && (enc->coded_frame || is_last_report)) {
1223 double error, error_sum = 0;
1224 double scale, scale_sum = 0;
1226 char type[3] = { 'Y','U','V' };
1227 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1228 for (j = 0; j < 3; j++) {
1229 if (is_last_report) {
1230 error = enc->error[j];
1231 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1233 error = enc->coded_frame->error[j];
1234 scale = enc->width * enc->height * 255.0 * 255.0;
1240 p = psnr(error / scale);
1241 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
1242 av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
1243 ost->file_index, ost->index, type[j] | 32, p);
1245 p = psnr(error_sum / scale_sum);
1246 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1247 av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
1248 ost->file_index, ost->index, p);
1252 /* compute min output value */
1253 if ((is_last_report || !ost->finished) && ost->st->pts.val != AV_NOPTS_VALUE)
1254 pts = FFMAX(pts, av_rescale_q(ost->st->pts.val,
1255 ost->st->time_base, AV_TIME_BASE_Q));
1258 secs = pts / AV_TIME_BASE;
1259 us = pts % AV_TIME_BASE;
1265 bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
1267 if (total_size < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1269 else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1270 "size=%8.0fkB time=", total_size / 1024.0);
1271 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1272 "%02d:%02d:%02d.%02d ", hours, mins, secs,
1273 (100 * us) / AV_TIME_BASE);
1274 if (bitrate < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1276 else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1277 "bitrate=%6.1fkbits/s", bitrate);
1278 if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
1279 else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
1280 av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
1281 av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
1282 hours, mins, secs, us);
1284 if (nb_frames_dup || nb_frames_drop)
1285 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1286 nb_frames_dup, nb_frames_drop);
1287 av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
1288 av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
1290 if (print_stats || is_last_report) {
1291 if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
1292 fprintf(stderr, "%s \r", buf);
1294 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
1299 if (progress_avio) {
1300 av_bprintf(&buf_script, "progress=%s\n",
1301 is_last_report ? "end" : "continue");
1302 avio_write(progress_avio, buf_script.str,
1303 FFMIN(buf_script.len, buf_script.size - 1));
1304 avio_flush(progress_avio);
1305 av_bprint_finalize(&buf_script, NULL);
1306 if (is_last_report) {
1307 avio_close(progress_avio);
1308 progress_avio = NULL;
1312 if (is_last_report) {
1313 int64_t raw= audio_size + video_size + subtitle_size + extra_size;
1314 av_log(NULL, AV_LOG_INFO, "\n");
1315 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0f global headers:%1.0fkB muxing overhead %f%%\n",
1316 video_size / 1024.0,
1317 audio_size / 1024.0,
1318 subtitle_size / 1024.0,
1319 extra_size / 1024.0,
1320 100.0 * (total_size - raw) / raw
1322 if(video_size + audio_size + subtitle_size + extra_size == 0){
1323 av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
1328 static void flush_encoders(void)
1332 for (i = 0; i < nb_output_streams; i++) {
1333 OutputStream *ost = output_streams[i];
1334 AVCodecContext *enc = ost->st->codec;
1335 AVFormatContext *os = output_files[ost->file_index]->ctx;
1336 int stop_encoding = 0;
1338 if (!ost->encoding_needed)
1341 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1343 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
1347 int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
1351 switch (ost->st->codec->codec_type) {
1352 case AVMEDIA_TYPE_AUDIO:
1353 encode = avcodec_encode_audio2;
1357 case AVMEDIA_TYPE_VIDEO:
1358 encode = avcodec_encode_video2;
1369 av_init_packet(&pkt);
1373 update_benchmark(NULL);
1374 ret = encode(enc, &pkt, NULL, &got_packet);
1375 update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
1377 av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
1381 if (ost->logfile && enc->stats_out) {
1382 fprintf(ost->logfile, "%s", enc->stats_out);
1388 if (pkt.pts != AV_NOPTS_VALUE)
1389 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1390 if (pkt.dts != AV_NOPTS_VALUE)
1391 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1392 if (pkt.duration > 0)
1393 pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
1394 write_frame(os, &pkt, ost);
1395 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
1396 do_video_stats(ost, pkt.size);
1407 * Check whether a packet from ist should be written into ost at this time
1409 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1411 OutputFile *of = output_files[ost->file_index];
1412 int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
1414 if (ost->source_index != ist_index)
1417 if (of->start_time && ist->pts < of->start_time)
1423 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1425 OutputFile *of = output_files[ost->file_index];
1426 int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
1430 av_init_packet(&opkt);
1432 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1433 !ost->copy_initial_nonkeyframes)
1436 if (!ost->frame_number && ist->pts < of->start_time &&
1437 !ost->copy_prior_start)
1440 if (of->recording_time != INT64_MAX &&
1441 ist->pts >= of->recording_time + of->start_time) {
1442 close_output_stream(ost);
1446 /* force the input stream PTS */
1447 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1448 audio_size += pkt->size;
1449 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1450 video_size += pkt->size;
1452 } else if (ost->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1453 subtitle_size += pkt->size;
1456 if (pkt->pts != AV_NOPTS_VALUE)
1457 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1459 opkt.pts = AV_NOPTS_VALUE;
1461 if (pkt->dts == AV_NOPTS_VALUE)
1462 opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
1464 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1465 opkt.dts -= ost_tb_start_time;
1467 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
1468 int duration = av_get_audio_frame_duration(ist->st->codec, pkt->size);
1470 duration = ist->st->codec->frame_size;
1471 opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
1472 (AVRational){1, ist->st->codec->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
1473 ost->st->time_base) - ost_tb_start_time;
1476 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1477 opkt.flags = pkt->flags;
1479 // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1480 if ( ost->st->codec->codec_id != AV_CODEC_ID_H264
1481 && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
1482 && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
1483 && ost->st->codec->codec_id != AV_CODEC_ID_VC1
1485 if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
1486 opkt.destruct = av_destruct_packet;
1488 opkt.data = pkt->data;
1489 opkt.size = pkt->size;
1492 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
1493 /* store AVPicture in AVPacket, as expected by the output format */
1494 avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
1495 opkt.data = (uint8_t *)&pict;
1496 opkt.size = sizeof(AVPicture);
1497 opkt.flags |= AV_PKT_FLAG_KEY;
1500 write_frame(of->ctx, &opkt, ost);
1501 ost->st->codec->frame_number++;
1504 static void rate_emu_sleep(InputStream *ist)
1506 if (input_files[ist->file_index]->rate_emu) {
1507 int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
1508 int64_t now = av_gettime() - ist->start;
1510 av_usleep(pts - now);
1514 int guess_input_channel_layout(InputStream *ist)
1516 AVCodecContext *dec = ist->st->codec;
1518 if (!dec->channel_layout) {
1519 char layout_name[256];
1521 if (dec->channels > ist->guess_layout_max)
1523 dec->channel_layout = av_get_default_channel_layout(dec->channels);
1524 if (!dec->channel_layout)
1526 av_get_channel_layout_string(layout_name, sizeof(layout_name),
1527 dec->channels, dec->channel_layout);
1528 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
1529 "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1534 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1536 AVFrame *decoded_frame;
1537 AVCodecContext *avctx = ist->st->codec;
1538 int i, ret, resample_changed;
1539 AVRational decoded_frame_tb;
1541 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1542 return AVERROR(ENOMEM);
1543 decoded_frame = ist->decoded_frame;
1545 update_benchmark(NULL);
1546 ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1547 update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
1549 if (ret >= 0 && avctx->sample_rate <= 0) {
1550 av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
1551 ret = AVERROR_INVALIDDATA;
1554 if (!*got_output || ret < 0) {
1556 for (i = 0; i < ist->nb_filters; i++)
1557 av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
1563 /* increment next_dts to use for the case where the input stream does not
1564 have timestamps or there are multiple frames in the packet */
1565 ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1567 ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1571 rate_emu_sleep(ist);
1573 resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
1574 ist->resample_channels != avctx->channels ||
1575 ist->resample_channel_layout != decoded_frame->channel_layout ||
1576 ist->resample_sample_rate != decoded_frame->sample_rate;
1577 if (resample_changed) {
1578 char layout1[64], layout2[64];
1580 if (!guess_input_channel_layout(ist)) {
1581 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
1582 "layout for Input Stream #%d.%d\n", ist->file_index,
1586 decoded_frame->channel_layout = avctx->channel_layout;
1588 av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
1589 ist->resample_channel_layout);
1590 av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
1591 decoded_frame->channel_layout);
1593 av_log(NULL, AV_LOG_INFO,
1594 "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",
1595 ist->file_index, ist->st->index,
1596 ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
1597 ist->resample_channels, layout1,
1598 decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
1599 avctx->channels, layout2);
1601 ist->resample_sample_fmt = decoded_frame->format;
1602 ist->resample_sample_rate = decoded_frame->sample_rate;
1603 ist->resample_channel_layout = decoded_frame->channel_layout;
1604 ist->resample_channels = avctx->channels;
1606 for (i = 0; i < nb_filtergraphs; i++)
1607 if (ist_in_filtergraph(filtergraphs[i], ist)) {
1608 FilterGraph *fg = filtergraphs[i];
1610 if (configure_filtergraph(fg) < 0) {
1611 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1614 for (j = 0; j < fg->nb_outputs; j++) {
1615 OutputStream *ost = fg->outputs[j]->ost;
1616 if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
1617 !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
1618 av_buffersink_set_frame_size(ost->filter->filter,
1619 ost->st->codec->frame_size);
1624 /* if the decoder provides a pts, use it instead of the last packet pts.
1625 the decoder could be delaying output by a packet or more. */
1626 if (decoded_frame->pts != AV_NOPTS_VALUE) {
1627 ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
1628 decoded_frame_tb = avctx->time_base;
1629 } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
1630 decoded_frame->pts = decoded_frame->pkt_pts;
1631 pkt->pts = AV_NOPTS_VALUE;
1632 decoded_frame_tb = ist->st->time_base;
1633 } else if (pkt->pts != AV_NOPTS_VALUE) {
1634 decoded_frame->pts = pkt->pts;
1635 pkt->pts = AV_NOPTS_VALUE;
1636 decoded_frame_tb = ist->st->time_base;
1638 decoded_frame->pts = ist->dts;
1639 decoded_frame_tb = AV_TIME_BASE_Q;
1641 if (decoded_frame->pts != AV_NOPTS_VALUE)
1642 decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
1643 (AVRational){1, ist->st->codec->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
1644 (AVRational){1, ist->st->codec->sample_rate});
1645 for (i = 0; i < ist->nb_filters; i++)
1646 av_buffersrc_add_frame_flags(ist->filters[i]->filter, decoded_frame,
1647 AV_BUFFERSRC_FLAG_KEEP_REF |
1648 AV_BUFFERSRC_FLAG_PUSH);
1650 decoded_frame->pts = AV_NOPTS_VALUE;
1655 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
1657 AVFrame *decoded_frame;
1658 void *buffer_to_free = NULL;
1659 int i, ret = 0, resample_changed;
1660 int64_t best_effort_timestamp;
1661 AVRational *frame_sample_aspect;
1663 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1664 return AVERROR(ENOMEM);
1665 decoded_frame = ist->decoded_frame;
1666 pkt->dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
1668 update_benchmark(NULL);
1669 ret = avcodec_decode_video2(ist->st->codec,
1670 decoded_frame, got_output, pkt);
1671 update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
1672 if (!*got_output || ret < 0) {
1674 for (i = 0; i < ist->nb_filters; i++)
1675 av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
1680 if(ist->top_field_first>=0)
1681 decoded_frame->top_field_first = ist->top_field_first;
1683 best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
1684 if(best_effort_timestamp != AV_NOPTS_VALUE)
1685 ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
1688 av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
1689 "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d \n",
1690 ist->st->index, av_ts2str(decoded_frame->pts),
1691 av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
1692 best_effort_timestamp,
1693 av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
1694 decoded_frame->key_frame, decoded_frame->pict_type);
1698 #if FF_API_DEINTERLACE
1699 pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
1702 rate_emu_sleep(ist);
1704 if (ist->st->sample_aspect_ratio.num)
1705 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
1707 resample_changed = ist->resample_width != decoded_frame->width ||
1708 ist->resample_height != decoded_frame->height ||
1709 ist->resample_pix_fmt != decoded_frame->format;
1710 if (resample_changed) {
1711 av_log(NULL, AV_LOG_INFO,
1712 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1713 ist->file_index, ist->st->index,
1714 ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
1715 decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
1717 ist->resample_width = decoded_frame->width;
1718 ist->resample_height = decoded_frame->height;
1719 ist->resample_pix_fmt = decoded_frame->format;
1721 for (i = 0; i < nb_filtergraphs; i++) {
1722 if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
1723 configure_filtergraph(filtergraphs[i]) < 0) {
1724 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1730 frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
1731 for (i = 0; i < ist->nb_filters; i++) {
1732 int changed = ist->st->codec->width != ist->filters[i]->filter->outputs[0]->w
1733 || ist->st->codec->height != ist->filters[i]->filter->outputs[0]->h
1734 || ist->st->codec->pix_fmt != ist->filters[i]->filter->outputs[0]->format;
1736 if (!frame_sample_aspect->num)
1737 *frame_sample_aspect = ist->st->sample_aspect_ratio;
1738 if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
1739 FrameBuffer *buf = decoded_frame->opaque;
1740 AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
1741 decoded_frame->data, decoded_frame->linesize,
1742 AV_PERM_READ | AV_PERM_PRESERVE,
1743 ist->st->codec->width, ist->st->codec->height,
1744 ist->st->codec->pix_fmt);
1746 avfilter_copy_frame_props(fb, decoded_frame);
1747 fb->buf->priv = buf;
1748 fb->buf->free = filter_release_buffer;
1750 av_assert0(buf->refcount>0);
1752 av_buffersrc_add_ref(ist->filters[i]->filter, fb,
1753 AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT |
1754 AV_BUFFERSRC_FLAG_NO_COPY |
1755 AV_BUFFERSRC_FLAG_PUSH);
1757 if(av_buffersrc_add_frame_flags(ist->filters[i]->filter, decoded_frame,
1758 AV_BUFFERSRC_FLAG_KEEP_REF |
1759 AV_BUFFERSRC_FLAG_PUSH)<0) {
1760 av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
1766 av_free(buffer_to_free);
1770 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
1772 AVSubtitle subtitle;
1773 int i, ret = avcodec_decode_subtitle2(ist->st->codec,
1774 &subtitle, got_output, pkt);
1775 if (ret < 0 || !*got_output) {
1777 sub2video_flush(ist);
1781 if (ist->fix_sub_duration) {
1782 if (ist->prev_sub.got_output) {
1783 int end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
1784 1000, AV_TIME_BASE);
1785 if (end < ist->prev_sub.subtitle.end_display_time) {
1786 av_log(ist->st->codec, AV_LOG_DEBUG,
1787 "Subtitle duration reduced from %d to %d\n",
1788 ist->prev_sub.subtitle.end_display_time, end);
1789 ist->prev_sub.subtitle.end_display_time = end;
1792 FFSWAP(int, *got_output, ist->prev_sub.got_output);
1793 FFSWAP(int, ret, ist->prev_sub.ret);
1794 FFSWAP(AVSubtitle, subtitle, ist->prev_sub.subtitle);
1797 sub2video_update(ist, &subtitle);
1799 if (!*got_output || !subtitle.num_rects)
1802 rate_emu_sleep(ist);
1804 for (i = 0; i < nb_output_streams; i++) {
1805 OutputStream *ost = output_streams[i];
1807 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1810 do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle);
1813 avsubtitle_free(&subtitle);
1817 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1818 static int output_packet(InputStream *ist, const AVPacket *pkt)
1824 if (!ist->saw_first_ts) {
1825 ist->dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
1827 if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
1828 ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
1829 ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
1831 ist->saw_first_ts = 1;
1834 if (ist->next_dts == AV_NOPTS_VALUE)
1835 ist->next_dts = ist->dts;
1836 if (ist->next_pts == AV_NOPTS_VALUE)
1837 ist->next_pts = ist->pts;
1841 av_init_packet(&avpkt);
1849 if (pkt->dts != AV_NOPTS_VALUE) {
1850 ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1851 if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
1852 ist->next_pts = ist->pts = ist->dts;
1855 // while we have more to decode or while the decoder did output something on EOF
1856 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
1860 ist->pts = ist->next_pts;
1861 ist->dts = ist->next_dts;
1863 if (avpkt.size && avpkt.size != pkt->size) {
1864 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
1865 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1866 ist->showed_multi_packet_warning = 1;
1869 switch (ist->st->codec->codec_type) {
1870 case AVMEDIA_TYPE_AUDIO:
1871 ret = decode_audio (ist, &avpkt, &got_output);
1873 case AVMEDIA_TYPE_VIDEO:
1874 ret = decode_video (ist, &avpkt, &got_output);
1875 if (avpkt.duration) {
1876 duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
1877 } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
1878 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
1879 duration = ((int64_t)AV_TIME_BASE *
1880 ist->st->codec->time_base.num * ticks) /
1881 ist->st->codec->time_base.den;
1885 if(ist->dts != AV_NOPTS_VALUE && duration) {
1886 ist->next_dts += duration;
1888 ist->next_dts = AV_NOPTS_VALUE;
1891 ist->next_pts += duration; //FIXME the duration is not correct in some cases
1893 case AVMEDIA_TYPE_SUBTITLE:
1894 ret = transcode_subtitles(ist, &avpkt, &got_output);
1904 avpkt.pts= AV_NOPTS_VALUE;
1906 // touch data and size only if not EOF
1908 if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
1918 /* handle stream copy */
1919 if (!ist->decoding_needed) {
1920 rate_emu_sleep(ist);
1921 ist->dts = ist->next_dts;
1922 switch (ist->st->codec->codec_type) {
1923 case AVMEDIA_TYPE_AUDIO:
1924 ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1925 ist->st->codec->sample_rate;
1927 case AVMEDIA_TYPE_VIDEO:
1928 if (pkt->duration) {
1929 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
1930 } else if(ist->st->codec->time_base.num != 0) {
1931 int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
1932 ist->next_dts += ((int64_t)AV_TIME_BASE *
1933 ist->st->codec->time_base.num * ticks) /
1934 ist->st->codec->time_base.den;
1938 ist->pts = ist->dts;
1939 ist->next_pts = ist->next_dts;
1941 for (i = 0; pkt && i < nb_output_streams; i++) {
1942 OutputStream *ost = output_streams[i];
1944 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
1947 do_streamcopy(ist, ost, pkt);
1953 static void print_sdp(void)
1957 AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
1961 for (i = 0; i < nb_output_files; i++)
1962 avc[i] = output_files[i]->ctx;
1964 av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
1965 printf("SDP:\n%s\n", sdp);
1970 static int init_input_stream(int ist_index, char *error, int error_len)
1973 InputStream *ist = input_streams[ist_index];
1975 if (ist->decoding_needed) {
1976 AVCodec *codec = ist->dec;
1978 snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
1979 avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
1980 return AVERROR(EINVAL);
1983 ist->dr1 = (codec->capabilities & CODEC_CAP_DR1) && !(FF_API_DEINTERLACE && do_deinterlace);
1984 if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
1985 ist->st->codec->get_buffer = codec_get_buffer;
1986 ist->st->codec->release_buffer = codec_release_buffer;
1987 ist->st->codec->opaque = &ist->buffer_pool;
1990 if (!av_dict_get(ist->opts, "threads", NULL, 0))
1991 av_dict_set(&ist->opts, "threads", "auto", 0);
1992 if ((ret = avcodec_open2(ist->st->codec, codec, &ist->opts)) < 0) {
1993 if (ret == AVERROR_EXPERIMENTAL)
1994 abort_codec_experimental(codec, 0);
1995 snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
1996 ist->file_index, ist->st->index);
1999 assert_avoptions(ist->opts);
2002 ist->next_pts = AV_NOPTS_VALUE;
2003 ist->next_dts = AV_NOPTS_VALUE;
2009 static InputStream *get_input_stream(OutputStream *ost)
2011 if (ost->source_index >= 0)
2012 return input_streams[ost->source_index];
2016 static int compare_int64(const void *a, const void *b)
2018 int64_t va = *(int64_t *)a, vb = *(int64_t *)b;
2019 return va < vb ? -1 : va > vb ? +1 : 0;
2022 static void parse_forced_key_frames(char *kf, OutputStream *ost,
2023 AVCodecContext *avctx)
2026 int n = 1, i, size, index = 0;
2029 for (p = kf; *p; p++)
2033 pts = av_malloc(sizeof(*pts) * size);
2035 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
2040 for (i = 0; i < n; i++) {
2041 char *next = strchr(p, ',');
2046 if (!memcmp(p, "chapters", 8)) {
2048 AVFormatContext *avf = output_files[ost->file_index]->ctx;
2051 if (avf->nb_chapters > INT_MAX - size ||
2052 !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
2054 av_log(NULL, AV_LOG_FATAL,
2055 "Could not allocate forced key frames array.\n");
2058 t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
2059 t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2061 for (j = 0; j < avf->nb_chapters; j++) {
2062 AVChapter *c = avf->chapters[j];
2063 av_assert1(index < size);
2064 pts[index++] = av_rescale_q(c->start, c->time_base,
2065 avctx->time_base) + t;
2070 t = parse_time_or_die("force_key_frames", p, 1);
2071 av_assert1(index < size);
2072 pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2079 av_assert0(index == size);
2080 qsort(pts, size, sizeof(*pts), compare_int64);
2081 ost->forced_kf_count = size;
2082 ost->forced_kf_pts = pts;
2085 static void report_new_stream(int input_index, AVPacket *pkt)
2087 InputFile *file = input_files[input_index];
2088 AVStream *st = file->ctx->streams[pkt->stream_index];
2090 if (pkt->stream_index < file->nb_streams_warn)
2092 av_log(file->ctx, AV_LOG_WARNING,
2093 "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
2094 av_get_media_type_string(st->codec->codec_type),
2095 input_index, pkt->stream_index,
2096 pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
2097 file->nb_streams_warn = pkt->stream_index + 1;
2100 static int transcode_init(void)
2102 int ret = 0, i, j, k;
2103 AVFormatContext *oc;
2104 AVCodecContext *codec;
2110 /* init framerate emulation */
2111 for (i = 0; i < nb_input_files; i++) {
2112 InputFile *ifile = input_files[i];
2113 if (ifile->rate_emu)
2114 for (j = 0; j < ifile->nb_streams; j++)
2115 input_streams[j + ifile->ist_index]->start = av_gettime();
2118 /* output stream init */
2119 for (i = 0; i < nb_output_files; i++) {
2120 oc = output_files[i]->ctx;
2121 if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2122 av_dump_format(oc, i, oc->filename, 1);
2123 av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2124 return AVERROR(EINVAL);
2128 /* init complex filtergraphs */
2129 for (i = 0; i < nb_filtergraphs; i++)
2130 if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2133 /* for each output stream, we compute the right encoding parameters */
2134 for (i = 0; i < nb_output_streams; i++) {
2135 AVCodecContext *icodec = NULL;
2136 ost = output_streams[i];
2137 oc = output_files[ost->file_index]->ctx;
2138 ist = get_input_stream(ost);
2140 if (ost->attachment_filename)
2143 codec = ost->st->codec;
2146 icodec = ist->st->codec;
2148 ost->st->disposition = ist->st->disposition;
2149 codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
2150 codec->chroma_sample_location = icodec->chroma_sample_location;
2153 if (ost->stream_copy) {
2154 uint64_t extra_size;
2156 av_assert0(ist && !ost->filter);
2158 extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2160 if (extra_size > INT_MAX) {
2161 return AVERROR(EINVAL);
2164 /* if stream_copy is selected, no need to decode or encode */
2165 codec->codec_id = icodec->codec_id;
2166 codec->codec_type = icodec->codec_type;
2168 if (!codec->codec_tag) {
2169 unsigned int codec_tag;
2170 if (!oc->oformat->codec_tag ||
2171 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2172 !av_codec_get_tag2(oc->oformat->codec_tag, icodec->codec_id, &codec_tag))
2173 codec->codec_tag = icodec->codec_tag;
2176 codec->bit_rate = icodec->bit_rate;
2177 codec->rc_max_rate = icodec->rc_max_rate;
2178 codec->rc_buffer_size = icodec->rc_buffer_size;
2179 codec->field_order = icodec->field_order;
2180 codec->extradata = av_mallocz(extra_size);
2181 if (!codec->extradata) {
2182 return AVERROR(ENOMEM);
2184 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2185 codec->extradata_size= icodec->extradata_size;
2186 codec->bits_per_coded_sample = icodec->bits_per_coded_sample;
2188 codec->time_base = ist->st->time_base;
2190 * Avi is a special case here because it supports variable fps but
2191 * having the fps and timebase differe significantly adds quite some
2194 if(!strcmp(oc->oformat->name, "avi")) {
2195 if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
2196 && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
2197 && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(icodec->time_base)
2198 && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(icodec->time_base) < 1.0/500
2200 codec->time_base.num = ist->st->r_frame_rate.den;
2201 codec->time_base.den = 2*ist->st->r_frame_rate.num;
2202 codec->ticks_per_frame = 2;
2203 } else if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
2204 && av_q2d(ist->st->time_base) < 1.0/500
2206 codec->time_base = icodec->time_base;
2207 codec->time_base.num *= icodec->ticks_per_frame;
2208 codec->time_base.den *= 2;
2209 codec->ticks_per_frame = 2;
2211 } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
2212 && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
2213 && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
2214 && strcmp(oc->oformat->name, "f4v")
2216 if( copy_tb<0 && icodec->time_base.den
2217 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
2218 && av_q2d(ist->st->time_base) < 1.0/500
2220 codec->time_base = icodec->time_base;
2221 codec->time_base.num *= icodec->ticks_per_frame;
2224 if ( codec->codec_tag == AV_RL32("tmcd")
2225 && icodec->time_base.num < icodec->time_base.den
2226 && icodec->time_base.num > 0
2227 && 121LL*icodec->time_base.num > icodec->time_base.den) {
2228 codec->time_base = icodec->time_base;
2231 if(ost->frame_rate.num)
2232 codec->time_base = av_inv_q(ost->frame_rate);
2234 av_reduce(&codec->time_base.num, &codec->time_base.den,
2235 codec->time_base.num, codec->time_base.den, INT_MAX);
2237 switch (codec->codec_type) {
2238 case AVMEDIA_TYPE_AUDIO:
2239 if (audio_volume != 256) {
2240 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2243 codec->channel_layout = icodec->channel_layout;
2244 codec->sample_rate = icodec->sample_rate;
2245 codec->channels = icodec->channels;
2246 codec->frame_size = icodec->frame_size;
2247 codec->audio_service_type = icodec->audio_service_type;
2248 codec->block_align = icodec->block_align;
2249 if((codec->block_align == 1 || codec->block_align == 1152 || codec->block_align == 576) && codec->codec_id == AV_CODEC_ID_MP3)
2250 codec->block_align= 0;
2251 if(codec->codec_id == AV_CODEC_ID_AC3)
2252 codec->block_align= 0;
2254 case AVMEDIA_TYPE_VIDEO:
2255 codec->pix_fmt = icodec->pix_fmt;
2256 codec->width = icodec->width;
2257 codec->height = icodec->height;
2258 codec->has_b_frames = icodec->has_b_frames;
2259 if (!codec->sample_aspect_ratio.num) {
2260 codec->sample_aspect_ratio =
2261 ost->st->sample_aspect_ratio =
2262 ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
2263 ist->st->codec->sample_aspect_ratio.num ?
2264 ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2266 ost->st->avg_frame_rate = ist->st->avg_frame_rate;
2268 case AVMEDIA_TYPE_SUBTITLE:
2269 codec->width = icodec->width;
2270 codec->height = icodec->height;
2272 case AVMEDIA_TYPE_DATA:
2273 case AVMEDIA_TYPE_ATTACHMENT:
2280 ost->enc = avcodec_find_encoder(codec->codec_id);
2282 /* should only happen when a default codec is not present. */
2283 snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
2284 avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
2285 ret = AVERROR(EINVAL);
2290 ist->decoding_needed++;
2291 ost->encoding_needed = 1;
2294 (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2295 codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
2297 fg = init_simple_filtergraph(ist, ost);
2298 if (configure_filtergraph(fg)) {
2299 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2304 if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2305 if (ost->filter && !ost->frame_rate.num)
2306 ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
2307 if (ist && !ost->frame_rate.num)
2308 ost->frame_rate = ist->framerate;
2309 if (ist && !ost->frame_rate.num)
2310 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
2311 // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
2312 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2313 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2314 ost->frame_rate = ost->enc->supported_framerates[idx];
2318 switch (codec->codec_type) {
2319 case AVMEDIA_TYPE_AUDIO:
2320 codec->sample_fmt = ost->filter->filter->inputs[0]->format;
2321 codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
2322 codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
2323 codec->channels = avfilter_link_get_channels(ost->filter->filter->inputs[0]);
2324 codec->time_base = (AVRational){ 1, codec->sample_rate };
2326 case AVMEDIA_TYPE_VIDEO:
2327 codec->time_base = av_inv_q(ost->frame_rate);
2328 if (ost->filter && !(codec->time_base.num && codec->time_base.den))
2329 codec->time_base = ost->filter->filter->inputs[0]->time_base;
2330 if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
2331 && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
2332 av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
2333 "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
2335 for (j = 0; j < ost->forced_kf_count; j++)
2336 ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
2340 codec->width = ost->filter->filter->inputs[0]->w;
2341 codec->height = ost->filter->filter->inputs[0]->h;
2342 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
2343 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
2344 av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
2345 ost->filter->filter->inputs[0]->sample_aspect_ratio;
2346 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
2349 codec->width != icodec->width ||
2350 codec->height != icodec->height ||
2351 codec->pix_fmt != icodec->pix_fmt) {
2352 codec->bits_per_raw_sample = frame_bits_per_raw_sample;
2355 if (ost->forced_keyframes) {
2356 if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
2357 ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
2358 forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
2360 av_log(NULL, AV_LOG_ERROR,
2361 "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
2364 ost->forced_keyframes_expr_const_values[FKF_N] = 0;
2365 ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
2366 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
2367 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
2369 parse_forced_key_frames(ost->forced_keyframes, ost, ost->st->codec);
2373 case AVMEDIA_TYPE_SUBTITLE:
2374 codec->time_base = (AVRational){1, 1000};
2375 if (!codec->width) {
2376 codec->width = input_streams[ost->source_index]->st->codec->width;
2377 codec->height = input_streams[ost->source_index]->st->codec->height;
2385 if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
2386 char logfilename[1024];
2389 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2390 ost->logfile_prefix ? ost->logfile_prefix :
2391 DEFAULT_PASS_LOGFILENAME_PREFIX,
2393 if (!strcmp(ost->enc->name, "libx264")) {
2394 av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
2396 if (codec->flags & CODEC_FLAG_PASS2) {
2398 size_t logbuffer_size;
2399 if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2400 av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2404 codec->stats_in = logbuffer;
2406 if (codec->flags & CODEC_FLAG_PASS1) {
2407 f = fopen(logfilename, "wb");
2409 av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2410 logfilename, strerror(errno));
2420 /* open each encoder */
2421 for (i = 0; i < nb_output_streams; i++) {
2422 ost = output_streams[i];
2423 if (ost->encoding_needed) {
2424 AVCodec *codec = ost->enc;
2425 AVCodecContext *dec = NULL;
2427 if ((ist = get_input_stream(ost)))
2428 dec = ist->st->codec;
2429 if (dec && dec->subtitle_header) {
2430 /* ASS code assumes this buffer is null terminated so add extra byte. */
2431 ost->st->codec->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
2432 if (!ost->st->codec->subtitle_header) {
2433 ret = AVERROR(ENOMEM);
2436 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2437 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2439 if (!av_dict_get(ost->opts, "threads", NULL, 0))
2440 av_dict_set(&ost->opts, "threads", "auto", 0);
2441 if ((ret = avcodec_open2(ost->st->codec, codec, &ost->opts)) < 0) {
2442 if (ret == AVERROR_EXPERIMENTAL)
2443 abort_codec_experimental(codec, 1);
2444 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2445 ost->file_index, ost->index);
2448 if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
2449 !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
2450 av_buffersink_set_frame_size(ost->filter->filter,
2451 ost->st->codec->frame_size);
2452 assert_avoptions(ost->opts);
2453 if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2454 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2455 " It takes bits/s as argument, not kbits/s\n");
2456 extra_size += ost->st->codec->extradata_size;
2458 if (ost->st->codec->me_threshold)
2459 input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
2461 av_opt_set_dict(ost->st->codec, &ost->opts);
2465 /* init input streams */
2466 for (i = 0; i < nb_input_streams; i++)
2467 if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
2468 for (i = 0; i < nb_output_streams; i++) {
2469 ost = output_streams[i];
2470 avcodec_close(ost->st->codec);
2475 /* discard unused programs */
2476 for (i = 0; i < nb_input_files; i++) {
2477 InputFile *ifile = input_files[i];
2478 for (j = 0; j < ifile->ctx->nb_programs; j++) {
2479 AVProgram *p = ifile->ctx->programs[j];
2480 int discard = AVDISCARD_ALL;
2482 for (k = 0; k < p->nb_stream_indexes; k++)
2483 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
2484 discard = AVDISCARD_DEFAULT;
2487 p->discard = discard;
2491 /* open files and write file headers */
2492 for (i = 0; i < nb_output_files; i++) {
2493 oc = output_files[i]->ctx;
2494 oc->interrupt_callback = int_cb;
2495 if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
2497 const char *errbuf_ptr = errbuf;
2498 if (av_strerror(ret, errbuf, sizeof(errbuf)) < 0)
2499 errbuf_ptr = strerror(AVUNERROR(ret));
2500 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?): %s", i, errbuf_ptr);
2501 ret = AVERROR(EINVAL);
2504 // assert_avoptions(output_files[i]->opts);
2505 if (strcmp(oc->oformat->name, "rtp")) {
2511 /* dump the file output parameters - cannot be done before in case
2513 for (i = 0; i < nb_output_files; i++) {
2514 av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
2517 /* dump the stream mapping */
2518 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2519 for (i = 0; i < nb_input_streams; i++) {
2520 ist = input_streams[i];
2522 for (j = 0; j < ist->nb_filters; j++) {
2523 if (ist->filters[j]->graph->graph_desc) {
2524 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
2525 ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
2526 ist->filters[j]->name);
2527 if (nb_filtergraphs > 1)
2528 av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
2529 av_log(NULL, AV_LOG_INFO, "\n");
2534 for (i = 0; i < nb_output_streams; i++) {
2535 ost = output_streams[i];
2537 if (ost->attachment_filename) {
2538 /* an attached file */
2539 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
2540 ost->attachment_filename, ost->file_index, ost->index);
2544 if (ost->filter && ost->filter->graph->graph_desc) {
2545 /* output from a complex graph */
2546 av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
2547 if (nb_filtergraphs > 1)
2548 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
2550 av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
2551 ost->index, ost->enc ? ost->enc->name : "?");
2555 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
2556 input_streams[ost->source_index]->file_index,
2557 input_streams[ost->source_index]->st->index,
2560 if (ost->sync_ist != input_streams[ost->source_index])
2561 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2562 ost->sync_ist->file_index,
2563 ost->sync_ist->st->index);
2564 if (ost->stream_copy)
2565 av_log(NULL, AV_LOG_INFO, " (copy)");
2567 av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
2568 input_streams[ost->source_index]->dec->name : "?",
2569 ost->enc ? ost->enc->name : "?");
2570 av_log(NULL, AV_LOG_INFO, "\n");
2574 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2585 /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
2586 static int need_output(void)
2590 for (i = 0; i < nb_output_streams; i++) {
2591 OutputStream *ost = output_streams[i];
2592 OutputFile *of = output_files[ost->file_index];
2593 AVFormatContext *os = output_files[ost->file_index]->ctx;
2595 if (ost->finished ||
2596 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2598 if (ost->frame_number >= ost->max_frames) {
2600 for (j = 0; j < of->ctx->nb_streams; j++)
2601 close_output_stream(output_streams[of->ost_index + j]);
2612 * Select the output stream to process.
2614 * @return selected output stream, or NULL if none available
2616 static OutputStream *choose_output(void)
2619 int64_t opts_min = INT64_MAX;
2620 OutputStream *ost_min = NULL;
2622 for (i = 0; i < nb_output_streams; i++) {
2623 OutputStream *ost = output_streams[i];
2624 int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
2626 if (!ost->unavailable && !ost->finished && opts < opts_min) {
2634 static int check_keyboard_interaction(int64_t cur_time)
2637 static int64_t last_time;
2638 if (received_nb_signals)
2639 return AVERROR_EXIT;
2640 /* read_key() returns 0 on EOF */
2641 if(cur_time - last_time >= 100000 && !run_as_daemon){
2643 last_time = cur_time;
2647 return AVERROR_EXIT;
2648 if (key == '+') av_log_set_level(av_log_get_level()+10);
2649 if (key == '-') av_log_set_level(av_log_get_level()-10);
2650 if (key == 's') qp_hist ^= 1;
2653 do_hex_dump = do_pkt_dump = 0;
2654 } else if(do_pkt_dump){
2658 av_log_set_level(AV_LOG_DEBUG);
2660 if (key == 'c' || key == 'C'){
2661 char buf[4096], target[64], command[256], arg[256] = {0};
2664 fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
2666 while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
2671 (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
2672 av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
2673 target, time, command, arg);
2674 for (i = 0; i < nb_filtergraphs; i++) {
2675 FilterGraph *fg = filtergraphs[i];
2678 ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
2679 key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
2680 fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
2682 ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
2687 av_log(NULL, AV_LOG_ERROR,
2688 "Parse error, at least 3 arguments were expected, "
2689 "only %d given in string '%s'\n", n, buf);
2692 if (key == 'd' || key == 'D'){
2695 debug = input_streams[0]->st->codec->debug<<1;
2696 if(!debug) debug = 1;
2697 while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
2700 if(scanf("%d", &debug)!=1)
2701 fprintf(stderr,"error parsing debug value\n");
2702 for(i=0;i<nb_input_streams;i++) {
2703 input_streams[i]->st->codec->debug = debug;
2705 for(i=0;i<nb_output_streams;i++) {
2706 OutputStream *ost = output_streams[i];
2707 ost->st->codec->debug = debug;
2709 if(debug) av_log_set_level(AV_LOG_DEBUG);
2710 fprintf(stderr,"debug=%d\n", debug);
2713 fprintf(stderr, "key function\n"
2714 "? show this help\n"
2715 "+ increase verbosity\n"
2716 "- decrease verbosity\n"
2717 "c Send command to filtergraph\n"
2718 "D cycle through available debug modes\n"
2719 "h dump packets/hex press to cycle through the 3 states\n"
2721 "s Show QP histogram\n"
2728 static void *input_thread(void *arg)
2733 while (!transcoding_finished && ret >= 0) {
2735 ret = av_read_frame(f->ctx, &pkt);
2737 if (ret == AVERROR(EAGAIN)) {
2744 pthread_mutex_lock(&f->fifo_lock);
2745 while (!av_fifo_space(f->fifo))
2746 pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
2748 av_dup_packet(&pkt);
2749 av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
2751 pthread_mutex_unlock(&f->fifo_lock);
2758 static void free_input_threads(void)
2762 if (nb_input_files == 1)
2765 transcoding_finished = 1;
2767 for (i = 0; i < nb_input_files; i++) {
2768 InputFile *f = input_files[i];
2771 if (!f->fifo || f->joined)
2774 pthread_mutex_lock(&f->fifo_lock);
2775 while (av_fifo_size(f->fifo)) {
2776 av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2777 av_free_packet(&pkt);
2779 pthread_cond_signal(&f->fifo_cond);
2780 pthread_mutex_unlock(&f->fifo_lock);
2782 pthread_join(f->thread, NULL);
2785 while (av_fifo_size(f->fifo)) {
2786 av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2787 av_free_packet(&pkt);
2789 av_fifo_free(f->fifo);
2793 static int init_input_threads(void)
2797 if (nb_input_files == 1)
2800 for (i = 0; i < nb_input_files; i++) {
2801 InputFile *f = input_files[i];
2803 if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
2804 return AVERROR(ENOMEM);
2806 pthread_mutex_init(&f->fifo_lock, NULL);
2807 pthread_cond_init (&f->fifo_cond, NULL);
2809 if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
2810 return AVERROR(ret);
2815 static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
2819 pthread_mutex_lock(&f->fifo_lock);
2821 if (av_fifo_size(f->fifo)) {
2822 av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
2823 pthread_cond_signal(&f->fifo_cond);
2828 ret = AVERROR(EAGAIN);
2831 pthread_mutex_unlock(&f->fifo_lock);
2837 static int get_input_packet(InputFile *f, AVPacket *pkt)
2840 if (nb_input_files > 1)
2841 return get_input_packet_mt(f, pkt);
2843 return av_read_frame(f->ctx, pkt);
2846 static int got_eagain(void)
2849 for (i = 0; i < nb_output_streams; i++)
2850 if (output_streams[i]->unavailable)
2855 static void reset_eagain(void)
2858 for (i = 0; i < nb_input_files; i++)
2859 input_files[i]->eagain = 0;
2860 for (i = 0; i < nb_output_streams; i++)
2861 output_streams[i]->unavailable = 0;
2866 * - 0 -- one packet was read and processed
2867 * - AVERROR(EAGAIN) -- no packets were available for selected file,
2868 * this function should be called again
2869 * - AVERROR_EOF -- this function should not be called again
2871 static int process_input(int file_index)
2873 InputFile *ifile = input_files[file_index];
2874 AVFormatContext *is;
2880 ret = get_input_packet(ifile, &pkt);
2882 if (ret == AVERROR(EAGAIN)) {
2887 if (ret != AVERROR_EOF) {
2888 print_error(is->filename, ret);
2892 ifile->eof_reached = 1;
2894 for (i = 0; i < ifile->nb_streams; i++) {
2895 ist = input_streams[ifile->ist_index + i];
2896 if (ist->decoding_needed)
2897 output_packet(ist, NULL);
2899 /* mark all outputs that don't go through lavfi as finished */
2900 for (j = 0; j < nb_output_streams; j++) {
2901 OutputStream *ost = output_streams[j];
2903 if (ost->source_index == ifile->ist_index + i &&
2904 (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
2905 close_output_stream(ost);
2909 return AVERROR(EAGAIN);
2915 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2916 is->streams[pkt.stream_index]);
2918 /* the following test is needed in case new streams appear
2919 dynamically in stream : we ignore them */
2920 if (pkt.stream_index >= ifile->nb_streams) {
2921 report_new_stream(file_index, &pkt);
2922 goto discard_packet;
2925 ist = input_streams[ifile->ist_index + pkt.stream_index];
2927 goto discard_packet;
2930 av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
2931 "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",
2932 ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
2933 av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
2934 av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
2935 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
2936 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
2937 av_ts2str(input_files[ist->file_index]->ts_offset),
2938 av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
2941 if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
2942 int64_t stime, stime2;
2943 // Correcting starttime based on the enabled streams
2944 // 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.
2945 // so we instead do it here as part of discontinuity handling
2946 if ( ist->next_dts == AV_NOPTS_VALUE
2947 && ifile->ts_offset == -is->start_time
2948 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
2949 int64_t new_start_time = INT64_MAX;
2950 for (i=0; i<is->nb_streams; i++) {
2951 AVStream *st = is->streams[i];
2952 if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
2954 new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
2956 if (new_start_time > is->start_time) {
2957 av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
2958 ifile->ts_offset = -new_start_time;
2962 stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
2963 stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
2964 ist->wrap_correction_done = 1;
2966 if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
2967 pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
2968 ist->wrap_correction_done = 0;
2970 if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
2971 pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
2972 ist->wrap_correction_done = 0;
2976 if (pkt.dts != AV_NOPTS_VALUE)
2977 pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2978 if (pkt.pts != AV_NOPTS_VALUE)
2979 pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2981 if (pkt.pts != AV_NOPTS_VALUE)
2982 pkt.pts *= ist->ts_scale;
2983 if (pkt.dts != AV_NOPTS_VALUE)
2984 pkt.dts *= ist->ts_scale;
2986 if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
2988 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2989 int64_t delta = pkt_dts - ist->next_dts;
2990 if (is->iformat->flags & AVFMT_TS_DISCONT) {
2991 if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
2992 (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
2993 ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
2994 pkt_dts+1<ist->pts){
2995 ifile->ts_offset -= delta;
2996 av_log(NULL, AV_LOG_DEBUG,
2997 "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2998 delta, ifile->ts_offset);
2999 pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3000 if (pkt.pts != AV_NOPTS_VALUE)
3001 pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3004 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3005 (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
3007 av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
3008 pkt.dts = AV_NOPTS_VALUE;
3010 if (pkt.pts != AV_NOPTS_VALUE){
3011 int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
3012 delta = pkt_pts - ist->next_dts;
3013 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3014 (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
3016 av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3017 pkt.pts = AV_NOPTS_VALUE;
3024 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",
3025 ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
3026 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3027 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3028 av_ts2str(input_files[ist->file_index]->ts_offset),
3029 av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
3032 sub2video_heartbeat(ist, pkt.pts);
3034 ret = output_packet(ist, &pkt);
3037 av_strerror(ret, buf, sizeof(buf));
3038 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
3039 ist->file_index, ist->st->index, buf);
3045 av_free_packet(&pkt);
3051 * Perform a step of transcoding for the specified filter graph.
3053 * @param[in] graph filter graph to consider
3054 * @param[out] best_ist input stream where a frame would allow to continue
3055 * @return 0 for success, <0 for error
3057 static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
3060 int nb_requests, nb_requests_max = 0;
3061 InputFilter *ifilter;
3065 ret = avfilter_graph_request_oldest(graph->graph);
3067 return reap_filters();
3069 if (ret == AVERROR_EOF) {
3070 ret = reap_filters();
3071 for (i = 0; i < graph->nb_outputs; i++)
3072 close_output_stream(graph->outputs[i]->ost);
3075 if (ret != AVERROR(EAGAIN))
3078 for (i = 0; i < graph->nb_inputs; i++) {
3079 ifilter = graph->inputs[i];
3081 if (input_files[ist->file_index]->eagain ||
3082 input_files[ist->file_index]->eof_reached)
3084 nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
3085 if (nb_requests > nb_requests_max) {
3086 nb_requests_max = nb_requests;
3092 for (i = 0; i < graph->nb_outputs; i++)
3093 graph->outputs[i]->ost->unavailable = 1;
3099 * Run a single step of transcoding.
3101 * @return 0 for success, <0 for error
3103 static int transcode_step(void)
3109 ost = choose_output();
3116 av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
3121 if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
3126 av_assert0(ost->source_index >= 0);
3127 ist = input_streams[ost->source_index];
3130 ret = process_input(ist->file_index);
3131 if (ret == AVERROR(EAGAIN)) {
3132 if (input_files[ist->file_index]->eagain)
3133 ost->unavailable = 1;
3137 return ret == AVERROR_EOF ? 0 : ret;
3139 return reap_filters();
3143 * The following code is the main loop of the file converter
3145 static int transcode(void)
3148 AVFormatContext *os;
3151 int64_t timer_start;
3153 ret = transcode_init();
3157 if (stdin_interaction) {
3158 av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
3161 timer_start = av_gettime();
3164 if ((ret = init_input_threads()) < 0)
3168 while (!received_sigterm) {
3169 int64_t cur_time= av_gettime();
3171 /* if 'q' pressed, exits */
3172 if (stdin_interaction)
3173 if (check_keyboard_interaction(cur_time) < 0)
3176 /* check if there's any stream where output is still needed */
3177 if (!need_output()) {
3178 av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
3182 ret = transcode_step();
3184 if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
3187 av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
3191 /* dump report by using the output first video and audio streams */
3192 print_report(0, timer_start, cur_time);
3195 free_input_threads();
3198 /* at the end of stream, we must flush the decoder buffers */
3199 for (i = 0; i < nb_input_streams; i++) {
3200 ist = input_streams[i];
3201 if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3202 output_packet(ist, NULL);
3209 /* write the trailer if needed and close file */
3210 for (i = 0; i < nb_output_files; i++) {
3211 os = output_files[i]->ctx;
3212 av_write_trailer(os);
3215 /* dump report by using the first video and audio streams */
3216 print_report(1, timer_start, av_gettime());
3218 /* close each encoder */
3219 for (i = 0; i < nb_output_streams; i++) {
3220 ost = output_streams[i];
3221 if (ost->encoding_needed) {
3222 av_freep(&ost->st->codec->stats_in);
3223 avcodec_close(ost->st->codec);
3227 /* close each decoder */
3228 for (i = 0; i < nb_input_streams; i++) {
3229 ist = input_streams[i];
3230 if (ist->decoding_needed) {
3231 avcodec_close(ist->st->codec);
3240 free_input_threads();
3243 if (output_streams) {
3244 for (i = 0; i < nb_output_streams; i++) {
3245 ost = output_streams[i];
3247 if (ost->stream_copy)
3248 av_freep(&ost->st->codec->extradata);
3250 fclose(ost->logfile);
3251 ost->logfile = NULL;
3253 av_freep(&ost->st->codec->subtitle_header);
3254 av_free(ost->forced_kf_pts);
3255 av_dict_free(&ost->opts);
3256 av_dict_free(&ost->swr_opts);
3257 av_dict_free(&ost->resample_opts);
3265 static int64_t getutime(void)
3268 struct rusage rusage;
3270 getrusage(RUSAGE_SELF, &rusage);
3271 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3272 #elif HAVE_GETPROCESSTIMES
3274 FILETIME c, e, k, u;
3275 proc = GetCurrentProcess();
3276 GetProcessTimes(proc, &c, &e, &k, &u);
3277 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
3279 return av_gettime();
3283 static int64_t getmaxrss(void)
3285 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
3286 struct rusage rusage;
3287 getrusage(RUSAGE_SELF, &rusage);
3288 return (int64_t)rusage.ru_maxrss * 1024;
3289 #elif HAVE_GETPROCESSMEMORYINFO
3291 PROCESS_MEMORY_COUNTERS memcounters;
3292 proc = GetCurrentProcess();
3293 memcounters.cb = sizeof(memcounters);
3294 GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
3295 return memcounters.PeakPagefileUsage;
3301 static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
3305 int main(int argc, char **argv)
3310 atexit(exit_program);
3312 setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
3314 av_log_set_flags(AV_LOG_SKIP_REPEATED);
3315 parse_loglevel(argc, argv, options);
3317 if(argc>1 && !strcmp(argv[1], "-d")){
3319 av_log_set_callback(log_callback_null);
3324 avcodec_register_all();
3326 avdevice_register_all();
3328 avfilter_register_all();
3330 avformat_network_init();
3332 show_banner(argc, argv, options);
3336 /* parse options and open all input/output files */
3337 ret = ffmpeg_parse_options(argc, argv);
3341 if (nb_output_files <= 0 && nb_input_files == 0) {
3343 av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
3347 /* file converter / grab */
3348 if (nb_output_files <= 0) {
3349 av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
3353 // if (nb_input_files == 0) {
3354 // av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
3358 current_time = ti = getutime();
3359 if (transcode() < 0)
3361 ti = getutime() - ti;
3363 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3366 exit(received_nb_signals ? 255 : 0);