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