1 /*
2 * Copyright (C) 2022 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 <pthread.h>
18
19 #define ATRACE_TAG ATRACE_TAG_AUDIO
20 #define LOG_TAG "AHAL_Stream"
21 #include <Utils.h>
22 #include <android-base/logging.h>
23 #include <android/binder_ibinder_platform.h>
24 #include <cutils/properties.h>
25 #include <utils/SystemClock.h>
26 #include <utils/Trace.h>
27
28 #include "core-impl/Stream.h"
29
30 using aidl::android::hardware::audio::common::AudioOffloadMetadata;
31 using aidl::android::hardware::audio::common::getChannelCount;
32 using aidl::android::hardware::audio::common::getFrameSizeInBytes;
33 using aidl::android::hardware::audio::common::hasMmapFlag;
34 using aidl::android::hardware::audio::common::isBitPositionFlagSet;
35 using aidl::android::hardware::audio::common::SinkMetadata;
36 using aidl::android::hardware::audio::common::SourceMetadata;
37 using aidl::android::media::audio::common::AudioDevice;
38 using aidl::android::media::audio::common::AudioDualMonoMode;
39 using aidl::android::media::audio::common::AudioInputFlags;
40 using aidl::android::media::audio::common::AudioIoFlags;
41 using aidl::android::media::audio::common::AudioLatencyMode;
42 using aidl::android::media::audio::common::AudioOffloadInfo;
43 using aidl::android::media::audio::common::AudioOutputFlags;
44 using aidl::android::media::audio::common::AudioPlaybackRate;
45 using aidl::android::media::audio::common::MicrophoneDynamicInfo;
46 using aidl::android::media::audio::common::MicrophoneInfo;
47
48 namespace aidl::android::hardware::audio::core {
49
50 namespace {
51
52 template <typename MQTypeError>
fmqErrorHandler(const char * mqName)53 auto fmqErrorHandler(const char* mqName) {
54 return [m = std::string(mqName)](MQTypeError fmqError, std::string&& errorMessage) {
55 CHECK_EQ(fmqError, MQTypeError::NONE) << m << ": " << errorMessage;
56 };
57 }
58
59 } // namespace
60
fillDescriptor(StreamDescriptor * desc)61 void StreamContext::fillDescriptor(StreamDescriptor* desc) {
62 if (mCommandMQ) {
63 desc->command = mCommandMQ->dupeDesc();
64 }
65 if (mReplyMQ) {
66 desc->reply = mReplyMQ->dupeDesc();
67 }
68 desc->frameSizeBytes = getFrameSize();
69 desc->bufferSizeFrames = getBufferSizeInFrames();
70 if (mDataMQ) {
71 desc->audio.set<StreamDescriptor::AudioBuffer::Tag::fmq>(mDataMQ->dupeDesc());
72 } else {
73 MmapBufferDescriptor mmapDesc; // Move-only due to `fd`.
74 mmapDesc.sharedMemory.fd = mMmapBufferDesc.sharedMemory.fd.dup();
75 mmapDesc.sharedMemory.size = mMmapBufferDesc.sharedMemory.size;
76 mmapDesc.burstSizeFrames = mMmapBufferDesc.burstSizeFrames;
77 mmapDesc.flags = mMmapBufferDesc.flags;
78 desc->audio.set<StreamDescriptor::AudioBuffer::Tag::mmap>(std::move(mmapDesc));
79 }
80 }
81
getBufferSizeInFrames() const82 size_t StreamContext::getBufferSizeInFrames() const {
83 if (mDataMQ) {
84 return mDataMQ->getQuantumCount() * mDataMQ->getQuantumSize() / getFrameSize();
85 } else {
86 return mMmapBufferDesc.sharedMemory.size / getFrameSize();
87 }
88 }
89
getFrameSize() const90 size_t StreamContext::getFrameSize() const {
91 return getFrameSizeInBytes(mFormat, mChannelLayout);
92 }
93
isValid() const94 bool StreamContext::isValid() const {
95 if (mCommandMQ && !mCommandMQ->isValid()) {
96 LOG(ERROR) << "command FMQ is invalid";
97 return false;
98 }
99 if (mReplyMQ && !mReplyMQ->isValid()) {
100 LOG(ERROR) << "reply FMQ is invalid";
101 return false;
102 }
103 if (getFrameSize() == 0) {
104 LOG(ERROR) << "frame size is invalid";
105 return false;
106 }
107 if (!isMmap() && mDataMQ && !mDataMQ->isValid()) {
108 LOG(ERROR) << "data FMQ is invalid";
109 return false;
110 } else if (isMmap() &&
111 (mMmapBufferDesc.sharedMemory.fd.get() == -1 ||
112 mMmapBufferDesc.sharedMemory.size == 0 || mMmapBufferDesc.burstSizeFrames == 0)) {
113 LOG(ERROR) << "mmap info is invalid" << mMmapBufferDesc.toString();
114 }
115 return true;
116 }
117
startStreamDataProcessor()118 void StreamContext::startStreamDataProcessor() {
119 auto streamDataProcessor = mStreamDataProcessor.lock();
120 if (streamDataProcessor != nullptr) {
121 streamDataProcessor->startDataProcessor(mSampleRate, getChannelCount(mChannelLayout),
122 mFormat);
123 }
124 }
125
reset()126 void StreamContext::reset() {
127 mCommandMQ.reset();
128 mReplyMQ.reset();
129 mDataMQ.reset();
130 mMmapBufferDesc.sharedMemory.fd.set(-1);
131 }
132
getTid() const133 pid_t StreamWorkerCommonLogic::getTid() const {
134 #if defined(__ANDROID__)
135 return pthread_gettid_np(pthread_self());
136 #else
137 return 0;
138 #endif
139 }
140
init()141 std::string StreamWorkerCommonLogic::init() {
142 if (mContext->getCommandMQ() == nullptr) return "Command MQ is null";
143 if (mContext->getReplyMQ() == nullptr) return "Reply MQ is null";
144 if (!mContext->isMmap()) {
145 StreamContext::DataMQ* const dataMQ = mContext->getDataMQ();
146 if (dataMQ == nullptr) return "Data MQ is null";
147 if (sizeof(DataBufferElement) != dataMQ->getQuantumSize()) {
148 return "Unexpected Data MQ quantum size: " + std::to_string(dataMQ->getQuantumSize());
149 }
150 mDataBufferSize = dataMQ->getQuantumCount() * dataMQ->getQuantumSize();
151 mDataBuffer.reset(new (std::nothrow) DataBufferElement[mDataBufferSize]);
152 if (mDataBuffer == nullptr) {
153 return "Failed to allocate data buffer for element count " +
154 std::to_string(dataMQ->getQuantumCount()) +
155 ", size in bytes: " + std::to_string(mDataBufferSize);
156 }
157 }
158 if (::android::status_t status = mDriver->init(this /*DriverCallbackInterface*/);
159 status != STATUS_OK) {
160 return "Failed to initialize the driver: " + std::to_string(status);
161 }
162 return "";
163 }
164
onBufferStateChange(size_t)165 void StreamWorkerCommonLogic::onBufferStateChange(size_t /*bufferFramesLeft*/) {}
onClipStateChange(size_t,bool)166 void StreamWorkerCommonLogic::onClipStateChange(size_t /*clipFramesLeft*/, bool /*hasNextClip*/) {}
167
populateReply(StreamDescriptor::Reply * reply,bool isConnected) const168 void StreamWorkerCommonLogic::populateReply(StreamDescriptor::Reply* reply,
169 bool isConnected) const {
170 static const StreamDescriptor::Position kUnknownPosition = {
171 .frames = StreamDescriptor::Position::UNKNOWN,
172 .timeNs = StreamDescriptor::Position::UNKNOWN};
173 reply->status = STATUS_OK;
174 if (isConnected) {
175 reply->observable.frames = mContext->getFrameCount();
176 reply->observable.timeNs = ::android::uptimeNanos();
177 if (auto status = mDriver->refinePosition(&reply->observable); status != ::android::OK) {
178 reply->observable = kUnknownPosition;
179 }
180 } else {
181 reply->observable = reply->hardware = kUnknownPosition;
182 }
183 if (mContext->isMmap()) {
184 if (auto status = mDriver->getMmapPositionAndLatency(&reply->hardware, &reply->latencyMs);
185 status != ::android::OK) {
186 reply->hardware = kUnknownPosition;
187 reply->latencyMs = StreamDescriptor::LATENCY_UNKNOWN;
188 }
189 }
190 }
191
populateReplyWrongState(StreamDescriptor::Reply * reply,const StreamDescriptor::Command & command) const192 void StreamWorkerCommonLogic::populateReplyWrongState(
193 StreamDescriptor::Reply* reply, const StreamDescriptor::Command& command) const {
194 LOG(WARNING) << "command '" << toString(command.getTag())
195 << "' can not be handled in the state " << toString(mState);
196 reply->status = STATUS_INVALID_OPERATION;
197 }
198
199 const std::string StreamInWorkerLogic::kThreadName = "reader";
200
cycle()201 StreamInWorkerLogic::Status StreamInWorkerLogic::cycle() {
202 // Note: for input streams, draining is driven by the client, thus
203 // "empty buffer" condition can only happen while handling the 'burst'
204 // command. Thus, unlike for output streams, it does not make sense to
205 // delay the 'DRAINING' state here by 'mTransientStateDelayMs'.
206 // TODO: Add a delay for transitions of async operations when/if they added.
207
208 StreamDescriptor::Command command{};
209 if (!mContext->getCommandMQ()->readBlocking(&command, 1)) {
210 LOG(ERROR) << __func__ << ": reading of command from MQ failed";
211 mState = StreamDescriptor::State::ERROR;
212 return Status::ABORT;
213 }
214 using Tag = StreamDescriptor::Command::Tag;
215 using LogSeverity = ::android::base::LogSeverity;
216 const LogSeverity severity =
217 command.getTag() == Tag::burst || command.getTag() == Tag::getStatus
218 ? LogSeverity::VERBOSE
219 : LogSeverity::DEBUG;
220 LOG(severity) << __func__ << ": received command " << command.toString() << " in "
221 << kThreadName;
222 StreamDescriptor::Reply reply{};
223 reply.status = STATUS_BAD_VALUE;
224 switch (command.getTag()) {
225 case Tag::halReservedExit: {
226 const int32_t cookie = command.get<Tag::halReservedExit>();
227 StreamInWorkerLogic::Status status = Status::CONTINUE;
228 if (cookie == (mContext->getInternalCommandCookie() ^ getTid())) {
229 mDriver->shutdown();
230 setClosed();
231 status = Status::EXIT;
232 } else {
233 LOG(WARNING) << __func__ << ": EXIT command has a bad cookie: " << cookie;
234 }
235 if (cookie != 0) { // This is an internal command, no need to reply.
236 return status;
237 }
238 // `cookie == 0` can only occur in the context of a VTS test, need to reply.
239 break;
240 }
241 case Tag::getStatus:
242 populateReply(&reply, mIsConnected);
243 break;
244 case Tag::start:
245 if (mState == StreamDescriptor::State::STANDBY ||
246 mState == StreamDescriptor::State::DRAINING) {
247 if (::android::status_t status = mDriver->start(); status == ::android::OK) {
248 populateReply(&reply, mIsConnected);
249 mState = mState == StreamDescriptor::State::STANDBY
250 ? StreamDescriptor::State::IDLE
251 : StreamDescriptor::State::ACTIVE;
252 } else {
253 LOG(ERROR) << __func__ << ": start failed: " << status;
254 mState = StreamDescriptor::State::ERROR;
255 }
256 } else {
257 populateReplyWrongState(&reply, command);
258 }
259 break;
260 case Tag::burst:
261 if (const int32_t fmqByteCount = command.get<Tag::burst>(); fmqByteCount >= 0) {
262 LOG(VERBOSE) << __func__ << ": '" << toString(command.getTag()) << "' command for "
263 << fmqByteCount << " bytes";
264 if (mState == StreamDescriptor::State::IDLE ||
265 mState == StreamDescriptor::State::ACTIVE ||
266 mState == StreamDescriptor::State::PAUSED ||
267 mState == StreamDescriptor::State::DRAINING) {
268 if (bool success =
269 mContext->isMmap() ? readMmap(&reply) : read(fmqByteCount, &reply);
270 !success) {
271 mState = StreamDescriptor::State::ERROR;
272 }
273 if (mState == StreamDescriptor::State::IDLE ||
274 mState == StreamDescriptor::State::PAUSED) {
275 mState = StreamDescriptor::State::ACTIVE;
276 } else if (mState == StreamDescriptor::State::DRAINING) {
277 // To simplify the reference code, we assume that the read operation
278 // has consumed all the data remaining in the hardware buffer.
279 // In a real implementation, here we would either remain in
280 // the 'DRAINING' state, or transfer to 'STANDBY' depending on the
281 // buffer state.
282 mState = StreamDescriptor::State::STANDBY;
283 }
284 } else {
285 populateReplyWrongState(&reply, command);
286 }
287 } else {
288 LOG(WARNING) << __func__ << ": invalid burst byte count: " << fmqByteCount;
289 }
290 break;
291 case Tag::drain:
292 if (const auto mode = command.get<Tag::drain>();
293 mode == StreamDescriptor::DrainMode::DRAIN_UNSPECIFIED) {
294 if (mState == StreamDescriptor::State::ACTIVE) {
295 if (::android::status_t status = mDriver->drain(mode);
296 status == ::android::OK) {
297 populateReply(&reply, mIsConnected);
298 mState = StreamDescriptor::State::DRAINING;
299 } else {
300 LOG(ERROR) << __func__ << ": drain failed: " << status;
301 mState = StreamDescriptor::State::ERROR;
302 }
303 } else {
304 populateReplyWrongState(&reply, command);
305 }
306 } else {
307 LOG(WARNING) << __func__ << ": invalid drain mode: " << toString(mode);
308 }
309 break;
310 case Tag::standby:
311 if (mState == StreamDescriptor::State::IDLE) {
312 populateReply(&reply, mIsConnected);
313 if (::android::status_t status = mDriver->standby(); status == ::android::OK) {
314 mState = StreamDescriptor::State::STANDBY;
315 } else {
316 LOG(ERROR) << __func__ << ": standby failed: " << status;
317 mState = StreamDescriptor::State::ERROR;
318 }
319 } else {
320 populateReplyWrongState(&reply, command);
321 }
322 break;
323 case Tag::pause:
324 if (mState == StreamDescriptor::State::ACTIVE) {
325 if (::android::status_t status = mDriver->pause(); status == ::android::OK) {
326 populateReply(&reply, mIsConnected);
327 mState = StreamDescriptor::State::PAUSED;
328 } else {
329 LOG(ERROR) << __func__ << ": pause failed: " << status;
330 mState = StreamDescriptor::State::ERROR;
331 }
332 } else {
333 populateReplyWrongState(&reply, command);
334 }
335 break;
336 case Tag::flush:
337 if (mState == StreamDescriptor::State::PAUSED) {
338 if (::android::status_t status = mDriver->flush(); status == ::android::OK) {
339 populateReply(&reply, mIsConnected);
340 mState = StreamDescriptor::State::STANDBY;
341 } else {
342 LOG(ERROR) << __func__ << ": flush failed: " << status;
343 mState = StreamDescriptor::State::ERROR;
344 }
345 } else {
346 populateReplyWrongState(&reply, command);
347 }
348 break;
349 }
350 reply.state = mState;
351 LOG(severity) << __func__ << ": writing reply " << reply.toString();
352 if (!mContext->getReplyMQ()->writeBlocking(&reply, 1)) {
353 LOG(ERROR) << __func__ << ": writing of reply " << reply.toString() << " to MQ failed";
354 mState = StreamDescriptor::State::ERROR;
355 return Status::ABORT;
356 }
357 return Status::CONTINUE;
358 }
359
read(size_t clientSize,StreamDescriptor::Reply * reply)360 bool StreamInWorkerLogic::read(size_t clientSize, StreamDescriptor::Reply* reply) {
361 ATRACE_CALL();
362 StreamContext::DataMQ* const dataMQ = mContext->getDataMQ();
363 const size_t byteCount = std::min({clientSize, dataMQ->availableToWrite(), mDataBufferSize});
364 const bool isConnected = mIsConnected;
365 const size_t frameSize = mContext->getFrameSize();
366 size_t actualFrameCount = 0;
367 bool fatal = false;
368 int32_t latency = mContext->getNominalLatencyMs();
369 if (isConnected) {
370 if (::android::status_t status = mDriver->transfer(mDataBuffer.get(), byteCount / frameSize,
371 &actualFrameCount, &latency);
372 status != ::android::OK) {
373 fatal = true;
374 LOG(ERROR) << __func__ << ": read failed: " << status;
375 }
376 } else {
377 usleep(3000); // Simulate blocking transfer delay.
378 for (size_t i = 0; i < byteCount; ++i) mDataBuffer[i] = 0;
379 actualFrameCount = byteCount / frameSize;
380 }
381 const size_t actualByteCount = actualFrameCount * frameSize;
382 if (bool success = actualByteCount > 0 ? dataMQ->write(&mDataBuffer[0], actualByteCount) : true;
383 success) {
384 LOG(VERBOSE) << __func__ << ": writing of " << actualByteCount << " bytes into data MQ"
385 << " succeeded; connected? " << isConnected;
386 // Frames are provided and counted regardless of connection status.
387 reply->fmqByteCount += actualByteCount;
388 mContext->advanceFrameCount(actualFrameCount);
389 populateReply(reply, isConnected);
390 } else {
391 LOG(WARNING) << __func__ << ": writing of " << actualByteCount
392 << " bytes of data to MQ failed";
393 reply->status = STATUS_NOT_ENOUGH_DATA;
394 }
395 reply->latencyMs = latency;
396 return !fatal;
397 }
398
readMmap(StreamDescriptor::Reply * reply)399 bool StreamInWorkerLogic::readMmap(StreamDescriptor::Reply* reply) {
400 void* buffer = nullptr;
401 size_t frameCount = 0;
402 size_t actualFrameCount = 0;
403 int32_t latency = mContext->getNominalLatencyMs();
404 // use default-initialized parameter values for mmap stream.
405 if (::android::status_t status =
406 mDriver->transfer(buffer, frameCount, &actualFrameCount, &latency);
407 status == ::android::OK) {
408 populateReply(reply, mIsConnected);
409 reply->latencyMs = latency;
410 return true;
411 } else {
412 LOG(ERROR) << __func__ << ": transfer failed: " << status;
413 return false;
414 }
415 }
416
417 const std::string StreamOutWorkerLogic::kThreadName = "writer";
418
onBufferStateChange(size_t bufferFramesLeft)419 void StreamOutWorkerLogic::onBufferStateChange(size_t bufferFramesLeft) {
420 const StreamDescriptor::State state = mState;
421 const DrainState drainState = mDrainState;
422 LOG(DEBUG) << __func__ << ": state: " << toString(state) << ", drainState: " << drainState
423 << ", bufferFramesLeft: " << bufferFramesLeft;
424 if (state == StreamDescriptor::State::TRANSFERRING || drainState == DrainState::EN_SENT) {
425 if (state == StreamDescriptor::State::TRANSFERRING) {
426 mState = StreamDescriptor::State::ACTIVE;
427 }
428 std::shared_ptr<IStreamCallback> asyncCallback = mContext->getAsyncCallback();
429 if (asyncCallback != nullptr) {
430 LOG(VERBOSE) << __func__ << ": sending onTransferReady";
431 ndk::ScopedAStatus status = asyncCallback->onTransferReady();
432 if (!status.isOk()) {
433 LOG(ERROR) << __func__ << ": error from onTransferReady: " << status;
434 }
435 }
436 }
437 }
438
onClipStateChange(size_t clipFramesLeft,bool hasNextClip)439 void StreamOutWorkerLogic::onClipStateChange(size_t clipFramesLeft, bool hasNextClip) {
440 const DrainState drainState = mDrainState;
441 std::shared_ptr<IStreamCallback> asyncCallback = mContext->getAsyncCallback();
442 LOG(DEBUG) << __func__ << ": drainState: " << drainState << "; clipFramesLeft "
443 << clipFramesLeft << "; hasNextClip? " << hasNextClip << "; asyncCallback? "
444 << (asyncCallback != nullptr);
445 if (drainState != DrainState::NONE && clipFramesLeft == 0) {
446 mState =
447 hasNextClip ? StreamDescriptor::State::TRANSFERRING : StreamDescriptor::State::IDLE;
448 mDrainState = DrainState::NONE;
449 if ((drainState == DrainState::ALL || drainState == DrainState::EN_SENT) &&
450 asyncCallback != nullptr) {
451 LOG(DEBUG) << __func__ << ": sending onDrainReady";
452 // For EN_SENT, this is the second onDrainReady which notifies about clip transition.
453 ndk::ScopedAStatus status = asyncCallback->onDrainReady();
454 if (!status.isOk()) {
455 LOG(ERROR) << __func__ << ": error from onDrainReady: " << status;
456 }
457 }
458 } else if (drainState == DrainState::EN && clipFramesLeft > 0) {
459 // The stream state does not change, it is still draining.
460 mDrainState = DrainState::EN_SENT;
461 if (asyncCallback != nullptr) {
462 LOG(DEBUG) << __func__ << ": sending onDrainReady";
463 ndk::ScopedAStatus status = asyncCallback->onDrainReady();
464 if (!status.isOk()) {
465 LOG(ERROR) << __func__ << ": error from onDrainReady: " << status;
466 }
467 }
468 }
469 }
470
cycle()471 StreamOutWorkerLogic::Status StreamOutWorkerLogic::cycle() {
472 // Non-blocking mode is handled within 'onClipStateChange'
473 if (std::shared_ptr<IStreamCallback> asyncCallback = mContext->getAsyncCallback();
474 mState == StreamDescriptor::State::DRAINING && asyncCallback == nullptr) {
475 if (auto stateDurationMs = std::chrono::duration_cast<std::chrono::milliseconds>(
476 std::chrono::steady_clock::now() - mTransientStateStart);
477 stateDurationMs >= mTransientStateDelayMs) {
478 mState = StreamDescriptor::State::IDLE;
479 if (mTransientStateDelayMs.count() != 0) {
480 LOG(DEBUG) << __func__ << ": switched to state " << toString(mState)
481 << " after a timeout";
482 }
483 }
484 }
485
486 StreamDescriptor::Command command{};
487 if (!mContext->getCommandMQ()->readBlocking(&command, 1)) {
488 LOG(ERROR) << __func__ << ": reading of command from MQ failed";
489 mState = StreamDescriptor::State::ERROR;
490 return Status::ABORT;
491 }
492 using Tag = StreamDescriptor::Command::Tag;
493 using LogSeverity = ::android::base::LogSeverity;
494 const LogSeverity severity =
495 command.getTag() == Tag::burst || command.getTag() == Tag::getStatus
496 ? LogSeverity::VERBOSE
497 : LogSeverity::DEBUG;
498 LOG(severity) << __func__ << ": received command " << command.toString() << " in "
499 << kThreadName;
500 StreamDescriptor::Reply reply{};
501 reply.status = STATUS_BAD_VALUE;
502 using Tag = StreamDescriptor::Command::Tag;
503 switch (command.getTag()) {
504 case Tag::halReservedExit: {
505 const int32_t cookie = command.get<Tag::halReservedExit>();
506 StreamOutWorkerLogic::Status status = Status::CONTINUE;
507 if (cookie == (mContext->getInternalCommandCookie() ^ getTid())) {
508 mDriver->shutdown();
509 setClosed();
510 status = Status::EXIT;
511 } else {
512 LOG(WARNING) << __func__ << ": EXIT command has a bad cookie: " << cookie;
513 }
514 if (cookie != 0) { // This is an internal command, no need to reply.
515 return status;
516 }
517 // `cookie == 0` can only occur in the context of a VTS test, need to reply.
518 break;
519 }
520 case Tag::getStatus:
521 populateReply(&reply, mIsConnected);
522 break;
523 case Tag::start: {
524 std::optional<StreamDescriptor::State> nextState;
525 switch (mState) {
526 case StreamDescriptor::State::STANDBY:
527 nextState = StreamDescriptor::State::IDLE;
528 break;
529 case StreamDescriptor::State::PAUSED:
530 nextState = StreamDescriptor::State::ACTIVE;
531 break;
532 case StreamDescriptor::State::DRAIN_PAUSED:
533 nextState = StreamDescriptor::State::DRAINING;
534 break;
535 case StreamDescriptor::State::TRANSFER_PAUSED:
536 nextState = StreamDescriptor::State::TRANSFERRING;
537 break;
538 default:
539 populateReplyWrongState(&reply, command);
540 }
541 if (nextState.has_value()) {
542 if (::android::status_t status = mDriver->start(); status == ::android::OK) {
543 populateReply(&reply, mIsConnected);
544 if (*nextState == StreamDescriptor::State::IDLE ||
545 *nextState == StreamDescriptor::State::ACTIVE) {
546 mState = *nextState;
547 } else {
548 switchToTransientState(*nextState);
549 }
550 } else {
551 LOG(ERROR) << __func__ << ": start failed: " << status;
552 mState = StreamDescriptor::State::ERROR;
553 }
554 }
555 } break;
556 case Tag::burst:
557 if (const int32_t fmqByteCount = command.get<Tag::burst>(); fmqByteCount >= 0) {
558 LOG(VERBOSE) << __func__ << ": '" << toString(command.getTag()) << "' command for "
559 << fmqByteCount << " bytes";
560 if (mState != StreamDescriptor::State::ERROR &&
561 mState != StreamDescriptor::State::TRANSFERRING &&
562 mState != StreamDescriptor::State::TRANSFER_PAUSED) {
563 if (bool success = mContext->isMmap() ? writeMmap(&reply)
564 : write(fmqByteCount, &reply);
565 !success) {
566 mState = StreamDescriptor::State::ERROR;
567 }
568 std::shared_ptr<IStreamCallback> asyncCallback = mContext->getAsyncCallback();
569 if (mState == StreamDescriptor::State::STANDBY ||
570 mState == StreamDescriptor::State::DRAIN_PAUSED ||
571 mState == StreamDescriptor::State::PAUSED) {
572 if (asyncCallback == nullptr ||
573 mState != StreamDescriptor::State::DRAIN_PAUSED) {
574 mState = StreamDescriptor::State::PAUSED;
575 } else {
576 mState = StreamDescriptor::State::TRANSFER_PAUSED;
577 }
578 } else if (mState == StreamDescriptor::State::IDLE ||
579 mState == StreamDescriptor::State::ACTIVE ||
580 (mState == StreamDescriptor::State::DRAINING &&
581 mDrainState != DrainState::EN_SENT)) {
582 if (asyncCallback == nullptr || reply.fmqByteCount == fmqByteCount) {
583 mState = StreamDescriptor::State::ACTIVE;
584 } else {
585 switchToTransientState(StreamDescriptor::State::TRANSFERRING);
586 }
587 } else if (mState == StreamDescriptor::State::DRAINING &&
588 mDrainState == DrainState::EN_SENT) {
589 // keep mState
590 }
591 } else {
592 populateReplyWrongState(&reply, command);
593 }
594 } else {
595 LOG(WARNING) << __func__ << ": invalid burst byte count: " << fmqByteCount;
596 }
597 break;
598 case Tag::drain:
599 if (const auto mode = command.get<Tag::drain>();
600 mode == StreamDescriptor::DrainMode::DRAIN_ALL ||
601 mode == StreamDescriptor::DrainMode::DRAIN_EARLY_NOTIFY) {
602 if (mState == StreamDescriptor::State::ACTIVE ||
603 mState == StreamDescriptor::State::TRANSFERRING) {
604 if (::android::status_t status = mDriver->drain(mode);
605 status == ::android::OK) {
606 populateReply(&reply, mIsConnected);
607 if (mState == StreamDescriptor::State::ACTIVE &&
608 mContext->getForceSynchronousDrain()) {
609 mState = StreamDescriptor::State::IDLE;
610 } else {
611 switchToTransientState(StreamDescriptor::State::DRAINING);
612 mDrainState = mode == StreamDescriptor::DrainMode::DRAIN_EARLY_NOTIFY
613 ? DrainState::EN
614 : DrainState::ALL;
615 }
616 } else {
617 LOG(ERROR) << __func__ << ": drain failed: " << status;
618 mState = StreamDescriptor::State::ERROR;
619 }
620 } else if (mState == StreamDescriptor::State::TRANSFER_PAUSED) {
621 mState = StreamDescriptor::State::DRAIN_PAUSED;
622 populateReply(&reply, mIsConnected);
623 } else {
624 populateReplyWrongState(&reply, command);
625 }
626 } else {
627 LOG(WARNING) << __func__ << ": invalid drain mode: " << toString(mode);
628 }
629 break;
630 case Tag::standby:
631 if (mState == StreamDescriptor::State::IDLE) {
632 populateReply(&reply, mIsConnected);
633 if (::android::status_t status = mDriver->standby(); status == ::android::OK) {
634 mState = StreamDescriptor::State::STANDBY;
635 } else {
636 LOG(ERROR) << __func__ << ": standby failed: " << status;
637 mState = StreamDescriptor::State::ERROR;
638 }
639 } else {
640 populateReplyWrongState(&reply, command);
641 }
642 break;
643 case Tag::pause: {
644 std::optional<StreamDescriptor::State> nextState;
645 switch (mState) {
646 case StreamDescriptor::State::ACTIVE:
647 nextState = StreamDescriptor::State::PAUSED;
648 break;
649 case StreamDescriptor::State::DRAINING:
650 nextState = StreamDescriptor::State::DRAIN_PAUSED;
651 break;
652 case StreamDescriptor::State::TRANSFERRING:
653 nextState = StreamDescriptor::State::TRANSFER_PAUSED;
654 break;
655 default:
656 populateReplyWrongState(&reply, command);
657 }
658 if (nextState.has_value()) {
659 if (::android::status_t status = mDriver->pause(); status == ::android::OK) {
660 populateReply(&reply, mIsConnected);
661 mState = nextState.value();
662 } else {
663 LOG(ERROR) << __func__ << ": pause failed: " << status;
664 mState = StreamDescriptor::State::ERROR;
665 }
666 }
667 } break;
668 case Tag::flush:
669 if (mState == StreamDescriptor::State::PAUSED ||
670 mState == StreamDescriptor::State::DRAIN_PAUSED ||
671 mState == StreamDescriptor::State::TRANSFER_PAUSED) {
672 if (::android::status_t status = mDriver->flush(); status == ::android::OK) {
673 populateReply(&reply, mIsConnected);
674 mState = StreamDescriptor::State::IDLE;
675 } else {
676 LOG(ERROR) << __func__ << ": flush failed: " << status;
677 mState = StreamDescriptor::State::ERROR;
678 }
679 } else {
680 populateReplyWrongState(&reply, command);
681 }
682 break;
683 }
684 reply.state = mState;
685 LOG(severity) << __func__ << ": writing reply " << reply.toString();
686 if (!mContext->getReplyMQ()->writeBlocking(&reply, 1)) {
687 LOG(ERROR) << __func__ << ": writing of reply " << reply.toString() << " to MQ failed";
688 mState = StreamDescriptor::State::ERROR;
689 return Status::ABORT;
690 }
691 return Status::CONTINUE;
692 }
693
write(size_t clientSize,StreamDescriptor::Reply * reply)694 bool StreamOutWorkerLogic::write(size_t clientSize, StreamDescriptor::Reply* reply) {
695 ATRACE_CALL();
696 StreamContext::DataMQ* const dataMQ = mContext->getDataMQ();
697 const size_t readByteCount = dataMQ->availableToRead();
698 const size_t frameSize = mContext->getFrameSize();
699 bool fatal = false;
700 int32_t latency = mContext->getNominalLatencyMs();
701 if (readByteCount > 0 ? dataMQ->read(&mDataBuffer[0], readByteCount) : true) {
702 const bool isConnected = mIsConnected;
703 LOG(VERBOSE) << __func__ << ": reading of " << readByteCount << " bytes from data MQ"
704 << " succeeded; connected? " << isConnected;
705 // Amount of data that the HAL module is going to actually use.
706 size_t byteCount = std::min({clientSize, readByteCount, mDataBufferSize});
707 if (byteCount >= frameSize && mContext->getForceTransientBurst()) {
708 // In order to prevent the state machine from going to ACTIVE state,
709 // simulate partial write.
710 byteCount -= frameSize;
711 }
712 size_t actualFrameCount = 0;
713 if (isConnected) {
714 if (::android::status_t status = mDriver->transfer(
715 mDataBuffer.get(), byteCount / frameSize, &actualFrameCount, &latency);
716 status != ::android::OK) {
717 fatal = true;
718 LOG(ERROR) << __func__ << ": write failed: " << status;
719 }
720 auto streamDataProcessor = mContext->getStreamDataProcessor().lock();
721 if (streamDataProcessor != nullptr) {
722 streamDataProcessor->process(mDataBuffer.get(), actualFrameCount * frameSize);
723 }
724 } else {
725 if (mContext->getAsyncCallback() == nullptr) {
726 usleep(3000); // Simulate blocking transfer delay.
727 }
728 actualFrameCount = byteCount / frameSize;
729 }
730 const size_t actualByteCount = actualFrameCount * frameSize;
731 // Frames are consumed and counted regardless of the connection status.
732 reply->fmqByteCount += actualByteCount;
733 mContext->advanceFrameCount(actualFrameCount);
734 populateReply(reply, isConnected);
735 } else {
736 LOG(WARNING) << __func__ << ": reading of " << readByteCount
737 << " bytes of data from MQ failed";
738 reply->status = STATUS_NOT_ENOUGH_DATA;
739 }
740 reply->latencyMs = latency;
741 return !fatal;
742 }
743
writeMmap(StreamDescriptor::Reply * reply)744 bool StreamOutWorkerLogic::writeMmap(StreamDescriptor::Reply* reply) {
745 void* buffer = nullptr;
746 size_t frameCount = 0;
747 size_t actualFrameCount = 0;
748 int32_t latency = mContext->getNominalLatencyMs();
749 // use default-initialized parameter values for mmap stream.
750 if (::android::status_t status =
751 mDriver->transfer(buffer, frameCount, &actualFrameCount, &latency);
752 status == ::android::OK) {
753 populateReply(reply, mIsConnected);
754 reply->latencyMs = latency;
755 return true;
756 } else {
757 LOG(ERROR) << __func__ << ": transfer failed: " << status;
758 return false;
759 }
760 }
761
~StreamCommonImpl()762 StreamCommonImpl::~StreamCommonImpl() {
763 // It is responsibility of the class that implements 'DriverInterface' to call 'cleanupWorker'
764 // in the destructor. Note that 'cleanupWorker' can not be properly called from this destructor
765 // because any subclasses have already been destroyed and thus the 'DriverInterface'
766 // implementation is not valid. Thus, here it can only be asserted whether the subclass has done
767 // its job.
768 if (!mWorkerStopIssued && !isClosed()) {
769 LOG(FATAL) << __func__ << ": the stream implementation must call 'cleanupWorker' "
770 << "in order to clean up the worker thread.";
771 }
772 }
773
initInstance(const std::shared_ptr<StreamCommonInterface> & delegate)774 ndk::ScopedAStatus StreamCommonImpl::initInstance(
775 const std::shared_ptr<StreamCommonInterface>& delegate) {
776 mCommon = ndk::SharedRefBase::make<StreamCommonDelegator>(delegate);
777 if (!mWorker->start()) {
778 LOG(ERROR) << __func__ << ": Worker start error: " << mWorker->getError();
779 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
780 }
781 setWorkerThreadPriority(mWorker->getTid());
782 getContext().getCommandMQ()->setErrorHandler(
783 fmqErrorHandler<StreamContext::CommandMQ::Error>("CommandMQ"));
784 getContext().getReplyMQ()->setErrorHandler(
785 fmqErrorHandler<StreamContext::ReplyMQ::Error>("ReplyMQ"));
786 if (getContext().getDataMQ() != nullptr) {
787 getContext().getDataMQ()->setErrorHandler(
788 fmqErrorHandler<StreamContext::DataMQ::Error>("DataMQ"));
789 }
790 return ndk::ScopedAStatus::ok();
791 }
792
getStreamCommonCommon(std::shared_ptr<IStreamCommon> * _aidl_return)793 ndk::ScopedAStatus StreamCommonImpl::getStreamCommonCommon(
794 std::shared_ptr<IStreamCommon>* _aidl_return) {
795 if (!mCommon) {
796 LOG(FATAL) << __func__ << ": the common interface was not created";
797 }
798 *_aidl_return = mCommon.getInstance();
799 LOG(DEBUG) << __func__ << ": returning " << _aidl_return->get()->asBinder().get();
800 return ndk::ScopedAStatus::ok();
801 }
802
updateHwAvSyncId(int32_t in_hwAvSyncId)803 ndk::ScopedAStatus StreamCommonImpl::updateHwAvSyncId(int32_t in_hwAvSyncId) {
804 LOG(DEBUG) << __func__ << ": id " << in_hwAvSyncId;
805 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
806 }
807
getVendorParameters(const std::vector<std::string> & in_ids,std::vector<VendorParameter> * _aidl_return)808 ndk::ScopedAStatus StreamCommonImpl::getVendorParameters(
809 const std::vector<std::string>& in_ids, std::vector<VendorParameter>* _aidl_return) {
810 LOG(DEBUG) << __func__ << ": id count: " << in_ids.size();
811 (void)_aidl_return;
812 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
813 }
814
setVendorParameters(const std::vector<VendorParameter> & in_parameters,bool in_async)815 ndk::ScopedAStatus StreamCommonImpl::setVendorParameters(
816 const std::vector<VendorParameter>& in_parameters, bool in_async) {
817 LOG(DEBUG) << __func__ << ": parameters count " << in_parameters.size()
818 << ", async: " << in_async;
819 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
820 }
821
addEffect(const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect> & in_effect)822 ndk::ScopedAStatus StreamCommonImpl::addEffect(
823 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
824 if (in_effect == nullptr) {
825 LOG(DEBUG) << __func__ << ": null effect";
826 } else {
827 LOG(DEBUG) << __func__ << ": effect Binder" << in_effect->asBinder().get();
828 }
829 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
830 }
831
removeEffect(const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect> & in_effect)832 ndk::ScopedAStatus StreamCommonImpl::removeEffect(
833 const std::shared_ptr<::aidl::android::hardware::audio::effect::IEffect>& in_effect) {
834 if (in_effect == nullptr) {
835 LOG(DEBUG) << __func__ << ": null effect";
836 } else {
837 LOG(DEBUG) << __func__ << ": effect Binder" << in_effect->asBinder().get();
838 }
839 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
840 }
841
close()842 ndk::ScopedAStatus StreamCommonImpl::close() {
843 LOG(DEBUG) << __func__;
844 if (!isClosed()) {
845 stopAndJoinWorker();
846 onClose(mWorker->setClosed());
847 return ndk::ScopedAStatus::ok();
848 } else {
849 LOG(ERROR) << __func__ << ": stream was already closed";
850 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
851 }
852 }
853
prepareToClose()854 ndk::ScopedAStatus StreamCommonImpl::prepareToClose() {
855 LOG(DEBUG) << __func__;
856 if (!isClosed()) {
857 return ndk::ScopedAStatus::ok();
858 }
859 LOG(ERROR) << __func__ << ": stream was closed";
860 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
861 }
862
cleanupWorker()863 void StreamCommonImpl::cleanupWorker() {
864 if (!isClosed()) {
865 LOG(ERROR) << __func__ << ": stream was not closed prior to destruction, resource leak";
866 stopAndJoinWorker();
867 }
868 }
869
setWorkerThreadPriority(pid_t workerTid)870 void StreamCommonImpl::setWorkerThreadPriority(pid_t workerTid) {
871 // FAST workers should be run with a SCHED_FIFO scheduler, however the host process
872 // might be lacking the capability to request it, thus a failure to set is not an error.
873 if (auto flags = getContext().getFlags();
874 (flags.getTag() == AudioIoFlags::Tag::input &&
875 isBitPositionFlagSet(flags.template get<AudioIoFlags::Tag::input>(),
876 AudioInputFlags::FAST)) ||
877 (flags.getTag() == AudioIoFlags::Tag::output &&
878 (isBitPositionFlagSet(flags.template get<AudioIoFlags::Tag::output>(),
879 AudioOutputFlags::FAST) ||
880 isBitPositionFlagSet(flags.template get<AudioIoFlags::Tag::output>(),
881 AudioOutputFlags::SPATIALIZER)))) {
882 constexpr int32_t kRTPriorityMin = 1; // SchedulingPolicyService.PRIORITY_MIN (Java).
883 constexpr int32_t kRTPriorityMax = 3; // SchedulingPolicyService.PRIORITY_MAX (Java).
884 int priorityBoost = kRTPriorityMax;
885 if (flags.getTag() == AudioIoFlags::Tag::output &&
886 isBitPositionFlagSet(flags.template get<AudioIoFlags::Tag::output>(),
887 AudioOutputFlags::SPATIALIZER)) {
888 const int32_t sptPrio =
889 property_get_int32("audio.spatializer.priority", kRTPriorityMin);
890 if (sptPrio >= kRTPriorityMin && sptPrio <= kRTPriorityMax) {
891 priorityBoost = sptPrio;
892 } else {
893 LOG(WARNING) << __func__ << ": invalid spatializer priority: " << sptPrio;
894 return;
895 }
896 }
897 struct sched_param param = {
898 .sched_priority = priorityBoost,
899 };
900 if (sched_setscheduler(workerTid, SCHED_FIFO | SCHED_RESET_ON_FORK, ¶m) != 0) {
901 PLOG(WARNING) << __func__ << ": failed to set FIFO scheduler and priority";
902 }
903 }
904 }
905
stopAndJoinWorker()906 void StreamCommonImpl::stopAndJoinWorker() {
907 stopWorker();
908 LOG(DEBUG) << __func__ << ": joining the worker thread...";
909 mWorker->join();
910 LOG(DEBUG) << __func__ << ": worker thread joined";
911 }
912
stopWorker()913 void StreamCommonImpl::stopWorker() {
914 if (auto commandMQ = mContext.getCommandMQ(); commandMQ != nullptr) {
915 LOG(DEBUG) << __func__ << ": asking the worker to exit...";
916 auto cmd = StreamDescriptor::Command::make<StreamDescriptor::Command::Tag::halReservedExit>(
917 mContext.getInternalCommandCookie() ^ mWorker->getTid());
918 // Note: never call 'pause' and 'resume' methods of StreamWorker
919 // in the HAL implementation. These methods are to be used by
920 // the client side only. Preventing the worker loop from running
921 // on the HAL side can cause a deadlock.
922 if (!commandMQ->writeBlocking(&cmd, 1)) {
923 LOG(ERROR) << __func__ << ": failed to write exit command to the MQ";
924 }
925 LOG(DEBUG) << __func__ << ": done";
926 }
927 mWorkerStopIssued = true;
928 }
929
updateMetadataCommon(const Metadata & metadata)930 ndk::ScopedAStatus StreamCommonImpl::updateMetadataCommon(const Metadata& metadata) {
931 LOG(DEBUG) << __func__;
932 if (!isClosed()) {
933 if (metadata.index() != mMetadata.index()) {
934 LOG(FATAL) << __func__ << ": changing metadata variant is not allowed";
935 }
936 mMetadata = metadata;
937 return ndk::ScopedAStatus::ok();
938 }
939 LOG(ERROR) << __func__ << ": stream was closed";
940 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
941 }
942
setConnectedDevices(const std::vector<::aidl::android::media::audio::common::AudioDevice> & devices)943 ndk::ScopedAStatus StreamCommonImpl::setConnectedDevices(
944 const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) {
945 mWorker->setIsConnected(!devices.empty());
946 mConnectedDevices = devices;
947 return ndk::ScopedAStatus::ok();
948 }
949
setGain(float gain)950 ndk::ScopedAStatus StreamCommonImpl::setGain(float gain) {
951 LOG(DEBUG) << __func__ << ": gain " << gain;
952 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
953 }
954
bluetoothParametersUpdated()955 ndk::ScopedAStatus StreamCommonImpl::bluetoothParametersUpdated() {
956 LOG(DEBUG) << __func__;
957 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
958 }
959
960 namespace {
transformMicrophones(const std::vector<MicrophoneInfo> & microphones)961 static std::map<AudioDevice, std::string> transformMicrophones(
962 const std::vector<MicrophoneInfo>& microphones) {
963 std::map<AudioDevice, std::string> result;
964 std::transform(microphones.begin(), microphones.end(), std::inserter(result, result.begin()),
965 [](const auto& mic) { return std::make_pair(mic.device, mic.id); });
966 return result;
967 }
968 } // namespace
969
StreamIn(StreamContext && context,const std::vector<MicrophoneInfo> & microphones)970 StreamIn::StreamIn(StreamContext&& context, const std::vector<MicrophoneInfo>& microphones)
971 : mContextInstance(std::move(context)), mMicrophones(transformMicrophones(microphones)) {
972 LOG(DEBUG) << __func__;
973 }
974
defaultOnClose()975 void StreamIn::defaultOnClose() {
976 mContextInstance.reset();
977 }
978
getActiveMicrophones(std::vector<MicrophoneDynamicInfo> * _aidl_return)979 ndk::ScopedAStatus StreamIn::getActiveMicrophones(
980 std::vector<MicrophoneDynamicInfo>* _aidl_return) {
981 std::vector<MicrophoneDynamicInfo> result;
982 std::vector<MicrophoneDynamicInfo::ChannelMapping> channelMapping{
983 getChannelCount(getContext().getChannelLayout()),
984 MicrophoneDynamicInfo::ChannelMapping::DIRECT};
985 for (auto it = getConnectedDevices().begin(); it != getConnectedDevices().end(); ++it) {
986 if (auto micIt = mMicrophones.find(*it); micIt != mMicrophones.end()) {
987 MicrophoneDynamicInfo dynMic;
988 dynMic.id = micIt->second;
989 dynMic.channelMapping = channelMapping;
990 result.push_back(std::move(dynMic));
991 }
992 }
993 *_aidl_return = std::move(result);
994 LOG(DEBUG) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return);
995 return ndk::ScopedAStatus::ok();
996 }
997
getMicrophoneDirection(MicrophoneDirection * _aidl_return)998 ndk::ScopedAStatus StreamIn::getMicrophoneDirection(MicrophoneDirection* _aidl_return) {
999 LOG(DEBUG) << __func__;
1000 (void)_aidl_return;
1001 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1002 }
1003
setMicrophoneDirection(MicrophoneDirection in_direction)1004 ndk::ScopedAStatus StreamIn::setMicrophoneDirection(MicrophoneDirection in_direction) {
1005 LOG(DEBUG) << __func__ << ": direction " << toString(in_direction);
1006 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1007 }
1008
getMicrophoneFieldDimension(float * _aidl_return)1009 ndk::ScopedAStatus StreamIn::getMicrophoneFieldDimension(float* _aidl_return) {
1010 LOG(DEBUG) << __func__;
1011 (void)_aidl_return;
1012 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1013 }
1014
setMicrophoneFieldDimension(float in_zoom)1015 ndk::ScopedAStatus StreamIn::setMicrophoneFieldDimension(float in_zoom) {
1016 LOG(DEBUG) << __func__ << ": zoom " << in_zoom;
1017 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1018 }
1019
getHwGain(std::vector<float> * _aidl_return)1020 ndk::ScopedAStatus StreamIn::getHwGain(std::vector<float>* _aidl_return) {
1021 LOG(DEBUG) << __func__;
1022 (void)_aidl_return;
1023 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1024 }
1025
setHwGain(const std::vector<float> & in_channelGains)1026 ndk::ScopedAStatus StreamIn::setHwGain(const std::vector<float>& in_channelGains) {
1027 LOG(DEBUG) << __func__ << ": gains " << ::android::internal::ToString(in_channelGains);
1028 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1029 }
1030
StreamInHwGainHelper(const StreamContext * context)1031 StreamInHwGainHelper::StreamInHwGainHelper(const StreamContext* context)
1032 : mChannelCount(getChannelCount(context->getChannelLayout())) {}
1033
getHwGainImpl(std::vector<float> * _aidl_return)1034 ndk::ScopedAStatus StreamInHwGainHelper::getHwGainImpl(std::vector<float>* _aidl_return) {
1035 if (mHwGains.empty()) {
1036 mHwGains.resize(mChannelCount, 0.0f);
1037 }
1038 *_aidl_return = mHwGains;
1039 LOG(DEBUG) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return);
1040 return ndk::ScopedAStatus::ok();
1041 }
1042
setHwGainImpl(const std::vector<float> & in_channelGains)1043 ndk::ScopedAStatus StreamInHwGainHelper::setHwGainImpl(const std::vector<float>& in_channelGains) {
1044 LOG(DEBUG) << __func__ << ": gains " << ::android::internal::ToString(in_channelGains);
1045 if (in_channelGains.size() != mChannelCount) {
1046 LOG(ERROR) << __func__
1047 << ": channel count does not match stream channel count: " << mChannelCount;
1048 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1049 }
1050 for (float gain : in_channelGains) {
1051 if (gain < StreamIn::HW_GAIN_MIN || gain > StreamIn::HW_GAIN_MAX) {
1052 LOG(ERROR) << __func__ << ": gain value out of range: " << gain;
1053 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1054 }
1055 }
1056 mHwGains = in_channelGains;
1057 return ndk::ScopedAStatus::ok();
1058 }
1059
StreamOut(StreamContext && context,const std::optional<AudioOffloadInfo> & offloadInfo)1060 StreamOut::StreamOut(StreamContext&& context, const std::optional<AudioOffloadInfo>& offloadInfo)
1061 : mContextInstance(std::move(context)), mOffloadInfo(offloadInfo) {
1062 LOG(DEBUG) << __func__;
1063 }
1064
defaultOnClose()1065 void StreamOut::defaultOnClose() {
1066 mContextInstance.reset();
1067 }
1068
updateOffloadMetadata(const AudioOffloadMetadata & in_offloadMetadata)1069 ndk::ScopedAStatus StreamOut::updateOffloadMetadata(
1070 const AudioOffloadMetadata& in_offloadMetadata) {
1071 LOG(DEBUG) << __func__;
1072 if (isClosed()) {
1073 LOG(ERROR) << __func__ << ": stream was closed";
1074 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
1075 }
1076 if (!mOffloadInfo.has_value()) {
1077 LOG(ERROR) << __func__ << ": not a compressed offload stream";
1078 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1079 }
1080 if (in_offloadMetadata.sampleRate < 0) {
1081 LOG(ERROR) << __func__ << ": invalid sample rate value: " << in_offloadMetadata.sampleRate;
1082 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1083 }
1084 if (in_offloadMetadata.averageBitRatePerSecond < 0) {
1085 LOG(ERROR) << __func__
1086 << ": invalid average BPS value: " << in_offloadMetadata.averageBitRatePerSecond;
1087 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1088 }
1089 if (in_offloadMetadata.delayFrames < 0) {
1090 LOG(ERROR) << __func__
1091 << ": invalid delay frames value: " << in_offloadMetadata.delayFrames;
1092 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1093 }
1094 if (in_offloadMetadata.paddingFrames < 0) {
1095 LOG(ERROR) << __func__
1096 << ": invalid padding frames value: " << in_offloadMetadata.paddingFrames;
1097 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1098 }
1099 mOffloadMetadata = in_offloadMetadata;
1100 return ndk::ScopedAStatus::ok();
1101 }
1102
getHwVolume(std::vector<float> * _aidl_return)1103 ndk::ScopedAStatus StreamOut::getHwVolume(std::vector<float>* _aidl_return) {
1104 LOG(DEBUG) << __func__;
1105 (void)_aidl_return;
1106 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1107 }
1108
setHwVolume(const std::vector<float> & in_channelVolumes)1109 ndk::ScopedAStatus StreamOut::setHwVolume(const std::vector<float>& in_channelVolumes) {
1110 LOG(DEBUG) << __func__ << ": gains " << ::android::internal::ToString(in_channelVolumes);
1111 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1112 }
1113
getAudioDescriptionMixLevel(float * _aidl_return)1114 ndk::ScopedAStatus StreamOut::getAudioDescriptionMixLevel(float* _aidl_return) {
1115 LOG(DEBUG) << __func__;
1116 (void)_aidl_return;
1117 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1118 }
1119
setAudioDescriptionMixLevel(float in_leveldB)1120 ndk::ScopedAStatus StreamOut::setAudioDescriptionMixLevel(float in_leveldB) {
1121 LOG(DEBUG) << __func__ << ": description mix level " << in_leveldB;
1122 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1123 }
1124
getDualMonoMode(AudioDualMonoMode * _aidl_return)1125 ndk::ScopedAStatus StreamOut::getDualMonoMode(AudioDualMonoMode* _aidl_return) {
1126 LOG(DEBUG) << __func__;
1127 (void)_aidl_return;
1128 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1129 }
1130
setDualMonoMode(AudioDualMonoMode in_mode)1131 ndk::ScopedAStatus StreamOut::setDualMonoMode(AudioDualMonoMode in_mode) {
1132 LOG(DEBUG) << __func__ << ": dual mono mode " << toString(in_mode);
1133 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1134 }
1135
getRecommendedLatencyModes(std::vector<AudioLatencyMode> * _aidl_return)1136 ndk::ScopedAStatus StreamOut::getRecommendedLatencyModes(
1137 std::vector<AudioLatencyMode>* _aidl_return) {
1138 LOG(DEBUG) << __func__;
1139 (void)_aidl_return;
1140 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1141 }
1142
setLatencyMode(AudioLatencyMode in_mode)1143 ndk::ScopedAStatus StreamOut::setLatencyMode(AudioLatencyMode in_mode) {
1144 LOG(DEBUG) << __func__ << ": latency mode " << toString(in_mode);
1145 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1146 }
1147
getPlaybackRateParameters(AudioPlaybackRate * _aidl_return)1148 ndk::ScopedAStatus StreamOut::getPlaybackRateParameters(AudioPlaybackRate* _aidl_return) {
1149 LOG(DEBUG) << __func__;
1150 (void)_aidl_return;
1151 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1152 }
1153
setPlaybackRateParameters(const AudioPlaybackRate & in_playbackRate)1154 ndk::ScopedAStatus StreamOut::setPlaybackRateParameters(const AudioPlaybackRate& in_playbackRate) {
1155 LOG(DEBUG) << __func__ << ": " << in_playbackRate.toString();
1156 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1157 }
1158
selectPresentation(int32_t in_presentationId,int32_t in_programId)1159 ndk::ScopedAStatus StreamOut::selectPresentation(int32_t in_presentationId, int32_t in_programId) {
1160 LOG(DEBUG) << __func__ << ": presentationId " << in_presentationId << ", programId "
1161 << in_programId;
1162 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
1163 }
1164
StreamOutHwVolumeHelper(const StreamContext * context)1165 StreamOutHwVolumeHelper::StreamOutHwVolumeHelper(const StreamContext* context)
1166 : mChannelCount(getChannelCount(context->getChannelLayout())) {}
1167
getHwVolumeImpl(std::vector<float> * _aidl_return)1168 ndk::ScopedAStatus StreamOutHwVolumeHelper::getHwVolumeImpl(std::vector<float>* _aidl_return) {
1169 if (mHwVolumes.empty()) {
1170 mHwVolumes.resize(mChannelCount, 0.0f);
1171 }
1172 *_aidl_return = mHwVolumes;
1173 LOG(DEBUG) << __func__ << ": returning " << ::android::internal::ToString(*_aidl_return);
1174 return ndk::ScopedAStatus::ok();
1175 }
1176
setHwVolumeImpl(const std::vector<float> & in_channelVolumes)1177 ndk::ScopedAStatus StreamOutHwVolumeHelper::setHwVolumeImpl(
1178 const std::vector<float>& in_channelVolumes) {
1179 LOG(DEBUG) << __func__ << ": volumes " << ::android::internal::ToString(in_channelVolumes);
1180 if (in_channelVolumes.size() != mChannelCount) {
1181 LOG(ERROR) << __func__
1182 << ": channel count does not match stream channel count: " << mChannelCount;
1183 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1184 }
1185 for (float volume : in_channelVolumes) {
1186 if (volume < StreamOut::HW_VOLUME_MIN || volume > StreamOut::HW_VOLUME_MAX) {
1187 LOG(ERROR) << __func__ << ": volume value out of range: " << volume;
1188 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
1189 }
1190 }
1191 mHwVolumes = in_channelVolumes;
1192 return ndk::ScopedAStatus::ok();
1193 }
1194
1195 } // namespace aidl::android::hardware::audio::core
1196