ffmpeg_transcode_aac.c修改为流式的输入和输出

启发:https://zhuanlan.zhihu.com/p/439000616
前言:在后台开发过程中,需求是转码前后的文件,不保存,直接写入到缓存中,可以直接、方便的插入到后台开发过程,接受上个模块的输入,以及提供给下一个模块使用。
名词解释

  • AVFormatContext: 存储音频数据的容器类;
  • AVCodecContext: 存储编码使用参数,列举重要参数:codec_type, bit_rate, sample_rate, channels, 等等;
  • AVCodec: 存储编解码器信息的结构体,列举重要参数:name, long_name, id(codecid),channel_layouts等等;
  • AVIOContext: 管理输入输出数据的结构体,列举重要参数:buffer, buffer_size, buf_ptr, buf_end, opaque;
  • AVPacket: 存储压缩编解码数据相关信息的结构体,列举重要参数:data, size, pts, dts, stream_index等等;
  • AVStream: 存储每个音频/视频信息的结构体,列举重要参数: index, codec, duration, time_base等等;
  • AVFrame: 码流参数较多的结构体,一般存储原始数据(非压缩数据)
  • AVAudioFifo: 缓冲区,以音频采样为基本单位的先进先出队列
  • codec: 编解码算法,主要分为有损和无损
  • container: 容器格式,即音频流,特定格式的文件中的协议
  • transcoding: 转码功能,将一种音频的编码方式转为另外的一种编码方式
    流程如下:
    输入的是音频流,例如wav、MP3等等,输出为指定格式AAC编码的音频流,例如m4a、MP4等,流式输入获取编码器 、上下文信息等,输出流指定封装格式,先将输入的音频重采样到指定AAC编码格式,接着使用FIFO形式处理解码数据,解码器根据packet根据指定的问codec_id解压成对应的帧,再根据指定的鹅codec_id将frame编码成packets,最后做封装打包为音频流。 在这里插入图片描述transcoding_aac.c源代码:
#include <stdio.h>
#include <iostream>
#include <mutex>
#include <sys/stat.h>
extern "C" {
#include "libavformat/avformat.h"
#include "libavcodec/avcodec.h"
#include "libswresample/swresample.h"
#include "libavdevice/avdevice.h"
#include <libavutil/file.h>
#include "libavformat/avio.h"
#include <libavutil/channel_layout.h>
#include <libavutil/common.h>
#include <libavutil/frame.h>
#include <libavutil/samplefmt.h>
#include <libavutil/audio_fifo.h>
#include "libavutil/avassert.h"
#include "libavutil/avstring.h"
#include "libavutil/opt.h"
}
using namespace std;
#ifdef av_err2str
#undef av_err2str
#include <string>
av_always_inline std::string av_err2string(int errnum) {
    char str[AV_ERROR_MAX_STRING_SIZE];
    return av_make_error_string(str, AV_ERROR_MAX_STRING_SIZE, errnum);
}
#define av_err2str(err) av_err2string(err).c_str()
#endif  // av_err2str

#define OUTPUT_BIT_RATE 96000


struct buffer_data_output{
    uint8_t *buf;
    size_t size;
    uint8_t *ptr;
    size_t room; 
};

struct buffer_data_input {
    uint8_t *ptr;   
    uint8_t *buf;   
    std::size_t  size;      
    std::size_t  file_size; 
};

