blob: 0ace0776e16cb5181923065d9c95ffef990e0aeb [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
17//#define LOG_NDEBUG 0
Glenn Kasten3ba430c2017-02-23 16:55:16 -080018#define LOG_TAG "audio_utils_mono_blend"
Andy Hung8bfe6a42015-12-18 17:37:19 -080019
Glenn Kasten715183b2016-01-27 17:21:35 -080020#include <math.h>
Glenn Kasten3ba430c2017-02-23 16:55:16 -080021#include <audio_utils/mono_blend.h>
Tri Vo82d94502017-06-23 15:42:32 -070022#include <log/log.h>
Glenn Kasten715183b2016-01-27 17:21:35 -080023#include <audio_utils/limiter.h>
Andy Hung8bfe6a42015-12-18 17:37:19 -080024
25// TODO: Speed up for special case of 2 channels?
Glenn Kasten715183b2016-01-27 17:21:35 -080026void mono_blend(void *buf, audio_format_t format, size_t channelCount, size_t frames, bool limit) {
27 if (channelCount < 2) {
28 return;
29 }
Andy Hung8bfe6a42015-12-18 17:37:19 -080030 switch (format) {
31 case AUDIO_FORMAT_PCM_16_BIT: {
32 int16_t *out = (int16_t *)buf;
33 for (size_t i = 0; i < frames; ++i) {
34 const int16_t *in = out;
35 int accum = 0;
36 for (size_t j = 0; j < channelCount; ++j) {
37 accum += *in++;
38 }
39 accum /= channelCount; // round to 0
40 for (size_t j = 0; j < channelCount; ++j) {
41 *out++ = accum;
42 }
43 }
44 } break;
45 case AUDIO_FORMAT_PCM_FLOAT: {
46 float *out = (float *)buf;
47 const float recipdiv = 1. / channelCount;
48 for (size_t i = 0; i < frames; ++i) {
49 const float *in = out;
50 float accum = 0;
51 for (size_t j = 0; j < channelCount; ++j) {
52 accum += *in++;
53 }
Glenn Kasten715183b2016-01-27 17:21:35 -080054 if (limit && channelCount == 2) {
55 accum = limiter(accum * M_SQRT1_2);
56 } else {
57 accum *= recipdiv;
58 }
Andy Hung8bfe6a42015-12-18 17:37:19 -080059 for (size_t j = 0; j < channelCount; ++j) {
60 *out++ = accum;
61 }
62 }
63 } break;
64 default:
65 ALOGE("mono_blend: invalid format %d", format);
66 break;
67 }
68}