blob: ad19fb1d09586f0a086f07e627bb9136ba1d673f [file] [log] [blame]
Vlad Popa2900c0a2022-10-24 13:38:00 +02001/*
2**
3** Copyright 2022, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18// #define LOG_NDEBUG 0
19#define LOG_TAG "SoundDoseManager"
20
21#include "SoundDoseManager.h"
22
Vlad Popa1d5f0d52022-12-18 12:21:26 +010023#if !defined(BACKEND_NDK)
24#define BACKEND_NDK
25#endif
26
27#include "android/media/SoundDoseRecord.h"
Vlad Popa2900c0a2022-10-24 13:38:00 +020028#include <android-base/stringprintf.h>
Vlad Popa1d5f0d52022-12-18 12:21:26 +010029#include <media/AidlConversionCppNdk.h>
30#include <cinttypes>
Vlad Popa2900c0a2022-10-24 13:38:00 +020031#include <time.h>
Vlad Popa4defd0b2022-11-06 14:22:31 +010032#include <utils/Log.h>
Vlad Popa2900c0a2022-10-24 13:38:00 +020033
34namespace android {
35
Vlad Popa1d5f0d52022-12-18 12:21:26 +010036using aidl::android::media::audio::common::AudioDevice;
37using aidl::android::media::audio::common::AudioDeviceAddress;
38
Vlad Popa2900c0a2022-10-24 13:38:00 +020039namespace {
40
41int64_t getMonotonicSecond() {
42 struct timespec now_ts;
43 if (clock_gettime(CLOCK_MONOTONIC, &now_ts) != 0) {
44 ALOGE("%s: cannot get timestamp", __func__);
45 return -1;
46 }
47 return now_ts.tv_sec;
48}
49
50} // namespace
51
Vlad Popaf09e93f2022-10-31 16:27:12 +010052sp<audio_utils::MelProcessor> SoundDoseManager::getOrCreateProcessorForDevice(
Vlad Popa4defd0b2022-11-06 14:22:31 +010053 audio_port_handle_t deviceId, audio_io_handle_t streamHandle, uint32_t sampleRate,
54 size_t channelCount, audio_format_t format) {
Vlad Popa2900c0a2022-10-24 13:38:00 +020055 std::lock_guard _l(mLock);
56
Vlad Popa1d5f0d52022-12-18 12:21:26 +010057 if (mHalSoundDose != nullptr) {
58 ALOGW("%s: using HAL MEL computation, no MelProcessor needed.", __func__);
59 return nullptr;
60 }
61
Vlad Popaf09e93f2022-10-31 16:27:12 +010062 auto streamProcessor = mActiveProcessors.find(streamHandle);
63 sp<audio_utils::MelProcessor> processor;
Vlad Popa4defd0b2022-11-06 14:22:31 +010064 if (streamProcessor != mActiveProcessors.end() &&
65 (processor = streamProcessor->second.promote())) {
Vlad Popa2900c0a2022-10-24 13:38:00 +020066 ALOGV("%s: found callback for stream %d", __func__, streamHandle);
Vlad Popaf09e93f2022-10-31 16:27:12 +010067 processor->setDeviceId(deviceId);
Vlad Popae3fd1c22022-11-07 21:03:18 +010068 processor->setOutputRs2(mRs2Value);
Vlad Popaf09e93f2022-10-31 16:27:12 +010069 return processor;
Vlad Popa2900c0a2022-10-24 13:38:00 +020070 } else {
71 ALOGV("%s: creating new callback for device %d", __func__, streamHandle);
Vlad Popa4defd0b2022-11-06 14:22:31 +010072 sp<audio_utils::MelProcessor> melProcessor = sp<audio_utils::MelProcessor>::make(
73 sampleRate, channelCount, format, *this, deviceId, mRs2Value);
Vlad Popaf09e93f2022-10-31 16:27:12 +010074 mActiveProcessors[streamHandle] = melProcessor;
75 return melProcessor;
Vlad Popa2900c0a2022-10-24 13:38:00 +020076 }
77}
78
Vlad Popa1d5f0d52022-12-18 12:21:26 +010079bool SoundDoseManager::setHalSoundDoseInterface(const std::shared_ptr<ISoundDose>& halSoundDose) {
80 ALOGV("%s", __func__);
81
82 {
83 std::lock_guard _l(mLock);
84
85 mHalSoundDose = halSoundDose;
86 if (halSoundDose == nullptr) {
87 ALOGI("%s: passed ISoundDose object is null, switching to internal CSD", __func__);
88 return false;
89 }
90
91 if (!mHalSoundDose->setOutputRs2(mRs2Value).isOk()) {
92 ALOGW("%s: Cannot set RS2 value for momentary exposure %f",
93 __func__,
94 mRs2Value);
95 }
96
97 // initialize the HAL sound dose callback lazily
98 if (mHalSoundDoseCallback == nullptr) {
99 mHalSoundDoseCallback =
100 ndk::SharedRefBase::make<HalSoundDoseCallback>(this);
101 }
102 }
103
104 auto status = halSoundDose->registerSoundDoseCallback(mHalSoundDoseCallback);
105 if (!status.isOk()) {
106 // Not a warning since this can happen if the callback was registered before
107 ALOGI("%s: Cannot register HAL sound dose callback with status message: %s",
108 __func__,
109 status.getMessage());
110 }
111
112 return true;
113}
114
Vlad Popa4defd0b2022-11-06 14:22:31 +0100115void SoundDoseManager::setOutputRs2(float rs2Value) {
Vlad Popa2900c0a2022-10-24 13:38:00 +0200116 ALOGV("%s", __func__);
Vlad Popaf09e93f2022-10-31 16:27:12 +0100117 std::lock_guard _l(mLock);
118
Vlad Popae3fd1c22022-11-07 21:03:18 +0100119 mRs2Value = rs2Value;
Vlad Popa1d5f0d52022-12-18 12:21:26 +0100120 if (mHalSoundDose != nullptr) {
121 // using the HAL sound dose interface
122 if (!mHalSoundDose->setOutputRs2(mRs2Value).isOk()) {
123 ALOGE("%s: Cannot set RS2 value for momentary exposure %f", __func__, mRs2Value);
124 }
125 return;
126 }
Vlad Popae3fd1c22022-11-07 21:03:18 +0100127
Vlad Popaf09e93f2022-10-31 16:27:12 +0100128 for (auto& streamProcessor : mActiveProcessors) {
129 sp<audio_utils::MelProcessor> processor = streamProcessor.second.promote();
130 if (processor != nullptr) {
Vlad Popae3fd1c22022-11-07 21:03:18 +0100131 status_t result = processor->setOutputRs2(mRs2Value);
Vlad Popaf09e93f2022-10-31 16:27:12 +0100132 if (result != NO_ERROR) {
Vlad Popae3fd1c22022-11-07 21:03:18 +0100133 ALOGW("%s: could not set RS2 value %f for stream %d", __func__, mRs2Value,
Vlad Popaf09e93f2022-10-31 16:27:12 +0100134 streamProcessor.first);
135 }
136 }
137 }
138}
139
Vlad Popa4defd0b2022-11-06 14:22:31 +0100140void SoundDoseManager::removeStreamProcessor(audio_io_handle_t streamHandle) {
Vlad Popaf09e93f2022-10-31 16:27:12 +0100141 std::lock_guard _l(mLock);
142 auto callbackToRemove = mActiveProcessors.find(streamHandle);
Vlad Popa4defd0b2022-11-06 14:22:31 +0100143 if (callbackToRemove != mActiveProcessors.end()) {
Vlad Popaf09e93f2022-10-31 16:27:12 +0100144 mActiveProcessors.erase(callbackToRemove);
145 }
146}
147
Vlad Popa1d5f0d52022-12-18 12:21:26 +0100148audio_port_handle_t SoundDoseManager::getIdForAudioDevice(const AudioDevice& audioDevice) const {
149 std::lock_guard _l(mLock);
150
151 audio_devices_t type;
152 std::string address;
153 auto result = aidl::android::aidl2legacy_AudioDevice_audio_device(
154 audioDevice, &type, &address);
155 if (result != NO_ERROR) {
156 ALOGE("%s: could not convert from AudioDevice to AudioDeviceTypeAddr", __func__);
157 return AUDIO_PORT_HANDLE_NONE;
158 }
159
160 auto adt = AudioDeviceTypeAddr(type, address);
161 auto deviceIt = mActiveDevices.find(adt);
162 if (deviceIt == mActiveDevices.end()) {
163 ALOGE("%s: could not find port id for device %s", __func__, adt.toString().c_str());
164 return AUDIO_PORT_HANDLE_NONE;
165 }
166 return deviceIt->second;
167}
168
169void SoundDoseManager::mapAddressToDeviceId(const AudioDeviceTypeAddr& adt,
170 const audio_port_handle_t deviceId) {
171 std::lock_guard _l(mLock);
172 ALOGI("%s: map address: %s to device id: %d", __func__, adt.toString().c_str(), deviceId);
173 mActiveDevices[adt] = deviceId;
174}
175
176void SoundDoseManager::clearMapDeviceIdEntries(audio_port_handle_t deviceId) {
177 std::lock_guard _l(mLock);
178 for (auto activeDevice = mActiveDevices.begin(); activeDevice != mActiveDevices.end();) {
179 if (activeDevice->second == deviceId) {
180 ALOGI("%s: clear mapping addr: %s to deviceId: %d",
181 __func__, activeDevice->first.toString().c_str(), deviceId);
182 activeDevice = mActiveDevices.erase(activeDevice);
183 continue;
184 }
185 ++activeDevice;
186 }
187 return;
188}
189
190ndk::ScopedAStatus SoundDoseManager::HalSoundDoseCallback::onMomentaryExposureWarning(
191 float in_currentDbA, const AudioDevice& in_audioDevice) {
192 auto soundDoseManager = mSoundDoseManager.promote();
193 if (soundDoseManager == nullptr) {
194 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
195 }
196
197 auto id = soundDoseManager->getIdForAudioDevice(in_audioDevice);
198 if (id == AUDIO_PORT_HANDLE_NONE) {
199 ALOGW("%s: no mapped id for audio device with type %d and address %s",
200 __func__, in_audioDevice.type.type,
201 in_audioDevice.address.get<AudioDeviceAddress::id>().c_str());
202 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
203 }
204 soundDoseManager->onMomentaryExposure(in_currentDbA, id);
205
206 return ndk::ScopedAStatus::ok();
207}
208
209ndk::ScopedAStatus SoundDoseManager::HalSoundDoseCallback::onNewMelValues(
210 const ISoundDose::IHalSoundDoseCallback::MelRecord& in_melRecord,
211 const AudioDevice& in_audioDevice) {
212 auto soundDoseManager = mSoundDoseManager.promote();
213 if (soundDoseManager == nullptr) {
214 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
215 }
216 auto id = soundDoseManager->getIdForAudioDevice(in_audioDevice);
217 if (id == AUDIO_PORT_HANDLE_NONE) {
218 ALOGW("%s: no mapped id for audio device with type %d and address %s",
219 __func__, in_audioDevice.type.type,
220 in_audioDevice.address.get<AudioDeviceAddress::id>().c_str());
221 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
222 }
223 // TODO: introduce timestamp in onNewMelValues callback
224 soundDoseManager->onNewMelValues(in_melRecord.melValues, 0,
225 in_melRecord.melValues.size(), id);
226
227 return ndk::ScopedAStatus::ok();
228}
229
Vlad Popae3fd1c22022-11-07 21:03:18 +0100230void SoundDoseManager::SoundDose::binderDied(__unused const wp<IBinder>& who) {
231 ALOGV("%s", __func__);
232
233 auto soundDoseManager = mSoundDoseManager.promote();
234 if (soundDoseManager != nullptr) {
235 soundDoseManager->resetSoundDose();
236 }
237}
238
239binder::Status SoundDoseManager::SoundDose::setOutputRs2(float value) {
240 ALOGV("%s", __func__);
241 auto soundDoseManager = mSoundDoseManager.promote();
242 if (soundDoseManager != nullptr) {
243 soundDoseManager->setOutputRs2(value);
244 }
245 return binder::Status::ok();
246}
247
248binder::Status SoundDoseManager::SoundDose::resetCsd(
249 float currentCsd, const std::vector<media::SoundDoseRecord>& records) {
250 ALOGV("%s", __func__);
251 auto soundDoseManager = mSoundDoseManager.promote();
252 if (soundDoseManager != nullptr) {
253 soundDoseManager->resetCsd(currentCsd, records);
254 }
255 return binder::Status::ok();
256}
257
Vlad Popa91930462022-12-20 22:42:48 +0100258binder::Status SoundDoseManager::SoundDose::getOutputRs2(float* value) {
259 ALOGV("%s", __func__);
260 auto soundDoseManager = mSoundDoseManager.promote();
261 if (soundDoseManager != nullptr) {
262 std::lock_guard _l(soundDoseManager->mLock);
263 *value = soundDoseManager->mRs2Value;
264 }
265 return binder::Status::ok();
266}
267
268binder::Status SoundDoseManager::SoundDose::getCsd(float* value) {
269 ALOGV("%s", __func__);
270 auto soundDoseManager = mSoundDoseManager.promote();
271 if (soundDoseManager != nullptr) {
272 *value = soundDoseManager->mMelAggregator->getCsd();
273 }
274 return binder::Status::ok();
275}
276
277binder::Status SoundDoseManager::SoundDose::forceUseFrameworkMel(bool useFrameworkMel) {
278 ALOGV("%s", __func__);
279 auto soundDoseManager = mSoundDoseManager.promote();
280 if (soundDoseManager != nullptr) {
281 soundDoseManager->setUseFrameworkMel(useFrameworkMel);
282 }
283 return binder::Status::ok();
284}
285
286binder::Status SoundDoseManager::SoundDose::forceComputeCsdOnAllDevices(
287 bool computeCsdOnAllDevices) {
288 ALOGV("%s", __func__);
289 auto soundDoseManager = mSoundDoseManager.promote();
290 if (soundDoseManager != nullptr) {
291 soundDoseManager->setComputeCsdOnAllDevices(computeCsdOnAllDevices);
292 }
293 return binder::Status::ok();
294}
295
296void SoundDoseManager::setUseFrameworkMel(bool useFrameworkMel) {
297 std::lock_guard _l(mLock);
298 mUseFrameworkMel = useFrameworkMel;
299}
300
301bool SoundDoseManager::useFrameworkMel() const {
302 std::lock_guard _l(mLock);
303 return mUseFrameworkMel;
304}
305
306void SoundDoseManager::setComputeCsdOnAllDevices(bool computeCsdOnAllDevices) {
307 std::lock_guard _l(mLock);
308 mComputeCsdOnAllDevices = computeCsdOnAllDevices;
309}
310
311bool SoundDoseManager::computeCsdOnAllDevices() const {
312 std::lock_guard _l(mLock);
313 return mComputeCsdOnAllDevices;
314}
315
Vlad Popae3fd1c22022-11-07 21:03:18 +0100316void SoundDoseManager::resetSoundDose() {
317 std::lock_guard lock(mLock);
318 mSoundDose = nullptr;
319}
320
321void SoundDoseManager::resetCsd(float currentCsd,
322 const std::vector<media::SoundDoseRecord>& records) {
323 std::lock_guard lock(mLock);
324 std::vector<audio_utils::CsdRecord> resetRecords;
325 for (const auto& record : records) {
326 resetRecords.emplace_back(record.timestamp, record.duration, record.value,
327 record.averageMel);
328 }
329
330 mMelAggregator->reset(currentCsd, resetRecords);
331}
332
Vlad Popa4defd0b2022-11-06 14:22:31 +0100333void SoundDoseManager::onNewMelValues(const std::vector<float>& mels, size_t offset, size_t length,
334 audio_port_handle_t deviceId) const {
Vlad Popaf09e93f2022-10-31 16:27:12 +0100335 ALOGV("%s", __func__);
Vlad Popa2900c0a2022-10-24 13:38:00 +0200336
Vlad Popa4defd0b2022-11-06 14:22:31 +0100337 sp<media::ISoundDoseCallback> soundDoseCallback;
338 std::vector<audio_utils::CsdRecord> records;
339 float currentCsd;
340 {
341 std::lock_guard _l(mLock);
Vlad Popa2900c0a2022-10-24 13:38:00 +0200342
Vlad Popa4defd0b2022-11-06 14:22:31 +0100343 int64_t timestampSec = getMonotonicSecond();
344
345 // only for internal callbacks
346 records = mMelAggregator->aggregateAndAddNewMelRecord(audio_utils::MelRecord(
347 deviceId, std::vector<float>(mels.begin() + offset, mels.begin() + offset + length),
348 timestampSec - length));
349
350 currentCsd = mMelAggregator->getCsd();
351 }
352
353 soundDoseCallback = getSoundDoseCallback();
354
355 if (records.size() > 0 && soundDoseCallback != nullptr) {
356 std::vector<media::SoundDoseRecord> newRecordsToReport;
357 for (const auto& record : records) {
358 newRecordsToReport.emplace_back(csdRecordToSoundDoseRecord(record));
359 }
360
361 soundDoseCallback->onNewCsdValue(currentCsd, newRecordsToReport);
362 }
Vlad Popa2900c0a2022-10-24 13:38:00 +0200363}
364
Vlad Popa4defd0b2022-11-06 14:22:31 +0100365sp<media::ISoundDoseCallback> SoundDoseManager::getSoundDoseCallback() const {
366 std::lock_guard _l(mLock);
Vlad Popae3fd1c22022-11-07 21:03:18 +0100367 if (mSoundDose == nullptr) {
368 return nullptr;
369 }
370
371 return mSoundDose->mSoundDoseCallback;
Vlad Popa4defd0b2022-11-06 14:22:31 +0100372}
373
374void SoundDoseManager::onMomentaryExposure(float currentMel, audio_port_handle_t deviceId) const {
375 ALOGV("%s: Momentary exposure for device %d triggered: %f MEL", __func__, deviceId, currentMel);
Vlad Popa63f047e2022-11-05 14:09:19 +0100376
Vlad Popae3fd1c22022-11-07 21:03:18 +0100377 auto soundDoseCallback = getSoundDoseCallback();
Vlad Popa63f047e2022-11-05 14:09:19 +0100378 if (soundDoseCallback != nullptr) {
Vlad Popae3fd1c22022-11-07 21:03:18 +0100379 soundDoseCallback->onMomentaryExposure(currentMel, deviceId);
Vlad Popa63f047e2022-11-05 14:09:19 +0100380 }
381}
382
Vlad Popae3fd1c22022-11-07 21:03:18 +0100383sp<media::ISoundDose> SoundDoseManager::getSoundDoseInterface(
384 const sp<media::ISoundDoseCallback>& callback) {
Vlad Popa63f047e2022-11-05 14:09:19 +0100385 ALOGV("%s: Register ISoundDoseCallback", __func__);
386
387 std::lock_guard _l(mLock);
Vlad Popae3fd1c22022-11-07 21:03:18 +0100388 if (mSoundDose == nullptr) {
389 mSoundDose = sp<SoundDose>::make(this, callback);
390 }
391 return mSoundDose;
Vlad Popaf09e93f2022-10-31 16:27:12 +0100392}
393
Vlad Popa4defd0b2022-11-06 14:22:31 +0100394std::string SoundDoseManager::dump() const {
Vlad Popa2900c0a2022-10-24 13:38:00 +0200395 std::string output;
Vlad Popaf09e93f2022-10-31 16:27:12 +0100396 mMelAggregator->foreachCsd([&output](audio_utils::CsdRecord csdRecord) {
Vlad Popa2900c0a2022-10-24 13:38:00 +0200397 base::StringAppendF(&output,
398 "CSD %f with average MEL %f in interval [%" PRId64 ", %" PRId64 "]",
Vlad Popa4defd0b2022-11-06 14:22:31 +0100399 csdRecord.value, csdRecord.averageMel, csdRecord.timestamp,
Vlad Popa2900c0a2022-10-24 13:38:00 +0200400 csdRecord.timestamp + csdRecord.duration);
401 base::StringAppendF(&output, "\n");
402 });
403
404 base::StringAppendF(&output, "\nCached Mel Records:\n");
Vlad Popaf09e93f2022-10-31 16:27:12 +0100405 mMelAggregator->foreachCachedMel([&output](const audio_utils::MelRecord& melRecord) {
Vlad Popa2900c0a2022-10-24 13:38:00 +0200406 base::StringAppendF(&output, "Continuous MELs for portId=%d, ", melRecord.portId);
407 base::StringAppendF(&output, "starting at timestamp %" PRId64 ": ", melRecord.timestamp);
408
409 for (const auto& mel : melRecord.mels) {
410 base::StringAppendF(&output, "%.2f ", mel);
411 }
412 base::StringAppendF(&output, "\n");
413 });
414
415 return output;
416}
417
418size_t SoundDoseManager::getCachedMelRecordsSize() const {
Vlad Popaf09e93f2022-10-31 16:27:12 +0100419 return mMelAggregator->getCachedMelRecordsSize();
Vlad Popa2900c0a2022-10-24 13:38:00 +0200420}
421
Vlad Popa4defd0b2022-11-06 14:22:31 +0100422media::SoundDoseRecord SoundDoseManager::csdRecordToSoundDoseRecord(
423 const audio_utils::CsdRecord& legacy) {
424 media::SoundDoseRecord soundDoseRecord{};
425 soundDoseRecord.timestamp = legacy.timestamp;
426 soundDoseRecord.duration = legacy.duration;
427 soundDoseRecord.value = legacy.value;
428 soundDoseRecord.averageMel = legacy.averageMel;
429 return soundDoseRecord;
430}
431
Vlad Popa2900c0a2022-10-24 13:38:00 +0200432} // namespace android