【音视频】⾳频处置处罚基本概念及⾳频重采样

[复制链接]
发表于 2025-9-19 22:56:52 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
一、重采样

1.1 什么是重采样

所谓的重采样,就是改变⾳频的采样率、sample format、声道数等参数,使之按照我们渴望的参数输出。
1.2 为什么要重采样

为什么要重采样?


  • 当然是原有的⾳频参数不满⾜我们的需求,⽐如在FFmpeg解码⾳频的时间,差别的⾳源有差别的格式,采样率等,在解码后的数据中的这些参数也会不⼀致(最新FFmpeg 解码⾳频后,⾳频格式为AV_SAMPLE_FMT_FLTP,这个参数应该是⼀致的),如果我们接下来必要使⽤解码后的⾳频数据做其他操纵,⽽这些参数的不⼀致导致会有许多额外⼯作,此时直接对其进⾏重采样,获取我们订定的⾳频参数,如许就会⽅便许多。
  • 再⽐如在将⾳频进⾏SDL播放时间,由于当前的SDL2.0不⽀持planar格式,也不⽀持浮点型的,⽽最新的FFMPEG 16年会将⾳频解码为AV_SAMPLE_FMT_FLTP格式,因此此时就必要我们对其重采样,使之可以在SDL2.0上进⾏播放。
1.3 可调治的参数

通过重采样,我们可以对:

  • sample rate(采样率)
  • sample format(采样格式)
  • channel layout(通道布局,可以通过此参数获取声道数)
二、 对应参数分析

2.1 采样率

采样装备每秒抽取样本的次数
2.2 采样格式及量化精度(位宽)

每种⾳频格式有差别的量化精度(位宽),位数越多,表现值就越精确,声⾳表现⾃然就越精准。
FFMpeg中⾳频格式有以下⼏种,每种格式有其占⽤的字节数信息
  1. enum AVSampleFormat {
  2. AV_SAMPLE_FMT_NONE = -1,
  3. AV_SAMPLE_FMT_U8, ///< unsigned 8 bits
  4. AV_SAMPLE_FMT_S16, ///< signed 16 bits
  5. AV_SAMPLE_FMT_S32, ///< signed 32 bits
  6. AV_SAMPLE_FMT_FLT, ///< float
  7. AV_SAMPLE_FMT_DBL, ///< double
  8. AV_SAMPLE_FMT_U8P, ///< unsigned 8 bits, planar
  9. AV_SAMPLE_FMT_S16P, ///< signed 16 bits, planar
  10. AV_SAMPLE_FMT_S32P, ///< signed 32 bits, planar
  11. AV_SAMPLE_FMT_FLTP, ///< float, planar
  12. AV_SAMPLE_FMT_DBLP, ///< double, planar
  13. AV_SAMPLE_FMT_S64, ///< signed 64 bits
  14. AV_SAMPLE_FMT_S64P, ///< signed 64 bits, planar
  15. AV_SAMPLE_FMT_NB ///< Number of sample formats. DO NOT USE if linking dynamically
  16. };
复制代码
2.3 分⽚(plane)和打包(packed)



  • 以双声道为例,带P(plane)的数据格式在存储时,其左声道和右声道的数据是分开存储的,左声道的数据存储在data[0],右声道的数据存储在data[1],每个声道的所占⽤的字节数为linesize[0]和linesize[1]
  • 不带P(packed)的⾳频数据在存储时,是按照LRLRLR…的格式瓜代存储在data[0]中,linesize[0]表现总的数据量。
2.4 声道分布(channel_layout)

声道分布在FFmpeg\libavutil\channel_layout.h中有界说,⼀般来说⽤的⽐较多的是AV_CH_LAYOUT_STEREO(双声道)和AV_CH_LAYOUT_SURROUND(三声道)
这两者的界说如下:
  1. #define AV_CH_LAYOUT_STEREO (AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT)
  2. #define AV_CH_LAYOUT_SURROUND (AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER)
