1 /*
2 * Copyright (C) 2018 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_NDEBUG 0
18 #define LOG_TAG "ACameraDeviceVendor"
19
20 #include <vector>
21 #include <inttypes.h>
22 #include <android/frameworks/cameraservice/service/2.0/ICameraService.h>
23 #include <android/frameworks/cameraservice/device/2.0/types.h>
24 #include <CameraMetadata.h>
25
26 #include "ndk_vendor/impl/ACameraDevice.h"
27 #include "ACameraCaptureSession.h"
28 #include "ACameraMetadata.h"
29 #include "ACaptureRequest.h"
30 #include "utils.h"
31
32 #include "ACameraCaptureSession.inc"
33
34 #define CHECK_TRANSACTION_AND_RET(remoteRet, status, callName) \
35 if (!remoteRet.isOk()) { \
36 ALOGE("%s: Transaction error during %s call %s", __FUNCTION__, callName, \
37 remoteRet.description().c_str()); \
38 return ACAMERA_ERROR_UNKNOWN; \
39 } \
40 if (status != Status::NO_ERROR) { \
41 ALOGE("%s: %s call failed", __FUNCTION__, callName); \
42 return utils::convertFromHidl(status); \
43 }
44
45 using namespace android;
46
~ACameraDevice()47 ACameraDevice::~ACameraDevice() {
48 mDevice->stopLooper();
49 }
50
51 namespace android {
52 namespace acam {
53
54 using HCameraMetadata = frameworks::cameraservice::device::V2_0::CameraMetadata;
55 using OutputConfiguration = frameworks::cameraservice::device::V2_0::OutputConfiguration;
56 using SessionConfiguration = frameworks::cameraservice::device::V2_0::SessionConfiguration;
57 using hardware::Void;
58
59 // Static member definitions
60 const char* CameraDevice::kContextKey = "Context";
61 const char* CameraDevice::kDeviceKey = "Device";
62 const char* CameraDevice::kErrorCodeKey = "ErrorCode";
63 const char* CameraDevice::kCallbackFpKey = "Callback";
64 const char* CameraDevice::kSessionSpKey = "SessionSp";
65 const char* CameraDevice::kCaptureRequestKey = "CaptureRequest";
66 const char* CameraDevice::kTimeStampKey = "TimeStamp";
67 const char* CameraDevice::kCaptureResultKey = "CaptureResult";
68 const char* CameraDevice::kPhysicalCaptureResultKey = "PhysicalCaptureResult";
69 const char* CameraDevice::kCaptureFailureKey = "CaptureFailure";
70 const char* CameraDevice::kSequenceIdKey = "SequenceId";
71 const char* CameraDevice::kFrameNumberKey = "FrameNumber";
72 const char* CameraDevice::kAnwKey = "Anw";
73 const char* CameraDevice::kFailingPhysicalCameraId= "FailingPhysicalCameraId";
74
75 /**
76 * CameraDevice Implementation
77 */
CameraDevice(const char * id,ACameraDevice_StateCallbacks * cb,sp<ACameraMetadata> chars,ACameraDevice * wrapper)78 CameraDevice::CameraDevice(
79 const char* id,
80 ACameraDevice_StateCallbacks* cb,
81 sp<ACameraMetadata> chars,
82 ACameraDevice* wrapper) :
83 mCameraId(id),
84 mAppCallbacks(*cb),
85 mChars(std::move(chars)),
86 mServiceCallback(new ServiceCallback(this)),
87 mWrapper(wrapper),
88 mInError(false),
89 mError(ACAMERA_OK),
90 mIdle(true),
91 mCurrentSession(nullptr) {
92 mClosing = false;
93 // Setup looper thread to perfrom device callbacks to app
94 mCbLooper = new ALooper;
95 mCbLooper->setName("C2N-dev-looper");
96 status_t err = mCbLooper->start(
97 /*runOnCallingThread*/false,
98 /*canCallJava*/ true,
99 PRIORITY_DEFAULT);
100 if (err != OK) {
101 ALOGE("%s: Unable to start camera device callback looper: %s (%d)",
102 __FUNCTION__, strerror(-err), err);
103 setCameraDeviceErrorLocked(ACAMERA_ERROR_CAMERA_DEVICE);
104 }
105 mHandler = new CallbackHandler(id);
106 mCbLooper->registerHandler(mHandler);
107
108 const CameraMetadata& metadata = mChars->getInternalData();
109 camera_metadata_ro_entry entry = metadata.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
110 if (entry.count != 1) {
111 ALOGW("%s: bad count %zu for partial result count", __FUNCTION__, entry.count);
112 mPartialResultCount = 1;
113 } else {
114 mPartialResultCount = entry.data.i32[0];
115 }
116
117 entry = metadata.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
118 if (entry.count != 2) {
119 ALOGW("%s: bad count %zu for shading map size", __FUNCTION__, entry.count);
120 mShadingMapSize[0] = 0;
121 mShadingMapSize[1] = 0;
122 } else {
123 mShadingMapSize[0] = entry.data.i32[0];
124 mShadingMapSize[1] = entry.data.i32[1];
125 }
126 }
127
128 // Device close implementaiton
~CameraDevice()129 CameraDevice::~CameraDevice() {
130 sp<ACameraCaptureSession> session = mCurrentSession.promote();
131 {
132 Mutex::Autolock _l(mDeviceLock);
133 if (!isClosed()) {
134 disconnectLocked(session);
135 }
136 mCurrentSession = nullptr;
137 LOG_ALWAYS_FATAL_IF(mCbLooper != nullptr,
138 "CameraDevice looper should've been stopped before ~CameraDevice");
139 }
140 }
141
142 void
postSessionMsgAndCleanup(sp<AMessage> & msg)143 CameraDevice::postSessionMsgAndCleanup(sp<AMessage>& msg) {
144 msg->post();
145 msg.clear();
146 sp<AMessage> cleanupMsg = new AMessage(kWhatCleanUpSessions, mHandler);
147 cleanupMsg->post();
148 }
149
150 // TODO: cached created request?
151 camera_status_t
createCaptureRequest(ACameraDevice_request_template templateId,const ACameraIdList * physicalCameraIdList,ACaptureRequest ** request) const152 CameraDevice::createCaptureRequest(
153 ACameraDevice_request_template templateId,
154 const ACameraIdList* physicalCameraIdList,
155 ACaptureRequest** request) const {
156 Mutex::Autolock _l(mDeviceLock);
157 camera_status_t ret = checkCameraClosedOrErrorLocked();
158 if (ret != ACAMERA_OK) {
159 return ret;
160 }
161 if (mRemote == nullptr) {
162 return ACAMERA_ERROR_CAMERA_DISCONNECTED;
163 }
164 CameraMetadata rawRequest;
165 Status status = Status::UNKNOWN_ERROR;
166 auto remoteRet = mRemote->createDefaultRequest(
167 utils::convertToHidl(templateId),
168 [&status, &rawRequest](auto s, const hidl_vec<uint8_t> &metadata) {
169 status = s;
170 if (status == Status::NO_ERROR && utils::convertFromHidlCloned(metadata, &rawRequest)) {
171 } else {
172 ALOGE("%s: Couldn't create default request", __FUNCTION__);
173 }
174 });
175 CHECK_TRANSACTION_AND_RET(remoteRet, status, "createDefaultRequest()")
176 ACaptureRequest* outReq = new ACaptureRequest();
177 outReq->settings = new ACameraMetadata(rawRequest.release(), ACameraMetadata::ACM_REQUEST);
178 if (physicalCameraIdList != nullptr) {
179 for (auto i = 0; i < physicalCameraIdList->numCameras; i++) {
180 outReq->physicalSettings.emplace(physicalCameraIdList->cameraIds[i],
181 new ACameraMetadata(*(outReq->settings)));
182 }
183 }
184 outReq->targets = new ACameraOutputTargets();
185 *request = outReq;
186 return ACAMERA_OK;
187 }
188
189 camera_status_t
createCaptureSession(const ACaptureSessionOutputContainer * outputs,const ACaptureRequest * sessionParameters,const ACameraCaptureSession_stateCallbacks * callbacks,ACameraCaptureSession ** session)190 CameraDevice::createCaptureSession(
191 const ACaptureSessionOutputContainer* outputs,
192 const ACaptureRequest* sessionParameters,
193 const ACameraCaptureSession_stateCallbacks* callbacks,
194 /*out*/ACameraCaptureSession** session) {
195 sp<ACameraCaptureSession> currentSession = mCurrentSession.promote();
196 Mutex::Autolock _l(mDeviceLock);
197 camera_status_t ret = checkCameraClosedOrErrorLocked();
198 if (ret != ACAMERA_OK) {
199 return ret;
200 }
201
202 if (currentSession != nullptr) {
203 currentSession->closeByDevice();
204 stopRepeatingLocked();
205 }
206
207 // Create new session
208 ret = configureStreamsLocked(outputs, sessionParameters);
209 if (ret != ACAMERA_OK) {
210 ALOGE("Fail to create new session. cannot configure streams");
211 return ret;
212 }
213
214 ACameraCaptureSession* newSession = new ACameraCaptureSession(
215 mNextSessionId++, outputs, callbacks, this);
216
217 // set new session as current session
218 newSession->incStrong((void *) ACameraDevice_createCaptureSession);
219 mCurrentSession = newSession;
220 mFlushing = false;
221 *session = newSession;
222 return ACAMERA_OK;
223 }
224
isSessionConfigurationSupported(const ACaptureSessionOutputContainer * sessionOutputContainer) const225 camera_status_t CameraDevice::isSessionConfigurationSupported(
226 const ACaptureSessionOutputContainer* sessionOutputContainer) const {
227 Mutex::Autolock _l(mDeviceLock);
228 camera_status_t ret = checkCameraClosedOrErrorLocked();
229 if (ret != ACAMERA_OK) {
230 return ret;
231 }
232
233 SessionConfiguration sessionConfig;
234 sessionConfig.inputWidth = 0;
235 sessionConfig.inputHeight = 0;
236 sessionConfig.inputFormat = -1;
237 sessionConfig.operationMode = StreamConfigurationMode::NORMAL_MODE;
238 sessionConfig.outputStreams.resize(sessionOutputContainer->mOutputs.size());
239 size_t index = 0;
240 for (const auto& output : sessionOutputContainer->mOutputs) {
241 sessionConfig.outputStreams[index].rotation = utils::convertToHidl(output.mRotation);
242 sessionConfig.outputStreams[index].windowGroupId = -1;
243 sessionConfig.outputStreams[index].windowHandles.resize(output.mSharedWindows.size() + 1);
244 sessionConfig.outputStreams[index].windowHandles[0] = output.mWindow;
245 sessionConfig.outputStreams[index].physicalCameraId = output.mPhysicalCameraId;
246 index++;
247 }
248
249 bool configSupported = false;
250 Status status = Status::UNKNOWN_ERROR;
251 auto remoteRet = mRemote->isSessionConfigurationSupported(sessionConfig,
252 [&status, &configSupported](auto s, auto supported) {
253 status = s;
254 configSupported = supported;
255 });
256
257 CHECK_TRANSACTION_AND_RET(remoteRet, status, "isSessionConfigurationSupported()");
258 return configSupported ? ACAMERA_OK : ACAMERA_ERROR_STREAM_CONFIGURE_FAIL;
259 }
260
addMetadataToPhysicalCameraSettings(const CameraMetadata * metadata,const std::string & cameraId,PhysicalCameraSettings * physicalCameraSettings)261 static void addMetadataToPhysicalCameraSettings(const CameraMetadata *metadata,
262 const std::string &cameraId, PhysicalCameraSettings *physicalCameraSettings) {
263 CameraMetadata metadataCopy = *metadata;
264 camera_metadata_t *camera_metadata = metadataCopy.release();
265 HCameraMetadata hCameraMetadata;
266 utils::convertToHidl(camera_metadata, &hCameraMetadata, /*shouldOwn*/ true);
267 physicalCameraSettings->settings.metadata(std::move(hCameraMetadata));
268 physicalCameraSettings->id = cameraId;
269 }
270
addRequestSettingsMetadata(ACaptureRequest * aCaptureRequest,sp<CaptureRequest> & req)271 void CameraDevice::addRequestSettingsMetadata(ACaptureRequest *aCaptureRequest,
272 sp<CaptureRequest> &req) {
273 req->mPhysicalCameraSettings.resize(1 + aCaptureRequest->physicalSettings.size());
274 addMetadataToPhysicalCameraSettings(&(aCaptureRequest->settings->getInternalData()), getId(),
275 &(req->mPhysicalCameraSettings[0]));
276 size_t i = 1;
277 for (auto &physicalSetting : aCaptureRequest->physicalSettings) {
278 addMetadataToPhysicalCameraSettings(&(physicalSetting.second->getInternalData()),
279 physicalSetting.first, &(req->mPhysicalCameraSettings[i]));
280 i++;
281 }
282 }
283
updateOutputConfigurationLocked(ACaptureSessionOutput * output)284 camera_status_t CameraDevice::updateOutputConfigurationLocked(ACaptureSessionOutput *output) {
285 camera_status_t ret = checkCameraClosedOrErrorLocked();
286 if (ret != ACAMERA_OK) {
287 return ret;
288 }
289
290 if (output == nullptr) {
291 return ACAMERA_ERROR_INVALID_PARAMETER;
292 }
293
294 if (!output->mIsShared) {
295 ALOGE("Error output configuration is not shared");
296 return ACAMERA_ERROR_INVALID_OPERATION;
297 }
298
299 int32_t streamId = -1;
300 for (auto& kvPair : mConfiguredOutputs) {
301 if (utils::isWindowNativeHandleEqual(kvPair.second.first, output->mWindow)) {
302 streamId = kvPair.first;
303 break;
304 }
305 }
306 if (streamId < 0) {
307 ALOGE("Error: Invalid output configuration");
308 return ACAMERA_ERROR_INVALID_PARAMETER;
309 }
310
311 OutputConfigurationWrapper outConfigW;
312 OutputConfiguration &outConfig = outConfigW.mOutputConfiguration;
313 outConfig.rotation = utils::convertToHidl(output->mRotation);
314 outConfig.windowHandles.resize(output->mSharedWindows.size() + 1);
315 outConfig.windowHandles[0] = output->mWindow;
316 outConfig.physicalCameraId = output->mPhysicalCameraId;
317 int i = 1;
318 for (auto& anw : output->mSharedWindows) {
319 outConfig.windowHandles[i++] = anw;
320 }
321
322 auto remoteRet = mRemote->updateOutputConfiguration(streamId, outConfig);
323 if (!remoteRet.isOk()) {
324 ALOGE("%s: Transaction error in updating OutputConfiguration: %s", __FUNCTION__,
325 remoteRet.description().c_str());
326 return ACAMERA_ERROR_UNKNOWN;
327 }
328
329 switch (remoteRet) {
330 case Status::NO_ERROR:
331 break;
332 case Status::INVALID_OPERATION:
333 ALOGE("Camera device %s invalid operation", getId());
334 return ACAMERA_ERROR_INVALID_OPERATION;
335 case Status::ALREADY_EXISTS:
336 ALOGE("Camera device %s output surface already exists", getId());
337 return ACAMERA_ERROR_INVALID_PARAMETER;
338 case Status::ILLEGAL_ARGUMENT:
339 ALOGE("Camera device %s invalid input argument", getId());
340 return ACAMERA_ERROR_INVALID_PARAMETER;
341 default:
342 ALOGE("Camera device %s failed to add shared output", getId());
343 return ACAMERA_ERROR_UNKNOWN;
344 }
345
346 mConfiguredOutputs[streamId] = std::make_pair(output->mWindow, outConfigW);
347
348 return ACAMERA_OK;
349 }
350
351 camera_status_t
allocateCaptureRequestLocked(const ACaptureRequest * request,sp<CaptureRequest> & outReq)352 CameraDevice::allocateCaptureRequestLocked(
353 const ACaptureRequest* request, /*out*/sp<CaptureRequest> &outReq) {
354 sp<CaptureRequest> req(new CaptureRequest());
355 req->mCaptureRequest.physicalCameraSettings.resize(1 + request->physicalSettings.size());
356
357 size_t index = 0;
358 allocateOneCaptureRequestMetadata(
359 req->mCaptureRequest.physicalCameraSettings[index++], mCameraId, request->settings);
360
361 for (auto& physicalEntry : request->physicalSettings) {
362 allocateOneCaptureRequestMetadata(
363 req->mCaptureRequest.physicalCameraSettings[index++],
364 physicalEntry.first, physicalEntry.second);
365 }
366
367 std::vector<int32_t> requestStreamIdxList;
368 std::vector<int32_t> requestSurfaceIdxList;
369 for (auto outputTarget : request->targets->mOutputs) {
370 native_handle_t* anw = outputTarget.mWindow;
371 bool found = false;
372 req->mSurfaceList.push_back(anw);
373 // lookup stream/surface ID
374 for (const auto& kvPair : mConfiguredOutputs) {
375 int streamId = kvPair.first;
376 const OutputConfigurationWrapper& outConfig = kvPair.second.second;
377 const auto& windowHandles = outConfig.mOutputConfiguration.windowHandles;
378 for (int surfaceId = 0; surfaceId < (int) windowHandles.size(); surfaceId++) {
379 // If two native handles are equivalent, so are their surfaces.
380 if (utils::isWindowNativeHandleEqual(windowHandles[surfaceId].getNativeHandle(),
381 anw)) {
382 found = true;
383 requestStreamIdxList.push_back(streamId);
384 requestSurfaceIdxList.push_back(surfaceId);
385 break;
386 }
387 }
388 if (found) {
389 break;
390 }
391 }
392 if (!found) {
393 ALOGE("Unconfigured output target %p in capture request!", anw);
394 return ACAMERA_ERROR_INVALID_PARAMETER;
395 }
396 }
397 req->mCaptureRequest.streamAndWindowIds.resize(requestStreamIdxList.size());
398 for (int i = 0; i < requestStreamIdxList.size(); i++) {
399 req->mCaptureRequest.streamAndWindowIds[i].streamId = requestStreamIdxList[i];
400 req->mCaptureRequest.streamAndWindowIds[i].windowId = requestSurfaceIdxList[i];
401 }
402 outReq = req;
403 return ACAMERA_OK;
404 }
405
allocateOneCaptureRequestMetadata(PhysicalCameraSettings & cameraSettings,const std::string & id,const sp<ACameraMetadata> & metadata)406 void CameraDevice::allocateOneCaptureRequestMetadata(
407 PhysicalCameraSettings& cameraSettings,
408 const std::string& id, const sp<ACameraMetadata>& metadata) {
409 cameraSettings.id = id;
410 // TODO: Do we really need to copy the metadata here ?
411 CameraMetadata metadataCopy = metadata->getInternalData();
412 camera_metadata_t *cameraMetadata = metadataCopy.release();
413 HCameraMetadata hCameraMetadata;
414 utils::convertToHidl(cameraMetadata, &hCameraMetadata, true);
415 if (metadata != nullptr) {
416 if (hCameraMetadata.data() != nullptr &&
417 mCaptureRequestMetadataQueue != nullptr &&
418 mCaptureRequestMetadataQueue->write(
419 reinterpret_cast<const uint8_t *>(hCameraMetadata.data()),
420 hCameraMetadata.size())) {
421 // The metadata field of the union would've been destructued, so no need
422 // to re-size it.
423 cameraSettings.settings.fmqMetadataSize(hCameraMetadata.size());
424 } else {
425 ALOGE("Fmq write capture result failed, falling back to hwbinder");
426 cameraSettings.settings.metadata(std::move(hCameraMetadata));
427 }
428 }
429 }
430
431
432 ACaptureRequest*
allocateACaptureRequest(sp<CaptureRequest> & req,const char * deviceId)433 CameraDevice::allocateACaptureRequest(sp<CaptureRequest>& req, const char* deviceId) {
434 ACaptureRequest* pRequest = new ACaptureRequest();
435 for (size_t i = 0; i < req->mPhysicalCameraSettings.size(); i++) {
436 const std::string& id = req->mPhysicalCameraSettings[i].id;
437 CameraMetadata clone;
438 utils::convertFromHidlCloned(req->mPhysicalCameraSettings[i].settings.metadata(), &clone);
439 camera_metadata_t *clonep = clone.release();
440 if (id == deviceId) {
441 pRequest->settings = new ACameraMetadata(clonep, ACameraMetadata::ACM_REQUEST);
442 } else {
443 pRequest->physicalSettings[req->mPhysicalCameraSettings[i].id] =
444 new ACameraMetadata(clonep, ACameraMetadata::ACM_REQUEST);
445 }
446 }
447 pRequest->targets = new ACameraOutputTargets();
448 for (size_t i = 0; i < req->mSurfaceList.size(); i++) {
449 native_handle_t* anw = req->mSurfaceList[i];
450 ACameraOutputTarget outputTarget(anw);
451 pRequest->targets->mOutputs.insert(outputTarget);
452 }
453 return pRequest;
454 }
455
456 void
freeACaptureRequest(ACaptureRequest * req)457 CameraDevice::freeACaptureRequest(ACaptureRequest* req) {
458 if (req == nullptr) {
459 return;
460 }
461 req->settings.clear();
462 delete req->targets;
463 delete req;
464 }
465
466 void
notifySessionEndOfLifeLocked(ACameraCaptureSession * session)467 CameraDevice::notifySessionEndOfLifeLocked(ACameraCaptureSession* session) {
468 if (isClosed()) {
469 // Device is closing already. do nothing
470 return;
471 }
472
473 if (mCurrentSession != session) {
474 // Session has been replaced by other seesion or device is closed
475 return;
476 }
477 mCurrentSession = nullptr;
478
479 // Should not happen
480 if (!session->mIsClosed) {
481 ALOGE("Error: unclosed session %p reaches end of life!", session);
482 setCameraDeviceErrorLocked(ACAMERA_ERROR_CAMERA_DEVICE);
483 return;
484 }
485
486 // No new session, unconfigure now
487 camera_status_t ret = configureStreamsLocked(nullptr, nullptr);
488 if (ret != ACAMERA_OK) {
489 ALOGE("Unconfigure stream failed. Device might still be configured! ret %d", ret);
490 }
491 }
492
493 void
disconnectLocked(sp<ACameraCaptureSession> & session)494 CameraDevice::disconnectLocked(sp<ACameraCaptureSession>& session) {
495 if (mClosing.exchange(true)) {
496 // Already closing, just return
497 ALOGW("Camera device %s is already closing.", getId());
498 return;
499 }
500
501 if (mRemote != nullptr) {
502 auto ret = mRemote->disconnect();
503 if (!ret.isOk()) {
504 ALOGE("%s: Transaction error while disconnecting device %s", __FUNCTION__,
505 ret.description().c_str());
506 }
507 }
508 mRemote = nullptr;
509
510 if (session != nullptr) {
511 session->closeByDevice();
512 }
513 }
514
515 camera_status_t
stopRepeatingLocked()516 CameraDevice::stopRepeatingLocked() {
517 camera_status_t ret = checkCameraClosedOrErrorLocked();
518 if (ret != ACAMERA_OK) {
519 ALOGE("Camera %s stop repeating failed! ret %d", getId(), ret);
520 return ret;
521 }
522 if (mRepeatingSequenceId != REQUEST_ID_NONE) {
523 int repeatingSequenceId = mRepeatingSequenceId;
524 mRepeatingSequenceId = REQUEST_ID_NONE;
525
526 int64_t lastFrameNumber;
527 Status status = Status::UNKNOWN_ERROR;
528 auto remoteRet = mRemote->cancelRepeatingRequest(
529 [&status, &lastFrameNumber](Status s, auto frameNumber) {
530 status = s;
531 lastFrameNumber = frameNumber;
532 });
533 CHECK_TRANSACTION_AND_RET(remoteRet, status, "cancelRepeatingRequest()");
534 checkRepeatingSequenceCompleteLocked(repeatingSequenceId, lastFrameNumber);
535 }
536 return ACAMERA_OK;
537 }
538
539 camera_status_t
flushLocked(ACameraCaptureSession * session)540 CameraDevice::flushLocked(ACameraCaptureSession* session) {
541 camera_status_t ret = checkCameraClosedOrErrorLocked();
542 if (ret != ACAMERA_OK) {
543 ALOGE("Camera %s abort captures failed! ret %d", getId(), ret);
544 return ret;
545 }
546
547 // This should never happen because creating a new session will close
548 // previous one and thus reject any API call from previous session.
549 // But still good to check here in case something unexpected happen.
550 if (mCurrentSession != session) {
551 ALOGE("Camera %s session %p is not current active session!", getId(), session);
552 return ACAMERA_ERROR_INVALID_OPERATION;
553 }
554
555 if (mFlushing) {
556 ALOGW("Camera %s is already aborting captures", getId());
557 return ACAMERA_OK;
558 }
559
560 mFlushing = true;
561
562 // Send onActive callback to guarantee there is always active->ready transition
563 sp<AMessage> msg = new AMessage(kWhatSessionStateCb, mHandler);
564 msg->setPointer(kContextKey, session->mUserSessionCallback.context);
565 msg->setObject(kSessionSpKey, session);
566 msg->setPointer(kCallbackFpKey, (void*) session->mUserSessionCallback.onActive);
567 postSessionMsgAndCleanup(msg);
568
569 // If device is already idling, send callback and exit early
570 if (mIdle) {
571 sp<AMessage> msg = new AMessage(kWhatSessionStateCb, mHandler);
572 msg->setPointer(kContextKey, session->mUserSessionCallback.context);
573 msg->setObject(kSessionSpKey, session);
574 msg->setPointer(kCallbackFpKey, (void*) session->mUserSessionCallback.onReady);
575 postSessionMsgAndCleanup(msg);
576 mFlushing = false;
577 return ACAMERA_OK;
578 }
579
580 int64_t lastFrameNumber;
581 Status status = Status::UNKNOWN_ERROR;
582 auto remoteRet = mRemote->flush([&status, &lastFrameNumber](auto s, auto frameNumber) {
583 status = s;
584 lastFrameNumber = frameNumber;
585 });
586 CHECK_TRANSACTION_AND_RET(remoteRet, status, "flush()")
587 if (mRepeatingSequenceId != REQUEST_ID_NONE) {
588 checkRepeatingSequenceCompleteLocked(mRepeatingSequenceId, lastFrameNumber);
589 }
590 return ACAMERA_OK;
591 }
592
593 camera_status_t
waitUntilIdleLocked()594 CameraDevice::waitUntilIdleLocked() {
595 camera_status_t ret = checkCameraClosedOrErrorLocked();
596 if (ret != ACAMERA_OK) {
597 ALOGE("Wait until camera %s idle failed! ret %d", getId(), ret);
598 return ret;
599 }
600
601 if (mRepeatingSequenceId != REQUEST_ID_NONE) {
602 ALOGE("Camera device %s won't go to idle when there is repeating request!", getId());
603 return ACAMERA_ERROR_INVALID_OPERATION;
604 }
605
606 auto remoteRet = mRemote->waitUntilIdle();
607 CHECK_TRANSACTION_AND_RET(remoteRet, remoteRet, "waitUntilIdle()")
608 return ACAMERA_OK;
609 }
610
611 camera_status_t
configureStreamsLocked(const ACaptureSessionOutputContainer * outputs,const ACaptureRequest * sessionParameters)612 CameraDevice::configureStreamsLocked(const ACaptureSessionOutputContainer* outputs,
613 const ACaptureRequest* sessionParameters) {
614 ACaptureSessionOutputContainer emptyOutput;
615 if (outputs == nullptr) {
616 outputs = &emptyOutput;
617 }
618
619 camera_status_t ret = checkCameraClosedOrErrorLocked();
620 if (ret != ACAMERA_OK) {
621 return ret;
622 }
623
624 std::set<std::pair<native_handle_ptr_wrapper, OutputConfigurationWrapper>> outputSet;
625 for (auto outConfig : outputs->mOutputs) {
626 native_handle_t* anw = outConfig.mWindow;
627 OutputConfigurationWrapper outConfigInsertW;
628 OutputConfiguration &outConfigInsert = outConfigInsertW.mOutputConfiguration;
629 outConfigInsert.rotation = utils::convertToHidl(outConfig.mRotation);
630 outConfigInsert.windowGroupId = -1;
631 outConfigInsert.windowHandles.resize(outConfig.mSharedWindows.size() + 1);
632 outConfigInsert.windowHandles[0] = anw;
633 outConfigInsert.physicalCameraId = outConfig.mPhysicalCameraId;
634 native_handle_ptr_wrapper wrap(anw);
635 outputSet.insert(std::make_pair(anw, outConfigInsertW));
636 }
637 std::set<std::pair<native_handle_ptr_wrapper, OutputConfigurationWrapper>> addSet = outputSet;
638 std::vector<int32_t> deleteList;
639
640 // Determine which streams need to be created, which to be deleted
641 for (auto& kvPair : mConfiguredOutputs) {
642 int32_t streamId = kvPair.first;
643 auto& outputPair = kvPair.second;
644 if (outputSet.count(outputPair)) {
645 deleteList.push_back(streamId); // Need to delete a no longer needed stream
646 } else {
647 addSet.erase(outputPair); // No need to add already existing stream
648 }
649 }
650
651 ret = stopRepeatingLocked();
652 if (ret != ACAMERA_OK) {
653 ALOGE("Camera device %s stop repeating failed, ret %d", getId(), ret);
654 return ret;
655 }
656
657 ret = waitUntilIdleLocked();
658 if (ret != ACAMERA_OK) {
659 ALOGE("Camera device %s wait until idle failed, ret %d", getId(), ret);
660 return ret;
661 }
662
663 // Send onReady to previous session
664 // CurrentSession will be updated after configureStreamLocked, so here
665 // mCurrentSession is the session to be replaced by a new session
666 if (!mIdle && mCurrentSession != nullptr) {
667 if (mBusySession != mCurrentSession) {
668 ALOGE("Current session != busy session");
669 setCameraDeviceErrorLocked(ACAMERA_ERROR_CAMERA_DEVICE);
670 return ACAMERA_ERROR_CAMERA_DEVICE;
671 }
672 sp<AMessage> msg = new AMessage(kWhatSessionStateCb, mHandler);
673 msg->setPointer(kContextKey, mBusySession->mUserSessionCallback.context);
674 msg->setObject(kSessionSpKey, mBusySession);
675 msg->setPointer(kCallbackFpKey, (void*) mBusySession->mUserSessionCallback.onReady);
676 mBusySession.clear();
677 postSessionMsgAndCleanup(msg);
678 }
679 mIdle = true;
680
681 auto remoteRet = mRemote->beginConfigure();
682 CHECK_TRANSACTION_AND_RET(remoteRet, remoteRet, "beginConfigure()")
683
684 // delete to-be-deleted streams
685 for (auto streamId : deleteList) {
686 remoteRet = mRemote->deleteStream(streamId);
687 CHECK_TRANSACTION_AND_RET(remoteRet, remoteRet, "deleteStream()")
688 mConfiguredOutputs.erase(streamId);
689 }
690
691 // add new streams
692 for (auto outputPair : addSet) {
693 int streamId;
694 Status status = Status::UNKNOWN_ERROR;
695 auto ret = mRemote->createStream(outputPair.second,
696 [&status, &streamId](Status s, auto stream_id) {
697 status = s;
698 streamId = stream_id;
699 });
700 CHECK_TRANSACTION_AND_RET(ret, status, "createStream()")
701 mConfiguredOutputs.insert(std::make_pair(streamId, outputPair));
702 }
703
704 CameraMetadata params;
705 HCameraMetadata hidlParams;
706 if ((sessionParameters != nullptr) && (sessionParameters->settings != nullptr)) {
707 params.append(sessionParameters->settings->getInternalData());
708 const camera_metadata_t *params_metadata = params.getAndLock();
709 utils::convertToHidl(params_metadata, &hidlParams);
710 params.unlock(params_metadata);
711 }
712 remoteRet = mRemote->endConfigure(StreamConfigurationMode::NORMAL_MODE, hidlParams);
713 CHECK_TRANSACTION_AND_RET(remoteRet, remoteRet, "endConfigure()")
714 return ACAMERA_OK;
715 }
716
717 void
setRemoteDevice(sp<ICameraDeviceUser> remote)718 CameraDevice::setRemoteDevice(sp<ICameraDeviceUser> remote) {
719 Mutex::Autolock _l(mDeviceLock);
720 mRemote = remote;
721 }
722
723 bool
setDeviceMetadataQueues()724 CameraDevice::setDeviceMetadataQueues() {
725 if (mRemote == nullptr) {
726 ALOGE("mRemote must not be null while trying to fetch metadata queues");
727 return false;
728 }
729 std::shared_ptr<RequestMetadataQueue> &reqQueue = mCaptureRequestMetadataQueue;
730 auto ret =
731 mRemote->getCaptureRequestMetadataQueue(
732 [&reqQueue](const auto &mqDescriptor) {
733 reqQueue = std::make_shared<RequestMetadataQueue>(mqDescriptor);
734 if (!reqQueue->isValid() || reqQueue->availableToWrite() <=0) {
735 ALOGE("Empty fmq from cameraserver");
736 reqQueue = nullptr;
737 }
738 });
739 if (!ret.isOk()) {
740 ALOGE("Transaction error trying to get capture request metadata queue");
741 return false;
742 }
743 std::shared_ptr<ResultMetadataQueue> &resQueue = mCaptureResultMetadataQueue;
744 ret =
745 mRemote->getCaptureResultMetadataQueue(
746 [&resQueue](const auto &mqDescriptor) {
747 resQueue = std::make_shared<ResultMetadataQueue>(mqDescriptor);
748 if (!resQueue->isValid() || resQueue->availableToWrite() <=0) {
749 ALOGE("Empty fmq from cameraserver");
750 }
751 });
752 if (!ret.isOk()) {
753 ALOGE("Transaction error trying to get capture result metadata queue");
754 return false;
755 }
756 return true;
757 }
758
759 camera_status_t
checkCameraClosedOrErrorLocked() const760 CameraDevice::checkCameraClosedOrErrorLocked() const {
761 if (mRemote == nullptr) {
762 ALOGE("%s: camera device already closed", __FUNCTION__);
763 return ACAMERA_ERROR_CAMERA_DISCONNECTED;
764 }
765 if (mInError) {// triggered by onDeviceError
766 ALOGE("%s: camera device has encountered a serious error", __FUNCTION__);
767 return mError;
768 }
769 return ACAMERA_OK;
770 }
771
772 void
setCameraDeviceErrorLocked(camera_status_t error)773 CameraDevice::setCameraDeviceErrorLocked(camera_status_t error) {
774 mInError = true;
775 mError = error;
776 return;
777 }
778
779 void
updateTracker(int64_t frameNumber,bool isError)780 CameraDevice::FrameNumberTracker::updateTracker(int64_t frameNumber, bool isError) {
781 ALOGV("updateTracker frame %" PRId64 " isError %d", frameNumber, isError);
782 if (isError) {
783 mFutureErrorSet.insert(frameNumber);
784 } else if (frameNumber <= mCompletedFrameNumber) {
785 ALOGE("Frame number %" PRId64 " decreased! current fn %" PRId64,
786 frameNumber, mCompletedFrameNumber);
787 return;
788 } else {
789 if (frameNumber != mCompletedFrameNumber + 1) {
790 ALOGE("Frame number out of order. Expect %" PRId64 " but get %" PRId64,
791 mCompletedFrameNumber + 1, frameNumber);
792 // Do not assert as in java implementation
793 }
794 mCompletedFrameNumber = frameNumber;
795 }
796 update();
797 }
798
799 void
update()800 CameraDevice::FrameNumberTracker::update() {
801 for (auto it = mFutureErrorSet.begin(); it != mFutureErrorSet.end();) {
802 int64_t errorFrameNumber = *it;
803 if (errorFrameNumber == mCompletedFrameNumber + 1) {
804 mCompletedFrameNumber++;
805 it = mFutureErrorSet.erase(it);
806 } else if (errorFrameNumber <= mCompletedFrameNumber) {
807 // This should not happen, but deal with it anyway
808 ALOGE("Completd frame number passed through current frame number!");
809 // erase the old error since it's no longer useful
810 it = mFutureErrorSet.erase(it);
811 } else {
812 // Normal requests hasn't catched up error frames, just break
813 break;
814 }
815 }
816 ALOGV("Update complete frame %" PRId64, mCompletedFrameNumber);
817 }
818
819 void
onCaptureErrorLocked(ErrorCode errorCode,const CaptureResultExtras & resultExtras)820 CameraDevice::onCaptureErrorLocked(
821 ErrorCode errorCode,
822 const CaptureResultExtras& resultExtras) {
823 int sequenceId = resultExtras.requestId;
824 int64_t frameNumber = resultExtras.frameNumber;
825 int32_t burstId = resultExtras.burstId;
826 auto it = mSequenceCallbackMap.find(sequenceId);
827 if (it == mSequenceCallbackMap.end()) {
828 ALOGE("%s: Error: capture sequence index %d not found!",
829 __FUNCTION__, sequenceId);
830 setCameraDeviceErrorLocked(ACAMERA_ERROR_CAMERA_SERVICE);
831 return;
832 }
833
834 CallbackHolder cbh = (*it).second;
835 sp<ACameraCaptureSession> session = cbh.mSession;
836 if ((size_t) burstId >= cbh.mRequests.size()) {
837 ALOGE("%s: Error: request index %d out of bound (size %zu)",
838 __FUNCTION__, burstId, cbh.mRequests.size());
839 setCameraDeviceErrorLocked(ACAMERA_ERROR_CAMERA_SERVICE);
840 return;
841 }
842 sp<CaptureRequest> request = cbh.mRequests[burstId];
843
844 // Handle buffer error
845 if (errorCode == ErrorCode::CAMERA_BUFFER) {
846 int32_t streamId = resultExtras.errorStreamId;
847 ACameraCaptureSession_captureCallback_bufferLost onBufferLost =
848 cbh.mOnCaptureBufferLost;
849 auto outputPairIt = mConfiguredOutputs.find(streamId);
850 if (outputPairIt == mConfiguredOutputs.end()) {
851 ALOGE("%s: Error: stream id %d does not exist", __FUNCTION__, streamId);
852 setCameraDeviceErrorLocked(ACAMERA_ERROR_CAMERA_SERVICE);
853 return;
854 }
855
856 const auto& windowHandles = outputPairIt->second.second.mOutputConfiguration.windowHandles;
857 for (const auto& outHandle : windowHandles) {
858 for (auto streamAndWindowId : request->mCaptureRequest.streamAndWindowIds) {
859 int32_t windowId = streamAndWindowId.windowId;
860 if (utils::isWindowNativeHandleEqual(windowHandles[windowId],outHandle)) {
861 native_handle_t* anw =
862 const_cast<native_handle_t *>(windowHandles[windowId].getNativeHandle());
863 ALOGV("Camera %s Lost output buffer for ANW %p frame %" PRId64,
864 getId(), anw, frameNumber);
865
866 sp<AMessage> msg = new AMessage(kWhatCaptureBufferLost, mHandler);
867 msg->setPointer(kContextKey, cbh.mContext);
868 msg->setObject(kSessionSpKey, session);
869 msg->setPointer(kCallbackFpKey, (void*) onBufferLost);
870 msg->setObject(kCaptureRequestKey, request);
871 msg->setPointer(kAnwKey, (void*) anw);
872 msg->setInt64(kFrameNumberKey, frameNumber);
873 postSessionMsgAndCleanup(msg);
874 }
875 }
876 }
877 } else { // Handle other capture failures
878 // Fire capture failure callback if there is one registered
879 ACameraCaptureSession_captureCallback_failed onError = cbh.mOnCaptureFailed;
880 sp<CameraCaptureFailure> failure(new CameraCaptureFailure());
881 failure->frameNumber = frameNumber;
882 // TODO: refine this when implementing flush
883 failure->reason = CAPTURE_FAILURE_REASON_ERROR;
884 failure->sequenceId = sequenceId;
885 failure->wasImageCaptured = (errorCode == ErrorCode::CAMERA_RESULT);
886
887 sp<AMessage> msg = new AMessage(cbh.mIsLogicalCameraCallback ? kWhatLogicalCaptureFail :
888 kWhatCaptureFail, mHandler);
889 msg->setPointer(kContextKey, cbh.mContext);
890 msg->setObject(kSessionSpKey, session);
891 if (cbh.mIsLogicalCameraCallback) {
892 if (resultExtras.errorPhysicalCameraId.size() > 0) {
893 msg->setString(kFailingPhysicalCameraId, resultExtras.errorPhysicalCameraId.c_str(),
894 resultExtras.errorPhysicalCameraId.size());
895 }
896 msg->setPointer(kCallbackFpKey, (void*) cbh.mOnLogicalCameraCaptureFailed);
897 } else {
898 msg->setPointer(kCallbackFpKey, (void*) onError);
899 }
900 msg->setObject(kCaptureRequestKey, request);
901 msg->setObject(kCaptureFailureKey, failure);
902 postSessionMsgAndCleanup(msg);
903
904 // Update tracker
905 mFrameNumberTracker.updateTracker(frameNumber, /*isError*/true);
906 checkAndFireSequenceCompleteLocked();
907 }
908 return;
909 }
910
CallbackHandler(const char * id)911 CameraDevice::CallbackHandler::CallbackHandler(const char *id) : mId(id) { }
912
onMessageReceived(const sp<AMessage> & msg)913 void CameraDevice::CallbackHandler::onMessageReceived(
914 const sp<AMessage> &msg) {
915 switch (msg->what()) {
916 case kWhatOnDisconnected:
917 case kWhatOnError:
918 case kWhatSessionStateCb:
919 case kWhatCaptureStart:
920 case kWhatCaptureResult:
921 case kWhatLogicalCaptureResult:
922 case kWhatCaptureFail:
923 case kWhatLogicalCaptureFail:
924 case kWhatCaptureSeqEnd:
925 case kWhatCaptureSeqAbort:
926 case kWhatCaptureBufferLost:
927 ALOGV("%s: Received msg %d", __FUNCTION__, msg->what());
928 break;
929 case kWhatCleanUpSessions:
930 mCachedSessions.clear();
931 return;
932 default:
933 ALOGE("%s:Error: unknown device callback %d", __FUNCTION__, msg->what());
934 return;
935 }
936 // Check the common part of all message
937 void* context;
938 bool found = msg->findPointer(kContextKey, &context);
939 if (!found) {
940 ALOGE("%s: Cannot find callback context!", __FUNCTION__);
941 return;
942 }
943 switch (msg->what()) {
944 case kWhatOnDisconnected:
945 {
946 ACameraDevice* dev;
947 found = msg->findPointer(kDeviceKey, (void**) &dev);
948 if (!found || dev == nullptr) {
949 ALOGE("%s: Cannot find device pointer!", __FUNCTION__);
950 return;
951 }
952 ACameraDevice_StateCallback onDisconnected;
953 found = msg->findPointer(kCallbackFpKey, (void**) &onDisconnected);
954 if (!found) {
955 ALOGE("%s: Cannot find onDisconnected!", __FUNCTION__);
956 return;
957 }
958 if (onDisconnected == nullptr) {
959 return;
960 }
961 (*onDisconnected)(context, dev);
962 break;
963 }
964 case kWhatOnError:
965 {
966 ACameraDevice* dev;
967 found = msg->findPointer(kDeviceKey, (void**) &dev);
968 if (!found || dev == nullptr) {
969 ALOGE("%s: Cannot find device pointer!", __FUNCTION__);
970 return;
971 }
972 ACameraDevice_ErrorStateCallback onError;
973 found = msg->findPointer(kCallbackFpKey, (void**) &onError);
974 if (!found) {
975 ALOGE("%s: Cannot find onError!", __FUNCTION__);
976 return;
977 }
978 int errorCode;
979 found = msg->findInt32(kErrorCodeKey, &errorCode);
980 if (!found) {
981 ALOGE("%s: Cannot find error code!", __FUNCTION__);
982 return;
983 }
984 if (onError == nullptr) {
985 return;
986 }
987 (*onError)(context, dev, errorCode);
988 break;
989 }
990 case kWhatSessionStateCb:
991 case kWhatCaptureStart:
992 case kWhatCaptureResult:
993 case kWhatLogicalCaptureResult:
994 case kWhatCaptureFail:
995 case kWhatLogicalCaptureFail:
996 case kWhatCaptureSeqEnd:
997 case kWhatCaptureSeqAbort:
998 case kWhatCaptureBufferLost:
999 {
1000 sp<RefBase> obj;
1001 found = msg->findObject(kSessionSpKey, &obj);
1002 if (!found || obj == nullptr) {
1003 ALOGE("%s: Cannot find session pointer!", __FUNCTION__);
1004 return;
1005 }
1006 sp<ACameraCaptureSession> session(static_cast<ACameraCaptureSession*>(obj.get()));
1007 mCachedSessions.push(session);
1008 sp<CaptureRequest> requestSp = nullptr;
1009 const char *id_cstr = mId.c_str();
1010 switch (msg->what()) {
1011 case kWhatCaptureStart:
1012 case kWhatCaptureResult:
1013 case kWhatLogicalCaptureResult:
1014 case kWhatCaptureFail:
1015 case kWhatLogicalCaptureFail:
1016 case kWhatCaptureBufferLost:
1017 found = msg->findObject(kCaptureRequestKey, &obj);
1018 if (!found) {
1019 ALOGE("%s: Cannot find capture request!", __FUNCTION__);
1020 return;
1021 }
1022 requestSp = static_cast<CaptureRequest*>(obj.get());
1023 break;
1024 }
1025
1026 switch (msg->what()) {
1027 case kWhatSessionStateCb:
1028 {
1029 ACameraCaptureSession_stateCallback onState;
1030 found = msg->findPointer(kCallbackFpKey, (void**) &onState);
1031 if (!found) {
1032 ALOGE("%s: Cannot find state callback!", __FUNCTION__);
1033 return;
1034 }
1035 if (onState == nullptr) {
1036 return;
1037 }
1038 (*onState)(context, session.get());
1039 break;
1040 }
1041 case kWhatCaptureStart:
1042 {
1043 ACameraCaptureSession_captureCallback_start onStart;
1044 found = msg->findPointer(kCallbackFpKey, (void**) &onStart);
1045 if (!found) {
1046 ALOGE("%s: Cannot find capture start callback!", __FUNCTION__);
1047 return;
1048 }
1049 if (onStart == nullptr) {
1050 return;
1051 }
1052 int64_t timestamp;
1053 found = msg->findInt64(kTimeStampKey, ×tamp);
1054 if (!found) {
1055 ALOGE("%s: Cannot find timestamp!", __FUNCTION__);
1056 return;
1057 }
1058 ACaptureRequest* request = allocateACaptureRequest(requestSp, id_cstr);
1059 (*onStart)(context, session.get(), request, timestamp);
1060 freeACaptureRequest(request);
1061 break;
1062 }
1063 case kWhatCaptureResult:
1064 {
1065 ACameraCaptureSession_captureCallback_result onResult;
1066 found = msg->findPointer(kCallbackFpKey, (void**) &onResult);
1067 if (!found) {
1068 ALOGE("%s: Cannot find capture result callback!", __FUNCTION__);
1069 return;
1070 }
1071 if (onResult == nullptr) {
1072 return;
1073 }
1074
1075 found = msg->findObject(kCaptureResultKey, &obj);
1076 if (!found) {
1077 ALOGE("%s: Cannot find capture result!", __FUNCTION__);
1078 return;
1079 }
1080 sp<ACameraMetadata> result(static_cast<ACameraMetadata*>(obj.get()));
1081 ACaptureRequest* request = allocateACaptureRequest(requestSp, id_cstr);
1082 (*onResult)(context, session.get(), request, result.get());
1083 freeACaptureRequest(request);
1084 break;
1085 }
1086 case kWhatLogicalCaptureResult:
1087 {
1088 ACameraCaptureSession_logicalCamera_captureCallback_result onResult;
1089 found = msg->findPointer(kCallbackFpKey, (void**) &onResult);
1090 if (!found) {
1091 ALOGE("%s: Cannot find capture result callback!", __FUNCTION__);
1092 return;
1093 }
1094 if (onResult == nullptr) {
1095 return;
1096 }
1097
1098 found = msg->findObject(kCaptureResultKey, &obj);
1099 if (!found) {
1100 ALOGE("%s: Cannot find capture result!", __FUNCTION__);
1101 return;
1102 }
1103 sp<ACameraMetadata> result(static_cast<ACameraMetadata*>(obj.get()));
1104
1105 found = msg->findObject(kPhysicalCaptureResultKey, &obj);
1106 if (!found) {
1107 ALOGE("%s: Cannot find physical capture result!", __FUNCTION__);
1108 return;
1109 }
1110 sp<ACameraPhysicalCaptureResultInfo> physicalResult(
1111 static_cast<ACameraPhysicalCaptureResultInfo*>(obj.get()));
1112 std::vector<PhysicalCaptureResultInfoLocal>& physicalResultInfo =
1113 physicalResult->mPhysicalResultInfo;
1114
1115 std::vector<std::string> physicalCameraIds;
1116 std::vector<sp<ACameraMetadata>> physicalMetadataCopy;
1117 for (size_t i = 0; i < physicalResultInfo.size(); i++) {
1118 physicalCameraIds.push_back(physicalResultInfo[i].physicalCameraId);
1119
1120 CameraMetadata clone = physicalResultInfo[i].physicalMetadata;
1121 clone.update(ANDROID_SYNC_FRAME_NUMBER,
1122 &physicalResult->mFrameNumber, /*data_count*/1);
1123 sp<ACameraMetadata> metadata =
1124 new ACameraMetadata(clone.release(), ACameraMetadata::ACM_RESULT);
1125 physicalMetadataCopy.push_back(metadata);
1126 }
1127 std::vector<const char*> physicalCameraIdPtrs;
1128 std::vector<const ACameraMetadata*> physicalMetadataCopyPtrs;
1129 for (size_t i = 0; i < physicalResultInfo.size(); i++) {
1130 physicalCameraIdPtrs.push_back(physicalCameraIds[i].c_str());
1131 physicalMetadataCopyPtrs.push_back(physicalMetadataCopy[i].get());
1132 }
1133
1134 ACaptureRequest* request = allocateACaptureRequest(requestSp, id_cstr);
1135 (*onResult)(context, session.get(), request, result.get(),
1136 physicalResultInfo.size(), physicalCameraIdPtrs.data(),
1137 physicalMetadataCopyPtrs.data());
1138 freeACaptureRequest(request);
1139 break;
1140 }
1141
1142 case kWhatCaptureFail:
1143 {
1144 ACameraCaptureSession_captureCallback_failed onFail;
1145 found = msg->findPointer(kCallbackFpKey, (void**) &onFail);
1146 if (!found) {
1147 ALOGE("%s: Cannot find capture fail callback!", __FUNCTION__);
1148 return;
1149 }
1150 if (onFail == nullptr) {
1151 return;
1152 }
1153
1154 found = msg->findObject(kCaptureFailureKey, &obj);
1155 if (!found) {
1156 ALOGE("%s: Cannot find capture failure!", __FUNCTION__);
1157 return;
1158 }
1159 sp<CameraCaptureFailure> failureSp(
1160 static_cast<CameraCaptureFailure*>(obj.get()));
1161 ACameraCaptureFailure* failure =
1162 static_cast<ACameraCaptureFailure*>(failureSp.get());
1163 ACaptureRequest* request = allocateACaptureRequest(requestSp, id_cstr);
1164 (*onFail)(context, session.get(), request, failure);
1165 freeACaptureRequest(request);
1166 break;
1167 }
1168 case kWhatLogicalCaptureFail:
1169 {
1170 ACameraCaptureSession_logicalCamera_captureCallback_failed onFail;
1171 found = msg->findPointer(kCallbackFpKey, (void**) &onFail);
1172 if (!found) {
1173 ALOGE("%s: Cannot find capture fail callback!", __FUNCTION__);
1174 return;
1175 }
1176 if (onFail == nullptr) {
1177 return;
1178 }
1179
1180 found = msg->findObject(kCaptureFailureKey, &obj);
1181 if (!found) {
1182 ALOGE("%s: Cannot find capture failure!", __FUNCTION__);
1183 return;
1184 }
1185 sp<CameraCaptureFailure> failureSp(
1186 static_cast<CameraCaptureFailure*>(obj.get()));
1187 ALogicalCameraCaptureFailure failure;
1188 AString physicalCameraId;
1189 found = msg->findString(kFailingPhysicalCameraId, &physicalCameraId);
1190 if (found && !physicalCameraId.empty()) {
1191 failure.physicalCameraId = physicalCameraId.c_str();
1192 } else {
1193 failure.physicalCameraId = nullptr;
1194 }
1195 failure.captureFailure = *failureSp;
1196 ACaptureRequest* request = allocateACaptureRequest(requestSp, id_cstr);
1197 (*onFail)(context, session.get(), request, &failure);
1198 freeACaptureRequest(request);
1199 break;
1200 }
1201 case kWhatCaptureSeqEnd:
1202 {
1203 ACameraCaptureSession_captureCallback_sequenceEnd onSeqEnd;
1204 found = msg->findPointer(kCallbackFpKey, (void**) &onSeqEnd);
1205 if (!found) {
1206 ALOGE("%s: Cannot find sequence end callback!", __FUNCTION__);
1207 return;
1208 }
1209 if (onSeqEnd == nullptr) {
1210 return;
1211 }
1212 int seqId;
1213 found = msg->findInt32(kSequenceIdKey, &seqId);
1214 if (!found) {
1215 ALOGE("%s: Cannot find frame number!", __FUNCTION__);
1216 return;
1217 }
1218 int64_t frameNumber;
1219 found = msg->findInt64(kFrameNumberKey, &frameNumber);
1220 if (!found) {
1221 ALOGE("%s: Cannot find frame number!", __FUNCTION__);
1222 return;
1223 }
1224 (*onSeqEnd)(context, session.get(), seqId, frameNumber);
1225 break;
1226 }
1227 case kWhatCaptureSeqAbort:
1228 {
1229 ACameraCaptureSession_captureCallback_sequenceAbort onSeqAbort;
1230 found = msg->findPointer(kCallbackFpKey, (void**) &onSeqAbort);
1231 if (!found) {
1232 ALOGE("%s: Cannot find sequence end callback!", __FUNCTION__);
1233 return;
1234 }
1235 if (onSeqAbort == nullptr) {
1236 return;
1237 }
1238 int seqId;
1239 found = msg->findInt32(kSequenceIdKey, &seqId);
1240 if (!found) {
1241 ALOGE("%s: Cannot find frame number!", __FUNCTION__);
1242 return;
1243 }
1244 (*onSeqAbort)(context, session.get(), seqId);
1245 break;
1246 }
1247 case kWhatCaptureBufferLost:
1248 {
1249 ACameraCaptureSession_captureCallback_bufferLost onBufferLost;
1250 found = msg->findPointer(kCallbackFpKey, (void**) &onBufferLost);
1251 if (!found) {
1252 ALOGE("%s: Cannot find buffer lost callback!", __FUNCTION__);
1253 return;
1254 }
1255 if (onBufferLost == nullptr) {
1256 return;
1257 }
1258
1259 native_handle_t* anw;
1260 found = msg->findPointer(kAnwKey, (void**) &anw);
1261 if (!found) {
1262 ALOGE("%s: Cannot find native_handle_t!", __FUNCTION__);
1263 return;
1264 }
1265
1266 int64_t frameNumber;
1267 found = msg->findInt64(kFrameNumberKey, &frameNumber);
1268 if (!found) {
1269 ALOGE("%s: Cannot find frame number!", __FUNCTION__);
1270 return;
1271 }
1272
1273 ACaptureRequest* request = allocateACaptureRequest(requestSp, id_cstr);
1274 (*onBufferLost)(context, session.get(), request, anw, frameNumber);
1275 freeACaptureRequest(request);
1276 break;
1277 }
1278 }
1279 break;
1280 }
1281 }
1282 }
1283
CallbackHolder(sp<ACameraCaptureSession> session,const Vector<sp<CaptureRequest>> & requests,bool isRepeating,ACameraCaptureSession_captureCallbacks * cbs)1284 CameraDevice::CallbackHolder::CallbackHolder(
1285 sp<ACameraCaptureSession> session,
1286 const Vector<sp<CaptureRequest> >& requests,
1287 bool isRepeating,
1288 ACameraCaptureSession_captureCallbacks* cbs) :
1289 mSession(session), mRequests(requests),
1290 mIsRepeating(isRepeating),
1291 mIsLogicalCameraCallback(false) {
1292 initCaptureCallbacks(cbs);
1293
1294 if (cbs != nullptr) {
1295 mOnCaptureCompleted = cbs->onCaptureCompleted;
1296 mOnCaptureFailed = cbs->onCaptureFailed;
1297 }
1298 }
1299
CallbackHolder(sp<ACameraCaptureSession> session,const Vector<sp<CaptureRequest>> & requests,bool isRepeating,ACameraCaptureSession_logicalCamera_captureCallbacks * lcbs)1300 CameraDevice::CallbackHolder::CallbackHolder(
1301 sp<ACameraCaptureSession> session,
1302 const Vector<sp<CaptureRequest> >& requests,
1303 bool isRepeating,
1304 ACameraCaptureSession_logicalCamera_captureCallbacks* lcbs) :
1305 mSession(session), mRequests(requests),
1306 mIsRepeating(isRepeating),
1307 mIsLogicalCameraCallback(true) {
1308 initCaptureCallbacks(lcbs);
1309
1310 if (lcbs != nullptr) {
1311 mOnLogicalCameraCaptureCompleted = lcbs->onLogicalCameraCaptureCompleted;
1312 mOnLogicalCameraCaptureFailed = lcbs->onLogicalCameraCaptureFailed;
1313 }
1314 }
1315
1316 void
checkRepeatingSequenceCompleteLocked(const int sequenceId,const int64_t lastFrameNumber)1317 CameraDevice::checkRepeatingSequenceCompleteLocked(
1318 const int sequenceId, const int64_t lastFrameNumber) {
1319 ALOGV("Repeating seqId %d lastFrameNumer %" PRId64, sequenceId, lastFrameNumber);
1320 if (lastFrameNumber == NO_FRAMES_CAPTURED) {
1321 if (mSequenceCallbackMap.count(sequenceId) == 0) {
1322 ALOGW("No callback found for sequenceId %d", sequenceId);
1323 return;
1324 }
1325 // remove callback holder from callback map
1326 auto cbIt = mSequenceCallbackMap.find(sequenceId);
1327 CallbackHolder cbh = cbIt->second;
1328 mSequenceCallbackMap.erase(cbIt);
1329 // send seq aborted callback
1330 sp<AMessage> msg = new AMessage(kWhatCaptureSeqAbort, mHandler);
1331 msg->setPointer(kContextKey, cbh.mContext);
1332 msg->setObject(kSessionSpKey, cbh.mSession);
1333 msg->setPointer(kCallbackFpKey, (void*) cbh.mOnCaptureSequenceAborted);
1334 msg->setInt32(kSequenceIdKey, sequenceId);
1335 postSessionMsgAndCleanup(msg);
1336 } else {
1337 // Use mSequenceLastFrameNumberMap to track
1338 mSequenceLastFrameNumberMap.insert(std::make_pair(sequenceId, lastFrameNumber));
1339
1340 // Last frame might have arrived. Check now
1341 checkAndFireSequenceCompleteLocked();
1342 }
1343 }
1344
1345 void
checkAndFireSequenceCompleteLocked()1346 CameraDevice::checkAndFireSequenceCompleteLocked() {
1347 int64_t completedFrameNumber = mFrameNumberTracker.getCompletedFrameNumber();
1348 auto it = mSequenceLastFrameNumberMap.begin();
1349 while (it != mSequenceLastFrameNumberMap.end()) {
1350 int sequenceId = it->first;
1351 int64_t lastFrameNumber = it->second;
1352 bool seqCompleted = false;
1353 bool hasCallback = true;
1354
1355 if (mRemote == nullptr) {
1356 ALOGW("Camera %s closed while checking sequence complete", getId());
1357 return;
1358 }
1359
1360 // Check if there is callback for this sequence
1361 // This should not happen because we always register callback (with nullptr inside)
1362 if (mSequenceCallbackMap.count(sequenceId) == 0) {
1363 ALOGW("No callback found for sequenceId %d", sequenceId);
1364 hasCallback = false;
1365 }
1366
1367 if (lastFrameNumber <= completedFrameNumber) {
1368 ALOGV("seq %d reached last frame %" PRId64 ", completed %" PRId64,
1369 sequenceId, lastFrameNumber, completedFrameNumber);
1370 seqCompleted = true;
1371 }
1372
1373 if (seqCompleted && hasCallback) {
1374 // remove callback holder from callback map
1375 auto cbIt = mSequenceCallbackMap.find(sequenceId);
1376 CallbackHolder cbh = cbIt->second;
1377 mSequenceCallbackMap.erase(cbIt);
1378 // send seq complete callback
1379 sp<AMessage> msg = new AMessage(kWhatCaptureSeqEnd, mHandler);
1380 msg->setPointer(kContextKey, cbh.mContext);
1381 msg->setObject(kSessionSpKey, cbh.mSession);
1382 msg->setPointer(kCallbackFpKey, (void*) cbh.mOnCaptureSequenceCompleted);
1383 msg->setInt32(kSequenceIdKey, sequenceId);
1384 msg->setInt64(kFrameNumberKey, lastFrameNumber);
1385
1386 // Clear the session sp before we send out the message
1387 // This will guarantee the rare case where the message is processed
1388 // before cbh goes out of scope and causing we call the session
1389 // destructor while holding device lock
1390 cbh.mSession.clear();
1391 postSessionMsgAndCleanup(msg);
1392 }
1393
1394 // No need to track sequence complete if there is no callback registered
1395 if (seqCompleted || !hasCallback) {
1396 it = mSequenceLastFrameNumberMap.erase(it);
1397 } else {
1398 ++it;
1399 }
1400 }
1401 }
1402
stopLooper()1403 void CameraDevice::stopLooper() {
1404 Mutex::Autolock _l(mDeviceLock);
1405 if (mCbLooper != nullptr) {
1406 mCbLooper->unregisterHandler(mHandler->id());
1407 mCbLooper->stop();
1408 }
1409 mCbLooper.clear();
1410 mHandler.clear();
1411 }
1412
1413 /**
1414 * Camera service callback implementation
1415 */
1416 android::hardware::Return<void>
onDeviceError(ErrorCode errorCode,const CaptureResultExtras & resultExtras)1417 CameraDevice::ServiceCallback::onDeviceError(
1418 ErrorCode errorCode,
1419 const CaptureResultExtras& resultExtras) {
1420 ALOGD("Device error received, code %d, frame number %" PRId64 ", request ID %d, subseq ID %d"
1421 " physical camera ID %s", errorCode, resultExtras.frameNumber, resultExtras.requestId,
1422 resultExtras.burstId, resultExtras.errorPhysicalCameraId.c_str());
1423 auto ret = Void();
1424 sp<CameraDevice> dev = mDevice.promote();
1425 if (dev == nullptr) {
1426 return ret; // device has been closed
1427 }
1428
1429 sp<ACameraCaptureSession> session = dev->mCurrentSession.promote();
1430 Mutex::Autolock _l(dev->mDeviceLock);
1431 if (dev->mRemote == nullptr) {
1432 return ret; // device has been closed
1433 }
1434 switch (errorCode) {
1435 case ErrorCode::CAMERA_DISCONNECTED:
1436 {
1437 // Camera is disconnected, close the session and expect no more callbacks
1438 if (session != nullptr) {
1439 session->closeByDevice();
1440 }
1441 dev->mCurrentSession = nullptr;
1442 sp<AMessage> msg = new AMessage(kWhatOnDisconnected, dev->mHandler);
1443 msg->setPointer(kContextKey, dev->mAppCallbacks.context);
1444 msg->setPointer(kDeviceKey, (void*) dev->getWrapper());
1445 msg->setPointer(kCallbackFpKey, (void*) dev->mAppCallbacks.onDisconnected);
1446 msg->post();
1447 break;
1448 }
1449 default:
1450 ALOGE("Unknown error from camera device: %d", errorCode);
1451 [[fallthrough]];
1452 case ErrorCode::CAMERA_DEVICE:
1453 case ErrorCode::CAMERA_SERVICE:
1454 {
1455 int32_t errorVal = ::ERROR_CAMERA_DEVICE;
1456 // We keep this switch since this block might be encountered with
1457 // more than just 2 states. The default fallthrough could have us
1458 // handling more unmatched error cases.
1459 switch (errorCode) {
1460 case ErrorCode::CAMERA_DEVICE:
1461 dev->setCameraDeviceErrorLocked(ACAMERA_ERROR_CAMERA_DEVICE);
1462 break;
1463 case ErrorCode::CAMERA_SERVICE:
1464 dev->setCameraDeviceErrorLocked(ACAMERA_ERROR_CAMERA_SERVICE);
1465 errorVal = ::ERROR_CAMERA_SERVICE;
1466 break;
1467 default:
1468 dev->setCameraDeviceErrorLocked(ACAMERA_ERROR_UNKNOWN);
1469 break;
1470 }
1471 sp<AMessage> msg = new AMessage(kWhatOnError, dev->mHandler);
1472 msg->setPointer(kContextKey, dev->mAppCallbacks.context);
1473 msg->setPointer(kDeviceKey, (void*) dev->getWrapper());
1474 msg->setPointer(kCallbackFpKey, (void*) dev->mAppCallbacks.onError);
1475 msg->setInt32(kErrorCodeKey, errorVal);
1476 msg->post();
1477 break;
1478 }
1479 case ErrorCode::CAMERA_REQUEST:
1480 case ErrorCode::CAMERA_RESULT:
1481 case ErrorCode::CAMERA_BUFFER:
1482 dev->onCaptureErrorLocked(errorCode, resultExtras);
1483 break;
1484 }
1485 return ret;
1486 }
1487
1488 android::hardware::Return<void>
onDeviceIdle()1489 CameraDevice::ServiceCallback::onDeviceIdle() {
1490 ALOGV("Camera is now idle");
1491 auto ret = Void();
1492 sp<CameraDevice> dev = mDevice.promote();
1493 if (dev == nullptr) {
1494 return ret; // device has been closed
1495 }
1496
1497 Mutex::Autolock _l(dev->mDeviceLock);
1498 if (dev->isClosed() || dev->mRemote == nullptr) {
1499 return ret;
1500 }
1501
1502 if (dev->mIdle) {
1503 // Already in idle state. Possibly other thread did waitUntilIdle
1504 return ret;
1505 }
1506
1507 if (dev->mCurrentSession != nullptr) {
1508 ALOGE("onDeviceIdle sending state cb");
1509 if (dev->mBusySession != dev->mCurrentSession) {
1510 ALOGE("Current session != busy session");
1511 dev->setCameraDeviceErrorLocked(ACAMERA_ERROR_CAMERA_DEVICE);
1512 return ret;
1513 }
1514
1515 sp<AMessage> msg = new AMessage(kWhatSessionStateCb, dev->mHandler);
1516 msg->setPointer(kContextKey, dev->mBusySession->mUserSessionCallback.context);
1517 msg->setObject(kSessionSpKey, dev->mBusySession);
1518 msg->setPointer(kCallbackFpKey, (void*) dev->mBusySession->mUserSessionCallback.onReady);
1519 // Make sure we clear the sp first so the session destructor can
1520 // only happen on handler thread (where we don't hold device/session lock)
1521 dev->mBusySession.clear();
1522 dev->postSessionMsgAndCleanup(msg);
1523 }
1524 dev->mIdle = true;
1525 dev->mFlushing = false;
1526 return ret;
1527 }
1528
1529 android::hardware::Return<void>
onCaptureStarted(const CaptureResultExtras & resultExtras,uint64_t timestamp)1530 CameraDevice::ServiceCallback::onCaptureStarted(
1531 const CaptureResultExtras& resultExtras,
1532 uint64_t timestamp) {
1533 auto ret = Void();
1534
1535 sp<CameraDevice> dev = mDevice.promote();
1536 if (dev == nullptr) {
1537 return ret; // device has been closed
1538 }
1539 Mutex::Autolock _l(dev->mDeviceLock);
1540 if (dev->isClosed() || dev->mRemote == nullptr) {
1541 return ret;
1542 }
1543
1544 int32_t sequenceId = resultExtras.requestId;
1545 int32_t burstId = resultExtras.burstId;
1546
1547 auto it = dev->mSequenceCallbackMap.find(sequenceId);
1548 if (it != dev->mSequenceCallbackMap.end()) {
1549 CallbackHolder cbh = (*it).second;
1550 ACameraCaptureSession_captureCallback_start onStart = cbh.mOnCaptureStarted;
1551 sp<ACameraCaptureSession> session = cbh.mSession;
1552 if ((size_t) burstId >= cbh.mRequests.size()) {
1553 ALOGE("%s: Error: request index %d out of bound (size %zu)",
1554 __FUNCTION__, burstId, cbh.mRequests.size());
1555 dev->setCameraDeviceErrorLocked(ACAMERA_ERROR_CAMERA_SERVICE);
1556 }
1557 sp<CaptureRequest> request = cbh.mRequests[burstId];
1558 sp<AMessage> msg = new AMessage(kWhatCaptureStart, dev->mHandler);
1559 msg->setPointer(kContextKey, cbh.mContext);
1560 msg->setObject(kSessionSpKey, session);
1561 msg->setPointer(kCallbackFpKey, (void*) onStart);
1562 msg->setObject(kCaptureRequestKey, request);
1563 msg->setInt64(kTimeStampKey, timestamp);
1564 dev->postSessionMsgAndCleanup(msg);
1565 }
1566 return ret;
1567 }
1568
1569 android::hardware::Return<void>
onResultReceived(const FmqSizeOrMetadata & resultMetadata,const CaptureResultExtras & resultExtras,const hidl_vec<PhysicalCaptureResultInfo> & physicalResultInfos)1570 CameraDevice::ServiceCallback::onResultReceived(
1571 const FmqSizeOrMetadata& resultMetadata,
1572 const CaptureResultExtras& resultExtras,
1573 const hidl_vec<PhysicalCaptureResultInfo>& physicalResultInfos) {
1574 auto ret = Void();
1575
1576 sp<CameraDevice> dev = mDevice.promote();
1577 if (dev == nullptr) {
1578 return ret; // device has been closed
1579 }
1580 int32_t sequenceId = resultExtras.requestId;
1581 int64_t frameNumber = resultExtras.frameNumber;
1582 int32_t burstId = resultExtras.burstId;
1583 bool isPartialResult = (resultExtras.partialResultCount < dev->mPartialResultCount);
1584
1585 if (!isPartialResult) {
1586 ALOGV("SeqId %d frame %" PRId64 " result arrive.", sequenceId, frameNumber);
1587 }
1588
1589 Mutex::Autolock _l(dev->mDeviceLock);
1590 if (dev->mRemote == nullptr) {
1591 return ret; // device has been disconnected
1592 }
1593
1594 if (dev->isClosed()) {
1595 if (!isPartialResult) {
1596 dev->mFrameNumberTracker.updateTracker(frameNumber, /*isError*/false);
1597 }
1598 // early return to avoid callback sent to closed devices
1599 return ret;
1600 }
1601
1602 CameraMetadata metadataCopy;
1603 camera_status_t status = readOneResultMetadata(resultMetadata,
1604 dev->mCaptureResultMetadataQueue.get(), &metadataCopy);
1605 if (status != ACAMERA_OK) {
1606 ALOGE("%s: result metadata couldn't be converted", __FUNCTION__);
1607 return ret;
1608 }
1609
1610 metadataCopy.update(ANDROID_LENS_INFO_SHADING_MAP_SIZE, dev->mShadingMapSize, /*data_count*/2);
1611 metadataCopy.update(ANDROID_SYNC_FRAME_NUMBER, &frameNumber, /*data_count*/1);
1612
1613 auto it = dev->mSequenceCallbackMap.find(sequenceId);
1614 if (it != dev->mSequenceCallbackMap.end()) {
1615 CallbackHolder cbh = (*it).second;
1616 sp<ACameraCaptureSession> session = cbh.mSession;
1617 if ((size_t) burstId >= cbh.mRequests.size()) {
1618 ALOGE("%s: Error: request index %d out of bound (size %zu)",
1619 __FUNCTION__, burstId, cbh.mRequests.size());
1620 dev->setCameraDeviceErrorLocked(ACAMERA_ERROR_CAMERA_SERVICE);
1621 }
1622 sp<CaptureRequest> request = cbh.mRequests[burstId];
1623 sp<ACameraMetadata> result(new ACameraMetadata(
1624 metadataCopy.release(), ACameraMetadata::ACM_RESULT));
1625
1626 std::vector<PhysicalCaptureResultInfoLocal> localPhysicalResult;
1627 localPhysicalResult.resize(physicalResultInfos.size());
1628 for (size_t i = 0; i < physicalResultInfos.size(); i++) {
1629 localPhysicalResult[i].physicalCameraId = physicalResultInfos[i].physicalCameraId;
1630 status = readOneResultMetadata(physicalResultInfos[i].physicalCameraMetadata,
1631 dev->mCaptureResultMetadataQueue.get(),
1632 &localPhysicalResult[i].physicalMetadata);
1633 if (status != ACAMERA_OK) {
1634 ALOGE("%s: physical camera result metadata couldn't be converted", __FUNCTION__);
1635 return ret;
1636 }
1637 }
1638 sp<ACameraPhysicalCaptureResultInfo> physicalResult(
1639 new ACameraPhysicalCaptureResultInfo(localPhysicalResult, frameNumber));
1640
1641 sp<AMessage> msg = new AMessage(
1642 cbh.mIsLogicalCameraCallback ? kWhatLogicalCaptureResult : kWhatCaptureResult,
1643 dev->mHandler);
1644 msg->setPointer(kContextKey, cbh.mContext);
1645 msg->setObject(kSessionSpKey, session);
1646 msg->setObject(kCaptureRequestKey, request);
1647 msg->setObject(kCaptureResultKey, result);
1648 if (isPartialResult) {
1649 msg->setPointer(kCallbackFpKey,
1650 (void *)cbh.mOnCaptureProgressed);
1651 } else if (cbh.mIsLogicalCameraCallback) {
1652 msg->setPointer(kCallbackFpKey,
1653 (void *)cbh.mOnLogicalCameraCaptureCompleted);
1654 msg->setObject(kPhysicalCaptureResultKey, physicalResult);
1655 } else {
1656 msg->setPointer(kCallbackFpKey,
1657 (void *)cbh.mOnCaptureCompleted);
1658 }
1659 dev->postSessionMsgAndCleanup(msg);
1660 }
1661
1662 if (!isPartialResult) {
1663 dev->mFrameNumberTracker.updateTracker(frameNumber, /*isError*/false);
1664 dev->checkAndFireSequenceCompleteLocked();
1665 }
1666
1667 return ret;
1668 }
1669
1670 android::hardware::Return<void>
onRepeatingRequestError(uint64_t lastFrameNumber,int32_t stoppedSequenceId)1671 CameraDevice::ServiceCallback::onRepeatingRequestError(
1672 uint64_t lastFrameNumber, int32_t stoppedSequenceId) {
1673 auto ret = Void();
1674
1675 sp<CameraDevice> dev = mDevice.promote();
1676 if (dev == nullptr) {
1677 return ret; // device has been closed
1678 }
1679
1680 Mutex::Autolock _l(dev->mDeviceLock);
1681
1682 int repeatingSequenceId = dev->mRepeatingSequenceId;
1683 if (stoppedSequenceId == repeatingSequenceId) {
1684 dev->mRepeatingSequenceId = REQUEST_ID_NONE;
1685 }
1686
1687 dev->checkRepeatingSequenceCompleteLocked(repeatingSequenceId, lastFrameNumber);
1688
1689 return ret;
1690 }
1691
readOneResultMetadata(const FmqSizeOrMetadata & fmqSizeOrMetadata,ResultMetadataQueue * metadataQueue,CameraMetadata * metadata)1692 camera_status_t CameraDevice::ServiceCallback::readOneResultMetadata(
1693 const FmqSizeOrMetadata& fmqSizeOrMetadata, ResultMetadataQueue* metadataQueue,
1694 CameraMetadata* metadata) {
1695 if (metadataQueue == nullptr || metadata == nullptr) {
1696 return ACAMERA_ERROR_INVALID_PARAMETER;
1697 }
1698 bool converted;
1699 HCameraMetadata hCameraMetadata;
1700 if (fmqSizeOrMetadata.getDiscriminator() ==
1701 FmqSizeOrMetadata::hidl_discriminator::fmqMetadataSize) {
1702 hCameraMetadata.resize(fmqSizeOrMetadata.fmqMetadataSize());
1703 bool read = metadataQueue->read(
1704 hCameraMetadata.data(), fmqSizeOrMetadata.fmqMetadataSize());
1705 if (!read) {
1706 ALOGE("%s capture request settings could't be read from fmq", __FUNCTION__);
1707 return ACAMERA_ERROR_UNKNOWN;
1708 }
1709 // TODO: Do we actually need to clone here ?
1710 converted = utils::convertFromHidlCloned(hCameraMetadata, metadata);
1711 } else {
1712 converted = utils::convertFromHidlCloned(fmqSizeOrMetadata.metadata(), metadata);
1713 }
1714
1715 return converted ? ACAMERA_OK : ACAMERA_ERROR_UNKNOWN;
1716 }
1717
1718 } // namespace acam
1719 } // namespace android
1720