xref: /aosp_15_r20/frameworks/av/media/psh_utils/include/psh_utils/AudioPowerManager.h (revision ec779b8e0859a360c3d303172224686826e6e0e1)
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 "PowerClientStats.h"
20 #include "PowerStatsCollector.h"
21 #include "Token.h"
22 
23 #include <android-base/thread_annotations.h>
24 #include <audio_utils/linked_hash_map.h>
25 #include <list>
26 #include <map>
27 #include <unordered_map>
28 #include <unordered_set>
29 
30 namespace android::media::psh_utils {
31 
32 /**
33  * AudioPowerManager is a singleton class that
34  * serializes the power, wakelock, and performance
35  * messages
36  */
37 class AudioPowerManager {
38     friend class AudioClientToken;
39     friend class AudioThreadToken;
40     friend class AudioTrackToken;
41 
42 public:
43     static AudioPowerManager& getAudioPowerManager();
44 
45     /**
46      * Returns a token indicating that a client is started.
47      * This is associated with an application.
48      */
49     std::unique_ptr<Token> startClient(pid_t pid, uid_t uid,
50             const std::string& additional);
51 
52     /**
53      * Returns a token that represents a start instance for uid.
54      * This is typically associated with an AudioTrack / AudioRecord start.
55      */
56     std::unique_ptr<Token> startTrack(uid_t uid, const std::string& additional);
57 
58     /**
59      * Returns a token that represents a wakelock for a Thread start.
60      */
61     std::unique_ptr<Token> startThread(
62             pid_t pid, const std::string& wakeLockName,
63             WakeFlag wakeFlag, const std::string& additional);
64 
65     std::string toString() const;
66 
67     static bool enabled();
68 
69 private:
70     // For AudioToken dtor only.
71     void clear_token_ptr(Token* token);
72     void stopClient(pid_t pid);
73 
74     static constexpr size_t kHistory = 6;
75 
76     mutable std::mutex mMutex;
77     std::unordered_set<Token *> mOutstandingTokens GUARDED_BY(mMutex);
78     std::unordered_map<pid_t, uid_t> mPidToUid GUARDED_BY(mMutex);
79     std::map<uid_t, std::shared_ptr<PowerClientStats>> mPowerClientStats GUARDED_BY(mMutex);
80     audio_utils::linked_hash_map<uid_t, std::shared_ptr<PowerClientStats>>
81             mHistoricalClients GUARDED_BY(mMutex);
82 };
83 
84 } // namespace android::media::psh_utils
85