static int iowrite_to_buffer(void *opaque, uint8_t *buf, int buf_size)
{
    struct buffer_data_output *bd = (struct buffer_data_output *)opaque;
    while (buf_size > bd->room)
    {
        int64_t offset = bd->ptr - bd->buf;
        bd->buf = (uint8_t*)av_realloc_f(bd->buf, 2, bd->size);
        if (!bd->buf)
            return AVERROR(ENOMEM);
        bd->size = bd->size*2;
        bd->ptr = bd->buf + offset;
        bd->room = bd->size - offset;
    }
    memcpy(bd->ptr, buf, buf_size);
    bd->ptr += buf_size;
    bd->room -= buf_size;
    // printf("write packet pkt_size:%d used_buf_size:%zu buf_size:%zu buf_room:%zu\n", buf_size, bd->ptr - bd->buf, bd->size, bd->room);
    return buf_size;
}
int64_t seek_buffer(void *ptr, int64_t pos, int whence)
{
    struct buffer_data_output *bd = (struct buffer_data_output *)ptr;
    int64_t ret = -1;
    switch (whence)
    {
    case AVSEEK_SIZE:
        return bd->size;
        break;
    case SEEK_SET:
        bd->ptr = bd->buf + pos;
        // bd->room = bd->size - pos;
        break;
    case SEEK_CUR:
	    if (bd->room > pos) {
		    bd->ptr += pos;
		    bd->room -= pos;
	    } else return EOF;
	    break;
    case SEEK_END:
	    if (bd->size > pos) {
		    bd->ptr = (bd->buf + bd->size) - pos;
		    int curPos = bd->ptr - bd->buf;
		    bd->room = bd->size - curPos;
    	} else return EOF;
	    break;
    default:
	    break;
    }
    ret = bd->ptr - bd->buf;
    // printf("whence=%d , offset=%ld , buffer_size=%ld, buffer_room=%ld\n", whence, pos, bd->size, bd->room);
    return ret;
}

static int read_packet_input(void *opaque, uint8_t *buf, int buf_size){
    struct buffer_data_input *bd = (struct buffer_data_input *)opaque;
    buf_size = FFMIN(buf_size, bd->size);
    if (!buf_size)
        return AVERROR_EOF;
    memcpy(buf, bd->ptr, buf_size);
    bd->ptr += buf_size;
    bd->size -= buf_size;
    return buf_size;
}

int64_t seek_buffer_input(void *ptr, int64_t pos, int whence){
    struct buffer_data_input *bd = (struct buffer_data_input *)ptr;
    int64_t ret = -1;
    switch (whence)
    {
    case AVSEEK_SIZE:
        return bd->file_size;
        break;
    case SEEK_SET:
	    if (bd->file_size > pos) {
        	bd->ptr = bd->buf + pos;
        	bd->size = bd->file_size - pos;
        } else return EOF;
        break;
    case SEEK_CUR:
	    if (bd->size > pos) {
		    bd->ptr += pos;
		    bd->size -= pos;
	    } else return EOF;
	    break;
    case SEEK_END:
	    if (bd->file_size > pos) {
		    bd->ptr = (bd->buf + bd->file_size) - pos;
		    int curPos = bd->ptr - bd->buf;
		    bd->size = bd->file_size - curPos;
    	} else return EOF;
	    break;
    default:
	    break;
    }
    return bd->ptr - bd->buf;
}

struct buffer_data_input bd = {0};
struct buffer_data_output bd_zm = {0};

/**
 * Open an input file and the required decoder.
 * @param[out] input_format_context Format context of opened file
 * @param[out] input_codec_context  Codec context of opened file
 * @return Error code (0 if successful)
 */
