blob: df6eb5b7e3f2cfe956644107572cd080db3bad05 [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
Vlad Popa3d6d39d2022-12-21 18:59:16 +0100197 std::shared_ptr<ISoundDose> halSoundDose;
198 soundDoseManager->getHalSoundDose(&halSoundDose);
199 if(halSoundDose == nullptr) {
200 ALOGW("%s: HAL sound dose interface deactivated. Ignoring", __func__);
201 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
202 }
203
Vlad Popa1d5f0d52022-12-18 12:21:26 +0100204 auto id = soundDoseManager->getIdForAudioDevice(in_audioDevice);
205 if (id == AUDIO_PORT_HANDLE_NONE) {
206 ALOGW("%s: no mapped id for audio device with type %d and address %s",
207 __func__, in_audioDevice.type.type,
208 in_audioDevice.address.get<AudioDeviceAddress::id>().c_str());
209 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
210 }
211 soundDoseManager->onMomentaryExposure(in_currentDbA, id);
212
213 return ndk::ScopedAStatus::ok();
214}
215
216ndk::ScopedAStatus SoundDoseManager::HalSoundDoseCallback::onNewMelValues(
217 const ISoundDose::IHalSoundDoseCallback::MelRecord& in_melRecord,
218 const AudioDevice& in_audioDevice) {
219 auto soundDoseManager = mSoundDoseManager.promote();
220 if (soundDoseManager == nullptr) {
221 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
222 }
Vlad Popa3d6d39d2022-12-21 18:59:16 +0100223
224 std::shared_ptr<ISoundDose> halSoundDose;
225 soundDoseManager->getHalSoundDose(&halSoundDose);
226 if(halSoundDose == nullptr) {
227 ALOGW("%s: HAL sound dose interface deactivated. Ignoring", __func__);
228 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
229 }
230
Vlad Popa1d5f0d52022-12-18 12:21:26 +0100231 auto id = soundDoseManager->getIdForAudioDevice(in_audioDevice);
232 if (id == AUDIO_PORT_HANDLE_NONE) {
233 ALOGW("%s: no mapped id for audio device with type %d and address %s",
234 __func__, in_audioDevice.type.type,
235 in_audioDevice.address.get<AudioDeviceAddress::id>().c_str());
236 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
237 }
238 // TODO: introduce timestamp in onNewMelValues callback
239 soundDoseManager->onNewMelValues(in_melRecord.melValues, 0,
240 in_melRecord.melValues.size(), id);
241
242 return ndk::ScopedAStatus::ok();
243}
244
Vlad Popae3fd1c22022-11-07 21:03:18 +0100245void SoundDoseManager::SoundDose::binderDied(__unused const wp<IBinder>& who) {
246 ALOGV("%s", __func__);
247
248 auto soundDoseManager = mSoundDoseManager.promote();
249 if (soundDoseManager != nullptr) {
250 soundDoseManager->resetSoundDose();
251 }
252}
253
254binder::Status SoundDoseManager::SoundDose::setOutputRs2(float value) {
255 ALOGV("%s", __func__);
256 auto soundDoseManager = mSoundDoseManager.promote();
257 if (soundDoseManager != nullptr) {
258 soundDoseManager->setOutputRs2(value);
259 }
260 return binder::Status::ok();
261}
262
263binder::Status SoundDoseManager::SoundDose::resetCsd(
264 float currentCsd, const std::vector<media::SoundDoseRecord>& records) {
265 ALOGV("%s", __func__);
266 auto soundDoseManager = mSoundDoseManager.promote();
267 if (soundDoseManager != nullptr) {
268 soundDoseManager->resetCsd(currentCsd, records);
269 }
270 return binder::Status::ok();
271}
272
Vlad Popa91930462022-12-20 22:42:48 +0100273binder::Status SoundDoseManager::SoundDose::getOutputRs2(float* value) {
274 ALOGV("%s", __func__);
275 auto soundDoseManager = mSoundDoseManager.promote();
276 if (soundDoseManager != nullptr) {
277 std::lock_guard _l(soundDoseManager->mLock);
278 *value = soundDoseManager->mRs2Value;
279 }
280 return binder::Status::ok();
281}
282
283binder::Status SoundDoseManager::SoundDose::getCsd(float* value) {
284 ALOGV("%s", __func__);
285 auto soundDoseManager = mSoundDoseManager.promote();
286 if (soundDoseManager != nullptr) {
287 *value = soundDoseManager->mMelAggregator->getCsd();
288 }
289 return binder::Status::ok();
290}
291
292binder::Status SoundDoseManager::SoundDose::forceUseFrameworkMel(bool useFrameworkMel) {
293 ALOGV("%s", __func__);
294 auto soundDoseManager = mSoundDoseManager.promote();
295 if (soundDoseManager != nullptr) {
296 soundDoseManager->setUseFrameworkMel(useFrameworkMel);
297 }
298 return binder::Status::ok();
299}
300
301binder::Status SoundDoseManager::SoundDose::forceComputeCsdOnAllDevices(
302 bool computeCsdOnAllDevices) {
303 ALOGV("%s", __func__);
304 auto soundDoseManager = mSoundDoseManager.promote();
305 if (soundDoseManager != nullptr) {
306 soundDoseManager->setComputeCsdOnAllDevices(computeCsdOnAllDevices);
307 }
308 return binder::Status::ok();
309}
310
311void SoundDoseManager::setUseFrameworkMel(bool useFrameworkMel) {
Vlad Popa3d6d39d2022-12-21 18:59:16 +0100312 // invalidate any HAL sound dose interface used
313 setHalSoundDoseInterface(nullptr);
314
Vlad Popa91930462022-12-20 22:42:48 +0100315 std::lock_guard _l(mLock);
316 mUseFrameworkMel = useFrameworkMel;
317}
318
Vlad Popa3d6d39d2022-12-21 18:59:16 +0100319bool SoundDoseManager::forceUseFrameworkMel() const {
Vlad Popa91930462022-12-20 22:42:48 +0100320 std::lock_guard _l(mLock);
321 return mUseFrameworkMel;
322}
323
324void SoundDoseManager::setComputeCsdOnAllDevices(bool computeCsdOnAllDevices) {
325 std::lock_guard _l(mLock);
326 mComputeCsdOnAllDevices = computeCsdOnAllDevices;
327}
328
Vlad Popa3d6d39d2022-12-21 18:59:16 +0100329bool SoundDoseManager::forceComputeCsdOnAllDevices() const {
Vlad Popa91930462022-12-20 22:42:48 +0100330 std::lock_guard _l(mLock);
331 return mComputeCsdOnAllDevices;
332}
333
Vlad Popa3d6d39d2022-12-21 18:59:16 +0100334void SoundDoseManager::getHalSoundDose(std::shared_ptr<ISoundDose>* halSoundDose) const {
335 std::lock_guard _l(mLock);
336 *halSoundDose = mHalSoundDose;
337}
338
Vlad Popae3fd1c22022-11-07 21:03:18 +0100339void SoundDoseManager::resetSoundDose() {
340 std::lock_guard lock(mLock);
341 mSoundDose = nullptr;
342}
343
344void SoundDoseManager::resetCsd(float currentCsd,
345 const std::vector<media::SoundDoseRecord>& records) {
346 std::lock_guard lock(mLock);
347 std::vector<audio_utils::CsdRecord> resetRecords;
348 for (const auto& record : records) {
349 resetRecords.emplace_back(record.timestamp, record.duration, record.value,
350 record.averageMel);
351 }
352
353 mMelAggregator->reset(currentCsd, resetRecords);
354}
355
Vlad Popa4defd0b2022-11-06 14:22:31 +0100356void SoundDoseManager::onNewMelValues(const std::vector<float>& mels, size_t offset, size_t length,
357 audio_port_handle_t deviceId) const {
Vlad Popaf09e93f2022-10-31 16:27:12 +0100358 ALOGV("%s", __func__);
Vlad Popa2900c0a2022-10-24 13:38:00 +0200359
Vlad Popa4defd0b2022-11-06 14:22:31 +0100360 sp<media::ISoundDoseCallback> soundDoseCallback;
361 std::vector<audio_utils::CsdRecord> records;
362 float currentCsd;
363 {
364 std::lock_guard _l(mLock);
Vlad Popa2900c0a2022-10-24 13:38:00 +0200365
Vlad Popa4defd0b2022-11-06 14:22:31 +0100366 int64_t timestampSec = getMonotonicSecond();
367
368 // only for internal callbacks
369 records = mMelAggregator->aggregateAndAddNewMelRecord(audio_utils::MelRecord(
370 deviceId, std::vector<float>(mels.begin() + offset, mels.begin() + offset + length),
371 timestampSec - length));
372
373 currentCsd = mMelAggregator->getCsd();
374 }
375
376 soundDoseCallback = getSoundDoseCallback();
377
378 if (records.size() > 0 && soundDoseCallback != nullptr) {
379 std::vector<media::SoundDoseRecord> newRecordsToReport;
380 for (const auto& record : records) {
381 newRecordsToReport.emplace_back(csdRecordToSoundDoseRecord(record));
382 }
383
384 soundDoseCallback->onNewCsdValue(currentCsd, newRecordsToReport);
385 }
Vlad Popa2900c0a2022-10-24 13:38:00 +0200386}
387
Vlad Popa4defd0b2022-11-06 14:22:31 +0100388sp<media::ISoundDoseCallback> SoundDoseManager::getSoundDoseCallback() const {
389 std::lock_guard _l(mLock);
Vlad Popae3fd1c22022-11-07 21:03:18 +0100390 if (mSoundDose == nullptr) {
391 return nullptr;
392 }
393
394 return mSoundDose->mSoundDoseCallback;
Vlad Popa4defd0b2022-11-06 14:22:31 +0100395}
396
397void SoundDoseManager::onMomentaryExposure(float currentMel, audio_port_handle_t deviceId) const {
398 ALOGV("%s: Momentary exposure for device %d triggered: %f MEL", __func__, deviceId, currentMel);
Vlad Popa63f047e2022-11-05 14:09:19 +0100399
Vlad Popae3fd1c22022-11-07 21:03:18 +0100400 auto soundDoseCallback = getSoundDoseCallback();
Vlad Popa63f047e2022-11-05 14:09:19 +0100401 if (soundDoseCallback != nullptr) {
Vlad Popae3fd1c22022-11-07 21:03:18 +0100402 soundDoseCallback->onMomentaryExposure(currentMel, deviceId);
Vlad Popa63f047e2022-11-05 14:09:19 +0100403 }
404}
405
Vlad Popae3fd1c22022-11-07 21:03:18 +0100406sp<media::ISoundDose> SoundDoseManager::getSoundDoseInterface(
407 const sp<media::ISoundDoseCallback>& callback) {
Vlad Popa63f047e2022-11-05 14:09:19 +0100408 ALOGV("%s: Register ISoundDoseCallback", __func__);
409
410 std::lock_guard _l(mLock);
Vlad Popae3fd1c22022-11-07 21:03:18 +0100411 if (mSoundDose == nullptr) {
412 mSoundDose = sp<SoundDose>::make(this, callback);
413 }
414 return mSoundDose;
Vlad Popaf09e93f2022-10-31 16:27:12 +0100415}
416
Vlad Popa4defd0b2022-11-06 14:22:31 +0100417std::string SoundDoseManager::dump() const {
Vlad Popa2900c0a2022-10-24 13:38:00 +0200418 std::string output;
Vlad Popaf09e93f2022-10-31 16:27:12 +0100419 mMelAggregator->foreachCsd([&output](audio_utils::CsdRecord csdRecord) {
Vlad Popa2900c0a2022-10-24 13:38:00 +0200420 base::StringAppendF(&output,
421 "CSD %f with average MEL %f in interval [%" PRId64 ", %" PRId64 "]",
Vlad Popa4defd0b2022-11-06 14:22:31 +0100422 csdRecord.value, csdRecord.averageMel, csdRecord.timestamp,
Vlad Popa2900c0a2022-10-24 13:38:00 +0200423 csdRecord.timestamp + csdRecord.duration);
424 base::StringAppendF(&output, "\n");
425 });
426
427 base::StringAppendF(&output, "\nCached Mel Records:\n");
Vlad Popaf09e93f2022-10-31 16:27:12 +0100428 mMelAggregator->foreachCachedMel([&output](const audio_utils::MelRecord& melRecord) {
Vlad Popa2900c0a2022-10-24 13:38:00 +0200429 base::StringAppendF(&output, "Continuous MELs for portId=%d, ", melRecord.portId);
430 base::StringAppendF(&output, "starting at timestamp %" PRId64 ": ", melRecord.timestamp);
431
432 for (const auto& mel : melRecord.mels) {
433 base::StringAppendF(&output, "%.2f ", mel);
434 }
435 base::StringAppendF(&output, "\n");
436 });
437
438 return output;
439}
440
441size_t SoundDoseManager::getCachedMelRecordsSize() const {
Vlad Popaf09e93f2022-10-31 16:27:12 +0100442 return mMelAggregator->getCachedMelRecordsSize();
Vlad Popa2900c0a2022-10-24 13:38:00 +0200443}
444
Vlad Popa4defd0b2022-11-06 14:22:31 +0100445media::SoundDoseRecord SoundDoseManager::csdRecordToSoundDoseRecord(
446 const audio_utils::CsdRecord& legacy) {
447 media::SoundDoseRecord soundDoseRecord{};
448 soundDoseRecord.timestamp = legacy.timestamp;
449 soundDoseRecord.duration = legacy.duration;
450 soundDoseRecord.value = legacy.value;
451 soundDoseRecord.averageMel = legacy.averageMel;
452 return soundDoseRecord;
453}
454
Vlad Popa2900c0a2022-10-24 13:38:00 +0200455} // namespace android