blob: acd4badad9b034487b7cd4e17a31a51caea84ead [file] [log] [blame]
Andy Hunge7937b92019-08-28 21:02:23 -07001/*
2 * Copyright (C) 2019 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_NDEBUG 0
18#define LOG_TAG "SoundPool::StreamManager"
19#include <utils/Log.h>
20
21#include "StreamManager.h"
22
23#include <audio_utils/clock.h>
24#include <audio_utils/roundup.h>
25
26namespace android::soundpool {
27
28// kMaxStreams is number that should be less than the current AudioTrack max per UID of 40.
29// It is the maximum number of AudioTrack resources allowed in the SoundPool.
30// We suggest a value at least 4 or greater to allow CTS tests to pass.
31static constexpr int32_t kMaxStreams = 32;
32
33// kStealActiveStream_OldestFirst = false historically (Q and earlier)
34// Changing to true could break app expectations but could change behavior beneficially.
35// In R, we change this to true, as it is the correct way per SoundPool documentation.
36static constexpr bool kStealActiveStream_OldestFirst = true;
37
38// kPlayOnCallingThread = true prior to R.
39// Changing to false means calls to play() are almost instantaneous instead of taking around
40// ~10ms to launch the AudioTrack. It is perhaps 100x faster.
Andy Hung8823c982019-12-12 19:43:12 +000041static constexpr bool kPlayOnCallingThread = true;
Andy Hunge7937b92019-08-28 21:02:23 -070042
43// Amount of time for a StreamManager thread to wait before closing.
44static constexpr int64_t kWaitTimeBeforeCloseNs = 9 * NANOS_PER_SECOND;
45
Andy Hung43da3d52021-03-15 11:31:45 -070046// Debug flag:
47// kForceLockStreamManagerStop is set to true to force lock the StreamManager
48// worker thread during stop. This limits concurrency of Stream processing.
49// Normally we lock the StreamManager worker thread during stop ONLY
50// for SoundPools configured with a single Stream.
51//
52static constexpr bool kForceLockStreamManagerStop = false;
53
Andy Hunge7937b92019-08-28 21:02:23 -070054////////////
55
56StreamMap::StreamMap(int32_t streams) {
57 ALOGV("%s(%d)", __func__, streams);
58 if (streams > kMaxStreams) {
59 ALOGW("%s: requested %d streams, clamping to %d", __func__, streams, kMaxStreams);
60 streams = kMaxStreams;
61 } else if (streams < 1) {
62 ALOGW("%s: requested %d streams, clamping to 1", __func__, streams);
63 streams = 1;
64 }
65 mStreamPoolSize = streams * 2;
Andy Hung77eb2bd2020-05-19 10:42:09 -070066 mStreamPool = std::make_unique<Stream[]>(mStreamPoolSize); // create array of streams.
Andy Hunge7937b92019-08-28 21:02:23 -070067 // we use a perfect hash table with 2x size to map StreamIDs to Stream pointers.
68 mPerfectHash = std::make_unique<PerfectHash<int32_t, Stream *>>(roundup(mStreamPoolSize * 2));
69}
70
71Stream* StreamMap::findStream(int32_t streamID) const
72{
73 Stream *stream = lookupStreamFromId(streamID);
74 return stream != nullptr && stream->getStreamID() == streamID ? stream : nullptr;
75}
76
77size_t StreamMap::streamPosition(const Stream* stream) const
78{
79 ptrdiff_t index = stream - mStreamPool.get();
Andy Hung77eb2bd2020-05-19 10:42:09 -070080 LOG_ALWAYS_FATAL_IF(index < 0 || (size_t)index >= mStreamPoolSize,
Andy Hunge7937b92019-08-28 21:02:23 -070081 "%s: stream position out of range: %td", __func__, index);
82 return (size_t)index;
83}
84
85Stream* StreamMap::lookupStreamFromId(int32_t streamID) const
86{
87 return streamID > 0 ? mPerfectHash->getValue(streamID).load() : nullptr;
88}
89
90int32_t StreamMap::getNextIdForStream(Stream* stream) const {
91 // even though it is const, it mutates the internal hash table.
92 const int32_t id = mPerfectHash->generateKey(
93 stream,
94 [] (Stream *stream) {
95 return stream == nullptr ? 0 : stream->getStreamID();
96 }, /* getKforV() */
97 stream->getStreamID() /* oldID */);
98 return id;
99}
100
101////////////
102
Andy Hung77eb2bd2020-05-19 10:42:09 -0700103// Thread safety analysis is supposed to be disabled for constructors and destructors
104// but clang in R seems to have a bug. We use pragma to disable.
105#pragma clang diagnostic push
106#pragma clang diagnostic ignored "-Wthread-safety-analysis"
107
Andy Hunge7937b92019-08-28 21:02:23 -0700108StreamManager::StreamManager(
Andy Hung240d32c2022-03-18 19:49:09 -0700109 int32_t streams, size_t threads, const audio_attributes_t& attributes,
jiabin181d26b2020-12-14 21:13:30 -0800110 std::string opPackageName)
Andy Hunge7937b92019-08-28 21:02:23 -0700111 : StreamMap(streams)
Andy Hung240d32c2022-03-18 19:49:09 -0700112 , mAttributes(attributes)
jiabin181d26b2020-12-14 21:13:30 -0800113 , mOpPackageName(std::move(opPackageName))
Andy Hung43da3d52021-03-15 11:31:45 -0700114 , mLockStreamManagerStop(streams == 1 || kForceLockStreamManagerStop)
Andy Hunge7937b92019-08-28 21:02:23 -0700115{
116 ALOGV("%s(%d, %zu, ...)", __func__, streams, threads);
117 forEach([this](Stream *stream) {
118 stream->setStreamManager(this);
119 if ((streamPosition(stream) & 1) == 0) { // put the first stream of pair as available.
120 mAvailableStreams.insert(stream);
121 }
122 });
123
124 mThreadPool = std::make_unique<ThreadPool>(
Andy Hung43da3d52021-03-15 11:31:45 -0700125 std::min((size_t)streams, // do not make more threads than streams to play
126 std::min(threads, (size_t)std::thread::hardware_concurrency())),
Andy Hunge7937b92019-08-28 21:02:23 -0700127 "SoundPool_");
128}
129
Andy Hung77eb2bd2020-05-19 10:42:09 -0700130#pragma clang diagnostic pop
131
Andy Hunge7937b92019-08-28 21:02:23 -0700132StreamManager::~StreamManager()
133{
134 ALOGV("%s", __func__);
135 {
136 std::unique_lock lock(mStreamManagerLock);
137 mQuit = true;
138 mStreamManagerCondition.notify_all();
139 }
140 mThreadPool->quit();
141
142 // call stop on the stream pool
143 forEach([](Stream *stream) { stream->stop(); });
144
145 // This invokes the destructor on the AudioTracks -
146 // we do it here to ensure that AudioTrack callbacks will not occur
147 // afterwards.
148 forEach([](Stream *stream) { stream->clearAudioTrack(); });
149}
150
151
152int32_t StreamManager::queueForPlay(const std::shared_ptr<Sound> &sound,
153 int32_t soundID, float leftVolume, float rightVolume,
Vlad Popaa6f2f1692022-08-19 15:08:22 +0200154 int32_t priority, int32_t loop, float rate, int32_t playerIId)
Andy Hunge7937b92019-08-28 21:02:23 -0700155{
Vlad Popaa6f2f1692022-08-19 15:08:22 +0200156 ALOGV(
157 "%s(sound=%p, soundID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f,"
158 " playerIId=%d)", __func__, sound.get(), soundID, leftVolume, rightVolume, priority,
159 loop, rate, playerIId);
160
Andy Hunge7937b92019-08-28 21:02:23 -0700161 bool launchThread = false;
162 int32_t streamID = 0;
Andy Hung4474c3f2021-11-29 09:53:39 -0800163 std::vector<std::any> garbage;
Andy Hunge7937b92019-08-28 21:02:23 -0700164
165 { // for lock
166 std::unique_lock lock(mStreamManagerLock);
167 Stream *newStream = nullptr;
168 bool fromAvailableQueue = false;
169 ALOGV("%s: mStreamManagerLock lock acquired", __func__);
170
171 sanityCheckQueue_l();
172 // find an available stream, prefer one that has matching sound id.
173 if (mAvailableStreams.size() > 0) {
Andy Hunge7937b92019-08-28 21:02:23 -0700174 for (auto stream : mAvailableStreams) {
175 if (stream->getSoundID() == soundID) {
176 newStream = stream;
Andy Hung457ed3a2019-11-19 16:44:13 -0800177 ALOGV("%s: found soundID %d in available queue", __func__, soundID);
Andy Hunge7937b92019-08-28 21:02:23 -0700178 break;
179 }
180 }
Andy Hung457ed3a2019-11-19 16:44:13 -0800181 if (newStream == nullptr) {
182 ALOGV("%s: found stream in available queue", __func__);
183 newStream = *mAvailableStreams.begin();
Andy Hunge7937b92019-08-28 21:02:23 -0700184 }
Andy Hung457ed3a2019-11-19 16:44:13 -0800185 newStream->setStopTimeNs(systemTime());
Andy Hunge7937b92019-08-28 21:02:23 -0700186 fromAvailableQueue = true;
187 }
188
189 // also look in the streams restarting (if the paired stream doesn't have a pending play)
190 if (newStream == nullptr || newStream->getSoundID() != soundID) {
191 for (auto [unused , stream] : mRestartStreams) {
192 if (!stream->getPairStream()->hasSound()) {
193 if (stream->getSoundID() == soundID) {
Andy Hung457ed3a2019-11-19 16:44:13 -0800194 ALOGV("%s: found soundID %d in restart queue", __func__, soundID);
Andy Hunge7937b92019-08-28 21:02:23 -0700195 newStream = stream;
Andy Hung8823c982019-12-12 19:43:12 +0000196 fromAvailableQueue = false;
Andy Hunge7937b92019-08-28 21:02:23 -0700197 break;
198 } else if (newStream == nullptr) {
Andy Hung457ed3a2019-11-19 16:44:13 -0800199 ALOGV("%s: found stream in restart queue", __func__);
Andy Hunge7937b92019-08-28 21:02:23 -0700200 newStream = stream;
201 }
202 }
203 }
204 }
205
206 // no available streams, look for one to steal from the active list
207 if (newStream == nullptr) {
208 for (auto stream : mActiveStreams) {
209 if (stream->getPriority() <= priority) {
210 if (newStream == nullptr
211 || newStream->getPriority() > stream->getPriority()) {
212 newStream = stream;
Andy Hung457ed3a2019-11-19 16:44:13 -0800213 ALOGV("%s: found stream in active queue", __func__);
Andy Hunge7937b92019-08-28 21:02:23 -0700214 }
215 }
216 }
217 if (newStream != nullptr) { // we need to mute as it is still playing.
218 (void)newStream->requestStop(newStream->getStreamID());
219 }
220 }
221
222 // none found, look for a stream that is restarting, evict one.
223 if (newStream == nullptr) {
224 for (auto [unused, stream] : mRestartStreams) {
225 if (stream->getPairPriority() <= priority) {
Andy Hung457ed3a2019-11-19 16:44:13 -0800226 ALOGV("%s: evict stream from restart queue", __func__);
Andy Hunge7937b92019-08-28 21:02:23 -0700227 newStream = stream;
228 break;
229 }
230 }
231 }
232
233 // DO NOT LOOK into mProcessingStreams as those are held by the StreamManager threads.
234
235 if (newStream == nullptr) {
236 ALOGD("%s: unable to find stream, returning 0", __func__);
237 return 0; // unable to find available stream
238 }
239
240 Stream *pairStream = newStream->getPairStream();
241 streamID = getNextIdForStream(pairStream);
Andy Hung457ed3a2019-11-19 16:44:13 -0800242 ALOGV("%s: newStream:%p pairStream:%p, streamID:%d",
243 __func__, newStream, pairStream, streamID);
Andy Hunge7937b92019-08-28 21:02:23 -0700244 pairStream->setPlay(
245 streamID, sound, soundID, leftVolume, rightVolume, priority, loop, rate);
246 if (fromAvailableQueue && kPlayOnCallingThread) {
247 removeFromQueues_l(newStream);
248 mProcessingStreams.emplace(newStream);
249 lock.unlock();
Vlad Popaa6f2f1692022-08-19 15:08:22 +0200250 if (Stream* nextStream = newStream->playPairStream(garbage, playerIId)) {
Andy Hunge7937b92019-08-28 21:02:23 -0700251 lock.lock();
252 ALOGV("%s: starting streamID:%d", __func__, nextStream->getStreamID());
253 addToActiveQueue_l(nextStream);
254 } else {
255 lock.lock();
256 mAvailableStreams.insert(newStream);
257 streamID = 0;
258 }
259 mProcessingStreams.erase(newStream);
260 } else {
261 launchThread = moveToRestartQueue_l(newStream) && needMoreThreads_l();
262 }
263 sanityCheckQueue_l();
264 ALOGV("%s: mStreamManagerLock released", __func__);
265 } // lock
266
267 if (launchThread) {
Andy Hungce8e6da2020-06-01 09:46:03 -0700268 const int32_t id = mThreadPool->launch([this](int32_t id) { run(id); });
269 (void)id; // avoid clang warning -Wunused-variable -Wused-but-marked-unused
Andy Hunge7937b92019-08-28 21:02:23 -0700270 ALOGV_IF(id != 0, "%s: launched thread %d", __func__, id);
271 }
272 ALOGV("%s: returning %d", __func__, streamID);
Andy Hung4474c3f2021-11-29 09:53:39 -0800273 // garbage is cleared here outside mStreamManagerLock.
Andy Hunge7937b92019-08-28 21:02:23 -0700274 return streamID;
275}
276
277void StreamManager::moveToRestartQueue(
278 Stream* stream, int32_t activeStreamIDToMatch)
279{
280 ALOGV("%s(stream(ID)=%d, activeStreamIDToMatch=%d)",
281 __func__, stream->getStreamID(), activeStreamIDToMatch);
282 bool restart;
283 {
284 std::lock_guard lock(mStreamManagerLock);
285 sanityCheckQueue_l();
286 if (mProcessingStreams.count(stream) > 0 ||
287 mProcessingStreams.count(stream->getPairStream()) > 0) {
288 ALOGD("%s: attempting to restart processing stream(%d)",
289 __func__, stream->getStreamID());
290 restart = false;
291 } else {
292 moveToRestartQueue_l(stream, activeStreamIDToMatch);
293 restart = needMoreThreads_l();
294 }
295 sanityCheckQueue_l();
296 }
297 if (restart) {
Andy Hungce8e6da2020-06-01 09:46:03 -0700298 const int32_t id = mThreadPool->launch([this](int32_t id) { run(id); });
299 (void)id; // avoid clang warning -Wunused-variable -Wused-but-marked-unused
Andy Hunge7937b92019-08-28 21:02:23 -0700300 ALOGV_IF(id != 0, "%s: launched thread %d", __func__, id);
301 }
302}
303
304bool StreamManager::moveToRestartQueue_l(
305 Stream* stream, int32_t activeStreamIDToMatch)
306{
307 ALOGV("%s(stream(ID)=%d, activeStreamIDToMatch=%d)",
308 __func__, stream->getStreamID(), activeStreamIDToMatch);
309 if (activeStreamIDToMatch > 0 && stream->getStreamID() != activeStreamIDToMatch) {
310 return false;
311 }
312 const ssize_t found = removeFromQueues_l(stream, activeStreamIDToMatch);
313 if (found < 0) return false;
314
315 LOG_ALWAYS_FATAL_IF(found > 1, "stream on %zd > 1 stream lists", found);
316
317 addToRestartQueue_l(stream);
318 mStreamManagerCondition.notify_one();
319 return true;
320}
321
322ssize_t StreamManager::removeFromQueues_l(
323 Stream* stream, int32_t activeStreamIDToMatch) {
324 size_t found = 0;
325 for (auto it = mActiveStreams.begin(); it != mActiveStreams.end(); ++it) {
326 if (*it == stream) {
327 mActiveStreams.erase(it); // we erase the iterator and break (otherwise it not safe).
328 ++found;
329 break;
330 }
331 }
332 // activeStreamIDToMatch is nonzero indicates we proceed only if found.
333 if (found == 0 && activeStreamIDToMatch > 0) {
334 return -1; // special code: not present on active streams, ignore restart request
335 }
336
337 for (auto it = mRestartStreams.begin(); it != mRestartStreams.end(); ++it) {
338 if (it->second == stream) {
339 mRestartStreams.erase(it);
340 ++found;
341 break;
342 }
343 }
344 found += mAvailableStreams.erase(stream);
345
346 // streams on mProcessingStreams are undergoing processing by the StreamManager thread
347 // and do not participate in normal stream migration.
Andy Hunga5daa172021-03-10 17:07:17 -0800348 return (ssize_t)found;
Andy Hunge7937b92019-08-28 21:02:23 -0700349}
350
351void StreamManager::addToRestartQueue_l(Stream *stream) {
352 mRestartStreams.emplace(stream->getStopTimeNs(), stream);
353}
354
355void StreamManager::addToActiveQueue_l(Stream *stream) {
356 if (kStealActiveStream_OldestFirst) {
357 mActiveStreams.push_back(stream); // oldest to newest
358 } else {
359 mActiveStreams.push_front(stream); // newest to oldest
360 }
361}
362
363void StreamManager::run(int32_t id)
364{
365 ALOGV("%s(%d) entering", __func__, id);
Andy Hungdaa60c22021-03-15 19:01:51 -0700366 int64_t waitTimeNs = 0; // on thread start, mRestartStreams can be non-empty.
Andy Hung4474c3f2021-11-29 09:53:39 -0800367 std::vector<std::any> garbage; // used for garbage collection
Andy Hunge7937b92019-08-28 21:02:23 -0700368 std::unique_lock lock(mStreamManagerLock);
369 while (!mQuit) {
Andy Hungdaa60c22021-03-15 19:01:51 -0700370 if (waitTimeNs > 0) {
Andy Hungba04dbe2020-03-19 21:32:53 -0700371 mStreamManagerCondition.wait_for(
372 lock, std::chrono::duration<int64_t, std::nano>(waitTimeNs));
373 }
Andy Hungdaa60c22021-03-15 19:01:51 -0700374 ALOGV("%s(%d) awake lock waitTimeNs:%lld", __func__, id, (long long)waitTimeNs);
Andy Hunge7937b92019-08-28 21:02:23 -0700375
376 sanityCheckQueue_l();
377
378 if (mQuit || (mRestartStreams.empty() && waitTimeNs == kWaitTimeBeforeCloseNs)) {
379 break; // end the thread
380 }
381
382 waitTimeNs = kWaitTimeBeforeCloseNs;
383 while (!mQuit && !mRestartStreams.empty()) {
384 const nsecs_t nowNs = systemTime();
385 auto it = mRestartStreams.begin();
386 Stream* const stream = it->second;
387 const int64_t diffNs = stream->getStopTimeNs() - nowNs;
388 if (diffNs > 0) {
389 waitTimeNs = std::min(waitTimeNs, diffNs);
390 break;
391 }
392 mRestartStreams.erase(it);
393 mProcessingStreams.emplace(stream);
Andy Hung43da3d52021-03-15 11:31:45 -0700394 if (!mLockStreamManagerStop) lock.unlock();
Andy Hunge7937b92019-08-28 21:02:23 -0700395 stream->stop();
396 ALOGV("%s(%d) stopping streamID:%d", __func__, id, stream->getStreamID());
Andy Hung4474c3f2021-11-29 09:53:39 -0800397 if (Stream* nextStream = stream->playPairStream(garbage)) {
Andy Hunge7937b92019-08-28 21:02:23 -0700398 ALOGV("%s(%d) starting streamID:%d", __func__, id, nextStream->getStreamID());
Andy Hung43da3d52021-03-15 11:31:45 -0700399 if (!mLockStreamManagerStop) lock.lock();
Andy Hunge7937b92019-08-28 21:02:23 -0700400 if (nextStream->getStopTimeNs() > 0) {
401 // the next stream was stopped before we can move it to the active queue.
402 ALOGV("%s(%d) stopping started streamID:%d",
403 __func__, id, nextStream->getStreamID());
404 moveToRestartQueue_l(nextStream);
405 } else {
406 addToActiveQueue_l(nextStream);
407 }
408 } else {
Andy Hung43da3d52021-03-15 11:31:45 -0700409 if (!mLockStreamManagerStop) lock.lock();
Andy Hunge7937b92019-08-28 21:02:23 -0700410 mAvailableStreams.insert(stream);
411 }
412 mProcessingStreams.erase(stream);
413 sanityCheckQueue_l();
Andy Hung4474c3f2021-11-29 09:53:39 -0800414 if (!garbage.empty()) {
415 lock.unlock();
416 // garbage audio tracks (etc) are cleared here outside mStreamManagerLock.
417 garbage.clear();
418 lock.lock();
419 }
Andy Hunge7937b92019-08-28 21:02:23 -0700420 }
421 }
422 ALOGV("%s(%d) exiting", __func__, id);
423}
424
425void StreamManager::dump() const
426{
427 forEach([](const Stream *stream) { stream->dump(); });
428}
429
430void StreamManager::sanityCheckQueue_l() const
431{
432 // We want to preserve the invariant that each stream pair is exactly on one of the queues.
433 const size_t availableStreams = mAvailableStreams.size();
434 const size_t restartStreams = mRestartStreams.size();
435 const size_t activeStreams = mActiveStreams.size();
436 const size_t processingStreams = mProcessingStreams.size();
437 const size_t managedStreams = availableStreams + restartStreams + activeStreams
438 + processingStreams;
439 const size_t totalStreams = getStreamMapSize() >> 1;
440 LOG_ALWAYS_FATAL_IF(managedStreams != totalStreams,
441 "%s: mAvailableStreams:%zu + mRestartStreams:%zu + "
442 "mActiveStreams:%zu + mProcessingStreams:%zu = %zu != total streams %zu",
443 __func__, availableStreams, restartStreams, activeStreams, processingStreams,
444 managedStreams, totalStreams);
445 ALOGV("%s: mAvailableStreams:%zu + mRestartStreams:%zu + "
446 "mActiveStreams:%zu + mProcessingStreams:%zu = %zu (total streams: %zu)",
447 __func__, availableStreams, restartStreams, activeStreams, processingStreams,
448 managedStreams, totalStreams);
449}
450
451} // namespace android::soundpool