• 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/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 and/or open camera
38     auto res = notifyCameraOpening();
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 != mCallingPid &&
167             callingPid != mServicePid) {
168         return res;
169     }
170 
171     mDisconnected = true;
172 
173     sCameraService->removeByClient(this);
174     sCameraService->logDisconnectedOffline(mCameraIdStr, mCallingPid, getPackageName());
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     notifyCameraClosing();
188     ALOGI("%s: Disconnected client for offline camera %s for PID %d", __FUNCTION__,
189             mCameraIdStr.c_str(), mCallingPid);
190 
191     // client shouldn't be able to call into us anymore
192     mCallingPid = 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 
notifyCameraOpening()230 status_t CameraOfflineSessionClient::notifyCameraOpening() {
231     ATRACE_CALL();
232     {
233         ALOGV("%s: Notify camera opening, package name = %s, client UID = %d", __FUNCTION__,
234               getPackageName().c_str(), getClientUid());
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, toString16(getPackageName()),
243                                           mOpsCallback);
244         // TODO : possibly change this to OP_OFFLINE_CAMERA_SESSION
245         res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, getClientUid(),
246                                              toString16(getPackageName()),
247                                              /*startIfModeDefault*/ false);
248 
249         if (res == AppOpsManager::MODE_ERRORED) {
250             ALOGI("Offline Camera %s: Access for \"%s\" has been revoked", mCameraIdStr.c_str(),
251                   getPackageName().c_str());
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", mCameraIdStr.c_str(),
259                   getPackageName().c_str());
260             // Return the same error as for device policy manager rejection
261             return -EACCES;
262         }
263     }
264 
265     mCameraOpen = true;
266 
267     // Transition device state to OPEN
268     sCameraService->mUidPolicy->registerMonitorUid(getClientUid(), /*openCamera*/ true);
269 
270     return OK;
271 }
272 
notifyCameraClosing()273 status_t CameraOfflineSessionClient::notifyCameraClosing() {
274     ATRACE_CALL();
275 
276     // Check if notifyCameraOpening succeeded, and if so, finish the camera op if necessary
277     if (mCameraOpen) {
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, getClientUid(),
282                                      toString16(getPackageName()));
283             mCameraOpen = 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(getClientUid(), /*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         using hardware::camera2::CameraMetadataInfo;
303         CameraMetadataInfo resultInfo;
304         resultInfo.set<CameraMetadataInfo::metadata>(result.mMetadata);
305         mRemoteCallback->onResultReceived(resultInfo, result.mResultExtras,
306                 result.mPhysicalMetadatas);
307     }
308 
309     for (size_t i = 0; i < mCompositeStreamMap.size(); i++) {
310         mCompositeStreamMap.valueAt(i)->onResultAvailable(result);
311     }
312 }
313 
notifyClientSharedAccessPriorityChanged(bool)314 void CameraOfflineSessionClient::notifyClientSharedAccessPriorityChanged(bool /*primaryClient*/) {
315 }
316 
notifyShutter(const CaptureResultExtras & resultExtras,nsecs_t timestamp)317 void CameraOfflineSessionClient::notifyShutter(const CaptureResultExtras& resultExtras,
318         nsecs_t timestamp) {
319 
320     if (mRemoteCallback.get() != nullptr) {
321         mRemoteCallback->onCaptureStarted(resultExtras, timestamp);
322     }
323 
324     for (size_t i = 0; i < mCompositeStreamMap.size(); i++) {
325         mCompositeStreamMap.valueAt(i)->onShutter(resultExtras, timestamp);
326     }
327 }
328 
notifyActive(float maxPreviewFps __unused)329 status_t CameraOfflineSessionClient::notifyActive(float maxPreviewFps __unused) {
330     return startCameraStreamingOps();
331 }
332 
notifyIdle(int64_t,int64_t,bool,std::pair<int32_t,int32_t>,const std::vector<hardware::CameraStreamStats> &)333 void CameraOfflineSessionClient::notifyIdle(
334         int64_t /*requestCount*/, int64_t /*resultErrorCount*/, bool /*deviceError*/,
335         std::pair<int32_t, int32_t> /*mostRequestedFpsRange*/,
336         const std::vector<hardware::CameraStreamStats>& /*streamStats*/) {
337     if (mRemoteCallback.get() != nullptr) {
338         mRemoteCallback->onDeviceIdle();
339     }
340     finishCameraStreamingOps();
341 }
342 
notifyAutoFocus(uint8_t newState,int triggerId)343 void CameraOfflineSessionClient::notifyAutoFocus([[maybe_unused]] uint8_t newState,
344                 [[maybe_unused]] int triggerId) {
345     ALOGV("%s: Autofocus state now %d, last trigger %d",
346           __FUNCTION__, newState, triggerId);
347 }
348 
notifyAutoExposure(uint8_t newState,int triggerId)349 void CameraOfflineSessionClient::notifyAutoExposure([[maybe_unused]] uint8_t newState,
350                 [[maybe_unused]] int triggerId) {
351     ALOGV("%s: Autoexposure state now %d, last trigger %d",
352             __FUNCTION__, newState, triggerId);
353 }
354 
notifyAutoWhitebalance(uint8_t newState,int triggerId)355 void CameraOfflineSessionClient::notifyAutoWhitebalance([[maybe_unused]] uint8_t newState,
356                 [[maybe_unused]] int triggerId) {
357     ALOGV("%s: Auto-whitebalance state now %d, last trigger %d", __FUNCTION__, newState,
358             triggerId);
359 }
360 
notifyPrepared(int)361 void CameraOfflineSessionClient::notifyPrepared(int /*streamId*/) {
362     ALOGE("%s: Unexpected stream prepare notification in offline mode!", __FUNCTION__);
363     notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
364                 CaptureResultExtras());
365 }
366 
notifyRequestQueueEmpty()367 void CameraOfflineSessionClient::notifyRequestQueueEmpty() {
368     if (mRemoteCallback.get() != nullptr) {
369         mRemoteCallback->onRequestQueueEmpty();
370     }
371 }
372 
notifyRepeatingRequestError(long)373 void CameraOfflineSessionClient::notifyRepeatingRequestError(long /*lastFrameNumber*/) {
374     ALOGE("%s: Unexpected repeating request error in offline mode!", __FUNCTION__);
375     notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
376                 CaptureResultExtras());
377 }
378 
injectCamera(const std::string & injectedCamId,sp<CameraProviderManager> manager)379 status_t CameraOfflineSessionClient::injectCamera(const std::string& injectedCamId,
380             sp<CameraProviderManager> manager) {
381     ALOGV("%s: This client doesn't support the injection camera. injectedCamId: %s providerPtr: %p",
382             __FUNCTION__, injectedCamId.c_str(), manager.get());
383 
384     return OK;
385 }
386 
stopInjection()387 status_t CameraOfflineSessionClient::stopInjection() {
388     ALOGV("%s: This client doesn't support the injection camera.", __FUNCTION__);
389 
390     return OK;
391 }
392 
injectSessionParams(const hardware::camera2::impl::CameraMetadataNative & sessionParams)393 status_t CameraOfflineSessionClient::injectSessionParams(
394         const hardware::camera2::impl::CameraMetadataNative& sessionParams) {
395     ALOGV("%s: This client doesn't support the injecting session parameters camera.",
396             __FUNCTION__);
397     (void)sessionParams;
398     return OK;
399 }
400 // ----------------------------------------------------------------------------
401 }; // namespace android
402