Roman Kiryanov | 2ab979a | 2020-07-17 19:07:03 -0700 | [diff] [blame] | 1 | /* |
| 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 | |
| 21 | namespace android { |
| 22 | namespace hardware { |
| 23 | namespace audio { |
Mikhail Naganov | 70fb69f | 2022-01-27 20:00:41 +0000 | [diff] [blame] | 24 | namespace CPP_VERSION { |
Roman Kiryanov | 2ab979a | 2020-07-17 19:07:03 -0700 | [diff] [blame] | 25 | namespace implementation { |
| 26 | namespace aops { |
| 27 | |
| 28 | void 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; |
| 62 | l7: STEP; |
| 63 | l6: STEP; |
| 64 | l5: STEP; |
| 65 | l4: STEP; |
| 66 | l3: STEP; |
| 67 | l2: STEP; |
| 68 | l1: STEP; |
| 69 | } |
| 70 | |
| 71 | #undef STEP |
| 72 | } |
| 73 | |
| 74 | } // namespace aops |
| 75 | } // namespace implementation |
Mikhail Naganov | 70fb69f | 2022-01-27 20:00:41 +0000 | [diff] [blame] | 76 | } // namespace CPP_VERSION |
Roman Kiryanov | 2ab979a | 2020-07-17 19:07:03 -0700 | [diff] [blame] | 77 | } // namespace audio |
| 78 | } // namespace hardware |
| 79 | } // namespace android |