美文网首页
音视频流媒体开发【十五】AVIO内存输⼊模式

音视频流媒体开发【十五】AVIO内存输⼊模式

作者: AlanGe | 来源:发表于2023-02-27 21:18 被阅读0次

音视频流媒体开发-目录

内存IO模式:avio_alloc_context()

/**
* Allocate and initialize an AVIOContext for buffered I/O. It must be later
* freed with avio_context_free().
*
* @param buffer Memory block for input/output operations via AVIOContext.
* The buffer must be allocated with av_malloc() and friends.
* It may be freed and replaced with a new buffer by libavformat.
* AVIOContext.buffer holds the buffer currently in use,
* which must be later freed with av_free().
* @param buffer_size The buffer size is very important for performance.
* For protocols with fixed blocksize it should be set to this blocksize.
* For others a typical size is a cache page, e.g. 4kb.
* @param write_flag Set to 1 if the buffer should be writable, 0 otherwise.
* @param opaque An opaque pointer to user-specific data.
* @param read_packet A function for refilling the buffer, may be NULL.
* For stream protocols, must never return 0 but rather
* a proper AVERROR code.
* @param write_packet A function for writing the buffer contents, may be NULL.
* The function may not change the input buffers content.
* @param seek A function for seeking to specified byte position, may be NULL.
*
* @return Allocated AVIOContext or NULL on failure.
*/
AVIOContext *avio_alloc_context(
    unsigned char *buffer,
    int buffer_size,
    int write_flag,
    void *opaque,
    int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),
    int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),
    int64_t (*seek)(void *opaque, int64_t offset, int whence)
);

opaque是 read_packet / write_packet 的第⼀个参数,指向⽤户数据。
buffer和buffer_size是 read_packet / write_packet 的第⼆个和第三个参数,是供FFmpeg使⽤的数据区。
buffer ⽤作FFmpeg输⼊时,由⽤户负责向 buffer 中填充数据,FFmpeg取⾛数据。
buffer ⽤作FFmpeg输出时,由FFmpeg负责向 buffer 中填充数据,⽤户取⾛数据。
write_flag是缓冲区读写标志,读写的主语是指FFmpeg。
write_flag 为1时, buffer ⽤于写,即作为FFmpeg输出。
write_flag 为0时, buffer ⽤于读,即作为FFmpeg输⼊。
read_packet和write_packet是函数指针,指向⽤户编写的回调函数。
seek也是函数指针,需要⽀持seek时使⽤。 可以类⽐fseek的机制。

案例:avio_decode_audio

.pro

TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += main.c
win32 {
INCLUDEPATH += $$PWD/ffmpeg-4.2.1-win32-dev/include
LIBS += $$PWD/ffmpeg-4.2.1-win32-dev/lib/avformat.lib   \
        $$PWD/ffmpeg-4.2.1-win32-dev/lib/avcodec.lib    \
        $$PWD/ffmpeg-4.2.1-win32-dev/lib/avdevice.lib   \
        $$PWD/ffmpeg-4.2.1-win32-dev/lib/avfilter.lib   \
        $$PWD/ffmpeg-4.2.1-win32-dev/lib/avutil.lib     \
        $$PWD/ffmpeg-4.2.1-win32-dev/lib/postproc.lib   \
        $$PWD/ffmpeg-4.2.1-win32-dev/lib/swresample.lib \
        $$PWD/ffmpeg-4.2.1-win32-dev/lib/swscale.lib
}
main.c

