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