static int open_input_file(uint8_t* buffer, size_t buffer_size, AVFormatContext **input_format_context,
                           AVCodecContext **input_codec_context)
{
    AVCodecContext *avctx;
    const AVCodec *input_codec;
    AVIOContext *avio_ctx;
    uint8_t *in_buffer = NULL;
    size_t avio_ctx_buffer_size = 4096;
    int error;
    
    in_buffer = (uint8_t*)av_malloc(avio_ctx_buffer_size);
    if (!in_buffer) {
        std::cout << "av malloc error!" << std::endl; 
        return AVERROR_EXIT;
    }
    bd.buf = bd.ptr = buffer;
    bd.size = bd.file_size = buffer_size;
    avio_ctx = avio_alloc_context(in_buffer, avio_ctx_buffer_size, 0, &bd, &read_packet_input, NULL, &seek_buffer_input);
    *input_format_context = avformat_alloc_context();
    if(!(*input_format_context)) {
        std::cout << "avformat_alloc_context error!" << std::endl; 
        return -1;
    }
    (*input_format_context)->pb = avio_ctx;
    (*input_format_context)->flags |= AVFMT_FLAG_CUSTOM_IO;

    if ((error = avformat_open_input(input_format_context, NULL, NULL,
                                     NULL)) < 0) {
        fprintf(stderr, "Could not open input file (error '%s')\n", av_err2str(error));
        *input_format_context = NULL;
        return error;
    }

    if ((error = avformat_find_stream_info(*input_format_context, NULL)) < 0) {
        fprintf(stderr, "Could not open find stream info (error '%s')\n",
                av_err2str(error));
        avformat_close_input(input_format_context);
        return error;
    }

    if ((*input_format_context)->nb_streams != 1) {
        fprintf(stderr, "Expected one audio input stream, but found %d\n",
                (*input_format_context)->nb_streams);
        avformat_close_input(input_format_context);
        return AVERROR_EXIT;
    }

    if (!(input_codec = avcodec_find_decoder((*input_format_context)->streams[0]->codecpar->codec_id))) {
        fprintf(stderr, "Could not find input codec\n");
        avformat_close_input(input_format_context);
        return AVERROR_EXIT;
    }

    avctx = avcodec_alloc_context3(input_codec);
    if (!avctx) {
        fprintf(stderr, "Could not allocate a decoding context\n");
        avformat_close_input(input_format_context);
        return AVERROR(ENOMEM);
    }

    error = avcodec_parameters_to_context(avctx, (*input_format_context)->streams[0]->codecpar);
    if (error < 0) {
        avformat_close_input(input_format_context);
        avcodec_free_context(&avctx);
        return error;
    }

    if ((error = avcodec_open2(avctx, input_codec, NULL)) < 0) {
        fprintf(stderr, "Could not open input codec (error '%s')\n",
                av_err2str(error));
        avcodec_free_context(&avctx);
        avformat_close_input(input_format_context);
        return error;
    }
    *input_codec_context = avctx;
    return 0;
}

/**
 * Open an output file and the required encoder.
 * Also set some basic encoder parameters.
 * Some of these parameters are based on the input file's parameters.
 * @param      channels              Output file channels
 * @param      input_codec_context   Codec context of input file
 * @param[out] output_format_context Format context of output file
 * @param[out] output_codec_context  Codec context of output file
 * @return Error code (0 if successful)
 */
