blob: 55f0461ee0fd50e381d7bb4656007d4ee04cf1d0 [file] [log] [blame]
Roman Kiryanov2ab979a2020-07-17 19:07:03 -07001/*
2 * Copyright (C) 2020 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 <string.h>
18#include <math.h>
19#include "audio_ops.h"
20
21namespace android {
22namespace hardware {
23namespace audio {
Mikhail Naganov70fb69f2022-01-27 20:00:41 +000024namespace CPP_VERSION {
Roman Kiryanov2ab979a2020-07-17 19:07:03 -070025namespace implementation {
26namespace aops {
27
28void multiplyByVolume(const float volume, int16_t *a, const size_t n) {
29 constexpr int_fast32_t kDenominator = 32768;
30 const int_fast32_t numerator =
31 static_cast<int_fast32_t>(round(volume * kDenominator));
32
33 if (numerator >= kDenominator) {
34 return; // (numerator > kDenominator) is not expected
35 } else if (numerator <= 0) {
36 memset(a, 0, n * sizeof(*a));
37 return; // (numerator < 0) is not expected
38 }
39
40 int16_t *end = a + n;
41
42 // The unroll code below is to save on CPU branch instructions.
43 // 8 is arbitrary chosen.
44
45#define STEP \
46 *a = (*a * numerator + kDenominator / 2) / kDenominator; \
47 ++a
48
49 switch (n % 8) {
50 case 7: goto l7;
51 case 6: goto l6;
52 case 5: goto l5;
53 case 4: goto l4;
54 case 3: goto l3;
55 case 2: goto l2;
56 case 1: goto l1;
57 default: break;
58 }
59
60 while (a < end) {
61 STEP;
62l7: STEP;
63l6: STEP;
64l5: STEP;
65l4: STEP;
66l3: STEP;
67l2: STEP;
68l1: STEP;
69 }
70
71#undef STEP
72}
73
74} // namespace aops
75} // namespace implementation
Mikhail Naganov70fb69f2022-01-27 20:00:41 +000076} // namespace CPP_VERSION
Roman Kiryanov2ab979a2020-07-17 19:07:03 -070077} // namespace audio
78} // namespace hardware
79} // namespace android