[Libav-user] Finding AVCodecContext data from sps and pps packets

Sampsa Riikonen sampsa.riikonen at iki.fi
Mon May 30 09:48:29 CEST 2016


Hello,

I have a code in which I am receiving H264 sps, pps and frame packets 
and want to mux them into matroska, using libav*.

As instructed in the sample codes, I am doing roughly the following:

AVFormatContext *oc;
AVCodec *codec;
AVCodecContext *ctx;
AVStream *stream;
AVPacket *avpkt;

avformat_alloc_output_context2(&oc, NULL, NULL, "output.mkv");

codec  = avcodec_find_decoder(AV_CODEC_ID_H264); // AVCodec = possible 
parameters for a codec
ctx    = avcodec_alloc_context3(codec);          // reserve memory for 
codec related thingies.. AVCodecContext = defines codec parameters (as 
per AVCodec)
stream = avformat_new_stream(oc,ctx->codec);     // add new stream to 
AVFormatContext ctx->codec is "AVCodec"

avcodec_copy_context(stream->codec,ctx);         // stream.codec == 
AVCodecContext (we populate the codec parameters for stream "stream")

// THE QUESTION: How do we populate stream->codec, i.e. AVCodecContext 
instance, correctly for the stream? (***)

avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);   // open the matroska 
file ..
ret = avformat_write_header(oc, NULL);

...

av_interleaved_write_frame(oc,avpkt);           // pass packets to the muxer


The problem is, that prior to opening the matroska file, stream->codec 
has no information about picture dimensions (matroska header requires 
pic dimensions).
I can solve this by passing sps, pps and an i-frame to a decoder (with 
avcodec_decode_video2), which populates an AVCodecContext with correct 
picture information, and then use that AVCodecContext.
However, this seems to be an overkill.. I do not want to decode 
anything, just to get the codec parameters from sps and pps.  Is there a 
simpler way to achieve this?

In fact, for files (AVFormatContext), there is the routine 
"avformat_find_stream_info" for such task.  At the present case, 
however, I only have raw sps, pps and frame packets.

One observation more: the sps, pps and I-frame (nal unit types 7,8 & 5), 
must the aggregated into a single packet in order for the matroska muxer 
to work.

Regards,

Sampsa



More information about the Libav-user mailing list