解码mp4文件分别存储为pcm,yuv文件

简介: 使用FFmpeg库在C++中解码MP4文件,并将音频数据存储为PCM格式,视频数据存储为YUV格式。
// 解码分别写入对应文件
#include "myLog.h"
#include <iostream>

extern "C"
{
#include <libavformat\avformat.h>
#include <libavutil\avutil.h>
#include <libavcodec\avcodec.h>
#include <libavutil\imgutils.h>
#include <libavutil\samplefmt.h>
}
#pragma comment(lib, "avformat.lib")
#pragma comment(lib, "avcodec.lib")

class Decoder
{
public:
    Decoder(std::string src_filename, std::string dst_audio_filename, std::string dst_video_filename);
    ~Decoder();

    // 解封装
    int demuxer();

    // 解码
    int decodec();

    // 打印音视频播放格式
    void print_audio_play_str();
private:
    // 打开解码器
    int open_decodec();

    // 解码pkt
    int decode_pkt(AVCodecContext* codec_ctx, AVPacket* pkt);

    // 输出视频帧
    int output_video_frame(AVFrame* frame);

    // 输出音频帧
    int output_audio_frame(AVFrame* frame);

    // 获取音频格式
    int get_format_from_sample_fmt(std::string& fmtStr, enum AVSampleFormat sample_fmt);
private:
    AVFormatContext* ifmt_ctx_;                    // 格式上下文
    AVCodecContext*  video_decode_ctx_;            // 视频解码器上下文
    AVCodecContext*  audio_decode_ctx_;            // 音频解码器上下文

    int video_idx_;                                // 视频索引                        
    AVStream* video_stream_;                    // 视频流

    int audio_idx_;                                // 音频索引
    AVStream* audio_stream_;                    // 音频流

    std::string src_filename_;                    // 输入文件路径
    std::string dst_audio_filename_;            // 输出音频pcm文件路径
    std::string dst_video_filename_;            // 输出视频yuv路径                            
    FILE* dst_video_fp_;
    FILE* dst_audio_fp_;

    AVFrame* frame_;
    uint8_t* video_dst_data_[4];                // 记录video一行数据
    int video_dst_buf_size_;                    // 分配的真实buf大小 
    int linesize_[4];                            // 每行数据大小(YUV RGB 第四个为保留字段)
};

Decoder::Decoder(std::string src_filename, std::string dst_audio_filename, std::string dst_video_filename)
: ifmt_ctx_(nullptr)
, video_decode_ctx_(nullptr)
, audio_decode_ctx_(nullptr)
, video_stream_(nullptr)
, audio_stream_(nullptr)
, dst_video_fp_(nullptr)
, dst_audio_fp_(nullptr)
, frame_(nullptr)
, src_filename_(src_filename)
, dst_audio_filename_(dst_audio_filename)
, dst_video_filename_(dst_video_filename)
{
    for (int i = 0; i < 4; i++)
    {
        video_dst_data_[i] = NULL;
    }
}

Decoder::~Decoder()
{
    // 释放相关资源
    if (ifmt_ctx_)
    {
        avformat_close_input(&ifmt_ctx_);
    }
    if (audio_decode_ctx_)
    {
        avcodec_free_context(&audio_decode_ctx_);
    }
    if (video_decode_ctx_)
    {
        avcodec_free_context(&video_decode_ctx_);
    }
    if (dst_audio_fp_)
    {
        fclose(dst_audio_fp_);
    }    
    if (dst_video_fp_)
    {
        fclose(dst_video_fp_);
    }
    if (frame_)
    {
        av_frame_free(&frame_);
    }
    if (video_dst_data_)
    {
        av_free(video_dst_data_[0]);    // 释放数据指针(其它三个指针无需释放) data[0]指向缓冲区开始位置,data[1] - data[3]也是指向data[0]的数据指针
    }
}

