chatGPT答: |
8v6.cn |
#include <iostream>
extern "C" {
#include <libavcodec/avcodec.h> // 声明编解码器相关函数
#include <libavformat/avformat.h> // 声明封装格式相关函数
}
int main() {
av_register_all(); // 注册所有的编解码器和封装格式库
AVFormatContext *pFormatCtx = NULL; // 封装格式上下文结构体指针,用于存储音视频封装格式中的信息
if (avformat_open_input(&pFormatCtx, "input.mp4", NULL, NULL) != 0) { // 打开输入文件并读取头部信息,返回值为0表示成功,否则表示失败
std::cerr << "Could not open input file." << std::endl;
return -1;
}
if (avformat_find_stream_info(pFormatCtx, NULL) < 0) { // 获取音视频流信息,返回值为小于0表示失败,否则表示成功
std::cerr << "Could not find stream information." << std::endl;
return -1;
}
int videoStreamIndex = -1;
for (unsigned int i = 0; i < pFormatCtx->nb_streams; ++i) {
if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
videoStreamIndex = i;
break;
}
}
if(videoStreamIndex == -1){
std::cerr<<"Could not find a video stream"<<std::endl;
return -1;
}
AVCodecParameters *pCodecParams=pFormatCtx->streams[videoStreamIndex]->codecpar;//获取视频流的编解码参数
AVCodec *pCodec= avcodec_find_decoder(pCodecParams-> codec_id);//查找对应ID的解码器
AVCodecContext * pCodeContex= avcodec_alloc_context3(pCodec);//分配AVCodeContex结构体,并初始化
if(avcodec_parameters_to_context(pCodeContex,pCodecParams)<0){//将AVCodcParameters中的参数复制到AVCodcContext中去。
std:cerr<<"Failed to copy codec parameters to context"<<std:endl;
return-1;
}
if(av_codec_open2(pCodeContex,pCoded,NULL)<o){//打开对应ID 的解码器。如果不是NULL,则使用该字典设置选项。
cerr<<“Failed to open decoder for”<<aVGetMediaTypeName(Pcodeparams-codec_type)<<std::end;//获取媒体类型名称字符串。
retrun-1;
}
av_packet_init(&packet); 初始化包结构体
while(av_read_frame(PFormateCTX,&packet)>=o){//循环读取每一帧数据
if(packet.stream_index==videoSreamindex){
ret=decode_write_video(frame,picture_buf_size,output_file);
frame_count++;
}
av_packet_unref(&packet);
}
flush_encoder(output_file);
fclose(output_file);
free_picture_buf();
free_encode_contxt();
}
|