開啟編解碼器上下文
獲得流格式上下文及其相應的編解碼器後,可以使用以下程式碼將其開啟以進行解碼:
// 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)