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 #pragma once
18 
19 #include <mutex>
20 #include <binder/IBinder.h>
21 #include <utils/StrongPointer.h>
22 
23 namespace android {
24 namespace media {
25 // Must be pre-declared, or else there isn't a good way to generate a header
26 // library.
27 class ICaptureStateListener;
28 }
29 
30 // A utility for managing capture state change notifications.
31 //
32 // We are making some strong assumptions, for the sake of simplicity:
33 // - There is no way to explicitly unregister listeners. The only way for a
34 //   listener to unregister is by dying.
35 // - There's only at most one listener at a given time. Attempting to register
36 //   a second listener will cause a crash.
37 // - This class isn't really meant to ever be destroyed. We expose a destructor
38 //   because it is convenient to use this class as a global instance or a member
39 //   of another class, but it will crash if destroyed while a listener is
40 //   registered.
41 //
42 // All of these assumptions can be lifted if there is ever a need.
43 //
44 // This class is thread-safe.
45 class CaptureStateNotifier {
46 public:
47     // Ctor.
48     // Accepts the initial active state.
49     explicit CaptureStateNotifier(bool initialActive);
50 
51     // Register a listener to be notified of state changes.
52     // The current state is returned and from that point on any change will be
53     // notified of.
54     bool RegisterListener(const sp<media::ICaptureStateListener>& listener);
55 
56     // Change the current capture state.
57     // Active means "actively capturing".
58     void setCaptureState(bool active);
59 
60     // Dtor. Do not actually call at runtime. Will cause a crash if a listener
61     // is registered.
62     ~CaptureStateNotifier();
63 
64 private:
65     std::mutex mMutex;
66     sp<media::ICaptureStateListener> mListener;
67     sp<IBinder::DeathRecipient> mDeathRecipient;
68     bool mActive;
69 
70     class DeathRecipient;
71 
72     void binderDied();
73 };
74 
75 }  // namespace android
76