• FFmpeg音频重采样API(libswresample)


    目录

    1. 参考
    2. lswr功能介绍
    3. lswr使用说明
    4. 示例代码

    1. 参考

    2. lswr功能介绍

    FFmpeg中重采样的功能由libswresample(后面简写为lswr)提供。
    lswr提供了高度优化的转换音频的采样频率、声道格式或样本格式的功能。

    功能说明:

    • 采样频率转换:对音频的采样频率进行转换的处理,例如把音频从一个高的44100Hz的采样频率转换到8000Hz。从高采样频率到低采样频率的音频转换是一个有损的过程。API提供了多种的重采样选项和算法。
    • 声道格式转换:对音频的声道格式进行转换的处理,例如立体声转换为单声道。当输入通道不能映射到输出流时,这个过程是有损的,因为它涉及不同的增益因素和混合。
    • 样本格式转换:对音频的样本格式进行转换的处理,例如把s16的PCM数据转换为s8格式或者f32的PCM数据。此外提供了Packed和Planar包装格式之间相互转换的功能,Packed和Planar的区别见PCM音频数据 - 知乎

    此外,还提供了一些其他音频转换的功能如拉伸和填充,通过专门的设置来启用。

    3. lswr使用说明

    重采样的处理流程:

    1. 创建上下文环境:重采样过程上下文环境为SwrContext数据结构。
    2. 参数设置:转换的参数设置到SwrContext中。
    3. SwrContext初始化:swr_init()。
    4. 分配样本数据内存空间:使用av_samples_alloc_array_and_samples、av_samples_alloc等工具函数。
    5. 开启重采样转换:通过重复地调用swr_convert来完成。
    6. 重采样转换完成, 释放相关资源:通过swr_free()释放SwrContext。

    下面是示例程序的一个流程图:

    函数说明:

    • swr_alloc() :创建SwrContext对象。
    • av_opt_set_*():设置输入和输出音频的信息。
    • swr_init(): 初始化SwrContext。
    • av_samples_alloc_array_and_samples:根据音频格式分配相应大小的内存空间。
    • av_samples_alloc:根据音频格式分配相应大小的内存空间。用于转换过程中对输出内存大小进行调整。
    • swr_convert:进行重采样转换。

    3.1 创建上下文环境

    重采样过程上下文环境为SwrContext数据结构(SwrContext的定义没有对外暴露)。

    创建SwrContext的方式有两种:

    1. swr_alloc() : 创建SwrContext之后再通过AVOptions的API来设置参数。
    2. swr_alloc_set_opts():在创建SwrContext的同时设置必要的参数。

    【CSDN文末扫码进君 羊,免费分享】资料包括《Andoird音视频开发必备手册+音视频学习视频+学习文档资料包+大厂面试真题+2022最新学习路线图》等等 

     

    两个函数的定义如下:

    1. struct SwrContext* swr_alloc()
    2. struct SwrContext* swr_alloc_set_opts(struct SwrContext * s, //如果为NULL则创建一个新的SwrContext,否则对已有的SwrContext进行参数设置
    3. int64_t out_ch_layout, //输出的声道格式,AV_CH_LAYOUT_*
    4. enum AVSampleFormat out_sample_fmt,
    5. int out_sample_rate,
    6. int64_t in_ch_layout,
    7. enum AVSampleFormat in_sample_fmt,
    8. int in_sample_rate,
    9. int log_offset,
    10. void * log_ctx
    11. )

     

    3.2 参数设置

    参数设置的方式有两种:

    1. AVOptions的API
    2. swr_alloc_set_opts():如果第一个参数为NULL则创建一个新的SwrContext,否则对已有的SwrContext进行参数设置。

    假定要进行如下的重采样转换:

    1. “f32le格式、采样频率48kHz、5.1声道格式”的PCM数据
    2. 转换为
    3. “s16le格式、采样频率44.1kHz、立体声格式”的PCM数据

    swr_alloc()的使用方式如下所示:

    1. SwrContext *swr = swr_alloc();
    2. av_opt_set_channel_layout(swr, "in_channel_layout", AV_CH_LAYOUT_5POINT1, 0);
    3. av_opt_set_channel_layou(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_FLPT, 0);
    7. av_opt_set_sample_fmt(swr, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0);

    3.3 SwrContext初始化:swr_init()

    参数设置好之后必须调用swr_init()对SwrContext进行初始化。

    如果需要修改转换的参数:

    1. 重新进行参数设置。
    2. 再次调用swr_init()。

    3.4 分配样本数据内存空间

    转换之前需要分配内存空间用于保存重采样的输出数据,内存空间的大小跟通道个数、样本格式需要、容纳的样本个数都有关系。libavutil中的samples处理API提供了一些函数方便管理样本数据,例如av_samples_alloc()函数用于分配存储sample的buffer。

    av_sample_alloc()的定义如下:

    1. /**
    2. * @param[out] audio_data 输出数组,每个元素是指向一个通道的数据的指针。
    3. * @param[out] linesize aligned size for audio buffer(s), may be NULL
    4. * @param nb_channels 通道的个数。
    5. * @param nb_samples 每个通道的样本个数。
    6. * @param align buffer size alignment (0 = default, 1 = no alignment)
    7. * @return 成功返回大于0的数,错误返回负数。
    8. */
    9. int av_samples_alloc(uint8_t **audio_data, int *linesize, int nb_channels,
    10. int nb_samples, enum AVSampleFormat sample_fmt, int align);

    3.5 开启重采样转换

    重采样转换是通过重复地调用swr_convert()来完成的。

    swr_convert()函数的定义如下:

    1. * @param out 输出缓冲区,当PCM数据为Packed包装格式时,只有out[0]会填充有数据。
    2. * @param out_count 每个通道可存储输出PCM数据的sample数量。
    3. * @param in 输入缓冲区,当PCM数据为Packed包装格式时,只有in[0]需要填充有数据。
    4. * @param in_count 输入PCM数据中每个通道可用的sample数量。
    5. *
    6. * @return 返回每个通道输出的sample数量,发生错误的时候返回负数。
    7. */
    8. int swr_convert(struct SwrContext *s, uint8_t **out, int out_count,
    9. const uint8_t **in , int in_count);

    说明:

    1. 如果没有提供足够的空间用于保存输出数据,采样数据会缓存在swr中。可以通过 swr_get_out_samples()来获取下一次调用swr_convert在给定输入样本数量下输出样本数量的上限,来提供足够的空间。
    2. 如果是采样频率转换,转换完成后采样数据可能会缓存在swr中,它期待你提供更多的输入数据。
    3. 如果实际上并不需要更多输入数据,通过调用swr_convert(),其中参数in_count设置为0来获取缓存在swr中的数据。
    4. 转换结束之后需要冲刷swr_context的缓冲区,通过调用swr_convert(),其中参数in设置为NULL,参数in_count设置为0。

    下面的代码演示了重采样转换处理的流程,其中假定依照上面的参数设置、get_input()和handle_output()已经定义好。

    1. uint8_t **input;
    2. int in_samples;
    3. while (get_input(&input, &in_samples)) {
    4. uint8_t *output;
    5. int out_samples = av_rescale_rnd(swr_get_delay(swr, 48000) +
    6. in_samples, 44100, 48000, AV_ROUND_UP);
    7. av_samples_alloc(&output, NULL, 2, out_samples,
    8. AV_SAMPLE_FMT_S16, 0);
    9. out_samples = swr_convert(swr, &output, out_samples,
    10. input, in_samples);
    11. handle_output(output, out_samples);
    12. av_freep(&output);
    13. }

    3.6 重采样转换完成, 释放相关资源

    转换结束之后,需要调用av_freep(&audio_data[0])来释放内存。

    4. 示例代码

    [3] 示例的代码。

    1. /**
    2. * @example resampling_audio.c
    3. * libswresample API use example.
    4. */
    5. #include
    6. #include
    7. #include
    8. #include
    9. static int get_format_from_sample_fmt(const char **fmt,
    10. enum AVSampleFormat sample_fmt)
    11. {
    12. int i;
    13. struct sample_fmt_entry {
    14. enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le;
    15. } sample_fmt_entries[] = {
    16. { AV_SAMPLE_FMT_U8, "u8", "u8" },
    17. { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
    18. { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
    19. { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
    20. { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
    21. };
    22. *fmt = NULL;
    23. for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
    24. struct sample_fmt_entry *entry = &sample_fmt_entries[i];
    25. if (sample_fmt == entry->sample_fmt) {
    26. *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
    27. return 0;
    28. }
    29. }
    30. fprintf(stderr,
    31. "Sample format %s not supported as output format\n",
    32. av_get_sample_fmt_name(sample_fmt));
    33. return AVERROR(EINVAL);
    34. }
    35. /**
    36. * Fill dst buffer with nb_samples, generated starting from t.
    37. */
    38. static void fill_samples(double *dst, int nb_samples, int nb_channels, int sample_rate, double *t)
    39. {
    40. int i, j;
    41. double tincr = 1.0 / sample_rate, *dstp = dst;
    42. const double c = 2 * M_PI * 440.0;
    43. /* generate sin tone with 440Hz frequency and duplicated channels */
    44. for (i = 0; i < nb_samples; i++) {
    45. *dstp = sin(c * *t);
    46. for (j = 1; j < nb_channels; j++)
    47. dstp[j] = dstp[0];
    48. dstp += nb_channels;
    49. *t += tincr;
    50. }
    51. }
    52. int main(int argc, char **argv)
    53. {
    54. int64_t src_ch_layout = AV_CH_LAYOUT_STEREO, dst_ch_layout = AV_CH_LAYOUT_SURROUND;
    55. int src_rate = 48000, dst_rate = 44100;
    56. uint8_t **src_data = NULL, **dst_data = NULL;
    57. int src_nb_channels = 0, dst_nb_channels = 0;
    58. int src_linesize, dst_linesize;
    59. int src_nb_samples = 1024, dst_nb_samples, max_dst_nb_samples;
    60. enum AVSampleFormat src_sample_fmt = AV_SAMPLE_FMT_DBL, dst_sample_fmt = AV_SAMPLE_FMT_S16;
    61. const char *dst_filename = NULL;
    62. FILE *dst_file;
    63. int dst_bufsize;
    64. const char *fmt;
    65. struct SwrContext *swr_ctx;
    66. double t;
    67. int ret;
    68. if (argc != 2) {
    69. fprintf(stderr, "Usage: %s output_file\n"
    70. "API example program to show how to resample an audio stream with libswresample.\n"
    71. "This program generates a series of audio frames, resamples them to a specified "
    72. "output format and rate and saves them to an output file named output_file.\n",
    73. argv[0]);
    74. exit(1);
    75. }
    76. dst_filename = argv[1];
    77. dst_file = fopen(dst_filename, "wb");
    78. if (!dst_file) {
    79. fprintf(stderr, "Could not open destination file %s\n", dst_filename);
    80. exit(1);
    81. }
    82. /* create resampler context */
    83. swr_ctx = swr_alloc();
    84. if (!swr_ctx) {
    85. fprintf(stderr, "Could not allocate resampler context\n");
    86. ret = AVERROR(ENOMEM);
    87. goto end;
    88. }
    89. /* set options */
    90. av_opt_set_int(swr_ctx, "in_channel_layout", src_ch_layout, 0);
    91. av_opt_set_int(swr_ctx, "in_sample_rate", src_rate, 0);
    92. av_opt_set_sample_fmt(swr_ctx, "in_sample_fmt", src_sample_fmt, 0);
    93. av_opt_set_int(swr_ctx, "out_channel_layout", dst_ch_layout, 0);
    94. av_opt_set_int(swr_ctx, "out_sample_rate", dst_rate, 0);
    95. av_opt_set_sample_fmt(swr_ctx, "out_sample_fmt", dst_sample_fmt, 0);
    96. /* initialize the resampling context */
    97. if ((ret = swr_init(swr_ctx)) < 0) {
    98. fprintf(stderr, "Failed to initialize the resampling context\n");
    99. goto end;
    100. }
    101. /* allocate source and destination samples buffers */
    102. src_nb_channels = av_get_channel_layout_nb_channels(src_ch_layout);
    103. ret = av_samples_alloc_array_and_samples(&src_data, &src_linesize, src_nb_channels,
    104. src_nb_samples, src_sample_fmt, 0);
    105. if (ret < 0) {
    106. fprintf(stderr, "Could not allocate source samples\n");
    107. goto end;
    108. }
    109. /* compute the number of converted samples: buffering is avoided
    110. * ensuring that the output buffer will contain at least all the
    111. * converted input samples */
    112. max_dst_nb_samples = dst_nb_samples =
    113. av_rescale_rnd(src_nb_samples, dst_rate, src_rate, AV_ROUND_UP);
    114. /* buffer is going to be directly written to a rawaudio file, no alignment */
    115. dst_nb_channels = av_get_channel_layout_nb_channels(dst_ch_layout);
    116. ret = av_samples_alloc_array_and_samples(&dst_data, &dst_linesize, dst_nb_channels,
    117. dst_nb_samples, dst_sample_fmt, 0);
    118. if (ret < 0) {
    119. fprintf(stderr, "Could not allocate destination samples\n");
    120. goto end;
    121. }
    122. t = 0;
    123. do {
    124. /* generate synthetic audio */
    125. fill_samples((double *)src_data[0], src_nb_samples, src_nb_channels, src_rate, &t);
    126. /* compute destination number of samples */
    127. dst_nb_samples = av_rescale_rnd(swr_get_delay(swr_ctx, src_rate) +
    128. src_nb_samples, dst_rate, src_rate, AV_ROUND_UP);
    129. if (dst_nb_samples > max_dst_nb_samples) {
    130. av_freep(&dst_data[0]);
    131. ret = av_samples_alloc(dst_data, &dst_linesize, dst_nb_channels,
    132. dst_nb_samples, dst_sample_fmt, 1);
    133. if (ret < 0)
    134. break;
    135. max_dst_nb_samples = dst_nb_samples;
    136. }
    137. /* convert to destination format */
    138. ret = swr_convert(swr_ctx, dst_data, dst_nb_samples, (const uint8_t **)src_data, src_nb_samples);
    139. if (ret < 0) {
    140. fprintf(stderr, "Error while converting\n");
    141. goto end;
    142. }
    143. dst_bufsize = av_samples_get_buffer_size(&dst_linesize, dst_nb_channels,
    144. ret, dst_sample_fmt, 1);
    145. if (dst_bufsize < 0) {
    146. fprintf(stderr, "Could not get sample buffer size\n");
    147. goto end;
    148. }
    149. printf("t:%f in:%d out:%d\n", t, src_nb_samples, ret);
    150. fwrite(dst_data[0], 1, dst_bufsize, dst_file);
    151. } while (t < 10);
    152. if ((ret = get_format_from_sample_fmt(&fmt, dst_sample_fmt)) < 0)
    153. goto end;
    154. fprintf(stderr, "Resampling succeeded. Play the output file with the command:\n"
    155. "ffplay -f %s -channel_layout %"PRId64" -channels %d -ar %d %s\n",
    156. fmt, dst_ch_layout, dst_nb_channels, dst_rate, dst_filename);
    157. end:
    158. fclose(dst_file);
    159. if (src_data)
    160. av_freep(&src_data[0]);
    161. av_freep(&src_data);
    162. if (dst_data)
    163. av_freep(&dst_data[0]);
    164. av_freep(&dst_data);
    165. swr_free(&swr_ctx);
    166. return ret < 0;
    167. }

  • 相关阅读:
    C#正则表达式总结
    如何成功将 API 客户的 transformer 模型推理速度加快 100 倍
    rt-thread 之------fal移植
    SDRAM 控制器(三)——自动刷新模块
    根据店铺ID或店铺昵称或店铺链接获取阿里巴巴店铺所有商品数据接口|阿里巴巴店铺整店商品数据接口|阿里巴巴API接口
    Gem5 Bug Record
    .NET开源的简单、快速、强大的前后端分离后台权限管理系统
    gitlub 加载慢问题处理
    讲讲URL与URI的区别
    Kafka 核心源码解读【三】--Controller模块
  • 原文地址:https://blog.csdn.net/yinshipin007/article/details/125900312