resample_pcm.cpp 2.9 KB

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