Skip to content
Snippets Groups Projects
avconv.c 80.3 KiB
Newer Older
  • Learn to ignore specific revisions
  • /*
     * avconv main
     * Copyright (c) 2000-2011 The libav developers.
     *
     * This file is part of Libav.
     *
     * Libav is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * Libav is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     *
     * You should have received a copy of the GNU Lesser General Public
     * License along with Libav; if not, write to the Free Software
     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
     */
    
    #include "config.h"
    #include <ctype.h>
    #include <string.h>
    #include <math.h>
    #include <stdlib.h>
    #include <errno.h>
    #include <signal.h>
    #include <limits.h>
    #include "libavformat/avformat.h"
    #include "libavdevice/avdevice.h"
    #include "libswscale/swscale.h"
    
    #include "libavresample/avresample.h"
    
    #include "libavutil/opt.h"
    #include "libavutil/audioconvert.h"
    #include "libavutil/parseutils.h"
    #include "libavutil/samplefmt.h"
    #include "libavutil/colorspace.h"
    #include "libavutil/fifo.h"
    #include "libavutil/intreadwrite.h"
    #include "libavutil/dict.h"
    #include "libavutil/mathematics.h"
    #include "libavutil/pixdesc.h"
    #include "libavutil/avstring.h"
    #include "libavutil/libm.h"
    
    #include "libavutil/imgutils.h"
    
    #include "libavutil/time.h"
    
    #include "libavformat/os_support.h"
    
    # include "libavfilter/avfilter.h"
    # include "libavfilter/avfiltergraph.h"
    
    # include "libavfilter/buffersrc.h"
    
    # include "libavfilter/buffersink.h"
    
    
    #if HAVE_SYS_RESOURCE_H
    
    #include <sys/time.h>
    
    #include <sys/types.h>
    #include <sys/resource.h>
    #elif HAVE_GETPROCESSTIMES
    #include <windows.h>
    #endif
    #if HAVE_GETPROCESSMEMORYINFO
    #include <windows.h>
    #include <psapi.h>
    #endif
    
    #if HAVE_SYS_SELECT_H
    #include <sys/select.h>
    #endif
    
    
    #if HAVE_PTHREADS
    #include <pthread.h>
    #endif
    
    
    #include "avconv.h"
    
    #include "cmdutils.h"
    
    #include "libavutil/avassert.h"
    
    const char program_name[] = "avconv";
    const int program_birth_year = 2000;
    
    static FILE *vstats_file;
    
    static int64_t video_size = 0;
    static int64_t audio_size = 0;
    static int64_t extra_size = 0;
    static int nb_frames_dup = 0;
    static int nb_frames_drop = 0;
    
    
    
    #if HAVE_PTHREADS
    
    /* signal to input threads that they should exit; set by the main thread */
    static int transcoding_finished;
    #endif
    
    
    #define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
    
    
    InputStream **input_streams = NULL;
    int        nb_input_streams = 0;
    InputFile   **input_files   = NULL;
    int        nb_input_files   = 0;
    
    OutputStream **output_streams = NULL;
    int         nb_output_streams = 0;
    OutputFile   **output_files   = NULL;
    int         nb_output_files   = 0;
    
    FilterGraph **filtergraphs;
    int        nb_filtergraphs;
    
    static void term_exit(void)
    {
        av_log(NULL, AV_LOG_QUIET, "");
    }
    
    static volatile int received_sigterm = 0;
    static volatile int received_nb_signals = 0;
    
    static void
    sigterm_handler(int sig)
    {
        received_sigterm = sig;
        received_nb_signals++;
        term_exit();
    }
    
    static void term_init(void)
    {
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
        signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).    */
    
        signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
    #ifdef SIGXCPU
        signal(SIGXCPU, sigterm_handler);
    #endif
    }
    
    
    {
        return received_nb_signals > 1;
    }
    
    
    const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
    
    static void exit_program(void)
    
        int i, j;
    
        for (i = 0; i < nb_filtergraphs; i++) {
            avfilter_graph_free(&filtergraphs[i]->graph);
    
            for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
                av_freep(&filtergraphs[i]->inputs[j]->name);
    
                av_freep(&filtergraphs[i]->inputs[j]);
    
            av_freep(&filtergraphs[i]->inputs);
    
            for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
                av_freep(&filtergraphs[i]->outputs[j]->name);
    
                av_freep(&filtergraphs[i]->outputs[j]);
    
            av_freep(&filtergraphs[i]->outputs);
            av_freep(&filtergraphs[i]);
        }
        av_freep(&filtergraphs);
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
        for (i = 0; i < nb_output_files; i++) {
    
            AVFormatContext *s = output_files[i]->ctx;
    
            if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
                avio_close(s->pb);
            avformat_free_context(s);
    
            av_dict_free(&output_files[i]->opts);
            av_freep(&output_files[i]);
    
        for (i = 0; i < nb_output_streams; i++) {
    
            AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
    
            while (bsfc) {
                AVBitStreamFilterContext *next = bsfc->next;
                av_bitstream_filter_close(bsfc);
                bsfc = next;
            }
    
            output_streams[i]->bitstream_filters = NULL;
    
            avcodec_free_frame(&output_streams[i]->filtered_frame);
    
            av_freep(&output_streams[i]->forced_keyframes);
    
            av_freep(&output_streams[i]->avfilter);
    
            av_freep(&output_streams[i]->logfile_prefix);
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
        for (i = 0; i < nb_input_files; i++) {
    
            avformat_close_input(&input_files[i]->ctx);
            av_freep(&input_files[i]);
    
        for (i = 0; i < nb_input_streams; i++) {
    
            avcodec_free_frame(&input_streams[i]->decoded_frame);
    
            av_dict_free(&input_streams[i]->opts);
    
            free_buffer_pool(&input_streams[i]->buffer_pool);
    
            av_freep(&input_streams[i]->filters);
    
    
        if (vstats_file)
            fclose(vstats_file);
        av_free(vstats_filename);
    
        av_freep(&input_streams);
        av_freep(&input_files);
    
    
        uninit_opts();
    
        avfilter_uninit();
    
        avformat_network_deinit();
    
    
        if (received_sigterm) {
    
            av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
                   (int) received_sigterm);
    
    void assert_avoptions(AVDictionary *m)
    
    {
        AVDictionaryEntry *t;
        if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
    
            av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
    
    static void abort_codec_experimental(AVCodec *c, int encoder)
    
    {
        const char *codec_string = encoder ? "encoder" : "decoder";
        AVCodec *codec;
    
        av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
                "results.\nAdd '-strict experimental' if you want to use it.\n",
                codec_string, c->name);
        codec = encoder ? avcodec_find_encoder(c->id) : avcodec_find_decoder(c->id);
        if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
            av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
                   codec_string, codec->name);
        exit(1);
    
     * Update the requested input sample format based on the output sample format.
     * This is currently only used to request float output from decoders which
     * support multiple sample formats, one of which is AV_SAMPLE_FMT_FLT.
     * Ideally this will be removed in the future when decoders do not do format
     * conversion and only output in their native format.
     */
    static void update_sample_fmt(AVCodecContext *dec, AVCodec *dec_codec,
                                  AVCodecContext *enc)
    {
        /* if sample formats match or a decoder sample format has already been
           requested, just return */
        if (enc->sample_fmt == dec->sample_fmt ||
            dec->request_sample_fmt > AV_SAMPLE_FMT_NONE)
            return;
    
        /* if decoder supports more than one output format */
        if (dec_codec && dec_codec->sample_fmts &&
            dec_codec->sample_fmts[0] != AV_SAMPLE_FMT_NONE &&
            dec_codec->sample_fmts[1] != AV_SAMPLE_FMT_NONE) {
            const enum AVSampleFormat *p;
    
            int min_dec = INT_MAX, min_inc = INT_MAX;
            enum AVSampleFormat dec_fmt = AV_SAMPLE_FMT_NONE;
            enum AVSampleFormat inc_fmt = AV_SAMPLE_FMT_NONE;
    
    
            /* find a matching sample format in the encoder */
            for (p = dec_codec->sample_fmts; *p != AV_SAMPLE_FMT_NONE; p++) {
                if (*p == enc->sample_fmt) {
                    dec->request_sample_fmt = *p;
                    return;
    
                } else {
                    enum AVSampleFormat dfmt = av_get_packed_sample_fmt(*p);
                    enum AVSampleFormat efmt = av_get_packed_sample_fmt(enc->sample_fmt);
                    int fmt_diff = 32 * abs(dfmt - efmt);
                    if (av_sample_fmt_is_planar(*p) !=
                        av_sample_fmt_is_planar(enc->sample_fmt))
                        fmt_diff++;
                    if (dfmt == efmt) {
                        min_inc = fmt_diff;
                        inc_fmt = *p;
                    } else if (dfmt > efmt) {
                        if (fmt_diff < min_inc) {
                            min_inc = fmt_diff;
                            inc_fmt = *p;
                        }
                    } else {
                        if (fmt_diff < min_dec) {
                            min_dec = fmt_diff;
                            dec_fmt = *p;
                        }
                    }
                }
    
            }
    
            /* if none match, provide the one that matches quality closest */
    
            dec->request_sample_fmt = min_inc != INT_MAX ? inc_fmt : dec_fmt;
    
    static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
    {
    
        AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
        AVCodecContext          *avctx = ost->st->codec;
    
        /*
         * Audio encoders may split the packets --  #frames in != #packets out.
         * But there is no reordering, so we can limit the number of output packets
         * by simply dropping them here.
         * Counting encoded video frames needs to be done separately because of
         * reordering, see do_video_out()
         */
        if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
    
            if (ost->frame_number >= ost->max_frames) {
                av_free_packet(pkt);
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
        while (bsfc) {
            AVPacket new_pkt = *pkt;
            int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
                                               &new_pkt.data, &new_pkt.size,
                                               pkt->data, pkt->size,
                                               pkt->flags & AV_PKT_FLAG_KEY);
            if (a > 0) {
    
                av_free_packet(pkt);
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
                new_pkt.destruct = av_destruct_packet;
            } else if (a < 0) {
    
                av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
                       bsfc->filter->name, pkt->stream_index,
                       avctx->codec ? avctx->codec->name : "copy");
    
                print_error("", a);
                if (exit_on_error)
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
            *pkt = new_pkt;
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
            bsfc = bsfc->next;
    
        pkt->stream_index = ost->index;
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
        ret = av_interleaved_write_frame(s, pkt);
        if (ret < 0) {
    
            print_error("av_interleaved_write_frame()", ret);
    
    static int check_recording_time(OutputStream *ost)
    {
    
        OutputFile *of = output_files[ost->file_index];
    
    
        if (of->recording_time != INT64_MAX &&
            av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
                          AV_TIME_BASE_Q) >= 0) {
    
    static void do_audio_out(AVFormatContext *s, OutputStream *ost,
                             AVFrame *frame)
    
    {
        AVCodecContext *enc = ost->st->codec;
        AVPacket pkt;
    
        int got_packet = 0;
    
    
        av_init_packet(&pkt);
        pkt.data = NULL;
        pkt.size = 0;
    
    
        if (!check_recording_time(ost))
            return;
    
        if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
    
            frame->pts = ost->sync_opts;
    
        ost->sync_opts = frame->pts + frame->nb_samples;
    
    
        if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
            av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
    
        }
    
        if (got_packet) {
            if (pkt.pts != AV_NOPTS_VALUE)
                pkt.pts      = av_rescale_q(pkt.pts,      enc->time_base, ost->st->time_base);
    
            if (pkt.dts != AV_NOPTS_VALUE)
                pkt.dts      = av_rescale_q(pkt.dts,      enc->time_base, ost->st->time_base);
    
            if (pkt.duration > 0)
                pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
    
            write_frame(s, &pkt, ost);
    
            audio_size += pkt.size;
        }
    
    }
    
    static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
    {
        AVCodecContext *dec;
        AVPicture *picture2;
        AVPicture picture_tmp;
        uint8_t *buf = 0;
    
        dec = ist->st->codec;
    
        /* deinterlace : must be done before any resize */
        if (do_deinterlace) {
            int size;
    
            /* create temporary picture */
            size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
            buf  = av_malloc(size);
    
            if (!buf)
                return;
    
            picture2 = &picture_tmp;
            avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
    
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
            if (avpicture_deinterlace(picture2, picture,
    
                                     dec->pix_fmt, dec->width, dec->height) < 0) {
                /* if error, do not deinterlace */
    
                av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
    
                av_free(buf);
                buf = NULL;
                picture2 = picture;
            }
        } else {
            picture2 = picture;
        }
    
        if (picture != picture2)
            *picture = *picture2;
        *bufp = buf;
    }
    
    static void do_subtitle_out(AVFormatContext *s,
                                OutputStream *ost,
                                InputStream *ist,
                                AVSubtitle *sub,
                                int64_t pts)
    {
        static uint8_t *subtitle_out = NULL;
        int subtitle_out_max_size = 1024 * 1024;
        int subtitle_out_size, nb, i;
        AVCodecContext *enc;
        AVPacket pkt;
    
        if (pts == AV_NOPTS_VALUE) {
    
            av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
    
            return;
        }
    
        enc = ost->st->codec;
    
        if (!subtitle_out) {
            subtitle_out = av_malloc(subtitle_out_max_size);
        }
    
        /* Note: DVB subtitle need one packet to draw them and one other
           packet to clear them */
        /* XXX: signal it in the codec context ? */
    
        if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
        for (i = 0; i < nb; i++) {
    
            ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
            if (!check_recording_time(ost))
                return;
    
    
            sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
            // start_display_time is required to be 0
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
            sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
            sub->end_display_time  -= sub->start_display_time;
    
            sub->start_display_time = 0;
            subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
                                                        subtitle_out_max_size, sub);
            if (subtitle_out_size < 0) {
    
                av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
    
            }
    
            av_init_packet(&pkt);
            pkt.data = subtitle_out;
            pkt.size = subtitle_out_size;
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
            pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
    
            if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
    
                /* XXX: the pts correction is handled here. Maybe handling
                   it in the codec would be better */
                if (i == 0)
                    pkt.pts += 90 * sub->start_display_time;
                else
                    pkt.pts += 90 * sub->end_display_time;
            }
    
    static void do_video_out(AVFormatContext *s,
                             OutputStream *ost,
                             AVFrame *in_picture,
    
                             int *frame_size)
    
        int ret, format_video_sync;
        AVPacket pkt;
        AVCodecContext *enc = ost->st->codec;
    
        format_video_sync = video_sync_method;
    
        if (format_video_sync == VSYNC_AUTO)
            format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :
                                (s->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;
    
        if (format_video_sync != VSYNC_PASSTHROUGH &&
            ost->frame_number &&
            in_picture->pts != AV_NOPTS_VALUE &&
            in_picture->pts < ost->sync_opts) {
    
            nb_frames_drop++;
            av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
    
        if (in_picture->pts == AV_NOPTS_VALUE)
            in_picture->pts = ost->sync_opts;
        ost->sync_opts = in_picture->pts;
    
    
    
        if (!ost->frame_number)
    
            ost->first_pts = in_picture->pts;
    
    Anton Khirnov's avatar
    Anton Khirnov committed
        av_init_packet(&pkt);
        pkt.data = NULL;
        pkt.size = 0;
    
    Anton Khirnov's avatar
    Anton Khirnov committed
        if (!check_recording_time(ost) ||
            ost->frame_number >= ost->max_frames)
            return;
    
    Anton Khirnov's avatar
    Anton Khirnov committed
        if (s->oformat->flags & AVFMT_RAWPICTURE &&
    
            enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
    
    Anton Khirnov's avatar
    Anton Khirnov committed
            /* raw pictures are written as AVPicture structure to
               avoid any copies. We support temporarily the older
               method. */
            enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
            enc->coded_frame->top_field_first  = in_picture->top_field_first;
            pkt.data   = (uint8_t *)in_picture;
            pkt.size   =  sizeof(AVPicture);
            pkt.pts    = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
            pkt.flags |= AV_PKT_FLAG_KEY;
    
    Anton Khirnov's avatar
    Anton Khirnov committed
            write_frame(s, &pkt, ost);
        } else {
            int got_packet;
            AVFrame big_picture;
    
            big_picture = *in_picture;
            /* better than nothing: use input picture interlaced
               settings */
            big_picture.interlaced_frame = in_picture->interlaced_frame;
            if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
                if (ost->top_field_first == -1)
                    big_picture.top_field_first = in_picture->top_field_first;
                else
                    big_picture.top_field_first = !!ost->top_field_first;
            }
    
            big_picture.quality = ost->st->codec->global_quality;
    
    Anton Khirnov's avatar
    Anton Khirnov committed
            if (!enc->me_threshold)
                big_picture.pict_type = 0;
            if (ost->forced_kf_index < ost->forced_kf_count &&
                big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
                big_picture.pict_type = AV_PICTURE_TYPE_I;
                ost->forced_kf_index++;
            }
            ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
            if (ret < 0) {
                av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
    
    Anton Khirnov's avatar
    Anton Khirnov committed
            }
    
    Anton Khirnov's avatar
    Anton Khirnov committed
            if (got_packet) {
                if (pkt.pts != AV_NOPTS_VALUE)
                    pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
                if (pkt.dts != AV_NOPTS_VALUE)
                    pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
    
    Anton Khirnov's avatar
    Anton Khirnov committed
                write_frame(s, &pkt, ost);
                *frame_size = pkt.size;
                video_size += pkt.size;
    
    Anton Khirnov's avatar
    Anton Khirnov committed
                /* if two pass, output log */
                if (ost->logfile && enc->stats_out) {
                    fprintf(ost->logfile, "%s", enc->stats_out);
    
    Anton Khirnov's avatar
    Anton Khirnov committed
        }
        ost->sync_opts++;
        /*
         * For video, number of frames in == number of packets out.
         * But there may be reordering, so we can't throw away frames on encoder
         * flush, we need to limit them here, before they go into encoder.
         */
        ost->frame_number++;
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
    static double psnr(double d)
    {
        return -10.0 * log(d) / log(10.0);
    
    }
    
    static void do_video_stats(AVFormatContext *os, OutputStream *ost,
                               int frame_size)
    {
        AVCodecContext *enc;
        int frame_number;
        double ti1, bitrate, avg_bitrate;
    
        /* this is executed just the first time do_video_stats is called */
        if (!vstats_file) {
            vstats_file = fopen(vstats_filename, "w");
            if (!vstats_file) {
                perror("fopen");
    
            }
        }
    
        enc = ost->st->codec;
        if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
            frame_number = ost->frame_number;
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
            fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
    
            if (enc->flags&CODEC_FLAG_PSNR)
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
                fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
    
    
            fprintf(vstats_file,"f_size= %6d ", frame_size);
            /* compute pts value */
            ti1 = ost->sync_opts * av_q2d(enc->time_base);
            if (ti1 < 0.01)
                ti1 = 0.01;
    
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
            bitrate     = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
    
            avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
            fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
                   (double)video_size / 1024, ti1, bitrate, avg_bitrate);
    
            fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
        }
    }
    
    
     * Read one frame for lavfi output for ost and encode it.
     */
    static int poll_filter(OutputStream *ost)
    
        OutputFile    *of = output_files[ost->file_index];
    
        AVFilterBufferRef *picref;
        AVFrame *filtered_frame = NULL;
    
        int frame_size, ret;
    
        if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
            return AVERROR(ENOMEM);
        } else
            avcodec_get_frame_defaults(ost->filtered_frame);
        filtered_frame = ost->filtered_frame;
    
        if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
            !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
            ret = av_buffersink_read_samples(ost->filter->filter, &picref,
                                             ost->st->codec->frame_size);
        else
            ret = av_buffersink_read(ost->filter->filter, &picref);
    
        if (ret < 0)
            return ret;
    
        avfilter_copy_buf_props(filtered_frame, picref);
        if (picref->pts != AV_NOPTS_VALUE) {
            filtered_frame->pts = av_rescale_q(picref->pts,
                                               ost->filter->filter->inputs[0]->time_base,
                                               ost->st->codec->time_base) -
                                  av_rescale_q(of->start_time,
                                               AV_TIME_BASE_Q,
                                               ost->st->codec->time_base);
    
            if (of->start_time && filtered_frame->pts < 0) {
    
                avfilter_unref_buffer(picref);
    
    
        switch (ost->filter->filter->inputs[0]->type) {
        case AVMEDIA_TYPE_VIDEO:
            if (!ost->frame_aspect_ratio)
                ost->st->codec->sample_aspect_ratio = picref->video->pixel_aspect;
    
    
            do_video_out(of->ctx, ost, filtered_frame, &frame_size);
    
            if (vstats_filename && frame_size)
                do_video_stats(of->ctx, ost, frame_size);
            break;
        case AVMEDIA_TYPE_AUDIO:
            do_audio_out(of->ctx, ost, filtered_frame);
            break;
        default:
            // TODO support subtitle filters
            av_assert0(0);
        }
    
        avfilter_unref_buffer(picref);
    
    
     * Read as many frames from possible from lavfi and encode them.
     *
     * Always read from the active stream with the lowest timestamp. If no frames
     * are available for it then return EAGAIN and wait for more input. This way we
     * can use lavfi sources that generate unlimited amount of frames without memory
     * usage exploding.
     */
    static int poll_filters(void)
    {
    
    
        while (ret >= 0 && !received_sigterm) {
            OutputStream *ost = NULL;
            int64_t min_pts = INT64_MAX;
    
            /* choose output stream with the lowest timestamp */
            for (i = 0; i < nb_output_streams; i++) {
                int64_t pts = output_streams[i]->sync_opts;
    
    
                if (!output_streams[i]->filter || output_streams[i]->finished)
    
                    continue;
    
                pts = av_rescale_q(pts, output_streams[i]->st->codec->time_base,
                                   AV_TIME_BASE_Q);
                if (pts < min_pts) {
                    min_pts = pts;
                    ost = output_streams[i];
                }
            }
    
            if (!ost)
                break;
    
            ret = poll_filter(ost);
    
            if (ret == AVERROR_EOF) {
    
                OutputFile *of = output_files[ost->file_index];
    
    
                if (of->shortest) {
                    for (j = 0; j < of->ctx->nb_streams; j++)
                        output_streams[of->ost_index + j]->finished = 1;
                }
    
    
                ret = 0;
            } else if (ret == AVERROR(EAGAIN))
                return 0;
        }
    
        return ret;
    }
    
    
    static void print_report(int is_last_report, int64_t timer_start)
    
    {
        char buf[1024];
        OutputStream *ost;
        AVFormatContext *oc;
        int64_t total_size;
        AVCodecContext *enc;
        int frame_number, vid, i;
        double bitrate, ti1, pts;
        static int64_t last_time = -1;
        static int qp_histogram[52];
    
    
        if (!print_stats && !is_last_report)
            return;
    
    
        if (!is_last_report) {
            int64_t cur_time;
            /* display the report every 0.5 seconds */
            cur_time = av_gettime();
            if (last_time == -1) {
                last_time = cur_time;
                return;
            }
            if ((cur_time - last_time) < 500000)
                return;
            last_time = cur_time;
        }
    
    
    
    
        total_size = avio_size(oc->pb);
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
        if (total_size < 0) // FIXME improve avio_size() so it works with non seekable output too
            total_size = avio_tell(oc->pb);
    
    
        buf[0] = '\0';
        ti1 = 1e10;
        vid = 0;
    
        for (i = 0; i < nb_output_streams; i++) {
    
            enc = ost->st->codec;
    
            if (!ost->stream_copy && enc->coded_frame)
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
                q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
    
            if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
            }
            if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
                float t = (av_gettime() - timer_start) / 1000000.0;
    
    
                frame_number = ost->frame_number;
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
                         frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
                if (is_last_report)
    
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
                if (qp_hist) {
    
                    int j;
                    int qp = lrintf(q);
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
                    if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
    
                        qp_histogram[qp]++;
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
                    for (j = 0; j < 32; j++)
    
                        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
                if (enc->flags&CODEC_FLAG_PSNR) {
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
                    double error, error_sum = 0;
                    double scale, scale_sum = 0;
                    char type[3] = { 'Y','U','V' };
    
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
                    for (j = 0; j < 3; j++) {
                        if (is_last_report) {
                            error = enc->error[j];
                            scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
                        } else {
                            error = enc->coded_frame->error[j];
                            scale = enc->width * enc->height * 255.0 * 255.0;
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
                        if (j)
                            scale /= 4;
    
                        error_sum += error;
                        scale_sum += scale;
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
                        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
    
                }
                vid = 1;
            }
            /* compute min output value */
            pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
            if ((pts < ti1) && (pts > 0))
                ti1 = pts;
        }
        if (ti1 < 0.01)
            ti1 = 0.01;
    
    
        bitrate = (double)(total_size * 8) / ti1 / 1000.0;
    
        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
    
                "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
                (double)total_size / 1024, ti1, bitrate);
    
    
        if (nb_frames_dup || nb_frames_drop)
            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
                    nb_frames_dup, nb_frames_drop);
    
        av_log(NULL, AV_LOG_INFO, "%s    \r", buf);
    
        fflush(stderr);
    
        if (is_last_report) {
    
            int64_t raw= audio_size + video_size + extra_size;
    
            av_log(NULL, AV_LOG_INFO, "\n");
            av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
                   video_size / 1024.0,
                   audio_size / 1024.0,
                   extra_size / 1024.0,
                   100.0 * (total_size - raw) / raw
    
    static void flush_encoders(void)
    
        for (i = 0; i < nb_output_streams; i++) {
    
            OutputStream   *ost = output_streams[i];
    
            AVCodecContext *enc = ost->st->codec;
    
            AVFormatContext *os = output_files[ost->file_index]->ctx;
    
            int stop_encoding = 0;
    
            if (!ost->encoding_needed)
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
            if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
    
            if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
    
    Aneesh Dogra's avatar
    Aneesh Dogra committed
            for (;;) {
    
                int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
                const char *desc;
                int64_t *size;
    
    
                switch (ost->st->codec->codec_type) {
                case AVMEDIA_TYPE_AUDIO:
    
                    encode = avcodec_encode_audio2;
                    desc   = "Audio";
                    size   = &audio_size;
    
                    break;
                case AVMEDIA_TYPE_VIDEO:
    
                    encode = avcodec_encode_video2;
                    desc   = "Video";
                    size   = &video_size;
                    break;
                default:
                    stop_encoding = 1;
                }
    
                if (encode) {
                    AVPacket pkt;
                    int got_packet;
                    av_init_packet(&pkt);
                    pkt.data = NULL;
                    pkt.size = 0;
    
                    ret = encode(enc, &pkt, NULL, &got_packet);
    
                        av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
    
                    *size += ret;
    
                    if (ost->logfile && enc->stats_out) {
                        fprintf(ost->logfile, "%s", enc->stats_out);
                    }
    
                    if (!got_packet) {
    
                        stop_encoding = 1;
                        break;
                    }
    
                    if (pkt.pts != AV_NOPTS_VALUE)
                        pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
                    if (pkt.dts != AV_NOPTS_VALUE)
                        pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
    
                    write_frame(os, &pkt, ost);
    
                if (stop_encoding)
    
    /*
     * Check whether a packet from ist should be written into ost at this time
     */
    static int check_output_constraints(InputStream *ist, OutputStream *ost)
    {
    
        OutputFile *of = output_files[ost->file_index];
        int ist_index  = input_files[ist->file_index]->ist_index + ist->st->index;
    
    
        if (ost->source_index != ist_index)
            return 0;
    
    
        if (of->start_time && ist->last_dts < of->start_time)
    
            return 0;
    
        return 1;
    }
    
    static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
    {
    
        OutputFile *of = output_files[ost->file_index];
    
        int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
        AVPacket opkt;
    
        av_init_packet(&opkt);
    
        if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
            !ost->copy_initial_nonkeyframes)
            return;
    
    
        if (of->recording_time != INT64_MAX &&
    
            ist->last_dts >= of->recording_time + of->start_time) {