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 #include "chre/platform/platform_audio.h"
18 
19 #include <cinttypes>
20 
21 #include "chre/core/audio_request_manager.h"
22 #include "chre/core/audio_util.h"
23 #include "chre/core/event_loop_manager.h"
24 #include "chre/platform/fatal_error.h"
25 #include "chre/platform/log.h"
26 #include "chre/platform/system_time.h"
27 
28 namespace chre {
29 
30 namespace {
31 
32 //! The fixed sampling rate for audio data when running CHRE on Android.
33 constexpr uint32_t kAndroidAudioSampleRate = 16000;
34 
35 //! The minimum buffer size in samples.
36 constexpr uint32_t kAndroidAudioMinBufferSize = kAndroidAudioSampleRate / 10;
37 
38 //! The maximum buffer size in samples.
39 constexpr uint32_t kAndroidAudioMaxBufferSize = kAndroidAudioSampleRate * 10;
40 
41 }  // namespace
42 
audioReadCallback(void * cookie)43 void PlatformAudioBase::audioReadCallback(void *cookie) {
44   auto *platformAudio = static_cast<PlatformAudio *>(cookie);
45 
46   auto &dataEvent = platformAudio->mDataEvent;
47   Nanoseconds samplingTime = AudioUtil::getDurationFromSampleCountAndRate(
48       platformAudio->mNumSamples, kAndroidAudioSampleRate);
49   dataEvent.timestamp =
50       (SystemTime::getMonotonicTime() - samplingTime).toRawNanoseconds();
51 
52   if (dataEvent.format == CHRE_AUDIO_DATA_FORMAT_16_BIT_SIGNED_PCM) {
53     uint32_t intervalNumSamples = AudioUtil::getSampleCountFromRateAndDuration(
54         kAndroidAudioSampleRate, platformAudio->mEventDelay);
55 
56     // Determine how much new audio data is required to be read from the device.
57     // Samples that are already buffered by this implementation may be reused.
58     int16_t *audioBuffer = platformAudio->mBuffer.data();
59     uint32_t readAmount = platformAudio->mNumSamples;
60     if (intervalNumSamples > platformAudio->mNumSamples) {
61       uint32_t seekAmount = intervalNumSamples - platformAudio->mNumSamples;
62       audioBuffer = &platformAudio->mBuffer.data()[seekAmount];
63       readAmount = platformAudio->mNumSamples - seekAmount;
64     }
65 
66     // Perform a blocking read. A timeout of 1 nanoasecond is passed here to
67     // ensure that we read exactly the amount of requested audio frames. The
68     // timer ensures that we wait approximately long enough to read the
69     // requested number of samples and the timeout ensures that they match
70     // exactly.
71     int32_t framesRead =
72         AAudioStream_read(platformAudio->mStream, audioBuffer, readAmount, 1);
73     if (framesRead != static_cast<int32_t>(platformAudio->mNumSamples)) {
74       FATAL_ERROR("Failed to read requested number of audio samples");
75     } else {
76       EventLoopManagerSingleton::get()
77           ->getAudioRequestManager()
78           .handleAudioDataEvent(&dataEvent);
79     }
80   } else {
81     FATAL_ERROR("Unimplemented data format");
82   }
83 }
84 
PlatformAudio()85 PlatformAudio::PlatformAudio() {
86   if (!mTimer.init()) {
87     FATAL_ERROR("Failed to initialize audio timer");
88   }
89 
90   aaudio_result_t result = AAudio_createStreamBuilder(&mStreamBuilder);
91   if (result != AAUDIO_OK) {
92     FATAL_ERROR("Failed to create audio stream builder with %" PRId32, result);
93   }
94 
95   AAudioStreamBuilder_setDirection(mStreamBuilder, AAUDIO_DIRECTION_INPUT);
96   AAudioStreamBuilder_setSharingMode(mStreamBuilder,
97                                      AAUDIO_SHARING_MODE_SHARED);
98   AAudioStreamBuilder_setSampleRate(mStreamBuilder, kAndroidAudioSampleRate);
99   AAudioStreamBuilder_setChannelCount(mStreamBuilder, 1);
100   AAudioStreamBuilder_setFormat(mStreamBuilder, AAUDIO_FORMAT_PCM_I16);
101   AAudioStreamBuilder_setBufferCapacityInFrames(mStreamBuilder,
102                                                 kAndroidAudioMaxBufferSize);
103 
104   result = AAudioStreamBuilder_openStream(mStreamBuilder, &mStream);
105   if (result != AAUDIO_OK) {
106     FATAL_ERROR("Failed to create audio stream with %" PRId32, result);
107   }
108 
109   int32_t bufferSize = AAudioStream_getBufferCapacityInFrames(mStream);
110   LOGD("Created audio stream with %" PRId32 " frames buffer size", bufferSize);
111 
112   mMinBufferDuration = AudioUtil::getDurationFromSampleCountAndRate(
113                            kAndroidAudioMinBufferSize, kAndroidAudioSampleRate)
114                            .toRawNanoseconds();
115   mMaxBufferDuration = AudioUtil::getDurationFromSampleCountAndRate(
116                            bufferSize, kAndroidAudioSampleRate)
117                            .toRawNanoseconds();
118 
119   result = AAudioStream_requestStart(mStream);
120   if (result != AAUDIO_OK) {
121     FATAL_ERROR("Failed to start audio stream with %" PRId32, result);
122   }
123 
124   mBuffer.resize(bufferSize);
125   initAudioDataEvent();
126 }
127 
~PlatformAudio()128 PlatformAudio::~PlatformAudio() {
129   AAudioStream_close(mStream);
130   AAudioStreamBuilder_delete(mStreamBuilder);
131 }
132 
init()133 void PlatformAudio::init() {
134   // TODO: Implement this.
135 }
136 
setHandleEnabled(uint32_t handle,bool enabled)137 void PlatformAudio::setHandleEnabled(uint32_t handle, bool enabled) {
138   // TODO: Implement this.
139 }
140 
requestAudioDataEvent(uint32_t handle,uint32_t numSamples,Nanoseconds eventDelay)141 bool PlatformAudio::requestAudioDataEvent(uint32_t handle, uint32_t numSamples,
142                                           Nanoseconds eventDelay) {
143   mNumSamples = numSamples;
144   mEventDelay = eventDelay;
145   mDataEvent.sampleCount = numSamples;
146   return mTimer.set(audioReadCallback, this, eventDelay);
147 }
148 
cancelAudioDataEventRequest(uint32_t handle)149 void PlatformAudio::cancelAudioDataEventRequest(uint32_t handle) {
150   mTimer.cancel();
151 }
152 
releaseAudioDataEvent(struct chreAudioDataEvent * event)153 void PlatformAudio::releaseAudioDataEvent(struct chreAudioDataEvent *event) {}
154 
getSourceCount()155 size_t PlatformAudio::getSourceCount() {
156   // Hardcoded at one as the Android platform only surfaces the default mic.
157   return 1;
158 }
159 
getAudioSource(uint32_t handle,chreAudioSource * audioSource) const160 bool PlatformAudio::getAudioSource(uint32_t handle,
161                                    chreAudioSource *audioSource) const {
162   bool success = false;
163   if (handle == 0) {
164     audioSource->name = "Default Android Audio Input";
165     audioSource->sampleRate = kAndroidAudioSampleRate;
166     audioSource->minBufferDuration = mMinBufferDuration;
167     audioSource->maxBufferDuration = mMaxBufferDuration;
168     audioSource->format = mDataEvent.format;
169     success = true;
170   }
171 
172   return success;
173 }
174 
initAudioDataEvent()175 void PlatformAudioBase::initAudioDataEvent() {
176   mDataEvent.version = CHRE_AUDIO_DATA_EVENT_VERSION;
177   memset(mDataEvent.reserved, 0, sizeof(mDataEvent.reserved));
178   mDataEvent.handle = 0;
179   mDataEvent.sampleRate = kAndroidAudioSampleRate;
180   mDataEvent.format = CHRE_AUDIO_DATA_FORMAT_16_BIT_SIGNED_PCM;
181   mDataEvent.samplesS16 = mBuffer.data();
182 }
183 
184 }  // namespace chre
185