int Decoder::demuxer()
{
    // 1. 打开文件
    int nRet = avformat_open_input(&ifmt_ctx_, src_filename_.c_str(), NULL, NULL);
    if (nRet < 0)
    {
        LOG_WARNING("avformat_open_input error\n");
        return -1;
    }

    // 2. 查找流信息
    nRet = avformat_find_stream_info(ifmt_ctx_, NULL);
    if (nRet < 0)
    {
        avformat_close_input(&ifmt_ctx_);
        LOG_WARNING("avformat_find_stream_info error\n");
        return -2;
    }

    // 3. 获取音视频流索引
    audio_idx_ = av_find_best_stream(ifmt_ctx_, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
    video_idx_ = av_find_best_stream(ifmt_ctx_, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);

    return 0;
}

int Decoder::open_decodec()
{
    // 打开音频解码器
    if (audio_idx_ >= 0)
    {
        audio_stream_ = ifmt_ctx_->streams[audio_idx_];
        // 查找解码器
        AVCodec* audio_decodec = avcodec_find_decoder(audio_stream_->codecpar->codec_id);
        if (!audio_decodec)
        {
            LOG_WARNING("avcodec_find_decoder error\n");
            return AVERROR(ENOMEM);
        }

        // 给解码上下文分配内存
        audio_decode_ctx_ = avcodec_alloc_context3(audio_decodec);
        if (!audio_decode_ctx_)
        {
            LOG_WARNING("avcodec_alloc_context3 error\n");
            return AVERROR(ENOMEM);
        }

        // 拷贝解码参数到解码上下文
        int nRet = avcodec_parameters_to_context(audio_decode_ctx_, audio_stream_->codecpar);
        if (nRet < 0)
        {
            LOG_WARNING("avcodec_parameters_to_context error\n");
            return -1;
        }
        // 打开解码器
        nRet = avcodec_open2(audio_decode_ctx_, audio_decodec, NULL);
        if (nRet < 0)
        {
            LOG_WARNING("avcodec_open2 error\n");
            return -2;
        }

        dst_audio_fp_ = fopen(dst_audio_filename_.c_str(), "wb");
        if (!dst_audio_fp_)
        {
            LOG_WARNING("fopen dst_audio_filename_ error\n");
            return -1;
        }
    }

    // 打开视频解码器
    if (video_idx_ >= 0)
    {
        video_stream_ = ifmt_ctx_->streams[video_idx_];
        // 查找解码器
        AVCodec* video_decodec = avcodec_find_decoder(video_stream_->codecpar->codec_id);
        if (!video_decodec)
        {
            LOG_WARNING("avcodec_find_decoder error\n");
            return AVERROR(ENOMEM);
        }

        // 给解码上下文分配内存
        video_decode_ctx_ = avcodec_alloc_context3(video_decodec);
        if (!video_decode_ctx_)
        {
            LOG_WARNING("avcodec_alloc_context3 error\n");
            return AVERROR(ENOMEM);
        }

        // 拷贝解码参数到解码上下文
        int nRet = avcodec_parameters_to_context(video_decode_ctx_, video_stream_->codecpar);
        if (nRet < 0)
        {
            LOG_WARNING("avcodec_parameters_to_context error\n");
            return -1;
        }
        // 打开解码器
        nRet = avcodec_open2(video_decode_ctx_,video_decodec, NULL);
        if (nRet < 0)
        {
            LOG_WARNING("avcodec_open2 error\n");
            return -2;
        }

        video_dst_buf_size_ = av_image_alloc(video_dst_data_, linesize_,
            video_decode_ctx_->width, video_decode_ctx_->height, video_decode_ctx_->pix_fmt, 1);

        dst_video_fp_ = fopen(dst_video_filename_.c_str(), "wb");
        if (!dst_video_fp_)
        {
            LOG_WARNING("fopen dst_video_filename_ error\n");
            return -1;
        }
    }
}

int Decoder::decodec()
{
    // 打开解码器
    int nRet = open_decodec();
    if (nRet < 0)
    {
        LOG_WARNING("open_decodec error\n");
        return -666;
    }

    AVPacket* pkt = av_packet_alloc();
    av_init_packet(pkt);
    pkt->data = NULL;
    pkt->size = 0;

    while (av_read_frame(ifmt_ctx_, pkt) >= 0)
    {
        if (pkt->stream_index == audio_idx_)    // 音频包
        {
            nRet = decode_pkt(audio_decode_ctx_, pkt);
        }
        else if (pkt->stream_index == video_idx_) // 视频包
        {
            nRet = decode_pkt(video_decode_ctx_, pkt);
        }
        av_packet_unref(pkt);
        if (nRet < 0)
        {
            break;
        }
    }

    // 冲刷解码器
    if (video_decode_ctx_)
    {
        decode_pkt(video_decode_ctx_, NULL);
    }
    if (audio_decode_ctx_)
    {
        decode_pkt(video_decode_ctx_, NULL);
    }
    return 0;
}

int Decoder::decode_pkt(AVCodecContext* codec_ctx, AVPacket* pkt)
{
    int nRet = avcodec_send_packet(codec_ctx, pkt);
    if (nRet < 0)
    {
        LOG_WARNING("avcodec_send_packet fflush codec\n");
        return -1;
    }

    // 一个包可能对应多个frame
    frame_ = av_frame_alloc();
    while (nRet >= 0)
    {
        nRet = avcodec_receive_frame(codec_ctx, frame_);
        if (nRet < 0)
        {
            if (nRet == AVERROR_EOF || nRet == AVERROR(EAGAIN))
                return 0;
            return nRet;
        }
        // 写数据
        if (codec_ctx->codec->type == AVMEDIA_TYPE_AUDIO)
        {
            nRet = output_audio_frame(frame_);
        }
        else if (codec_ctx->codec->type == AVMEDIA_TYPE_VIDEO)
        {
            nRet = output_video_frame(frame_);
        }
        av_frame_unref(frame_);
        if (nRet < 0)
            return nRet;
    }
}

int Decoder::output_video_frame(AVFrame* frame)
{
    if (video_dst_buf_size_ < 0)
    {
        LOG_WARNING("av_image_alloc error\n");
        return -2;
    }
    // 写入帧到文件
    if (frame->width != video_decode_ctx_->width ||
        frame->height != video_decode_ctx_->height ||
        frame->format != video_decode_ctx_->pix_fmt)
    {
        LOG_WARNING("frame and video_decode_ctx_ error\n");
        return -3;
    }
    // 填充数据到 video_dst_data
    av_image_copy(video_dst_data_, linesize_,
        (const uint8_t**)(frame->data), frame->linesize,
        video_decode_ctx_->pix_fmt, video_decode_ctx_->width, video_decode_ctx_->height);
    size_t write_video_size = fwrite(video_dst_data_[0], 1, video_dst_buf_size_, dst_video_fp_);
    fflush(dst_video_fp_);
    return 0;
}

int Decoder::output_audio_frame(AVFrame* frame)
{
    // 计算一帧音频数据的bytes
    size_t a_sample_point_bytes = frame->nb_samples * av_get_bytes_per_sample((AVSampleFormat)frame->format);
    // 写入数据到文件
    fwrite(frame->extended_data[0], 1, a_sample_point_bytes, dst_audio_fp_);
    fflush(dst_audio_fp_);
    return 0;
}

int Decoder::get_format_from_sample_fmt(std::string& fmtStr, enum AVSampleFormat sample_fmt)
{
    struct sample_fmt_entry {
        enum AVSampleFormat sample_fmt; 
        std::string fmt_be;
        std::string fmt_le;
    } sample_fmt_entries[] = {
        { AV_SAMPLE_FMT_U8, "u8", "u8" },
        { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
        { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
        { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
        { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
    };

    for (int i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
        struct sample_fmt_entry *entry = &sample_fmt_entries[i];
        if (sample_fmt == entry->sample_fmt) {
            fmtStr = AV_NE(entry->fmt_be, entry->fmt_le);
            return 0;
        }
    }

    fprintf(stderr, "sample format %s is not supported as output format\n", av_get_sample_fmt_name(sample_fmt));
    return -1;
}

void Decoder::print_audio_play_str()
{
    if (audio_stream_) {
        enum AVSampleFormat sfmt = audio_decode_ctx_->sample_fmt;
        int n_channels = audio_decode_ctx_->channels;
        std::string fmtStr;

        if (av_sample_fmt_is_planar(sfmt))    // 是planar格式
        {
            const char *packed = av_get_sample_fmt_name(sfmt);
            LOG_INFO("Warning: the sample format the decoder produced is planar "
                "(%s). This example will output the first channel only.\n",
                packed ? packed : "?");
            sfmt = av_get_packed_sample_fmt(sfmt);
            n_channels = 1;
        }

        int ret = -1;
        if ((ret = get_format_from_sample_fmt(fmtStr, sfmt)) < 0)
            return;

        LOG_INFO("Play the output audio file with the command:\n"
            "ffplay -f %s -ac %d -ar %d %s\n",
            fmtStr.c_str(), n_channels, audio_decode_ctx_->sample_rate,
            dst_audio_filename_.c_str());

        LOG_INFO("play video yuv:\nffplay -video_size %dx%d -f rawvideo -pixel_format yuv420p %s",
            video_decode_ctx_->width, video_decode_ctx_->height, dst_video_filename_.c_str());
    }
}

int main()
{
    std::string src_filename = "./MediaFile/HTA_13s.mp4";    // input_5s
    std::string dst_audio_filename = "./MediaFile/HTA_13s_decodec_audio.pcm"; // HTA_13s_decodec_audio
    std::string dst_video_filename = "./MediaFile/HTA_13s_decodec_video.yuv"; // HTA_13s_decodec_video

    Decoder decoder(src_filename, dst_audio_filename, dst_video_filename);
    // 解复用
    int nRet = decoder.demuxer();
    if (nRet < 0)
    {
        LOG_WARNING("main demuxer error\n");
        return -666;
    }
    // 解码写入到文件
    nRet = decoder.decodec();
    if (nRet < 0)
    {
        LOG_WARNING("main decodec error\n");
        return -777;
    }

    LOG_INFO("decode finish, write file success\n");
    decoder.print_audio_play_str();

    getchar();
    return 0;
}

注意:使用av_image_alloc为一个char* data[4]的数组分配内存时,其内部只是为data[0]分配内存,其余的data[1] - data[3]指针指向data[0]的某个位置(根据像素格式的不同)

相关文章
|
消息中间件 Java Shell
在CentOS7上安装RocketMQ 4.8.0
本文是博主在CentOS7上安装RocketMQ 4.8.0的记录,希望对大家有所帮助。
1444 0
|
编解码 监控 C++
C++音视频编程探秘
C++音视频编程探秘
1043 1
|
11月前
|
人工智能 自然语言处理 知识图谱
实战指南:基于【两大核心+四轮驱动】理论,制定高效Geo优化策略
随着生成式AI重塑信息获取方式,传统SEO正升级为GEO(生成式引擎优化)。本文解读于磊老师首创的【两大核心+四轮驱动】GEO理论,融合E-E-A-T原则,提出以人性化内容与权威性建设为核心,通过结构化数据、多模态覆盖、意图优化与持续监测,构建AI时代高效获客的内容战略。
900 1
|
机器学习/深度学习 算法 安全
【光伏功率预测】基于EMD-PCA-LSTM的光伏功率预测模型(Matlab代码实现)
【光伏功率预测】基于EMD-PCA-LSTM的光伏功率预测模型(Matlab代码实现)
535 1
|
XML 存储 前端开发
免费在线图片转Base64编码工具
利用图片转 Base64 编码工具(支持 PNG, GIF, JPEG 等格式)。操作极其简单:将目标图片拖拽至工具指定区域,即可自动完成转换并获得编码结果。
3476 3
|
人工智能 数据可视化 测试技术
UAT测试排程工具深度解析:让验收测试不再失控,项目稳稳上线
在系统交付节奏加快的背景下,“测试节奏混乱”已成为项目延期的主因之一。UAT测试排程工具应运而生,帮助团队结构化拆解任务、清晰分配责任、实时掌控进度,打通需求、测试、开发三方协作闭环,提升测试效率与质量。本文还盘点了2025年热门UAT工具,助力团队选型落地,告别靠表格和群聊推进测试的低效方式,实现有节奏、有章法的测试管理。
|
并行计算 Linux TensorFlow
TensorFlow各个GPU版本CUDA和cuDNN对应版本
TensorFlow各个GPU版本CUDA和cuDNN对应版本
TensorFlow各个GPU版本CUDA和cuDNN对应版本
|
安全 前端开发 JavaScript
跨域iframe通信
跨域iframe通信
877 2
|
Web App开发 编解码 监控
直播协议
【10月更文挑战第26天】不同的直播协议具有不同的特点和应用场景。在选择直播协议时,需要根据直播的需求、目标受众、网络环境等因素进行综合考虑,以选择最适合的直播协议,确保直播的流畅性、稳定性和高质量。
|
监控 安全 数据安全/隐私保护
什么是OTA升级模式?
【7月更文挑战第20天】什么是OTA升级模式?
7359 8