xref: /aosp_15_r20/system/chre/apps/audio_world/audio_world.cc (revision 84e339476a462649f82315436d70fd732297a399)
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 <cinttypes>
18 #include <cmath>
19 #include <cstddef>
20 
21 #include "chre/util/macros.h"
22 #include "chre/util/nanoapp/audio.h"
23 #include "chre/util/nanoapp/log.h"
24 #include "chre/util/time.h"
25 #include "chre_api/chre.h"
26 #include "kiss_fftr.h"
27 
28 #define LOG_TAG "[AudioWorld]"
29 
30 #ifdef CHRE_NANOAPP_INTERNAL
31 namespace chre {
32 namespace {
33 #endif  // CHRE_NANOAPP_INTERNAL
34 
35 using chre::Milliseconds;
36 using chre::Nanoseconds;
37 
38 //! The number of frequencies to generate an FFT over.
39 constexpr size_t kNumFrequencies = 128;
40 
41 //! True if audio has successfully been requested.
42 bool gAudioRequested = false;
43 
44 //! The requested audio handle.
45 uint32_t gAudioHandle;
46 
47 //! State for Kiss FFT and logging.
48 alignas(std::max_align_t) uint8_t gKissFftBuffer[4096];
49 kiss_fftr_cfg gKissFftConfig;
50 kiss_fft_cpx gKissFftOutput[(kNumFrequencies / 2) + 1];
51 Milliseconds gFirstAudioEventTimestamp = Milliseconds(0);
52 
53 /**
54  * Returns a graphical representation of a uint16_t value.
55  *
56  * @param value the value to visualize.
57  * @return a character that visually represents the value.
58  */
getFftCharForValue(uint16_t value)59 char getFftCharForValue(uint16_t value) {
60   constexpr uint16_t kFftLowLimit = 128;
61   constexpr uint16_t kFftMedLimit = 256;
62   constexpr uint16_t kFftHighLimit = 512;  // Texas Hold'em ༼⁰o⁰;༽
63   constexpr uint16_t kFftVeryHighLimit = 1024;
64 
65   if (value < kFftLowLimit) {
66     return ' ';
67   } else if (value >= kFftLowLimit && value < kFftMedLimit) {
68     return '_';
69   } else if (value >= kFftMedLimit && value < kFftHighLimit) {
70     return '.';
71   } else if (value >= kFftHighLimit && value < kFftVeryHighLimit) {
72     return 'x';
73   } else {
74     return 'X';
75   }
76 }
77 
78 /**
79  * Initializes Kiss FFT.
80  */
initKissFft()81 void initKissFft() {
82   size_t kissFftBufferSize = sizeof(gKissFftBuffer);
83   gKissFftConfig = kiss_fftr_alloc(kNumFrequencies, false, gKissFftBuffer,
84                                    &kissFftBufferSize);
85   if (gKissFftConfig == NULL) {
86     LOGE("Failed to init Kiss FFT, needs minimum %zu buffer size",
87          kissFftBufferSize);
88   } else {
89     LOGI("Initialized Kiss FFT, using %zu/%zu of the buffer", kissFftBufferSize,
90          sizeof(gKissFftBuffer));
91   }
92 }
93 
94 /**
95  * Logs an audio data event with an FFT visualization of the received audio
96  * data.
97  *
98  * @param event the audio data event to log.
99  */
handleAudioDataEvent(const struct chreAudioDataEvent * event)100 void handleAudioDataEvent(const struct chreAudioDataEvent *event) {
101   kiss_fftr(gKissFftConfig, event->samplesS16, gKissFftOutput);
102 
103   char fftStr[ARRAY_SIZE(gKissFftOutput) + 1];
104   fftStr[ARRAY_SIZE(gKissFftOutput)] = '\0';
105 
106   for (size_t i = 0; i < ARRAY_SIZE(gKissFftOutput); i++) {
107     float value =
108         sqrtf(powf(gKissFftOutput[i].r, 2) + powf(gKissFftOutput[i].i, 2));
109     fftStr[i] = getFftCharForValue(static_cast<uint16_t>(value));
110   }
111 
112   Milliseconds timestamp = Milliseconds(Nanoseconds(event->timestamp));
113   if (gFirstAudioEventTimestamp == Milliseconds(0)) {
114     gFirstAudioEventTimestamp = timestamp;
115   }
116 
117   Milliseconds adjustedTimestamp = timestamp - gFirstAudioEventTimestamp;
118   LOGD("Audio data - FFT [%s] at %" PRIu64 "ms with %" PRIu32 " samples",
119        fftStr, adjustedTimestamp.getMilliseconds(), event->sampleCount);
120 }
121 
handleAudioSamplingChangeEvent(const struct chreAudioSourceStatusEvent * event)122 void handleAudioSamplingChangeEvent(
123     const struct chreAudioSourceStatusEvent *event) {
124   LOGD("Audio sampling status event for handle %" PRIu32 ", suspended: %d",
125        event->handle, event->status.suspended);
126 }
127 
handleAudioSettingChangedNotification(const struct chreUserSettingChangedEvent * event)128 void handleAudioSettingChangedNotification(
129     const struct chreUserSettingChangedEvent *event) {
130   // The following checks on event and setting are primarily meant for
131   // debugging and/or bring-up. Production nanoapps should not need to worry
132   // about these scenarios since CHRE guarantees that out-of-memory conditions
133   // are caught during event allocation before they're posted, and the setting
134   // is guaranteed to be a member of enum chreUserSettingState.
135   if (event != nullptr) {
136     if (event->setting != CHRE_USER_SETTING_MICROPHONE) {
137       LOGE("Unexpected setting ID: %u", event->setting);
138     } else {
139       LOGI("Microphone settings notification: status change to %d",
140            static_cast<int8_t>(event->settingState));
141     }
142   } else {
143     LOGE("Null event data for settings changed event");
144   }
145 }
146 
nanoappStart()147 bool nanoappStart() {
148   LOGI("Started");
149 
150   struct chreAudioSource audioSource;
151   for (uint32_t i = 0; chreAudioGetSource(i, &audioSource); i++) {
152     LOGI("Found audio source '%s' with %" PRIu32 "Hz %s data", audioSource.name,
153          audioSource.sampleRate,
154          chre::getChreAudioFormatString(audioSource.format));
155     LOGI("  buffer duration: [%" PRIu64 "ns, %" PRIu64 "ns]",
156          audioSource.minBufferDuration, audioSource.maxBufferDuration);
157 
158     if (i == 0) {
159       // Only request audio data from the first source, but continue discovery.
160       if (chreAudioConfigureSource(i, true, audioSource.minBufferDuration,
161                                    audioSource.minBufferDuration)) {
162         gAudioRequested = true;
163         gAudioHandle = i;
164         LOGI("Requested audio from handle %" PRIu32 " successfully", i);
165       } else {
166         LOGE("Failed to request audio from handle %" PRIu32, i);
167       }
168     }
169   }
170 
171   initKissFft();
172 
173   int8_t settingState = chreUserSettingGetState(CHRE_USER_SETTING_MICROPHONE);
174   LOGD("Microphone setting status: %d", settingState);
175 
176   chreUserSettingConfigureEvents(CHRE_USER_SETTING_MICROPHONE,
177                                  true /* enable */);
178 
179   return true;
180 }
181 
nanoappHandleEvent(uint32_t senderInstanceId,uint16_t eventType,const void * eventData)182 void nanoappHandleEvent(uint32_t senderInstanceId, uint16_t eventType,
183                         const void *eventData) {
184   UNUSED_VAR(senderInstanceId);
185 
186   switch (eventType) {
187     case CHRE_EVENT_AUDIO_DATA:
188       handleAudioDataEvent(
189           static_cast<const struct chreAudioDataEvent *>(eventData));
190       break;
191     case CHRE_EVENT_AUDIO_SAMPLING_CHANGE:
192       handleAudioSamplingChangeEvent(
193           static_cast<const struct chreAudioSourceStatusEvent *>(eventData));
194       break;
195 
196     case CHRE_EVENT_SETTING_CHANGED_MICROPHONE:
197       handleAudioSettingChangedNotification(
198           static_cast<const struct chreUserSettingChangedEvent *>(eventData));
199       break;
200 
201     default:
202       LOGW("Unknown event received");
203       break;
204   }
205 }
206 
nanoappEnd()207 void nanoappEnd() {
208   if (gAudioRequested) {
209     chreAudioConfigureSource(gAudioHandle, false /* enable */,
210                              0 /* bufferDuration */, 0 /* deliveryInterval */);
211   }
212 
213   chreUserSettingConfigureEvents(CHRE_USER_SETTING_MICROPHONE,
214                                  false /* enable */);
215 
216   LOGI("Stopped");
217 }
218 
219 #ifdef CHRE_NANOAPP_INTERNAL
220 }  // anonymous namespace
221 }  // namespace chre
222 
223 #include "chre/platform/static_nanoapp_init.h"
224 #include "chre/util/nanoapp/app_id.h"
225 #include "chre/util/system/napp_permissions.h"
226 
227 CHRE_STATIC_NANOAPP_INIT(AudioWorld, chre::kAudioWorldAppId, 0,
228                          chre::NanoappPermissions::CHRE_PERMS_AUDIO);
229 #endif  // CHRE_NANOAPP_INTERNAL
230