1 /*
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
26 namespace 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.
31 static 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.
36 static constexpr bool kStealActiveStream_OldestFirst = true;
37
38 // 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.
40 static constexpr bool kPlayOnCallingThread = false;
41
42 // Amount of time for a StreamManager thread to wait before closing.
43 static constexpr int64_t kWaitTimeBeforeCloseNs = 9 * NANOS_PER_SECOND;
44
45 // 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 //
51 static constexpr bool kForceLockStreamManagerStop = false;
52
53 ////////////
54
StreamMap(int32_t streams)55 StreamMap::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;
65 mStreamPool = std::make_unique<Stream[]>(mStreamPoolSize); // create array of streams.
66 // 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
findStream(int32_t streamID) const70 Stream* StreamMap::findStream(int32_t streamID) const
71 {
72 Stream *stream = lookupStreamFromId(streamID);
73 return stream != nullptr && stream->getStreamID() == streamID ? stream : nullptr;
74 }
75
streamPosition(const Stream * stream) const76 size_t StreamMap::streamPosition(const Stream* stream) const
77 {
78 ptrdiff_t index = stream - mStreamPool.get();
79 LOG_ALWAYS_FATAL_IF(index < 0 || (size_t)index >= mStreamPoolSize,
80 "%s: stream position out of range: %td", __func__, index);
81 return (size_t)index;
82 }
83
lookupStreamFromId(int32_t streamID) const84 Stream* StreamMap::lookupStreamFromId(int32_t streamID) const
85 {
86 return streamID > 0 ? mPerfectHash->getValue(streamID).load() : nullptr;
87 }
88
getNextIdForStream(Stream * stream) const89 int32_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
102 // 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
StreamManager(int32_t streams,size_t threads,const audio_attributes_t & attributes,std::string opPackageName)107 StreamManager::StreamManager(
108 int32_t streams, size_t threads, const audio_attributes_t& attributes,
109 std::string opPackageName)
110 : StreamMap(streams)
111 , 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; }())
115 , mOpPackageName(std::move(opPackageName))
116 , mLockStreamManagerStop(streams == 1 || kForceLockStreamManagerStop)
117 {
118 ALOGV("%s(%d, %zu, ...)", __func__, streams, threads);
__anon2eef97d60302(Stream *stream) 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>(
127 std::min((size_t)streams, // do not make more threads than streams to play
128 std::min(threads, (size_t)std::thread::hardware_concurrency())),
129 "SoundPool_",
130 ANDROID_PRIORITY_AUDIO);
131 }
132
133 #pragma clang diagnostic pop
134
~StreamManager()135 StreamManager::~StreamManager()
136 {
137 ALOGV("%s", __func__);
138 {
139 std::unique_lock lock(mStreamManagerLock);
140 mQuit = true;
141 mStreamManagerCondition.notify_all();
142 }
143 mThreadPool->quit();
144
145 // call stop on the stream pool
146 forEach([](Stream *stream) { stream->stop(); });
147
148 // This invokes the destructor on the AudioTracks -
149 // we do it here to ensure that AudioTrack callbacks will not occur
150 // afterwards.
151 forEach([](Stream *stream) { stream->clearAudioTrack(); });
152 }
153
154
queueForPlay(const std::shared_ptr<Sound> & sound,int32_t soundID,float leftVolume,float rightVolume,int32_t priority,int32_t loop,float rate,int32_t playerIId)155 int32_t StreamManager::queueForPlay(const std::shared_ptr<Sound> &sound,
156 int32_t soundID, float leftVolume, float rightVolume,
157 int32_t priority, int32_t loop, float rate, int32_t playerIId)
158 {
159 ALOGV(
160 "%s(sound=%p, soundID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f,"
161 " playerIId=%d)", __func__, sound.get(), soundID, leftVolume, rightVolume, priority,
162 loop, rate, playerIId);
163
164 bool launchThread = false;
165 int32_t streamID = 0;
166 std::vector<std::any> garbage;
167
168 { // for lock
169 std::unique_lock lock(mStreamManagerLock);
170 Stream *newStream = nullptr;
171 bool fromAvailableQueue = false;
172 ALOGV("%s: mStreamManagerLock lock acquired", __func__);
173
174 sanityCheckQueue_l();
175 // find an available stream, prefer one that has matching sound id.
176 if (mAvailableStreams.size() > 0) {
177 for (auto stream : mAvailableStreams) {
178 if (stream->getSoundID() == soundID) {
179 newStream = stream;
180 ALOGV("%s: found soundID %d in available queue", __func__, soundID);
181 break;
182 }
183 }
184 if (newStream == nullptr) {
185 ALOGV("%s: found stream in available queue", __func__);
186 newStream = *mAvailableStreams.begin();
187 }
188 newStream->setStopTimeNs(systemTime());
189 fromAvailableQueue = true;
190 }
191
192 // also look in the streams restarting (if the paired stream doesn't have a pending play)
193 if (newStream == nullptr || newStream->getSoundID() != soundID) {
194 for (auto [unused , stream] : mRestartStreams) {
195 if (!stream->getPairStream()->hasSound()) {
196 if (stream->getSoundID() == soundID) {
197 ALOGV("%s: found soundID %d in restart queue", __func__, soundID);
198 newStream = stream;
199 fromAvailableQueue = false;
200 break;
201 } else if (newStream == nullptr) {
202 ALOGV("%s: found stream in restart queue", __func__);
203 newStream = stream;
204 }
205 }
206 }
207 }
208
209 // no available streams, look for one to steal from the active list
210 if (newStream == nullptr) {
211 for (auto stream : mActiveStreams) {
212 if (stream->getPriority() <= priority) {
213 if (newStream == nullptr
214 || newStream->getPriority() > stream->getPriority()) {
215 newStream = stream;
216 ALOGV("%s: found stream in active queue", __func__);
217 }
218 }
219 }
220 if (newStream != nullptr) { // we need to mute as it is still playing.
221 (void)newStream->requestStop(newStream->getStreamID());
222 }
223 }
224
225 // none found, look for a stream that is restarting, evict one.
226 if (newStream == nullptr) {
227 for (auto [unused, stream] : mRestartStreams) {
228 if (stream->getPairPriority() <= priority) {
229 ALOGV("%s: evict stream from restart queue", __func__);
230 newStream = stream;
231 break;
232 }
233 }
234 }
235
236 // DO NOT LOOK into mProcessingStreams as those are held by the StreamManager threads.
237
238 if (newStream == nullptr) {
239 ALOGD("%s: unable to find stream, returning 0", __func__);
240 return 0; // unable to find available stream
241 }
242
243 Stream *pairStream = newStream->getPairStream();
244 streamID = getNextIdForStream(pairStream);
245 ALOGV("%s: newStream:%p pairStream:%p, streamID:%d",
246 __func__, newStream, pairStream, streamID);
247 pairStream->setPlay(
248 streamID, sound, soundID, leftVolume, rightVolume, priority, loop, rate);
249 if (fromAvailableQueue && kPlayOnCallingThread) {
250 removeFromQueues_l(newStream);
251 mProcessingStreams.emplace(newStream);
252 lock.unlock();
253 if (Stream* nextStream = newStream->playPairStream(garbage, playerIId)) {
254 lock.lock();
255 ALOGV("%s: starting streamID:%d", __func__, nextStream->getStreamID());
256 addToActiveQueue_l(nextStream);
257 } else {
258 lock.lock();
259 mAvailableStreams.insert(newStream);
260 streamID = 0;
261 }
262 mProcessingStreams.erase(newStream);
263 } else {
264 launchThread = moveToRestartQueue_l(newStream) && needMoreThreads_l();
265 }
266 sanityCheckQueue_l();
267 ALOGV("%s: mStreamManagerLock released", __func__);
268 } // lock
269
270 if (launchThread) {
271 const int32_t id = mThreadPool->launch([this](int32_t id) { run(id); });
272 (void)id; // avoid clang warning -Wunused-variable -Wused-but-marked-unused
273 ALOGV_IF(id != 0, "%s: launched thread %d", __func__, id);
274 }
275 ALOGV("%s: returning %d", __func__, streamID);
276 // garbage is cleared here outside mStreamManagerLock.
277 return streamID;
278 }
279
moveToRestartQueue(Stream * stream,int32_t activeStreamIDToMatch)280 void StreamManager::moveToRestartQueue(
281 Stream* stream, int32_t activeStreamIDToMatch)
282 {
283 ALOGV("%s(stream(ID)=%d, activeStreamIDToMatch=%d)",
284 __func__, stream->getStreamID(), activeStreamIDToMatch);
285 bool restart;
286 {
287 std::lock_guard lock(mStreamManagerLock);
288 sanityCheckQueue_l();
289 if (mProcessingStreams.count(stream) > 0 ||
290 mProcessingStreams.count(stream->getPairStream()) > 0) {
291 ALOGD("%s: attempting to restart processing stream(%d)",
292 __func__, stream->getStreamID());
293 restart = false;
294 } else {
295 moveToRestartQueue_l(stream, activeStreamIDToMatch);
296 restart = needMoreThreads_l();
297 }
298 sanityCheckQueue_l();
299 }
300 if (restart) {
301 const int32_t id = mThreadPool->launch([this](int32_t id) { run(id); });
302 (void)id; // avoid clang warning -Wunused-variable -Wused-but-marked-unused
303 ALOGV_IF(id != 0, "%s: launched thread %d", __func__, id);
304 }
305 }
306
moveToRestartQueue_l(Stream * stream,int32_t activeStreamIDToMatch)307 bool StreamManager::moveToRestartQueue_l(
308 Stream* stream, int32_t activeStreamIDToMatch)
309 {
310 ALOGV("%s(stream(ID)=%d, activeStreamIDToMatch=%d)",
311 __func__, stream->getStreamID(), activeStreamIDToMatch);
312 if (activeStreamIDToMatch > 0 && stream->getStreamID() != activeStreamIDToMatch) {
313 return false;
314 }
315 const ssize_t found = removeFromQueues_l(stream, activeStreamIDToMatch);
316 if (found < 0) return false;
317
318 LOG_ALWAYS_FATAL_IF(found > 1, "stream on %zd > 1 stream lists", found);
319
320 addToRestartQueue_l(stream);
321 mStreamManagerCondition.notify_one();
322 return true;
323 }
324
removeFromQueues_l(Stream * stream,int32_t activeStreamIDToMatch)325 ssize_t StreamManager::removeFromQueues_l(
326 Stream* stream, int32_t activeStreamIDToMatch) {
327 size_t found = 0;
328 for (auto it = mActiveStreams.begin(); it != mActiveStreams.end(); ++it) {
329 if (*it == stream) {
330 mActiveStreams.erase(it); // we erase the iterator and break (otherwise it not safe).
331 ++found;
332 break;
333 }
334 }
335 // activeStreamIDToMatch is nonzero indicates we proceed only if found.
336 if (found == 0 && activeStreamIDToMatch > 0) {
337 return -1; // special code: not present on active streams, ignore restart request
338 }
339
340 for (auto it = mRestartStreams.begin(); it != mRestartStreams.end(); ++it) {
341 if (it->second == stream) {
342 mRestartStreams.erase(it);
343 ++found;
344 break;
345 }
346 }
347 found += mAvailableStreams.erase(stream);
348
349 // streams on mProcessingStreams are undergoing processing by the StreamManager thread
350 // and do not participate in normal stream migration.
351 return (ssize_t)found;
352 }
353
addToRestartQueue_l(Stream * stream)354 void StreamManager::addToRestartQueue_l(Stream *stream) {
355 mRestartStreams.emplace(stream->getStopTimeNs(), stream);
356 }
357
addToActiveQueue_l(Stream * stream)358 void StreamManager::addToActiveQueue_l(Stream *stream) {
359 if (kStealActiveStream_OldestFirst) {
360 mActiveStreams.push_back(stream); // oldest to newest
361 } else {
362 mActiveStreams.push_front(stream); // newest to oldest
363 }
364 }
365
run(int32_t id)366 void StreamManager::run(int32_t id)
367 {
368 ALOGV("%s(%d) entering", __func__, id);
369 int64_t waitTimeNs = 0; // on thread start, mRestartStreams can be non-empty.
370 std::vector<std::any> garbage; // used for garbage collection
371 std::unique_lock lock(mStreamManagerLock);
372 while (!mQuit) {
373 if (waitTimeNs > 0) {
374 mStreamManagerCondition.wait_for(
375 lock, std::chrono::duration<int64_t, std::nano>(waitTimeNs));
376 }
377 ALOGV("%s(%d) awake lock waitTimeNs:%lld", __func__, id, (long long)waitTimeNs);
378
379 sanityCheckQueue_l();
380
381 if (mQuit || (mRestartStreams.empty() && waitTimeNs == kWaitTimeBeforeCloseNs)) {
382 break; // end the thread
383 }
384
385 waitTimeNs = kWaitTimeBeforeCloseNs;
386 while (!mQuit && !mRestartStreams.empty()) {
387 const nsecs_t nowNs = systemTime();
388 auto it = mRestartStreams.begin();
389 Stream* const stream = it->second;
390 const int64_t diffNs = stream->getStopTimeNs() - nowNs;
391 if (diffNs > 0) {
392 waitTimeNs = std::min(waitTimeNs, diffNs);
393 break;
394 }
395 mRestartStreams.erase(it);
396 mProcessingStreams.emplace(stream);
397 if (!mLockStreamManagerStop) lock.unlock();
398 stream->stop();
399 ALOGV("%s(%d) stopping streamID:%d", __func__, id, stream->getStreamID());
400 if (Stream* nextStream = stream->playPairStream(garbage)) {
401 ALOGV("%s(%d) starting streamID:%d", __func__, id, nextStream->getStreamID());
402 if (!mLockStreamManagerStop) lock.lock();
403 if (nextStream->getStopTimeNs() > 0) {
404 // the next stream was stopped before we can move it to the active queue.
405 ALOGV("%s(%d) stopping started streamID:%d",
406 __func__, id, nextStream->getStreamID());
407 moveToRestartQueue_l(nextStream);
408 } else {
409 addToActiveQueue_l(nextStream);
410 }
411 } else {
412 if (!mLockStreamManagerStop) lock.lock();
413 mAvailableStreams.insert(stream);
414 }
415 mProcessingStreams.erase(stream);
416 sanityCheckQueue_l();
417 if (!garbage.empty()) {
418 lock.unlock();
419 // garbage audio tracks (etc) are cleared here outside mStreamManagerLock.
420 garbage.clear();
421 lock.lock();
422 }
423 }
424 }
425 ALOGV("%s(%d) exiting", __func__, id);
426 }
427
dump() const428 void StreamManager::dump() const
429 {
430 forEach([](const Stream *stream) { stream->dump(); });
431 }
432
sanityCheckQueue_l() const433 void StreamManager::sanityCheckQueue_l() const
434 {
435 // We want to preserve the invariant that each stream pair is exactly on one of the queues.
436 const size_t availableStreams = mAvailableStreams.size();
437 const size_t restartStreams = mRestartStreams.size();
438 const size_t activeStreams = mActiveStreams.size();
439 const size_t processingStreams = mProcessingStreams.size();
440 const size_t managedStreams = availableStreams + restartStreams + activeStreams
441 + processingStreams;
442 const size_t totalStreams = getStreamMapSize() >> 1;
443 LOG_ALWAYS_FATAL_IF(managedStreams != totalStreams,
444 "%s: mAvailableStreams:%zu + mRestartStreams:%zu + "
445 "mActiveStreams:%zu + mProcessingStreams:%zu = %zu != total streams %zu",
446 __func__, availableStreams, restartStreams, activeStreams, processingStreams,
447 managedStreams, totalStreams);
448 ALOGV("%s: mAvailableStreams:%zu + mRestartStreams:%zu + "
449 "mActiveStreams:%zu + mProcessingStreams:%zu = %zu (total streams: %zu)",
450 __func__, availableStreams, restartStreams, activeStreams, processingStreams,
451 managedStreams, totalStreams);
452 }
453
454 } // namespace android::soundpool
455