1 /*
2  * Copyright (C) 2017 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 #ifndef CHRE_CORE_AUDIO_UTIL_H_
18 #define CHRE_CORE_AUDIO_UTIL_H_
19 
20 #include <cstdint>
21 
22 #include "chre/util/time.h"
23 
24 namespace chre {
25 
26 /**
27  * Class to define utility functions for CHRE audio.
28  */
29 class AudioUtil {
30  public:
31   /**
32    * A convenience function to convert sample count and sample rate into a time
33    * duration. It is illegal to call this function with a rate of zero.
34    *
35    * @param sampleCount The number of samples to convert to time at the provided
36    *        rate.
37    * @param sampleRate The rate to perform the time conversion at.
38    * @return The duration of time for these two parameters.
39    */
getDurationFromSampleCountAndRate(uint32_t sampleCount,uint32_t sampleRate)40   static constexpr Nanoseconds getDurationFromSampleCountAndRate(
41       uint32_t sampleCount, uint32_t sampleRate) {
42     // This function will overflow with high sample counts but does work for
43     // reasonable expected values.
44     //
45     // Example: 22050 * 1000000000 / 44100 = 500000000ns
46     return Nanoseconds((sampleCount * kOneSecondInNanoseconds) / sampleRate);
47   }
48 
49   /**
50    * A convenience function to convert sample rate and duration into a sample
51    * count. This can be used by platform implementations to ensure that the
52    * computed buffer sizes match those expected by CHRE.
53    *
54    * @param sampleRate The sample rate of the audio source.
55    * @param duration The duration of the buffer delivered.
56    * @return The number of samples given this configuration.
57    */
getSampleCountFromRateAndDuration(uint32_t sampleRate,Nanoseconds duration)58   static constexpr uint32_t getSampleCountFromRateAndDuration(
59       uint32_t sampleRate, Nanoseconds duration) {
60     // This function will overflow at high sample rates or extremely high
61     // durations, but does work for reasonable expected values.
62     //
63     // Example: 44100 * 60 seconds (in nanoseconds) fits into a uint64_t as an
64     // intermediate value before casting to uint32_t.
65     return static_cast<uint32_t>((sampleRate * duration.toRawNanoseconds()) /
66                                  kOneSecondInNanoseconds);
67   }
68 };
69 
70 }  // namespace chre
71 
72 #endif  // CHRE_CORE_AUDIO_UTIL_H_
73