blob: 9ff4254284dc96bc3223279817cc882d88145bdc [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 Hung8823c982019-12-12 19:43:12 +000041static 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;
Andy Hung77eb2bd2020-05-19 10:42:09 -070058 mStreamPool = std::make_unique<Stream[]>(mStreamPoolSize); // create array of streams.
Andy Hunge7937b92019-08-28 21:02:23 -070059 // 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();
Andy Hung77eb2bd2020-05-19 10:42:09 -070072 LOG_ALWAYS_FATAL_IF(index < 0 || (size_t)index >= mStreamPoolSize,
Andy Hunge7937b92019-08-28 21:02:23 -070073 "%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
Andy Hung77eb2bd2020-05-19 10:42:09 -070095// 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
Andy Hunge7937b92019-08-28 21:02:23 -0700100StreamManager::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
Andy Hung77eb2bd2020-05-19 10:42:09 -0700118#pragma clang diagnostic pop
119
Andy Hunge7937b92019-08-28 21:02:23 -0700120StreamManager::~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
140int32_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) {
Andy Hunge7937b92019-08-28 21:02:23 -0700158 for (auto stream : mAvailableStreams) {
159 if (stream->getSoundID() == soundID) {
160 newStream = stream;
Andy Hung457ed3a2019-11-19 16:44:13 -0800161 ALOGV("%s: found soundID %d in available queue", __func__, soundID);
Andy Hunge7937b92019-08-28 21:02:23 -0700162 break;
163 }
164 }
Andy Hung457ed3a2019-11-19 16:44:13 -0800165 if (newStream == nullptr) {
166 ALOGV("%s: found stream in available queue", __func__);
167 newStream = *mAvailableStreams.begin();
Andy Hunge7937b92019-08-28 21:02:23 -0700168 }
Andy Hung457ed3a2019-11-19 16:44:13 -0800169 newStream->setStopTimeNs(systemTime());
Andy Hunge7937b92019-08-28 21:02:23 -0700170 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) {
Andy Hung457ed3a2019-11-19 16:44:13 -0800178 ALOGV("%s: found soundID %d in restart queue", __func__, soundID);
Andy Hunge7937b92019-08-28 21:02:23 -0700179 newStream = stream;
Andy Hung8823c982019-12-12 19:43:12 +0000180 fromAvailableQueue = false;
Andy Hunge7937b92019-08-28 21:02:23 -0700181 break;
182 } else if (newStream == nullptr) {
Andy Hung457ed3a2019-11-19 16:44:13 -0800183 ALOGV("%s: found stream in restart queue", __func__);
Andy Hunge7937b92019-08-28 21:02:23 -0700184 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;
Andy Hung457ed3a2019-11-19 16:44:13 -0800197 ALOGV("%s: found stream in active queue", __func__);
Andy Hunge7937b92019-08-28 21:02:23 -0700198 }
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) {
Andy Hung457ed3a2019-11-19 16:44:13 -0800210 ALOGV("%s: evict stream from restart queue", __func__);
Andy Hunge7937b92019-08-28 21:02:23 -0700211 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);
Andy Hung457ed3a2019-11-19 16:44:13 -0800226 ALOGV("%s: newStream:%p pairStream:%p, streamID:%d",
227 __func__, newStream, pairStream, streamID);
Andy Hunge7937b92019-08-28 21:02:23 -0700228 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 __unused = mThreadPool->launch([this](int32_t id) { run(id); });
253 ALOGV_IF(id != 0, "%s: launched thread %d", __func__, id);
254 }
255 ALOGV("%s: returning %d", __func__, streamID);
256 return streamID;
257}
258
259void StreamManager::moveToRestartQueue(
260 Stream* stream, int32_t activeStreamIDToMatch)
261{
262 ALOGV("%s(stream(ID)=%d, activeStreamIDToMatch=%d)",
263 __func__, stream->getStreamID(), activeStreamIDToMatch);
264 bool restart;
265 {
266 std::lock_guard lock(mStreamManagerLock);
267 sanityCheckQueue_l();
268 if (mProcessingStreams.count(stream) > 0 ||
269 mProcessingStreams.count(stream->getPairStream()) > 0) {
270 ALOGD("%s: attempting to restart processing stream(%d)",
271 __func__, stream->getStreamID());
272 restart = false;
273 } else {
274 moveToRestartQueue_l(stream, activeStreamIDToMatch);
275 restart = needMoreThreads_l();
276 }
277 sanityCheckQueue_l();
278 }
279 if (restart) {
280 const int32_t id __unused = mThreadPool->launch([this](int32_t id) { run(id); });
281 ALOGV_IF(id != 0, "%s: launched thread %d", __func__, id);
282 }
283}
284
285bool StreamManager::moveToRestartQueue_l(
286 Stream* stream, int32_t activeStreamIDToMatch)
287{
288 ALOGV("%s(stream(ID)=%d, activeStreamIDToMatch=%d)",
289 __func__, stream->getStreamID(), activeStreamIDToMatch);
290 if (activeStreamIDToMatch > 0 && stream->getStreamID() != activeStreamIDToMatch) {
291 return false;
292 }
293 const ssize_t found = removeFromQueues_l(stream, activeStreamIDToMatch);
294 if (found < 0) return false;
295
296 LOG_ALWAYS_FATAL_IF(found > 1, "stream on %zd > 1 stream lists", found);
297
298 addToRestartQueue_l(stream);
299 mStreamManagerCondition.notify_one();
300 return true;
301}
302
303ssize_t StreamManager::removeFromQueues_l(
304 Stream* stream, int32_t activeStreamIDToMatch) {
305 size_t found = 0;
306 for (auto it = mActiveStreams.begin(); it != mActiveStreams.end(); ++it) {
307 if (*it == stream) {
308 mActiveStreams.erase(it); // we erase the iterator and break (otherwise it not safe).
309 ++found;
310 break;
311 }
312 }
313 // activeStreamIDToMatch is nonzero indicates we proceed only if found.
314 if (found == 0 && activeStreamIDToMatch > 0) {
315 return -1; // special code: not present on active streams, ignore restart request
316 }
317
318 for (auto it = mRestartStreams.begin(); it != mRestartStreams.end(); ++it) {
319 if (it->second == stream) {
320 mRestartStreams.erase(it);
321 ++found;
322 break;
323 }
324 }
325 found += mAvailableStreams.erase(stream);
326
327 // streams on mProcessingStreams are undergoing processing by the StreamManager thread
328 // and do not participate in normal stream migration.
329 return found;
330}
331
332void StreamManager::addToRestartQueue_l(Stream *stream) {
333 mRestartStreams.emplace(stream->getStopTimeNs(), stream);
334}
335
336void StreamManager::addToActiveQueue_l(Stream *stream) {
337 if (kStealActiveStream_OldestFirst) {
338 mActiveStreams.push_back(stream); // oldest to newest
339 } else {
340 mActiveStreams.push_front(stream); // newest to oldest
341 }
342}
343
344void StreamManager::run(int32_t id)
345{
346 ALOGV("%s(%d) entering", __func__, id);
347 int64_t waitTimeNs = kWaitTimeBeforeCloseNs;
348 std::unique_lock lock(mStreamManagerLock);
349 while (!mQuit) {
Andy Hungba04dbe2020-03-19 21:32:53 -0700350 if (mRestartStreams.empty()) { // on thread start, mRestartStreams can be non-empty.
351 mStreamManagerCondition.wait_for(
352 lock, std::chrono::duration<int64_t, std::nano>(waitTimeNs));
353 }
Andy Hunge7937b92019-08-28 21:02:23 -0700354 ALOGV("%s(%d) awake", __func__, id);
355
356 sanityCheckQueue_l();
357
358 if (mQuit || (mRestartStreams.empty() && waitTimeNs == kWaitTimeBeforeCloseNs)) {
359 break; // end the thread
360 }
361
362 waitTimeNs = kWaitTimeBeforeCloseNs;
363 while (!mQuit && !mRestartStreams.empty()) {
364 const nsecs_t nowNs = systemTime();
365 auto it = mRestartStreams.begin();
366 Stream* const stream = it->second;
367 const int64_t diffNs = stream->getStopTimeNs() - nowNs;
368 if (diffNs > 0) {
369 waitTimeNs = std::min(waitTimeNs, diffNs);
370 break;
371 }
372 mRestartStreams.erase(it);
373 mProcessingStreams.emplace(stream);
374 lock.unlock();
375 stream->stop();
376 ALOGV("%s(%d) stopping streamID:%d", __func__, id, stream->getStreamID());
377 if (Stream* nextStream = stream->playPairStream()) {
378 ALOGV("%s(%d) starting streamID:%d", __func__, id, nextStream->getStreamID());
379 lock.lock();
380 if (nextStream->getStopTimeNs() > 0) {
381 // the next stream was stopped before we can move it to the active queue.
382 ALOGV("%s(%d) stopping started streamID:%d",
383 __func__, id, nextStream->getStreamID());
384 moveToRestartQueue_l(nextStream);
385 } else {
386 addToActiveQueue_l(nextStream);
387 }
388 } else {
389 lock.lock();
390 mAvailableStreams.insert(stream);
391 }
392 mProcessingStreams.erase(stream);
393 sanityCheckQueue_l();
394 }
395 }
396 ALOGV("%s(%d) exiting", __func__, id);
397}
398
399void StreamManager::dump() const
400{
401 forEach([](const Stream *stream) { stream->dump(); });
402}
403
404void StreamManager::sanityCheckQueue_l() const
405{
406 // We want to preserve the invariant that each stream pair is exactly on one of the queues.
407 const size_t availableStreams = mAvailableStreams.size();
408 const size_t restartStreams = mRestartStreams.size();
409 const size_t activeStreams = mActiveStreams.size();
410 const size_t processingStreams = mProcessingStreams.size();
411 const size_t managedStreams = availableStreams + restartStreams + activeStreams
412 + processingStreams;
413 const size_t totalStreams = getStreamMapSize() >> 1;
414 LOG_ALWAYS_FATAL_IF(managedStreams != totalStreams,
415 "%s: mAvailableStreams:%zu + mRestartStreams:%zu + "
416 "mActiveStreams:%zu + mProcessingStreams:%zu = %zu != total streams %zu",
417 __func__, availableStreams, restartStreams, activeStreams, processingStreams,
418 managedStreams, totalStreams);
419 ALOGV("%s: mAvailableStreams:%zu + mRestartStreams:%zu + "
420 "mActiveStreams:%zu + mProcessingStreams:%zu = %zu (total streams: %zu)",
421 __func__, availableStreams, restartStreams, activeStreams, processingStreams,
422 managedStreams, totalStreams);
423}
424
425} // namespace android::soundpool