blob: 11838f8d95338b18ad74e526d7b7c7c693cfbada [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>
19
20#include <cmath>
21
22#include "core-impl/StreamRemoteSubmix.h"
23
24using aidl::android::hardware::audio::common::SinkMetadata;
25using aidl::android::hardware::audio::common::SourceMetadata;
Shraddha Basantwani2e460342023-07-26 16:12:21 +000026using aidl::android::hardware::audio::core::r_submix::SubmixRoute;
27using aidl::android::media::audio::common::AudioDeviceAddress;
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053028using aidl::android::media::audio::common::AudioOffloadInfo;
29using aidl::android::media::audio::common::MicrophoneDynamicInfo;
30using aidl::android::media::audio::common::MicrophoneInfo;
31
32namespace aidl::android::hardware::audio::core {
33
Shraddha Basantwani2e460342023-07-26 16:12:21 +000034StreamRemoteSubmix::StreamRemoteSubmix(StreamContext* context, const Metadata& metadata,
35 const AudioDeviceAddress& deviceAddress)
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -070036 : StreamCommonImpl(context, metadata),
Shraddha Basantwani2e460342023-07-26 16:12:21 +000037 mDeviceAddress(deviceAddress),
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053038 mIsInput(isInput(metadata)) {
Mikhail Naganov1eedc132023-07-21 17:45:28 -070039 mStreamConfig.frameSize = context->getFrameSize();
40 mStreamConfig.format = context->getFormat();
41 mStreamConfig.channelLayout = context->getChannelLayout();
42 mStreamConfig.sampleRate = context->getSampleRate();
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053043}
44
45std::mutex StreamRemoteSubmix::sSubmixRoutesLock;
Shraddha Basantwani2e460342023-07-26 16:12:21 +000046std::map<AudioDeviceAddress, std::shared_ptr<SubmixRoute>> StreamRemoteSubmix::sSubmixRoutes;
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053047
48::android::status_t StreamRemoteSubmix::init() {
49 {
50 std::lock_guard guard(sSubmixRoutesLock);
Shraddha Basantwani2e460342023-07-26 16:12:21 +000051 auto routeItr = sSubmixRoutes.find(mDeviceAddress);
52 if (routeItr != sSubmixRoutes.end()) {
53 mCurrentRoute = routeItr->second;
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053054 }
55 }
56 // If route is not available for this port, add it.
57 if (mCurrentRoute == nullptr) {
58 // Initialize the pipe.
59 mCurrentRoute = std::make_shared<SubmixRoute>();
60 if (::android::OK != mCurrentRoute->createPipe(mStreamConfig)) {
61 LOG(ERROR) << __func__ << ": create pipe failed";
Mikhail Naganov49712b52023-06-27 16:39:33 -070062 return ::android::NO_INIT;
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053063 }
64 {
65 std::lock_guard guard(sSubmixRoutesLock);
Shraddha Basantwani2e460342023-07-26 16:12:21 +000066 sSubmixRoutes.emplace(mDeviceAddress, mCurrentRoute);
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053067 }
68 } else {
69 if (!mCurrentRoute->isStreamConfigValid(mIsInput, mStreamConfig)) {
70 LOG(ERROR) << __func__ << ": invalid stream config";
Mikhail Naganov49712b52023-06-27 16:39:33 -070071 return ::android::NO_INIT;
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053072 }
73 sp<MonoPipe> sink = mCurrentRoute->getSink();
74 if (sink == nullptr) {
75 LOG(ERROR) << __func__ << ": nullptr sink when opening stream";
Mikhail Naganov49712b52023-06-27 16:39:33 -070076 return ::android::NO_INIT;
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053077 }
78 // If the sink has been shutdown or pipe recreation is forced, delete the pipe and
79 // recreate it.
80 if (sink->isShutdown()) {
81 LOG(DEBUG) << __func__ << ": Non-nullptr shut down sink when opening stream";
82 if (::android::OK != mCurrentRoute->resetPipe()) {
83 LOG(ERROR) << __func__ << ": reset pipe failed";
Mikhail Naganov49712b52023-06-27 16:39:33 -070084 return ::android::NO_INIT;
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053085 }
86 }
87 }
88
89 mCurrentRoute->openStream(mIsInput);
Mikhail Naganov49712b52023-06-27 16:39:33 -070090 return ::android::OK;
Shraddha Basantwani6bb69632023-04-25 15:26:38 +053091}
92
93::android::status_t StreamRemoteSubmix::drain(StreamDescriptor::DrainMode) {
94 usleep(1000);
95 return ::android::OK;
96}
97
98::android::status_t StreamRemoteSubmix::flush() {
99 usleep(1000);
100 return ::android::OK;
101}
102
103::android::status_t StreamRemoteSubmix::pause() {
104 usleep(1000);
105 return ::android::OK;
106}
107
Mikhail Naganov49712b52023-06-27 16:39:33 -0700108::android::status_t StreamRemoteSubmix::standby() {
109 mCurrentRoute->standby(mIsInput);
110 return ::android::OK;
111}
112
113::android::status_t StreamRemoteSubmix::start() {
114 mCurrentRoute->exitStandby(mIsInput);
115 return ::android::OK;
116}
117
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530118ndk::ScopedAStatus StreamRemoteSubmix::prepareToClose() {
119 if (!mIsInput) {
120 std::shared_ptr<SubmixRoute> route = nullptr;
121 {
122 std::lock_guard guard(sSubmixRoutesLock);
Shraddha Basantwani2e460342023-07-26 16:12:21 +0000123 auto routeItr = sSubmixRoutes.find(mDeviceAddress);
124 if (routeItr != sSubmixRoutes.end()) {
125 route = routeItr->second;
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530126 }
127 }
128 if (route != nullptr) {
129 sp<MonoPipe> sink = route->getSink();
130 if (sink == nullptr) {
131 ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
132 }
133 LOG(DEBUG) << __func__ << ": shutting down MonoPipe sink";
134
135 sink->shutdown(true);
136 } else {
137 LOG(DEBUG) << __func__ << ": stream already closed.";
138 ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
139 }
140 }
141 return ndk::ScopedAStatus::ok();
142}
143
144// Remove references to the specified input and output streams. When the device no longer
145// references input and output streams destroy the associated pipe.
146void StreamRemoteSubmix::shutdown() {
147 mCurrentRoute->closeStream(mIsInput);
148 // If all stream instances are closed, we can remove route information for this port.
149 if (!mCurrentRoute->hasAtleastOneStreamOpen()) {
150 mCurrentRoute->releasePipe();
151 LOG(DEBUG) << __func__ << ": pipe destroyed";
152
153 std::lock_guard guard(sSubmixRoutesLock);
Shraddha Basantwani2e460342023-07-26 16:12:21 +0000154 sSubmixRoutes.erase(mDeviceAddress);
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530155 }
Mikhail Naganov49712b52023-06-27 16:39:33 -0700156 mCurrentRoute.reset();
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530157}
158
159::android::status_t StreamRemoteSubmix::transfer(void* buffer, size_t frameCount,
160 size_t* actualFrameCount, int32_t* latencyMs) {
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530161 *latencyMs = (getStreamPipeSizeInFrames() * MILLIS_PER_SECOND) / mStreamConfig.sampleRate;
162 LOG(VERBOSE) << __func__ << ": Latency " << *latencyMs << "ms";
163
164 sp<MonoPipe> sink = mCurrentRoute->getSink();
165 if (sink != nullptr) {
166 if (sink->isShutdown()) {
167 sink.clear();
168 LOG(VERBOSE) << __func__ << ": pipe shutdown, ignoring the transfer.";
169 // the pipe has already been shutdown, this buffer will be lost but we must simulate
170 // timing so we don't drain the output faster than realtime
171 const size_t delayUs = static_cast<size_t>(
172 std::roundf(frameCount * MICROS_PER_SECOND / mStreamConfig.sampleRate));
173 usleep(delayUs);
174
175 *actualFrameCount = frameCount;
176 return ::android::OK;
177 }
178 } else {
179 LOG(ERROR) << __func__ << ": transfer without a pipe!";
180 return ::android::UNEXPECTED_NULL;
181 }
182
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530183 return (mIsInput ? inRead(buffer, frameCount, actualFrameCount)
184 : outWrite(buffer, frameCount, actualFrameCount));
185}
186
Mikhail Naganov459b7332023-08-03 10:26:21 -0700187::android::status_t StreamRemoteSubmix::refinePosition(StreamDescriptor::Position* position) {
Mikhail Naganov704aec42023-07-13 11:08:29 -0700188 sp<MonoPipeReader> source = mCurrentRoute->getSource();
189 if (source == nullptr) {
190 return ::android::NO_INIT;
191 }
192 const ssize_t framesInPipe = source->availableToRead();
193 if (framesInPipe < 0) {
194 return ::android::INVALID_OPERATION;
195 }
196 if (mIsInput) {
197 position->frames += framesInPipe;
198 } else {
199 if (position->frames > framesInPipe) {
200 position->frames -= framesInPipe;
201 } else {
202 position->frames = 0;
203 }
204 }
205 return ::android::OK;
206}
207
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530208// Calculate the maximum size of the pipe buffer in frames for the specified stream.
209size_t StreamRemoteSubmix::getStreamPipeSizeInFrames() {
210 auto pipeConfig = mCurrentRoute->mPipeConfig;
211 const size_t maxFrameSize = std::max(mStreamConfig.frameSize, pipeConfig.frameSize);
212 return (pipeConfig.frameCount * pipeConfig.frameSize) / maxFrameSize;
213}
214
215::android::status_t StreamRemoteSubmix::outWrite(void* buffer, size_t frameCount,
216 size_t* actualFrameCount) {
217 sp<MonoPipe> sink = mCurrentRoute->getSink();
218 if (sink != nullptr) {
219 if (sink->isShutdown()) {
220 sink.clear();
221 LOG(VERBOSE) << __func__ << ": pipe shutdown, ignoring the write.";
222 // the pipe has already been shutdown, this buffer will be lost but we must
223 // simulate timing so we don't drain the output faster than realtime
224 const size_t delayUs = static_cast<size_t>(
225 std::roundf(frameCount * MICROS_PER_SECOND / mStreamConfig.sampleRate));
226 usleep(delayUs);
227 *actualFrameCount = frameCount;
228 return ::android::OK;
229 }
230 } else {
231 LOG(FATAL) << __func__ << ": without a pipe!";
232 return ::android::UNKNOWN_ERROR;
233 }
234
235 const size_t availableToWrite = sink->availableToWrite();
236 // NOTE: sink has been checked above and sink and source life cycles are synchronized
237 sp<MonoPipeReader> source = mCurrentRoute->getSource();
238 // If the write to the sink should be blocked, flush enough frames from the pipe to make space
239 // to write the most recent data.
240 if (!mCurrentRoute->shouldBlockWrite() && availableToWrite < frameCount) {
241 static uint8_t flushBuffer[64];
242 const size_t flushBufferSizeFrames = sizeof(flushBuffer) / mStreamConfig.frameSize;
243 size_t framesToFlushFromSource = frameCount - availableToWrite;
244 LOG(VERBOSE) << __func__ << ": flushing " << framesToFlushFromSource
245 << " frames from the pipe to avoid blocking";
246 while (framesToFlushFromSource) {
247 const size_t flushSize = std::min(framesToFlushFromSource, flushBufferSizeFrames);
248 framesToFlushFromSource -= flushSize;
249 // read does not block
250 source->read(flushBuffer, flushSize);
251 }
252 }
253
254 ssize_t writtenFrames = sink->write(buffer, frameCount);
255 if (writtenFrames < 0) {
256 if (writtenFrames == (ssize_t)::android::NEGOTIATE) {
257 LOG(ERROR) << __func__ << ": write to pipe returned NEGOTIATE";
258 sink.clear();
259 *actualFrameCount = 0;
260 return ::android::UNKNOWN_ERROR;
261 } else {
262 // write() returned UNDERRUN or WOULD_BLOCK, retry
263 LOG(ERROR) << __func__ << ": write to pipe returned unexpected " << writtenFrames;
264 writtenFrames = sink->write(buffer, frameCount);
265 }
266 }
267 sink.clear();
268
269 if (writtenFrames < 0) {
270 LOG(ERROR) << __func__ << ": failed writing to pipe with " << writtenFrames;
271 *actualFrameCount = 0;
272 return ::android::UNKNOWN_ERROR;
273 }
274 LOG(VERBOSE) << __func__ << ": wrote " << writtenFrames << "frames";
275 *actualFrameCount = writtenFrames;
276 return ::android::OK;
277}
278
279::android::status_t StreamRemoteSubmix::inRead(void* buffer, size_t frameCount,
280 size_t* actualFrameCount) {
281 // about to read from audio source
282 sp<MonoPipeReader> source = mCurrentRoute->getSource();
Shraddha Basantwani675cce22023-07-28 16:53:43 +0000283 if (source == nullptr || source->availableToRead() == 0) {
284 if (source == nullptr) {
285 int readErrorCount = mCurrentRoute->notifyReadError();
286 if (readErrorCount < kMaxReadErrorLogs) {
287 LOG(ERROR) << __func__
288 << ": no audio pipe yet we're trying to read! (not all errors will be "
289 "logged)";
290 } else {
291 LOG(ERROR) << __func__ << ": Read errors " << readErrorCount;
292 }
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530293 } else {
Shraddha Basantwani675cce22023-07-28 16:53:43 +0000294 LOG(INFO) << __func__ << ": no data to read yet, providing empty data";
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530295 }
296 const size_t delayUs = static_cast<size_t>(
297 std::roundf(frameCount * MICROS_PER_SECOND / mStreamConfig.sampleRate));
298 usleep(delayUs);
299 memset(buffer, 0, mStreamConfig.frameSize * frameCount);
300 *actualFrameCount = frameCount;
301 return ::android::OK;
302 }
303
304 // read the data from the pipe
305 int attempts = 0;
306 const size_t delayUs = static_cast<size_t>(std::roundf(kReadAttemptSleepUs));
307 char* buff = (char*)buffer;
308 size_t remainingFrames = frameCount;
309
310 while ((remainingFrames > 0) && (attempts < kMaxReadFailureAttempts)) {
311 LOG(VERBOSE) << __func__ << ": frames available to read " << source->availableToRead();
312
313 ssize_t framesRead = source->read(buff, remainingFrames);
314
315 LOG(VERBOSE) << __func__ << ": frames read " << framesRead;
316
317 if (framesRead > 0) {
318 remainingFrames -= framesRead;
319 buff += framesRead * mStreamConfig.frameSize;
320 LOG(VERBOSE) << __func__ << ": (attempts = " << attempts << ") got " << framesRead
321 << " frames, remaining=" << remainingFrames;
322 } else {
323 attempts++;
324 LOG(WARNING) << __func__ << ": read returned " << framesRead
325 << " , read failure attempts = " << attempts;
326 usleep(delayUs);
327 }
328 }
329 // done using the source
330 source.clear();
331
332 if (remainingFrames > 0) {
333 const size_t remainingBytes = remainingFrames * mStreamConfig.frameSize;
334 LOG(VERBOSE) << __func__ << ": clearing remaining_frames = " << remainingFrames;
335 memset(((char*)buffer) + (mStreamConfig.frameSize * frameCount) - remainingBytes, 0,
336 remainingBytes);
337 }
338
339 long readCounterFrames = mCurrentRoute->updateReadCounterFrames(frameCount);
340 *actualFrameCount = frameCount;
341
342 // compute how much we need to sleep after reading the data by comparing the wall clock with
343 // the projected time at which we should return.
344 // wall clock after reading from the pipe
345 auto recordDurationUs = std::chrono::steady_clock::now() - mCurrentRoute->getRecordStartTime();
346
347 // readCounterFrames contains the number of frames that have been read since the beginning of
348 // recording (including this call): it's converted to usec and compared to how long we've been
349 // recording for, which gives us how long we must wait to sync the projected recording time, and
350 // the observed recording time.
Shraddha Basantwani675cce22023-07-28 16:53:43 +0000351 const size_t projectedVsObservedOffsetUs = static_cast<size_t>(
352 std::roundf((readCounterFrames * MICROS_PER_SECOND / mStreamConfig.sampleRate) -
353 recordDurationUs.count()));
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530354
355 LOG(VERBOSE) << __func__ << ": record duration " << recordDurationUs.count()
356 << " microseconds, will wait: " << projectedVsObservedOffsetUs << " microseconds";
357 if (projectedVsObservedOffsetUs > 0) {
358 usleep(projectedVsObservedOffsetUs);
359 }
360 return ::android::OK;
361}
362
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700363StreamInRemoteSubmix::StreamInRemoteSubmix(StreamContext&& context,
364 const SinkMetadata& sinkMetadata,
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530365 const std::vector<MicrophoneInfo>& microphones)
Mikhail Naganov459b7332023-08-03 10:26:21 -0700366 : StreamIn(std::move(context), microphones), StreamSwitcher(&mContextInstance, sinkMetadata) {}
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530367
368ndk::ScopedAStatus StreamInRemoteSubmix::getActiveMicrophones(
369 std::vector<MicrophoneDynamicInfo>* _aidl_return) {
370 LOG(DEBUG) << __func__ << ": not supported";
371 *_aidl_return = std::vector<MicrophoneDynamicInfo>();
372 return ndk::ScopedAStatus::ok();
373}
374
Shraddha Basantwani2e460342023-07-26 16:12:21 +0000375StreamSwitcher::DeviceSwitchBehavior StreamInRemoteSubmix::switchCurrentStream(
376 const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) {
377 // This implementation effectively postpones stream creation until
378 // receiving the first call to 'setConnectedDevices' with a non-empty list.
379 if (isStubStream()) {
380 if (devices.size() == 1) {
381 auto deviceDesc = devices.front().type;
382 if (deviceDesc.type ==
383 ::aidl::android::media::audio::common::AudioDeviceType::IN_SUBMIX) {
384 return DeviceSwitchBehavior::CREATE_NEW_STREAM;
385 }
386 LOG(ERROR) << __func__ << ": Device type " << toString(deviceDesc.type)
387 << " not supported";
388 } else {
389 LOG(ERROR) << __func__ << ": Only single device supported.";
390 }
391 return DeviceSwitchBehavior::UNSUPPORTED_DEVICES;
392 }
393 return DeviceSwitchBehavior::USE_CURRENT_STREAM;
394}
395
396std::unique_ptr<StreamCommonInterfaceEx> StreamInRemoteSubmix::createNewStream(
397 const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices,
398 StreamContext* context, const Metadata& metadata) {
399 return std::unique_ptr<StreamCommonInterfaceEx>(
400 new InnerStreamWrapper<StreamRemoteSubmix>(context, metadata, devices.front().address));
401}
402
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700403StreamOutRemoteSubmix::StreamOutRemoteSubmix(StreamContext&& context,
404 const SourceMetadata& sourceMetadata,
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530405 const std::optional<AudioOffloadInfo>& offloadInfo)
Mikhail Naganov6ddefdb2023-07-19 17:30:06 -0700406 : StreamOut(std::move(context), offloadInfo),
Mikhail Naganov459b7332023-08-03 10:26:21 -0700407 StreamSwitcher(&mContextInstance, sourceMetadata) {}
Shraddha Basantwani2e460342023-07-26 16:12:21 +0000408
409StreamSwitcher::DeviceSwitchBehavior StreamOutRemoteSubmix::switchCurrentStream(
410 const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices) {
411 // This implementation effectively postpones stream creation until
412 // receiving the first call to 'setConnectedDevices' with a non-empty list.
413 if (isStubStream()) {
414 if (devices.size() == 1) {
415 auto deviceDesc = devices.front().type;
416 if (deviceDesc.type ==
417 ::aidl::android::media::audio::common::AudioDeviceType::OUT_SUBMIX) {
418 return DeviceSwitchBehavior::CREATE_NEW_STREAM;
419 }
420 LOG(ERROR) << __func__ << ": Device type " << toString(deviceDesc.type)
421 << " not supported";
422 } else {
423 LOG(ERROR) << __func__ << ": Only single device supported.";
424 }
425 return DeviceSwitchBehavior::UNSUPPORTED_DEVICES;
426 }
427 return DeviceSwitchBehavior::USE_CURRENT_STREAM;
428}
429
430std::unique_ptr<StreamCommonInterfaceEx> StreamOutRemoteSubmix::createNewStream(
431 const std::vector<::aidl::android::media::audio::common::AudioDevice>& devices,
432 StreamContext* context, const Metadata& metadata) {
433 return std::unique_ptr<StreamCommonInterfaceEx>(
434 new InnerStreamWrapper<StreamRemoteSubmix>(context, metadata, devices.front().address));
435}
Shraddha Basantwani6bb69632023-04-25 15:26:38 +0530436
437} // namespace aidl::android::hardware::audio::core