blob: 4e9740608c72029812ba75a9885bf43f8cb3ec4b [file] [log] [blame]
Chong Zhanga9d45c72020-09-09 12:41:17 -07001/**
2 *
3 * Copyright 2020, The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18//#define LOG_NDEBUG 0
19#define LOG_TAG "ResourceObserverService"
20#include <utils/Log.h>
21
22#include <android/binder_manager.h>
23#include <android/binder_process.h>
24#include <binder/IServiceManager.h>
25#include <utils/String16.h>
26#include <aidl/android/media/MediaResourceParcel.h>
27
28#include "ResourceObserverService.h"
29
Chong Zhanga9d45c72020-09-09 12:41:17 -070030namespace android {
31
32using ::aidl::android::media::MediaResourceParcel;
33using ::aidl::android::media::MediaObservableEvent;
34
35// MediaObservableEvent will be used as uint64_t flags.
36static_assert(sizeof(MediaObservableEvent) == sizeof(uint64_t));
37
38static std::vector<MediaObservableEvent> sEvents = {
39 MediaObservableEvent::kBusy,
40 MediaObservableEvent::kIdle,
41};
42
43static MediaObservableType getObservableType(const MediaResourceParcel& res) {
44 if (res.subType == MediaResourceSubType::kVideoCodec) {
45 if (res.type == MediaResourceType::kNonSecureCodec) {
46 return MediaObservableType::kVideoNonSecureCodec;
47 }
48 if (res.type == MediaResourceType::kSecureCodec) {
49 return MediaObservableType::kVideoSecureCodec;
50 }
51 }
52 return MediaObservableType::kInvalid;
53}
54
55//static
56std::mutex ResourceObserverService::sDeathRecipientLock;
57//static
58std::map<uintptr_t, std::shared_ptr<ResourceObserverService::DeathRecipient> >
59ResourceObserverService::sDeathRecipientMap;
60
61struct ResourceObserverService::DeathRecipient {
62 DeathRecipient(ResourceObserverService* _service,
63 const std::shared_ptr<IResourceObserver>& _observer)
64 : service(_service), observer(_observer) {}
65 ~DeathRecipient() {}
66
67 void binderDied() {
68 if (service != nullptr) {
69 service->unregisterObserver(observer);
70 }
71 }
72
73 ResourceObserverService* service;
74 std::shared_ptr<IResourceObserver> observer;
75};
76
77// static
78void ResourceObserverService::BinderDiedCallback(void* cookie) {
79 uintptr_t id = reinterpret_cast<uintptr_t>(cookie);
80
81 ALOGW("Observer %lld is dead", (long long)id);
82
83 std::shared_ptr<DeathRecipient> recipient;
84
85 {
86 std::scoped_lock lock{sDeathRecipientLock};
87
88 auto it = sDeathRecipientMap.find(id);
89 if (it != sDeathRecipientMap.end()) {
90 recipient = it->second;
91 }
92 }
93
94 if (recipient != nullptr) {
95 recipient->binderDied();
96 }
97}
98
99//static
100std::shared_ptr<ResourceObserverService> ResourceObserverService::instantiate() {
101 std::shared_ptr<ResourceObserverService> observerService =
102 ::ndk::SharedRefBase::make<ResourceObserverService>();
103 binder_status_t status = AServiceManager_addService(observerService->asBinder().get(),
104 ResourceObserverService::getServiceName());
105 if (status != STATUS_OK) {
106 return nullptr;
107 }
108 return observerService;
109}
110
111ResourceObserverService::ResourceObserverService()
112 : mDeathRecipient(AIBinder_DeathRecipient_new(BinderDiedCallback)) {}
113
114binder_status_t ResourceObserverService::dump(
115 int fd, const char** /*args*/, uint32_t /*numArgs*/) {
116 String8 result;
117
118 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
119 result.format("Permission Denial: "
120 "can't dump ResourceManagerService from pid=%d, uid=%d\n",
121 AIBinder_getCallingPid(),
122 AIBinder_getCallingUid());
123 write(fd, result.string(), result.size());
124 return PERMISSION_DENIED;
125 }
126
127 result.appendFormat("ResourceObserverService: %p\n", this);
128 result.appendFormat(" Registered Observers: %zu\n", mObserverInfoMap.size());
129
130 {
131 std::scoped_lock lock{mObserverLock};
132
133 for (auto &observer : mObserverInfoMap) {
134 result.appendFormat(" Observer %p:\n", observer.second.binder.get());
135 for (auto &observable : observer.second.filters) {
136 String8 enabledEventsStr;
137 for (auto &event : sEvents) {
138 if (((uint64_t)observable.eventFilter & (uint64_t)event) != 0) {
139 if (!enabledEventsStr.isEmpty()) {
140 enabledEventsStr.append("|");
141 }
142 enabledEventsStr.append(toString(event).c_str());
143 }
144 }
145 result.appendFormat(" %s: %s\n",
146 toString(observable.type).c_str(), enabledEventsStr.c_str());
147 }
148 }
149 }
150
151 write(fd, result.string(), result.size());
152 return OK;
153}
154
155Status ResourceObserverService::registerObserver(
156 const std::shared_ptr<IResourceObserver>& in_observer,
157 const std::vector<MediaObservableFilter>& in_filters) {
Chong Zhang43a6ba62020-10-08 13:43:02 -0700158 if ((getpid() != AIBinder_getCallingPid()) &&
159 checkCallingPermission(
Chong Zhangd9c4faf2020-09-25 11:54:12 -0700160 String16("android.permission.REGISTER_MEDIA_RESOURCE_OBSERVER")) == false) {
161 ALOGE("Permission Denial: "
162 "can't registerObserver from pid=%d, uid=%d\n",
163 AIBinder_getCallingPid(),
164 AIBinder_getCallingUid());
165 return Status::fromServiceSpecificError(PERMISSION_DENIED);
166 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700167
Chong Zhanga781cee2021-03-17 11:42:33 -0700168 if (in_observer == nullptr) {
169 return Status::fromServiceSpecificError(BAD_VALUE);
170 }
171
Chong Zhanga9d45c72020-09-09 12:41:17 -0700172 ::ndk::SpAIBinder binder = in_observer->asBinder();
173
174 {
175 std::scoped_lock lock{mObserverLock};
176
177 if (mObserverInfoMap.find((uintptr_t)binder.get()) != mObserverInfoMap.end()) {
178 return Status::fromServiceSpecificError(ALREADY_EXISTS);
179 }
180
181 if (in_filters.empty()) {
182 return Status::fromServiceSpecificError(BAD_VALUE);
183 }
184
185 // Add observer info.
186 mObserverInfoMap.emplace((uintptr_t)binder.get(),
187 ObserverInfo{binder, in_observer, in_filters});
188
189 // Add observer to observable->subscribers map.
190 for (auto &filter : in_filters) {
191 for (auto &event : sEvents) {
192 if (!((uint64_t)filter.eventFilter & (uint64_t)event)) {
193 continue;
194 }
195 MediaObservableFilter key{filter.type, event};
196 mObservableToSubscribersMap[key].emplace((uintptr_t)binder.get(), in_observer);
197 }
198 }
199 }
200
201 // Add death binder and link.
202 uintptr_t cookie = (uintptr_t)binder.get();
203 {
204 std::scoped_lock lock{sDeathRecipientLock};
205 sDeathRecipientMap.emplace(
206 cookie, std::make_shared<DeathRecipient>(this, in_observer));
207 }
208
209 AIBinder_linkToDeath(binder.get(), mDeathRecipient.get(),
210 reinterpret_cast<void*>(cookie));
211
212 return Status::ok();
213}
214
215Status ResourceObserverService::unregisterObserver(
216 const std::shared_ptr<IResourceObserver>& in_observer) {
Chong Zhang43a6ba62020-10-08 13:43:02 -0700217 if ((getpid() != AIBinder_getCallingPid()) &&
218 checkCallingPermission(
Chong Zhangd9c4faf2020-09-25 11:54:12 -0700219 String16("android.permission.REGISTER_MEDIA_RESOURCE_OBSERVER")) == false) {
220 ALOGE("Permission Denial: "
221 "can't unregisterObserver from pid=%d, uid=%d\n",
222 AIBinder_getCallingPid(),
223 AIBinder_getCallingUid());
224 return Status::fromServiceSpecificError(PERMISSION_DENIED);
225 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700226
Chong Zhanga781cee2021-03-17 11:42:33 -0700227 if (in_observer == nullptr) {
228 return Status::fromServiceSpecificError(BAD_VALUE);
229 }
230
Chong Zhanga9d45c72020-09-09 12:41:17 -0700231 ::ndk::SpAIBinder binder = in_observer->asBinder();
232
233 {
234 std::scoped_lock lock{mObserverLock};
235
236 auto it = mObserverInfoMap.find((uintptr_t)binder.get());
237 if (it == mObserverInfoMap.end()) {
238 return Status::fromServiceSpecificError(NAME_NOT_FOUND);
239 }
240
241 // Remove observer from observable->subscribers map.
242 for (auto &filter : it->second.filters) {
243 for (auto &event : sEvents) {
244 if (!((uint64_t)filter.eventFilter & (uint64_t)event)) {
245 continue;
246 }
247 MediaObservableFilter key{filter.type, event};
248 mObservableToSubscribersMap[key].erase((uintptr_t)binder.get());
249
250 //Remove the entry if there's no more subscribers.
251 if (mObservableToSubscribersMap[key].empty()) {
252 mObservableToSubscribersMap.erase(key);
253 }
254 }
255 }
256
257 // Remove observer info.
258 mObserverInfoMap.erase(it);
259 }
260
261 // Unlink and remove death binder.
262 uintptr_t cookie = (uintptr_t)binder.get();
263 AIBinder_unlinkToDeath(binder.get(), mDeathRecipient.get(),
264 reinterpret_cast<void*>(cookie));
265
266 {
267 std::scoped_lock lock{sDeathRecipientLock};
268 sDeathRecipientMap.erase(cookie);
269 }
270
271 return Status::ok();
272}
273
274void ResourceObserverService::notifyObservers(
275 MediaObservableEvent event, int uid, int pid, const ResourceList &resources) {
276 struct CalleeInfo {
277 std::shared_ptr<IResourceObserver> observer;
278 std::vector<MediaObservableParcel> monitors;
279 };
280 // Build a consolidated list of observers to call with their respective observables.
281 std::map<uintptr_t, CalleeInfo> calleeList;
282
283 {
284 std::scoped_lock lock{mObserverLock};
285
286 for (auto &res : resources) {
287 // Skip if this resource doesn't map to any observable type.
288 MediaObservableType observableType = getObservableType(res.second);
289 if (observableType == MediaObservableType::kInvalid) {
290 continue;
291 }
292 MediaObservableFilter key{observableType, event};
293 // Skip if no one subscribed to this observable.
294 auto observableIt = mObservableToSubscribersMap.find(key);
295 if (observableIt == mObservableToSubscribersMap.end()) {
296 continue;
297 }
298 // Loop through all subsribers.
299 for (auto &subscriber : observableIt->second) {
300 auto calleeIt = calleeList.find(subscriber.first);
301 if (calleeIt == calleeList.end()) {
302 calleeList.emplace(subscriber.first, CalleeInfo{
303 subscriber.second, {{observableType, res.second.value}}});
304 } else {
305 calleeIt->second.monitors.push_back({observableType, res.second.value});
306 }
307 }
308 }
309 }
310
311 // Finally call the observers about the status change.
312 for (auto &calleeInfo : calleeList) {
313 calleeInfo.second.observer->onStatusChanged(
314 event, uid, pid, calleeInfo.second.monitors);
315 }
316}
317
318void ResourceObserverService::onResourceAdded(
319 int uid, int pid, const ResourceList &resources) {
320 notifyObservers(MediaObservableEvent::kBusy, uid, pid, resources);
321}
322
323void ResourceObserverService::onResourceRemoved(
324 int uid, int pid, const ResourceList &resources) {
325 notifyObservers(MediaObservableEvent::kIdle, uid, pid, resources);
326}
327
328} // namespace android