复制代码
2.5 ⾳频帧的数据量计算



  • ⼀帧⾳频的数据量(字节)=channel 数 * nb_samples样本数 * 每个样本占⽤的字节数
  • 如果该⾳频帧是FLTP格式的PCM数据,包罗1024个样本,双声道,那么该⾳频帧包罗的⾳频数据量是2*1024*4=8192字节。
  • AV_SAMPLE_FMT_DBL : 2*1024*8 = 16384
2.6 ⾳频播放时间计算



  • 以采样率44100Hz来计算,每秒44100个sample,⽽正常⼀帧为1024个sample,可知每帧播放时间/1024=1000ms/44100,得到每帧播放时间=1024*1000/44100=23.2ms (更精确的是23.21995464852608)。
  • ⼀帧播放时间(毫秒) = nb_samples样本数 *1000/采样率
  • (1)1024*1000/44100=23.21995464852608ms ->约即是 23.2ms,精度丧失了0.011995464852608ms,如果累计10万帧,误差>1199毫秒,如果有视频⼀起的就会有⾳视频同步的题目。 如果按着23.2去计算pts(0 23.2 46.4 )就会有累积误差。
  • (2)1024*1000/48000=21.33333333333333ms
三、FFmpeg重采样API

分配⾳频重采样的上下⽂
  1. struct SwrContext *swr_alloc(void)
复制代码
当设置好干系的参数后,使⽤此函数来初始化SwrContext布局体
  1. int swr_init(struct SwrContext *s);
复制代码
分配SwrContext并设置/重置常⽤的参数。
  1. struct SwrContext *swr_alloc_set_opts(struct SwrContext *s, // ⾳频重采样上下⽂
  2.         int64_t out_ch_layout, // 输出的layout, 如:5.1声道
  3.         enum AVSampleFormat out_sample_fmt, // 输出的采样格式。Float, S16,⼀般选⽤是s16 绝⼤部分声卡⽀持
  4.         int out_sample_rate, //输出采样率
  5.         int64_t in_ch_layout, // 输⼊的layout
  6.         enum AVSampleFormat in_sample_fmt, // 输⼊的采样格式
  7.         int in_sample_rate, // 输⼊的采样率
  8.         int log_offset, // ⽇志相关,不⽤管先,直接为0
  9.         void *log_ctx // ⽇志相关,不⽤管先,直接为NULL
  10. );
复制代码
将输⼊的⾳频按照界说的参数进⾏转换并输出


  • 返回值 <= out_count,
  • in和in_count可以设置为0,以末了革新末了⼏个样本。
  1. int swr_convert(struct SwrContext *s, // ⾳频重采样的上下⽂
  2.         uint8_t **out, // 输出的指针。传递的输出的数组
  3.         int out_count, //输出的样本数量,不是字节数。单通道的样本数量。
  4.         const uint8_t **in , //输⼊的数组,AVFrame解码出来的DATA
  5.         int in_count // 输⼊的单通道的样本数量。
  6. );
复制代码
开释掉SwrContext布局体并将此布局体置为NULL
  1. void swr_free(struct SwrContext **s);
复制代码


  • 与lswr的交互是通过SwrContext完成的,SwrContext被分配给swr_alloc()或
    swr_alloc_set_opts()。 它是不透明的,以是全部参数必须使⽤AVOptions API设置。
  • 为了使⽤lswr,你必要做的第⼀件事就是分配SwrContext。 这可以使⽤swr_alloc()或swr_alloc_set_opts()来完成。 如果您使⽤前者,则必须通过AVOptions API设置选项。 后⼀个函数提供了雷同的功能,但它答应您在同⼀语句中设置⼀些常⽤选项。
  • 比方,以下代码将设置从平⾯浮动样本格式到交错的带符号16位整数的转换,从48kHz到44.1kHz的下采样,以及从5.1声道到⽴体声的下混淆(使⽤默认混淆矩阵)。 这是使⽤swr_alloc()函数。
  1. SwrContext *swr = swr_alloc();
  2. av_opt_set_channel_layout(swr, "in_channel_layout", AV_CH_LAYOUT_POINT1, 0);
  3. av_opt_set_channel_layout(swr, "out_channel_layout", AV_CH_LAYOUT_STEREO, 0);
  4. av_opt_set_int(swr, "in_sample_rate", 48000, 0);
  5. av_opt_set_int(swr, "out_sample_rate", 44100, 0);
  6. av_opt_set_sample_fmt(swr, "in_sample_fmt", AV_SAMPLE_FMT_FLTP, 0);
  7. av_opt_set_sample_fmt(swr, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0);
