blob: a4b6ce7d3526ff94363021d22070ce9614e0920f [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 Zhangd9c4faf2020-09-25 11:54:12 -0700166 if (checkCallingPermission(
167 String16("android.permission.REGISTER_MEDIA_RESOURCE_OBSERVER")) == false) {
168 ALOGE("Permission Denial: "
169 "can't registerObserver from pid=%d, uid=%d\n",
170 AIBinder_getCallingPid(),
171 AIBinder_getCallingUid());
172 return Status::fromServiceSpecificError(PERMISSION_DENIED);
173 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700174
175 ::ndk::SpAIBinder binder = in_observer->asBinder();
176
177 {
178 std::scoped_lock lock{mObserverLock};
179
180 if (mObserverInfoMap.find((uintptr_t)binder.get()) != mObserverInfoMap.end()) {
181 return Status::fromServiceSpecificError(ALREADY_EXISTS);
182 }
183
184 if (in_filters.empty()) {
185 return Status::fromServiceSpecificError(BAD_VALUE);
186 }
187
188 // Add observer info.
189 mObserverInfoMap.emplace((uintptr_t)binder.get(),
190 ObserverInfo{binder, in_observer, in_filters});
191
192 // Add observer to observable->subscribers map.
193 for (auto &filter : in_filters) {
194 for (auto &event : sEvents) {
195 if (!((uint64_t)filter.eventFilter & (uint64_t)event)) {
196 continue;
197 }
198 MediaObservableFilter key{filter.type, event};
199 mObservableToSubscribersMap[key].emplace((uintptr_t)binder.get(), in_observer);
200 }
201 }
202 }
203
204 // Add death binder and link.
205 uintptr_t cookie = (uintptr_t)binder.get();
206 {
207 std::scoped_lock lock{sDeathRecipientLock};
208 sDeathRecipientMap.emplace(
209 cookie, std::make_shared<DeathRecipient>(this, in_observer));
210 }
211
212 AIBinder_linkToDeath(binder.get(), mDeathRecipient.get(),
213 reinterpret_cast<void*>(cookie));
214
215 return Status::ok();
216}
217
218Status ResourceObserverService::unregisterObserver(
219 const std::shared_ptr<IResourceObserver>& in_observer) {
Chong Zhangd9c4faf2020-09-25 11:54:12 -0700220 if (checkCallingPermission(
221 String16("android.permission.REGISTER_MEDIA_RESOURCE_OBSERVER")) == false) {
222 ALOGE("Permission Denial: "
223 "can't unregisterObserver from pid=%d, uid=%d\n",
224 AIBinder_getCallingPid(),
225 AIBinder_getCallingUid());
226 return Status::fromServiceSpecificError(PERMISSION_DENIED);
227 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700228
229 ::ndk::SpAIBinder binder = in_observer->asBinder();
230
231 {
232 std::scoped_lock lock{mObserverLock};
233
234 auto it = mObserverInfoMap.find((uintptr_t)binder.get());
235 if (it == mObserverInfoMap.end()) {
236 return Status::fromServiceSpecificError(NAME_NOT_FOUND);
237 }
238
239 // Remove observer from observable->subscribers map.
240 for (auto &filter : it->second.filters) {
241 for (auto &event : sEvents) {
242 if (!((uint64_t)filter.eventFilter & (uint64_t)event)) {
243 continue;
244 }
245 MediaObservableFilter key{filter.type, event};
246 mObservableToSubscribersMap[key].erase((uintptr_t)binder.get());
247
248 //Remove the entry if there's no more subscribers.
249 if (mObservableToSubscribersMap[key].empty()) {
250 mObservableToSubscribersMap.erase(key);
251 }
252 }
253 }
254
255 // Remove observer info.
256 mObserverInfoMap.erase(it);
257 }
258
259 // Unlink and remove death binder.
260 uintptr_t cookie = (uintptr_t)binder.get();
261 AIBinder_unlinkToDeath(binder.get(), mDeathRecipient.get(),
262 reinterpret_cast<void*>(cookie));
263
264 {
265 std::scoped_lock lock{sDeathRecipientLock};
266 sDeathRecipientMap.erase(cookie);
267 }
268
269 return Status::ok();
270}
271
272void ResourceObserverService::notifyObservers(
273 MediaObservableEvent event, int uid, int pid, const ResourceList &resources) {
274 struct CalleeInfo {
275 std::shared_ptr<IResourceObserver> observer;
276 std::vector<MediaObservableParcel> monitors;
277 };
278 // Build a consolidated list of observers to call with their respective observables.
279 std::map<uintptr_t, CalleeInfo> calleeList;
280
281 {
282 std::scoped_lock lock{mObserverLock};
283
284 for (auto &res : resources) {
285 // Skip if this resource doesn't map to any observable type.
286 MediaObservableType observableType = getObservableType(res.second);
287 if (observableType == MediaObservableType::kInvalid) {
288 continue;
289 }
290 MediaObservableFilter key{observableType, event};
291 // Skip if no one subscribed to this observable.
292 auto observableIt = mObservableToSubscribersMap.find(key);
293 if (observableIt == mObservableToSubscribersMap.end()) {
294 continue;
295 }
296 // Loop through all subsribers.
297 for (auto &subscriber : observableIt->second) {
298 auto calleeIt = calleeList.find(subscriber.first);
299 if (calleeIt == calleeList.end()) {
300 calleeList.emplace(subscriber.first, CalleeInfo{
301 subscriber.second, {{observableType, res.second.value}}});
302 } else {
303 calleeIt->second.monitors.push_back({observableType, res.second.value});
304 }
305 }
306 }
307 }
308
309 // Finally call the observers about the status change.
310 for (auto &calleeInfo : calleeList) {
311 calleeInfo.second.observer->onStatusChanged(
312 event, uid, pid, calleeInfo.second.monitors);
313 }
314}
315
316void ResourceObserverService::onResourceAdded(
317 int uid, int pid, const ResourceList &resources) {
318 notifyObservers(MediaObservableEvent::kBusy, uid, pid, resources);
319}
320
321void ResourceObserverService::onResourceRemoved(
322 int uid, int pid, const ResourceList &resources) {
323 notifyObservers(MediaObservableEvent::kIdle, uid, pid, resources);
324}
325
326} // namespace android