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