static int open_output_file(int channels, AVCodecContext *input_codec_context,
                            AVFormatContext **output_format_context,
                            AVCodecContext **output_codec_context)
{
    AVCodecContext *avctx          = NULL;
    AVStream *stream               = NULL;
    const AVCodec *output_codec    = NULL;
    int error;

    AVIOContext *avio_ctx_zm = NULL;
    uint8_t *avio_ctx_buffer_zm = NULL;
    size_t avio_ctx_buffer_size_zm = 4096;
    const size_t bd_out_buf_size = 1024;
    
    const AVOutputFormat *output_format = av_guess_format("mp4", NULL , NULL);
    avformat_alloc_output_context2(output_format_context, output_format, NULL, NULL);
     if (!(*output_format_context)) {
        av_log(NULL, AV_LOG_ERROR, "Could not create output context\n");
        return AVERROR_UNKNOWN;
    }
    bd_zm.ptr = bd_zm.buf = (uint8_t*)av_malloc(bd_out_buf_size);
    if (!bd_zm.buf) {
        return AVERROR(ENOMEM);
    }
    bd_zm.size = bd_zm.room = bd_out_buf_size;
    avio_ctx_buffer_zm = (uint8_t*)av_malloc(avio_ctx_buffer_size_zm);
    if (!avio_ctx_buffer_zm) {
        av_log(NULL, AV_LOG_ERROR, "allocate buffer error\n");
        return AVERROR(ENOMEM);
    }
    avio_ctx_zm = avio_alloc_context(avio_ctx_buffer_zm, avio_ctx_buffer_size_zm,
                                     1, &bd_zm, NULL, iowrite_to_buffer, seek_buffer);
    if (!avio_ctx_zm) {
        av_log(NULL, AV_LOG_ERROR, "allocate avio context error\n");
        return AVERROR(ENOMEM);
    }
    
    (*output_format_context)->pb = avio_ctx_zm;
    if (!(*output_format_context)->pb) {
        av_log(NULL, AV_LOG_ERROR, "output format context pb is empty\n");
        return AVERROR(ENOMEM);
    }
    // (*output_format_context)->flags |= AVFMT_FLAG_CUSTOM_IO;
    (*output_format_context)->oformat = output_format;

    if (!(output_codec = avcodec_find_encoder(AV_CODEC_ID_AAC))) {
        fprintf(stderr, "Could not find an AAC encoder.\n");
        goto cleanup;
    }

    if (!(stream = avformat_new_stream(*output_format_context, NULL))) {
        fprintf(stderr, "Could not create new stream\n");
        error = AVERROR(ENOMEM);
        goto cleanup;
    }
    avctx = avcodec_alloc_context3(output_codec);
    if (!avctx) {
        fprintf(stderr, "Could not allocate an encoding context\n");
        error = AVERROR(ENOMEM);
        goto cleanup;
    }

    avctx->channels       = channels;
    avctx->channel_layout = av_get_default_channel_layout(avctx->channels);
    avctx->sample_rate    = input_codec_context->sample_rate;
    avctx->sample_fmt     = output_codec->sample_fmts[0];
    avctx->bit_rate       = OUTPUT_BIT_RATE;

    avctx->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;

    stream->time_base.den = input_codec_context->sample_rate;
    stream->time_base.num = 1;

    if ((*output_format_context)->oformat->flags & AVFMT_GLOBALHEADER)
        avctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;

    if ((error = avcodec_open2(avctx, output_codec, NULL)) < 0) {
        fprintf(stderr, "Could not open output codec (error '%s')\n",
                av_err2str(error));
        goto cleanup;
    }

    error = avcodec_parameters_from_context(stream->codecpar, avctx);
    if (error < 0) {
        fprintf(stderr, "Could not initialize stream parameters\n");
        goto cleanup;
    }
    
    *output_codec_context = avctx;

    if ((avformat_write_header(*output_format_context, NULL)) < 0) {
        av_log(NULL, AV_LOG_ERROR, "Error occurred when opening output file\n");
        return -1;
    }
    return 0;

cleanup:
    avcodec_free_context(&avctx);
    avio_closep(&(*output_format_context)->pb);
    avformat_free_context(*output_format_context);
    *output_format_context = NULL;
    return error < 0 ? error : AVERROR_EXIT;
}


/**
 * Initialize one data packet for reading or writing.
 * @param[out] packet Packet to be initialized
 * @return Error code (0 if successful)
 */
static int init_packet(AVPacket **packet)
{
    if (!(*packet = av_packet_alloc())) {
        fprintf(stderr, "Could not allocate packet\n");
        return AVERROR(ENOMEM);
    }
    return 0;
}

/**
 * Initialize one audio frame for reading from the input file.
 * @param[out] frame Frame to be initialized
 * @return Error code (0 if successful)
 */
static int init_input_frame(AVFrame **frame)
{
    if (!(*frame = av_frame_alloc())) {
        fprintf(stderr, "Could not allocate input frame\n");
        return AVERROR(ENOMEM);
    }
    return 0;
}

/**
 * Initialize the audio resampler based on the input and output codec settings.
 * If the input and output sample formats differ, a conversion is required
 * libswresample takes care of this, but requires initialization.
 * @param      input_codec_context  Codec context of the input file
 * @param      output_codec_context Codec context of the output file
 * @param[out] resample_context     Resample context for the required conversion
 * @return Error code (0 if successful)
 */
