1 /* 2 * Copyright (c) 2025-2025 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 #ifndef AUDIO_POLICY_STATE_MONITOR_H 16 #define AUDIO_POLICY_STATE_MONITOR_H 17 18 #include <mutex> 19 #include <thread> 20 #include <map> 21 #include "singleton.h" 22 23 namespace OHOS { 24 namespace AudioStandard { 25 26 enum CallbackType { 27 ONE_TIME, 28 REPEAT, 29 }; 30 31 enum { 32 INVALID_CB_ID = -1, 33 MAX_CB_ID_NUM = 100, 34 }; 35 36 class CallBackTimeInfo { 37 public: 38 virtual ~CallBackTimeInfo() = default; 39 std::time_t startTimeStamp_; // Callback registration start timestamp, Unit: second 40 std::time_t delayTime_; // Callback timeout duration, Unit: second 41 CallbackType callbackType_ = ONE_TIME; 42 }; 43 44 class AudioPolicyStateMonitorCallback : public CallBackTimeInfo { 45 public: 46 virtual void OnTimeOut() = 0; 47 }; 48 49 /** 50 * AudioPolicyStateMonitor's min timeout period is 1 second. 51 * It Support one-time or periodic timeout monitoring. 52 * It is generally used for monitoring with low precison requirement. 53 */ 54 class AudioPolicyStateMonitor { 55 DECLARE_DELAYED_SINGLETON(AudioPolicyStateMonitor); 56 public: 57 int32_t RegisterCallback( 58 const std::shared_ptr<AudioPolicyStateMonitorCallback> &cb, std::time_t delayTime_, CallbackType callbackType); 59 void UnRegisterCallback(int32_t cbId); 60 61 private: 62 void TraverseAndInvokeTimeoutCallbacks(); 63 void CheckStateThreadMain(); 64 int32_t AllocateCbId(); 65 void FreeCbId(int32_t cbId); 66 67 private: 68 bool idAllocator_[MAX_CB_ID_NUM] = {false}; 69 std::unordered_map<int32_t, std::shared_ptr<AudioPolicyStateMonitorCallback>> monitoredObj_; 70 std::shared_ptr<std::thread> stateMonitorThread_; 71 std::mutex monitorMutex_; 72 std::mutex condMutex_; 73 std::condition_variable stopCond_; 74 bool threadStoped_ = false; 75 }; 76 77 } // namespace AudioStandard 78 } // namespace OHOS 79 #endif // AUDIO_POLICY_STATE_MONITOR_H 80