复制代码
同样的⼯作也可以使⽤swr_alloc_set_opts():
  1. SwrContext *swr = swr_alloc_set_opts(NULL, // we're allocating a new_context
  2.         AV_CH_LAYOUT_STEREO, // out_ch_layout
  3.         AV_SAMPLE_FMT_S16, // out_sample_fmt
  4.         44100, // out_sample_rate
  5.         AV_CH_LAYOUT_5POINT1, // in_ch_layout
  6.         AV_SAMPLE_FMT_FLTP, // in_sample_fmt
  7.         48000, // in_sample_rate
  8.         0, // log_offset
  9.         NULL); // log_ctx
复制代码


  • ⼀旦设置了全部值,它必须⽤swr_init()初始化。 如果必要更改转换参数,可以使⽤AVOptions来更改参数,如上⾯第⼀个例⼦所述; 或者使⽤swr_alloc_set_opts(),但是第⼀个参数是分配的上下⽂。 您必须再次调⽤swr_init()。
  • 转换本身通过重复调⽤swr_convert()来完成。 请注意,如果提供的输出空间不⾜或采样率转换完成后,样本大概会在swr中缓冲,这必要“未来”样本。 可以随时通过使⽤swr_convert()(in_count可以设置为0)来检索不必要未来输⼊的样本。 在转换竣事时,可以通过调⽤具有NULL in和in incount的swr_convert()来革新重采样缓冲区。
实现流程

添加输出文件

在main函数参数中参加输出文件,这里设置为out.pcm

打开输出文件

二进制写方式打开
  1. FILE *dst_file;
  2. dst_filename = argv[1];
  3. dst_file = fopen(dst_filename, "wb");
复制代码
设置输入参数和输出参数



  • 这里的输入源是我们手动生成了,生成的是一个正弦波
  • 手动设置一下输入源的参数信息
  1. // 输入参数
  2. int64_t src_ch_layout = AV_CH_LAYOUT_STEREO;
  3. int src_rate = 48000;
  4. enum AVSampleFormat src_sample_fmt = AV_SAMPLE_FMT_DBL;
  5. int src_nb_channels = 0;
  6. uint8_t **src_data = NULL;  // 二级指针
  7. int src_linesize;
  8. int src_nb_samples = 1024;
复制代码


  • 设置输出参数,改变采样率和采样格式
  1. // 输出参数
  2. int64_t dst_ch_layout = AV_CH_LAYOUT_STEREO;
  3. int dst_rate = 44100;
  4. enum AVSampleFormat dst_sample_fmt = AV_SAMPLE_FMT_S16;
  5. int dst_nb_channels = 0;
  6. uint8_t **dst_data = NULL;  //二级指针
  7. int dst_linesize;
  8. int dst_nb_samples;
  9. int max_dst_nb_samples;
复制代码


  • 创建重采样上下文对象
  • 分配重采样上下文内存
  • 设置重采样参数
  • 初始化重采样
  1. struct SwrContext *swr_ctx;
  2. swr_ctx = swr_alloc();
  3. av_opt_set_int(swr_ctx, "in_channel_layout",    src_ch_layout, 0);
  4. av_opt_set_int(swr_ctx, "in_sample_rate",       src_rate, 0);
  5. av_opt_set_sample_fmt(swr_ctx, "in_sample_fmt", src_sample_fmt, 0);
  6.     /* initialize the resampling context */
  7. if ((ret = swr_init(swr_ctx)) < 0) {
  8.         fprintf(stderr, "Failed to initialize the resampling context\n");
  9.         goto end;
  10. }
