1 /*
2 * Copyright (C) 2023 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 #define LOG_TAG "StreamHalAidl"
18 //#define LOG_NDEBUG 0
19
20 #include <algorithm>
21 #include <cstdint>
22
23 #include <audio_utils/clock.h>
24 #include <media/AidlConversion.h>
25 #include <media/AidlConversionCore.h>
26 #include <media/AidlConversionCppNdk.h>
27 #include <media/AidlConversionNdk.h>
28 #include <media/AidlConversionUtil.h>
29 #include <media/AudioParameter.h>
30 #include <mediautils/TimeCheck.h>
31 #include <system/audio.h>
32 #include <utils/Log.h>
33
34 #include "DeviceHalAidl.h"
35 #include "EffectHalAidl.h"
36 #include "StreamHalAidl.h"
37
38 using ::aidl::android::aidl_utils::statusTFromBinderStatus;
39 using ::aidl::android::hardware::audio::common::PlaybackTrackMetadata;
40 using ::aidl::android::hardware::audio::common::RecordTrackMetadata;
41 using ::aidl::android::hardware::audio::core::IStreamCommon;
42 using ::aidl::android::hardware::audio::core::IStreamIn;
43 using ::aidl::android::hardware::audio::core::IStreamOut;
44 using ::aidl::android::hardware::audio::core::StreamDescriptor;
45 using ::aidl::android::hardware::audio::core::MmapBufferDescriptor;
46 using ::aidl::android::media::audio::common::MicrophoneDynamicInfo;
47 using ::aidl::android::media::audio::IHalAdapterVendorExtension;
48
49 namespace android {
50
51 using HalCommand = StreamDescriptor::Command;
52 namespace {
makeHalCommand()53 template<HalCommand::Tag cmd> HalCommand makeHalCommand() {
54 return HalCommand::make<cmd>(::aidl::android::media::audio::common::Void{});
55 }
makeHalCommand(T data)56 template<HalCommand::Tag cmd, typename T> HalCommand makeHalCommand(T data) {
57 return HalCommand::make<cmd>(data);
58 }
59 } // namespace
60
61 // static
62 template<class T>
getStreamCommon(const std::shared_ptr<T> & stream)63 std::shared_ptr<IStreamCommon> StreamHalAidl::getStreamCommon(const std::shared_ptr<T>& stream) {
64 std::shared_ptr<::aidl::android::hardware::audio::core::IStreamCommon> streamCommon;
65 if (stream != nullptr) {
66 if (ndk::ScopedAStatus status = stream->getStreamCommon(&streamCommon);
67 !status.isOk()) {
68 ALOGE("%s: failed to retrieve IStreamCommon instance: %s", __func__,
69 status.getDescription().c_str());
70 }
71 }
72 return streamCommon;
73 }
74
StreamHalAidl(std::string_view className,bool isInput,const audio_config & config,int32_t nominalLatency,StreamContextAidl && context,const std::shared_ptr<IStreamCommon> & stream,const std::shared_ptr<IHalAdapterVendorExtension> & vext)75 StreamHalAidl::StreamHalAidl(
76 std::string_view className, bool isInput, const audio_config& config,
77 int32_t nominalLatency, StreamContextAidl&& context,
78 const std::shared_ptr<IStreamCommon>& stream,
79 const std::shared_ptr<IHalAdapterVendorExtension>& vext)
80 : ConversionHelperAidl(className),
81 mIsInput(isInput),
82 mConfig(configToBase(config)),
83 mContext(std::move(context)),
84 mStream(stream),
85 mVendorExt(vext) {
86 {
87 std::lock_guard l(mLock);
88 mLastReply.latencyMs = nominalLatency;
89 }
90 // Instrument audio signal power logging.
91 // Note: This assumes channel mask, format, and sample rate do not change after creation.
92 if (audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
93 /* mStreamPowerLog.isUserDebugOrEngBuild() && */
94 StreamHalAidl::getAudioProperties(&config) == NO_ERROR) {
95 mStreamPowerLog.init(config.sample_rate, config.channel_mask, config.format);
96 }
97 }
98
~StreamHalAidl()99 StreamHalAidl::~StreamHalAidl() {
100 if (mStream != nullptr) {
101 ndk::ScopedAStatus status = mStream->close();
102 ALOGE_IF(!status.isOk(), "%s: status %s", __func__, status.getDescription().c_str());
103 }
104 }
105
getBufferSize(size_t * size)106 status_t StreamHalAidl::getBufferSize(size_t *size) {
107 ALOGD("%p %s::%s", this, getClassName().c_str(), __func__);
108 if (size == nullptr) {
109 return BAD_VALUE;
110 }
111 if (mContext.getFrameSizeBytes() == 0 || mContext.getBufferSizeFrames() == 0 ||
112 !mStream) {
113 return NO_INIT;
114 }
115 *size = mContext.getBufferSizeBytes();
116 return OK;
117 }
118
getAudioProperties(audio_config_base_t * configBase)119 status_t StreamHalAidl::getAudioProperties(audio_config_base_t *configBase) {
120 ALOGD("%p %s::%s", this, getClassName().c_str(), __func__);
121 if (configBase == nullptr) {
122 return BAD_VALUE;
123 }
124 if (!mStream) return NO_INIT;
125 *configBase = mConfig;
126 return OK;
127 }
128
setParameters(const String8 & kvPairs)129 status_t StreamHalAidl::setParameters(const String8& kvPairs) {
130 TIME_CHECK();
131 if (!mStream) return NO_INIT;
132 AudioParameter parameters(kvPairs);
133 ALOGD("%s: parameters: %s", __func__, parameters.toString().c_str());
134
135 (void)VALUE_OR_RETURN_STATUS(filterOutAndProcessParameter<int>(
136 parameters, String8(AudioParameter::keyStreamHwAvSync),
137 [&](int hwAvSyncId) {
138 return statusTFromBinderStatus(mStream->updateHwAvSyncId(hwAvSyncId));
139 }));
140 return parseAndSetVendorParameters(mVendorExt, mStream, parameters);
141 }
142
getParameters(const String8 & keys __unused,String8 * values)143 status_t StreamHalAidl::getParameters(const String8& keys __unused, String8 *values) {
144 TIME_CHECK();
145 if (!mStream) return NO_INIT;
146 if (values == nullptr) {
147 return BAD_VALUE;
148 }
149 AudioParameter parameterKeys(keys), result;
150 *values = result.toString();
151 return parseAndGetVendorParameters(mVendorExt, mStream, parameterKeys, values);
152 }
153
getFrameSize(size_t * size)154 status_t StreamHalAidl::getFrameSize(size_t *size) {
155 ALOGD("%p %s::%s", this, getClassName().c_str(), __func__);
156 if (size == nullptr) {
157 return BAD_VALUE;
158 }
159 if (mContext.getFrameSizeBytes() == 0 || !mStream) {
160 return NO_INIT;
161 }
162 *size = mContext.getFrameSizeBytes();
163 return OK;
164 }
165
addEffect(sp<EffectHalInterface> effect)166 status_t StreamHalAidl::addEffect(sp<EffectHalInterface> effect) {
167 ALOGD("%p %s::%s", this, getClassName().c_str(), __func__);
168 TIME_CHECK();
169 if (!mStream) return NO_INIT;
170 if (effect == nullptr) {
171 return BAD_VALUE;
172 }
173 auto aidlEffect = sp<effect::EffectHalAidl>::cast(effect);
174 return statusTFromBinderStatus(mStream->addEffect(aidlEffect->getIEffect()));
175 }
176
removeEffect(sp<EffectHalInterface> effect)177 status_t StreamHalAidl::removeEffect(sp<EffectHalInterface> effect) {
178 ALOGD("%p %s::%s", this, getClassName().c_str(), __func__);
179 TIME_CHECK();
180 if (!mStream) return NO_INIT;
181 if (effect == nullptr) {
182 return BAD_VALUE;
183 }
184 auto aidlEffect = sp<effect::EffectHalAidl>::cast(effect);
185 return statusTFromBinderStatus(mStream->removeEffect(aidlEffect->getIEffect()));
186 }
187
standby()188 status_t StreamHalAidl::standby() {
189 ALOGD("%p %s::%s", this, getClassName().c_str(), __func__);
190 TIME_CHECK();
191 if (!mStream) return NO_INIT;
192 const auto state = getState();
193 StreamDescriptor::Reply reply;
194 switch (state) {
195 case StreamDescriptor::State::ACTIVE:
196 if (status_t status = pause(&reply); status != OK) return status;
197 if (reply.state != StreamDescriptor::State::PAUSED) {
198 ALOGE("%s: unexpected stream state: %s (expected PAUSED)",
199 __func__, toString(reply.state).c_str());
200 return INVALID_OPERATION;
201 }
202 FALLTHROUGH_INTENDED;
203 case StreamDescriptor::State::PAUSED:
204 case StreamDescriptor::State::DRAIN_PAUSED:
205 if (mIsInput) return flush();
206 if (status_t status = flush(&reply); status != OK) return status;
207 if (reply.state != StreamDescriptor::State::IDLE) {
208 ALOGE("%s: unexpected stream state: %s (expected IDLE)",
209 __func__, toString(reply.state).c_str());
210 return INVALID_OPERATION;
211 }
212 FALLTHROUGH_INTENDED;
213 case StreamDescriptor::State::IDLE:
214 if (status_t status = sendCommand(makeHalCommand<HalCommand::Tag::standby>(),
215 &reply, true /*safeFromNonWorkerThread*/); status != OK) {
216 return status;
217 }
218 if (reply.state != StreamDescriptor::State::STANDBY) {
219 ALOGE("%s: unexpected stream state: %s (expected STANDBY)",
220 __func__, toString(reply.state).c_str());
221 return INVALID_OPERATION;
222 }
223 FALLTHROUGH_INTENDED;
224 case StreamDescriptor::State::STANDBY:
225 return OK;
226 default:
227 ALOGE("%s: not supported from %s stream state %s",
228 __func__, mIsInput ? "input" : "output", toString(state).c_str());
229 return INVALID_OPERATION;
230 }
231 }
232
dump(int fd,const Vector<String16> & args)233 status_t StreamHalAidl::dump(int fd, const Vector<String16>& args) {
234 ALOGD("%p %s::%s", this, getClassName().c_str(), __func__);
235 TIME_CHECK();
236 if (!mStream) return NO_INIT;
237 return mStream->dump(fd, Args(args).args(), args.size());
238 }
239
start()240 status_t StreamHalAidl::start() {
241 ALOGD("%p %s::%s", this, getClassName().c_str(), __func__);
242 TIME_CHECK();
243 if (!mStream) return NO_INIT;
244 const auto state = getState();
245 StreamDescriptor::Reply reply;
246 if (state == StreamDescriptor::State::STANDBY) {
247 if (status_t status = sendCommand(makeHalCommand<HalCommand::Tag::start>(), &reply, true);
248 status != OK) {
249 return status;
250 }
251 return sendCommand(makeHalCommand<HalCommand::Tag::burst>(0), &reply, true);
252 }
253
254 return INVALID_OPERATION;
255 }
256
stop()257 status_t StreamHalAidl::stop() {
258 ALOGD("%p %s::%s", this, getClassName().c_str(), __func__);
259 if (!mStream) return NO_INIT;
260 return standby();
261 }
262
getLatency(uint32_t * latency)263 status_t StreamHalAidl::getLatency(uint32_t *latency) {
264 ALOGV("%p %s::%s", this, getClassName().c_str(), __func__);
265 if (!mStream) return NO_INIT;
266 StreamDescriptor::Reply reply;
267 if (status_t status = updateCountersIfNeeded(&reply); status != OK) {
268 return status;
269 }
270 *latency = std::max<int32_t>(0, reply.latencyMs);
271 return OK;
272 }
273
getObservablePosition(int64_t * frames,int64_t * timestamp)274 status_t StreamHalAidl::getObservablePosition(int64_t *frames, int64_t *timestamp) {
275 ALOGV("%p %s::%s", this, getClassName().c_str(), __func__);
276 if (!mStream) return NO_INIT;
277 StreamDescriptor::Reply reply;
278 if (status_t status = updateCountersIfNeeded(&reply); status != OK) {
279 return status;
280 }
281 *frames = reply.observable.frames;
282 *timestamp = reply.observable.timeNs;
283 return OK;
284 }
285
getHardwarePosition(int64_t * frames,int64_t * timestamp)286 status_t StreamHalAidl::getHardwarePosition(int64_t *frames, int64_t *timestamp) {
287 ALOGV("%p %s::%s", this, getClassName().c_str(), __func__);
288 if (!mStream) return NO_INIT;
289 StreamDescriptor::Reply reply;
290 // TODO: switch to updateCountersIfNeeded once we sort out mWorkerTid initialization
291 if (status_t status = sendCommand(makeHalCommand<HalCommand::Tag::getStatus>(), &reply, true);
292 status != OK) {
293 return status;
294 }
295 *frames = reply.hardware.frames;
296 *timestamp = reply.hardware.timeNs;
297 return OK;
298 }
299
getXruns(int32_t * frames)300 status_t StreamHalAidl::getXruns(int32_t *frames) {
301 ALOGV("%p %s::%s", this, getClassName().c_str(), __func__);
302 if (!mStream) return NO_INIT;
303 StreamDescriptor::Reply reply;
304 if (status_t status = updateCountersIfNeeded(&reply); status != OK) {
305 return status;
306 }
307 *frames = reply.xrunFrames;
308 return OK;
309 }
310
transfer(void * buffer,size_t bytes,size_t * transferred)311 status_t StreamHalAidl::transfer(void *buffer, size_t bytes, size_t *transferred) {
312 ALOGV("%p %s::%s", this, getClassName().c_str(), __func__);
313 // TIME_CHECK(); // TODO(b/243839867) reenable only when optimized.
314 if (!mStream || mContext.getDataMQ() == nullptr) return NO_INIT;
315 mWorkerTid.store(gettid(), std::memory_order_release);
316 // Switch the stream into an active state if needed.
317 // Note: in future we may add support for priming the audio pipeline
318 // with data prior to enabling output (thus we can issue a "burst" command in the "standby"
319 // stream state), however this scenario wasn't supported by the HIDL HAL.
320 if (getState() == StreamDescriptor::State::STANDBY) {
321 StreamDescriptor::Reply reply;
322 if (status_t status = sendCommand(makeHalCommand<HalCommand::Tag::start>(), &reply);
323 status != OK) {
324 return status;
325 }
326 if (reply.state != StreamDescriptor::State::IDLE) {
327 ALOGE("%s: failed to get the stream out of standby, actual state: %s",
328 __func__, toString(reply.state).c_str());
329 return INVALID_OPERATION;
330 }
331 }
332 if (!mIsInput) {
333 bytes = std::min(bytes, mContext.getDataMQ()->availableToWrite());
334 }
335 StreamDescriptor::Command burst =
336 StreamDescriptor::Command::make<StreamDescriptor::Command::Tag::burst>(bytes);
337 if (!mIsInput) {
338 if (!mContext.getDataMQ()->write(static_cast<const int8_t*>(buffer), bytes)) {
339 ALOGE("%s: failed to write %zu bytes to data MQ", __func__, bytes);
340 return NOT_ENOUGH_DATA;
341 }
342 }
343 StreamDescriptor::Reply reply;
344 if (status_t status = sendCommand(burst, &reply); status != OK) {
345 return status;
346 }
347 *transferred = reply.fmqByteCount;
348 if (mIsInput) {
349 LOG_ALWAYS_FATAL_IF(*transferred > bytes,
350 "%s: HAL module read %zu bytes, which exceeds requested count %zu",
351 __func__, *transferred, bytes);
352 if (auto toRead = mContext.getDataMQ()->availableToRead();
353 toRead != 0 && !mContext.getDataMQ()->read(static_cast<int8_t*>(buffer), toRead)) {
354 ALOGE("%s: failed to read %zu bytes to data MQ", __func__, toRead);
355 return NOT_ENOUGH_DATA;
356 }
357 }
358 mStreamPowerLog.log(buffer, *transferred);
359 return OK;
360 }
361
pause(StreamDescriptor::Reply * reply)362 status_t StreamHalAidl::pause(StreamDescriptor::Reply* reply) {
363 ALOGD("%p %s::%s", this, getClassName().c_str(), __func__);
364 TIME_CHECK();
365 if (!mStream) return NO_INIT;
366 return sendCommand(makeHalCommand<HalCommand::Tag::pause>(), reply,
367 true /*safeFromNonWorkerThread*/); // The workers stops its I/O activity first.
368 }
369
resume(StreamDescriptor::Reply * reply)370 status_t StreamHalAidl::resume(StreamDescriptor::Reply* reply) {
371 ALOGD("%p %s::%s", this, getClassName().c_str(), __func__);
372 TIME_CHECK();
373 if (!mStream) return NO_INIT;
374 if (mIsInput) {
375 return sendCommand(makeHalCommand<HalCommand::Tag::burst>(0), reply);
376 } else {
377 if (mContext.isAsynchronous()) {
378 // Handle pause-flush-resume sequence. 'flush' from PAUSED goes to
379 // IDLE. We move here from IDLE to ACTIVE (same as 'start' from PAUSED).
380 const auto state = getState();
381 if (state == StreamDescriptor::State::IDLE) {
382 StreamDescriptor::Reply localReply{};
383 StreamDescriptor::Reply* innerReply = reply ?: &localReply;
384 if (status_t status =
385 sendCommand(makeHalCommand<HalCommand::Tag::burst>(0), innerReply);
386 status != OK) {
387 return status;
388 }
389 if (innerReply->state != StreamDescriptor::State::ACTIVE) {
390 ALOGE("%s: unexpected stream state: %s (expected ACTIVE)",
391 __func__, toString(innerReply->state).c_str());
392 return INVALID_OPERATION;
393 }
394 return OK;
395 }
396 }
397 return sendCommand(makeHalCommand<HalCommand::Tag::start>(), reply);
398 }
399 }
400
drain(bool earlyNotify,StreamDescriptor::Reply * reply)401 status_t StreamHalAidl::drain(bool earlyNotify, StreamDescriptor::Reply* reply) {
402 ALOGD("%p %s::%s", this, getClassName().c_str(), __func__);
403 TIME_CHECK();
404 if (!mStream) return NO_INIT;
405 return sendCommand(makeHalCommand<HalCommand::Tag::drain>(
406 mIsInput ? StreamDescriptor::DrainMode::DRAIN_UNSPECIFIED :
407 earlyNotify ? StreamDescriptor::DrainMode::DRAIN_EARLY_NOTIFY :
408 StreamDescriptor::DrainMode::DRAIN_ALL), reply,
409 true /*safeFromNonWorkerThread*/);
410 }
411
flush(StreamDescriptor::Reply * reply)412 status_t StreamHalAidl::flush(StreamDescriptor::Reply* reply) {
413 ALOGD("%p %s::%s", this, getClassName().c_str(), __func__);
414 TIME_CHECK();
415 if (!mStream) return NO_INIT;
416 return sendCommand(makeHalCommand<HalCommand::Tag::flush>(), reply,
417 true /*safeFromNonWorkerThread*/); // The workers stops its I/O activity first.
418 }
419
exit()420 status_t StreamHalAidl::exit() {
421 ALOGD("%p %s::%s", this, getClassName().c_str(), __func__);
422 TIME_CHECK();
423 if (!mStream) return NO_INIT;
424 return statusTFromBinderStatus(mStream->prepareToClose());
425 }
426
createMmapBuffer(int32_t minSizeFrames __unused,struct audio_mmap_buffer_info * info)427 status_t StreamHalAidl::createMmapBuffer(int32_t minSizeFrames __unused,
428 struct audio_mmap_buffer_info *info) {
429 ALOGD("%p %s::%s", this, getClassName().c_str(), __func__);
430 TIME_CHECK();
431 if (!mStream) return NO_INIT;
432 if (!mContext.isMmapped()) {
433 return BAD_VALUE;
434 }
435 const MmapBufferDescriptor& bufferDescriptor = mContext.getMmapBufferDescriptor();
436 info->shared_memory_fd = bufferDescriptor.sharedMemory.fd.get();
437 info->buffer_size_frames = mContext.getBufferSizeFrames();
438 info->burst_size_frames = bufferDescriptor.burstSizeFrames;
439 info->flags = static_cast<audio_mmap_buffer_flag>(bufferDescriptor.flags);
440
441 return OK;
442 }
443
getMmapPosition(struct audio_mmap_position * position)444 status_t StreamHalAidl::getMmapPosition(struct audio_mmap_position *position) {
445 TIME_CHECK();
446 if (!mStream) return NO_INIT;
447 if (!mContext.isMmapped()) {
448 return BAD_VALUE;
449 }
450 int64_t aidlPosition = 0, aidlTimestamp = 0;
451 if (status_t status = getHardwarePosition(&aidlPosition, &aidlTimestamp); status != OK) {
452 return status;
453 }
454
455 position->time_nanoseconds = aidlTimestamp;
456 position->position_frames = static_cast<int32_t>(aidlPosition);
457 return OK;
458 }
459
setHalThreadPriority(int priority __unused)460 status_t StreamHalAidl::setHalThreadPriority(int priority __unused) {
461 // Obsolete, must be done by the HAL module.
462 return OK;
463 }
464
legacyCreateAudioPatch(const struct audio_port_config & port __unused,std::optional<audio_source_t> source __unused,audio_devices_t type __unused)465 status_t StreamHalAidl::legacyCreateAudioPatch(const struct audio_port_config& port __unused,
466 std::optional<audio_source_t> source __unused,
467 audio_devices_t type __unused) {
468 // Obsolete since 'DeviceHalAidl.supportsAudioPatches' always returns 'true'.
469 return INVALID_OPERATION;
470 }
471
legacyReleaseAudioPatch()472 status_t StreamHalAidl::legacyReleaseAudioPatch() {
473 // Obsolete since 'DeviceHalAidl.supportsAudioPatches' always returns 'true'.
474 return INVALID_OPERATION;
475 }
476
sendCommand(const::aidl::android::hardware::audio::core::StreamDescriptor::Command & command,::aidl::android::hardware::audio::core::StreamDescriptor::Reply * reply,bool safeFromNonWorkerThread)477 status_t StreamHalAidl::sendCommand(
478 const ::aidl::android::hardware::audio::core::StreamDescriptor::Command &command,
479 ::aidl::android::hardware::audio::core::StreamDescriptor::Reply* reply,
480 bool safeFromNonWorkerThread) {
481 // TIME_CHECK(); // TODO(b/243839867) reenable only when optimized.
482 if (!safeFromNonWorkerThread) {
483 const pid_t workerTid = mWorkerTid.load(std::memory_order_acquire);
484 LOG_ALWAYS_FATAL_IF(workerTid != gettid(),
485 "%s %s: must be invoked from the worker thread (%d)",
486 __func__, command.toString().c_str(), workerTid);
487 }
488 if (!mContext.getCommandMQ()->writeBlocking(&command, 1)) {
489 ALOGE("%s: failed to write command %s to MQ", __func__, command.toString().c_str());
490 return NOT_ENOUGH_DATA;
491 }
492 StreamDescriptor::Reply localReply{};
493 if (reply == nullptr) {
494 reply = &localReply;
495 }
496 if (!mContext.getReplyMQ()->readBlocking(reply, 1)) {
497 ALOGE("%s: failed to read from reply MQ, command %s", __func__, command.toString().c_str());
498 return NOT_ENOUGH_DATA;
499 }
500 {
501 std::lock_guard l(mLock);
502 mLastReply = *reply;
503 }
504 switch (reply->status) {
505 case STATUS_OK: return OK;
506 case STATUS_BAD_VALUE: return BAD_VALUE;
507 case STATUS_INVALID_OPERATION: return INVALID_OPERATION;
508 case STATUS_NOT_ENOUGH_DATA: return NOT_ENOUGH_DATA;
509 default:
510 ALOGE("%s: unexpected status %d returned for command %s",
511 __func__, reply->status, command.toString().c_str());
512 return INVALID_OPERATION;
513 }
514 }
515
updateCountersIfNeeded(::aidl::android::hardware::audio::core::StreamDescriptor::Reply * reply)516 status_t StreamHalAidl::updateCountersIfNeeded(
517 ::aidl::android::hardware::audio::core::StreamDescriptor::Reply* reply) {
518 if (mWorkerTid.load(std::memory_order_acquire) == gettid()) {
519 if (const auto state = getState(); state != StreamDescriptor::State::ACTIVE &&
520 state != StreamDescriptor::State::DRAINING &&
521 state != StreamDescriptor::State::TRANSFERRING) {
522 return sendCommand(makeHalCommand<HalCommand::Tag::getStatus>(), reply);
523 }
524 }
525 if (reply != nullptr) {
526 std::lock_guard l(mLock);
527 *reply = mLastReply;
528 }
529 return OK;
530 }
531
532 // static
533 ConversionResult<::aidl::android::hardware::audio::common::SourceMetadata>
legacy2aidl_SourceMetadata(const StreamOutHalInterface::SourceMetadata & legacy)534 StreamOutHalAidl::legacy2aidl_SourceMetadata(const StreamOutHalInterface::SourceMetadata& legacy) {
535 ::aidl::android::hardware::audio::common::SourceMetadata aidl;
536 aidl.tracks = VALUE_OR_RETURN(
537 ::aidl::android::convertContainer<std::vector<PlaybackTrackMetadata>>(
538 legacy.tracks,
539 ::aidl::android::legacy2aidl_playback_track_metadata_v7_PlaybackTrackMetadata));
540 return aidl;
541 }
542
StreamOutHalAidl(const audio_config & config,StreamContextAidl && context,int32_t nominalLatency,const std::shared_ptr<IStreamOut> & stream,const std::shared_ptr<IHalAdapterVendorExtension> & vext,const sp<CallbackBroker> & callbackBroker)543 StreamOutHalAidl::StreamOutHalAidl(
544 const audio_config& config, StreamContextAidl&& context, int32_t nominalLatency,
545 const std::shared_ptr<IStreamOut>& stream,
546 const std::shared_ptr<IHalAdapterVendorExtension>& vext,
547 const sp<CallbackBroker>& callbackBroker)
548 : StreamHalAidl("StreamOutHalAidl", false /*isInput*/, config, nominalLatency,
549 std::move(context), getStreamCommon(stream), vext),
550 mStream(stream), mCallbackBroker(callbackBroker) {
551 // Initialize the offload metadata
552 mOffloadMetadata.sampleRate = static_cast<int32_t>(config.sample_rate);
553 mOffloadMetadata.channelMask = VALUE_OR_FATAL(
554 ::aidl::android::legacy2aidl_audio_channel_mask_t_AudioChannelLayout(
555 config.channel_mask, false));
556 mOffloadMetadata.averageBitRatePerSecond = static_cast<int32_t>(config.offload_info.bit_rate);
557 }
558
~StreamOutHalAidl()559 StreamOutHalAidl::~StreamOutHalAidl() {
560 if (auto broker = mCallbackBroker.promote(); broker != nullptr) {
561 broker->clearCallbacks(this);
562 }
563 }
564
setParameters(const String8 & kvPairs)565 status_t StreamOutHalAidl::setParameters(const String8& kvPairs) {
566 if (!mStream) return NO_INIT;
567
568 AudioParameter parameters(kvPairs);
569 ALOGD("%s: parameters: \"%s\"", __func__, parameters.toString().c_str());
570
571 if (status_t status = filterAndUpdateOffloadMetadata(parameters); status != OK) {
572 ALOGW("%s: filtering or updating offload metadata failed: %d", __func__, status);
573 }
574
575 return StreamHalAidl::setParameters(parameters.toString());
576 }
577
getLatency(uint32_t * latency)578 status_t StreamOutHalAidl::getLatency(uint32_t *latency) {
579 return StreamHalAidl::getLatency(latency);
580 }
581
setVolume(float left,float right)582 status_t StreamOutHalAidl::setVolume(float left, float right) {
583 TIME_CHECK();
584 if (!mStream) return NO_INIT;
585 return statusTFromBinderStatus(mStream->setHwVolume({left, right}));
586 }
587
selectPresentation(int presentationId,int programId)588 status_t StreamOutHalAidl::selectPresentation(int presentationId, int programId) {
589 TIME_CHECK();
590 if (!mStream) return NO_INIT;
591 return statusTFromBinderStatus(mStream->selectPresentation(presentationId, programId));
592 }
593
write(const void * buffer,size_t bytes,size_t * written)594 status_t StreamOutHalAidl::write(const void *buffer, size_t bytes, size_t *written) {
595 if (buffer == nullptr || written == nullptr) {
596 return BAD_VALUE;
597 }
598 // For the output scenario, 'transfer' does not modify the buffer.
599 return transfer(const_cast<void*>(buffer), bytes, written);
600 }
601
getRenderPosition(uint32_t * dspFrames)602 status_t StreamOutHalAidl::getRenderPosition(uint32_t *dspFrames) {
603 if (dspFrames == nullptr) {
604 return BAD_VALUE;
605 }
606 int64_t aidlFrames = 0, aidlTimestamp = 0;
607 if (status_t status = getObservablePosition(&aidlFrames, &aidlTimestamp); status != OK) {
608 return OK;
609 }
610 *dspFrames = std::clamp<int64_t>(aidlFrames, 0, UINT32_MAX);
611 return OK;
612 }
613
getNextWriteTimestamp(int64_t * timestamp __unused)614 status_t StreamOutHalAidl::getNextWriteTimestamp(int64_t *timestamp __unused) {
615 // Obsolete, use getPresentationPosition.
616 return INVALID_OPERATION;
617 }
618
setCallback(wp<StreamOutHalInterfaceCallback> callback)619 status_t StreamOutHalAidl::setCallback(wp<StreamOutHalInterfaceCallback> callback) {
620 TIME_CHECK();
621 if (!mStream) return NO_INIT;
622 if (!mContext.isAsynchronous()) {
623 ALOGE("%s: the callback is intended for asynchronous streams only", __func__);
624 return INVALID_OPERATION;
625 }
626 if (auto broker = mCallbackBroker.promote(); broker != nullptr) {
627 if (auto cb = callback.promote(); cb != nullptr) {
628 broker->setStreamOutCallback(this, cb);
629 } else {
630 // It is expected that the framework never passes a null pointer.
631 // In the AIDL model callbacks can't be "unregistered".
632 LOG_ALWAYS_FATAL("%s: received an expired or null callback pointer", __func__);
633 }
634 }
635 return OK;
636 }
637
supportsPauseAndResume(bool * supportsPause,bool * supportsResume)638 status_t StreamOutHalAidl::supportsPauseAndResume(bool *supportsPause, bool *supportsResume) {
639 if (supportsPause == nullptr || supportsResume == nullptr) {
640 return BAD_VALUE;
641 }
642 TIME_CHECK();
643 if (!mStream) return NO_INIT;
644 *supportsPause = *supportsResume = true;
645 return OK;
646 }
647
pause()648 status_t StreamOutHalAidl::pause() {
649 return StreamHalAidl::pause();
650 }
651
resume()652 status_t StreamOutHalAidl::resume() {
653 return StreamHalAidl::resume();
654 }
655
supportsDrain(bool * supportsDrain)656 status_t StreamOutHalAidl::supportsDrain(bool *supportsDrain) {
657 if (supportsDrain == nullptr) {
658 return BAD_VALUE;
659 }
660 TIME_CHECK();
661 if (!mStream) return NO_INIT;
662 *supportsDrain = true;
663 return OK;
664 }
665
drain(bool earlyNotify)666 status_t StreamOutHalAidl::drain(bool earlyNotify) {
667 return StreamHalAidl::drain(earlyNotify);
668 }
669
flush()670 status_t StreamOutHalAidl::flush() {
671 return StreamHalAidl::flush();
672 }
673
getPresentationPosition(uint64_t * frames,struct timespec * timestamp)674 status_t StreamOutHalAidl::getPresentationPosition(uint64_t *frames, struct timespec *timestamp) {
675 if (frames == nullptr || timestamp == nullptr) {
676 return BAD_VALUE;
677 }
678 int64_t aidlFrames = 0, aidlTimestamp = 0;
679 if (status_t status = getObservablePosition(&aidlFrames, &aidlTimestamp); status != OK) {
680 return status;
681 }
682 *frames = std::max<int64_t>(0, aidlFrames);
683 timestamp->tv_sec = aidlTimestamp / NANOS_PER_SECOND;
684 timestamp->tv_nsec = aidlTimestamp - timestamp->tv_sec * NANOS_PER_SECOND;
685 return OK;
686 }
687
updateSourceMetadata(const StreamOutHalInterface::SourceMetadata & sourceMetadata)688 status_t StreamOutHalAidl::updateSourceMetadata(
689 const StreamOutHalInterface::SourceMetadata& sourceMetadata) {
690 TIME_CHECK();
691 if (!mStream) return NO_INIT;
692 ::aidl::android::hardware::audio::common::SourceMetadata aidlMetadata =
693 VALUE_OR_RETURN_STATUS(legacy2aidl_SourceMetadata(sourceMetadata));
694 return statusTFromBinderStatus(mStream->updateMetadata(aidlMetadata));
695 }
696
getDualMonoMode(audio_dual_mono_mode_t * mode)697 status_t StreamOutHalAidl::getDualMonoMode(audio_dual_mono_mode_t* mode) {
698 TIME_CHECK();
699 if (!mStream) return NO_INIT;
700 if (mode == nullptr) {
701 return BAD_VALUE;
702 }
703 ::aidl::android::media::audio::common::AudioDualMonoMode aidlMode;
704 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mStream->getDualMonoMode(&aidlMode)));
705 *mode = VALUE_OR_RETURN_STATUS(
706 ::aidl::android::aidl2legacy_AudioDualMonoMode_audio_dual_mono_mode_t(aidlMode));
707 return OK;
708 }
709
setDualMonoMode(audio_dual_mono_mode_t mode)710 status_t StreamOutHalAidl::setDualMonoMode(audio_dual_mono_mode_t mode) {
711 TIME_CHECK();
712 if (!mStream) return NO_INIT;
713 ::aidl::android::media::audio::common::AudioDualMonoMode aidlMode = VALUE_OR_RETURN_STATUS(
714 ::aidl::android::legacy2aidl_audio_dual_mono_mode_t_AudioDualMonoMode(mode));
715 return statusTFromBinderStatus(mStream->setDualMonoMode(aidlMode));
716 }
717
getAudioDescriptionMixLevel(float * leveldB)718 status_t StreamOutHalAidl::getAudioDescriptionMixLevel(float* leveldB) {
719 TIME_CHECK();
720 if (!mStream) return NO_INIT;
721 if (leveldB == nullptr) {
722 return BAD_VALUE;
723 }
724 return statusTFromBinderStatus(mStream->getAudioDescriptionMixLevel(leveldB));
725 }
726
setAudioDescriptionMixLevel(float leveldB)727 status_t StreamOutHalAidl::setAudioDescriptionMixLevel(float leveldB) {
728 TIME_CHECK();
729 if (!mStream) return NO_INIT;
730 return statusTFromBinderStatus(mStream->setAudioDescriptionMixLevel(leveldB));
731 }
732
getPlaybackRateParameters(audio_playback_rate_t * playbackRate)733 status_t StreamOutHalAidl::getPlaybackRateParameters(audio_playback_rate_t* playbackRate) {
734 TIME_CHECK();
735 if (!mStream) return NO_INIT;
736 if (playbackRate == nullptr) {
737 return BAD_VALUE;
738 }
739 ::aidl::android::media::audio::common::AudioPlaybackRate aidlRate;
740 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mStream->getPlaybackRateParameters(&aidlRate)));
741 *playbackRate = VALUE_OR_RETURN_STATUS(
742 ::aidl::android::aidl2legacy_AudioPlaybackRate_audio_playback_rate_t(aidlRate));
743 return OK;
744 }
745
setPlaybackRateParameters(const audio_playback_rate_t & playbackRate)746 status_t StreamOutHalAidl::setPlaybackRateParameters(const audio_playback_rate_t& playbackRate) {
747 TIME_CHECK();
748 if (!mStream) return NO_INIT;
749 ::aidl::android::media::audio::common::AudioPlaybackRate aidlRate = VALUE_OR_RETURN_STATUS(
750 ::aidl::android::legacy2aidl_audio_playback_rate_t_AudioPlaybackRate(playbackRate));
751 return statusTFromBinderStatus(mStream->setPlaybackRateParameters(aidlRate));
752 }
753
setEventCallback(const sp<StreamOutHalInterfaceEventCallback> & callback)754 status_t StreamOutHalAidl::setEventCallback(
755 const sp<StreamOutHalInterfaceEventCallback>& callback) {
756 TIME_CHECK();
757 if (!mStream) return NO_INIT;
758 if (auto broker = mCallbackBroker.promote(); broker != nullptr) {
759 broker->setStreamOutEventCallback(this, callback);
760 }
761 return OK;
762 }
763
setLatencyMode(audio_latency_mode_t mode)764 status_t StreamOutHalAidl::setLatencyMode(audio_latency_mode_t mode) {
765 TIME_CHECK();
766 if (!mStream) return NO_INIT;
767 ::aidl::android::media::audio::common::AudioLatencyMode aidlMode = VALUE_OR_RETURN_STATUS(
768 ::aidl::android::legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode));
769 return statusTFromBinderStatus(mStream->setLatencyMode(aidlMode));
770 };
771
getRecommendedLatencyModes(std::vector<audio_latency_mode_t> * modes)772 status_t StreamOutHalAidl::getRecommendedLatencyModes(std::vector<audio_latency_mode_t> *modes) {
773 TIME_CHECK();
774 if (!mStream) return NO_INIT;
775 if (modes == nullptr) {
776 return BAD_VALUE;
777 }
778 std::vector<::aidl::android::media::audio::common::AudioLatencyMode> aidlModes;
779 RETURN_STATUS_IF_ERROR(
780 statusTFromBinderStatus(mStream->getRecommendedLatencyModes(&aidlModes)));
781 *modes = VALUE_OR_RETURN_STATUS(
782 ::aidl::android::convertContainer<std::vector<audio_latency_mode_t>>(
783 aidlModes,
784 ::aidl::android::aidl2legacy_AudioLatencyMode_audio_latency_mode_t));
785 return OK;
786 };
787
setLatencyModeCallback(const sp<StreamOutHalInterfaceLatencyModeCallback> & callback)788 status_t StreamOutHalAidl::setLatencyModeCallback(
789 const sp<StreamOutHalInterfaceLatencyModeCallback>& callback) {
790 TIME_CHECK();
791 if (!mStream) return NO_INIT;
792 if (auto broker = mCallbackBroker.promote(); broker != nullptr) {
793 broker->setStreamOutLatencyModeCallback(this, callback);
794 }
795 return OK;
796 };
797
exit()798 status_t StreamOutHalAidl::exit() {
799 return StreamHalAidl::exit();
800 }
801
filterAndUpdateOffloadMetadata(AudioParameter & parameters)802 status_t StreamOutHalAidl::filterAndUpdateOffloadMetadata(AudioParameter ¶meters) {
803 TIME_CHECK();
804 bool updateMetadata = false;
805 if (VALUE_OR_RETURN_STATUS(filterOutAndProcessParameter<int>(
806 parameters, String8(AudioParameter::keyOffloadCodecAverageBitRate),
807 [&](int value) {
808 return value > 0 ?
809 mOffloadMetadata.averageBitRatePerSecond = value, OK : BAD_VALUE;
810 }))) {
811 updateMetadata = true;
812 }
813 if (VALUE_OR_RETURN_STATUS(filterOutAndProcessParameter<int>(
814 parameters, String8(AudioParameter::keyOffloadCodecSampleRate),
815 [&](int value) {
816 return value > 0 ? mOffloadMetadata.sampleRate = value, OK : BAD_VALUE;
817 }))) {
818 updateMetadata = true;
819 }
820 if (VALUE_OR_RETURN_STATUS(filterOutAndProcessParameter<int>(
821 parameters, String8(AudioParameter::keyOffloadCodecChannels),
822 [&](int value) -> status_t {
823 if (value > 0) {
824 audio_channel_mask_t channel_mask = audio_channel_out_mask_from_count(
825 static_cast<uint32_t>(value));
826 if (channel_mask == AUDIO_CHANNEL_INVALID) return BAD_VALUE;
827 mOffloadMetadata.channelMask = VALUE_OR_RETURN_STATUS(
828 ::aidl::android::legacy2aidl_audio_channel_mask_t_AudioChannelLayout(
829 channel_mask, false /*isInput*/));
830 }
831 return BAD_VALUE;
832 }))) {
833 updateMetadata = true;
834 }
835 if (VALUE_OR_RETURN_STATUS(filterOutAndProcessParameter<int>(
836 parameters, String8(AudioParameter::keyOffloadCodecDelaySamples),
837 [&](int value) {
838 // The legacy keys are misnamed, the value is in frames.
839 return value >= 0 ? mOffloadMetadata.delayFrames = value, OK : BAD_VALUE;
840 }))) {
841 updateMetadata = true;
842 }
843 if (VALUE_OR_RETURN_STATUS(filterOutAndProcessParameter<int>(
844 parameters, String8(AudioParameter::keyOffloadCodecPaddingSamples),
845 [&](int value) {
846 // The legacy keys are misnamed, the value is in frames.
847 return value >= 0 ? mOffloadMetadata.paddingFrames = value, OK : BAD_VALUE;
848 }))) {
849 updateMetadata = true;
850 }
851 if (updateMetadata) {
852 ALOGD("%s set offload metadata %s", __func__, mOffloadMetadata.toString().c_str());
853 if (status_t status = statusTFromBinderStatus(
854 mStream->updateOffloadMetadata(mOffloadMetadata)); status != OK) {
855 ALOGE("%s: updateOffloadMetadata failed %d", __func__, status);
856 return status;
857 }
858 }
859 return OK;
860 }
861
862 // static
863 ConversionResult<::aidl::android::hardware::audio::common::SinkMetadata>
legacy2aidl_SinkMetadata(const StreamInHalInterface::SinkMetadata & legacy)864 StreamInHalAidl::legacy2aidl_SinkMetadata(const StreamInHalInterface::SinkMetadata& legacy) {
865 ::aidl::android::hardware::audio::common::SinkMetadata aidl;
866 aidl.tracks = VALUE_OR_RETURN(
867 ::aidl::android::convertContainer<std::vector<RecordTrackMetadata>>(
868 legacy.tracks,
869 ::aidl::android::legacy2aidl_record_track_metadata_v7_RecordTrackMetadata));
870 return aidl;
871 }
872
StreamInHalAidl(const audio_config & config,StreamContextAidl && context,int32_t nominalLatency,const std::shared_ptr<IStreamIn> & stream,const std::shared_ptr<IHalAdapterVendorExtension> & vext,const sp<MicrophoneInfoProvider> & micInfoProvider)873 StreamInHalAidl::StreamInHalAidl(
874 const audio_config& config, StreamContextAidl&& context, int32_t nominalLatency,
875 const std::shared_ptr<IStreamIn>& stream,
876 const std::shared_ptr<IHalAdapterVendorExtension>& vext,
877 const sp<MicrophoneInfoProvider>& micInfoProvider)
878 : StreamHalAidl("StreamInHalAidl", true /*isInput*/, config, nominalLatency,
879 std::move(context), getStreamCommon(stream), vext),
880 mStream(stream), mMicInfoProvider(micInfoProvider) {}
881
setGain(float gain)882 status_t StreamInHalAidl::setGain(float gain) {
883 TIME_CHECK();
884 if (!mStream) return NO_INIT;
885 return statusTFromBinderStatus(mStream->setHwGain({gain}));
886 }
887
read(void * buffer,size_t bytes,size_t * read)888 status_t StreamInHalAidl::read(void *buffer, size_t bytes, size_t *read) {
889 if (buffer == nullptr || read == nullptr) {
890 return BAD_VALUE;
891 }
892 return transfer(buffer, bytes, read);
893 }
894
getInputFramesLost(uint32_t * framesLost)895 status_t StreamInHalAidl::getInputFramesLost(uint32_t *framesLost) {
896 if (framesLost == nullptr) {
897 return BAD_VALUE;
898 }
899 int32_t aidlXruns = 0;
900 if (status_t status = getXruns(&aidlXruns); status != OK) {
901 return status;
902 }
903 *framesLost = std::max<int32_t>(0, aidlXruns);
904 return OK;
905 }
906
getCapturePosition(int64_t * frames,int64_t * time)907 status_t StreamInHalAidl::getCapturePosition(int64_t *frames, int64_t *time) {
908 if (frames == nullptr || time == nullptr) {
909 return BAD_VALUE;
910 }
911 return getObservablePosition(frames, time);
912 }
913
getActiveMicrophones(std::vector<media::MicrophoneInfoFw> * microphones)914 status_t StreamInHalAidl::getActiveMicrophones(std::vector<media::MicrophoneInfoFw> *microphones) {
915 if (!microphones) {
916 return BAD_VALUE;
917 }
918 TIME_CHECK();
919 if (!mStream) return NO_INIT;
920 sp<MicrophoneInfoProvider> micInfoProvider = mMicInfoProvider.promote();
921 if (!micInfoProvider) return NO_INIT;
922 auto staticInfo = micInfoProvider->getMicrophoneInfo();
923 if (!staticInfo) return INVALID_OPERATION;
924 std::vector<MicrophoneDynamicInfo> dynamicInfo;
925 RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(mStream->getActiveMicrophones(&dynamicInfo)));
926 std::vector<media::MicrophoneInfoFw> result;
927 result.reserve(dynamicInfo.size());
928 for (const auto& d : dynamicInfo) {
929 const auto staticInfoIt = std::find_if(staticInfo->begin(), staticInfo->end(),
930 [&](const auto& s) { return s.id == d.id; });
931 if (staticInfoIt != staticInfo->end()) {
932 // Convert into the c++ backend type from the ndk backend type via the legacy structure.
933 audio_microphone_characteristic_t legacy = VALUE_OR_RETURN_STATUS(
934 ::aidl::android::aidl2legacy_MicrophoneInfos_audio_microphone_characteristic_t(
935 *staticInfoIt, d));
936 media::MicrophoneInfoFw info = VALUE_OR_RETURN_STATUS(
937 ::android::legacy2aidl_audio_microphone_characteristic_t_MicrophoneInfoFw(
938 legacy));
939 // Note: info.portId is not filled because it's a bit of framework info.
940 result.push_back(std::move(info));
941 } else {
942 ALOGE("%s: no static info for active microphone with id '%s'", __func__, d.id.c_str());
943 }
944 }
945 *microphones = std::move(result);
946 return OK;
947 }
948
updateSinkMetadata(const StreamInHalInterface::SinkMetadata & sinkMetadata)949 status_t StreamInHalAidl::updateSinkMetadata(
950 const StreamInHalInterface::SinkMetadata& sinkMetadata) {
951 TIME_CHECK();
952 if (!mStream) return NO_INIT;
953 ::aidl::android::hardware::audio::common::SinkMetadata aidlMetadata =
954 VALUE_OR_RETURN_STATUS(legacy2aidl_SinkMetadata(sinkMetadata));
955 return statusTFromBinderStatus(mStream->updateMetadata(aidlMetadata));
956 }
957
setPreferredMicrophoneDirection(audio_microphone_direction_t direction)958 status_t StreamInHalAidl::setPreferredMicrophoneDirection(audio_microphone_direction_t direction) {
959 TIME_CHECK();
960 if (!mStream) return NO_INIT;
961 ::aidl::android::hardware::audio::core::IStreamIn::MicrophoneDirection aidlDirection =
962 VALUE_OR_RETURN_STATUS(
963 ::aidl::android::legacy2aidl_audio_microphone_direction_t_MicrophoneDirection(
964 direction));
965 return statusTFromBinderStatus(mStream->setMicrophoneDirection(aidlDirection));
966 }
967
setPreferredMicrophoneFieldDimension(float zoom)968 status_t StreamInHalAidl::setPreferredMicrophoneFieldDimension(float zoom) {
969 TIME_CHECK();
970 if (!mStream) return NO_INIT;
971 return statusTFromBinderStatus(mStream->setMicrophoneFieldDimension(zoom));
972 }
973
974 } // namespace android
975