1 /*
2  * Copyright (C) 2007 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"
19 #include <utils/Log.h>
20 
21 #include <algorithm>
22 #include <thread>
23 
24 #include "SoundPool.h"
25 
26 namespace android
27 {
28 
29 // kManagerThreads = 1 historically.
30 // Not really necessary to have more than one, but it does speed things up by about
31 // 25% having 2 threads instead of 1 when playing many sounds.  Having many threads
32 // could starve other AudioFlinger clients with SoundPool activity. It may also cause
33 // issues with app loading, e.g. Camera.
34 static const size_t kStreamManagerThreads = std::thread::hardware_concurrency() >= 4 ? 2 : 1;
35 
36 // kUseApiLock = true prior to R.
37 // Set to true to prevent multiple users access internal to the SoundPool API.
38 // Set to false to make the SoundPool methods weakly consistent.  When set to false,
39 // only AutoPause and AutoResume are locked, which are the only two methods that
40 // require API level locking for consistency.
41 static constexpr bool kUseApiLock = false;
42 
43 namespace {
44 // Check input arguments to SoundPool - return "true" to reject request.
45 
checkVolume(float * leftVolume,float * rightVolume)46 bool checkVolume(float *leftVolume, float *rightVolume)
47 {
48     if (*leftVolume != std::clamp(*leftVolume, 0.f, 1.f) ||
49             *rightVolume != std::clamp(*rightVolume, 0.f, 1.f)) {
50         ALOGI("volume l=%f r=%f out of (0.f, 1.f) bounds, using 1.f", *leftVolume, *rightVolume);
51         // for backward compatibility use 1.f.
52         *leftVolume = *rightVolume = 1.f;
53     }
54     return false;
55 }
56 
checkRate(float * rate)57 bool checkRate(float *rate)
58 {
59     if (*rate != std::clamp(*rate, 0.125f, 8.f)) {
60         ALOGI("rate %f out of (0.125f, 8.f) bounds, clamping", *rate);
61         // for backward compatibility just clamp
62         *rate = std::clamp(*rate, 0.125f, 8.f);
63     }
64     return false;
65 }
66 
checkPriority(int32_t * priority)67 bool checkPriority(int32_t *priority)
68 {
69     if (*priority < 0) {
70         ALOGI("negative priority %d, should be >= 0.", *priority);
71         // for backward compatibility, ignore.
72     }
73     return false;
74 }
75 
checkLoop(int32_t * loop)76 bool checkLoop(int32_t *loop)
77 {
78     if (*loop < -1) {
79         ALOGI("loop %d, should be >= -1", *loop);
80         *loop = -1;
81     }
82     return false;
83 }
84 
85 } // namespace
86 
SoundPool(int32_t maxStreams,const audio_attributes_t * attributes,const std::string & opPackageName)87 SoundPool::SoundPool(
88         int32_t maxStreams, const audio_attributes_t* attributes, const std::string& opPackageName)
89     : mStreamManager(maxStreams, kStreamManagerThreads, attributes, opPackageName)
90 {
91     ALOGV("%s(maxStreams=%d, attr={ content_type=%d, usage=%d, flags=0x%x, tags=%s })",
92             __func__, maxStreams,
93             attributes->content_type, attributes->usage, attributes->flags, attributes->tags);
94 }
95 
~SoundPool()96 SoundPool::~SoundPool()
97 {
98     ALOGV("%s()", __func__);
99 }
100 
load(int fd,int64_t offset,int64_t length,int32_t priority)101 int32_t SoundPool::load(int fd, int64_t offset, int64_t length, int32_t priority)
102 {
103     ALOGV("%s(fd=%d, offset=%lld, length=%lld, priority=%d)",
104             __func__, fd, (long long)offset, (long long)length, priority);
105     auto apiLock = kUseApiLock ? std::make_unique<std::lock_guard<std::mutex>>(mApiLock) : nullptr;
106     return mSoundManager.load(fd, offset, length, priority);
107 }
108 
unload(int32_t soundID)109 bool SoundPool::unload(int32_t soundID)
110 {
111     ALOGV("%s(%d)", __func__, soundID);
112     auto apiLock = kUseApiLock ? std::make_unique<std::lock_guard<std::mutex>>(mApiLock) : nullptr;
113     return mSoundManager.unload(soundID);
114 }
115 
play(int32_t soundID,float leftVolume,float rightVolume,int32_t priority,int32_t loop,float rate)116 int32_t SoundPool::play(int32_t soundID, float leftVolume, float rightVolume,
117         int32_t priority, int32_t loop, float rate)
118 {
119     ALOGV("%s(soundID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f)",
120             __func__, soundID, leftVolume, rightVolume, priority, loop, rate);
121 
122     // New for R: check arguments to ensure track can be created.
123     // If SoundPool defers the creation of the AudioTrack to the StreamManager thread,
124     // the failure to create may not be visible to the caller, so this precheck is needed.
125     if (checkVolume(&leftVolume, &rightVolume)
126             || checkPriority(&priority)
127             || checkLoop(&loop)
128             || checkRate(&rate)) return 0;
129 
130     auto apiLock = kUseApiLock ? std::make_unique<std::lock_guard<std::mutex>>(mApiLock) : nullptr;
131     const std::shared_ptr<soundpool::Sound> sound = mSoundManager.findSound(soundID);
132     if (sound == nullptr || sound->getState() != soundpool::Sound::READY) {
133         ALOGW("%s soundID %d not READY", __func__, soundID);
134         return 0;
135     }
136 
137     const int32_t streamID = mStreamManager.queueForPlay(
138             sound, soundID, leftVolume, rightVolume, priority, loop, rate);
139     ALOGV("%s returned %d", __func__, streamID);
140     return streamID;
141 }
142 
autoPause()143 void SoundPool::autoPause()
144 {
145     ALOGV("%s()", __func__);
146     auto apiLock = std::make_unique<std::lock_guard<std::mutex>>(mApiLock);
147     mStreamManager.forEach([](soundpool::Stream *stream) { stream->autoPause(); });
148 }
149 
autoResume()150 void SoundPool::autoResume()
151 {
152     ALOGV("%s()", __func__);
153     auto apiLock = std::make_unique<std::lock_guard<std::mutex>>(mApiLock);
154     mStreamManager.forEach([](soundpool::Stream *stream) { stream->autoResume(); });
155 }
156 
mute(bool muting)157 void SoundPool::mute(bool muting)
158 {
159     ALOGV("%s(%d)", __func__, muting);
160     auto apiLock = std::make_unique<std::lock_guard<std::mutex>>(mApiLock);
161     mStreamManager.forEach([=](soundpool::Stream *stream) { stream->mute(muting); });
162 }
163 
pause(int32_t streamID)164 void SoundPool::pause(int32_t streamID)
165 {
166     ALOGV("%s(%d)", __func__, streamID);
167     auto apiLock = kUseApiLock ? std::make_unique<std::lock_guard<std::mutex>>(mApiLock) : nullptr;
168     if (soundpool::Stream* stream = mStreamManager.findStream(streamID)) {
169         stream->pause(streamID);
170     }
171 }
172 
resume(int32_t streamID)173 void SoundPool::resume(int32_t streamID)
174 {
175     ALOGV("%s(%d)", __func__, streamID);
176     auto apiLock = kUseApiLock ? std::make_unique<std::lock_guard<std::mutex>>(mApiLock) : nullptr;
177     if (soundpool::Stream* stream = mStreamManager.findStream(streamID)) {
178         stream->resume(streamID);
179     }
180 }
181 
stop(int32_t streamID)182 void SoundPool::stop(int32_t streamID)
183 {
184     ALOGV("%s(%d)", __func__, streamID);
185     auto apiLock = kUseApiLock ? std::make_unique<std::lock_guard<std::mutex>>(mApiLock) : nullptr;
186     soundpool::Stream* stream = mStreamManager.findStream(streamID);
187     if (stream != nullptr && stream->requestStop(streamID)) {
188         mStreamManager.moveToRestartQueue(stream);
189     }
190 }
191 
setVolume(int32_t streamID,float leftVolume,float rightVolume)192 void SoundPool::setVolume(int32_t streamID, float leftVolume, float rightVolume)
193 {
194     ALOGV("%s(%d, %f %f)", __func__, streamID, leftVolume, rightVolume);
195     if (checkVolume(&leftVolume, &rightVolume)) return;
196     auto apiLock = kUseApiLock ? std::make_unique<std::lock_guard<std::mutex>>(mApiLock) : nullptr;
197     if (soundpool::Stream* stream = mStreamManager.findStream(streamID)) {
198         stream->setVolume(streamID, leftVolume, rightVolume);
199     }
200 }
201 
setPriority(int32_t streamID,int32_t priority)202 void SoundPool::setPriority(int32_t streamID, int32_t priority)
203 {
204     ALOGV("%s(%d, %d)", __func__, streamID, priority);
205     if (checkPriority(&priority)) return;
206     auto apiLock = kUseApiLock ? std::make_unique<std::lock_guard<std::mutex>>(mApiLock) : nullptr;
207     if (soundpool::Stream* stream = mStreamManager.findStream(streamID)) {
208         stream->setPriority(streamID, priority);
209     }
210 }
211 
setLoop(int32_t streamID,int32_t loop)212 void SoundPool::setLoop(int32_t streamID, int32_t loop)
213 {
214     ALOGV("%s(%d, %d)", __func__, streamID, loop);
215     if (checkLoop(&loop)) return;
216     auto apiLock = kUseApiLock ? std::make_unique<std::lock_guard<std::mutex>>(mApiLock) : nullptr;
217     if (soundpool::Stream* stream = mStreamManager.findStream(streamID)) {
218         stream->setLoop(streamID, loop);
219     }
220 }
221 
setRate(int32_t streamID,float rate)222 void SoundPool::setRate(int32_t streamID, float rate)
223 {
224     ALOGV("%s(%d, %f)", __func__, streamID, rate);
225     if (checkRate(&rate)) return;
226     auto apiLock = kUseApiLock ? std::make_unique<std::lock_guard<std::mutex>>(mApiLock) : nullptr;
227     if (soundpool::Stream* stream = mStreamManager.findStream(streamID)) {
228         stream->setRate(streamID, rate);
229     }
230 }
231 
setCallback(SoundPoolCallback * callback,void * user)232 void SoundPool::setCallback(SoundPoolCallback* callback, void* user)
233 {
234     ALOGV("%s(%p, %p)", __func__, callback, user);
235     auto apiLock = kUseApiLock ? std::make_unique<std::lock_guard<std::mutex>>(mApiLock) : nullptr;
236     mSoundManager.setCallback(this, callback, user);
237 }
238 
getUserData() const239 void* SoundPool::getUserData() const
240 {
241     ALOGV("%s()", __func__);
242     auto apiLock = kUseApiLock ? std::make_unique<std::lock_guard<std::mutex>>(mApiLock) : nullptr;
243     return mSoundManager.getUserData();
244 }
245 
246 } // end namespace android
247