初始化视频流信息
- (instancetype)initWithVideo:(NSString *)moviePath
{
if (!(self = [super init])) {
return nil;
}
self.isNetwork = isNetworkPath(moviePath);
if (self.isNetwork) {
avformat_network_init();
}
AVCodec *pCodec;
//注册所有的文件格式和编解码器
avcodec_register_all();
av_register_all();
//打开视频文件
/*打开输入流,四个参数1.获得文件名,这个函数读取文件的头部并且把信息保存到AVFormatContext结构体中,,fmt:如果非空,这个参数强制一个特定的输入格式。否则自动适应格式
##注释 将文件格式的上下文传递到AVFormatContext类型的结构体formatCtx中
*/
if (avformat_open_input(&pFormatContext, [moviePath cStringUsingEncoding:NSASCIIStringEncoding], NULL, NULL)) {
av_log(NULL, AV_LOG_ERROR, "Couldn't open file\n");
goto initError;
}
//读取数据包获取流媒体文件的信息,每个AVStream存储一个视频/音频流的相关数据;每个AVStream对应一个AVCodecContext,存储该视频/音频流使用解码方式的相关数据 ##注释 查找文件中流的信息
if (avformat_find_stream_info(pFormatContext, NULL) < 0) {
av_log(NULL, AV_LOG_ERROR, "Couldn't find a video stream in the input");
goto initError;
}
//find the first video stream
if ((videoStream = av_find_best_stream(pFormatContext, AVMEDIA_TYPE_VIDEO, -1, -1, &pCodec, 0)) < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot find a video stream in the input file\n");
goto initError;
}
NSLog(@"videoStream:%d",videoStream);
// find the audio stream;
/*
if ((audioStream = av_find_best_stream(pFormatContext, AVMEDIA_TYPE_AUDIO, -1, -1, &pCodec, 0))<0) {
av_log(NULL, AV_LOG_ERROR, "Cannot find a audio stream in the input file\n");
}
*/
//Get a pointer to the codec context for the video stream
pCodecContext = pFormatContext->streams[videoStream]->codec;
//find the decoder for the video stream
pCodec = avcodec_find_decoder(pCodecContext->codec_id);
if (pCodec == NULL) {
av_log(NULL, AV_LOG_ERROR, "Unsupported codec!\n");
goto initError;
}
NSLog(@"Codec:%s",pCodec->name);
//open codec
if (avcodec_open2(pCodecContext, pCodec, NULL) < 0) {
av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n");
goto initError;
}
pFrame = av_frame_alloc();
self.outputWidth = pCodecContext->width;
self.outputHeight = pCodecContext->height;
NSLog(@"width,height,dur,%d,%d",self.outputWidth,self.outputHeight);
return self;
initError:
return nil;
}
播放:
- (NSArray *)playFrame
{
NSLog(@"===================GO");
//AVPacket packet;
int frameFinished = 0; // 是否解析结束. 0:未结束 1:已结束
NSLog(@"BEGIN --- while (!frameFinished && av_read_frame(pFormatContext, &packet)>=0)");
while (!frameFinished && av_read_frame(pFormatContext, &packet)>=0) {
NSLog(@"DOING --- while (!frameFinished && av_read_frame(pFormatContext, &packet)>=0)");
//is this a packet from the video stream
if (packet.stream_index == videoStream) {
avcodec_decode_video2(pCodecContext, pFrame, &frameFinished, &packet);
}
NSLog(@"%lld",pFrame->pkt_duration);
}
return [NSArray arrayWithObjects:[NSNumber numberWithBool:(frameFinished != 0)] ,[self currentImage], nil];
}