[FFMPEG]iOS下解码H264裸流

如下代码,
初始化:

 */
- (BOOL)initH264DecoderWithWidth:(int)width height:(int)height {
    
    av_register_all();
    avcodec_register_all();
    avformat_network_init();
    self.codec = avcodec_find_decoder(AV_CODEC_ID_H264);
    av_init_packet(&_packet);
    
    if (self.codec != nil) {
        self.pCodecContext = avcodec_alloc_context3(self.codec);
        
        // 每包一个视频帧
        self.pCodecContext->frame_number = 1;
        self.pCodecContext->codec_type = AVMEDIA_TYPE_VIDEO;
        
        NSLog(@"pCodecContextWidth,Height,%d,%d",self.pCodecContext->width,self.pCodecContext->height);
        
        // 视频的宽度和高度
        self.pCodecContext->width = width;
        self.pCodecContext->height = height;
        
        // 打开codec
        if (avcodec_open2(self.pCodecContext, self.codec, NULL) >= 0) {
            self.frame = av_frame_alloc();
            if (self.frame == NULL) {
                return NO;
            }
        }
    }
    NSLog(@"size:%d",self.pCodecContext->frame_size);
    
    int version = avcodec_version();
    return (BOOL)self.frame;
}

2.解码过程

- (void)H264decoderWithVideoData:(NSString *)moviePath{
    /*打开输入流,四个参数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");
        return;
    }
    
    //find the first video stream
    videoStream = 0;
    
    NSData *VideoData = [NSData dataWithContentsOfFile:moviePath];
    
    static int i;
    i++;
    count++;
    
    _packet.data = (uint8_t *)VideoData.bytes;
    _packet.size = (int)VideoData.length;
    
    
    int got_picture_ptr;
    int status = avcodec_decode_video2(self.pCodecContext, self.frame, &got_picture_ptr, &(_packet));
    [self setupScaler];
    
    if (status >0)
    {
//        [self dispatchAVFrame:self.frame];
        [self playFrame];
    }else
    {
        avcodec_flush_buffers(self.pCodecContext);
    }
}

你可能感兴趣的:([FFMPEG]iOS下解码H264裸流)