resample_pcm.cpp 2.1 KB

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