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