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