static int init_resampler(AVCodecContext *input_codec_context,
                          AVCodecContext *output_codec_context,
                          SwrContext **resample_context)
{
        int error;

        *resample_context = swr_alloc_set_opts(NULL,
                                              av_get_default_channel_layout(output_codec_context->channels),
                                              output_codec_context->sample_fmt,
                                              output_codec_context->sample_rate,
                                              av_get_default_channel_layout(input_codec_context->channels),
                                              input_codec_context->sample_fmt,
                                              input_codec_context->sample_rate,
                                              0, NULL);
        if (!*resample_context) {
            fprintf(stderr, "Could not allocate resample context\n");
            return AVERROR(ENOMEM);
        }
        av_assert0(output_codec_context->sample_rate == input_codec_context->sample_rate);

        if ((error = swr_init(*resample_context)) < 0) {
            fprintf(stderr, "Could not open resample context\n");
            swr_free(resample_context);
            return error;
        }
    return 0;
}

/**
 * Initialize a FIFO buffer for the audio samples to be encoded.
 * @param[out] fifo                 Sample buffer
 * @param      output_codec_context Codec context of the output file
 * @return Error code (0 if successful)
 */
static int init_fifo(AVAudioFifo **fifo, AVCodecContext *output_codec_context)
{
    if (!(*fifo = av_audio_fifo_alloc(output_codec_context->sample_fmt,
                                      output_codec_context->channels, 1))) {
        fprintf(stderr, "Could not allocate FIFO\n");
        return AVERROR(ENOMEM);
    }
    return 0;
}

/**
 * Decode one audio frame from the input file.
 * @param      frame                Audio frame to be decoded
 * @param      input_format_context Format context of the input file
 * @param      input_codec_context  Codec context of the input file
 * @param[out] data_present         Indicates whether data has been decoded
 * @param[out] finished             Indicates whether the end of file has
 *                                  been reached and all data has been
 *                                  decoded. If this flag is false, there
 *                                  is more data to be decoded, i.e., this
 *                                  function has to be called again.
 * @return Error code (0 if successful)
 */
static int decode_audio_frame(AVFrame *frame,
                              AVFormatContext *input_format_context,
                              AVCodecContext *input_codec_context,
                              int *data_present, int *finished)
{
    AVPacket *input_packet;
    int error;

    error = init_packet(&input_packet);
    if (error < 0)
        return error;

    if ((error = av_read_frame(input_format_context, input_packet)) < 0) {
        if (error == AVERROR_EOF)
            *finished = 1;
        else {
            fprintf(stderr, "Could not read frame (error '%s')\n",
                    av_err2str(error));
            goto cleanup;
        }
    }

    if ((error = avcodec_send_packet(input_codec_context, input_packet)) < 0) {
        fprintf(stderr, "Could not send packet for decoding (error '%s')\n",
                av_err2str(error));
        goto cleanup;
    }

    error = avcodec_receive_frame(input_codec_context, frame);
    if (error == AVERROR(EAGAIN)) {
        error = 0;
        goto cleanup;
    } else if (error == AVERROR_EOF) {
        *finished = 1;
        error = 0;
        goto cleanup;
    } else if (error < 0) {
        fprintf(stderr, "Could not decode frame (error '%s')\n",
                av_err2str(error));
        goto cleanup;
    } else {
        *data_present = 1;
        goto cleanup;
    }

cleanup:
    av_packet_free(&input_packet);
    return error;
}

/**
 * Initialize a temporary storage for the specified number of audio samples.
 * The conversion requires temporary storage due to the different format.
 * The number of audio samples to be allocated is specified in frame_size.
 * @param[out] converted_input_samples Array of converted samples. The
 *                                     dimensions are reference, channel
 *                                     (for multi-channel audio), sample.
 * @param      output_codec_context    Codec context of the output file
 * @param      frame_size              Number of samples to be converted in
 *                                     each round
 * @return Error code (0 if successful)
 */
