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 17 #include <assert.h> 18 #include <math.h> 19 #include <audio_utils/limiter.h> 20 #include <audio_utils/mono_blend.h> 21 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 assert(false); 63 break; 64 } 65 } 66