• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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 #define LOG_TAG "CameraOfflineClient"
18 #define ATRACE_TAG ATRACE_TAG_CAMERA
19 //#define LOG_NDEBUG 0
20 
21 #include "CameraOfflineSessionClient.h"
22 #include "utils/CameraThreadState.h"
23 #include <utils/Trace.h>
24 
25 namespace android {
26 
27 using binder::Status;
28 
initialize(sp<CameraProviderManager>,const String8 &)29 status_t CameraOfflineSessionClient::initialize(sp<CameraProviderManager>, const String8&) {
30     ATRACE_CALL();
31 
32     if (mFrameProcessor.get() != nullptr) {
33         // Already initialized
34         return OK;
35     }
36 
37     // Verify ops permissions
38     auto res = startCameraOps();
39     if (res != OK) {
40         return res;
41     }
42 
43     if (mOfflineSession.get() == nullptr) {
44         ALOGE("%s: Camera %s: No valid offline session",
45                 __FUNCTION__, mCameraIdStr.string());
46         return NO_INIT;
47     }
48 
49     String8 threadName;
50     mFrameProcessor = new camera2::FrameProcessorBase(mOfflineSession);
51     threadName = String8::format("Offline-%s-FrameProc", mCameraIdStr.string());
52     res = mFrameProcessor->run(threadName.string());
53     if (res != OK) {
54         ALOGE("%s: Unable to start frame processor thread: %s (%d)",
55                 __FUNCTION__, strerror(-res), res);
56         return res;
57     }
58 
59     mFrameProcessor->registerListener(camera2::FrameProcessorBase::FRAME_PROCESSOR_LISTENER_MIN_ID,
60                                       camera2::FrameProcessorBase::FRAME_PROCESSOR_LISTENER_MAX_ID,
61                                       /*listener*/this,
62                                       /*sendPartials*/true);
63 
64     wp<NotificationListener> weakThis(this);
65     res = mOfflineSession->initialize(weakThis);
66     if (res != OK) {
67         ALOGE("%s: Camera %s: unable to initialize device: %s (%d)",
68                 __FUNCTION__, mCameraIdStr.string(), strerror(-res), res);
69         return res;
70     }
71 
72     for (size_t i = 0; i < mCompositeStreamMap.size(); i++) {
73         mCompositeStreamMap.valueAt(i)->switchToOffline();
74     }
75 
76     return OK;
77 }
78 
setCameraServiceWatchdog(bool)79 status_t CameraOfflineSessionClient::setCameraServiceWatchdog(bool) {
80     return OK;
81 }
82 
setRotateAndCropOverride(uint8_t,bool)83 status_t CameraOfflineSessionClient::setRotateAndCropOverride(uint8_t /*rotateAndCrop*/,
84         bool /*fromHal*/) {
85     // Since we're not submitting more capture requests, changes to rotateAndCrop override
86     // make no difference.
87     return OK;
88 }
89 
setAutoframingOverride(uint8_t)90 status_t CameraOfflineSessionClient::setAutoframingOverride(uint8_t) {
91     return OK;
92 }
93 
supportsCameraMute()94 bool CameraOfflineSessionClient::supportsCameraMute() {
95     // Offline mode doesn't support muting
96     return false;
97 }
98 
setCameraMute(bool)99 status_t CameraOfflineSessionClient::setCameraMute(bool) {
100     return INVALID_OPERATION;
101 }
102 
setStreamUseCaseOverrides(const std::vector<int64_t> &)103 void CameraOfflineSessionClient::setStreamUseCaseOverrides(
104         const std::vector<int64_t>& /*useCaseOverrides*/) {
105 }
106 
clearStreamUseCaseOverrides()107 void CameraOfflineSessionClient::clearStreamUseCaseOverrides() {
108 }
109 
supportsZoomOverride()110 bool CameraOfflineSessionClient::supportsZoomOverride() {
111     return false;
112 }
113 
setZoomOverride(int32_t)114 status_t CameraOfflineSessionClient::setZoomOverride(int32_t /*zoomOverride*/) {
115     return INVALID_OPERATION;
116 }
117 
dump(int fd,const Vector<String16> & args)118 status_t CameraOfflineSessionClient::dump(int fd, const Vector<String16>& args) {
119     return BasicClient::dump(fd, args);
120 }
121 
dumpClient(int fd,const Vector<String16> & args)122 status_t CameraOfflineSessionClient::dumpClient(int fd, const Vector<String16>& args) {
123     String8 result;
124 
125     result = "  Offline session dump:\n";
126     write(fd, result.string(), result.size());
127 
128     if (mOfflineSession.get() == nullptr) {
129         result = "  *** Offline session is detached\n";
130         write(fd, result.string(), result.size());
131         return NO_ERROR;
132     }
133 
134     mFrameProcessor->dump(fd, args);
135 
136     auto res = mOfflineSession->dump(fd);
137     if (res != OK) {
138         result = String8::format("   Error dumping offline session: %s (%d)",
139                 strerror(-res), res);
140         write(fd, result.string(), result.size());
141     }
142 
143     return OK;
144 }
145 
startWatchingTags(const String8 & tags,int outFd)146 status_t CameraOfflineSessionClient::startWatchingTags(const String8 &tags, int outFd) {
147     return BasicClient::startWatchingTags(tags, outFd);
148 }
149 
stopWatchingTags(int outFd)150 status_t CameraOfflineSessionClient::stopWatchingTags(int outFd) {
151     return BasicClient::stopWatchingTags(outFd);
152 }
153 
dumpWatchedEventsToVector(std::vector<std::string> & out)154 status_t CameraOfflineSessionClient::dumpWatchedEventsToVector(std::vector<std::string> &out) {
155     return BasicClient::dumpWatchedEventsToVector(out);
156 }
157 
disconnect()158 binder::Status CameraOfflineSessionClient::disconnect() {
159     Mutex::Autolock icl(mBinderSerializationLock);
160 
161     binder::Status res = Status::ok();
162     if (mDisconnected) {
163         return res;
164     }
165     // Allow both client and the media server to disconnect at all times
166     int callingPid = CameraThreadState::getCallingPid();
167     if (callingPid != mClientPid &&
168             callingPid != mServicePid) {
169         return res;
170     }
171 
172     mDisconnected = true;
173 
174     sCameraService->removeByClient(this);
175     sCameraService->logDisconnectedOffline(mCameraIdStr, mClientPid, String8(mClientPackageName));
176 
177     sp<IBinder> remote = getRemote();
178     if (remote != nullptr) {
179         remote->unlinkToDeath(sCameraService);
180     }
181 
182     mFrameProcessor->removeListener(camera2::FrameProcessorBase::FRAME_PROCESSOR_LISTENER_MIN_ID,
183                                     camera2::FrameProcessorBase::FRAME_PROCESSOR_LISTENER_MAX_ID,
184                                     /*listener*/this);
185     mFrameProcessor->requestExit();
186     mFrameProcessor->join();
187 
188     finishCameraOps();
189     ALOGI("%s: Disconnected client for offline camera %s for PID %d", __FUNCTION__,
190             mCameraIdStr.string(), mClientPid);
191 
192     // client shouldn't be able to call into us anymore
193     mClientPid = 0;
194 
195     if (mOfflineSession.get() != nullptr) {
196         auto ret = mOfflineSession->disconnect();
197         if (ret != OK) {
198             ALOGE("%s: Failed disconnecting from offline session %s (%d)", __FUNCTION__,
199                     strerror(-ret), ret);
200         }
201         mOfflineSession = nullptr;
202     }
203 
204     for (size_t i = 0; i < mCompositeStreamMap.size(); i++) {
205         auto ret = mCompositeStreamMap.valueAt(i)->deleteInternalStreams();
206         if (ret != OK) {
207             ALOGE("%s: Failed removing composite stream  %s (%d)", __FUNCTION__,
208                     strerror(-ret), ret);
209         }
210     }
211     mCompositeStreamMap.clear();
212 
213     return res;
214 }
215 
notifyError(int32_t errorCode,const CaptureResultExtras & resultExtras)216 void CameraOfflineSessionClient::notifyError(int32_t errorCode,
217         const CaptureResultExtras& resultExtras) {
218     // Thread safe. Don't bother locking.
219     // Composites can have multiple internal streams. Error notifications coming from such internal
220     // streams may need to remain within camera service.
221     bool skipClientNotification = false;
222     for (size_t i = 0; i < mCompositeStreamMap.size(); i++) {
223         skipClientNotification |= mCompositeStreamMap.valueAt(i)->onError(errorCode, resultExtras);
224     }
225 
226     if ((mRemoteCallback.get() != nullptr) && (!skipClientNotification)) {
227         mRemoteCallback->onDeviceError(errorCode, resultExtras);
228     }
229 }
230 
startCameraOps()231 status_t CameraOfflineSessionClient::startCameraOps() {
232     ATRACE_CALL();
233     {
234         ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
235               __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
236     }
237 
238     if (mAppOpsManager != nullptr) {
239         // Notify app ops that the camera is not available
240         mOpsCallback = new OpsCallback(this);
241         int32_t res;
242         // TODO : possibly change this to OP_OFFLINE_CAMERA_SESSION
243         mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
244                 mClientPackageName, mOpsCallback);
245         // TODO : possibly change this to OP_OFFLINE_CAMERA_SESSION
246         res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA,
247                 mClientUid, mClientPackageName, /*startIfModeDefault*/ false);
248 
249         if (res == AppOpsManager::MODE_ERRORED) {
250             ALOGI("Offline Camera %s: Access for \"%s\" has been revoked",
251                     mCameraIdStr.string(), String8(mClientPackageName).string());
252             return PERMISSION_DENIED;
253         }
254 
255         // If the calling Uid is trusted (a native service), the AppOpsManager could
256         // return MODE_IGNORED. Do not treat such case as error.
257         if (!mUidIsTrusted && res == AppOpsManager::MODE_IGNORED) {
258             ALOGI("Offline Camera %s: Access for \"%s\" has been restricted",
259                     mCameraIdStr.string(), String8(mClientPackageName).string());
260             // Return the same error as for device policy manager rejection
261             return -EACCES;
262         }
263     }
264 
265     mOpsActive = true;
266 
267     // Transition device state to OPEN
268     sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
269 
270     return OK;
271 }
272 
finishCameraOps()273 status_t CameraOfflineSessionClient::finishCameraOps() {
274     ATRACE_CALL();
275 
276     // Check if startCameraOps succeeded, and if so, finish the camera op
277     if (mOpsActive) {
278         // Notify app ops that the camera is available again
279         if (mAppOpsManager != nullptr) {
280         // TODO : possibly change this to OP_OFFLINE_CAMERA_SESSION
281             mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
282                     mClientPackageName);
283             mOpsActive = false;
284         }
285     }
286     // Always stop watching, even if no camera op is active
287     if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
288         mAppOpsManager->stopWatchingMode(mOpsCallback);
289     }
290     mOpsCallback.clear();
291 
292     sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
293 
294     return OK;
295 }
296 
onResultAvailable(const CaptureResult & result)297 void CameraOfflineSessionClient::onResultAvailable(const CaptureResult& result) {
298     ATRACE_CALL();
299     ALOGV("%s", __FUNCTION__);
300 
301     if (mRemoteCallback.get() != NULL) {
302         mRemoteCallback->onResultReceived(result.mMetadata, result.mResultExtras,
303                 result.mPhysicalMetadatas);
304     }
305 
306     for (size_t i = 0; i < mCompositeStreamMap.size(); i++) {
307         mCompositeStreamMap.valueAt(i)->onResultAvailable(result);
308     }
309 }
310 
notifyShutter(const CaptureResultExtras & resultExtras,nsecs_t timestamp)311 void CameraOfflineSessionClient::notifyShutter(const CaptureResultExtras& resultExtras,
312         nsecs_t timestamp) {
313 
314     if (mRemoteCallback.get() != nullptr) {
315         mRemoteCallback->onCaptureStarted(resultExtras, timestamp);
316     }
317 
318     for (size_t i = 0; i < mCompositeStreamMap.size(); i++) {
319         mCompositeStreamMap.valueAt(i)->onShutter(resultExtras, timestamp);
320     }
321 }
322 
notifyActive(float maxPreviewFps __unused)323 status_t CameraOfflineSessionClient::notifyActive(float maxPreviewFps __unused) {
324     return startCameraStreamingOps();
325 }
326 
notifyIdle(int64_t,int64_t,bool,const std::vector<hardware::CameraStreamStats> &)327 void CameraOfflineSessionClient::notifyIdle(
328         int64_t /*requestCount*/, int64_t /*resultErrorCount*/, bool /*deviceError*/,
329         const std::vector<hardware::CameraStreamStats>& /*streamStats*/) {
330     if (mRemoteCallback.get() != nullptr) {
331         mRemoteCallback->onDeviceIdle();
332     }
333     finishCameraStreamingOps();
334 }
335 
notifyAutoFocus(uint8_t newState,int triggerId)336 void CameraOfflineSessionClient::notifyAutoFocus([[maybe_unused]] uint8_t newState,
337                 [[maybe_unused]] int triggerId) {
338     ALOGV("%s: Autofocus state now %d, last trigger %d",
339           __FUNCTION__, newState, triggerId);
340 }
341 
notifyAutoExposure(uint8_t newState,int triggerId)342 void CameraOfflineSessionClient::notifyAutoExposure([[maybe_unused]] uint8_t newState,
343                 [[maybe_unused]] int triggerId) {
344     ALOGV("%s: Autoexposure state now %d, last trigger %d",
345             __FUNCTION__, newState, triggerId);
346 }
347 
notifyAutoWhitebalance(uint8_t newState,int triggerId)348 void CameraOfflineSessionClient::notifyAutoWhitebalance([[maybe_unused]] uint8_t newState,
349                 [[maybe_unused]] int triggerId) {
350     ALOGV("%s: Auto-whitebalance state now %d, last trigger %d", __FUNCTION__, newState,
351             triggerId);
352 }
353 
notifyPrepared(int)354 void CameraOfflineSessionClient::notifyPrepared(int /*streamId*/) {
355     ALOGE("%s: Unexpected stream prepare notification in offline mode!", __FUNCTION__);
356     notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
357                 CaptureResultExtras());
358 }
359 
notifyRequestQueueEmpty()360 void CameraOfflineSessionClient::notifyRequestQueueEmpty() {
361     if (mRemoteCallback.get() != nullptr) {
362         mRemoteCallback->onRequestQueueEmpty();
363     }
364 }
365 
notifyRepeatingRequestError(long)366 void CameraOfflineSessionClient::notifyRepeatingRequestError(long /*lastFrameNumber*/) {
367     ALOGE("%s: Unexpected repeating request error in offline mode!", __FUNCTION__);
368     notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
369                 CaptureResultExtras());
370 }
371 
injectCamera(const String8 & injectedCamId,sp<CameraProviderManager> manager)372 status_t CameraOfflineSessionClient::injectCamera(const String8& injectedCamId,
373             sp<CameraProviderManager> manager) {
374     ALOGV("%s: This client doesn't support the injection camera. injectedCamId: %s providerPtr: %p",
375             __FUNCTION__, injectedCamId.string(), manager.get());
376 
377     return OK;
378 }
379 
stopInjection()380 status_t CameraOfflineSessionClient::stopInjection() {
381     ALOGV("%s: This client doesn't support the injection camera.", __FUNCTION__);
382 
383     return OK;
384 }
385 
386 // ----------------------------------------------------------------------------
387 }; // namespace android
388