resample_pcm.cpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #include "resample_pcm.h"
  2. #include "error_define.h"
  3. #include "log_helper.h"
  4. namespace am {
  5. resample_pcm::resample_pcm()
  6. {
  7. _sample_src = NULL;
  8. _sample_dst = NULL;
  9. _ctx = NULL;
  10. }
  11. resample_pcm::~resample_pcm()
  12. {
  13. cleanup();
  14. }
  15. int resample_pcm::init(const SAMPLE_SETTING *sample_src,
  16. const SAMPLE_SETTING *sample_dst,
  17. int *resapmled_frame_size)
  18. {
  19. int err = AE_NO;
  20. do {
  21. _sample_src = (SAMPLE_SETTING *) malloc(sizeof(SAMPLE_SETTING));
  22. _sample_dst = (SAMPLE_SETTING *) malloc(sizeof(SAMPLE_SETTING));
  23. memcpy(_sample_src, sample_src, sizeof(SAMPLE_SETTING));
  24. memcpy(_sample_dst, sample_dst, sizeof(SAMPLE_SETTING));
  25. _ctx = swr_alloc_set_opts(NULL,
  26. _sample_dst->channel_layout,
  27. _sample_dst->fmt,
  28. _sample_dst->sample_rate,
  29. _sample_src->channel_layout,
  30. _sample_src->fmt,
  31. _sample_src->sample_rate,
  32. 0,
  33. NULL);
  34. if (_ctx == NULL) {
  35. err = AE_RESAMPLE_INIT_FAILED;
  36. break;
  37. }
  38. int ret = swr_init(_ctx);
  39. if (ret < 0) {
  40. err = AE_RESAMPLE_INIT_FAILED;
  41. break;
  42. }
  43. *resapmled_frame_size = av_samples_get_buffer_size(NULL,
  44. _sample_dst->nb_channels,
  45. _sample_dst->nb_samples,
  46. _sample_dst->fmt,
  47. 1);
  48. } while (0);
  49. if (err != AE_NO) {
  50. cleanup();
  51. al_fatal("resample pcm init failed:%d", err);
  52. }
  53. return err;
  54. }
  55. int resample_pcm::convert(const uint8_t *src, int src_len, uint8_t *dst, int dst_len)
  56. {
  57. uint8_t *out[2] = {0};
  58. out[0] = dst;
  59. out[1] = dst + dst_len / 2;
  60. const uint8_t *in1[2] = {src, NULL};
  61. /*
  62. uint8_t *in[2] = { 0 };
  63. in[0] = (uint8_t*)src;
  64. in[1] = (uint8_t*)(src + src_len / 2);
  65. AVFrame *sample_frame = av_frame_alloc();
  66. sample_frame->nb_samples = 1024;
  67. sample_frame->channel_layout = _sample_dst->channel_layout;
  68. sample_frame->format = _sample_dst->fmt;
  69. sample_frame->sample_rate = _sample_dst->sample_rate;
  70. avcodec_fill_audio_frame(sample_frame, _sample_dst->nb_channels, _sample_dst->fmt, src, src_len, 0);
  71. */
  72. return swr_convert(_ctx, out, _sample_dst->nb_samples, in1, _sample_src->nb_samples);
  73. }
  74. void resample_pcm::cleanup()
  75. {
  76. if (_sample_src)
  77. free(_sample_src);
  78. if (_sample_dst)
  79. free(_sample_dst);
  80. if (_ctx)
  81. swr_free(&_ctx);
  82. }
  83. } // namespace am