利用ffmpeg解码h264裸流并存储成YUV420

6 篇文章 0 订阅
2 篇文章 0 订阅

此处用的ffmpeg版本为3.2.2。
例子是在linux下所写的,大致流程如下:

  1. 初始化ffmpeg库
  2. 创建YUV文件,用于存储解码后的YUV数据
  3. 初始化H264解码器
  4. 给解码器的一些结构变量赋值
  5. 打开解码器
  6. 打开H264裸流文件
  7. 读取一定数据的h264数据(因为不知道一帧到底有多大)
  8. 调用ffmpeg函数,循环分析读取到的数据,每循环一次得到一帧数据,然后调用解码器解码,并存储成YUV420文件。直到分析完读入的数据
  9. 释放内存,解码结束

编译命令如下(有些库非必须):
gcc -o codec codec.c -lavdevice -lavformat -lavfilter -lpostproc -lavcodec -lswresample -lswscale -lavutil -lpthread -ldl -lxml2 -lz -lx264 -ldl -lm

具体代码:

#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavfilter/avfiltergraph.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libavutil/opt.h>
#include <libavutil/pixdesc.h>
#include <sys/time.h>

#define INBUF_SIZE 40960000
FILE *yuv_fp = NULL;

int main(int argc, int argv)
{   
    //解码后,存储的文件,测试文件分辨率是640x480
    yuv_fp = fopen("test_640x360.yuv","wb");
    if(NULL == yuv_fp)
    {
        fprintf(stderr,"Open test.yuv fail\n");
        exit(1);
    }

    avcodec_register_all();
    AVCodec *codec;
    AVCodecContext *c = NULL;
    AVFrame *frame;
    AVCodecParserContext *avParserContext;
    FILE *f = NULL;
    int frame_count = 0;
    //读取264文件后所存储的buf
    unsigned char * inbuf = (unsigned char*)malloc(INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
    int got_frame;
    int read_size;

    memset(inbuf + INBUF_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);

    codec = avcodec_find_decoder(AV_CODEC_ID_H264);
    if( NULL == codec )
    {
        fprintf(stderr,"Codec not found\n");
        exit(1);
    }

    c = avcodec_alloc_context3(codec);
    if(NULL == c)
    {
        fprintf(stderr,"Could not allocate video codec context\n");
        exit(1);
    }

    //初始化解码器所需要的参数,其实不设置也是可以正常解码的,因为264流中有对应的pps,sps相关结构
    //里面包含解码所需要的相关信息
    c->width = 640;
    c->height = 360;
    c->bit_rate = 1000;
    c->time_base.num = 1;
    c->time_base.den = 25;
    c->codec_id = AV_CODEC_ID_H264;
    c->codec_type = AVMEDIA_TYPE_VIDEO;

    avParserContext = av_parser_init(AV_CODEC_ID_H264);
    if( NULL == avParserContext)
    {
        fprintf(stderr,"Could not init avParserContext\n");
        exit(1);
    }

    if(avcodec_open2(c,codec, NULL) < 0)
    {
        fprintf(stderr,"Could not open codec\n");
        exit(1);
    }

    frame = av_frame_alloc();
    if(NULL == frame)
    {
        fprintf(stderr,"Could not allocate video frame\n");
        exit(1);
    }

    f = fopen("test.264","rb");
    if( NULL == f )
    {
        fprintf(stderr,"Could not allocate video frame");
        exit(1);
    }

    for(;;)
    {
        //解码还有问题,因为avpkt不是一帧数据,而是有很多帧的数据,
        //需要增加一个filter,一帧一帧过滤出来
        read_size = fread(inbuf, 1,INBUF_SIZE, f);
        printf("read_size_orig=%d\n",read_size);
        if(read_size == 0)
        {
            break;
        }

        while(read_size)
        {
            unsigned char *buf = 0;
            int buf_len = 0;
            int parse_len = av_parser_parse2(avParserContext, c, &buf, &buf_len,
                        inbuf, read_size,
                        AV_NOPTS_VALUE, AV_NOPTS_VALUE,AV_NOPTS_VALUE);
            inbuf += parse_len;
            read_size -= parse_len;
            //printf("read_size=%d, parse_len=%d, buf_len=%d\n",read_size, parse_len, buf_len);
            #if 1
            if(buf_len != 0)
            {
                AVPacket avpkt = {0}; 
                av_init_packet(&avpkt);
                avpkt.data = buf;
                avpkt.size = buf_len;
                time_t start ,end;
                start = clock();
                int decode_len = avcodec_decode_video2(c,frame, &got_frame, &avpkt);
                end = clock();
                printf("decoded frame used %d\n",end - start);
                if(decode_len < 0)
                    fprintf(stderr,"Error while decoding frame %d\n",frame_count);
                if(got_frame)
                {
                    fprintf(stderr,"decode success\n");
                    int width = frame->width;
                    int height = frame->height;
                    unsigned char* yuv_buf = (unsigned char*)malloc(width * height *1.5);//可以放在while循环外面,这样就不用每次都申请,释放了
                    int i = 0;

                    //把解码出来的数据存成YUV数据,方便验证解码是否正确
                    for(i = 0; i < height; i++)
                    {
                        memcpy(yuv_buf + width * i, frame->data[0] + frame->linesize[0]*i, width);
                        if(i < height >> 1)
                        {
                            memcpy(yuv_buf + width * height + width *i / 2, frame->data[1] + frame->linesize[1]*i, width / 2);
                            memcpy(yuv_buf + width * height * 5 /4 + width * i / 2 ,frame->data[2] + frame->linesize[2]*i, width / 2);
                        }
                    }
                    fwrite(yuv_buf, sizeof(unsigned char),width * height * 1.5 ,yuv_fp);
                    free(yuv_buf);
                    frame_count++;

                }
                else
                {
                    fprintf(stderr,"decode fail\n");
                }
                av_packet_unref(&avpkt);
            }
            #endif
        }
    }

    //记得释放变量的空间
    return 0;
}
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要保存 YUV 格式数据,可以使用 FFmpeg 库提供的 `AVFrame` 结构体和 `av_write_frame` 函数。下面是保存 YUV 格式数据的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libavformat/avformat.h> int main(int argc, char *argv[]) { int ret; AVFormatContext *fmt_ctx = NULL; AVOutputFormat *ofmt = NULL; AVStream *video_st = NULL; AVCodecContext *codec_ctx = NULL; AVFrame *frame = NULL; uint8_t *frame_data = NULL; int frame_size; int width = 640, height = 480; // 打开输出文件 if ((ret = avformat_alloc_output_context2(&fmt_ctx, NULL, NULL, "output.yuv")) < 0) { fprintf(stderr, "Error allocating output context: %s\n", av_err2str(ret)); return 1; } ofmt = fmt_ctx->oformat; // 添加视频流 video_st = avformat_new_stream(fmt_ctx, NULL); if (!video_st) { fprintf(stderr, "Error creating video stream\n"); return 1; } codec_ctx = video_st->codec; codec_ctx->codec_id = AV_CODEC_ID_RAWVIDEO; codec_ctx->codec_type = AVMEDIA_TYPE_VIDEO; codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P; codec_ctx->width = width; codec_ctx->height = height; codec_ctx->time_base = (AVRational){1, 25}; if ((ret = avcodec_parameters_to_context(codec_ctx, video_st->codecpar)) < 0) { fprintf(stderr, "Error copying codec parameters to context: %s\n", av_err2str(ret)); return 1; } // 打开视频编码器 if ((ret = avcodec_open2(codec_ctx, NULL, NULL)) < 0) { fprintf(stderr, "Error opening video encoder: %s\n", av_err2str(ret)); return 1; } // 创建帧缓冲区 frame = av_frame_alloc(); if (!frame) { fprintf(stderr, "Error allocating frame\n"); return 1; } frame->width = width; frame->height = height; frame->format = codec_ctx->pix_fmt; if ((ret = av_frame_get_buffer(frame, 0)) < 0) { fprintf(stderr, "Error allocating frame buffer: %s\n", av_err2str(ret)); return 1; } frame_data = frame->data[0]; frame_size = av_image_get_buffer_size(codec_ctx->pix_fmt, width, height, 1); // 打开输出文件 if (!(ofmt->flags & AVFMT_NOFILE)) { if ((ret = avio_open(&fmt_ctx->pb, "output.yuv", AVIO_FLAG_WRITE)) < 0) { fprintf(stderr, "Error opening output file: %s\n", av_err2str(ret)); return 1; } } // 写入视频帧 for (int i = 0; i < 25; i++) { // 生测试图像 for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int r = rand() % 256; int g = rand() % 256; int b = rand() % 256; uint8_t *yuv = frame_data + y * frame->linesize[0] + x * 3 / 2; yuv[0] = 0.299 * r + 0.587 * g + 0.114 * b; yuv[1] = -0.14713 * r - 0.28886 * g + 0.436 * b; yuv[2] = 0.615 * r - 0.51498 * g - 0.10001 * b; } } // 编码并写入帧 frame->pts = i; AVPacket pkt = {0}; av_init_packet(&pkt); pkt.data = NULL; pkt.size = 0; if ((ret = avcodec_send_frame(codec_ctx, frame)) < 0) { fprintf(stderr, "Error sending frame to encoder: %s\n", av_err2str(ret)); return 1; } while (ret >= 0) { ret = avcodec_receive_packet(codec_ctx, &pkt); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { break; } else if (ret < 0) { fprintf(stderr, "Error encoding frame: %s\n", av_err2str(ret)); return 1; } pkt.stream_index = video_st->index; av_write_frame(fmt_ctx, &pkt); av_packet_unref(&pkt); } } // 清理工作 av_write_trailer(fmt_ctx); if (codec_ctx) avcodec_close(codec_ctx); if (frame) av_frame_free(&frame); if (fmt_ctx && !(ofmt->flags & AVFMT_NOFILE)) avio_closep(&fmt_ctx->pb); avformat_free_context(fmt_ctx); return 0; } ``` 这段代码首先创建一个 YUV 格式的视频流,然后生一些随机数据作为测试图像,并将每帧图像编码 YUV 格式的数据,最终将所有帧数据写入到文件中。注意,这里使用了随机数据生测试图像,实际应用中需要根据实际情况生真实的图像数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值