打开编解码器上下文
获得流格式上下文及其相应的编解码器后,可以使用以下代码将其打开以进行解码:
// The format context and codec, given - see Find a stream for how to get these
AVFormatContext *formatContext;
AVCodec* codec;
int streamIndex;
// Get the codec context
AVCodecContext *codecContext = avcodec_alloc_context3(codec);
if (!codecContext){
// Out of memory
avformat_close_input(&formatContext);
}
// Set the parameters of the codec context from the stream
int result = avcodec_parameters_to_context(
codecContext,
formatContext->streams[streamIndex]->codecpar
);
if(result < 0){
// Failed to set parameters
avformat_close_input(&formatContext);
avcodec_free_context(&codecContext);
}
// Ready to open stream based on previous parameters
// Third parameter (NULL) is optional dictionary settings
if (avcodec_open2(codecContext, codec, NULL) < 0){
// Cannot open the video codec
codecContext = nullptr;
}
// Do something with the opened codec context... (ie decode frames through the context)