[Libav-user] demuxing streams and mux them back to file

Wuerfel, Hannes Hannes.Wuerfel at student.hpi.uni-potsdam.de
Wed Nov 14 12:43:04 CET 2012


Hey all,

I'm trying to write a simple program which decodes the video and audio frames and encodes and mux it back to a file.
How can I generally accomplish that?

decoding and encoding the videostream for itself works.
decoding and encoding the audiostream for itself works.
(as shown in the decoding_encoding.c example)

Basically I took the demuxing.c example and wanted to mux the video and audio frames back together but I'm stucked for days on this.

I've added an output AVFormatContext and an out AVStream for video and an out AVStream for audio.
I've tried to copy the input Codec settings.
Further I used avio_open to open the file,
used avformat_write_header to write the stream headers
and after decoding I use av_write_trailer
and avio_close

Is this basically write or do I miss something important?

This is how I tried to copy the input Codec settings to the output Codec settings:

static AVStream *add_stream(AVFormatContext *oc, const AVCodec *inCodec,
                            AVCodec** outCodec, enum AVCodecID codec_id)
{
    AVCodecContext *c;
    AVStream *st;

    /* find the encoder */
    *outCodec = avcodec_find_encoder(codec_id);
    if (!(*outCodec)) {
        fprintf(stderr, "Could not find codec\n");
        exit(1);
    }

    st = avformat_new_stream(oc, *outCodec);
    if (!st) {
        fprintf(stderr, "Could not allocate stream\n");
        exit(1);
    }
    st->id = oc->nb_streams-1;
    c = st->codec;

    switch ((*outCodec)->type) {
    case AVMEDIA_TYPE_AUDIO:
        st->id = 1;
        c->sample_fmt  = audio_stream->codec->sample_fmt;
        c->bit_rate    = audio_stream->codec->bit_rate;
        c->sample_rate = audio_stream->codec->sample_rate;
        c->channels    = audio_stream->codec->channels;
        break;
    case AVMEDIA_TYPE_VIDEO:
        avcodec_get_context_defaults3(c, inCodec);
        c->codec_id = video_stream->codec->codec_id;

        c->bit_rate = video_stream->codec->bit_rate;
        c->width    = video_stream->codec->width;
        c->height   = video_stream->codec->height;
        c->time_base.den = video_stream->codec->time_base.den;
        c->time_base.num = video_stream->codec->time_base.num;
        c->gop_size      = video_stream->codec->gop_size;
        c->pix_fmt       = video_stream->codec->pix_fmt;
        c->max_b_frames = video_stream->codec->max_b_frames;
        c->mb_decision = video_stream->codec->mb_decision;
		break;
    default:
        break;
    }

    /* Some formats want stream headers to be separate. */
    if (oc->oformat->flags & AVFMT_GLOBALHEADER)
        c->flags |= CODEC_FLAG_GLOBAL_HEADER;

    return st;
}

Thanks.


More information about the Libav-user mailing list