ffmpeg的H.264解碼

FFmpeg_allluckly.cn.png

新建工程,導入由Mac編譯ffmpeg獲取FFmpeg-iOS編譯好的FFmpeg-iOS,然后導入系統(tǒng)依賴的庫

AudioToolbox.framework
CoreMedia.framework
VideoToolbox.framework
libiconv.tbd
libbz2.tbd
libz.tbd

編譯的時候報錯: 'libavcodec/avcodec.h' file not found ,修改Header search paths 里的路徑:

$(PROJECT_DIR)/FFmpeg-iOS/include

然后導入頭文件

/*----------------解碼必須導入-----------------*/
#import "avformat.h"
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libswscale/swscale.h>
/*-------------------------------------------*/

運行一下項目不報錯的話,就可以開始解碼渲染之旅了。下面我們先從解碼開始;

h.264解碼

ffmpeg對視頻文件進行解碼的大致流程:

1.注冊所有容器格式和CODEC: av_register_all()

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        av_register_all();
    });

2.打開文件: av_open_input_file()

    pFormatContext = avformat_alloc_context();
    NSString *fileName = [[NSBundle mainBundle] pathForResource:@"zjd.h264" ofType:nil];
    if (fileName == nil)
    {
        NSLog(@"Couldn't open file:%@",fileName);
        return;
    }
    //[1]函數(shù)調(diào)用成功之后處理過的AVFormatContext結(jié)構(gòu)體;[2]打開的視音頻流的URL;[3]強制指定AVFormatContext中AVInputFormat的。這個參數(shù)一般情況下可以設(shè)置為NULL,這樣FFmpeg可以自動檢測AVInputFormat;[4]附加的一些選項,一般情況下可以設(shè)置為NULL。)
    if (avformat_open_input(&pFormatContext, [fileName cStringUsingEncoding:NSASCIIStringEncoding], NULL, NULL) != 0)
    {
        NSLog(@"無法打開文件");
        return;
    }

3.從文件中提取流信息: av_find_stream_info()

if (avformat_find_stream_info(pFormatContext, NULL) < 0) {
        NSLog(@"無法提取流信息");
        return;
 }

4.窮舉所有的流,查找其中種類為CODEC_TYPE_VIDEO

    int videoStream = -1;
    for (int i = 0; i < pFormatContext -> nb_streams; i++)
    {
        if (pFormatContext -> streams[i] -> codec -> codec_type == AVMEDIA_TYPE_VIDEO)
        {
            videoStream = i;
        }
    }
    if (videoStream == -1) {
        NSLog(@"Didn't find a video stream.");
        return;
    }

5.查找對應的解碼器: avcodec_find_decoder()

pCodecCtx = pFormatContext->streams[videoStream]->codec;
    AVCodec *pCodec = avcodec_find_decoder(AV_CODEC_ID_H264);
    if (pCodec == NULL) {
        NSLog(@"pVideoCodec not found.");
        return NO;
    }

6.打開編解碼器: avcodec_open()

avcodec_open2(pCodecCtx, pCodec, NULL);

7.為解碼幀分配內(nèi)存: avcodec_alloc_frame()

pFrame = av_frame_alloc();

8.不停地從碼流中提取中幀數(shù)據(jù): av_read_frame()

    AVPacket packet;
    av_init_packet(&packet);

    if (av_read_frame(pFormatContext, &packet) >= 0)
    {//已經(jīng)讀取到了數(shù)據(jù)
    
    }else{//沒讀取到數(shù)據(jù)

    }

9.判斷幀的類型,對于視頻幀調(diào)用: avcodec_decode_video()

      //作用是解碼一幀視頻數(shù)據(jù)。輸入一個壓縮編碼的結(jié)構(gòu)體AVPacket,輸出一個解碼后的結(jié)構(gòu)體AVFrame
    avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
    av_free_packet(&packet);
    if (frameFinished) //解碼成功
    {
   
    }

10.解碼完后,釋放解碼器: avcodec_close()

avcodec_close()

11.關(guān)閉輸入文件:av_close_input_file()

av_close_input_file()

最后封裝的代碼如下


/*input_str  輸入的文件路徑
 *output_str 輸出的文件路徑
 *return 解碼后的信息
 */

