blob: 44fe72d3fd88f61e1631344f71f20555a96e341e [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
30namespace aidl {
31namespace android {
32namespace media {
33bool operator<(const MediaObservableFilter& lhs, const MediaObservableFilter &rhs) {
34 return lhs.type < rhs.type || (lhs.type == rhs.type && lhs.eventFilter < rhs.eventFilter);
35}
36}}} // namespace ::aidl::android::media
37
38namespace android {
39
40using ::aidl::android::media::MediaResourceParcel;
41using ::aidl::android::media::MediaObservableEvent;
42
43// MediaObservableEvent will be used as uint64_t flags.
44static_assert(sizeof(MediaObservableEvent) == sizeof(uint64_t));
45
46static std::vector<MediaObservableEvent> sEvents = {
47 MediaObservableEvent::kBusy,
48 MediaObservableEvent::kIdle,
49};
50
51static MediaObservableType getObservableType(const MediaResourceParcel& res) {
52 if (res.subType == MediaResourceSubType::kVideoCodec) {
53 if (res.type == MediaResourceType::kNonSecureCodec) {
54 return MediaObservableType::kVideoNonSecureCodec;
55 }
56 if (res.type == MediaResourceType::kSecureCodec) {
57 return MediaObservableType::kVideoSecureCodec;
58 }
59 }
60 return MediaObservableType::kInvalid;
61}
62
63//static
64std::mutex ResourceObserverService::sDeathRecipientLock;
65//static
66std::map<uintptr_t, std::shared_ptr<ResourceObserverService::DeathRecipient> >
67ResourceObserverService::sDeathRecipientMap;
68
69struct ResourceObserverService::DeathRecipient {
70 DeathRecipient(ResourceObserverService* _service,
71 const std::shared_ptr<IResourceObserver>& _observer)
72 : service(_service), observer(_observer) {}
73 ~DeathRecipient() {}
74
75 void binderDied() {
76 if (service != nullptr) {
77 service->unregisterObserver(observer);
78 }
79 }
80
81 ResourceObserverService* service;
82 std::shared_ptr<IResourceObserver> observer;
83};
84
85// static
86void ResourceObserverService::BinderDiedCallback(void* cookie) {
87 uintptr_t id = reinterpret_cast<uintptr_t>(cookie);
88
89 ALOGW("Observer %lld is dead", (long long)id);
90
91 std::shared_ptr<DeathRecipient> recipient;
92
93 {
94 std::scoped_lock lock{sDeathRecipientLock};
95
96 auto it = sDeathRecipientMap.find(id);
97 if (it != sDeathRecipientMap.end()) {
98 recipient = it->second;
99 }
100 }
101
102 if (recipient != nullptr) {
103 recipient->binderDied();
104 }
105}
106
107//static
108std::shared_ptr<ResourceObserverService> ResourceObserverService::instantiate() {
109 std::shared_ptr<ResourceObserverService> observerService =
110 ::ndk::SharedRefBase::make<ResourceObserverService>();
111 binder_status_t status = AServiceManager_addService(observerService->asBinder().get(),
112 ResourceObserverService::getServiceName());
113 if (status != STATUS_OK) {
114 return nullptr;
115 }
116 return observerService;
117}
118
119ResourceObserverService::ResourceObserverService()
120 : mDeathRecipient(AIBinder_DeathRecipient_new(BinderDiedCallback)) {}
121
122binder_status_t ResourceObserverService::dump(
123 int fd, const char** /*args*/, uint32_t /*numArgs*/) {
124 String8 result;
125
126 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
127 result.format("Permission Denial: "
128 "can't dump ResourceManagerService from pid=%d, uid=%d\n",
129 AIBinder_getCallingPid(),
130 AIBinder_getCallingUid());
131 write(fd, result.string(), result.size());
132 return PERMISSION_DENIED;
133 }
134
135 result.appendFormat("ResourceObserverService: %p\n", this);
136 result.appendFormat(" Registered Observers: %zu\n", mObserverInfoMap.size());
137
138 {
139 std::scoped_lock lock{mObserverLock};
140
141 for (auto &observer : mObserverInfoMap) {
142 result.appendFormat(" Observer %p:\n", observer.second.binder.get());
143 for (auto &observable : observer.second.filters) {
144 String8 enabledEventsStr;
145 for (auto &event : sEvents) {
146 if (((uint64_t)observable.eventFilter & (uint64_t)event) != 0) {
147 if (!enabledEventsStr.isEmpty()) {
148 enabledEventsStr.append("|");
149 }
150 enabledEventsStr.append(toString(event).c_str());
151 }
152 }
153 result.appendFormat(" %s: %s\n",
154 toString(observable.type).c_str(), enabledEventsStr.c_str());
155 }
156 }
157 }
158
159 write(fd, result.string(), result.size());
160 return OK;
161}
162
163Status ResourceObserverService::registerObserver(
164 const std::shared_ptr<IResourceObserver>& in_observer,
165 const std::vector<MediaObservableFilter>& in_filters) {
Chong Zhang43a6ba62020-10-08 13:43:02 -0700166 if ((getpid() != AIBinder_getCallingPid()) &&
167 checkCallingPermission(
Chong Zhangd9c4faf2020-09-25 11:54:12 -0700168 String16("android.permission.REGISTER_MEDIA_RESOURCE_OBSERVER")) == false) {
169 ALOGE("Permission Denial: "
170 "can't registerObserver from pid=%d, uid=%d\n",
171 AIBinder_getCallingPid(),
172 AIBinder_getCallingUid());
173 return Status::fromServiceSpecificError(PERMISSION_DENIED);
174 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700175
176 ::ndk::SpAIBinder binder = in_observer->asBinder();
177
178 {
179 std::scoped_lock lock{mObserverLock};
180
181 if (mObserverInfoMap.find((uintptr_t)binder.get()) != mObserverInfoMap.end()) {
182 return Status::fromServiceSpecificError(ALREADY_EXISTS);
183 }
184
185 if (in_filters.empty()) {
186 return Status::fromServiceSpecificError(BAD_VALUE);
187 }
188
189 // Add observer info.
190 mObserverInfoMap.emplace((uintptr_t)binder.get(),
191 ObserverInfo{binder, in_observer, in_filters});
192
193 // Add observer to observable->subscribers map.
194 for (auto &filter : in_filters) {
195 for (auto &event : sEvents) {
196 if (!((uint64_t)filter.eventFilter & (uint64_t)event)) {
197 continue;
198 }
199 MediaObservableFilter key{filter.type, event};
200 mObservableToSubscribersMap[key].emplace((uintptr_t)binder.get(), in_observer);
201 }
202 }
203 }
204
205 // Add death binder and link.
206 uintptr_t cookie = (uintptr_t)binder.get();
207 {
208 std::scoped_lock lock{sDeathRecipientLock};
209 sDeathRecipientMap.emplace(
210 cookie, std::make_shared<DeathRecipient>(this, in_observer));
211 }
212
213 AIBinder_linkToDeath(binder.get(), mDeathRecipient.get(),
214 reinterpret_cast<void*>(cookie));
215
216 return Status::ok();
217}
218
219Status ResourceObserverService::unregisterObserver(
220 const std::shared_ptr<IResourceObserver>& in_observer) {
Chong Zhang43a6ba62020-10-08 13:43:02 -0700221 if ((getpid() != AIBinder_getCallingPid()) &&
222 checkCallingPermission(
Chong Zhangd9c4faf2020-09-25 11:54:12 -0700223 String16("android.permission.REGISTER_MEDIA_RESOURCE_OBSERVER")) == false) {
224 ALOGE("Permission Denial: "
225 "can't unregisterObserver from pid=%d, uid=%d\n",
226 AIBinder_getCallingPid(),
227 AIBinder_getCallingUid());
228 return Status::fromServiceSpecificError(PERMISSION_DENIED);
229 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700230
231 ::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