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