blob: df706ac026b9ff4fd98091df514a6f73467b6b27 [file] [log] [blame]
Shraddha Basantwani6bb69632023-04-25 15:26:38 +05301/*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "AHAL_StreamRemoteSubmix"
18#include <android-base/logging.h>
Mikhail Naganov06085452023-11-27 17:28:51 -080019#include <audio_utils/clock.h>
20#include <error/Result.h>
21#include <error/expected_utils.h>
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053022
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053023#include "core-impl/StreamRemoteSubmix.h"
24
25using aidl::android::hardware::audio::common::SinkMetadata;
26using aidl::android::hardware::audio::common::SourceMetadata;
Shraddha Basantwani2e460342023-07-26 16:12:21 +000027using aidl::android::hardware::audio::core::r_submix::SubmixRoute;
28using aidl::android::media::audio::common::AudioDeviceAddress;
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053029using aidl::android::media::audio::common::AudioOffloadInfo;
30using aidl::android::media::audio::common::MicrophoneDynamicInfo;
31using aidl::android::media::audio::common::MicrophoneInfo;
32
33namespace aidl::android::hardware::audio::core {
34
Shraddha Basantwani2e460342023-07-26 16:12:21 +000035StreamRemoteSubmix::StreamRemoteSubmix(StreamContext* context, const Metadata& metadata,
36 const AudioDeviceAddress& deviceAddress)
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -070037 : StreamCommonImpl(context, metadata),
Shraddha Basantwani2e460342023-07-26 16:12:21 +000038 mDeviceAddress(deviceAddress),
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053039 mIsInput(isInput(metadata)) {
Mikhail Naganov1eedc132023-07-21 17:45:28 -070040 mStreamConfig.frameSize = context->getFrameSize();
41 mStreamConfig.format = context->getFormat();
42 mStreamConfig.channelLayout = context->getChannelLayout();
43 mStreamConfig.sampleRate = context->getSampleRate();
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053044}
45
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053046::android::status_t StreamRemoteSubmix::init() {
Mikhail Naganov3b732892023-12-20 16:05:01 -080047 mCurrentRoute = SubmixRoute::findOrCreateRoute(mDeviceAddress, mStreamConfig);
48 if (mCurrentRoute == nullptr) {
49 return ::android::NO_INIT;
Mikhail Naganov06085452023-11-27 17:28:51 -080050 }
51 if (!mCurrentRoute->isStreamConfigValid(mIsInput, mStreamConfig)) {
52 LOG(ERROR) << __func__ << ": invalid stream config";
53 return ::android::NO_INIT;
54 }
55 sp<MonoPipe> sink = mCurrentRoute->getSink();
56 if (sink == nullptr) {
57 LOG(ERROR) << __func__ << ": nullptr sink when opening stream";
58 return ::android::NO_INIT;
59 }
Mikhail Naganov7b234d42023-12-05 11:28:56 -080060 if ((!mIsInput || mCurrentRoute->isStreamInOpen()) && sink->isShutdown()) {
61 LOG(DEBUG) << __func__ << ": Shut down sink when opening stream";
Mikhail Naganov06085452023-11-27 17:28:51 -080062 if (::android::OK != mCurrentRoute->resetPipe()) {
63 LOG(ERROR) << __func__ << ": reset pipe failed";
64 return ::android::NO_INIT;
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053065 }
66 }
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053067 mCurrentRoute->openStream(mIsInput);
Mikhail Naganov49712b52023-06-27 16:39:33 -070068 return ::android::OK;
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053069}
70
71::android::status_t StreamRemoteSubmix::drain(StreamDescriptor::DrainMode) {
72 usleep(1000);
73 return ::android::OK;
74}
75
76::android::status_t StreamRemoteSubmix::flush() {
77 usleep(1000);
78 return ::android::OK;
79}
80
81::android::status_t StreamRemoteSubmix::pause() {
82 usleep(1000);
83 return ::android::OK;
84}
85
Mikhail Naganov49712b52023-06-27 16:39:33 -070086::android::status_t StreamRemoteSubmix::standby() {
87 mCurrentRoute->standby(mIsInput);
88 return ::android::OK;
89}
90
91::android::status_t StreamRemoteSubmix::start() {
92 mCurrentRoute->exitStandby(mIsInput);
Mikhail Naganov06085452023-11-27 17:28:51 -080093 mStartTimeNs = ::android::uptimeNanos();
94 mFramesSinceStart = 0;
Mikhail Naganov49712b52023-06-27 16:39:33 -070095 return ::android::OK;
96}
97
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053098ndk::ScopedAStatus StreamRemoteSubmix::prepareToClose() {
99 if (!mIsInput) {
Mikhail Naganov3b732892023-12-20 16:05:01 -0800100 std::shared_ptr<SubmixRoute> route = SubmixRoute::findRoute(mDeviceAddress);
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530101 if (route != nullptr) {
102 sp<MonoPipe> sink = route->getSink();
103 if (sink == nullptr) {
104 ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
105 }
106 LOG(DEBUG) << __func__ << ": shutting down MonoPipe sink";
107
108 sink->shutdown(true);
Mikhail Naganov2ebe3902023-11-07 16:43:26 -0800109 // The client already considers this stream as closed, release the output end.
110 route->closeStream(mIsInput);
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530111 } else {
112 LOG(DEBUG) << __func__ << ": stream already closed.";
113 ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
114 }
115 }
116 return ndk::ScopedAStatus::ok();
117}
118
119// Remove references to the specified input and output streams. When the device no longer
120// references input and output streams destroy the associated pipe.
121void StreamRemoteSubmix::shutdown() {
122 mCurrentRoute->closeStream(mIsInput);
123 // If all stream instances are closed, we can remove route information for this port.
124 if (!mCurrentRoute->hasAtleastOneStreamOpen()) {
125 mCurrentRoute->releasePipe();
126 LOG(DEBUG) << __func__ << ": pipe destroyed";
Mikhail Naganov3b732892023-12-20 16:05:01 -0800127 SubmixRoute::removeRoute(mDeviceAddress);
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530128 }
Mikhail Naganov49712b52023-06-27 16:39:33 -0700129 mCurrentRoute.reset();
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530130}
131
132::android::status_t StreamRemoteSubmix::transfer(void* buffer, size_t frameCount,
133 size_t* actualFrameCount, int32_t* latencyMs) {
Mikhail Naganov2aab7662023-10-24 13:56:07 -0700134 *latencyMs = getDelayInUsForFrameCount(getStreamPipeSizeInFrames()) / 1000;
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530135 LOG(VERBOSE) << __func__ << ": Latency " << *latencyMs << "ms";
Shraddha Basantwani95f92322023-08-22 15:07:16 +0000136 mCurrentRoute->exitStandby(mIsInput);
Mikhail Naganov06085452023-11-27 17:28:51 -0800137 RETURN_STATUS_IF_ERROR(mIsInput ? inRead(buffer, frameCount, actualFrameCount)
138 : outWrite(buffer, frameCount, actualFrameCount));
139 const long bufferDurationUs =
140 (*actualFrameCount) * MICROS_PER_SECOND / mContext.getSampleRate();
141 const long totalDurationUs = (::android::uptimeNanos() - mStartTimeNs) / NANOS_PER_MICROSECOND;
142 mFramesSinceStart += *actualFrameCount;
143 const long totalOffsetUs =
144 mFramesSinceStart * MICROS_PER_SECOND / mContext.getSampleRate() - totalDurationUs;
145 LOG(VERBOSE) << __func__ << ": totalOffsetUs " << totalOffsetUs;
146 if (totalOffsetUs > 0) {
147 const long sleepTimeUs = std::min(totalOffsetUs, bufferDurationUs);
148 LOG(VERBOSE) << __func__ << ": sleeping for " << sleepTimeUs << " us";
149 usleep(sleepTimeUs);
150 }
151 return ::android::OK;
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530152}
153
Mikhail Naganov459b7332023-08-03 10:26:21 -0700154::android::status_t StreamRemoteSubmix::refinePosition(StreamDescriptor::Position* position) {
Mikhail Naganov704aec42023-07-13 11:08:29 -0700155 sp<MonoPipeReader> source = mCurrentRoute->getSource();
156 if (source == nullptr) {
157 return ::android::NO_INIT;
158 }
159 const ssize_t framesInPipe = source->availableToRead();
Shraddha Basantwani95f92322023-08-22 15:07:16 +0000160 if (framesInPipe <= 0) {
161 // No need to update the position frames
162 return ::android::OK;
Mikhail Naganov704aec42023-07-13 11:08:29 -0700163 }
164 if (mIsInput) {
165 position->frames += framesInPipe;
Shraddha Basantwani95f92322023-08-22 15:07:16 +0000166 } else if (position->frames >= framesInPipe) {
167 position->frames -= framesInPipe;
Mikhail Naganov704aec42023-07-13 11:08:29 -0700168 }
169 return ::android::OK;
170}
171
Mikhail Naganov2aab7662023-10-24 13:56:07 -0700172long StreamRemoteSubmix::getDelayInUsForFrameCount(size_t frameCount) {
173 return frameCount * MICROS_PER_SECOND / mStreamConfig.sampleRate;
174}
175
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530176// Calculate the maximum size of the pipe buffer in frames for the specified stream.
177size_t StreamRemoteSubmix::getStreamPipeSizeInFrames() {
Mikhail Naganov3b732892023-12-20 16:05:01 -0800178 auto pipeConfig = mCurrentRoute->getPipeConfig();
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530179 const size_t maxFrameSize = std::max(mStreamConfig.frameSize, pipeConfig.frameSize);
180 return (pipeConfig.frameCount * pipeConfig.frameSize) / maxFrameSize;
181}
182
183::android::status_t StreamRemoteSubmix::outWrite(void* buffer, size_t frameCount,
184 size_t* actualFrameCount) {
185 sp<MonoPipe> sink = mCurrentRoute->getSink();
186 if (sink != nullptr) {
187 if (sink->isShutdown()) {
188 sink.clear();
Mikhail Naganov06085452023-11-27 17:28:51 -0800189 LOG(DEBUG) << __func__ << ": pipe shutdown, ignoring the write";
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530190 *actualFrameCount = frameCount;
191 return ::android::OK;
192 }
193 } else {
194 LOG(FATAL) << __func__ << ": without a pipe!";
195 return ::android::UNKNOWN_ERROR;
196 }
197
Mikhail Naganov06085452023-11-27 17:28:51 -0800198 LOG(VERBOSE) << __func__ << ": " << mDeviceAddress.toString() << ", " << frameCount
199 << " frames";
200
Mikhail Naganov2aab7662023-10-24 13:56:07 -0700201 const bool shouldBlockWrite = mCurrentRoute->shouldBlockWrite();
202 size_t availableToWrite = sink->availableToWrite();
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530203 // NOTE: sink has been checked above and sink and source life cycles are synchronized
204 sp<MonoPipeReader> source = mCurrentRoute->getSource();
205 // If the write to the sink should be blocked, flush enough frames from the pipe to make space
206 // to write the most recent data.
Mikhail Naganov2aab7662023-10-24 13:56:07 -0700207 if (!shouldBlockWrite && availableToWrite < frameCount) {
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530208 static uint8_t flushBuffer[64];
209 const size_t flushBufferSizeFrames = sizeof(flushBuffer) / mStreamConfig.frameSize;
210 size_t framesToFlushFromSource = frameCount - availableToWrite;
Mikhail Naganov2aab7662023-10-24 13:56:07 -0700211 LOG(DEBUG) << __func__ << ": flushing " << framesToFlushFromSource
212 << " frames from the pipe to avoid blocking";
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530213 while (framesToFlushFromSource) {
214 const size_t flushSize = std::min(framesToFlushFromSource, flushBufferSizeFrames);
215 framesToFlushFromSource -= flushSize;
216 // read does not block
217 source->read(flushBuffer, flushSize);
218 }
219 }
Mikhail Naganov2aab7662023-10-24 13:56:07 -0700220 availableToWrite = sink->availableToWrite();
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530221
Mikhail Naganov2aab7662023-10-24 13:56:07 -0700222 if (!shouldBlockWrite && frameCount > availableToWrite) {
Mikhail Naganov06085452023-11-27 17:28:51 -0800223 LOG(WARNING) << __func__ << ": writing " << availableToWrite << " vs. requested "
224 << frameCount;
Mikhail Naganov2aab7662023-10-24 13:56:07 -0700225 // Truncate the request to avoid blocking.
226 frameCount = availableToWrite;
227 }
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530228 ssize_t writtenFrames = sink->write(buffer, frameCount);
229 if (writtenFrames < 0) {
230 if (writtenFrames == (ssize_t)::android::NEGOTIATE) {
231 LOG(ERROR) << __func__ << ": write to pipe returned NEGOTIATE";
232 sink.clear();
233 *actualFrameCount = 0;
234 return ::android::UNKNOWN_ERROR;
235 } else {
236 // write() returned UNDERRUN or WOULD_BLOCK, retry
237 LOG(ERROR) << __func__ << ": write to pipe returned unexpected " << writtenFrames;
238 writtenFrames = sink->write(buffer, frameCount);
239 }
240 }
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530241
242 if (writtenFrames < 0) {
243 LOG(ERROR) << __func__ << ": failed writing to pipe with " << writtenFrames;
244 *actualFrameCount = 0;
245 return ::android::UNKNOWN_ERROR;
246 }
Mikhail Naganov06085452023-11-27 17:28:51 -0800247 if (writtenFrames > 0 && frameCount > (size_t)writtenFrames) {
248 LOG(WARNING) << __func__ << ": wrote " << writtenFrames << " vs. requested " << frameCount;
249 }
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530250 *actualFrameCount = writtenFrames;
251 return ::android::OK;
252}
253
254::android::status_t StreamRemoteSubmix::inRead(void* buffer, size_t frameCount,
255 size_t* actualFrameCount) {
Mikhail Naganov06085452023-11-27 17:28:51 -0800256 // in any case, it is emulated that data for the entire buffer was available
257 memset(buffer, 0, mStreamConfig.frameSize * frameCount);
258 *actualFrameCount = frameCount;
259
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530260 // about to read from audio source
261 sp<MonoPipeReader> source = mCurrentRoute->getSource();
Shraddha Basantwani95f92322023-08-22 15:07:16 +0000262 if (source == nullptr) {
Mikhail Naganov06085452023-11-27 17:28:51 -0800263 if (++mReadErrorCount < kMaxReadErrorLogs) {
Shraddha Basantwani95f92322023-08-22 15:07:16 +0000264 LOG(ERROR) << __func__
265 << ": no audio pipe yet we're trying to read! (not all errors will be "
266 "logged)";
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530267 }
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530268 return ::android::OK;
269 }
270
Mikhail Naganov06085452023-11-27 17:28:51 -0800271 LOG(VERBOSE) << __func__ << ": " << mDeviceAddress.toString() << ", " << frameCount
272 << " frames";
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530273 // read the data from the pipe
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530274 char* buff = (char*)buffer;
Mikhail Naganov06085452023-11-27 17:28:51 -0800275 size_t actuallyRead = 0;
276 long remainingFrames = frameCount;
277 const long deadlineTimeNs = ::android::uptimeNanos() +
278 getDelayInUsForFrameCount(frameCount) * NANOS_PER_MICROSECOND;
279 while (remainingFrames > 0) {
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530280 ssize_t framesRead = source->read(buff, remainingFrames);
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530281 LOG(VERBOSE) << __func__ << ": frames read " << framesRead;
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530282 if (framesRead > 0) {
283 remainingFrames -= framesRead;
284 buff += framesRead * mStreamConfig.frameSize;
Mikhail Naganov06085452023-11-27 17:28:51 -0800285 LOG(VERBOSE) << __func__ << ": got " << framesRead
Mikhail Naganov2aab7662023-10-24 13:56:07 -0700286 << " frames, remaining =" << remainingFrames;
Mikhail Naganov06085452023-11-27 17:28:51 -0800287 actuallyRead += framesRead;
288 }
289 if (::android::uptimeNanos() >= deadlineTimeNs) break;
290 if (framesRead <= 0) {
291 LOG(VERBOSE) << __func__ << ": read returned " << framesRead
292 << ", read failure, sleeping for " << kReadAttemptSleepUs << " us";
293 usleep(kReadAttemptSleepUs);
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530294 }
295 }
Mikhail Naganov06085452023-11-27 17:28:51 -0800296 if (actuallyRead < frameCount) {
297 LOG(WARNING) << __func__ << ": read " << actuallyRead << " vs. requested " << frameCount;
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530298 }
Mikhail Naganov06085452023-11-27 17:28:51 -0800299 mCurrentRoute->updateReadCounterFrames(*actualFrameCount);
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530300 return ::android::OK;
301}
302
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700303StreamInRemoteSubmix::StreamInRemoteSubmix(StreamContext&& context,
304 const SinkMetadata& sinkMetadata,
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530305 const std::vector<MicrophoneInfo>& microphones)
Mikhail Naganov459b7332023-08-03 10:26:21 -0700306 : StreamIn(std::move(context), microphones), StreamSwitcher(&mContextInstance, sinkMetadata) {}
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530307
308ndk::ScopedAStatus StreamInRemoteSubmix::getActiveMicrophones(
309 std::vector<MicrophoneDynamicInfo>* _aidl_return) {
310 LOG(DEBUG) << __func__ << ": not supported";
311 *_aidl_return = std::vector<MicrophoneDynamicInfo>();
312 return ndk::ScopedAStatus::ok();
313}
314
Shraddha Basantwani2e460342023-07-26 16:12:21 +0000315StreamSwitcher::DeviceSwitchBehavior StreamInRemoteSubmix::switchCurrentStream(
316 const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) {
317 // This implementation effectively postpones stream creation until
318 // receiving the first call to 'setConnectedDevices' with a non-empty list.
319 if (isStubStream()) {
320 if (devices.size() == 1) {
321 auto deviceDesc = devices.front().type;
322 if (deviceDesc.type ==
323 ::aidl::android::media::audio::common::AudioDeviceType::IN_SUBMIX) {
324 return DeviceSwitchBehavior::CREATE_NEW_STREAM;
325 }
326 LOG(ERROR) << __func__ << ": Device type " << toString(deviceDesc.type)
327 << " not supported";
328 } else {
329 LOG(ERROR) << __func__ << ": Only single device supported.";
330 }
331 return DeviceSwitchBehavior::UNSUPPORTED_DEVICES;
332 }
333 return DeviceSwitchBehavior::USE_CURRENT_STREAM;
334}
335
336std::unique_ptr<StreamCommonInterfaceEx> StreamInRemoteSubmix::createNewStream(
337 const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices,
338 StreamContext* context, const Metadata& metadata) {
339 return std::unique_ptr<StreamCommonInterfaceEx>(
340 new InnerStreamWrapper<StreamRemoteSubmix>(context, metadata, devices.front().address));
341}
342
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700343StreamOutRemoteSubmix::StreamOutRemoteSubmix(StreamContext&& context,
344 const SourceMetadata& sourceMetadata,
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530345 const std::optional<AudioOffloadInfo>& offloadInfo)
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700346 : StreamOut(std::move(context), offloadInfo),
Mikhail Naganov459b7332023-08-03 10:26:21 -0700347 StreamSwitcher(&mContextInstance, sourceMetadata) {}
Shraddha Basantwani2e460342023-07-26 16:12:21 +0000348
349StreamSwitcher::DeviceSwitchBehavior StreamOutRemoteSubmix::switchCurrentStream(
350 const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) {
351 // This implementation effectively postpones stream creation until
352 // receiving the first call to 'setConnectedDevices' with a non-empty list.
353 if (isStubStream()) {
354 if (devices.size() == 1) {
355 auto deviceDesc = devices.front().type;
356 if (deviceDesc.type ==
357 ::aidl::android::media::audio::common::AudioDeviceType::OUT_SUBMIX) {
358 return DeviceSwitchBehavior::CREATE_NEW_STREAM;
359 }
360 LOG(ERROR) << __func__ << ": Device type " << toString(deviceDesc.type)
361 << " not supported";
362 } else {
363 LOG(ERROR) << __func__ << ": Only single device supported.";
364 }
365 return DeviceSwitchBehavior::UNSUPPORTED_DEVICES;
366 }
367 return DeviceSwitchBehavior::USE_CURRENT_STREAM;
368}
369
370std::unique_ptr<StreamCommonInterfaceEx> StreamOutRemoteSubmix::createNewStream(
371 const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices,
372 StreamContext* context, const Metadata& metadata) {
373 return std::unique_ptr<StreamCommonInterfaceEx>(
374 new InnerStreamWrapper<StreamRemoteSubmix>(context, metadata, devices.front().address));
375}
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530376
377} // namespace aidl::android::hardware::audio::core