blob: 312df720eb90712203f5caaf3a3d3757e6e0726c [file] [log] [blame]
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +00001/*
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#define LOG_TAG "AHAL_Stream"
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000018#include <android-base/logging.h>
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000019#include <utils/SystemClock.h>
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000020
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000021#include "core-impl/Module.h"
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000022#include "core-impl/Stream.h"
23
24using aidl::android::hardware::audio::common::SinkMetadata;
25using aidl::android::hardware::audio::common::SourceMetadata;
26using aidl::android::media::audio::common::AudioOffloadInfo;
27
28namespace aidl::android::hardware::audio::core {
29
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000030void StreamContext::fillDescriptor(StreamDescriptor* desc) {
31 if (mCommandMQ) {
32 desc->command = mCommandMQ->dupeDesc();
33 }
34 if (mReplyMQ) {
35 desc->reply = mReplyMQ->dupeDesc();
36 }
37 if (mDataMQ) {
Mikhail Naganova2c71412022-08-19 21:37:35 +000038 desc->frameSizeBytes = mFrameSize;
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000039 desc->bufferSizeFrames =
40 mDataMQ->getQuantumCount() * mDataMQ->getQuantumSize() / mFrameSize;
41 desc->audio.set<StreamDescriptor::AudioBuffer::Tag::fmq>(mDataMQ->dupeDesc());
42 }
Mikhail Naganov6a4872d2022-06-15 21:39:04 +000043}
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +000044
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +000045bool StreamContext::isValid() const {
46 if (mCommandMQ && !mCommandMQ->isValid()) {
47 LOG(ERROR) << "command FMQ is invalid";
48 return false;
49 }
50 if (mReplyMQ && !mReplyMQ->isValid()) {
51 LOG(ERROR) << "reply FMQ is invalid";
52 return false;
53 }
54 if (mFrameSize == 0) {
55 LOG(ERROR) << "frame size is not set";
56 return false;
57 }
58 if (mDataMQ && !mDataMQ->isValid()) {
59 LOG(ERROR) << "data FMQ is invalid";
60 return false;
61 }
62 return true;
63}
64
65void StreamContext::reset() {
66 mCommandMQ.reset();
67 mReplyMQ.reset();
68 mDataMQ.reset();
69}
70
71std::string StreamWorkerCommonLogic::init() {
72 if (mCommandMQ == nullptr) return "Command MQ is null";
73 if (mReplyMQ == nullptr) return "Reply MQ is null";
74 if (mDataMQ == nullptr) return "Data MQ is null";
75 if (sizeof(decltype(mDataBuffer)::element_type) != mDataMQ->getQuantumSize()) {
76 return "Unexpected Data MQ quantum size: " + std::to_string(mDataMQ->getQuantumSize());
77 }
78 mDataBufferSize = mDataMQ->getQuantumCount() * mDataMQ->getQuantumSize();
79 mDataBuffer.reset(new (std::nothrow) int8_t[mDataBufferSize]);
80 if (mDataBuffer == nullptr) {
81 return "Failed to allocate data buffer for element count " +
82 std::to_string(mDataMQ->getQuantumCount()) +
83 ", size in bytes: " + std::to_string(mDataBufferSize);
84 }
85 return "";
86}
87
88const std::string StreamInWorkerLogic::kThreadName = "reader";
89
90StreamInWorkerLogic::Status StreamInWorkerLogic::cycle() {
91 StreamDescriptor::Command command{};
92 if (!mCommandMQ->readBlocking(&command, 1)) {
93 LOG(ERROR) << __func__ << ": reading of command from MQ failed";
94 return Status::ABORT;
95 }
96 StreamDescriptor::Reply reply{};
97 if (command.code == StreamContext::COMMAND_EXIT &&
98 command.fmqByteCount == mInternalCommandCookie) {
99 LOG(DEBUG) << __func__ << ": received EXIT command";
100 // This is an internal command, no need to reply.
101 return Status::EXIT;
102 } else if (command.code == StreamDescriptor::COMMAND_BURST && command.fmqByteCount >= 0) {
103 LOG(DEBUG) << __func__ << ": received BURST read command for " << command.fmqByteCount
104 << " bytes";
105 usleep(3000); // Simulate a blocking call into the driver.
106 const size_t byteCount = std::min({static_cast<size_t>(command.fmqByteCount),
107 mDataMQ->availableToWrite(), mDataBufferSize});
108 const bool isConnected = mIsConnected;
109 // Simulate reading of data, or provide zeroes if the stream is not connected.
110 for (size_t i = 0; i < byteCount; ++i) {
111 using buffer_type = decltype(mDataBuffer)::element_type;
112 constexpr int kBufferValueRange = std::numeric_limits<buffer_type>::max() -
113 std::numeric_limits<buffer_type>::min() + 1;
114 mDataBuffer[i] = isConnected ? (std::rand() % kBufferValueRange) +
115 std::numeric_limits<buffer_type>::min()
116 : 0;
117 }
118 bool success = byteCount > 0 ? mDataMQ->write(&mDataBuffer[0], byteCount) : true;
119 if (success) {
120 LOG(DEBUG) << __func__ << ": writing of " << byteCount << " bytes into data MQ"
121 << " succeeded; connected? " << isConnected;
122 // Frames are provided and counted regardless of connection status.
123 reply.fmqByteCount = byteCount;
124 mFrameCount += byteCount / mFrameSize;
125 if (isConnected) {
126 reply.status = STATUS_OK;
127 reply.observable.frames = mFrameCount;
128 reply.observable.timeNs = ::android::elapsedRealtimeNano();
129 } else {
130 reply.status = STATUS_INVALID_OPERATION;
131 }
132 } else {
133 LOG(WARNING) << __func__ << ": writing of " << byteCount
134 << " bytes of data to MQ failed";
135 reply.status = STATUS_NOT_ENOUGH_DATA;
136 }
137 reply.latencyMs = Module::kLatencyMs;
138 } else {
139 LOG(WARNING) << __func__ << ": invalid command (" << command.toString()
140 << ") or count: " << command.fmqByteCount;
141 reply.status = STATUS_BAD_VALUE;
142 }
143 LOG(DEBUG) << __func__ << ": writing reply " << reply.toString();
144 if (!mReplyMQ->writeBlocking(&reply, 1)) {
145 LOG(ERROR) << __func__ << ": writing of reply " << reply.toString() << " to MQ failed";
146 return Status::ABORT;
147 }
148 return Status::CONTINUE;
149}
150
151const std::string StreamOutWorkerLogic::kThreadName = "writer";
152
153StreamOutWorkerLogic::Status StreamOutWorkerLogic::cycle() {
154 StreamDescriptor::Command command{};
155 if (!mCommandMQ->readBlocking(&command, 1)) {
156 LOG(ERROR) << __func__ << ": reading of command from MQ failed";
157 return Status::ABORT;
158 }
159 StreamDescriptor::Reply reply{};
160 if (command.code == StreamContext::COMMAND_EXIT &&
161 command.fmqByteCount == mInternalCommandCookie) {
162 LOG(DEBUG) << __func__ << ": received EXIT command";
163 // This is an internal command, no need to reply.
164 return Status::EXIT;
165 } else if (command.code == StreamDescriptor::COMMAND_BURST && command.fmqByteCount >= 0) {
166 LOG(DEBUG) << __func__ << ": received BURST write command for " << command.fmqByteCount
167 << " bytes";
168 const size_t byteCount = std::min({static_cast<size_t>(command.fmqByteCount),
169 mDataMQ->availableToRead(), mDataBufferSize});
170 bool success = byteCount > 0 ? mDataMQ->read(&mDataBuffer[0], byteCount) : true;
171 if (success) {
172 const bool isConnected = mIsConnected;
173 LOG(DEBUG) << __func__ << ": reading of " << byteCount << " bytes from data MQ"
174 << " succeeded; connected? " << isConnected;
175 // Frames are consumed and counted regardless of connection status.
176 reply.fmqByteCount = byteCount;
177 mFrameCount += byteCount / mFrameSize;
178 if (isConnected) {
179 reply.status = STATUS_OK;
180 reply.observable.frames = mFrameCount;
181 reply.observable.timeNs = ::android::elapsedRealtimeNano();
182 } else {
183 reply.status = STATUS_INVALID_OPERATION;
184 }
185 usleep(3000); // Simulate a blocking call into the driver.
186 } else {
187 LOG(WARNING) << __func__ << ": reading of " << byteCount
188 << " bytes of data from MQ failed";
189 reply.status = STATUS_NOT_ENOUGH_DATA;
190 }
191 reply.latencyMs = Module::kLatencyMs;
192 } else {
193 LOG(WARNING) << __func__ << ": invalid command (" << command.toString()
194 << ") or count: " << command.fmqByteCount;
195 reply.status = STATUS_BAD_VALUE;
196 }
197 LOG(DEBUG) << __func__ << ": writing reply " << reply.toString();
198 if (!mReplyMQ->writeBlocking(&reply, 1)) {
199 LOG(ERROR) << __func__ << ": writing of reply " << reply.toString() << " to MQ failed";
200 return Status::ABORT;
201 }
202 return Status::CONTINUE;
203}
204
205template <class Metadata, class StreamWorker>
206StreamCommon<Metadata, StreamWorker>::~StreamCommon() {
207 if (!mIsClosed) {
208 LOG(ERROR) << __func__ << ": stream was not closed prior to destruction, resource leak";
209 stopWorker();
210 // The worker and the context should clean up by themselves via destructors.
211 }
212}
213
214template <class Metadata, class StreamWorker>
215ndk::ScopedAStatus StreamCommon<Metadata, StreamWorker>::close() {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000216 LOG(DEBUG) << __func__;
217 if (!mIsClosed) {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000218 stopWorker();
219 LOG(DEBUG) << __func__ << ": joining the worker thread...";
220 mWorker.stop();
221 LOG(DEBUG) << __func__ << ": worker thread joined";
222 mContext.reset();
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000223 mIsClosed = true;
224 return ndk::ScopedAStatus::ok();
225 } else {
226 LOG(ERROR) << __func__ << ": stream was already closed";
227 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
228 }
229}
230
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000231template <class Metadata, class StreamWorker>
232void StreamCommon<Metadata, StreamWorker>::stopWorker() {
233 if (auto commandMQ = mContext.getCommandMQ(); commandMQ != nullptr) {
234 LOG(DEBUG) << __func__ << ": asking the worker to stop...";
235 StreamDescriptor::Command cmd;
236 cmd.code = StreamContext::COMMAND_EXIT;
237 cmd.fmqByteCount = mContext.getInternalCommandCookie();
238 // FIXME: This can block in the case when the client wrote a command
239 // while the stream worker's cycle is not running. Need to revisit
240 // when implementing standby and pause/resume.
241 if (!commandMQ->writeBlocking(&cmd, 1)) {
242 LOG(ERROR) << __func__ << ": failed to write exit command to the MQ";
243 }
244 LOG(DEBUG) << __func__ << ": done";
245 }
246}
247
248template <class Metadata, class StreamWorker>
249ndk::ScopedAStatus StreamCommon<Metadata, StreamWorker>::updateMetadata(const Metadata& metadata) {
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000250 LOG(DEBUG) << __func__;
251 if (!mIsClosed) {
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000252 mMetadata = metadata;
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000253 return ndk::ScopedAStatus::ok();
254 }
255 LOG(ERROR) << __func__ << ": stream was closed";
256 return ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
257}
258
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000259StreamIn::StreamIn(const SinkMetadata& sinkMetadata, StreamContext context)
260 : StreamCommon<SinkMetadata, StreamInWorker>(sinkMetadata, std::move(context)) {
261 LOG(DEBUG) << __func__;
262}
263
264StreamOut::StreamOut(const SourceMetadata& sourceMetadata, StreamContext context,
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000265 const std::optional<AudioOffloadInfo>& offloadInfo)
Mikhail Naganov4f5d3f12022-07-22 23:23:25 +0000266 : StreamCommon<SourceMetadata, StreamOutWorker>(sourceMetadata, std::move(context)),
267 mOffloadInfo(offloadInfo) {
Mikhail Naganov6a4872d2022-06-15 21:39:04 +0000268 LOG(DEBUG) << __func__;
269}
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000270
Mikhail Naganovdf5adfd2021-11-11 22:09:22 +0000271} // namespace aidl::android::hardware::audio::core