static int init_converted_samples(uint8_t ***converted_input_samples,
                                  AVCodecContext *output_codec_context,
                                  int frame_size)
{
    int error;

    if (!(*converted_input_samples = static_cast<uint8_t **>(calloc(output_codec_context->channels,
                                            sizeof(**converted_input_samples))))) {
        fprintf(stderr, "Could not allocate converted input sample pointers\n");
        return AVERROR(ENOMEM);
    }

    if ((error = av_samples_alloc(*converted_input_samples, NULL,
                                  output_codec_context->channels,
                                  frame_size,
                                  output_codec_context->sample_fmt, 0)) < 0) {
        fprintf(stderr,
                "Could not allocate converted input samples (error '%s')\n",
                av_err2str(error));
        av_freep(&(*converted_input_samples)[0]);
        free(*converted_input_samples);
        return error;
    }
    return 0;
}

/**
 * Convert the input audio samples into the output sample format.
 * The conversion happens on a per-frame basis, the size of which is
 * specified by frame_size.
 * @param      input_data       Samples to be decoded. The dimensions are
 *                              channel (for multi-channel audio), sample.
 * @param[out] converted_data   Converted samples. The dimensions are channel
 *                              (for multi-channel audio), sample.
 * @param      frame_size       Number of samples to be converted
 * @param      resample_context Resample context for the conversion
 * @return Error code (0 if successful)
 */
static int convert_samples(const uint8_t **input_data,
                           uint8_t **converted_data, const int frame_size,
                           SwrContext *resample_context)
{
    int error;

    if ((error = swr_convert(resample_context,
                             converted_data, frame_size,
                             input_data    , frame_size)) < 0) {
        fprintf(stderr, "Could not convert input samples (error '%s')\n",
                av_err2str(error));
        return error;
    }

    return 0;
}

/**
 * Add converted input audio samples to the FIFO buffer for later processing.
 * @param fifo                    Buffer to add the samples to
 * @param converted_input_samples Samples to be added. The dimensions are channel
 *                                (for multi-channel audio), sample.
 * @param frame_size              Number of samples to be converted
 * @return Error code (0 if successful)
 */
static int add_samples_to_fifo(AVAudioFifo *fifo,
                               uint8_t **converted_input_samples,
                               const int frame_size)
{
    int error;

    if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + frame_size)) < 0) {
        fprintf(stderr, "Could not reallocate FIFO\n");
        return error;
    }

    if (av_audio_fifo_write(fifo, (void **)converted_input_samples,
                            frame_size) < frame_size) {
        fprintf(stderr, "Could not write data to FIFO\n");
        return AVERROR_EXIT;
    }
    return 0;
}

/**
 * Read one audio frame from the input file, decode, convert and store
 * it in the FIFO buffer.
 * @param      fifo                 Buffer used for temporary storage
 * @param      input_format_context Format context of the input file
 * @param      input_codec_context  Codec context of the input file
 * @param      output_codec_context Codec context of the output file
 * @param      resampler_context    Resample context for the conversion
 * @param[out] finished             Indicates whether the end of file has
 *                                  been reached and all data has been
 *                                  decoded. If this flag is false,
 *                                  there is more data to be decoded,
 *                                  i.e., this function has to be called
 *                                  again.
 * @return Error code (0 if successful)
 */
static int read_decode_convert_and_store(AVAudioFifo *fifo,
                                         AVFormatContext *input_format_context,
                                         AVCodecContext *input_codec_context,
                                         AVCodecContext *output_codec_context,
                                         SwrContext *resampler_context,
                                         int *finished)
{
    AVFrame *input_frame = NULL;
    uint8_t **converted_input_samples = NULL;
    int data_present = 0;
    int ret = AVERROR_EXIT;

    if (init_input_frame(&input_frame))
        goto cleanup;
    if (decode_audio_frame(input_frame, input_format_context,
                           input_codec_context, &data_present, finished))
        goto cleanup;
    if (*finished) {
        ret = 0;
        goto cleanup;
    }
    if (data_present) {
        if (init_converted_samples(&converted_input_samples, output_codec_context,
                                   input_frame->nb_samples))
            goto cleanup;

        if (convert_samples((const uint8_t**)input_frame->extended_data, converted_input_samples,
                            input_frame->nb_samples, resampler_context))
            goto cleanup;

        if (add_samples_to_fifo(fifo, converted_input_samples,
                                input_frame->nb_samples))
            goto cleanup;
        ret = 0;
    }
    ret = 0;

cleanup:
    if (converted_input_samples) {
        av_freep(&converted_input_samples[0]);
        free(converted_input_samples);
    }
    av_frame_free(&input_frame);

    return ret;
}

