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.h>
18 #include <cinttypes>
19 #include <cmath>
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 "kiss_fftr.h"
26 
27 #define LOG_TAG "[AudioWorld]"
28 
29 #ifdef CHRE_NANOAPP_INTERNAL
30 namespace chre {
31 namespace {
32 #endif  // CHRE_NANOAPP_INTERNAL
33 
34 using chre::Milliseconds;
35 using chre::Nanoseconds;
36 
37 //! The number of frequencies to generate an FFT over.
38 constexpr size_t kNumFrequencies = 128;
39 
40 //! State for Kiss FFT and logging.
41 uint8_t gKissFftBuffer[4096];
42 kiss_fftr_cfg gKissFftConfig;
43 kiss_fft_cpx gKissFftOutput[(kNumFrequencies / 2) + 1];
44 Milliseconds gFirstAudioEventTimestamp = Milliseconds(0);
45 
46 /**
47  * Returns a graphical representation of a uint16_t value.
48  *
49  * @param value the value to visualize.
50  * @return a character that visually represents the value.
51  */
getFftCharForValue(uint16_t value)52 char getFftCharForValue(uint16_t value) {
53   constexpr uint16_t kFftLowLimit = 128;
54   constexpr uint16_t kFftMedLimit = 256;
55   constexpr uint16_t kFftHighLimit = 512;  // Texas Hold'em ༼⁰o⁰;༽
56   constexpr uint16_t kFftVeryHighLimit = 1024;
57 
58   if (value < kFftLowLimit) {
59     return ' ';
60   } else if (value >= kFftLowLimit && value < kFftMedLimit) {
61     return '_';
62   } else if (value >= kFftMedLimit && value < kFftHighLimit) {
63     return '.';
64   } else if (value >= kFftHighLimit && value < kFftVeryHighLimit) {
65     return 'x';
66   } else {
67     return 'X';
68   }
69 }
70 
71 /**
72  * Initializes Kiss FFT.
73  */
initKissFft()74 void initKissFft() {
75   size_t kissFftBufferSize = sizeof(gKissFftBuffer);
76   gKissFftConfig = kiss_fftr_alloc(kNumFrequencies, false,
77                                    gKissFftBuffer, &kissFftBufferSize);
78   if (gKissFftConfig == NULL) {
79     LOGE("Failed to init Kiss FFT, needs minimum %zu buffer size",
80          kissFftBufferSize);
81   } else {
82     LOGI("Initialized Kiss FFT, using %zu/%zu of the buffer",
83          kissFftBufferSize, sizeof(gKissFftBuffer));
84   }
85 }
86 
87 /**
88  * Logs an audio data event with an FFT visualization of the received audio
89  * data.
90  *
91  * @param event the audio data event to log.
92  */
handleAudioDataEvent(const struct chreAudioDataEvent * event)93 void handleAudioDataEvent(const struct chreAudioDataEvent *event) {
94   kiss_fftr(gKissFftConfig, event->samplesS16, gKissFftOutput);
95 
96   char fftStr[ARRAY_SIZE(gKissFftOutput) + 1];
97   fftStr[ARRAY_SIZE(gKissFftOutput)] = '\0';
98 
99   for (size_t i = 0; i < ARRAY_SIZE(gKissFftOutput); i++) {
100     float value = sqrtf(powf(gKissFftOutput[i].r, 2)
101         + powf(gKissFftOutput[i].i, 2));
102     fftStr[i] = getFftCharForValue(static_cast<uint16_t>(value));
103   }
104 
105   Milliseconds timestamp = Milliseconds(Nanoseconds(event->timestamp));
106   if (gFirstAudioEventTimestamp == Milliseconds(0)) {
107     gFirstAudioEventTimestamp = timestamp;
108   }
109 
110   Milliseconds adjustedTimestamp = timestamp - gFirstAudioEventTimestamp;
111   LOGD("Audio data - FFT [%s] at %" PRIu64 "ms with %" PRIu32 " samples",
112        fftStr, adjustedTimestamp.getMilliseconds(), event->sampleCount);
113 }
114 
handleAudioSamplingChangeEvent(const struct chreAudioSourceStatusEvent * event)115 void handleAudioSamplingChangeEvent(
116     const struct chreAudioSourceStatusEvent *event) {
117   LOGD("Audio sampling status event for handle %" PRIu32 ", suspended: %d",
118        event->handle, event->status.suspended);
119 }
120 
nanoappStart()121 bool nanoappStart() {
122   LOGI("Started");
123 
124   struct chreAudioSource audioSource;
125   for (uint32_t i = 0; chreAudioGetSource(i, &audioSource); i++) {
126     LOGI("Found audio source '%s' with %" PRIu32 "Hz %s data",
127          audioSource.name, audioSource.sampleRate,
128          chre::getChreAudioFormatString(audioSource.format));
129     LOGI("  buffer duration: [%" PRIu64 "ns, %" PRIu64 "ns]",
130         audioSource.minBufferDuration, audioSource.maxBufferDuration);
131 
132     if (i == 0) {
133       // Only request audio data from the first source, but continue discovery.
134       if (chreAudioConfigureSource(i, true,
135           audioSource.minBufferDuration, audioSource.minBufferDuration)) {
136         LOGI("Requested audio from handle %" PRIu32 " successfully", i);
137       } else {
138         LOGE("Failed to request audio from handle %" PRIu32, i);
139       }
140     }
141   }
142 
143   initKissFft();
144   return true;
145 }
146 
nanoappHandleEvent(uint32_t senderInstanceId,uint16_t eventType,const void * eventData)147 void nanoappHandleEvent(uint32_t senderInstanceId,
148                         uint16_t eventType,
149                         const void *eventData) {
150   switch (eventType) {
151     case CHRE_EVENT_AUDIO_DATA:
152       handleAudioDataEvent(
153           static_cast<const struct chreAudioDataEvent *>(eventData));
154       break;
155     case CHRE_EVENT_AUDIO_SAMPLING_CHANGE:
156       handleAudioSamplingChangeEvent(
157           static_cast<const struct chreAudioSourceStatusEvent *>(eventData));
158       break;
159     default:
160       LOGW("Unknown event received");
161       break;
162   }
163 }
164 
nanoappEnd()165 void nanoappEnd() {
166   LOGI("Stopped");
167 }
168 
169 #ifdef CHRE_NANOAPP_INTERNAL
170 }  // anonymous namespace
171 }  // namespace chre
172 
173 #include "chre/util/nanoapp/app_id.h"
174 #include "chre/platform/static_nanoapp_init.h"
175 
176 CHRE_STATIC_NANOAPP_INIT(AudioWorld, chre::kAudioWorldAppId, 0);
177 #endif  // CHRE_NANOAPP_INTERNAL
178