blob: 8415109875178ad1fdffe7b2e2b8287b2fbc4c5a [file] [log] [blame]
Andy Hung8bfe6a42015-12-18 17:37:19 -08001/*
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
Glenn Kastence746682020-06-24 12:46:43 -070017#include <assert.h>
Glenn Kasten715183b2016-01-27 17:21:35 -080018#include <math.h>
Glenn Kasten715183b2016-01-27 17:21:35 -080019#include <audio_utils/limiter.h>
Glenn Kasten7370d352018-10-30 09:01:36 -070020#include <audio_utils/mono_blend.h>
Andy Hung8bfe6a42015-12-18 17:37:19 -080021
22// TODO: Speed up for special case of 2 channels?
Glenn Kasten715183b2016-01-27 17:21:35 -080023void mono_blend(void *buf, audio_format_t format, size_t channelCount, size_t frames, bool limit) {
24 if (channelCount < 2) {
25 return;
26 }
Andy Hung8bfe6a42015-12-18 17:37:19 -080027 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 }
Glenn Kasten715183b2016-01-27 17:21:35 -080051 if (limit && channelCount == 2) {
52 accum = limiter(accum * M_SQRT1_2);
53 } else {
54 accum *= recipdiv;
55 }
Andy Hung8bfe6a42015-12-18 17:37:19 -080056 for (size_t j = 0; j < channelCount; ++j) {
57 *out++ = accum;
58 }
59 }
60 } break;
61 default:
Glenn Kastence746682020-06-24 12:46:43 -070062 assert(false);
Andy Hung8bfe6a42015-12-18 17:37:19 -080063 break;
64 }
65}