mono_blend.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright (C) 2015 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. //#define LOG_NDEBUG 0
  17. #define LOG_TAG "audio_utils_mono_blend"
  18. #include <math.h>
  19. #include <log/log.h>
  20. #include <audio_utils/limiter.h>
  21. #include <audio_utils/mono_blend.h>
  22. // TODO: Speed up for special case of 2 channels?
  23. void mono_blend(void *buf, audio_format_t format, size_t channelCount, size_t frames, bool limit) {
  24. if (channelCount < 2) {
  25. return;
  26. }
  27. switch (format) {
  28. case AUDIO_FORMAT_PCM_16_BIT: {
  29. int16_t *out = (int16_t *)buf;
  30. for (size_t i = 0; i < frames; ++i) {
  31. const int16_t *in = out;
  32. int accum = 0;
  33. for (size_t j = 0; j < channelCount; ++j) {
  34. accum += *in++;
  35. }
  36. accum /= channelCount; // round to 0
  37. for (size_t j = 0; j < channelCount; ++j) {
  38. *out++ = accum;
  39. }
  40. }
  41. } break;
  42. case AUDIO_FORMAT_PCM_FLOAT: {
  43. float *out = (float *)buf;
  44. const float recipdiv = 1. / channelCount;
  45. for (size_t i = 0; i < frames; ++i) {
  46. const float *in = out;
  47. float accum = 0;
  48. for (size_t j = 0; j < channelCount; ++j) {
  49. accum += *in++;
  50. }
  51. if (limit && channelCount == 2) {
  52. accum = limiter(accum * M_SQRT1_2);
  53. } else {
  54. accum *= recipdiv;
  55. }
  56. for (size_t j = 0; j < channelCount; ++j) {
  57. *out++ = accum;
  58. }
  59. }
  60. } break;
  61. default:
  62. ALOGE("mono_blend: invalid format %d", format);
  63. break;
  64. }
  65. }