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 ////////////
47 
StreamMap(int32_t streams)48 StreamMap::StreamMap(int32_t streams) {
49     ALOGV("%s(%d)", __func__, streams);
50     if (streams > kMaxStreams) {
51         ALOGW("%s: requested %d streams, clamping to %d", __func__, streams, kMaxStreams);
52         streams = kMaxStreams;
53     } else if (streams < 1) {
54         ALOGW("%s: requested %d streams, clamping to 1", __func__, streams);
55         streams = 1;
56     }
57     mStreamPoolSize = streams * 2;
58     mStreamPool = std::make_unique<Stream[]>(mStreamPoolSize); // create array of streams.
59     // we use a perfect hash table with 2x size to map StreamIDs to Stream pointers.
60     mPerfectHash = std::make_unique<PerfectHash<int32_t, Stream *>>(roundup(mStreamPoolSize * 2));
61 }
62 
findStream(int32_t streamID) const63 Stream* StreamMap::findStream(int32_t streamID) const
64 {
65     Stream *stream = lookupStreamFromId(streamID);
66     return stream != nullptr && stream->getStreamID() == streamID ? stream : nullptr;
67 }
68 
streamPosition(const Stream * stream) const69 size_t StreamMap::streamPosition(const Stream* stream) const
70 {
71     ptrdiff_t index = stream - mStreamPool.get();
72     LOG_ALWAYS_FATAL_IF(index < 0 || (size_t)index >= mStreamPoolSize,
73             "%s: stream position out of range: %td", __func__, index);
74     return (size_t)index;
75 }
76 
lookupStreamFromId(int32_t streamID) const77 Stream* StreamMap::lookupStreamFromId(int32_t streamID) const
78 {
79     return streamID > 0 ? mPerfectHash->getValue(streamID).load() : nullptr;
80 }
81 
getNextIdForStream(Stream * stream) const82 int32_t StreamMap::getNextIdForStream(Stream* stream) const {
83     // even though it is const, it mutates the internal hash table.
84     const int32_t id = mPerfectHash->generateKey(
85         stream,
86         [] (Stream *stream) {
87             return stream == nullptr ? 0 : stream->getStreamID();
88         }, /* getKforV() */
89         stream->getStreamID() /* oldID */);
90     return id;
91 }
92 
93 ////////////
94 
95 // Thread safety analysis is supposed to be disabled for constructors and destructors
96 // but clang in R seems to have a bug.  We use pragma to disable.
97 #pragma clang diagnostic push
98 #pragma clang diagnostic ignored "-Wthread-safety-analysis"
99 
StreamManager(int32_t streams,size_t threads,const audio_attributes_t * attributes)100 StreamManager::StreamManager(
101         int32_t streams, size_t threads, const audio_attributes_t* attributes)
102     : StreamMap(streams)
103     , mAttributes(*attributes)
104 {
105     ALOGV("%s(%d, %zu, ...)", __func__, streams, threads);
106     forEach([this](Stream *stream) {
107         stream->setStreamManager(this);
108         if ((streamPosition(stream) & 1) == 0) { // put the first stream of pair as available.
109             mAvailableStreams.insert(stream);
110         }
111     });
112 
113     mThreadPool = std::make_unique<ThreadPool>(
114             std::min(threads, (size_t)std::thread::hardware_concurrency()),
115             "SoundPool_");
116 }
117 
118 #pragma clang diagnostic pop
119 
~StreamManager()120 StreamManager::~StreamManager()
121 {
122     ALOGV("%s", __func__);
123     {
124         std::unique_lock lock(mStreamManagerLock);
125         mQuit = true;
126         mStreamManagerCondition.notify_all();
127     }
128     mThreadPool->quit();
129 
130     // call stop on the stream pool
131     forEach([](Stream *stream) { stream->stop(); });
132 
133     // This invokes the destructor on the AudioTracks -
134     // we do it here to ensure that AudioTrack callbacks will not occur
135     // afterwards.
136     forEach([](Stream *stream) { stream->clearAudioTrack(); });
137 }
138 
139 
queueForPlay(const std::shared_ptr<Sound> & sound,int32_t soundID,float leftVolume,float rightVolume,int32_t priority,int32_t loop,float rate)140 int32_t StreamManager::queueForPlay(const std::shared_ptr<Sound> &sound,
141         int32_t soundID, float leftVolume, float rightVolume,
142         int32_t priority, int32_t loop, float rate)
143 {
144     ALOGV("%s(sound=%p, soundID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f)",
145             __func__, sound.get(), soundID, leftVolume, rightVolume, priority, loop, rate);
146     bool launchThread = false;
147     int32_t streamID = 0;
148 
149     { // for lock
150         std::unique_lock lock(mStreamManagerLock);
151         Stream *newStream = nullptr;
152         bool fromAvailableQueue = false;
153         ALOGV("%s: mStreamManagerLock lock acquired", __func__);
154 
155         sanityCheckQueue_l();
156         // find an available stream, prefer one that has matching sound id.
157         if (mAvailableStreams.size() > 0) {
158             for (auto stream : mAvailableStreams) {
159                 if (stream->getSoundID() == soundID) {
160                     newStream = stream;
161                     ALOGV("%s: found soundID %d in available queue", __func__, soundID);
162                     break;
163                 }
164             }
165             if (newStream == nullptr) {
166                 ALOGV("%s: found stream in available queue", __func__);
167                 newStream = *mAvailableStreams.begin();
168             }
169             newStream->setStopTimeNs(systemTime());
170             fromAvailableQueue = true;
171         }
172 
173         // also look in the streams restarting (if the paired stream doesn't have a pending play)
174         if (newStream == nullptr || newStream->getSoundID() != soundID) {
175             for (auto [unused , stream] : mRestartStreams) {
176                 if (!stream->getPairStream()->hasSound()) {
177                     if (stream->getSoundID() == soundID) {
178                         ALOGV("%s: found soundID %d in restart queue", __func__, soundID);
179                         newStream = stream;
180                         fromAvailableQueue = false;
181                         break;
182                     } else if (newStream == nullptr) {
183                         ALOGV("%s: found stream in restart queue", __func__);
184                         newStream = stream;
185                     }
186                 }
187             }
188         }
189 
190         // no available streams, look for one to steal from the active list
191         if (newStream == nullptr) {
192             for (auto stream : mActiveStreams) {
193                 if (stream->getPriority() <= priority) {
194                     if (newStream == nullptr
195                             || newStream->getPriority() > stream->getPriority()) {
196                         newStream = stream;
197                         ALOGV("%s: found stream in active queue", __func__);
198                     }
199                 }
200             }
201             if (newStream != nullptr) { // we need to mute as it is still playing.
202                 (void)newStream->requestStop(newStream->getStreamID());
203             }
204         }
205 
206         // none found, look for a stream that is restarting, evict one.
207         if (newStream == nullptr) {
208             for (auto [unused, stream] : mRestartStreams) {
209                 if (stream->getPairPriority() <= priority) {
210                     ALOGV("%s: evict stream from restart queue", __func__);
211                     newStream = stream;
212                     break;
213                 }
214             }
215         }
216 
217         // DO NOT LOOK into mProcessingStreams as those are held by the StreamManager threads.
218 
219         if (newStream == nullptr) {
220             ALOGD("%s: unable to find stream, returning 0", __func__);
221             return 0; // unable to find available stream
222         }
223 
224         Stream *pairStream = newStream->getPairStream();
225         streamID = getNextIdForStream(pairStream);
226         ALOGV("%s: newStream:%p  pairStream:%p, streamID:%d",
227                 __func__, newStream, pairStream, streamID);
228         pairStream->setPlay(
229                 streamID, sound, soundID, leftVolume, rightVolume, priority, loop, rate);
230         if (fromAvailableQueue && kPlayOnCallingThread) {
231             removeFromQueues_l(newStream);
232             mProcessingStreams.emplace(newStream);
233             lock.unlock();
234             if (Stream* nextStream = newStream->playPairStream()) {
235                 lock.lock();
236                 ALOGV("%s: starting streamID:%d", __func__, nextStream->getStreamID());
237                 addToActiveQueue_l(nextStream);
238             } else {
239                 lock.lock();
240                 mAvailableStreams.insert(newStream);
241                 streamID = 0;
242             }
243             mProcessingStreams.erase(newStream);
244         } else {
245             launchThread = moveToRestartQueue_l(newStream) && needMoreThreads_l();
246         }
247         sanityCheckQueue_l();
248         ALOGV("%s: mStreamManagerLock released", __func__);
249     } // lock
250 
251     if (launchThread) {
252         const int32_t id = mThreadPool->launch([this](int32_t id) { run(id); });
253         (void)id; // avoid clang warning -Wunused-variable -Wused-but-marked-unused
254         ALOGV_IF(id != 0, "%s: launched thread %d", __func__, id);
255     }
256     ALOGV("%s: returning %d", __func__, streamID);
257     return streamID;
258 }
259 
moveToRestartQueue(Stream * stream,int32_t activeStreamIDToMatch)260 void StreamManager::moveToRestartQueue(
261         Stream* stream, int32_t activeStreamIDToMatch)
262 {
263     ALOGV("%s(stream(ID)=%d, activeStreamIDToMatch=%d)",
264             __func__, stream->getStreamID(), activeStreamIDToMatch);
265     bool restart;
266     {
267         std::lock_guard lock(mStreamManagerLock);
268         sanityCheckQueue_l();
269         if (mProcessingStreams.count(stream) > 0 ||
270                 mProcessingStreams.count(stream->getPairStream()) > 0) {
271             ALOGD("%s: attempting to restart processing stream(%d)",
272                     __func__, stream->getStreamID());
273             restart = false;
274         } else {
275             moveToRestartQueue_l(stream, activeStreamIDToMatch);
276             restart = needMoreThreads_l();
277         }
278         sanityCheckQueue_l();
279     }
280     if (restart) {
281         const int32_t id = mThreadPool->launch([this](int32_t id) { run(id); });
282         (void)id; // avoid clang warning -Wunused-variable -Wused-but-marked-unused
283         ALOGV_IF(id != 0, "%s: launched thread %d", __func__, id);
284     }
285 }
286 
moveToRestartQueue_l(Stream * stream,int32_t activeStreamIDToMatch)287 bool StreamManager::moveToRestartQueue_l(
288         Stream* stream, int32_t activeStreamIDToMatch)
289 {
290     ALOGV("%s(stream(ID)=%d, activeStreamIDToMatch=%d)",
291             __func__, stream->getStreamID(), activeStreamIDToMatch);
292     if (activeStreamIDToMatch > 0 && stream->getStreamID() != activeStreamIDToMatch) {
293         return false;
294     }
295     const ssize_t found = removeFromQueues_l(stream, activeStreamIDToMatch);
296     if (found < 0) return false;
297 
298     LOG_ALWAYS_FATAL_IF(found > 1, "stream on %zd > 1 stream lists", found);
299 
300     addToRestartQueue_l(stream);
301     mStreamManagerCondition.notify_one();
302     return true;
303 }
304 
removeFromQueues_l(Stream * stream,int32_t activeStreamIDToMatch)305 ssize_t StreamManager::removeFromQueues_l(
306         Stream* stream, int32_t activeStreamIDToMatch) {
307     size_t found = 0;
308     for (auto it = mActiveStreams.begin(); it != mActiveStreams.end(); ++it) {
309         if (*it == stream) {
310             mActiveStreams.erase(it); // we erase the iterator and break (otherwise it not safe).
311             ++found;
312             break;
313         }
314     }
315     // activeStreamIDToMatch is nonzero indicates we proceed only if found.
316     if (found == 0 && activeStreamIDToMatch > 0) {
317         return -1;  // special code: not present on active streams, ignore restart request
318     }
319 
320     for (auto it = mRestartStreams.begin(); it != mRestartStreams.end(); ++it) {
321         if (it->second == stream) {
322             mRestartStreams.erase(it);
323             ++found;
324             break;
325         }
326     }
327     found += mAvailableStreams.erase(stream);
328 
329     // streams on mProcessingStreams are undergoing processing by the StreamManager thread
330     // and do not participate in normal stream migration.
331     return found;
332 }
333 
addToRestartQueue_l(Stream * stream)334 void StreamManager::addToRestartQueue_l(Stream *stream) {
335     mRestartStreams.emplace(stream->getStopTimeNs(), stream);
336 }
337 
addToActiveQueue_l(Stream * stream)338 void StreamManager::addToActiveQueue_l(Stream *stream) {
339     if (kStealActiveStream_OldestFirst) {
340         mActiveStreams.push_back(stream);  // oldest to newest
341     } else {
342         mActiveStreams.push_front(stream); // newest to oldest
343     }
344 }
345 
run(int32_t id)346 void StreamManager::run(int32_t id)
347 {
348     ALOGV("%s(%d) entering", __func__, id);
349     int64_t waitTimeNs = kWaitTimeBeforeCloseNs;
350     std::unique_lock lock(mStreamManagerLock);
351     while (!mQuit) {
352         if (mRestartStreams.empty()) { // on thread start, mRestartStreams can be non-empty.
353             mStreamManagerCondition.wait_for(
354                     lock, std::chrono::duration<int64_t, std::nano>(waitTimeNs));
355         }
356         ALOGV("%s(%d) awake", __func__, id);
357 
358         sanityCheckQueue_l();
359 
360         if (mQuit || (mRestartStreams.empty() && waitTimeNs == kWaitTimeBeforeCloseNs)) {
361             break;  // end the thread
362         }
363 
364         waitTimeNs = kWaitTimeBeforeCloseNs;
365         while (!mQuit && !mRestartStreams.empty()) {
366             const nsecs_t nowNs = systemTime();
367             auto it = mRestartStreams.begin();
368             Stream* const stream = it->second;
369             const int64_t diffNs = stream->getStopTimeNs() - nowNs;
370             if (diffNs > 0) {
371                 waitTimeNs = std::min(waitTimeNs, diffNs);
372                 break;
373             }
374             mRestartStreams.erase(it);
375             mProcessingStreams.emplace(stream);
376             lock.unlock();
377             stream->stop();
378             ALOGV("%s(%d) stopping streamID:%d", __func__, id, stream->getStreamID());
379             if (Stream* nextStream = stream->playPairStream()) {
380                 ALOGV("%s(%d) starting streamID:%d", __func__, id, nextStream->getStreamID());
381                 lock.lock();
382                 if (nextStream->getStopTimeNs() > 0) {
383                     // the next stream was stopped before we can move it to the active queue.
384                     ALOGV("%s(%d) stopping started streamID:%d",
385                             __func__, id, nextStream->getStreamID());
386                     moveToRestartQueue_l(nextStream);
387                 } else {
388                     addToActiveQueue_l(nextStream);
389                 }
390             } else {
391                 lock.lock();
392                 mAvailableStreams.insert(stream);
393             }
394             mProcessingStreams.erase(stream);
395             sanityCheckQueue_l();
396         }
397     }
398     ALOGV("%s(%d) exiting", __func__, id);
399 }
400 
dump() const401 void StreamManager::dump() const
402 {
403     forEach([](const Stream *stream) { stream->dump(); });
404 }
405 
sanityCheckQueue_l() const406 void StreamManager::sanityCheckQueue_l() const
407 {
408     // We want to preserve the invariant that each stream pair is exactly on one of the queues.
409     const size_t availableStreams = mAvailableStreams.size();
410     const size_t restartStreams = mRestartStreams.size();
411     const size_t activeStreams = mActiveStreams.size();
412     const size_t processingStreams = mProcessingStreams.size();
413     const size_t managedStreams = availableStreams + restartStreams + activeStreams
414                 + processingStreams;
415     const size_t totalStreams = getStreamMapSize() >> 1;
416     LOG_ALWAYS_FATAL_IF(managedStreams != totalStreams,
417             "%s: mAvailableStreams:%zu + mRestartStreams:%zu + "
418             "mActiveStreams:%zu + mProcessingStreams:%zu = %zu != total streams %zu",
419             __func__, availableStreams, restartStreams, activeStreams, processingStreams,
420             managedStreams, totalStreams);
421     ALOGV("%s: mAvailableStreams:%zu + mRestartStreams:%zu + "
422             "mActiveStreams:%zu + mProcessingStreams:%zu = %zu (total streams: %zu)",
423             __func__, availableStreams, restartStreams, activeStreams, processingStreams,
424             managedStreams, totalStreams);
425 }
426 
427 } // namespace android::soundpool
428