1 /*
2 * Copyright (C) 2008 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 #include <stdio.h>
18
19 //#define LOG_NDEBUG 0
20 #define LOG_TAG "SoundPool-JNI"
21
22 #include <utils/Log.h>
23 #include <audio_utils/string.h>
24 #include <jni.h>
25 #include <nativehelper/JNIPlatformHelp.h>
26 #include <nativehelper/ScopedUtfChars.h>
27 #include <android_runtime/AndroidRuntime.h>
28 #include "SoundPool.h"
29
30 using namespace android;
31
32 static struct fields_t {
33 jfieldID mNativeContext;
34 jmethodID mPostEvent;
35 jclass mSoundPoolClass;
36 } fields;
37
38 namespace {
39
40 /**
41 * ObjectManager creates a native "object" on the heap and stores
42 * its pointer in a long field in a Java object.
43 *
44 * The type T must have 3 properties in the current implementation.
45 * 1) A T{} default constructor which represents a nullValue.
46 * 2) T::operator bool() const efficient detection of such a nullValue.
47 * 3) T must be copyable.
48 *
49 * Some examples of such a type T are std::shared_ptr<>, android::sp<>,
50 * std::optional, std::function<>, etc.
51 *
52 * Using set() with a nullValue T results in destroying the underlying native
53 * "object" if it exists. A nullValue T is returned by get() if there is
54 * no underlying native Object.
55 *
56 * This class is thread safe for multiple access.
57 *
58 * Design notes:
59 * 1) For objects of type T that do not naturally have an "nullValue",
60 * wrapping with
61 * a) TOpt, where TOpt = std::optional<T>
62 * b) TShared, where TShared = std::shared_ptr<T>
63 *
64 * 2) An overload for an explicit equality comparable nullValue such as
65 * get(..., const T& nullValue) or set(..., const T& nullValue)
66 * is omitted. An alternative is to pass a fixed nullValue in the constructor.
67 */
68 template <typename T>
69 class ObjectManager
70 {
71 // Can a jlong hold a pointer?
72 static_assert(sizeof(jlong) >= sizeof(void*));
73
74 public:
75 // fieldId is associated with a Java long member variable in the object.
76 // ObjectManager will store the native pointer in that field.
77 //
78 // If a native object is set() in that field, it
ObjectManager(jfieldID fieldId)79 explicit ObjectManager(jfieldID fieldId) : mFieldId(fieldId) {}
~ObjectManager()80 ~ObjectManager() {
81 ALOGE_IF(mObjectCount != 0, "%s: mObjectCount: %d should be zero on destruction",
82 __func__, mObjectCount.load());
83 // Design note: it would be possible to keep a map of the outstanding allocated
84 // objects and force a delete on them on ObjectManager destruction.
85 // The consequences of that is probably worse than keeping them alive.
86 }
87
88 // Retrieves the associated object, returns nullValue T if not available.
get(JNIEnv * env,jobject thiz)89 T get(JNIEnv *env, jobject thiz) {
90 std::lock_guard lg(mLock);
91 // NOLINTNEXTLINE(performance-no-int-to-ptr)
92 auto ptr = reinterpret_cast<T*>(env->GetLongField(thiz, mFieldId));
93 if (ptr != nullptr) {
94 return *ptr;
95 }
96 return {};
97 }
98
99 // Sets the object and returns the old one.
100 //
101 // If the old object doesn't exist, then nullValue T is returned.
102 // If the new object is false by operator bool(), the internal object is destroyed.
103 // Note: The old object is returned so if T is a smart pointer, it can be held
104 // by the caller to be deleted outside of any external lock.
105 //
106 // Remember to call set(env, thiz, {}) to destroy the object in the Java
107 // object finalize to avoid orphaned objects on the heap.
set(JNIEnv * env,jobject thiz,const T & newObject)108 T set(JNIEnv *env, jobject thiz, const T& newObject) {
109 std::lock_guard lg(mLock);
110 // NOLINTNEXTLINE(performance-no-int-to-ptr)
111 auto ptr = reinterpret_cast<T*>(env->GetLongField(thiz, mFieldId));
112 if (ptr != nullptr) {
113 T old = std::move(*ptr); // *ptr will be replaced or deleted.
114 if (newObject) {
115 env->SetLongField(thiz, mFieldId, (jlong)0);
116 delete ptr;
117 --mObjectCount;
118 } else {
119 *ptr = newObject;
120 }
121 return old;
122 } else {
123 if (newObject) {
124 env->SetLongField(thiz, mFieldId, (jlong)new T(newObject));
125 ++mObjectCount;
126 }
127 return {};
128 }
129 }
130
131 // Returns the number of outstanding objects.
132 //
133 // This is purely for debugging purposes and tracks the number of active Java
134 // objects that have native T objects; hence represents the number of
135 // T heap allocations we have made.
136 //
137 // When all those Java objects have been finalized we expect this to go to 0.
getObjectCount() const138 int32_t getObjectCount() const {
139 return mObjectCount;
140 }
141
142 private:
143 // NOLINTNEXTLINE(misc-misplaced-const)
144 const jfieldID mFieldId; // '_jfieldID *const'
145
146 // mObjectCount is the number of outstanding native T heap allocations we have
147 // made (and thus the number of active Java objects which are associated with them).
148 std::atomic_int32_t mObjectCount{};
149
150 mutable std::mutex mLock;
151 };
152
153 // We use SoundPoolManager to associate a native std::shared_ptr<SoundPool>
154 // object with a field in the Java object.
155 //
156 // We can then retrieve the std::shared_ptr<SoundPool> from the object.
157 //
158 // Design notes:
159 // 1) This is based on ObjectManager class.
160 // 2) An alternative that does not require a field in the Java object
161 // is to create an associative map using as a key a NewWeakGlobalRef
162 // to the Java object.
163 // The problem of this method is that lookup is O(N) because comparison
164 // between the WeakGlobalRef to a JNI jobject LocalRef must be done
165 // through the JNI IsSameObject() call, hence iterative through the map.
166 // One advantage of this method is that manual garbage collection
167 // is possible by checking if the WeakGlobalRef is null equivalent.
168
getSoundPoolManager()169 auto& getSoundPoolManager() {
170 static ObjectManager<std::shared_ptr<SoundPool>> soundPoolManager(fields.mNativeContext);
171 return soundPoolManager;
172 }
173
getSoundPool(JNIEnv * env,jobject thiz)174 inline auto getSoundPool(JNIEnv *env, jobject thiz) {
175 return getSoundPoolManager().get(env, thiz);
176 }
177
178 // Note: one must call setSoundPool(env, thiz, nullptr) to release any native resources
179 // somewhere in the Java object finalize().
setSoundPool(JNIEnv * env,jobject thiz,const std::shared_ptr<SoundPool> & soundPool)180 inline auto setSoundPool(
181 JNIEnv *env, jobject thiz, const std::shared_ptr<SoundPool>& soundPool) {
182 return getSoundPoolManager().set(env, thiz, soundPool);
183 }
184
185 /**
186 * ConcurrentHashMap is a locked hash map
187 *
188 * As from the name, this class is thread_safe.
189 *
190 * The type V must have 3 properties in the current implementation.
191 * 1) A V{} default constructor which represents a nullValue.
192 * 2) V::operator bool() const efficient detection of such a nullValue.
193 * 3) V must be copyable.
194 *
195 * Note: The Key cannot be a Java LocalRef, as those change between JNI calls.
196 * The Key could be the raw native object pointer if one wanted to associate
197 * extra data with a native object.
198 *
199 * Using set() with a nullValue V results in erasing the key entry.
200 * A nullValue V is returned by get() if there is no underlying entry.
201 *
202 * Design notes:
203 * 1) For objects of type V that do not naturally have a "nullValue",
204 * wrapping VOpt = std::optional<V> or VShared = std::shared<V> is recommended.
205 *
206 * 2) An overload for an explicit equality comparable nullValue such as
207 * get(..., const V& nullValue) or set(..., const V& nullValue)
208 * is omitted. An alternative is to pass a fixed nullValue into a special
209 * constructor (omitted) for equality comparisons and return value.
210 *
211 * 3) This ConcurrentHashMap currently allows only one thread at a time.
212 * It is not optimized for heavy multi-threaded use.
213 */
214 template <typename K, typename V>
215 class ConcurrentHashMap
216 {
217 public:
218
219 // Sets the value and returns the old one.
220 //
221 // If the old value doesn't exist, then nullValue V is returned.
222 // If the new value is false by operator bool(), the internal value is destroyed.
223 // Note: The old value is returned so if V is a smart pointer, it can be held
224 // by the caller to be deleted outside of any external lock.
225
set(const K & key,const V & value)226 V set(const K& key, const V& value) {
227 std::lock_guard lg(mLock);
228 auto it = mMap.find(key);
229 if (it == mMap.end()) {
230 if (value) {
231 mMap[key] = value;
232 }
233 return {};
234 }
235 V oldValue = std::move(it->second);
236 if (value) {
237 it->second = value;
238 } else {
239 mMap.erase(it);
240 }
241 return oldValue;
242 }
243
244 // Retrieves the associated object, returns nullValue V if not available.
get(const K & key) const245 V get(const K& key) const {
246 std::lock_guard lg(mLock);
247 auto it = mMap.find(key);
248 return it != mMap.end() ? it->second : V{};
249 }
250 private:
251 mutable std::mutex mLock;
252 std::unordered_map<K, V> mMap GUARDED_BY(mLock);
253 };
254
255 // *jobject is needed to fit the jobject into a std::shared_ptr.
256 // This is the Android type _jobject, but we derive this type as JObjectValue.
257 using JObjectValue = std::remove_pointer_t<jobject>; // _jobject
258
259 // Check that jobject is really a pointer to JObjectValue.
260 // The JNI contract is that jobject is NULL comparable,
261 // so jobject is pointer equivalent; we check here to be sure.
262 // Note std::remove_ptr_t<NonPointerType> == NonPointerType.
263 static_assert(std::is_same_v<JObjectValue*, jobject>);
264
265 // *jweak is needed to fit the jweak into a std::shared_ptr.
266 // This is the Android type _jobject, but we derive this type as JWeakValue.
267 using JWeakValue = std::remove_pointer_t<jweak>; // this is just _jobject
268
269 // Check that jweak is really a pointer to JWeakValue.
270 static_assert(std::is_same_v<JWeakValue*, jweak>);
271
272 // We store the ancillary data associated with a SoundPool object in a concurrent
273 // hash map indexed on the SoundPool native object pointer.
getSoundPoolJavaRefManager()274 auto& getSoundPoolJavaRefManager() {
275 // Note this can store shared_ptrs to either jweak and jobject,
276 // as the underlying type is identical.
277 static ConcurrentHashMap<SoundPool *, std::shared_ptr<JWeakValue>> concurrentHashMap;
278 return concurrentHashMap;
279 }
280
281 // make_shared_globalref_from_localref() creates a sharable Java global
282 // reference from a Java local reference. The equivalent type is
283 // std::shared_ptr<_jobject> (where _jobject is JObjectValue,
284 // and _jobject * is jobject),
285 // and the jobject may be retrieved by .get() or pointer dereference.
286 // This encapsulation gives the benefit of std::shared_ptr
287 // ref counting, weak_ptr, etc.
288 //
289 // The Java global reference should be stable between JNI calls. It is a limited
290 // quantity so sparingly use global references.
291 //
292 // The Android JNI implementation is described here:
293 // https://developer.android.com/training/articles/perf-jni
294 // https://android-developers.googleblog.com/2011/11/jni-local-reference-changes-in-ics.html
295 //
296 // Consider using a weak reference if this is self-referential.
297 [[maybe_unused]]
make_shared_globalref_from_localref(JNIEnv * env,jobject localRef)298 inline auto make_shared_globalref_from_localref(JNIEnv *env, jobject localRef) {
299 return std::shared_ptr<JObjectValue>(
300 env->NewGlobalRef(localRef),
301 [](JObjectValue* object) { // cannot cache env as don't know which thread we're on.
302 if (object != nullptr) AndroidRuntime::getJNIEnv()->DeleteGlobalRef(object);
303 });
304 }
305
306 // Create a weak global reference from local ref.
make_shared_weakglobalref_from_localref(JNIEnv * env,jobject localRef)307 inline auto make_shared_weakglobalref_from_localref(JNIEnv *env, jobject localRef) {
308 return std::shared_ptr<JWeakValue>(
309 env->NewWeakGlobalRef(localRef),
310 [](JWeakValue* weak) { // cannot cache env as don't know which thread we're on.
311 if (weak != nullptr) AndroidRuntime::getJNIEnv()->DeleteWeakGlobalRef(weak);
312 });
313 }
314
315 // std::unique_ptr<> does not store a type-erased deleter like std::shared_ptr<>.
316 // Define a lambda here to use for the std::unique_ptr<> type definition.
__anon3bc760c90402(JObjectValue* object) 317 auto LocalRefDeleter = [](JObjectValue* object) {
318 if (object != nullptr) AndroidRuntime::getJNIEnv()->DeleteLocalRef(object);
319 };
320
321 // Create a local reference from another reference.
322 // This is a unique_ptr to avoid the temptation of sharing with other threads.
323 //
324 // This can be used to promote a WeakGlobalRef jweak into a stable LocalRef jobject.
325 //
make_unique_localref_from_ref(JNIEnv * env,jobject object)326 inline auto make_unique_localref_from_ref(JNIEnv *env, jobject object) {
327 return std::unique_ptr<JObjectValue, decltype(LocalRefDeleter)>(
328 env->NewLocalRef(object),
329 LocalRefDeleter);
330 }
331
332 } // namespace
333
334 static const char* const kAudioAttributesClassPathName = "android/media/AudioAttributes";
335 struct audio_attributes_fields_t {
336 jfieldID fieldUsage; // AudioAttributes.mUsage
337 jfieldID fieldContentType; // AudioAttributes.mContentType
338 jfieldID fieldFlags; // AudioAttributes.mFlags
339 jfieldID fieldFormattedTags;// AudioAttributes.mFormattedTags
340 };
341 static audio_attributes_fields_t javaAudioAttrFields;
342
343 // ----------------------------------------------------------------------------
344
345 static jint
android_media_SoundPool_load_FD(JNIEnv * env,jobject thiz,jobject fileDescriptor,jlong offset,jlong length,jint priority)346 android_media_SoundPool_load_FD(JNIEnv *env, jobject thiz, jobject fileDescriptor,
347 jlong offset, jlong length, jint priority)
348 {
349 ALOGV("android_media_SoundPool_load_FD");
350 auto soundPool = getSoundPool(env, thiz);
351 if (soundPool == nullptr) return 0;
352 return (jint) soundPool->load(jniGetFDFromFileDescriptor(env, fileDescriptor),
353 int64_t(offset), int64_t(length), int(priority));
354 }
355
356 static jboolean
android_media_SoundPool_unload(JNIEnv * env,jobject thiz,jint sampleID)357 android_media_SoundPool_unload(JNIEnv *env, jobject thiz, jint sampleID) {
358 ALOGV("android_media_SoundPool_unload\n");
359 auto soundPool = getSoundPool(env, thiz);
360 if (soundPool == nullptr) return JNI_FALSE;
361 return soundPool->unload(sampleID) ? JNI_TRUE : JNI_FALSE;
362 }
363
364 static jint
android_media_SoundPool_play(JNIEnv * env,jobject thiz,jint sampleID,jfloat leftVolume,jfloat rightVolume,jint priority,jint loop,jfloat rate)365 android_media_SoundPool_play(JNIEnv *env, jobject thiz, jint sampleID,
366 jfloat leftVolume, jfloat rightVolume, jint priority, jint loop,
367 jfloat rate)
368 {
369 ALOGV("android_media_SoundPool_play\n");
370 auto soundPool = getSoundPool(env, thiz);
371 if (soundPool == nullptr) return 0;
372 return (jint) soundPool->play(sampleID, leftVolume, rightVolume, priority, loop, rate);
373 }
374
375 static void
android_media_SoundPool_pause(JNIEnv * env,jobject thiz,jint channelID)376 android_media_SoundPool_pause(JNIEnv *env, jobject thiz, jint channelID)
377 {
378 ALOGV("android_media_SoundPool_pause");
379 auto soundPool = getSoundPool(env, thiz);
380 if (soundPool == nullptr) return;
381 soundPool->pause(channelID);
382 }
383
384 static void
android_media_SoundPool_resume(JNIEnv * env,jobject thiz,jint channelID)385 android_media_SoundPool_resume(JNIEnv *env, jobject thiz, jint channelID)
386 {
387 ALOGV("android_media_SoundPool_resume");
388 auto soundPool = getSoundPool(env, thiz);
389 if (soundPool == nullptr) return;
390 soundPool->resume(channelID);
391 }
392
393 static void
android_media_SoundPool_autoPause(JNIEnv * env,jobject thiz)394 android_media_SoundPool_autoPause(JNIEnv *env, jobject thiz)
395 {
396 ALOGV("android_media_SoundPool_autoPause");
397 auto soundPool = getSoundPool(env, thiz);
398 if (soundPool == nullptr) return;
399 soundPool->autoPause();
400 }
401
402 static void
android_media_SoundPool_autoResume(JNIEnv * env,jobject thiz)403 android_media_SoundPool_autoResume(JNIEnv *env, jobject thiz)
404 {
405 ALOGV("android_media_SoundPool_autoResume");
406 auto soundPool = getSoundPool(env, thiz);
407 if (soundPool == nullptr) return;
408 soundPool->autoResume();
409 }
410
411 static void
android_media_SoundPool_stop(JNIEnv * env,jobject thiz,jint channelID)412 android_media_SoundPool_stop(JNIEnv *env, jobject thiz, jint channelID)
413 {
414 ALOGV("android_media_SoundPool_stop");
415 auto soundPool = getSoundPool(env, thiz);
416 if (soundPool == nullptr) return;
417 soundPool->stop(channelID);
418 }
419
420 static void
android_media_SoundPool_setVolume(JNIEnv * env,jobject thiz,jint channelID,jfloat leftVolume,jfloat rightVolume)421 android_media_SoundPool_setVolume(JNIEnv *env, jobject thiz, jint channelID,
422 jfloat leftVolume, jfloat rightVolume)
423 {
424 ALOGV("android_media_SoundPool_setVolume");
425 auto soundPool = getSoundPool(env, thiz);
426 if (soundPool == nullptr) return;
427 soundPool->setVolume(channelID, (float) leftVolume, (float) rightVolume);
428 }
429
430 static void
android_media_SoundPool_mute(JNIEnv * env,jobject thiz,jboolean muting)431 android_media_SoundPool_mute(JNIEnv *env, jobject thiz, jboolean muting)
432 {
433 ALOGV("android_media_SoundPool_mute(%d)", muting);
434 auto soundPool = getSoundPool(env, thiz);
435 if (soundPool == nullptr) return;
436 soundPool->mute(muting == JNI_TRUE);
437 }
438
439 static void
android_media_SoundPool_setPriority(JNIEnv * env,jobject thiz,jint channelID,jint priority)440 android_media_SoundPool_setPriority(JNIEnv *env, jobject thiz, jint channelID,
441 jint priority)
442 {
443 ALOGV("android_media_SoundPool_setPriority");
444 auto soundPool = getSoundPool(env, thiz);
445 if (soundPool == nullptr) return;
446 soundPool->setPriority(channelID, (int) priority);
447 }
448
449 static void
android_media_SoundPool_setLoop(JNIEnv * env,jobject thiz,jint channelID,int loop)450 android_media_SoundPool_setLoop(JNIEnv *env, jobject thiz, jint channelID,
451 int loop)
452 {
453 ALOGV("android_media_SoundPool_setLoop");
454 auto soundPool = getSoundPool(env, thiz);
455 if (soundPool == nullptr) return;
456 soundPool->setLoop(channelID, loop);
457 }
458
459 static void
android_media_SoundPool_setRate(JNIEnv * env,jobject thiz,jint channelID,jfloat rate)460 android_media_SoundPool_setRate(JNIEnv *env, jobject thiz, jint channelID,
461 jfloat rate)
462 {
463 ALOGV("android_media_SoundPool_setRate");
464 auto soundPool = getSoundPool(env, thiz);
465 if (soundPool == nullptr) return;
466 soundPool->setRate(channelID, (float) rate);
467 }
468
android_media_callback(SoundPoolEvent event,SoundPool * soundPool,void * user)469 static void android_media_callback(SoundPoolEvent event, SoundPool* soundPool, void* user)
470 {
471 ALOGV("callback: (%d, %d, %d, %p, %p)", event.mMsg, event.mArg1, event.mArg2, soundPool, user);
472 auto weakRef = getSoundPoolJavaRefManager().get(soundPool); // shared_ptr to WeakRef
473 if (weakRef == nullptr) {
474 ALOGD("%s: no weak ref, object released, ignoring callback", __func__);
475 return;
476 }
477 JNIEnv *env = AndroidRuntime::getJNIEnv();
478 // "promote" the WeakGlobalRef into a LocalRef.
479 auto javaSoundPool = make_unique_localref_from_ref(env, weakRef.get());
480 if (!javaSoundPool) {
481 ALOGW("%s: weak reference promotes to null (release() not called?), "
482 "ignoring callback", __func__);
483 return;
484 }
485 env->CallVoidMethod(javaSoundPool.get(), fields.mPostEvent,
486 event.mMsg, event.mArg1, event.mArg2, nullptr /* object */);
487
488 if (env->ExceptionCheck() != JNI_FALSE) {
489 ALOGE("%s: Uncaught exception returned from Java callback", __func__);
490 env->ExceptionDescribe();
491 env->ExceptionClear(); // Just clear it, hopefully all is ok.
492 }
493 }
494
495 static jint
android_media_SoundPool_native_setup(JNIEnv * env,jobject thiz,jint maxChannels,jobject jaa,jstring opPackageName)496 android_media_SoundPool_native_setup(JNIEnv *env, jobject thiz,
497 jint maxChannels, jobject jaa, jstring opPackageName)
498 {
499 ALOGV("android_media_SoundPool_native_setup");
500 if (jaa == nullptr) {
501 ALOGE("Error creating SoundPool: invalid audio attributes");
502 return -1;
503 }
504
505 // Use the AUDIO_ATTRIBUTES_INITIALIZER here to ensure all non-relevant fields are
506 // initialized properly. (note that .source is not explicitly initialized here).
507 audio_attributes_t audioAttributes = AUDIO_ATTRIBUTES_INITIALIZER;
508 // read the AudioAttributes values
509 const auto jtags =
510 (jstring) env->GetObjectField(jaa, javaAudioAttrFields.fieldFormattedTags);
511 const char* tags = env->GetStringUTFChars(jtags, nullptr);
512 // infers array size and guarantees zero termination (does not zero fill to the end).
513 audio_utils_strlcpy(audioAttributes.tags, tags);
514 env->ReleaseStringUTFChars(jtags, tags);
515 audioAttributes.usage =
516 (audio_usage_t) env->GetIntField(jaa, javaAudioAttrFields.fieldUsage);
517 audioAttributes.content_type =
518 (audio_content_type_t) env->GetIntField(jaa, javaAudioAttrFields.fieldContentType);
519 audioAttributes.flags =
520 (audio_flags_mask_t) env->GetIntField(jaa, javaAudioAttrFields.fieldFlags);
521 ScopedUtfChars opPackageNameStr(env, opPackageName);
522 auto soundPool = std::make_shared<SoundPool>(
523 maxChannels, audioAttributes, opPackageNameStr.c_str());
524 soundPool->setCallback(android_media_callback, nullptr /* user */);
525
526 // register with SoundPoolManager.
527 auto oldSoundPool = setSoundPool(env, thiz, soundPool);
528 // register Java SoundPool WeakRef using native SoundPool * as the key, for the callback.
529 auto oldSoundPoolJavaRef = getSoundPoolJavaRefManager().set(
530 soundPool.get(), make_shared_weakglobalref_from_localref(env, thiz));
531
532 ALOGW_IF(oldSoundPool != nullptr, "%s: Aliased SoundPool object %p",
533 __func__, oldSoundPool.get());
534 return 0;
535 }
536
537 static void
android_media_SoundPool_release(JNIEnv * env,jobject thiz)538 android_media_SoundPool_release(JNIEnv *env, jobject thiz)
539 {
540 ALOGV("android_media_SoundPool_release");
541
542 // Remove us from SoundPoolManager.
543
544 auto oldSoundPool = setSoundPool(env, thiz, nullptr);
545 if (oldSoundPool != nullptr) {
546 // Note: setting the weak ref is thread safe in case there is a callback
547 // simultaneously occurring.
548 auto oldSoundPoolJavaRef = getSoundPoolJavaRefManager().set(oldSoundPool.get(), nullptr);
549 }
550 // destructor to oldSoundPool should occur at exit.
551 }
552
553 // ----------------------------------------------------------------------------
554
555 // Dalvik VM type signatures
556 static JNINativeMethod gMethods[] = {
557 { "_load",
558 "(Ljava/io/FileDescriptor;JJI)I",
559 (void *)android_media_SoundPool_load_FD
560 },
561 { "unload",
562 "(I)Z",
563 (void *)android_media_SoundPool_unload
564 },
565 { "_play",
566 "(IFFIIF)I",
567 (void *)android_media_SoundPool_play
568 },
569 { "pause",
570 "(I)V",
571 (void *)android_media_SoundPool_pause
572 },
573 { "resume",
574 "(I)V",
575 (void *)android_media_SoundPool_resume
576 },
577 { "autoPause",
578 "()V",
579 (void *)android_media_SoundPool_autoPause
580 },
581 { "autoResume",
582 "()V",
583 (void *)android_media_SoundPool_autoResume
584 },
585 { "stop",
586 "(I)V",
587 (void *)android_media_SoundPool_stop
588 },
589 { "_setVolume",
590 "(IFF)V",
591 (void *)android_media_SoundPool_setVolume
592 },
593 { "_mute",
594 "(Z)V",
595 (void *)android_media_SoundPool_mute
596 },
597 { "setPriority",
598 "(II)V",
599 (void *)android_media_SoundPool_setPriority
600 },
601 { "setLoop",
602 "(II)V",
603 (void *)android_media_SoundPool_setLoop
604 },
605 { "setRate",
606 "(IF)V",
607 (void *)android_media_SoundPool_setRate
608 },
609 { "native_setup",
610 "(ILjava/lang/Object;Ljava/lang/String;)I",
611 (void*)android_media_SoundPool_native_setup
612 },
613 { "native_release",
614 "()V",
615 (void*)android_media_SoundPool_release
616 }
617 };
618
619 static const char* const kClassPathName = "android/media/SoundPool";
620
JNI_OnLoad(JavaVM * vm,void *)621 jint JNI_OnLoad(JavaVM* vm, void* /* reserved */)
622 {
623 JNIEnv* env = nullptr;
624 jint result = -1;
625 jclass clazz;
626
627 if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
628 ALOGE("ERROR: GetEnv failed\n");
629 return result;
630 }
631 assert(env != nullptr);
632
633 clazz = env->FindClass(kClassPathName);
634 if (clazz == nullptr) {
635 ALOGE("Can't find %s", kClassPathName);
636 return result;
637 }
638
639 fields.mNativeContext = env->GetFieldID(clazz, "mNativeContext", "J");
640 if (fields.mNativeContext == nullptr) {
641 ALOGE("Can't find SoundPool.mNativeContext");
642 return result;
643 }
644
645 fields.mPostEvent = env->GetMethodID(
646 clazz, "postEventFromNative", "(IIILjava/lang/Object;)V");
647 if (fields.mPostEvent == nullptr) {
648 ALOGE("Can't find android/media/SoundPool.postEventFromNative");
649 return result;
650 }
651
652 // create a reference to class. Technically, we're leaking this reference
653 // since it's a static object.
654 fields.mSoundPoolClass = (jclass) env->NewGlobalRef(clazz);
655
656 if (AndroidRuntime::registerNativeMethods(
657 env, kClassPathName, gMethods, NELEM(gMethods)) < 0) {
658 return result;
659 }
660
661 // Get the AudioAttributes class and fields
662 jclass audioAttrClass = env->FindClass(kAudioAttributesClassPathName);
663 if (audioAttrClass == nullptr) {
664 ALOGE("Can't find %s", kAudioAttributesClassPathName);
665 return result;
666 }
667 auto audioAttributesClassRef = (jclass)env->NewGlobalRef(audioAttrClass);
668 javaAudioAttrFields.fieldUsage = env->GetFieldID(audioAttributesClassRef, "mUsage", "I");
669 javaAudioAttrFields.fieldContentType
670 = env->GetFieldID(audioAttributesClassRef, "mContentType", "I");
671 javaAudioAttrFields.fieldFlags = env->GetFieldID(audioAttributesClassRef, "mFlags", "I");
672 javaAudioAttrFields.fieldFormattedTags =
673 env->GetFieldID(audioAttributesClassRef, "mFormattedTags", "Ljava/lang/String;");
674 env->DeleteGlobalRef(audioAttributesClassRef);
675 if (javaAudioAttrFields.fieldUsage == nullptr
676 || javaAudioAttrFields.fieldContentType == nullptr
677 || javaAudioAttrFields.fieldFlags == nullptr
678 || javaAudioAttrFields.fieldFormattedTags == nullptr) {
679 ALOGE("Can't initialize AudioAttributes fields");
680 return result;
681 }
682
683 /* success -- return valid version number */
684 return JNI_VERSION_1_4;
685 }
686