/**
 * Initialize one input frame for writing to the output file.
 * The frame will be exactly frame_size samples large.
 * @param[out] frame                Frame to be initialized
 * @param      output_codec_context Codec context of the output file
 * @param      frame_size           Size of the frame
 * @return Error code (0 if successful)
 */
static int init_output_frame(AVFrame **frame,
                             AVCodecContext *output_codec_context,
                             int frame_size)
{
    int error;

    if (!(*frame = av_frame_alloc())) {
        fprintf(stderr, "Could not allocate output frame\n");
        return AVERROR_EXIT;
    }

    (*frame)->nb_samples     = frame_size;
    (*frame)->channel_layout = output_codec_context->channel_layout;
    (*frame)->format         = output_codec_context->sample_fmt;
    (*frame)->sample_rate    = output_codec_context->sample_rate;

    if ((error = av_frame_get_buffer(*frame, 0)) < 0) {
        fprintf(stderr, "Could not allocate output frame samples (error '%s')\n",
                av_err2str(error));
        av_frame_free(frame);
        return error;
    }

    return 0;
}

/* Global timestamp for the audio frames. */
static int64_t pts = 0;

/**
 * Encode one frame worth of audio to the output file.
 * @param      frame                 Samples to be encoded
 * @param      output_format_context Format context of the output file
 * @param      output_codec_context  Codec context of the output file
 * @param[out] data_present          Indicates whether data has been
 *                                   encoded
 * @return Error code (0 if successful)
 */
static int encode_audio_frame(AVFrame *frame,
                              AVFormatContext *output_format_context,
                              AVCodecContext *output_codec_context,
                              int *data_present)
{
    AVPacket *output_packet;
    int error;

    error = init_packet(&output_packet);
    if (error < 0)
        return error;

    if (frame) {
        frame->pts = pts;
        pts += frame->nb_samples;
    }

    error = avcodec_send_frame(output_codec_context, frame);
    if (error == AVERROR_EOF) {
        error = 0;
        goto cleanup;
    } else if (error < 0) {
        fprintf(stderr, "Could not send packet for encoding (error '%s')\n",
                av_err2str(error));
        goto cleanup;
    }

    /* Receive one encoded frame from the encoder. */
    error = avcodec_receive_packet(output_codec_context, output_packet);
    if (error == AVERROR(EAGAIN)) {
        error = 0;
        goto cleanup;
    } else if (error == AVERROR_EOF) {
        error = 0;
        goto cleanup;
    } else if (error < 0) {
        fprintf(stderr, "Could not encode frame (error '%s')\n",
                av_err2str(error));
        goto cleanup;
    } else {
        *data_present = 1;
    }

    if (*data_present &&
        (error = av_write_frame(output_format_context, output_packet)) < 0) {
        fprintf(stderr, "Could not write frame (error '%s')\n",
                av_err2str(error));
        goto cleanup;
    }

cleanup:
    av_packet_free(&output_packet);
    return error;
}

/**
 * Load one audio frame from the FIFO buffer, encode and write it to the
 * output file.
 * @param fifo                  Buffer used for temporary storage
 * @param output_format_context Format context of the output file
 * @param output_codec_context  Codec context of the output file
 * @return Error code (0 if successful)
 */
