代码比较详细,并且加有详细的注释,方便深入了解。
int32_t FFDecoder::OpenFile(const std::string& filename) {
//创建一个AVFormatContext类型的结构体变量ctx_,用于存储视频信息和解码时所需的上下文信息。
ctx_ = avformat_alloc_context();
//判断创建的ctx_是否为空,如果为空
//则说明为该结构体分配空间时出现了问题,日志输出错误信息,并返回-1表示打开文件失败。
if (!ctx_) {
FLOGE << "avformat_alloc_context fail";
return -1;
}
//打开指定的多媒体文件,并将文件信息读入到ctx_中,
//其中filename是指定文件名,ret是函数返回值,用于保存打开文件的结果。
auto ret = avformat_open_input(&ctx_, filename.c_str(), nullptr, nullptr);
if (ret < 0) {
FLOGE << "avformat_open_input fail:" << ret << " " << FFErr2Str(ret);
return -1;
}
//查找多媒体文件中的音视频流信息,并将其存入ctx_中,其中ret是函数返回值,用于保存查找结果。
ret = avformat_find_stream_info(ctx_, nullptr);
if (ret < 0) {
FLOGE << "avformat_find_stream_info fail:" << ret << " " << FFErr2Str(ret);
return -1;
}
//遍历ctx_中存储的所有流信息,查找有效的音视频流。
for (int i = 0; i < ctx_->nb_streams; ++i) {
//判断当前流信息是否为视频流信息,如果是则获取该流索引videoStreamIdx_,否则略过。
if (ctx_->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
videoStreamIdx_ = i;
}
//判断当前流信息是否为音频流信息,如果是则可以进行音频相关处理或者解码,这里暂不实现。
else if (ctx_->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
// audio
}
//如果不是视频/音频流信息,则输出警告信息并略过。
else {
FLOGW << "unknown stream type";
}
}
//判断是否成功获取到有效的视频流信息,如果没有则说明打开文件失败。
//此处日志输出错误信息并返回-1表示打开文件失败。
if (videoStreamIdx_ < 0) {
FLOGE << "cannot fint valid video stream";
return -1;
}
return 0;
}