#pragma mark - 基于FFmpeg的視頻解碼器
- (NSString *)decoder:(NSString *)input_str output_str:(NSString *)output_str{
    AVFormatContext *pFormatCtx;
    int             i, videoindex;
    AVCodecContext  *pCodecCtx;
    AVCodec         *pCodec;
    AVFrame *pFrame,*pFrameYUV;
    uint8_t *out_buffer;
    AVPacket *packet;
    int y_size;
    int ret, got_picture;
    struct SwsContext *img_convert_ctx;
    FILE *fp_yuv;
    int frame_cnt;
    clock_t time_start, time_finish;
    double  time_duration = 0.0;
    
    char input_str_full[500]={0};
    char output_str_full[500]={0};
    char info[1000]={0};
    
//    NSString *input_str= [NSString stringWithFormat:@"resource.bundle/sintel.mov"];
//    NSString *output_str= [NSString stringWithFormat:@"resource.bundle/test.yuv"];
    
    NSString *input_nsstr=[[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:input_str];
    NSString *output_nsstr=[[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:output_str];
    
    sprintf(input_str_full,"%s",[input_nsstr UTF8String]);
    sprintf(output_str_full,"%s",[output_nsstr UTF8String]);
    
    printf("Input Path:%s\n",input_str_full);
    printf("Output Path:%s\n",output_str_full);
    //注冊編解碼器
    av_register_all();
    //打開網(wǎng)絡(luò)流
    avformat_network_init();
    //初始化AVFormatContext
    pFormatCtx = avformat_alloc_context();
    
    if(avformat_open_input(&pFormatCtx,input_str_full,NULL,NULL)!=0){
        printf("Couldn't open input stream.\n");
        return nil;
    }
    if(avformat_find_stream_info(pFormatCtx,NULL)<0){
        printf("Couldn't find stream information.\n");
        return nil;
    }
    videoindex=-1;
    for(i=0; i<pFormatCtx->nb_streams; i++)
        if(pFormatCtx->streams[i]->codecpar->codec_type==AVMEDIA_TYPE_VIDEO){
            videoindex=i;
            break;
        }
    if(videoindex==-1){
        printf("Couldn't find a video stream.\n");
        return nil;
    }
    pCodecCtx = avcodec_alloc_context3(NULL);
    if (pCodecCtx == NULL)
    {
        printf("Could not allocate AVCodecContext\n");
        return nil;
    }
    avcodec_parameters_to_context(pCodecCtx, pFormatCtx->streams[videoindex]->codecpar);
    
    pCodec = avcodec_find_decoder(pCodecCtx->codec_id);  //指向AVCodec的指針.查找解碼器
    if(pCodec==NULL){
        printf("Couldn't find Codec.\n");
        return nil;
    }
    if(avcodec_open2(pCodecCtx, pCodec,NULL)<0){
        printf("Couldn't open codec.\n");
        return nil;
    }
    
    pFrame=av_frame_alloc();
    pFrameYUV=av_frame_alloc();
    out_buffer=(unsigned char *)av_malloc(av_image_get_buffer_size(AV_PIX_FMT_YUV420P,  pCodecCtx->width, pCodecCtx->height,1));
    av_image_fill_arrays(pFrameYUV->data, pFrameYUV->linesize,out_buffer,
                         AV_PIX_FMT_YUV420P,pCodecCtx->width, pCodecCtx->height,1);
    packet=(AVPacket *)av_malloc(sizeof(AVPacket));
    
    img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
                                     pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
    
    
    sprintf(info,   "[Input     ]%s\n", [input_str UTF8String]);
    sprintf(info, "%s[Output    ]%s\n",info,[output_str UTF8String]);
    sprintf(info, "%s[Format    ]%s\n",info, pFormatCtx->iformat->name);
    sprintf(info, "%s[Codec     ]%s\n",info, pCodecCtx->codec->name);
    sprintf(info, "%s[Resolution]%dx%d\n",info, pCodecCtx->width,pCodecCtx->height);
    
    
    fp_yuv=fopen(output_str_full,"wb+");
    if(fp_yuv==NULL){
        printf("Cannot open output file.\n");
        return nil;
    }
    
    frame_cnt=0;
    time_start = clock();
    
    while(av_read_frame(pFormatCtx, packet)>=0){
        if(packet->stream_index==videoindex){
            ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
            if(ret < 0){
                printf("Decode Error.\n");
                return nil;
            }
            if(got_picture){
                sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height,
                          pFrameYUV->data, pFrameYUV->linesize);
                
                y_size=pCodecCtx->width*pCodecCtx->height;
                fwrite(pFrameYUV->data[0],1,y_size,fp_yuv);    //Y
                fwrite(pFrameYUV->data[1],1,y_size/4,fp_yuv);  //U
                fwrite(pFrameYUV->data[2],1,y_size/4,fp_yuv);  //V
                //Output info
                char pictype_str[10]={0};
                switch(pFrame->pict_type){
                    case AV_PICTURE_TYPE_I:sprintf(pictype_str,"I");break;
                    case AV_PICTURE_TYPE_P:sprintf(pictype_str,"P");break;
                    case AV_PICTURE_TYPE_B:sprintf(pictype_str,"B");break;
                    default:sprintf(pictype_str,"Other");break;
                }
                printf("Frame Index: %5d. Type:%s\n",frame_cnt,pictype_str);
                frame_cnt++;
            }
        }
        av_packet_unref(packet);
    }
    //flush decoder
    //FIX: Flush Frames remained in Codec
    while (1) {
        ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
        if (ret < 0)
            break;
        if (!got_picture)
            break;
        sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height,
                  pFrameYUV->data, pFrameYUV->linesize);
        int y_size=pCodecCtx->width*pCodecCtx->height;
        fwrite(pFrameYUV->data[0],1,y_size,fp_yuv);    //Y
        fwrite(pFrameYUV->data[1],1,y_size/4,fp_yuv);  //U
        fwrite(pFrameYUV->data[2],1,y_size/4,fp_yuv);  //V
        //Output info
        char pictype_str[10]={0};
        switch(pFrame->pict_type){
            case AV_PICTURE_TYPE_I:sprintf(pictype_str,"I");break;
            case AV_PICTURE_TYPE_P:sprintf(pictype_str,"P");break;
            case AV_PICTURE_TYPE_B:sprintf(pictype_str,"B");break;
            default:sprintf(pictype_str,"Other");break;
        }
        printf("Frame Index: %5d. Type:%s\n",frame_cnt,pictype_str);
        frame_cnt++;
    }
    time_finish = clock();
    time_duration=(double)(time_finish - time_start);
    
    sprintf(info, "%s[Time      ]%fus\n",info,time_duration);
    sprintf(info, "%s[Count     ]%d\n",info,frame_cnt);
    
    sws_freeContext(img_convert_ctx);
    
    fclose(fp_yuv);
    
    av_frame_free(&pFrameYUV);
    av_frame_free(&pFrame);
    avcodec_close(pCodecCtx);
    avformat_close_input(&pFormatCtx);
    
    NSString * info_ns = [NSString stringWithFormat:@"%s", info];
    
//    NSLog(@"解碼后的信息%@",info_ns);
    NSLog(@"文件輸出路徑%@",output_nsstr);
    
    return info_ns;
    
}

參考資料:雷神的ffmpeg解碼

LBffmpegDemo下載地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • 教程一:視頻截圖(Tutorial 01: Making Screencaps) 首先我們需要了解視頻文件的一些基...
    90后的思維閱讀 4,987評論 0 3
  • 現(xiàn)狀:現(xiàn)在視頻直播非常的火,所以在視頻直播開發(fā)中,使用的對視頻進行遍解碼的框架顯得尤為重要了,其實,這種框架蠻多的...
    ZHANG_GO閱讀 3,274評論 0 2
  • ffmpeg是一個非常有用的命令行程序,它可以用來轉(zhuǎn)碼媒體文件。它是領(lǐng)先的多媒體框架FFmpeg的一部分,其有很多...
    城市之光閱讀 7,045評論 3 6
  • 原文地址:http://blog.csdn.net/yipie/article/details/7912291 摘...
    冬的天閱讀 7,274評論 1 6
  • 醒了哭,哭累了睡的張杰看著墻上的鐘,滴滴答答每一聲仿佛都敲在自己的心臟上。室外的瓢潑大雨也跟著湊趣似得,緊鑼密鼓,...
    樵砥閱讀 269評論 0 0

友情鏈接更多精彩內(nèi)容