复制代码


  • 必要根据通道格式获取通道的数量
  1. src_nb_channels = av_get_channel_layout_nb_channels(src_ch_layout);
  2. dst_nb_channels = av_get_channel_layout_nb_channels(dst_ch_layout);
复制代码


  • 根据输入(输出)参数(采样率、音频格式、通道数)分配内存
  1. ret = av_samples_alloc_array_and_samples(&src_data, &src_linesize, src_nb_channels,
  2.                                                                                  src_nb_samples, src_sample_fmt, 0);
  3. dst_nb_channels = av_get_channel_layout_nb_channels(dst_ch_layout);
  4. // 分配输出缓存内存
  5. ret = av_samples_alloc_array_and_samples(&dst_data, &dst_linesize, dst_nb_channels,
  6.                                                                                  dst_nb_samples, dst_sample_fmt, 0);
  7.    
复制代码


  • 根据输入的采样率和输入的采样点计算出输出文件的总采样数量
  • 这里的采样点指的是一帧采样的总采样点,是循环举行如许每一帧的采样
  • AV_ROUND_UP是上取整,由于存在小数
  1. max_dst_nb_samples = dst_nb_samples =
  2.                 av_rescale_rnd(src_nb_samples, dst_rate, src_rate, AV_ROUND_UP);
复制代码
生成输入输出数据



  • 生成输入源,由于输入格式使用的是packet模式的格式
  • 每次生成数据计算时间t,我们只生成10s数据
  1. fill_samples((double *)src_data[0], src_nb_samples, src_nb_channels, src_rate, &t);
复制代码


  • fill_samples函数用于生成一个440Hz频率的正弦波
  • 这里是打包模式,只有src_data[0]有数据,而且每个采样点依次输入到每个channel中
  1. static void fill_samples(double *dst, int nb_samples, int nb_channels, int sample_rate, double *t)
  2. {
  3.     int i, j;
  4.     double tincr = 1.0 / sample_rate, *dstp = dst;
  5.     const double c = 2 * M_PI * 440.0;
  6.     /* generate sin tone with 440Hz frequency and duplicated channels */
  7.     for (i = 0; i < nb_samples; i++) {
  8.         *dstp =sin(c * *t);
  9.         for (j = 1; j < nb_channels; j++)
  10.             dstp[j] = dstp[0];
  11.         dstp += nb_channels;
  12.         *t += tincr;
  13.     }
  14. }