static int load_encode_and_write(AVAudioFifo *fifo,
                                 AVFormatContext *output_format_context,
                                 AVCodecContext *output_codec_context)
{
    AVFrame *output_frame;
    const int frame_size = FFMIN(av_audio_fifo_size(fifo),
                                 output_codec_context->frame_size);
    int data_written;

    if (init_output_frame(&output_frame, output_codec_context, frame_size))
        return AVERROR_EXIT;

    if (av_audio_fifo_read(fifo, (void **)output_frame->data, frame_size) < frame_size) {
        fprintf(stderr, "Could not read data from FIFO\n");
        av_frame_free(&output_frame);
        return AVERROR_EXIT;
    }

    if (encode_audio_frame(output_frame, output_format_context,
                           output_codec_context, &data_written)) {
        av_frame_free(&output_frame);
        return AVERROR_EXIT;
    }
    av_frame_free(&output_frame);
    return 0;
}

int tom4atype(uint8_t* buffer, size_t buffer_size, int channels, std::string &output)
{
    AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
    AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
    SwrContext *resample_context = NULL;
    AVAudioFifo *fifo = NULL;
    int ret = AVERROR_EXIT;

    //打开输入文件buffer去读
    if (open_input_file(buffer, buffer_size, &input_format_context,
                        &input_codec_context))
        goto cleanup;
    //打开输出文件buffer去写
    if (open_output_file(channels, input_codec_context, &output_format_context, 
                        &output_codec_context))
        goto cleanup;
    //初始化转换上下文
    if (init_resampler(input_codec_context, output_codec_context,
                       &resample_context))
        goto cleanup;

    if (init_fifo(&fifo, output_codec_context))
        goto cleanup;
    
    while (1) {
        //输出时每个通道的采样数
        const int output_frame_size = output_codec_context->frame_size;
        int finished                = 0;

        while (av_audio_fifo_size(fifo) < output_frame_size) {
            //解码输入数据,进行转换,然后放到输出数据中,类似于生产者-消费者
            if (read_decode_convert_and_store(fifo, input_format_context,
                                              input_codec_context,
                                              output_codec_context,
                                              resample_context, &finished))
                goto cleanup;
            if (finished)
                break;
        }
        //样本数足够,写buffer
        while (av_audio_fifo_size(fifo) >= output_frame_size ||
               (finished && av_audio_fifo_size(fifo) > 0))
            
            if (load_encode_and_write(fifo, output_format_context,
                                      output_codec_context))
                goto cleanup;
        if (finished) {
            int data_written;
            do {
                data_written = 0;
                //刷新编码器中的数据
                if (encode_audio_frame(NULL, output_format_context,
                                       output_codec_context, &data_written))
                    goto cleanup;
            } while (data_written);
            break;
        }
    }

    //写文件尾到buffer
    av_write_trailer(output_format_context);
    //写结果
    output.assign((char*)bd_zm.buf, bd_zm.size - bd_zm.room);
    std::cout << "output size: " << output.size() << std::endl;
    ret = 0;

cleanup:
    if (fifo)
        av_audio_fifo_free(fifo);
    swr_free(&resample_context);
    if (output_codec_context)
        avcodec_free_context(&output_codec_context);
    if (output_format_context) {
        avformat_free_context(output_format_context);
    }
    if (input_codec_context)
        avcodec_free_context(&input_codec_context);
    if (input_format_context)
        avformat_close_input(&input_format_context);

    return ret;
}

int main(int argc, char** argv) {
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
        exit(1);
    }

    uint8_t* buffer;
    size_t buffer_size;
    int  ret = av_file_map(argv[1], &buffer, &buffer_size, 0, NULL);
    if (ret < 0) {
        std::cout << "av_file_map error" << std::endl;
        return -1;
    }
    std::string output;
    tom4atype(buffer, buffer_size, 2, output);
    
    FILE *pFile;
    pFile = fopen(argv[2], "wb");
    if (pFile) {
        // fwrite(bd_zm.buf, bd_zm.size - bd_zm.room, 1, pFile);  //跟ffmpeg命令行比, 最后多个8bit的空值
        fwrite(output.data(), bd_zm.size - bd_zm.room, 1, pFile);
        puts("Wrote to file!");
    }
    else {
        puts("Something wrong writing to File.");
    }
    fclose(pFile);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值