ffmpeg解码H264文件并实时播放


ffmpeg rtsp推流、解码   课程教学:

ffmpeg实现H264编、解码,RTSP推流,RTSP解码

里面提供源码可以直接下载运行!
 


一、ffmpeg初始化

av_register_all(); //初始化FFMPEG
av_init_packet(&pkt);

二、查找解码器

    AVCodecID codec_id = AV_CODEC_ID_H264;
    pCodec = avcodec_find_decoder(codec_id);
    if (!pCodec)
    {
        printf("Codec not found\n");
        return ;
    }

三、分配解码器空间

    pCodecCtx = avcodec_alloc_context3(pCodec);
    if (!pCodecCtx)
    {
        printf("Could not allocate video codec context\n");
        return ;
    }

四、设置解码器属性

    pCodecCtx->codec_type  = AVMEDIA_TYPE_VIDEO;
    pCodecCtx->pix_fmt     = AV_PIX_FMT_YUV420P; //解码器的输出格式

五、打开解码器

    if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0)
    {
        qDebug()<<"Could not open codec";
        return ;
    }

六、分配pFrame结构体

     pFrame = av_frame_alloc();
    if (!pFrame)
    {
        printf("Could not allocate video frame\n");
        return ;
    }

七、打开264文件

    //打开264文件
    fp_in = fopen(filename_in, "rb");
    if (!fp_in)
    {
        printf("Could not open %s\n", filename_in);
        return ;
    }
    int inLen=0;
    unsigned char* inBuf=NULL;
    unsigned char* outBuf=NULL;
    inBuf  = (unsigned char*)calloc ( 500000, sizeof(char));
    outBuf = (unsigned char*)calloc ( 1000000, sizeof(char));

八、解码主循环

8.1 找到帧头

inLen = getNextNal(fp_in, inBuf);

8.2 解码

int ret= avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, &pkt);
if (ret < 0)
{
      printf("avcodec_decode_video2 failed\n");
      //return ;  //注意不要return  有可能264有一些不是关键帧  需要跳过
}

8.3 YUV422--->RGB

//================================ 设置数据转换参数 ================================//
struct SwsContext *img_convert_ctx;
img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
                    pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_RGB32, SWS_BICUBIC, NULL, NULL, NULL);


//转换一帧图像
sws_scale(img_convert_ctx,pFrame->data, pFrame->linesize, 0, pCodecCtx->height,  //源
                          pFrameRGB->data, pFrameRGB->linesize);                              //目的

8.4 触发信号,更新绘图QImage

 QImage tmpimage((uchar *)out_buffer,pCodecCtx->width,pCodecCtx->height,QImage::Format_RGB32);
 QImage image = tmpimage.copy();
 emit sig_GetOneFrame(image);  //发送信号


ffmpeg rtsp推流、解码   课程教学:

ffmpeg实现H264编、解码,RTSP推流,RTSP解码​​​​​​​

里面提供源码可以直接下载运行!
 


公众号名称:玩转电子世界

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章