1 /*
2 * Copyright (C) 2020 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 <sstream>
18
19 #define LOG_TAG "ExternalCaptureStateTracker"
20
21 #include "core_jni_helpers.h"
22 #include <log/log.h>
23 #include <media/AudioSystem.h>
24
25 namespace android {
26 namespace {
27
28 #define PACKAGE "com/android/server/soundtrigger_middleware"
29 #define CLASSNAME PACKAGE "/ExternalCaptureStateTracker"
30
31 jclass gExternalCaptureStateTrackerClassId;
32 jmethodID gSetCaptureStateMethodId;
33 jmethodID gBinderDiedMethodId;
34
PopulateIds(JNIEnv * env)35 void PopulateIds(JNIEnv* env) {
36 gExternalCaptureStateTrackerClassId =
37 (jclass) env->NewGlobalRef(FindClassOrDie(env, CLASSNAME));
38 gSetCaptureStateMethodId = GetMethodIDOrDie(env,
39 gExternalCaptureStateTrackerClassId,
40 "setCaptureState",
41 "(Z)V");
42 gBinderDiedMethodId = GetMethodIDOrDie(env,
43 gExternalCaptureStateTrackerClassId,
44 "binderDied",
45 "()V");
46 }
47
48 class Listener : public AudioSystem::CaptureStateListener {
49 public:
Listener(JNIEnv * env,jobject obj)50 Listener(JNIEnv* env, jobject obj) : mObj(env->NewGlobalRef(obj)) {}
51
~Listener()52 ~Listener() {
53 JNIEnv* env = AndroidRuntime::getJNIEnv();
54 env->DeleteGlobalRef(mObj);
55 }
56
onStateChanged(bool active)57 void onStateChanged(bool active) override {
58 JNIEnv* env = AndroidRuntime::getJNIEnv();
59 env->CallVoidMethod(mObj, gSetCaptureStateMethodId, active);
60 }
61
onServiceDied()62 void onServiceDied() override {
63 JNIEnv* env = AndroidRuntime::getJNIEnv();
64 env->CallVoidMethod(mObj, gBinderDiedMethodId);
65 }
66
67 private:
68 jobject mObj;
69 };
70
connect(JNIEnv * env,jobject obj)71 void connect(JNIEnv* env, jobject obj) {
72 sp<AudioSystem::CaptureStateListener> listener(new Listener(env, obj));
73 status_t status =
74 AudioSystem::registerSoundTriggerCaptureStateListener(listener);
75 LOG_ALWAYS_FATAL_IF(status != NO_ERROR);
76 }
77
78 const JNINativeMethod gMethods[] = {
79 {"connect", "()V", reinterpret_cast<void*>(connect)},
80 };
81
82 } // namespace
83
register_com_android_server_soundtrigger_middleware_ExternalCaptureStateTracker(JNIEnv * env)84 int register_com_android_server_soundtrigger_middleware_ExternalCaptureStateTracker(
85 JNIEnv* env) {
86 PopulateIds(env);
87 return RegisterMethodsOrDie(env,
88 CLASSNAME,
89 gMethods,
90 NELEM(gMethods));
91 }
92
93 } // namespace android
94