1 /* 2 * Copyright (c) 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 16 #define HST_LOG_TAG "InterruptMonitor" 17 18 #include "common/interrupt_monitor.h" 19 #include <algorithm> 20 21 using namespace std; 22 23 namespace OHOS { 24 25 namespace Media { SetInterruptState(bool isInterruptNeeded)26void InterruptMonitor::SetInterruptState(bool isInterruptNeeded) 27 { 28 interruptState_.store(isInterruptNeeded); 29 NotifyInterrupt(isInterruptNeeded); 30 } 31 RegisterListener(const shared_ptr<InterruptListener> listener)32void InterruptMonitor::RegisterListener(const shared_ptr<InterruptListener> listener) 33 { 34 std::unique_lock<std::mutex> interruptLock(mutex_); 35 vec_.push_back(std::weak_ptr<InterruptListener>(listener)); 36 } 37 DeregisterListener(std::shared_ptr<InterruptListener> listener)38void InterruptMonitor::DeregisterListener(std::shared_ptr<InterruptListener> listener) 39 { 40 if (listener == nullptr) { 41 return; 42 } 43 std::unique_lock<std::mutex> interruptLock(mutex_); 44 for (auto it = vec_.begin(); it != vec_.end();) { 45 if (it->lock() == listener) { 46 vec_.erase(it); 47 break; 48 } else { 49 ++it; 50 } 51 } 52 } 53 CleanUnusedListener()54void InterruptMonitor::CleanUnusedListener() 55 { 56 std::unique_lock<std::mutex> interruptLock(mutex_); 57 for (auto it = vec_.begin(); it != vec_.end();) { 58 if (!(it->expired())) { 59 it = vec_.erase(it); 60 } else { 61 ++it; 62 } 63 } 64 } 65 NotifyInterrupt(bool isInterruptNeeded)66void InterruptMonitor::NotifyInterrupt(bool isInterruptNeeded) 67 { 68 std::unique_lock<std::mutex> interruptLock(mutex_); 69 for (auto listener : vec_) { 70 if (auto interruptListener = listener.lock()) { 71 interruptListener->OnInterrupted(isInterruptNeeded); 72 } 73 } 74 } 75 } // namespace Media 76 77 } // namespace OHOS