/**
* @projectName   07-05-decode_audio
* @brief         解码音频,主要的测试格式aac和mp3
* @author        Liao Qingfu
* @date          2020-01-16
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <libavutil/frame.h>
#include <libavutil/mem.h>

#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>

#define BUF_SIZE 20480


static char* av_get_err(int errnum)
{
    static char err_buf[128] = {0};
    av_strerror(errnum, err_buf, 128);
    return err_buf;
}

static void print_sample_format(const AVFrame *frame)
{
    printf("ar-samplerate: %uHz\n", frame->sample_rate);
    printf("ac-channel: %u\n", frame->channels);
    printf("f-format: %u\n", frame->format);// 格式需要注意,实际存储到本地文件时已经改成交错模式
}

static int read_packet(void *opaque, uint8_t *buf, int buf_size)
{
    FILE *in_file = (FILE *)opaque;
    int read_size = fread(buf, 1, buf_size, in_file);
    printf("read_packet read_size:%d, buf_size:%d\n", read_size, buf_size);
    if(read_size <=0) {
        return AVERROR_EOF;     // 数据读取完毕
    }
    return read_size;
}

static void decode(AVCodecContext *dec_ctx, AVPacket *packet, AVFrame *frame,
                   FILE *outfile)
{
    int ret = 0;
    ret = avcodec_send_packet(dec_ctx, packet);
    if(ret == AVERROR(EAGAIN)) {
        printf("Receive_frame and send_packet both returned EAGAIN, which is an API violation.\n");
    } else if(ret < 0) {
        printf("Error submitting the packet to the decoder, err:%s\n",
               av_get_err(ret));
        return;
    }

    while (ret >= 0) {
        ret = avcodec_receive_frame(dec_ctx, frame);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
            return;
        } else if (ret < 0)  {
            printf("Error during decoding\n");
            exit(1);
        }
        if(!packet) {
            printf("get flush frame\n");
        }
        int data_size = av_get_bytes_per_sample(dec_ctx->sample_fmt);
        //        print_sample_format(frame);
        /**
           P表示Planar(平面),其数据格式排列方式为 :
           LLLLLLRRRRRRLLLLLLRRRRRRLLLLLLRRRRRRL...(每个LLLLLLRRRRRR为一个音频帧)
           而不带P的数据格式(即交错排列)排列方式为:
           LRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRL...(每个LR为一个音频样本)
        播放范例:   ffplay -ar 48000 -ac 2 -f f32le believe.pcm
            并不是每一种都是这样的格式
        */
        // 这里的写法不是通用,通用要调用重采样的函数去实现
        // 这里只是针对解码出来是planar格式的转换
        for(int i = 0; i < frame->nb_samples; i++) {
            for(int ch = 0; ch < dec_ctx->channels; ch++) {
                fwrite(frame->data[ch] + data_size *i, 1, data_size, outfile);
            }
        }
    }
}

int main(int argc, char **argv)
{
    if(argc != 3) {
        printf("usage: %s <intput file> <out file>\n", argv[0]);
        return -1;
    }
    const char *in_file_name = argv[1];
    const char *out_file_name = argv[2];
    FILE *in_file = NULL;
    FILE *out_file = NULL;

    // 1. 打开参数文件
    in_file = fopen(in_file_name, "rb");
    if(!in_file) {
        printf("open file %s failed\n", in_file_name);
        return  -1;
    }
    out_file = fopen(out_file_name, "wb");
    if(!out_file) {
        printf("open file %s failed\n", out_file_name);
        return  -1;
    }

    // 2自定义 io
    uint8_t *io_buffer = av_malloc(BUF_SIZE);
    AVIOContext *avio_ctx = avio_alloc_context(io_buffer, BUF_SIZE, 0, (void *)in_file,    \
                                               read_packet, NULL, NULL);
    AVFormatContext *format_ctx = avformat_alloc_context();
    format_ctx->pb = avio_ctx;
    int ret = avformat_open_input(&format_ctx, NULL, NULL, NULL);
    if(ret < 0) {
        printf("avformat_open_input failed:%s\n", av_err2str(ret));
        return -1;
    }

    // 编码器查找
    AVCodec *codec = avcodec_find_decoder(AV_CODEC_ID_AAC);
    if(!codec) {
        printf("avcodec_find_decoder failed\n");
        return -1;
    }

    AVCodecContext *codec_ctx = avcodec_alloc_context3(codec);
    if(!codec_ctx) {
        printf("avcodec_alloc_context3 failed\n");
        return -1;
    }
    ret = avcodec_open2(codec_ctx, codec, NULL);
    if(ret < 0) {
        printf("avcodec_open2 failed:%s\n", av_err2str(ret));
        return -1;
    }

    AVPacket *packet = av_packet_alloc();
    AVFrame *frame = av_frame_alloc();

    while (1) {
        ret = av_read_frame(format_ctx, packet);
        if(ret < 0) {
            printf("av_read_frame failed:%s\n", av_err2str(ret));
            break;
        }
        decode(codec_ctx, packet, frame, out_file);
    }

    printf("read file finish\n");
    decode(codec_ctx, NULL, frame, out_file);

    fclose(in_file);
    fclose(out_file);

    av_free(io_buffer);
    av_frame_free(frame);
    av_packet_free(packet);

    avformat_close_input(&format_ctx);
    avcodec_free_context(&codec_ctx);

    printf("main finish\n");

    return 0;
}

believe.aac believe.pcm

cd E:\Ovoice\av_media\online\07-ffmpeg-decode\build-07-09-avio_decode_audio-Desktop_Qt_5_10_1_MinGW_32bit-Debug
ffplay -ar 48000 -ac 2 -f f32le believe.pcm

相关文章

网友评论

      本文标题:音视频流媒体开发【十五】AVIO内存输⼊模式

      本文链接:https://www.haomeiwen.com/subject/vgwcldtx.html