复制代码
计算采样点毛病



  • 由于我们转换后的采样点不能整除,因此会在重采样器中缓存一部门采样点
  • 我们就必要动态拿出这个缓存的采样点,如果采样点大于之前的最大采样点,那么我就必要重新分配输出样本的内存,而且重新设置最大采样点
  1. int64_t delay = swr_get_delay(swr_ctx, src_rate);
  2.         dst_nb_samples = av_rescale_rnd(delay + src_nb_samples, dst_rate, src_rate, AV_ROUND_UP);
  3.         if (dst_nb_samples > max_dst_nb_samples) {
  4.             av_freep(&dst_data[0]);
  5.             ret = av_samples_alloc(dst_data, &dst_linesize, dst_nb_channels,
  6.                                    dst_nb_samples, dst_sample_fmt, 1);
  7.             if (ret < 0)
  8.                 break;
  9.             max_dst_nb_samples = dst_nb_samples;
复制代码
重采样转换



  • 根据输入输出的样本数将输入数据重采样转换到输出数据
  1. ret = swr_convert(swr_ctx, dst_data, dst_nb_samples, (const uint8_t **)src_data, src_nb_samples);
  2. if (ret < 0) {
  3.         fprintf(stderr, "Error while converting\n");
  4.         goto end;
  5. }
复制代码
写入文件



  • 获取dst数据的巨细,要根据通道数、音频格式,以及linesize来推断
  • 获取数据巨细后,写入相应巨细的数据到文件
  1. ret = swr_convert(swr_ctx, dst_data, dst_nb_samples, (const uint8_t **)src_data, src_nb_samples);
  2. if (ret < 0) {
  3.         fprintf(stderr, "Error while converting\n");
  4.         goto end;
  5. }
  6. dst_bufsize = av_samples_get_buffer_size(&dst_linesize, dst_nb_channels,                                                                                 ret, dst_sample_fmt, 1);if (dst_bufsize < 0) {        fprintf(stderr, "Could not get sample buffer size\n");        goto end;}fwrite(dst_data[0], 1, dst_bufsize, dst_file);
复制代码
团体转换代码



  • 团体转换的代码如下,只重采样10s的数据
  1. t = 0;    do {        /* generate synthetic audio */        // 生成输入源        fill_samples((double *)src_data[0], src_nb_samples, src_nb_channels, src_rate, &t);
  2.         /* compute destination number of samples */        int64_t delay = swr_get_delay(swr_ctx, src_rate);
  3.         dst_nb_samples = av_rescale_rnd(delay + src_nb_samples, dst_rate, src_rate, AV_ROUND_UP);
  4.         if (dst_nb_samples > max_dst_nb_samples) {
  5.             av_freep(&dst_data[0]);
  6.             ret = av_samples_alloc(dst_data, &dst_linesize, dst_nb_channels,
  7.                                    dst_nb_samples, dst_sample_fmt, 1);
  8.             if (ret < 0)
  9.                 break;
  10.             max_dst_nb_samples = dst_nb_samples;
  11.         }        //        int fifo_size = swr_get_out_samples(swr_ctx,src_nb_samples);        //        printf("fifo_size:%d\n", fifo_size);        //        if(fifo_size < 1024)        //            continue;        /* convert to destination format */        //        ret = swr_convert(swr_ctx, dst_data, dst_nb_samples, (const uint8_t **)src_data, src_nb_samples);        ret = swr_convert(swr_ctx, dst_data, dst_nb_samples, (const uint8_t **)src_data, src_nb_samples);        if (ret < 0) {            fprintf(stderr, "Error while converting\n");            goto end;        }        dst_bufsize = av_samples_get_buffer_size(&dst_linesize, dst_nb_channels,                                                 ret, dst_sample_fmt, 1);        if (dst_bufsize < 0) {            fprintf(stderr, "Could not get sample buffer size\n");            goto end;        }        printf("t:%f in:%d out:%d\n", t, src_nb_samples, ret);        fwrite(dst_data[0], 1, dst_bufsize, dst_file);    } while (t < 10);
复制代码
冲刷重采样器



  • 冲刷重采样,紧张是为了将剩余的数据写入到文件中
  • 输入数据写为NULL即可
  1. ret = swr_convert(swr_ctx, dst_data, dst_nb_samples, NULL, 0);
  2. if (ret < 0) {
  3.         fprintf(stderr, "Error while converting\n");
  4.         goto end;
  5. }
  6. dst_bufsize = av_samples_get_buffer_size(&dst_linesize, dst_nb_channels,
  7.                                                                                  ret, dst_sample_fmt, 1);
  8. if (dst_bufsize < 0) {
  9.         fprintf(stderr, "Could not get sample buffer size\n");
  10.         goto end;
  11. }
  12. fwrite(dst_data[0], 1, dst_bufsize, dst_file);
复制代码
竣事工作



  • 开释重采样器内存、开释输入输出缓冲区内存
  • 关闭输出文件
  1. fclose(dst_file);
  2. if (src_data)
  3.         av_freep(&src_data[0]);
  4. av_freep(&src_data);
  5. if (dst_data)
  6.         av_freep(&dst_data[0]);
  7. av_freep(&dst_data);
  8. swr_free(&swr_ctx);
复制代码
完备代码

main.c
  1. /* * Copyright (c) 2012 Stefano Sabatini * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *//** * @example resampling_audio.c * libswresample API use example. */#include <libavutil/opt.h>#include <libavutil/channel_layout.h>#include <libavutil/samplefmt.h>#include <libswresample/swresample.h>static int get_format_from_sample_fmt(const char **fmt,                                      enum AVSampleFormat sample_fmt){    int i;    struct sample_fmt_entry {        enum AVSampleFormat sample_fmt; const char *fmt_be, *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" },};    *fmt = NULL;    for (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) {            *fmt = AV_NE(entry->fmt_be, entry->fmt_le);            return 0;        }    }    fprintf(stderr,            "Sample format %s not supported as output format\n",            av_get_sample_fmt_name(sample_fmt));    return AVERROR(EINVAL);}/** * Fill dst buffer with nb_samples, generated starting from t. 交错模式的 */static void fill_samples(double *dst, int nb_samples, int nb_channels, int sample_rate, double *t)
  2. {
  3.     int i, j;
  4.     double tincr = 1.0 / sample_rate, *dstp = dst;
  5.     const double c = 2 * M_PI * 440.0;
  6.     /* generate sin tone with 440Hz frequency and duplicated channels */
  7.     for (i = 0; i < nb_samples; i++) {
  8.         *dstp =sin(c * *t);
  9.         for (j = 1; j < nb_channels; j++)
  10.             dstp[j] = dstp[0];
  11.         dstp += nb_channels;
  12.         *t += tincr;
  13.     }
  14. }
  15. int main(int argc, char **argv){    // 输入参数    int64_t src_ch_layout = AV_CH_LAYOUT_STEREO;    int src_rate = 48000;    enum AVSampleFormat src_sample_fmt = AV_SAMPLE_FMT_DBL;    int src_nb_channels = 0;    uint8_t **src_data = NULL;  // 二级指针    int src_linesize;    int src_nb_samples = 1024;    // 输出参数    int64_t dst_ch_layout = AV_CH_LAYOUT_STEREO;    int dst_rate = 44100;    enum AVSampleFormat dst_sample_fmt = AV_SAMPLE_FMT_S16;    int dst_nb_channels = 0;    uint8_t **dst_data = NULL;  //二级指针    int dst_linesize;    int dst_nb_samples;    int max_dst_nb_samples;    // 输出文件    const char *dst_filename = NULL;    // 生存输出的pcm到当地,然后播放验证    FILE *dst_file;    int dst_bufsize;    const char *fmt;    // 重采样实例    struct SwrContext *swr_ctx;    double t;    int ret;    if (argc != 2) {        fprintf(stderr, "Usage: %s output_file\n"                        "API example program to show how to resample an audio stream with libswresample.\n"                        "This program generates a series of audio frames, resamples them to a specified "                        "output format and rate and saves them to an output file named output_file.\n",                argv[0]);        exit(1);    }    dst_filename = argv[1];    dst_file = fopen(dst_filename, "wb");    if (!dst_file) {        fprintf(stderr, "Could not open destination file %s\n", dst_filename);        exit(1);    }    // 创建重采样器    /* create resampler context */    swr_ctx = swr_alloc();    if (!swr_ctx) {        fprintf(stderr, "Could not allocate resampler context\n");        ret = AVERROR(ENOMEM);        goto end;    }    // 设置重采样参数    /* set options */    // 输入参数    av_opt_set_int(swr_ctx, "in_channel_layout",    src_ch_layout, 0);    av_opt_set_int(swr_ctx, "in_sample_rate",       src_rate, 0);    av_opt_set_sample_fmt(swr_ctx, "in_sample_fmt", src_sample_fmt, 0);    // 输出参数    av_opt_set_int(swr_ctx, "out_channel_layout",    dst_ch_layout, 0);    av_opt_set_int(swr_ctx, "out_sample_rate",       dst_rate, 0);    av_opt_set_sample_fmt(swr_ctx, "out_sample_fmt", dst_sample_fmt, 0);    // 初始化重采样    /* initialize the resampling context */    if ((ret = swr_init(swr_ctx)) < 0) {        fprintf(stderr, "Failed to initialize the resampling context\n");        goto end;    }    /* allocate source and destination samples buffers */    // 计算出输入源的通道数量    src_nb_channels = av_get_channel_layout_nb_channels(src_ch_layout);    // 给输入源分配内存空间    ret = av_samples_alloc_array_and_samples(&src_data, &src_linesize, src_nb_channels,                                             src_nb_samples, src_sample_fmt, 0);    if (ret < 0) {        fprintf(stderr, "Could not allocate source samples\n");        goto end;    }    /* compute the number of converted samples: buffering is avoided     * ensuring that the output buffer will contain at least all the     * converted input samples */    // 计算输出采样数量    max_dst_nb_samples = dst_nb_samples =            av_rescale_rnd(src_nb_samples, dst_rate, src_rate, AV_ROUND_UP);    printf("max_dst_nb_samples = %d\n",max_dst_nb_samples);    /* buffer is going to be directly written to a rawaudio file, no alignment */    dst_nb_channels = av_get_channel_layout_nb_channels(dst_ch_layout);    // 分配输出缓存内存    ret = av_samples_alloc_array_and_samples(&dst_data, &dst_linesize, dst_nb_channels,                                             dst_nb_samples, dst_sample_fmt, 0);    printf("linesize = %d\n",dst_linesize);    if (ret < 0) {        fprintf(stderr, "Could not allocate destination samples\n");        goto end;    }    t = 0;    do {        /* generate synthetic audio */        // 生成输入源        fill_samples((double *)src_data[0], src_nb_samples, src_nb_channels, src_rate, &t);
  16.         /* compute destination number of samples */        int64_t delay = swr_get_delay(swr_ctx, src_rate);        dst_nb_samples = av_rescale_rnd(delay + src_nb_samples, dst_rate, src_rate, AV_ROUND_UP);        if (dst_nb_samples > max_dst_nb_samples) {            av_freep(&dst_data[0]);            ret = av_samples_alloc(dst_data, &dst_linesize, dst_nb_channels,                                   dst_nb_samples, dst_sample_fmt, 1);            if (ret < 0)****                break;            max_dst_nb_samples = dst_nb_samples;        }        //        int fifo_size = swr_get_out_samples(swr_ctx,src_nb_samples);        //        printf("fifo_size:%d\n", fifo_size);        //        if(fifo_size < 1024)        //            continue;        /* convert to destination format */        //        ret = swr_convert(swr_ctx, dst_data, dst_nb_samples, (const uint8_t **)src_data, src_nb_samples);        ret = swr_convert(swr_ctx, dst_data, dst_nb_samples, (const uint8_t **)src_data, src_nb_samples);        if (ret < 0) {            fprintf(stderr, "Error while converting\n");            goto end;        }        dst_bufsize = av_samples_get_buffer_size(&dst_linesize, dst_nb_channels,                                                 ret, dst_sample_fmt, 1);        if (dst_bufsize < 0) {            fprintf(stderr, "Could not get sample buffer size\n");            goto end;        }        printf("t:%f in:%d out:%d\n", t, src_nb_samples, ret);        fwrite(dst_data[0], 1, dst_bufsize, dst_file);    } while (t < 10);    ret = swr_convert(swr_ctx, dst_data, dst_nb_samples, NULL, 0);    if (ret < 0) {        fprintf(stderr, "Error while converting\n");        goto end;    }    dst_bufsize = av_samples_get_buffer_size(&dst_linesize, dst_nb_channels,                                             ret, dst_sample_fmt, 1);    if (dst_bufsize < 0) {        fprintf(stderr, "Could not get sample buffer size\n");        goto end;    }    printf("dst_bufsize = %d\n",dst_bufsize);    printf("flush in:%d out:%d\n", 0, ret);    fwrite(dst_data[0], 1, dst_bufsize, dst_file);    if ((ret = get_format_from_sample_fmt(&fmt, dst_sample_fmt)) < 0)        goto end;    fprintf(stderr, "Resampling succeeded. Play the output file with the command:\n"                    "ffplay -f %s -channel_layout %"PRId64" -channels %d -ar %d %s\n",            fmt, dst_ch_layout, dst_nb_channels, dst_rate, dst_filename);end:    fclose(dst_file);    if (src_data)        av_freep(&src_data[0]);    av_freep(&src_data);    if (dst_data)        av_freep(&dst_data[0]);    av_freep(&dst_data);    swr_free(&swr_ctx);    return ret < 0;}
复制代码
更多资料:https://github.com/0voice
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表