1 /* 2 * Copyright (C) 2024 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 "PowerStats.h" 20 #include <android-base/thread_annotations.h> 21 #include <memory> 22 #include <utils/Errors.h> // status_t 23 24 namespace android::media::psh_utils { 25 26 // Internal providers that fill up the PowerStats state object. 27 class PowerStatsProvider { 28 public: 29 virtual ~PowerStatsProvider() = default; 30 virtual status_t fill(PowerStats* stat) const = 0; 31 }; 32 33 class PowerStatsCollector { 34 public: 35 // singleton getter 36 static PowerStatsCollector& getCollector(); 37 38 // Returns a snapshot of the state. 39 // If toleranceNs > 0, we permit the use of a stale snapshot taken within that tolerance. 40 std::shared_ptr<const PowerStats> getStats(int64_t toleranceNs = 0) 41 EXCLUDES(mMutex, mMutexExclusiveFill); 42 43 private: 44 PowerStatsCollector(); // use the singleton getter 45 46 // Returns non-empty PowerStats if we have a previous stats snapshot within toleranceNs. 47 std::shared_ptr<const PowerStats> checkLastStats(int64_t toleranceNs) const EXCLUDES(mMutex); 48 int fill(PowerStats* stats) const; 49 void addProvider(std::unique_ptr<PowerStatsProvider>&& powerStatsProvider); 50 51 mutable std::mutex mMutexExclusiveFill; 52 mutable std::mutex mMutex; 53 // addProvider is called in the ctor, so effectively const. 54 std::vector<std::unique_ptr<PowerStatsProvider>> mPowerStatsProviders; 55 int64_t mLastFetchNs GUARDED_BY(mMutex) = 0; 56 std::shared_ptr<const PowerStats> mLastFetchStats GUARDED_BY(mMutex); 57 }; 58 59 } // namespace android::media::psh_utils 60