• FFMPEG音视频解码


    文章转自:https://www.cnblogs.com/CoderTian/p/6791638.html

    1.播放多媒体文件步骤

    通常情况下,我们下载的视频文件如MP4,MKV、FLV等都属于封装格式,就是把音视频数据按照相应的规范,打包成一个文本文件。我们可以使用MediaInfo这个工具查看媒体文件的相关信息。

    所以当我们播放一个媒体文件时,通常需要经过以下几个步骤

    ①解封装(Demuxing):就是将输入的封装格式的数据,分离成为音频流压缩编码数据和视频流压缩编码数据。封装格式种类很多,例如MP4,MKV,RMVB,TS,FLV,AVI等等,它的作用就是将已经压缩编码的视频数据和音频数据按照一定的格式放到一起。例如,FLV格式的数据,经过解封装操作后,输出H.264编码的视频码流和AAC编码的音频码流。

    ②解码(Decode):就是将视频/音频压缩编码数据,解码成为非压缩的视频/音频原始数据。音频的压缩编码标准包含AAC,MP3等,视频的压缩编码标准则包含H.264,MPEG2等。解码是整个系统中最重要也是最复杂的一个环节。通过解码,压缩编码的视频数据输出成为非压缩的颜色数据,例如YUV、RGB等等;压缩编码的音频数据输出成为非压缩的音频抽样数据,例如PCM数据。

    ③音视频同步:就是根据解封装模块处理过程中获取到的参数信息,同步解码出来的音频和视频数据,并将音视频频数据送至系统的显卡和声卡播放出来(Render)。

    2.FFMPEG音视频解码

    通过上面对媒体文件播放步骤的了解,我们在解码多媒体文件的时候需要经过两个步骤,即解封装(Demuxing)和解码(Decode)。下面就来看一下FFMPEG解码媒体文件的时候是怎样做这两个步骤的。

    在使用FFMPEG解码媒体文件之前,我们首先需要注册FFMPEG的各种组件,通过

    av_register_all();
    这个函数,可以注册所有支持的容器和对应的codec。之后我们通过
    AVFormatContext *pFormatCtx = avformat_alloc_context();
    avformat_open_input(&pFormatCtx,input_cstr,NULL,NULL);
    avformat_find_stream_info(pFormatCtx,NULL);

    来打开一个媒体文件,并获得媒体文件封装格式的上下文。之后我们就可以通过遍历定义在libavformat/avformat.h里保存着媒体文件中封装的流数量的nb_streams在媒体文件中分离出音视频流。

    分离出音视频流之后,就可以对音视频流分别进行解码了,这里先以视频解码为例,我们可以遍历AVStream找到codec_type为AVMEDIA_TYPE_VIDEO的的AVStream即为视频流的索引值。

    复制代码
    //视频解码,需要找到视频对应的AVStream所在pFormatCtx->streams的索引位置
        int video_stream_idx = -1;
        int i = 0;
        for(; i < pFormatCtx->nb_streams;i++){
            //根据类型判断,是否是视频流
            if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO){
                video_stream_idx = i;
                break;
            }
        }
    复制代码

    然后我们就可以通过AVStream来找到对应的AVCodecContext即编解码器的上下文。之后就可以通过这个上下文,使用

    avcodec_find_decoder()

    来找到对应的解码器,再通过

    avcodec_open2()

    来打开解码器,AVFormatContext、AVStream、AVCodecContext、AVCodec四者之间的关系为

    打开解码器之后,就可以循环的将一帧待解码的数据AVPacket送给

    avcodec_decode_video2()

    进行解码,解码之后的数据存放在AVFrame里面。

    3.示例代码

    3.1.视频解码

    复制代码
    #include <stdio.h>
    #include <stdlib.h>
    //编码
    #include "libavcodec/avcodec.h"
    //封装格式处理
    #include "libavformat/avformat.h"
    //像素处理
    #include "libswscale/swscale.h"
    
    int main()
    {
        //获取输入输出文件名
        const char *input = "test.mp4";
        const char *output = "test.yuv";
    
        //1.注册所有组件
        av_register_all();
    
        //封装格式上下文,统领全局的结构体,保存了视频文件封装格式的相关信息
        AVFormatContext *pFormatCtx = avformat_alloc_context();
    
        //2.打开输入视频文件
        if (avformat_open_input(&pFormatCtx, input, NULL, NULL) != 0)
        {
            printf("%s","无法打开输入视频文件");
            return;
        }
    
        //3.获取视频文件信息
        if (avformat_find_stream_info(pFormatCtx,NULL) < 0)
        {
            printf("%s","无法获取视频文件信息");
            return;
        }
    
        //获取视频流的索引位置
        //遍历所有类型的流(音频流、视频流、字幕流),找到视频流
        int v_stream_idx = -1;
        int i = 0;
        //number of streams
        for (; i < pFormatCtx->nb_streams; i++)
        {
            //流的类型
            if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
            {
                v_stream_idx = i;
                break;
            }
        }
    
        if (v_stream_idx == -1)
        {
            printf("%s","找不到视频流
    ");
            return;
        }
    
        //只有知道视频的编码方式,才能够根据编码方式去找到解码器
        //获取视频流中的编解码上下文
        AVCodecContext *pCodecCtx = pFormatCtx->streams[v_stream_idx]->codec;
        //4.根据编解码上下文中的编码id查找对应的解码
        AVCodec *pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
        if (pCodec == NULL)
        {
            printf("%s","找不到解码器
    ");
            return;
        }
    
        //5.打开解码器
        if (avcodec_open2(pCodecCtx,pCodec,NULL)<0)
        {
            printf("%s","解码器无法打开
    ");
            return;
        }
    
        //输出视频信息
        printf("视频的文件格式:%s",pFormatCtx->iformat->name);
        printf("视频时长:%d", (pFormatCtx->duration)/1000000);
        printf("视频的宽高:%d,%d",pCodecCtx->width,pCodecCtx->height);
        printf("解码器的名称:%s",pCodec->name);
    
        //准备读取
        //AVPacket用于存储一帧一帧的压缩数据(H264)
        //缓冲区,开辟空间
        AVPacket *packet = (AVPacket*)av_malloc(sizeof(AVPacket));
    
        //AVFrame用于存储解码后的像素数据(YUV)
        //内存分配
        AVFrame *pFrame = av_frame_alloc();
        //YUV420
        AVFrame *pFrameYUV = av_frame_alloc();
        //只有指定了AVFrame的像素格式、画面大小才能真正分配内存
        //缓冲区分配内存
        uint8_t *out_buffer = (uint8_t *)av_malloc(avpicture_get_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));
        //初始化缓冲区
        avpicture_fill((AVPicture *)pFrameYUV, out_buffer, AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);
    
        //用于转码(缩放)的参数,转之前的宽高,转之后的宽高,格式等
        struct SwsContext *sws_ctx = sws_getContext(pCodecCtx->width,pCodecCtx->height,pCodecCtx->pix_fmt,
                                                    pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_YUV420P,
                                                    SWS_BICUBIC, NULL, NULL, NULL);
        int got_picture, ret;
    
        FILE *fp_yuv = fopen(output, "wb+");
    
        int frame_count = 0;
    
        //6.一帧一帧的读取压缩数据
        while (av_read_frame(pFormatCtx, packet) >= 0)
        {
            //只要视频压缩数据(根据流的索引位置判断)
            if (packet->stream_index == v_stream_idx)
            {
                //7.解码一帧视频压缩数据,得到视频像素数据
                ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
                if (ret < 0)
                {
                    printf("%s","解码错误");
                    return;
                }
    
                //为0说明解码完成,非0正在解码
                if (got_picture)
                {
                    //AVFrame转为像素格式YUV420,宽高
                    //2 6输入、输出数据
                    //3 7输入、输出画面一行的数据的大小 AVFrame 转换是一行一行转换的
                    //4 输入数据第一列要转码的位置 从0开始
                    //5 输入画面的高度
                    sws_scale(sws_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height,
                              pFrameYUV->data, pFrameYUV->linesize);
    
                    //输出到YUV文件
                    //AVFrame像素帧写入文件
                    //data解码后的图像像素数据(音频采样数据)
                    //Y 亮度 UV 色度(压缩了) 人对亮度更加敏感
                    //U V 个数是Y的1/4
                    int y_size = pCodecCtx->width * pCodecCtx->height;
                    fwrite(pFrameYUV->data[0], 1, y_size, fp_yuv);
                    fwrite(pFrameYUV->data[1], 1, y_size / 4, fp_yuv);
                    fwrite(pFrameYUV->data[2], 1, y_size / 4, fp_yuv);
    
                    frame_count++;
                    printf("解码第%d帧
    ",frame_count);
                }
            }
    
            //释放资源
            av_free_packet(packet);
        }
    
        fclose(fp_yuv);
    
        av_frame_free(&pFrame);
    
        avcodec_close(pCodecCtx);
    
        avformat_free_context(pFormatCtx);
    
    }
    复制代码

    3.2.音频解码

    复制代码
    #include <stdlib.h>
    #include <stdio.h>
    #include <unistd.h>
    
    //封装格式
    #include "libavformat/avformat.h"
    //解码
    #include "libavcodec/avcodec.h"
    //缩放
    #include "libswscale/swscale.h"
    #include "libswresample/swresample.h"
    
    int main (void)
    {
    
        //1.注册组件
        av_register_all();
        //封装格式上下文
        AVFormatContext *pFormatCtx = avformat_alloc_context();
    
        //2.打开输入音频文件
        if (avformat_open_input(&pFormatCtx, "test.mp3", NULL, NULL) != 0) {
            printf("%s", "打开输入音频文件失败");
            return;
        }
        //3.获取音频信息
        if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
            printf("%s", "获取音频信息失败");
            return;
        }
    
        //音频解码,需要找到对应的AVStream所在的pFormatCtx->streams的索引位置
        int audio_stream_idx = -1;
        int i = 0;
        for (; i < pFormatCtx->nb_streams; i++) {
            //根据类型判断是否是音频流
            if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
                audio_stream_idx = i;
                break;
            }
        }
        //4.获取解码器
        //根据索引拿到对应的流,根据流拿到解码器上下文
        AVCodecContext *pCodeCtx = pFormatCtx->streams[audio_stream_idx]->codec;
        //再根据上下文拿到编解码id,通过该id拿到解码器
        AVCodec *pCodec = avcodec_find_decoder(pCodeCtx->codec_id);
        if (pCodec == NULL) {
            printf("%s", "无法解码");
            return;
        }
        //5.打开解码器
        if (avcodec_open2(pCodeCtx, pCodec, NULL) < 0) {
            printf("%s", "编码器无法打开");
            return;
        }
        //编码数据
        AVPacket *packet = av_malloc(sizeof(AVPacket));
        //解压缩数据
        AVFrame *frame = av_frame_alloc();
        
        //frame->16bit 44100 PCM 统一音频采样格式与采样率
        SwrContext *swrCtx = swr_alloc();
        //重采样设置选项-----------------------------------------------------------start
        //输入的采样格式
        enum AVSampleFormat in_sample_fmt = pCodeCtx->sample_fmt;
        //输出的采样格式 16bit PCM
        enum AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;
        //输入的采样率
        int in_sample_rate = pCodeCtx->sample_rate;
        //输出的采样率
        int out_sample_rate = 44100;
        //输入的声道布局
        uint64_t in_ch_layout = pCodeCtx->channel_layout;
        //输出的声道布局
        uint64_t out_ch_layout = AV_CH_LAYOUT_MONO;
    
        swr_alloc_set_opts(swrCtx, out_ch_layout, out_sample_fmt, out_sample_rate, in_ch_layout, in_sample_fmt,
                in_sample_rate, 0, NULL);
        swr_init(swrCtx);
        //重采样设置选项-----------------------------------------------------------end
        //获取输出的声道个数
        int out_channel_nb = av_get_channel_layout_nb_channels(out_ch_layout);
        //存储pcm数据
        uint8_t *out_buffer = (uint8_t *) av_malloc(2 * 44100);
        FILE *fp_pcm = fopen("out.pcm", "wb");
        int ret, got_frame, framecount = 0;
        //6.一帧一帧读取压缩的音频数据AVPacket
        while (av_read_frame(pFormatCtx, packet) >= 0) {
            if (packet->stream_index == audio_stream_idx) {
                //解码AVPacket->AVFrame
                ret = avcodec_decode_audio4(pCodeCtx, frame, &got_frame, packet);
                if (ret < 0) {
                    printf("%s", "解码完成");
                }
                //非0,正在解码
                if (got_frame) {
                    printf("解码%d帧", framecount++);
                    swr_convert(swrCtx, &out_buffer, 2 * 44100, frame->data, frame->nb_samples);
                    //获取sample的size
                    int out_buffer_size = av_samples_get_buffer_size(NULL, out_channel_nb, frame->nb_samples,
                            out_sample_fmt, 1);
                    //写入文件进行测试
                    fwrite(out_buffer, 1, out_buffer_size, fp_pcm);
                }
            }
            av_free_packet(packet);
        }
        fclose(fp_pcm);
        av_frame_free(&frame);
        av_free(out_buffer);
        swr_free(&swrCtx);
        avcodec_close(pCodeCtx);
        avformat_close_input(&pFormatCtx);
        return 0;
    }
    复制代码
  • 相关阅读:
    一些正则表达式
    iOS汉字中提取首字母
    flutter 按钮弹簧动画AnimationController
    In iOS 14+,debug mode Flutter apps can only be launched from Flutter tooling,IDEs with Flutter plugins or from Xcode.
    Failed to connect to raw.githubusercontent.com port 443: Connection refused
    iOS组件库创建(二)
    iOS组件库创建(一)
    同个电脑多个ssh key的配置
    网络相关总结
    flutter 热更新实现方案—UI资源化(二)
  • 原文地址:https://www.cnblogs.com/boonya/p/8571849.html
Copyright © 2020-2023  润新知