blob: 66fec1c528e79d94db2896677ea5655db943396c [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
Andy Hunge7937b92019-08-28 21:02:23 -070038// Changing to false means calls to play() are almost instantaneous instead of taking around
39// ~10ms to launch the AudioTrack. It is perhaps 100x faster.
Andy Hungb9faaa32024-01-10 17:47:44 -080040static constexpr bool kPlayOnCallingThread = false;
Andy Hunge7937b92019-08-28 21:02:23 -070041
42// Amount of time for a StreamManager thread to wait before closing.
43static constexpr int64_t kWaitTimeBeforeCloseNs = 9 * NANOS_PER_SECOND;
44
Andy Hung43da3d52021-03-15 11:31:45 -070045// Debug flag:
46// kForceLockStreamManagerStop is set to true to force lock the StreamManager
47// worker thread during stop. This limits concurrency of Stream processing.
48// Normally we lock the StreamManager worker thread during stop ONLY
49// for SoundPools configured with a single Stream.
50//
51static constexpr bool kForceLockStreamManagerStop = false;
52
Andy Hunge7937b92019-08-28 21:02:23 -070053////////////
54
55StreamMap::StreamMap(int32_t streams) {
56 ALOGV("%s(%d)", __func__, streams);
57 if (streams > kMaxStreams) {
58 ALOGW("%s: requested %d streams, clamping to %d", __func__, streams, kMaxStreams);
59 streams = kMaxStreams;
60 } else if (streams < 1) {
61 ALOGW("%s: requested %d streams, clamping to 1", __func__, streams);
62 streams = 1;
63 }
64 mStreamPoolSize = streams * 2;
Andy Hung77eb2bd2020-05-19 10:42:09 -070065 mStreamPool = std::make_unique<Stream[]>(mStreamPoolSize); // create array of streams.
Andy Hunge7937b92019-08-28 21:02:23 -070066 // we use a perfect hash table with 2x size to map StreamIDs to Stream pointers.
67 mPerfectHash = std::make_unique<PerfectHash<int32_t, Stream *>>(roundup(mStreamPoolSize * 2));
68}
69
70Stream* StreamMap::findStream(int32_t streamID) const
71{
72 Stream *stream = lookupStreamFromId(streamID);
73 return stream != nullptr && stream->getStreamID() == streamID ? stream : nullptr;
74}
75
76size_t StreamMap::streamPosition(const Stream* stream) const
77{
78 ptrdiff_t index = stream - mStreamPool.get();
Andy Hung77eb2bd2020-05-19 10:42:09 -070079 LOG_ALWAYS_FATAL_IF(index < 0 || (size_t)index >= mStreamPoolSize,
Andy Hunge7937b92019-08-28 21:02:23 -070080 "%s: stream position out of range: %td", __func__, index);
81 return (size_t)index;
82}
83
84Stream* StreamMap::lookupStreamFromId(int32_t streamID) const
85{
86 return streamID > 0 ? mPerfectHash->getValue(streamID).load() : nullptr;
87}
88
89int32_t StreamMap::getNextIdForStream(Stream* stream) const {
90 // even though it is const, it mutates the internal hash table.
91 const int32_t id = mPerfectHash->generateKey(
92 stream,
93 [] (Stream *stream) {
94 return stream == nullptr ? 0 : stream->getStreamID();
95 }, /* getKforV() */
96 stream->getStreamID() /* oldID */);
97 return id;
98}
99
100////////////
101
Andy Hung77eb2bd2020-05-19 10:42:09 -0700102// Thread safety analysis is supposed to be disabled for constructors and destructors
103// but clang in R seems to have a bug. We use pragma to disable.
104#pragma clang diagnostic push
105#pragma clang diagnostic ignored "-Wthread-safety-analysis"
106
Andy Hunge7937b92019-08-28 21:02:23 -0700107StreamManager::StreamManager(
Andy Hung240d32c2022-03-18 19:49:09 -0700108 int32_t streams, size_t threads, const audio_attributes_t& attributes,
jiabin181d26b2020-12-14 21:13:30 -0800109 std::string opPackageName)
Andy Hunge7937b92019-08-28 21:02:23 -0700110 : StreamMap(streams)
Eric Laurent7ab61032023-05-17 14:40:01 +0200111 , mAttributes([attributes](){
112 audio_attributes_t attr = attributes;
113 attr.flags = static_cast<audio_flags_mask_t>(attr.flags | AUDIO_FLAG_LOW_LATENCY);
114 return attr; }())
jiabin181d26b2020-12-14 21:13:30 -0800115 , mOpPackageName(std::move(opPackageName))
Andy Hung43da3d52021-03-15 11:31:45 -0700116 , mLockStreamManagerStop(streams == 1 || kForceLockStreamManagerStop)
Andy Hunge7937b92019-08-28 21:02:23 -0700117{
118 ALOGV("%s(%d, %zu, ...)", __func__, streams, threads);
119 forEach([this](Stream *stream) {
120 stream->setStreamManager(this);
121 if ((streamPosition(stream) & 1) == 0) { // put the first stream of pair as available.
122 mAvailableStreams.insert(stream);
123 }
124 });
125
126 mThreadPool = std::make_unique<ThreadPool>(
Andy Hung43da3d52021-03-15 11:31:45 -0700127 std::min((size_t)streams, // do not make more threads than streams to play
128 std::min(threads, (size_t)std::thread::hardware_concurrency())),
Andy Hunge7937b92019-08-28 21:02:23 -0700129 "SoundPool_");
130}
131
Andy Hung77eb2bd2020-05-19 10:42:09 -0700132#pragma clang diagnostic pop
133
Andy Hunge7937b92019-08-28 21:02:23 -0700134StreamManager::~StreamManager()
135{
136 ALOGV("%s", __func__);
137 {
138 std::unique_lock lock(mStreamManagerLock);
139 mQuit = true;
140 mStreamManagerCondition.notify_all();
141 }
142 mThreadPool->quit();
143
144 // call stop on the stream pool
145 forEach([](Stream *stream) { stream->stop(); });
146
147 // This invokes the destructor on the AudioTracks -
148 // we do it here to ensure that AudioTrack callbacks will not occur
149 // afterwards.
150 forEach([](Stream *stream) { stream->clearAudioTrack(); });
151}
152
153
154int32_t StreamManager::queueForPlay(const std::shared_ptr<Sound> &sound,
155 int32_t soundID, float leftVolume, float rightVolume,
Vlad Popaa6f2f1692022-08-19 15:08:22 +0200156 int32_t priority, int32_t loop, float rate, int32_t playerIId)
Andy Hunge7937b92019-08-28 21:02:23 -0700157{
Vlad Popaa6f2f1692022-08-19 15:08:22 +0200158 ALOGV(
159 "%s(sound=%p, soundID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f,"
160 " playerIId=%d)", __func__, sound.get(), soundID, leftVolume, rightVolume, priority,
161 loop, rate, playerIId);
162
Andy Hunge7937b92019-08-28 21:02:23 -0700163 bool launchThread = false;
164 int32_t streamID = 0;
Andy Hung4474c3f2021-11-29 09:53:39 -0800165 std::vector<std::any> garbage;
Andy Hunge7937b92019-08-28 21:02:23 -0700166
167 { // for lock
168 std::unique_lock lock(mStreamManagerLock);
169 Stream *newStream = nullptr;
170 bool fromAvailableQueue = false;
171 ALOGV("%s: mStreamManagerLock lock acquired", __func__);
172
173 sanityCheckQueue_l();
174 // find an available stream, prefer one that has matching sound id.
175 if (mAvailableStreams.size() > 0) {
Andy Hunge7937b92019-08-28 21:02:23 -0700176 for (auto stream : mAvailableStreams) {
177 if (stream->getSoundID() == soundID) {
178 newStream = stream;
Andy Hung457ed3a2019-11-19 16:44:13 -0800179 ALOGV("%s: found soundID %d in available queue", __func__, soundID);
Andy Hunge7937b92019-08-28 21:02:23 -0700180 break;
181 }
182 }
Andy Hung457ed3a2019-11-19 16:44:13 -0800183 if (newStream == nullptr) {
184 ALOGV("%s: found stream in available queue", __func__);
185 newStream = *mAvailableStreams.begin();
Andy Hunge7937b92019-08-28 21:02:23 -0700186 }
Andy Hung457ed3a2019-11-19 16:44:13 -0800187 newStream->setStopTimeNs(systemTime());
Andy Hunge7937b92019-08-28 21:02:23 -0700188 fromAvailableQueue = true;
189 }
190
191 // also look in the streams restarting (if the paired stream doesn't have a pending play)
192 if (newStream == nullptr || newStream->getSoundID() != soundID) {
193 for (auto [unused , stream] : mRestartStreams) {
194 if (!stream->getPairStream()->hasSound()) {
195 if (stream->getSoundID() == soundID) {
Andy Hung457ed3a2019-11-19 16:44:13 -0800196 ALOGV("%s: found soundID %d in restart queue", __func__, soundID);
Andy Hunge7937b92019-08-28 21:02:23 -0700197 newStream = stream;
Andy Hung8823c982019-12-12 19:43:12 +0000198 fromAvailableQueue = false;
Andy Hunge7937b92019-08-28 21:02:23 -0700199 break;
200 } else if (newStream == nullptr) {
Andy Hung457ed3a2019-11-19 16:44:13 -0800201 ALOGV("%s: found stream in restart queue", __func__);
Andy Hunge7937b92019-08-28 21:02:23 -0700202 newStream = stream;
203 }
204 }
205 }
206 }
207
208 // no available streams, look for one to steal from the active list
209 if (newStream == nullptr) {
210 for (auto stream : mActiveStreams) {
211 if (stream->getPriority() <= priority) {
212 if (newStream == nullptr
213 || newStream->getPriority() > stream->getPriority()) {
214 newStream = stream;
Andy Hung457ed3a2019-11-19 16:44:13 -0800215 ALOGV("%s: found stream in active queue", __func__);
Andy Hunge7937b92019-08-28 21:02:23 -0700216 }
217 }
218 }
219 if (newStream != nullptr) { // we need to mute as it is still playing.
220 (void)newStream->requestStop(newStream->getStreamID());
221 }
222 }
223
224 // none found, look for a stream that is restarting, evict one.
225 if (newStream == nullptr) {
226 for (auto [unused, stream] : mRestartStreams) {
227 if (stream->getPairPriority() <= priority) {
Andy Hung457ed3a2019-11-19 16:44:13 -0800228 ALOGV("%s: evict stream from restart queue", __func__);
Andy Hunge7937b92019-08-28 21:02:23 -0700229 newStream = stream;
230 break;
231 }
232 }
233 }
234
235 // DO NOT LOOK into mProcessingStreams as those are held by the StreamManager threads.
236
237 if (newStream == nullptr) {
238 ALOGD("%s: unable to find stream, returning 0", __func__);
239 return 0; // unable to find available stream
240 }
241
242 Stream *pairStream = newStream->getPairStream();
243 streamID = getNextIdForStream(pairStream);
Andy Hung457ed3a2019-11-19 16:44:13 -0800244 ALOGV("%s: newStream:%p pairStream:%p, streamID:%d",
245 __func__, newStream, pairStream, streamID);
Andy Hunge7937b92019-08-28 21:02:23 -0700246 pairStream->setPlay(
247 streamID, sound, soundID, leftVolume, rightVolume, priority, loop, rate);
248 if (fromAvailableQueue && kPlayOnCallingThread) {
249 removeFromQueues_l(newStream);
250 mProcessingStreams.emplace(newStream);
251 lock.unlock();
Vlad Popaa6f2f1692022-08-19 15:08:22 +0200252 if (Stream* nextStream = newStream->playPairStream(garbage, playerIId)) {
Andy Hunge7937b92019-08-28 21:02:23 -0700253 lock.lock();
254 ALOGV("%s: starting streamID:%d", __func__, nextStream->getStreamID());
255 addToActiveQueue_l(nextStream);
256 } else {
257 lock.lock();
258 mAvailableStreams.insert(newStream);
259 streamID = 0;
260 }
261 mProcessingStreams.erase(newStream);
262 } else {
263 launchThread = moveToRestartQueue_l(newStream) && needMoreThreads_l();
264 }
265 sanityCheckQueue_l();
266 ALOGV("%s: mStreamManagerLock released", __func__);
267 } // lock
268
269 if (launchThread) {
Andy Hungce8e6da2020-06-01 09:46:03 -0700270 const int32_t id = mThreadPool->launch([this](int32_t id) { run(id); });
271 (void)id; // avoid clang warning -Wunused-variable -Wused-but-marked-unused
Andy Hunge7937b92019-08-28 21:02:23 -0700272 ALOGV_IF(id != 0, "%s: launched thread %d", __func__, id);
273 }
274 ALOGV("%s: returning %d", __func__, streamID);
Andy Hung4474c3f2021-11-29 09:53:39 -0800275 // garbage is cleared here outside mStreamManagerLock.
Andy Hunge7937b92019-08-28 21:02:23 -0700276 return streamID;
277}
278
279void StreamManager::moveToRestartQueue(
280 Stream* stream, int32_t activeStreamIDToMatch)
281{
282 ALOGV("%s(stream(ID)=%d, activeStreamIDToMatch=%d)",
283 __func__, stream->getStreamID(), activeStreamIDToMatch);
284 bool restart;
285 {
286 std::lock_guard lock(mStreamManagerLock);
287 sanityCheckQueue_l();
288 if (mProcessingStreams.count(stream) > 0 ||
289 mProcessingStreams.count(stream->getPairStream()) > 0) {
290 ALOGD("%s: attempting to restart processing stream(%d)",
291 __func__, stream->getStreamID());
292 restart = false;
293 } else {
294 moveToRestartQueue_l(stream, activeStreamIDToMatch);
295 restart = needMoreThreads_l();
296 }
297 sanityCheckQueue_l();
298 }
299 if (restart) {
Andy Hungce8e6da2020-06-01 09:46:03 -0700300 const int32_t id = mThreadPool->launch([this](int32_t id) { run(id); });
301 (void)id; // avoid clang warning -Wunused-variable -Wused-but-marked-unused
Andy Hunge7937b92019-08-28 21:02:23 -0700302 ALOGV_IF(id != 0, "%s: launched thread %d", __func__, id);
303 }
304}
305
306bool StreamManager::moveToRestartQueue_l(
307 Stream* stream, int32_t activeStreamIDToMatch)
308{
309 ALOGV("%s(stream(ID)=%d, activeStreamIDToMatch=%d)",
310 __func__, stream->getStreamID(), activeStreamIDToMatch);
311 if (activeStreamIDToMatch > 0 && stream->getStreamID() != activeStreamIDToMatch) {
312 return false;
313 }
314 const ssize_t found = removeFromQueues_l(stream, activeStreamIDToMatch);
315 if (found < 0) return false;
316
317 LOG_ALWAYS_FATAL_IF(found > 1, "stream on %zd > 1 stream lists", found);
318
319 addToRestartQueue_l(stream);
320 mStreamManagerCondition.notify_one();
321 return true;
322}
323
324ssize_t StreamManager::removeFromQueues_l(
325 Stream* stream, int32_t activeStreamIDToMatch) {
326 size_t found = 0;
327 for (auto it = mActiveStreams.begin(); it != mActiveStreams.end(); ++it) {
328 if (*it == stream) {
329 mActiveStreams.erase(it); // we erase the iterator and break (otherwise it not safe).
330 ++found;
331 break;
332 }
333 }
334 // activeStreamIDToMatch is nonzero indicates we proceed only if found.
335 if (found == 0 && activeStreamIDToMatch > 0) {
336 return -1; // special code: not present on active streams, ignore restart request
337 }
338
339 for (auto it = mRestartStreams.begin(); it != mRestartStreams.end(); ++it) {
340 if (it->second == stream) {
341 mRestartStreams.erase(it);
342 ++found;
343 break;
344 }
345 }
346 found += mAvailableStreams.erase(stream);
347
348 // streams on mProcessingStreams are undergoing processing by the StreamManager thread
349 // and do not participate in normal stream migration.
Andy Hunga5daa172021-03-10 17:07:17 -0800350 return (ssize_t)found;
Andy Hunge7937b92019-08-28 21:02:23 -0700351}
352
353void StreamManager::addToRestartQueue_l(Stream *stream) {
354 mRestartStreams.emplace(stream->getStopTimeNs(), stream);
355}
356
357void StreamManager::addToActiveQueue_l(Stream *stream) {
358 if (kStealActiveStream_OldestFirst) {
359 mActiveStreams.push_back(stream); // oldest to newest
360 } else {
361 mActiveStreams.push_front(stream); // newest to oldest
362 }
363}
364
365void StreamManager::run(int32_t id)
366{
367 ALOGV("%s(%d) entering", __func__, id);
Andy Hungdaa60c22021-03-15 19:01:51 -0700368 int64_t waitTimeNs = 0; // on thread start, mRestartStreams can be non-empty.
Andy Hung4474c3f2021-11-29 09:53:39 -0800369 std::vector<std::any> garbage; // used for garbage collection
Andy Hunge7937b92019-08-28 21:02:23 -0700370 std::unique_lock lock(mStreamManagerLock);
371 while (!mQuit) {
Andy Hungdaa60c22021-03-15 19:01:51 -0700372 if (waitTimeNs > 0) {
Andy Hungba04dbe2020-03-19 21:32:53 -0700373 mStreamManagerCondition.wait_for(
374 lock, std::chrono::duration<int64_t, std::nano>(waitTimeNs));
375 }
Andy Hungdaa60c22021-03-15 19:01:51 -0700376 ALOGV("%s(%d) awake lock waitTimeNs:%lld", __func__, id, (long long)waitTimeNs);
Andy Hunge7937b92019-08-28 21:02:23 -0700377
378 sanityCheckQueue_l();
379
380 if (mQuit || (mRestartStreams.empty() && waitTimeNs == kWaitTimeBeforeCloseNs)) {
381 break; // end the thread
382 }
383
384 waitTimeNs = kWaitTimeBeforeCloseNs;
385 while (!mQuit && !mRestartStreams.empty()) {
386 const nsecs_t nowNs = systemTime();
387 auto it = mRestartStreams.begin();
388 Stream* const stream = it->second;
389 const int64_t diffNs = stream->getStopTimeNs() - nowNs;
390 if (diffNs > 0) {
391 waitTimeNs = std::min(waitTimeNs, diffNs);
392 break;
393 }
394 mRestartStreams.erase(it);
395 mProcessingStreams.emplace(stream);
Andy Hung43da3d52021-03-15 11:31:45 -0700396 if (!mLockStreamManagerStop) lock.unlock();
Andy Hunge7937b92019-08-28 21:02:23 -0700397 stream->stop();
398 ALOGV("%s(%d) stopping streamID:%d", __func__, id, stream->getStreamID());
Andy Hung4474c3f2021-11-29 09:53:39 -0800399 if (Stream* nextStream = stream->playPairStream(garbage)) {
Andy Hunge7937b92019-08-28 21:02:23 -0700400 ALOGV("%s(%d) starting streamID:%d", __func__, id, nextStream->getStreamID());
Andy Hung43da3d52021-03-15 11:31:45 -0700401 if (!mLockStreamManagerStop) lock.lock();
Andy Hunge7937b92019-08-28 21:02:23 -0700402 if (nextStream->getStopTimeNs() > 0) {
403 // the next stream was stopped before we can move it to the active queue.
404 ALOGV("%s(%d) stopping started streamID:%d",
405 __func__, id, nextStream->getStreamID());
406 moveToRestartQueue_l(nextStream);
407 } else {
408 addToActiveQueue_l(nextStream);
409 }
410 } else {
Andy Hung43da3d52021-03-15 11:31:45 -0700411 if (!mLockStreamManagerStop) lock.lock();
Andy Hunge7937b92019-08-28 21:02:23 -0700412 mAvailableStreams.insert(stream);
413 }
414 mProcessingStreams.erase(stream);
415 sanityCheckQueue_l();
Andy Hung4474c3f2021-11-29 09:53:39 -0800416 if (!garbage.empty()) {
417 lock.unlock();
418 // garbage audio tracks (etc) are cleared here outside mStreamManagerLock.
419 garbage.clear();
420 lock.lock();
421 }
Andy Hunge7937b92019-08-28 21:02:23 -0700422 }
423 }
424 ALOGV("%s(%d) exiting", __func__, id);
425}
426
427void StreamManager::dump() const
428{
429 forEach([](const Stream *stream) { stream->dump(); });
430}
431
432void StreamManager::sanityCheckQueue_l() const
433{
434 // We want to preserve the invariant that each stream pair is exactly on one of the queues.
435 const size_t availableStreams = mAvailableStreams.size();
436 const size_t restartStreams = mRestartStreams.size();
437 const size_t activeStreams = mActiveStreams.size();
438 const size_t processingStreams = mProcessingStreams.size();
439 const size_t managedStreams = availableStreams + restartStreams + activeStreams
440 + processingStreams;
441 const size_t totalStreams = getStreamMapSize() >> 1;
442 LOG_ALWAYS_FATAL_IF(managedStreams != totalStreams,
443 "%s: mAvailableStreams:%zu + mRestartStreams:%zu + "
444 "mActiveStreams:%zu + mProcessingStreams:%zu = %zu != total streams %zu",
445 __func__, availableStreams, restartStreams, activeStreams, processingStreams,
446 managedStreams, totalStreams);
447 ALOGV("%s: mAvailableStreams:%zu + mRestartStreams:%zu + "
448 "mActiveStreams:%zu + mProcessingStreams:%zu = %zu (total streams: %zu)",
449 __func__, availableStreams, restartStreams, activeStreams, processingStreams,
450 managedStreams, totalStreams);
451}
452
453} // namespace android::soundpool