1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "StreamOutHAL"
18
19 #include "core/default/StreamOut.h"
20 #include "core/default/Util.h"
21
22 //#define LOG_NDEBUG 0
23 #define ATRACE_TAG ATRACE_TAG_AUDIO
24
25 #include <string.h>
26
27 #include <memory>
28
29 #include <android/log.h>
30 #include <hardware/audio.h>
31 #include <utils/Trace.h>
32
33 namespace android {
34 namespace hardware {
35 namespace audio {
36 namespace CPP_VERSION {
37 namespace implementation {
38
39 namespace {
40
41 class WriteThread : public Thread {
42 public:
43 // WriteThread's lifespan never exceeds StreamOut's lifespan.
WriteThread(std::atomic<bool> * stop,audio_stream_out_t * stream,StreamOut::CommandMQ * commandMQ,StreamOut::DataMQ * dataMQ,StreamOut::StatusMQ * statusMQ,EventFlag * efGroup)44 WriteThread(std::atomic<bool>* stop, audio_stream_out_t* stream,
45 StreamOut::CommandMQ* commandMQ, StreamOut::DataMQ* dataMQ,
46 StreamOut::StatusMQ* statusMQ, EventFlag* efGroup)
47 : Thread(false /*canCallJava*/),
48 mStop(stop),
49 mStream(stream),
50 mCommandMQ(commandMQ),
51 mDataMQ(dataMQ),
52 mStatusMQ(statusMQ),
53 mEfGroup(efGroup),
54 mBuffer(nullptr) {}
init()55 bool init() {
56 mBuffer.reset(new (std::nothrow) uint8_t[mDataMQ->getQuantumCount()]);
57 return mBuffer != nullptr;
58 }
~WriteThread()59 virtual ~WriteThread() {}
60
61 private:
62 std::atomic<bool>* mStop;
63 audio_stream_out_t* mStream;
64 StreamOut::CommandMQ* mCommandMQ;
65 StreamOut::DataMQ* mDataMQ;
66 StreamOut::StatusMQ* mStatusMQ;
67 EventFlag* mEfGroup;
68 std::unique_ptr<uint8_t[]> mBuffer;
69 IStreamOut::WriteStatus mStatus;
70
71 bool threadLoop() override;
72
73 void doGetLatency();
74 void doGetPresentationPosition();
75 void doWrite();
76 };
77
doWrite()78 void WriteThread::doWrite() {
79 const size_t availToRead = mDataMQ->availableToRead();
80 mStatus.retval = Result::OK;
81 mStatus.reply.written = 0;
82 if (mDataMQ->read(&mBuffer[0], availToRead)) {
83 ssize_t writeResult = mStream->write(mStream, &mBuffer[0], availToRead);
84 if (writeResult >= 0) {
85 mStatus.reply.written = writeResult;
86 } else {
87 mStatus.retval = Stream::analyzeStatus("write", writeResult);
88 }
89 }
90 }
91
doGetPresentationPosition()92 void WriteThread::doGetPresentationPosition() {
93 mStatus.retval =
94 StreamOut::getPresentationPositionImpl(mStream, &mStatus.reply.presentationPosition.frames,
95 &mStatus.reply.presentationPosition.timeStamp);
96 }
97
doGetLatency()98 void WriteThread::doGetLatency() {
99 mStatus.retval = Result::OK;
100 mStatus.reply.latencyMs = mStream->get_latency(mStream);
101 }
102
threadLoop()103 bool WriteThread::threadLoop() {
104 // This implementation doesn't return control back to the Thread until it
105 // decides to stop,
106 // as the Thread uses mutexes, and this can lead to priority inversion.
107 while (!std::atomic_load_explicit(mStop, std::memory_order_acquire)) {
108 uint32_t efState = 0;
109 mEfGroup->wait(static_cast<uint32_t>(MessageQueueFlagBits::NOT_EMPTY), &efState);
110 if (!(efState & static_cast<uint32_t>(MessageQueueFlagBits::NOT_EMPTY))) {
111 continue; // Nothing to do.
112 }
113 if (!mCommandMQ->read(&mStatus.replyTo)) {
114 continue; // Nothing to do.
115 }
116 switch (mStatus.replyTo) {
117 case IStreamOut::WriteCommand::WRITE:
118 doWrite();
119 break;
120 case IStreamOut::WriteCommand::GET_PRESENTATION_POSITION:
121 doGetPresentationPosition();
122 break;
123 case IStreamOut::WriteCommand::GET_LATENCY:
124 doGetLatency();
125 break;
126 default:
127 ALOGE("Unknown write thread command code %d", mStatus.replyTo);
128 mStatus.retval = Result::NOT_SUPPORTED;
129 break;
130 }
131 if (!mStatusMQ->write(&mStatus)) {
132 ALOGE("status message queue write failed");
133 }
134 mEfGroup->wake(static_cast<uint32_t>(MessageQueueFlagBits::NOT_FULL));
135 }
136
137 return false;
138 }
139
140 } // namespace
141
StreamOut(const sp<Device> & device,audio_stream_out_t * stream)142 StreamOut::StreamOut(const sp<Device>& device, audio_stream_out_t* stream)
143 : mDevice(device),
144 mStream(stream),
145 mStreamCommon(new Stream(&stream->common)),
146 mStreamMmap(new StreamMmap<audio_stream_out_t>(stream)),
147 mEfGroup(nullptr),
148 mStopWriteThread(false) {}
149
~StreamOut()150 StreamOut::~StreamOut() {
151 ATRACE_CALL();
152 (void)close();
153 if (mWriteThread.get()) {
154 ATRACE_NAME("mWriteThread->join");
155 status_t status = mWriteThread->join();
156 ALOGE_IF(status, "write thread exit error: %s", strerror(-status));
157 }
158 if (mEfGroup) {
159 status_t status = EventFlag::deleteEventFlag(&mEfGroup);
160 ALOGE_IF(status, "write MQ event flag deletion error: %s", strerror(-status));
161 }
162 mCallback.clear();
163 #if MAJOR_VERSION <= 5
164 mDevice->closeOutputStream(mStream);
165 // Closing the output stream in the HAL waits for the callback to finish,
166 // and joins the callback thread. Thus is it guaranteed that the callback
167 // thread will not be accessing our object anymore.
168 #endif
169 mStream = nullptr;
170 }
171
172 // Methods from ::android::hardware::audio::CPP_VERSION::IStream follow.
getFrameSize()173 Return<uint64_t> StreamOut::getFrameSize() {
174 return audio_stream_out_frame_size(mStream);
175 }
176
getFrameCount()177 Return<uint64_t> StreamOut::getFrameCount() {
178 return mStreamCommon->getFrameCount();
179 }
180
getBufferSize()181 Return<uint64_t> StreamOut::getBufferSize() {
182 return mStreamCommon->getBufferSize();
183 }
184
getSampleRate()185 Return<uint32_t> StreamOut::getSampleRate() {
186 return mStreamCommon->getSampleRate();
187 }
188
189 #if MAJOR_VERSION == 2
getSupportedChannelMasks(getSupportedChannelMasks_cb _hidl_cb)190 Return<void> StreamOut::getSupportedChannelMasks(getSupportedChannelMasks_cb _hidl_cb) {
191 return mStreamCommon->getSupportedChannelMasks(_hidl_cb);
192 }
getSupportedSampleRates(getSupportedSampleRates_cb _hidl_cb)193 Return<void> StreamOut::getSupportedSampleRates(getSupportedSampleRates_cb _hidl_cb) {
194 return mStreamCommon->getSupportedSampleRates(_hidl_cb);
195 }
196 #endif
197
getSupportedChannelMasks(AudioFormat format,getSupportedChannelMasks_cb _hidl_cb)198 Return<void> StreamOut::getSupportedChannelMasks(AudioFormat format,
199 getSupportedChannelMasks_cb _hidl_cb) {
200 return mStreamCommon->getSupportedChannelMasks(format, _hidl_cb);
201 }
getSupportedSampleRates(AudioFormat format,getSupportedSampleRates_cb _hidl_cb)202 Return<void> StreamOut::getSupportedSampleRates(AudioFormat format,
203 getSupportedSampleRates_cb _hidl_cb) {
204 return mStreamCommon->getSupportedSampleRates(format, _hidl_cb);
205 }
206
setSampleRate(uint32_t sampleRateHz)207 Return<Result> StreamOut::setSampleRate(uint32_t sampleRateHz) {
208 return mStreamCommon->setSampleRate(sampleRateHz);
209 }
210
getChannelMask()211 Return<AudioChannelBitfield> StreamOut::getChannelMask() {
212 return mStreamCommon->getChannelMask();
213 }
214
setChannelMask(AudioChannelBitfield mask)215 Return<Result> StreamOut::setChannelMask(AudioChannelBitfield mask) {
216 return mStreamCommon->setChannelMask(mask);
217 }
218
getFormat()219 Return<AudioFormat> StreamOut::getFormat() {
220 return mStreamCommon->getFormat();
221 }
222
getSupportedFormats(getSupportedFormats_cb _hidl_cb)223 Return<void> StreamOut::getSupportedFormats(getSupportedFormats_cb _hidl_cb) {
224 return mStreamCommon->getSupportedFormats(_hidl_cb);
225 }
226
setFormat(AudioFormat format)227 Return<Result> StreamOut::setFormat(AudioFormat format) {
228 return mStreamCommon->setFormat(format);
229 }
230
getAudioProperties(getAudioProperties_cb _hidl_cb)231 Return<void> StreamOut::getAudioProperties(getAudioProperties_cb _hidl_cb) {
232 return mStreamCommon->getAudioProperties(_hidl_cb);
233 }
234
addEffect(uint64_t effectId)235 Return<Result> StreamOut::addEffect(uint64_t effectId) {
236 return mStreamCommon->addEffect(effectId);
237 }
238
removeEffect(uint64_t effectId)239 Return<Result> StreamOut::removeEffect(uint64_t effectId) {
240 return mStreamCommon->removeEffect(effectId);
241 }
242
standby()243 Return<Result> StreamOut::standby() {
244 return mStreamCommon->standby();
245 }
246
setHwAvSync(uint32_t hwAvSync)247 Return<Result> StreamOut::setHwAvSync(uint32_t hwAvSync) {
248 return mStreamCommon->setHwAvSync(hwAvSync);
249 }
250
251 #if MAJOR_VERSION == 2
setConnectedState(const DeviceAddress & address,bool connected)252 Return<Result> StreamOut::setConnectedState(const DeviceAddress& address, bool connected) {
253 return mStreamCommon->setConnectedState(address, connected);
254 }
255
getDevice()256 Return<AudioDevice> StreamOut::getDevice() {
257 return mStreamCommon->getDevice();
258 }
259
setDevice(const DeviceAddress & address)260 Return<Result> StreamOut::setDevice(const DeviceAddress& address) {
261 return mStreamCommon->setDevice(address);
262 }
263
getParameters(const hidl_vec<hidl_string> & keys,getParameters_cb _hidl_cb)264 Return<void> StreamOut::getParameters(const hidl_vec<hidl_string>& keys,
265 getParameters_cb _hidl_cb) {
266 return mStreamCommon->getParameters(keys, _hidl_cb);
267 }
268
setParameters(const hidl_vec<ParameterValue> & parameters)269 Return<Result> StreamOut::setParameters(const hidl_vec<ParameterValue>& parameters) {
270 return mStreamCommon->setParameters(parameters);
271 }
272
debugDump(const hidl_handle & fd)273 Return<void> StreamOut::debugDump(const hidl_handle& fd) {
274 return mStreamCommon->debugDump(fd);
275 }
276 #elif MAJOR_VERSION >= 4
getDevices(getDevices_cb _hidl_cb)277 Return<void> StreamOut::getDevices(getDevices_cb _hidl_cb) {
278 return mStreamCommon->getDevices(_hidl_cb);
279 }
280
setDevices(const hidl_vec<DeviceAddress> & devices)281 Return<Result> StreamOut::setDevices(const hidl_vec<DeviceAddress>& devices) {
282 return mStreamCommon->setDevices(devices);
283 }
getParameters(const hidl_vec<ParameterValue> & context,const hidl_vec<hidl_string> & keys,getParameters_cb _hidl_cb)284 Return<void> StreamOut::getParameters(const hidl_vec<ParameterValue>& context,
285 const hidl_vec<hidl_string>& keys,
286 getParameters_cb _hidl_cb) {
287 return mStreamCommon->getParameters(context, keys, _hidl_cb);
288 }
289
setParameters(const hidl_vec<ParameterValue> & context,const hidl_vec<ParameterValue> & parameters)290 Return<Result> StreamOut::setParameters(const hidl_vec<ParameterValue>& context,
291 const hidl_vec<ParameterValue>& parameters) {
292 return mStreamCommon->setParameters(context, parameters);
293 }
294 #endif
295
close()296 Return<Result> StreamOut::close() {
297 if (mStopWriteThread.load(std::memory_order_relaxed)) { // only this thread writes
298 return Result::INVALID_STATE;
299 }
300 mStopWriteThread.store(true, std::memory_order_release);
301 if (mEfGroup) {
302 mEfGroup->wake(static_cast<uint32_t>(MessageQueueFlagBits::NOT_EMPTY));
303 }
304 #if MAJOR_VERSION >= 6
305 mDevice->closeOutputStream(mStream);
306 #endif
307 return Result::OK;
308 }
309
310 // Methods from ::android::hardware::audio::CPP_VERSION::IStreamOut follow.
getLatency()311 Return<uint32_t> StreamOut::getLatency() {
312 return mStream->get_latency(mStream);
313 }
314
setVolume(float left,float right)315 Return<Result> StreamOut::setVolume(float left, float right) {
316 if (mStream->set_volume == NULL) {
317 return Result::NOT_SUPPORTED;
318 }
319 if (!isGainNormalized(left)) {
320 ALOGW("Can not set a stream output volume {%f, %f} outside [0,1]", left, right);
321 return Result::INVALID_ARGUMENTS;
322 }
323 return Stream::analyzeStatus("set_volume", mStream->set_volume(mStream, left, right),
324 {ENOSYS} /*ignore*/);
325 }
326
prepareForWriting(uint32_t frameSize,uint32_t framesCount,prepareForWriting_cb _hidl_cb)327 Return<void> StreamOut::prepareForWriting(uint32_t frameSize, uint32_t framesCount,
328 prepareForWriting_cb _hidl_cb) {
329 status_t status;
330 ThreadInfo threadInfo = {0, 0};
331
332 // Wrap the _hidl_cb to return an error
333 auto sendError = [&threadInfo, &_hidl_cb](Result result) {
334 _hidl_cb(result, CommandMQ::Descriptor(), DataMQ::Descriptor(), StatusMQ::Descriptor(),
335 threadInfo);
336 };
337
338 // Create message queues.
339 if (mDataMQ) {
340 ALOGE("the client attempts to call prepareForWriting twice");
341 sendError(Result::INVALID_STATE);
342 return Void();
343 }
344 std::unique_ptr<CommandMQ> tempCommandMQ(new CommandMQ(1));
345
346 // Check frameSize and framesCount
347 if (frameSize == 0 || framesCount == 0) {
348 ALOGE("Null frameSize (%u) or framesCount (%u)", frameSize, framesCount);
349 sendError(Result::INVALID_ARGUMENTS);
350 return Void();
351 }
352 if (frameSize > Stream::MAX_BUFFER_SIZE / framesCount) {
353 ALOGE("Buffer too big: %u*%u bytes > MAX_BUFFER_SIZE (%u)", frameSize, framesCount,
354 Stream::MAX_BUFFER_SIZE);
355 sendError(Result::INVALID_ARGUMENTS);
356 return Void();
357 }
358 std::unique_ptr<DataMQ> tempDataMQ(new DataMQ(frameSize * framesCount, true /* EventFlag */));
359
360 std::unique_ptr<StatusMQ> tempStatusMQ(new StatusMQ(1));
361 if (!tempCommandMQ->isValid() || !tempDataMQ->isValid() || !tempStatusMQ->isValid()) {
362 ALOGE_IF(!tempCommandMQ->isValid(), "command MQ is invalid");
363 ALOGE_IF(!tempDataMQ->isValid(), "data MQ is invalid");
364 ALOGE_IF(!tempStatusMQ->isValid(), "status MQ is invalid");
365 sendError(Result::INVALID_ARGUMENTS);
366 return Void();
367 }
368 EventFlag* tempRawEfGroup{};
369 status = EventFlag::createEventFlag(tempDataMQ->getEventFlagWord(), &tempRawEfGroup);
370 std::unique_ptr<EventFlag, void (*)(EventFlag*)> tempElfGroup(
371 tempRawEfGroup, [](auto* ef) { EventFlag::deleteEventFlag(&ef); });
372 if (status != OK || !tempElfGroup) {
373 ALOGE("failed creating event flag for data MQ: %s", strerror(-status));
374 sendError(Result::INVALID_ARGUMENTS);
375 return Void();
376 }
377
378 // Create and launch the thread.
379 auto tempWriteThread =
380 std::make_unique<WriteThread>(&mStopWriteThread, mStream, tempCommandMQ.get(),
381 tempDataMQ.get(), tempStatusMQ.get(), tempElfGroup.get());
382 if (!tempWriteThread->init()) {
383 ALOGW("failed to start writer thread: %s", strerror(-status));
384 sendError(Result::INVALID_ARGUMENTS);
385 return Void();
386 }
387 status = tempWriteThread->run("writer", PRIORITY_URGENT_AUDIO);
388 if (status != OK) {
389 ALOGW("failed to start writer thread: %s", strerror(-status));
390 sendError(Result::INVALID_ARGUMENTS);
391 return Void();
392 }
393
394 mCommandMQ = std::move(tempCommandMQ);
395 mDataMQ = std::move(tempDataMQ);
396 mStatusMQ = std::move(tempStatusMQ);
397 mWriteThread = tempWriteThread.release();
398 mEfGroup = tempElfGroup.release();
399 threadInfo.pid = getpid();
400 threadInfo.tid = mWriteThread->getTid();
401 _hidl_cb(Result::OK, *mCommandMQ->getDesc(), *mDataMQ->getDesc(), *mStatusMQ->getDesc(),
402 threadInfo);
403 return Void();
404 }
405
getRenderPosition(getRenderPosition_cb _hidl_cb)406 Return<void> StreamOut::getRenderPosition(getRenderPosition_cb _hidl_cb) {
407 uint32_t halDspFrames;
408 Result retval = Stream::analyzeStatus("get_render_position",
409 mStream->get_render_position(mStream, &halDspFrames),
410 {ENOSYS} /*ignore*/);
411 _hidl_cb(retval, halDspFrames);
412 return Void();
413 }
414
getNextWriteTimestamp(getNextWriteTimestamp_cb _hidl_cb)415 Return<void> StreamOut::getNextWriteTimestamp(getNextWriteTimestamp_cb _hidl_cb) {
416 Result retval(Result::NOT_SUPPORTED);
417 int64_t timestampUs = 0;
418 if (mStream->get_next_write_timestamp != NULL) {
419 retval = Stream::analyzeStatus("get_next_write_timestamp",
420 mStream->get_next_write_timestamp(mStream, ×tampUs),
421 {ENOSYS} /*ignore*/);
422 }
423 _hidl_cb(retval, timestampUs);
424 return Void();
425 }
426
setCallback(const sp<IStreamOutCallback> & callback)427 Return<Result> StreamOut::setCallback(const sp<IStreamOutCallback>& callback) {
428 if (mStream->set_callback == NULL) return Result::NOT_SUPPORTED;
429 // Safe to pass 'this' because it is guaranteed that the callback thread
430 // is joined prior to exit from StreamOut's destructor.
431 int result = mStream->set_callback(mStream, StreamOut::asyncCallback, this);
432 if (result == 0) {
433 mCallback = callback;
434 }
435 return Stream::analyzeStatus("set_callback", result, {ENOSYS} /*ignore*/);
436 }
437
clearCallback()438 Return<Result> StreamOut::clearCallback() {
439 if (mStream->set_callback == NULL) return Result::NOT_SUPPORTED;
440 mCallback.clear();
441 return Result::OK;
442 }
443
444 // static
asyncCallback(stream_callback_event_t event,void *,void * cookie)445 int StreamOut::asyncCallback(stream_callback_event_t event, void*, void* cookie) {
446 // It is guaranteed that the callback thread is joined prior
447 // to exiting from StreamOut's destructor. Must *not* use sp<StreamOut>
448 // here because it can make this code the last owner of StreamOut,
449 // and an attempt to run the destructor on the callback thread
450 // will cause a deadlock in the legacy HAL code.
451 StreamOut* self = reinterpret_cast<StreamOut*>(cookie);
452 // It's correct to hold an sp<> to callback because the reference
453 // in the StreamOut instance can be cleared in the meantime. There is
454 // no difference on which thread to run IStreamOutCallback's destructor.
455 sp<IStreamOutCallback> callback = self->mCallback;
456 if (callback.get() == nullptr) return 0;
457 ALOGV("asyncCallback() event %d", event);
458 Return<void> result;
459 switch (event) {
460 case STREAM_CBK_EVENT_WRITE_READY:
461 result = callback->onWriteReady();
462 break;
463 case STREAM_CBK_EVENT_DRAIN_READY:
464 result = callback->onDrainReady();
465 break;
466 case STREAM_CBK_EVENT_ERROR:
467 result = callback->onError();
468 break;
469 default:
470 ALOGW("asyncCallback() unknown event %d", event);
471 break;
472 }
473 ALOGW_IF(!result.isOk(), "Client callback failed: %s", result.description().c_str());
474 return 0;
475 }
476
supportsPauseAndResume(supportsPauseAndResume_cb _hidl_cb)477 Return<void> StreamOut::supportsPauseAndResume(supportsPauseAndResume_cb _hidl_cb) {
478 _hidl_cb(mStream->pause != NULL, mStream->resume != NULL);
479 return Void();
480 }
481
pause()482 Return<Result> StreamOut::pause() {
483 return mStream->pause != NULL
484 ? Stream::analyzeStatus("pause", mStream->pause(mStream), {ENOSYS} /*ignore*/)
485 : Result::NOT_SUPPORTED;
486 }
487
resume()488 Return<Result> StreamOut::resume() {
489 return mStream->resume != NULL
490 ? Stream::analyzeStatus("resume", mStream->resume(mStream), {ENOSYS} /*ignore*/)
491 : Result::NOT_SUPPORTED;
492 }
493
supportsDrain()494 Return<bool> StreamOut::supportsDrain() {
495 return mStream->drain != NULL;
496 }
497
drain(AudioDrain type)498 Return<Result> StreamOut::drain(AudioDrain type) {
499 return mStream->drain != NULL
500 ? Stream::analyzeStatus(
501 "drain",
502 mStream->drain(mStream, static_cast<audio_drain_type_t>(type)),
503 {ENOSYS} /*ignore*/)
504 : Result::NOT_SUPPORTED;
505 }
506
flush()507 Return<Result> StreamOut::flush() {
508 return mStream->flush != NULL
509 ? Stream::analyzeStatus("flush", mStream->flush(mStream), {ENOSYS} /*ignore*/)
510 : Result::NOT_SUPPORTED;
511 }
512
513 // static
getPresentationPositionImpl(audio_stream_out_t * stream,uint64_t * frames,TimeSpec * timeStamp)514 Result StreamOut::getPresentationPositionImpl(audio_stream_out_t* stream, uint64_t* frames,
515 TimeSpec* timeStamp) {
516 // Don't logspam on EINVAL--it's normal for get_presentation_position
517 // to return it sometimes. EAGAIN may be returned by A2DP audio HAL
518 // implementation. ENODATA can also be reported while the writer is
519 // continuously querying it, but the stream has been stopped.
520 static const std::vector<int> ignoredErrors{EINVAL, EAGAIN, ENODATA, ENOSYS};
521 Result retval(Result::NOT_SUPPORTED);
522 if (stream->get_presentation_position == NULL) return retval;
523 struct timespec halTimeStamp;
524 retval = Stream::analyzeStatus("get_presentation_position",
525 stream->get_presentation_position(stream, frames, &halTimeStamp),
526 ignoredErrors);
527 if (retval == Result::OK) {
528 timeStamp->tvSec = halTimeStamp.tv_sec;
529 timeStamp->tvNSec = halTimeStamp.tv_nsec;
530 }
531 return retval;
532 }
533
getPresentationPosition(getPresentationPosition_cb _hidl_cb)534 Return<void> StreamOut::getPresentationPosition(getPresentationPosition_cb _hidl_cb) {
535 uint64_t frames = 0;
536 TimeSpec timeStamp = {0, 0};
537 Result retval = getPresentationPositionImpl(mStream, &frames, &timeStamp);
538 _hidl_cb(retval, frames, timeStamp);
539 return Void();
540 }
541
start()542 Return<Result> StreamOut::start() {
543 return mStreamMmap->start();
544 }
545
stop()546 Return<Result> StreamOut::stop() {
547 return mStreamMmap->stop();
548 }
549
createMmapBuffer(int32_t minSizeFrames,createMmapBuffer_cb _hidl_cb)550 Return<void> StreamOut::createMmapBuffer(int32_t minSizeFrames, createMmapBuffer_cb _hidl_cb) {
551 return mStreamMmap->createMmapBuffer(minSizeFrames, audio_stream_out_frame_size(mStream),
552 _hidl_cb);
553 }
554
getMmapPosition(getMmapPosition_cb _hidl_cb)555 Return<void> StreamOut::getMmapPosition(getMmapPosition_cb _hidl_cb) {
556 return mStreamMmap->getMmapPosition(_hidl_cb);
557 }
558
debug(const hidl_handle & fd,const hidl_vec<hidl_string> & options)559 Return<void> StreamOut::debug(const hidl_handle& fd, const hidl_vec<hidl_string>& options) {
560 return mStreamCommon->debug(fd, options);
561 }
562
563 #if MAJOR_VERSION >= 4
updateSourceMetadata(const SourceMetadata & sourceMetadata)564 Return<void> StreamOut::updateSourceMetadata(const SourceMetadata& sourceMetadata) {
565 if (mStream->update_source_metadata == nullptr) {
566 return Void(); // not supported by the HAL
567 }
568 std::vector<playback_track_metadata> halTracks;
569 halTracks.reserve(sourceMetadata.tracks.size());
570 for (auto& metadata : sourceMetadata.tracks) {
571 halTracks.push_back({
572 .usage = static_cast<audio_usage_t>(metadata.usage),
573 .content_type = static_cast<audio_content_type_t>(metadata.contentType),
574 .gain = metadata.gain,
575 });
576 }
577 const source_metadata_t halMetadata = {
578 .track_count = halTracks.size(),
579 .tracks = halTracks.data(),
580 };
581 mStream->update_source_metadata(mStream, &halMetadata);
582 return Void();
583 }
selectPresentation(int32_t,int32_t)584 Return<Result> StreamOut::selectPresentation(int32_t /*presentationId*/, int32_t /*programId*/) {
585 return Result::NOT_SUPPORTED; // TODO: propagate to legacy
586 }
587 #endif
588
589 #if MAJOR_VERSION >= 6
getDualMonoMode(getDualMonoMode_cb _hidl_cb)590 Return<void> StreamOut::getDualMonoMode(getDualMonoMode_cb _hidl_cb) {
591 _hidl_cb(Result::NOT_SUPPORTED, DualMonoMode::OFF);
592 return Void();
593 }
594
setDualMonoMode(DualMonoMode)595 Return<Result> StreamOut::setDualMonoMode(DualMonoMode /*mode*/) {
596 return Result::NOT_SUPPORTED;
597 }
598
getAudioDescriptionMixLevel(getAudioDescriptionMixLevel_cb _hidl_cb)599 Return<void> StreamOut::getAudioDescriptionMixLevel(getAudioDescriptionMixLevel_cb _hidl_cb) {
600 _hidl_cb(Result::NOT_SUPPORTED, -std::numeric_limits<float>::infinity());
601 return Void();
602 }
603
setAudioDescriptionMixLevel(float)604 Return<Result> StreamOut::setAudioDescriptionMixLevel(float /*leveldB*/) {
605 return Result::NOT_SUPPORTED;
606 }
607
getPlaybackRateParameters(getPlaybackRateParameters_cb _hidl_cb)608 Return<void> StreamOut::getPlaybackRateParameters(getPlaybackRateParameters_cb _hidl_cb) {
609 _hidl_cb(Result::NOT_SUPPORTED,
610 // Same as AUDIO_PLAYBACK_RATE_INITIALIZER
611 PlaybackRate{1.0f, 1.0f, TimestretchMode::DEFAULT, TimestretchFallbackMode::FAIL});
612 return Void();
613 }
614
setPlaybackRateParameters(const PlaybackRate &)615 Return<Result> StreamOut::setPlaybackRateParameters(const PlaybackRate& /*playbackRate*/) {
616 return Result::NOT_SUPPORTED;
617 }
618
setEventCallback(const sp<IStreamOutEventCallback> & callback)619 Return<Result> StreamOut::setEventCallback(const sp<IStreamOutEventCallback>& callback) {
620 if (mStream->set_event_callback == nullptr) return Result::NOT_SUPPORTED;
621 int result = mStream->set_event_callback(mStream, StreamOut::asyncEventCallback, this);
622 if (result == 0) {
623 mEventCallback = callback;
624 }
625 return Stream::analyzeStatus("set_stream_out_callback", result, {ENOSYS} /*ignore*/);
626 }
627
628 // static
asyncEventCallback(stream_event_callback_type_t event,void * param,void * cookie)629 int StreamOut::asyncEventCallback(stream_event_callback_type_t event, void* param, void* cookie) {
630 StreamOut* self = reinterpret_cast<StreamOut*>(cookie);
631 sp<IStreamOutEventCallback> eventCallback = self->mEventCallback;
632 if (eventCallback.get() == nullptr) return 0;
633 ALOGV("%s event %d", __func__, event);
634 Return<void> result;
635 switch (event) {
636 case STREAM_EVENT_CBK_TYPE_CODEC_FORMAT_CHANGED: {
637 hidl_vec<uint8_t> audioMetadata;
638 audioMetadata.setToExternal((uint8_t*)param, strlen((char*)param));
639 result = eventCallback->onCodecFormatChanged(audioMetadata);
640 } break;
641 default:
642 ALOGW("%s unknown event %d", __func__, event);
643 break;
644 }
645 ALOGW_IF(!result.isOk(), "Client callback failed: %s", result.description().c_str());
646 return 0;
647 }
648 #endif
649
650 } // namespace implementation
651 } // namespace CPP_VERSION
652 } // namespace audio
653 } // namespace hardware
654 } // namespace android
655