1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef PA_ADAPTER_TOOLS_H
17 #define PA_ADAPTER_TOOLS_H
18 
19 #include <pulse/pulseaudio.h>
20 #include <pulse/thread-mainloop.h>
21 
22 namespace OHOS {
23 namespace AudioStandard {
24 // PaLockGuard is used to auto-call unlock.
25 class PaLockGuard {
26 public:
27     PaLockGuard(pa_threaded_mainloop *mainloop, bool mainloopCheck = false) : mainloop_(mainloop)
28     {
29         if (mainloopCheck) {
30             isInMainloop_ = pa_threaded_mainloop_in_thread(mainloop_) ? true : false;
31         } else {
32             isInMainloop_ = false;
33         }
34         if (!isInMainloop_) {
35             pa_threaded_mainloop_lock(mainloop_);
36         }
37     }
38 
~PaLockGuard()39     ~PaLockGuard()
40     {
41         Unlock();
42     }
43 
Unlock()44     void Unlock()
45     {
46         if (!isInMainloop_ && !isUnlocked_) {
47             pa_threaded_mainloop_unlock(mainloop_);
48             isUnlocked_ = true;
49         }
50     }
51 
Relock()52     void Relock()
53     {
54         if (!isInMainloop_ && isUnlocked_) {
55             isUnlocked_ = false;
56             pa_threaded_mainloop_lock(mainloop_);
57         }
58     }
59 private:
60     bool isUnlocked_ = false;
61     bool isInMainloop_ = false;
62     pa_threaded_mainloop *mainloop_ = nullptr;
63 };
64 } // namespace AudioStandard
65 } // namespace OHOS
66 #endif // PA_ADAPTER_TOOLS_H
67