1 /*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "CameraDeviceClient"
18 #define ATRACE_TAG ATRACE_TAG_CAMERA
19 //#define LOG_NDEBUG 0
20
21 #include <cutils/properties.h>
22 #include <utils/Log.h>
23 #include <utils/Trace.h>
24 #include <gui/Surface.h>
25 #include <camera/camera2/CaptureRequest.h>
26 #include <camera/CameraUtils.h>
27
28 #include "common/CameraDeviceBase.h"
29 #include "api2/CameraDeviceClient.h"
30
31 // Convenience methods for constructing binder::Status objects for error returns
32
33 #define STATUS_ERROR(errorCode, errorString) \
34 binder::Status::fromServiceSpecificError(errorCode, \
35 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
36
37 #define STATUS_ERROR_FMT(errorCode, errorString, ...) \
38 binder::Status::fromServiceSpecificError(errorCode, \
39 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
40 __VA_ARGS__))
41
42 namespace android {
43 using namespace camera2;
44
CameraDeviceClientBase(const sp<CameraService> & cameraService,const sp<hardware::camera2::ICameraDeviceCallbacks> & remoteCallback,const String16 & clientPackageName,int cameraId,int cameraFacing,int clientPid,uid_t clientUid,int servicePid)45 CameraDeviceClientBase::CameraDeviceClientBase(
46 const sp<CameraService>& cameraService,
47 const sp<hardware::camera2::ICameraDeviceCallbacks>& remoteCallback,
48 const String16& clientPackageName,
49 int cameraId,
50 int cameraFacing,
51 int clientPid,
52 uid_t clientUid,
53 int servicePid) :
54 BasicClient(cameraService,
55 IInterface::asBinder(remoteCallback),
56 clientPackageName,
57 cameraId,
58 cameraFacing,
59 clientPid,
60 clientUid,
61 servicePid),
62 mRemoteCallback(remoteCallback) {
63 }
64
65 // Interface used by CameraService
66
CameraDeviceClient(const sp<CameraService> & cameraService,const sp<hardware::camera2::ICameraDeviceCallbacks> & remoteCallback,const String16 & clientPackageName,int cameraId,int cameraFacing,int clientPid,uid_t clientUid,int servicePid)67 CameraDeviceClient::CameraDeviceClient(const sp<CameraService>& cameraService,
68 const sp<hardware::camera2::ICameraDeviceCallbacks>& remoteCallback,
69 const String16& clientPackageName,
70 int cameraId,
71 int cameraFacing,
72 int clientPid,
73 uid_t clientUid,
74 int servicePid) :
75 Camera2ClientBase(cameraService, remoteCallback, clientPackageName,
76 cameraId, cameraFacing, clientPid, clientUid, servicePid),
77 mInputStream(),
78 mStreamingRequestId(REQUEST_ID_NONE),
79 mRequestIdCounter(0) {
80
81 ATRACE_CALL();
82 ALOGI("CameraDeviceClient %d: Opened", cameraId);
83 }
84
initialize(CameraModule * module)85 status_t CameraDeviceClient::initialize(CameraModule *module)
86 {
87 ATRACE_CALL();
88 status_t res;
89
90 res = Camera2ClientBase::initialize(module);
91 if (res != OK) {
92 return res;
93 }
94
95 String8 threadName;
96 mFrameProcessor = new FrameProcessorBase(mDevice);
97 threadName = String8::format("CDU-%d-FrameProc", mCameraId);
98 mFrameProcessor->run(threadName.string());
99
100 mFrameProcessor->registerListener(FRAME_PROCESSOR_LISTENER_MIN_ID,
101 FRAME_PROCESSOR_LISTENER_MAX_ID,
102 /*listener*/this,
103 /*sendPartials*/true);
104
105 return OK;
106 }
107
~CameraDeviceClient()108 CameraDeviceClient::~CameraDeviceClient() {
109 }
110
submitRequest(const hardware::camera2::CaptureRequest & request,bool streaming,hardware::camera2::utils::SubmitInfo * submitInfo)111 binder::Status CameraDeviceClient::submitRequest(
112 const hardware::camera2::CaptureRequest& request,
113 bool streaming,
114 /*out*/
115 hardware::camera2::utils::SubmitInfo *submitInfo) {
116 std::vector<hardware::camera2::CaptureRequest> requestList = { request };
117 return submitRequestList(requestList, streaming, submitInfo);
118 }
119
submitRequestList(const std::vector<hardware::camera2::CaptureRequest> & requests,bool streaming,hardware::camera2::utils::SubmitInfo * submitInfo)120 binder::Status CameraDeviceClient::submitRequestList(
121 const std::vector<hardware::camera2::CaptureRequest>& requests,
122 bool streaming,
123 /*out*/
124 hardware::camera2::utils::SubmitInfo *submitInfo) {
125 ATRACE_CALL();
126 ALOGV("%s-start of function. Request list size %zu", __FUNCTION__, requests.size());
127
128 binder::Status res = binder::Status::ok();
129 status_t err;
130 if ( !(res = checkPidStatus(__FUNCTION__) ).isOk()) {
131 return res;
132 }
133
134 Mutex::Autolock icl(mBinderSerializationLock);
135
136 if (!mDevice.get()) {
137 return STATUS_ERROR(CameraService::ERROR_DISCONNECTED, "Camera device no longer alive");
138 }
139
140 if (requests.empty()) {
141 ALOGE("%s: Camera %d: Sent null request. Rejecting request.",
142 __FUNCTION__, mCameraId);
143 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, "Empty request list");
144 }
145
146 List<const CameraMetadata> metadataRequestList;
147 submitInfo->mRequestId = mRequestIdCounter;
148 uint32_t loopCounter = 0;
149
150 for (auto&& request: requests) {
151 if (request.mIsReprocess) {
152 if (!mInputStream.configured) {
153 ALOGE("%s: Camera %d: no input stream is configured.", __FUNCTION__, mCameraId);
154 return STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
155 "No input configured for camera %d but request is for reprocessing",
156 mCameraId);
157 } else if (streaming) {
158 ALOGE("%s: Camera %d: streaming reprocess requests not supported.", __FUNCTION__,
159 mCameraId);
160 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT,
161 "Repeating reprocess requests not supported");
162 }
163 }
164
165 CameraMetadata metadata(request.mMetadata);
166 if (metadata.isEmpty()) {
167 ALOGE("%s: Camera %d: Sent empty metadata packet. Rejecting request.",
168 __FUNCTION__, mCameraId);
169 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT,
170 "Request settings are empty");
171 } else if (request.mSurfaceList.isEmpty()) {
172 ALOGE("%s: Camera %d: Requests must have at least one surface target. "
173 "Rejecting request.", __FUNCTION__, mCameraId);
174 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT,
175 "Request has no output targets");
176 }
177
178 if (!enforceRequestPermissions(metadata)) {
179 // Callee logs
180 return STATUS_ERROR(CameraService::ERROR_PERMISSION_DENIED,
181 "Caller does not have permission to change restricted controls");
182 }
183
184 /**
185 * Write in the output stream IDs which we calculate from
186 * the capture request's list of surface targets
187 */
188 Vector<int32_t> outputStreamIds;
189 outputStreamIds.setCapacity(request.mSurfaceList.size());
190 for (sp<Surface> surface : request.mSurfaceList) {
191 if (surface == 0) continue;
192
193 sp<IGraphicBufferProducer> gbp = surface->getIGraphicBufferProducer();
194 int idx = mStreamMap.indexOfKey(IInterface::asBinder(gbp));
195
196 // Trying to submit request with surface that wasn't created
197 if (idx == NAME_NOT_FOUND) {
198 ALOGE("%s: Camera %d: Tried to submit a request with a surface that"
199 " we have not called createStream on",
200 __FUNCTION__, mCameraId);
201 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT,
202 "Request targets Surface that is not part of current capture session");
203 }
204
205 int streamId = mStreamMap.valueAt(idx);
206 outputStreamIds.push_back(streamId);
207 ALOGV("%s: Camera %d: Appending output stream %d to request",
208 __FUNCTION__, mCameraId, streamId);
209 }
210
211 metadata.update(ANDROID_REQUEST_OUTPUT_STREAMS, &outputStreamIds[0],
212 outputStreamIds.size());
213
214 if (request.mIsReprocess) {
215 metadata.update(ANDROID_REQUEST_INPUT_STREAMS, &mInputStream.id, 1);
216 }
217
218 metadata.update(ANDROID_REQUEST_ID, &(submitInfo->mRequestId), /*size*/1);
219 loopCounter++; // loopCounter starts from 1
220 ALOGV("%s: Camera %d: Creating request with ID %d (%d of %zu)",
221 __FUNCTION__, mCameraId, submitInfo->mRequestId, loopCounter, requests.size());
222
223 metadataRequestList.push_back(metadata);
224 }
225 mRequestIdCounter++;
226
227 if (streaming) {
228 err = mDevice->setStreamingRequestList(metadataRequestList, &(submitInfo->mLastFrameNumber));
229 if (err != OK) {
230 String8 msg = String8::format(
231 "Camera %d: Got error %s (%d) after trying to set streaming request",
232 mCameraId, strerror(-err), err);
233 ALOGE("%s: %s", __FUNCTION__, msg.string());
234 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
235 msg.string());
236 } else {
237 Mutex::Autolock idLock(mStreamingRequestIdLock);
238 mStreamingRequestId = submitInfo->mRequestId;
239 }
240 } else {
241 err = mDevice->captureList(metadataRequestList, &(submitInfo->mLastFrameNumber));
242 if (err != OK) {
243 String8 msg = String8::format(
244 "Camera %d: Got error %s (%d) after trying to submit capture request",
245 mCameraId, strerror(-err), err);
246 ALOGE("%s: %s", __FUNCTION__, msg.string());
247 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
248 msg.string());
249 }
250 ALOGV("%s: requestId = %d ", __FUNCTION__, submitInfo->mRequestId);
251 }
252
253 ALOGV("%s: Camera %d: End of function", __FUNCTION__, mCameraId);
254 return res;
255 }
256
cancelRequest(int requestId,int64_t * lastFrameNumber)257 binder::Status CameraDeviceClient::cancelRequest(
258 int requestId,
259 /*out*/
260 int64_t* lastFrameNumber) {
261 ATRACE_CALL();
262 ALOGV("%s, requestId = %d", __FUNCTION__, requestId);
263
264 status_t err;
265 binder::Status res;
266
267 if (!(res = checkPidStatus(__FUNCTION__)).isOk()) return res;
268
269 Mutex::Autolock icl(mBinderSerializationLock);
270
271 if (!mDevice.get()) {
272 return STATUS_ERROR(CameraService::ERROR_DISCONNECTED, "Camera device no longer alive");
273 }
274
275 Mutex::Autolock idLock(mStreamingRequestIdLock);
276 if (mStreamingRequestId != requestId) {
277 String8 msg = String8::format("Camera %d: Canceling request ID %d doesn't match "
278 "current request ID %d", mCameraId, requestId, mStreamingRequestId);
279 ALOGE("%s: %s", __FUNCTION__, msg.string());
280 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.string());
281 }
282
283 err = mDevice->clearStreamingRequest(lastFrameNumber);
284
285 if (err == OK) {
286 ALOGV("%s: Camera %d: Successfully cleared streaming request",
287 __FUNCTION__, mCameraId);
288 mStreamingRequestId = REQUEST_ID_NONE;
289 } else {
290 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
291 "Camera %d: Error clearing streaming request: %s (%d)",
292 mCameraId, strerror(-err), err);
293 }
294
295 return res;
296 }
297
beginConfigure()298 binder::Status CameraDeviceClient::beginConfigure() {
299 // TODO: Implement this.
300 ALOGV("%s: Not implemented yet.", __FUNCTION__);
301 return binder::Status::ok();
302 }
303
endConfigure(bool isConstrainedHighSpeed)304 binder::Status CameraDeviceClient::endConfigure(bool isConstrainedHighSpeed) {
305 ALOGV("%s: ending configure (%d input stream, %zu output streams)",
306 __FUNCTION__, mInputStream.configured ? 1 : 0, mStreamMap.size());
307
308 binder::Status res;
309 if (!(res = checkPidStatus(__FUNCTION__)).isOk()) return res;
310
311 Mutex::Autolock icl(mBinderSerializationLock);
312
313 if (!mDevice.get()) {
314 return STATUS_ERROR(CameraService::ERROR_DISCONNECTED, "Camera device no longer alive");
315 }
316
317 // Sanitize the high speed session against necessary capability bit.
318 if (isConstrainedHighSpeed) {
319 CameraMetadata staticInfo = mDevice->info();
320 camera_metadata_entry_t entry = staticInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
321 bool isConstrainedHighSpeedSupported = false;
322 for(size_t i = 0; i < entry.count; ++i) {
323 uint8_t capability = entry.data.u8[i];
324 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO) {
325 isConstrainedHighSpeedSupported = true;
326 break;
327 }
328 }
329 if (!isConstrainedHighSpeedSupported) {
330 String8 msg = String8::format(
331 "Camera %d: Try to create a constrained high speed configuration on a device"
332 " that doesn't support it.", mCameraId);
333 ALOGE("%s: %s", __FUNCTION__, msg.string());
334 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT,
335 msg.string());
336 }
337 }
338
339 status_t err = mDevice->configureStreams(isConstrainedHighSpeed);
340 if (err == BAD_VALUE) {
341 String8 msg = String8::format("Camera %d: Unsupported set of inputs/outputs provided",
342 mCameraId);
343 ALOGE("%s: %s", __FUNCTION__, msg.string());
344 res = STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.string());
345 } else if (err != OK) {
346 String8 msg = String8::format("Camera %d: Error configuring streams: %s (%d)",
347 mCameraId, strerror(-err), err);
348 ALOGE("%s: %s", __FUNCTION__, msg.string());
349 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.string());
350 }
351
352 return res;
353 }
354
deleteStream(int streamId)355 binder::Status CameraDeviceClient::deleteStream(int streamId) {
356 ATRACE_CALL();
357 ALOGV("%s (streamId = 0x%x)", __FUNCTION__, streamId);
358
359 binder::Status res;
360 if (!(res = checkPidStatus(__FUNCTION__)).isOk()) return res;
361
362 Mutex::Autolock icl(mBinderSerializationLock);
363
364 if (!mDevice.get()) {
365 return STATUS_ERROR(CameraService::ERROR_DISCONNECTED, "Camera device no longer alive");
366 }
367
368 bool isInput = false;
369 ssize_t index = NAME_NOT_FOUND;
370 ssize_t dIndex = NAME_NOT_FOUND;
371
372 if (mInputStream.configured && mInputStream.id == streamId) {
373 isInput = true;
374 } else {
375 // Guard against trying to delete non-created streams
376 for (size_t i = 0; i < mStreamMap.size(); ++i) {
377 if (streamId == mStreamMap.valueAt(i)) {
378 index = i;
379 break;
380 }
381 }
382
383 if (index == NAME_NOT_FOUND) {
384 // See if this stream is one of the deferred streams.
385 for (size_t i = 0; i < mDeferredStreams.size(); ++i) {
386 if (streamId == mDeferredStreams[i]) {
387 dIndex = i;
388 break;
389 }
390 }
391 if (dIndex == NAME_NOT_FOUND) {
392 String8 msg = String8::format("Camera %d: Invalid stream ID (%d) specified, no such"
393 " stream created yet", mCameraId, streamId);
394 ALOGW("%s: %s", __FUNCTION__, msg.string());
395 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.string());
396 }
397 }
398 }
399
400 // Also returns BAD_VALUE if stream ID was not valid
401 status_t err = mDevice->deleteStream(streamId);
402
403 if (err != OK) {
404 String8 msg = String8::format("Camera %d: Unexpected error %s (%d) when deleting stream %d",
405 mCameraId, strerror(-err), err, streamId);
406 ALOGE("%s: %s", __FUNCTION__, msg.string());
407 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.string());
408 } else {
409 if (isInput) {
410 mInputStream.configured = false;
411 } else if (index != NAME_NOT_FOUND) {
412 mStreamMap.removeItemsAt(index);
413 } else {
414 mDeferredStreams.removeItemsAt(dIndex);
415 }
416 }
417
418 return res;
419 }
420
createStream(const hardware::camera2::params::OutputConfiguration & outputConfiguration,int32_t * newStreamId)421 binder::Status CameraDeviceClient::createStream(
422 const hardware::camera2::params::OutputConfiguration &outputConfiguration,
423 /*out*/
424 int32_t* newStreamId) {
425 ATRACE_CALL();
426
427 binder::Status res;
428 if (!(res = checkPidStatus(__FUNCTION__)).isOk()) return res;
429
430 Mutex::Autolock icl(mBinderSerializationLock);
431
432 sp<IGraphicBufferProducer> bufferProducer = outputConfiguration.getGraphicBufferProducer();
433 bool deferredConsumer = bufferProducer == NULL;
434 int surfaceType = outputConfiguration.getSurfaceType();
435 bool validSurfaceType = ((surfaceType == OutputConfiguration::SURFACE_TYPE_SURFACE_VIEW) ||
436 (surfaceType == OutputConfiguration::SURFACE_TYPE_SURFACE_TEXTURE));
437 if (deferredConsumer && !validSurfaceType) {
438 ALOGE("%s: Target surface is invalid: bufferProducer = %p, surfaceType = %d.",
439 __FUNCTION__, bufferProducer.get(), surfaceType);
440 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, "Target Surface is invalid");
441 }
442
443 if (!mDevice.get()) {
444 return STATUS_ERROR(CameraService::ERROR_DISCONNECTED, "Camera device no longer alive");
445 }
446
447 int width, height, format;
448 int32_t consumerUsage;
449 android_dataspace dataSpace;
450 status_t err;
451
452 // Create stream for deferred surface case.
453 if (deferredConsumer) {
454 return createDeferredSurfaceStreamLocked(outputConfiguration, newStreamId);
455 }
456
457 // Don't create multiple streams for the same target surface
458 {
459 ssize_t index = mStreamMap.indexOfKey(IInterface::asBinder(bufferProducer));
460 if (index != NAME_NOT_FOUND) {
461 String8 msg = String8::format("Camera %d: Surface already has a stream created for it "
462 "(ID %zd)", mCameraId, index);
463 ALOGW("%s: %s", __FUNCTION__, msg.string());
464 return STATUS_ERROR(CameraService::ERROR_ALREADY_EXISTS, msg.string());
465 }
466 }
467
468 // HACK b/10949105
469 // Query consumer usage bits to set async operation mode for
470 // GLConsumer using controlledByApp parameter.
471 bool useAsync = false;
472 if ((err = bufferProducer->query(NATIVE_WINDOW_CONSUMER_USAGE_BITS,
473 &consumerUsage)) != OK) {
474 String8 msg = String8::format("Camera %d: Failed to query Surface consumer usage: %s (%d)",
475 mCameraId, strerror(-err), err);
476 ALOGE("%s: %s", __FUNCTION__, msg.string());
477 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.string());
478 }
479 if (consumerUsage & GraphicBuffer::USAGE_HW_TEXTURE) {
480 ALOGW("%s: Camera %d with consumer usage flag: 0x%x: Forcing asynchronous mode for stream",
481 __FUNCTION__, mCameraId, consumerUsage);
482 useAsync = true;
483 }
484
485 int32_t disallowedFlags = GraphicBuffer::USAGE_HW_VIDEO_ENCODER |
486 GRALLOC_USAGE_RENDERSCRIPT;
487 int32_t allowedFlags = GraphicBuffer::USAGE_SW_READ_MASK |
488 GraphicBuffer::USAGE_HW_TEXTURE |
489 GraphicBuffer::USAGE_HW_COMPOSER;
490 bool flexibleConsumer = (consumerUsage & disallowedFlags) == 0 &&
491 (consumerUsage & allowedFlags) != 0;
492
493 sp<IBinder> binder = IInterface::asBinder(bufferProducer);
494 sp<Surface> surface = new Surface(bufferProducer, useAsync);
495 ANativeWindow *anw = surface.get();
496
497 if ((err = anw->query(anw, NATIVE_WINDOW_WIDTH, &width)) != OK) {
498 String8 msg = String8::format("Camera %d: Failed to query Surface width: %s (%d)",
499 mCameraId, strerror(-err), err);
500 ALOGE("%s: %s", __FUNCTION__, msg.string());
501 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.string());
502 }
503 if ((err = anw->query(anw, NATIVE_WINDOW_HEIGHT, &height)) != OK) {
504 String8 msg = String8::format("Camera %d: Failed to query Surface height: %s (%d)",
505 mCameraId, strerror(-err), err);
506 ALOGE("%s: %s", __FUNCTION__, msg.string());
507 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.string());
508 }
509 if ((err = anw->query(anw, NATIVE_WINDOW_FORMAT, &format)) != OK) {
510 String8 msg = String8::format("Camera %d: Failed to query Surface format: %s (%d)",
511 mCameraId, strerror(-err), err);
512 ALOGE("%s: %s", __FUNCTION__, msg.string());
513 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.string());
514 }
515 if ((err = anw->query(anw, NATIVE_WINDOW_DEFAULT_DATASPACE,
516 reinterpret_cast<int*>(&dataSpace))) != OK) {
517 String8 msg = String8::format("Camera %d: Failed to query Surface dataspace: %s (%d)",
518 mCameraId, strerror(-err), err);
519 ALOGE("%s: %s", __FUNCTION__, msg.string());
520 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.string());
521 }
522
523 // FIXME: remove this override since the default format should be
524 // IMPLEMENTATION_DEFINED. b/9487482
525 if (format >= HAL_PIXEL_FORMAT_RGBA_8888 &&
526 format <= HAL_PIXEL_FORMAT_BGRA_8888) {
527 ALOGW("%s: Camera %d: Overriding format %#x to IMPLEMENTATION_DEFINED",
528 __FUNCTION__, mCameraId, format);
529 format = HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
530 }
531
532 // Round dimensions to the nearest dimensions available for this format
533 if (flexibleConsumer && !CameraDeviceClient::roundBufferDimensionNearest(width, height,
534 format, dataSpace, mDevice->info(), /*out*/&width, /*out*/&height)) {
535 String8 msg = String8::format("Camera %d: No supported stream configurations with "
536 "format %#x defined, failed to create output stream", mCameraId, format);
537 ALOGE("%s: %s", __FUNCTION__, msg.string());
538 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.string());
539 }
540
541 int streamId = camera3::CAMERA3_STREAM_ID_INVALID;
542 err = mDevice->createStream(surface, width, height, format, dataSpace,
543 static_cast<camera3_stream_rotation_t>(outputConfiguration.getRotation()),
544 &streamId, outputConfiguration.getSurfaceSetID());
545
546 if (err != OK) {
547 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
548 "Camera %d: Error creating output stream (%d x %d, fmt %x, dataSpace %x): %s (%d)",
549 mCameraId, width, height, format, dataSpace, strerror(-err), err);
550 } else {
551 mStreamMap.add(binder, streamId);
552
553 ALOGV("%s: Camera %d: Successfully created a new stream ID %d for output surface"
554 " (%d x %d) with format 0x%x.",
555 __FUNCTION__, mCameraId, streamId, width, height, format);
556
557 // Set transform flags to ensure preview to be rotated correctly.
558 res = setStreamTransformLocked(streamId);
559
560 *newStreamId = streamId;
561 }
562
563 return res;
564 }
565
createDeferredSurfaceStreamLocked(const hardware::camera2::params::OutputConfiguration & outputConfiguration,int * newStreamId)566 binder::Status CameraDeviceClient::createDeferredSurfaceStreamLocked(
567 const hardware::camera2::params::OutputConfiguration &outputConfiguration,
568 /*out*/
569 int* newStreamId) {
570 int width, height, format, surfaceType;
571 int32_t consumerUsage;
572 android_dataspace dataSpace;
573 status_t err;
574 binder::Status res;
575
576 if (!mDevice.get()) {
577 return STATUS_ERROR(CameraService::ERROR_DISCONNECTED, "Camera device no longer alive");
578 }
579
580 // Infer the surface info for deferred surface stream creation.
581 width = outputConfiguration.getWidth();
582 height = outputConfiguration.getHeight();
583 surfaceType = outputConfiguration.getSurfaceType();
584 format = HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
585 dataSpace = android_dataspace_t::HAL_DATASPACE_UNKNOWN;
586 // Hardcode consumer usage flags: SurfaceView--0x900, SurfaceTexture--0x100.
587 consumerUsage = GraphicBuffer::USAGE_HW_TEXTURE;
588 if (surfaceType == OutputConfiguration::SURFACE_TYPE_SURFACE_VIEW) {
589 consumerUsage |= GraphicBuffer::USAGE_HW_COMPOSER;
590 }
591 int streamId = camera3::CAMERA3_STREAM_ID_INVALID;
592 err = mDevice->createStream(/*surface*/nullptr, width, height, format, dataSpace,
593 static_cast<camera3_stream_rotation_t>(outputConfiguration.getRotation()),
594 &streamId, outputConfiguration.getSurfaceSetID(), consumerUsage);
595
596 if (err != OK) {
597 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
598 "Camera %d: Error creating output stream (%d x %d, fmt %x, dataSpace %x): %s (%d)",
599 mCameraId, width, height, format, dataSpace, strerror(-err), err);
600 } else {
601 // Can not add streamId to mStreamMap here, as the surface is deferred. Add it to
602 // a separate list to track. Once the deferred surface is set, this id will be
603 // relocated to mStreamMap.
604 mDeferredStreams.push_back(streamId);
605
606 ALOGV("%s: Camera %d: Successfully created a new stream ID %d for a deferred surface"
607 " (%d x %d) stream with format 0x%x.",
608 __FUNCTION__, mCameraId, streamId, width, height, format);
609
610 // Set transform flags to ensure preview to be rotated correctly.
611 res = setStreamTransformLocked(streamId);
612
613 *newStreamId = streamId;
614 }
615 return res;
616 }
617
setStreamTransformLocked(int streamId)618 binder::Status CameraDeviceClient::setStreamTransformLocked(int streamId) {
619 int32_t transform = 0;
620 status_t err;
621 binder::Status res;
622
623 if (!mDevice.get()) {
624 return STATUS_ERROR(CameraService::ERROR_DISCONNECTED, "Camera device no longer alive");
625 }
626
627 err = getRotationTransformLocked(&transform);
628 if (err != OK) {
629 // Error logged by getRotationTransformLocked.
630 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
631 "Unable to calculate rotation transform for new stream");
632 }
633
634 err = mDevice->setStreamTransform(streamId, transform);
635 if (err != OK) {
636 String8 msg = String8::format("Failed to set stream transform (stream id %d)",
637 streamId);
638 ALOGE("%s: %s", __FUNCTION__, msg.string());
639 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.string());
640 }
641
642 return res;
643 }
644
createInputStream(int width,int height,int format,int32_t * newStreamId)645 binder::Status CameraDeviceClient::createInputStream(
646 int width, int height, int format,
647 /*out*/
648 int32_t* newStreamId) {
649
650 ATRACE_CALL();
651 ALOGV("%s (w = %d, h = %d, f = 0x%x)", __FUNCTION__, width, height, format);
652
653 binder::Status res;
654 if (!(res = checkPidStatus(__FUNCTION__)).isOk()) return res;
655
656 Mutex::Autolock icl(mBinderSerializationLock);
657
658 if (!mDevice.get()) {
659 return STATUS_ERROR(CameraService::ERROR_DISCONNECTED, "Camera device no longer alive");
660 }
661
662 if (mInputStream.configured) {
663 String8 msg = String8::format("Camera %d: Already has an input stream "
664 "configured (ID %zd)", mCameraId, mInputStream.id);
665 ALOGE("%s: %s", __FUNCTION__, msg.string() );
666 return STATUS_ERROR(CameraService::ERROR_ALREADY_EXISTS, msg.string());
667 }
668
669 int streamId = -1;
670 status_t err = mDevice->createInputStream(width, height, format, &streamId);
671 if (err == OK) {
672 mInputStream.configured = true;
673 mInputStream.width = width;
674 mInputStream.height = height;
675 mInputStream.format = format;
676 mInputStream.id = streamId;
677
678 ALOGV("%s: Camera %d: Successfully created a new input stream ID %d",
679 __FUNCTION__, mCameraId, streamId);
680
681 *newStreamId = streamId;
682 } else {
683 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
684 "Camera %d: Error creating new input stream: %s (%d)", mCameraId,
685 strerror(-err), err);
686 }
687
688 return res;
689 }
690
getInputSurface(view::Surface * inputSurface)691 binder::Status CameraDeviceClient::getInputSurface(/*out*/ view::Surface *inputSurface) {
692
693 binder::Status res;
694 if (!(res = checkPidStatus(__FUNCTION__)).isOk()) return res;
695
696 if (inputSurface == NULL) {
697 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, "Null input surface");
698 }
699
700 Mutex::Autolock icl(mBinderSerializationLock);
701 if (!mDevice.get()) {
702 return STATUS_ERROR(CameraService::ERROR_DISCONNECTED, "Camera device no longer alive");
703 }
704 sp<IGraphicBufferProducer> producer;
705 status_t err = mDevice->getInputBufferProducer(&producer);
706 if (err != OK) {
707 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
708 "Camera %d: Error getting input Surface: %s (%d)",
709 mCameraId, strerror(-err), err);
710 } else {
711 inputSurface->name = String16("CameraInput");
712 inputSurface->graphicBufferProducer = producer;
713 }
714 return res;
715 }
716
roundBufferDimensionNearest(int32_t width,int32_t height,int32_t format,android_dataspace dataSpace,const CameraMetadata & info,int32_t * outWidth,int32_t * outHeight)717 bool CameraDeviceClient::roundBufferDimensionNearest(int32_t width, int32_t height,
718 int32_t format, android_dataspace dataSpace, const CameraMetadata& info,
719 /*out*/int32_t* outWidth, /*out*/int32_t* outHeight) {
720
721 camera_metadata_ro_entry streamConfigs =
722 (dataSpace == HAL_DATASPACE_DEPTH) ?
723 info.find(ANDROID_DEPTH_AVAILABLE_DEPTH_STREAM_CONFIGURATIONS) :
724 info.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
725
726 int32_t bestWidth = -1;
727 int32_t bestHeight = -1;
728
729 // Iterate through listed stream configurations and find the one with the smallest euclidean
730 // distance from the given dimensions for the given format.
731 for (size_t i = 0; i < streamConfigs.count; i += 4) {
732 int32_t fmt = streamConfigs.data.i32[i];
733 int32_t w = streamConfigs.data.i32[i + 1];
734 int32_t h = streamConfigs.data.i32[i + 2];
735
736 // Ignore input/output type for now
737 if (fmt == format) {
738 if (w == width && h == height) {
739 bestWidth = width;
740 bestHeight = height;
741 break;
742 } else if (w <= ROUNDING_WIDTH_CAP && (bestWidth == -1 ||
743 CameraDeviceClient::euclidDistSquare(w, h, width, height) <
744 CameraDeviceClient::euclidDistSquare(bestWidth, bestHeight, width, height))) {
745 bestWidth = w;
746 bestHeight = h;
747 }
748 }
749 }
750
751 if (bestWidth == -1) {
752 // Return false if no configurations for this format were listed
753 return false;
754 }
755
756 // Set the outputs to the closet width/height
757 if (outWidth != NULL) {
758 *outWidth = bestWidth;
759 }
760 if (outHeight != NULL) {
761 *outHeight = bestHeight;
762 }
763
764 // Return true if at least one configuration for this format was listed
765 return true;
766 }
767
euclidDistSquare(int32_t x0,int32_t y0,int32_t x1,int32_t y1)768 int64_t CameraDeviceClient::euclidDistSquare(int32_t x0, int32_t y0, int32_t x1, int32_t y1) {
769 int64_t d0 = x0 - x1;
770 int64_t d1 = y0 - y1;
771 return d0 * d0 + d1 * d1;
772 }
773
774 // Create a request object from a template.
createDefaultRequest(int templateId,hardware::camera2::impl::CameraMetadataNative * request)775 binder::Status CameraDeviceClient::createDefaultRequest(int templateId,
776 /*out*/
777 hardware::camera2::impl::CameraMetadataNative* request)
778 {
779 ATRACE_CALL();
780 ALOGV("%s (templateId = 0x%x)", __FUNCTION__, templateId);
781
782 binder::Status res;
783 if (!(res = checkPidStatus(__FUNCTION__)).isOk()) return res;
784
785 Mutex::Autolock icl(mBinderSerializationLock);
786
787 if (!mDevice.get()) {
788 return STATUS_ERROR(CameraService::ERROR_DISCONNECTED, "Camera device no longer alive");
789 }
790
791 CameraMetadata metadata;
792 status_t err;
793 if ( (err = mDevice->createDefaultRequest(templateId, &metadata) ) == OK &&
794 request != NULL) {
795
796 request->swap(metadata);
797 } else if (err == BAD_VALUE) {
798 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
799 "Camera %d: Template ID %d is invalid or not supported: %s (%d)",
800 mCameraId, templateId, strerror(-err), err);
801
802 } else {
803 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
804 "Camera %d: Error creating default request for template %d: %s (%d)",
805 mCameraId, templateId, strerror(-err), err);
806 }
807 return res;
808 }
809
getCameraInfo(hardware::camera2::impl::CameraMetadataNative * info)810 binder::Status CameraDeviceClient::getCameraInfo(
811 /*out*/
812 hardware::camera2::impl::CameraMetadataNative* info)
813 {
814 ATRACE_CALL();
815 ALOGV("%s", __FUNCTION__);
816
817 binder::Status res;
818
819 if (!(res = checkPidStatus(__FUNCTION__)).isOk()) return res;
820
821 Mutex::Autolock icl(mBinderSerializationLock);
822
823 if (!mDevice.get()) {
824 return STATUS_ERROR(CameraService::ERROR_DISCONNECTED, "Camera device no longer alive");
825 }
826
827 if (info != NULL) {
828 *info = mDevice->info(); // static camera metadata
829 // TODO: merge with device-specific camera metadata
830 }
831
832 return res;
833 }
834
waitUntilIdle()835 binder::Status CameraDeviceClient::waitUntilIdle()
836 {
837 ATRACE_CALL();
838 ALOGV("%s", __FUNCTION__);
839
840 binder::Status res;
841 if (!(res = checkPidStatus(__FUNCTION__)).isOk()) return res;
842
843 Mutex::Autolock icl(mBinderSerializationLock);
844
845 if (!mDevice.get()) {
846 return STATUS_ERROR(CameraService::ERROR_DISCONNECTED, "Camera device no longer alive");
847 }
848
849 // FIXME: Also need check repeating burst.
850 Mutex::Autolock idLock(mStreamingRequestIdLock);
851 if (mStreamingRequestId != REQUEST_ID_NONE) {
852 String8 msg = String8::format(
853 "Camera %d: Try to waitUntilIdle when there are active streaming requests",
854 mCameraId);
855 ALOGE("%s: %s", __FUNCTION__, msg.string());
856 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.string());
857 }
858 status_t err = mDevice->waitUntilDrained();
859 if (err != OK) {
860 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
861 "Camera %d: Error waiting to drain: %s (%d)",
862 mCameraId, strerror(-err), err);
863 }
864 ALOGV("%s Done", __FUNCTION__);
865 return res;
866 }
867
flush(int64_t * lastFrameNumber)868 binder::Status CameraDeviceClient::flush(
869 /*out*/
870 int64_t* lastFrameNumber) {
871 ATRACE_CALL();
872 ALOGV("%s", __FUNCTION__);
873
874 binder::Status res;
875 if (!(res = checkPidStatus(__FUNCTION__)).isOk()) return res;
876
877 Mutex::Autolock icl(mBinderSerializationLock);
878
879 if (!mDevice.get()) {
880 return STATUS_ERROR(CameraService::ERROR_DISCONNECTED, "Camera device no longer alive");
881 }
882
883 Mutex::Autolock idLock(mStreamingRequestIdLock);
884 mStreamingRequestId = REQUEST_ID_NONE;
885 status_t err = mDevice->flush(lastFrameNumber);
886 if (err != OK) {
887 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
888 "Camera %d: Error flushing device: %s (%d)", mCameraId, strerror(-err), err);
889 }
890 return res;
891 }
892
prepare(int streamId)893 binder::Status CameraDeviceClient::prepare(int streamId) {
894 ATRACE_CALL();
895 ALOGV("%s", __FUNCTION__);
896
897 binder::Status res;
898 if (!(res = checkPidStatus(__FUNCTION__)).isOk()) return res;
899
900 Mutex::Autolock icl(mBinderSerializationLock);
901
902 // Guard against trying to prepare non-created streams
903 ssize_t index = NAME_NOT_FOUND;
904 for (size_t i = 0; i < mStreamMap.size(); ++i) {
905 if (streamId == mStreamMap.valueAt(i)) {
906 index = i;
907 break;
908 }
909 }
910
911 if (index == NAME_NOT_FOUND) {
912 String8 msg = String8::format("Camera %d: Invalid stream ID (%d) specified, no stream "
913 "with that ID exists", mCameraId, streamId);
914 ALOGW("%s: %s", __FUNCTION__, msg.string());
915 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.string());
916 }
917
918 // Also returns BAD_VALUE if stream ID was not valid, or stream already
919 // has been used
920 status_t err = mDevice->prepare(streamId);
921 if (err == BAD_VALUE) {
922 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
923 "Camera %d: Stream %d has already been used, and cannot be prepared",
924 mCameraId, streamId);
925 } else if (err != OK) {
926 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
927 "Camera %d: Error preparing stream %d: %s (%d)", mCameraId, streamId,
928 strerror(-err), err);
929 }
930 return res;
931 }
932
prepare2(int maxCount,int streamId)933 binder::Status CameraDeviceClient::prepare2(int maxCount, int streamId) {
934 ATRACE_CALL();
935 ALOGV("%s", __FUNCTION__);
936
937 binder::Status res;
938 if (!(res = checkPidStatus(__FUNCTION__)).isOk()) return res;
939
940 Mutex::Autolock icl(mBinderSerializationLock);
941
942 // Guard against trying to prepare non-created streams
943 ssize_t index = NAME_NOT_FOUND;
944 for (size_t i = 0; i < mStreamMap.size(); ++i) {
945 if (streamId == mStreamMap.valueAt(i)) {
946 index = i;
947 break;
948 }
949 }
950
951 if (index == NAME_NOT_FOUND) {
952 String8 msg = String8::format("Camera %d: Invalid stream ID (%d) specified, no stream "
953 "with that ID exists", mCameraId, streamId);
954 ALOGW("%s: %s", __FUNCTION__, msg.string());
955 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.string());
956 }
957
958 if (maxCount <= 0) {
959 String8 msg = String8::format("Camera %d: maxCount (%d) must be greater than 0",
960 mCameraId, maxCount);
961 ALOGE("%s: %s", __FUNCTION__, msg.string());
962 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.string());
963 }
964
965 // Also returns BAD_VALUE if stream ID was not valid, or stream already
966 // has been used
967 status_t err = mDevice->prepare(maxCount, streamId);
968 if (err == BAD_VALUE) {
969 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
970 "Camera %d: Stream %d has already been used, and cannot be prepared",
971 mCameraId, streamId);
972 } else if (err != OK) {
973 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
974 "Camera %d: Error preparing stream %d: %s (%d)", mCameraId, streamId,
975 strerror(-err), err);
976 }
977
978 return res;
979 }
980
tearDown(int streamId)981 binder::Status CameraDeviceClient::tearDown(int streamId) {
982 ATRACE_CALL();
983 ALOGV("%s", __FUNCTION__);
984
985 binder::Status res;
986 if (!(res = checkPidStatus(__FUNCTION__)).isOk()) return res;
987
988 Mutex::Autolock icl(mBinderSerializationLock);
989
990 // Guard against trying to prepare non-created streams
991 ssize_t index = NAME_NOT_FOUND;
992 for (size_t i = 0; i < mStreamMap.size(); ++i) {
993 if (streamId == mStreamMap.valueAt(i)) {
994 index = i;
995 break;
996 }
997 }
998
999 if (index == NAME_NOT_FOUND) {
1000 String8 msg = String8::format("Camera %d: Invalid stream ID (%d) specified, no stream "
1001 "with that ID exists", mCameraId, streamId);
1002 ALOGW("%s: %s", __FUNCTION__, msg.string());
1003 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.string());
1004 }
1005
1006 // Also returns BAD_VALUE if stream ID was not valid or if the stream is in
1007 // use
1008 status_t err = mDevice->tearDown(streamId);
1009 if (err == BAD_VALUE) {
1010 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
1011 "Camera %d: Stream %d is still in use, cannot be torn down",
1012 mCameraId, streamId);
1013 } else if (err != OK) {
1014 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
1015 "Camera %d: Error tearing down stream %d: %s (%d)", mCameraId, streamId,
1016 strerror(-err), err);
1017 }
1018
1019 return res;
1020 }
1021
setDeferredConfiguration(int32_t streamId,const hardware::camera2::params::OutputConfiguration & outputConfiguration)1022 binder::Status CameraDeviceClient::setDeferredConfiguration(int32_t streamId,
1023 const hardware::camera2::params::OutputConfiguration &outputConfiguration) {
1024 ATRACE_CALL();
1025
1026 binder::Status res;
1027 if (!(res = checkPidStatus(__FUNCTION__)).isOk()) return res;
1028
1029 Mutex::Autolock icl(mBinderSerializationLock);
1030
1031 sp<IGraphicBufferProducer> bufferProducer = outputConfiguration.getGraphicBufferProducer();
1032
1033 // Client code should guarantee that the surface is from SurfaceView or SurfaceTexture.
1034 if (bufferProducer == NULL) {
1035 ALOGE("%s: bufferProducer must not be null", __FUNCTION__);
1036 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, "Target Surface is invalid");
1037 }
1038 // Check if this stram id is one of the deferred streams
1039 ssize_t index = NAME_NOT_FOUND;
1040 for (size_t i = 0; i < mDeferredStreams.size(); i++) {
1041 if (streamId == mDeferredStreams[i]) {
1042 index = i;
1043 break;
1044 }
1045 }
1046 if (index == NAME_NOT_FOUND) {
1047 String8 msg = String8::format("Camera %d: deferred surface is set to a unknown stream"
1048 "(ID %d)", mCameraId, streamId);
1049 ALOGW("%s: %s", __FUNCTION__, msg.string());
1050 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.string());
1051 }
1052
1053 if (!mDevice.get()) {
1054 return STATUS_ERROR(CameraService::ERROR_DISCONNECTED, "Camera device no longer alive");
1055 }
1056
1057 // Don't create multiple streams for the same target surface
1058 {
1059 ssize_t index = mStreamMap.indexOfKey(IInterface::asBinder(bufferProducer));
1060 if (index != NAME_NOT_FOUND) {
1061 String8 msg = String8::format("Camera %d: Surface already has a stream created "
1062 " for it (ID %zd)", mCameraId, index);
1063 ALOGW("%s: %s", __FUNCTION__, msg.string());
1064 return STATUS_ERROR(CameraService::ERROR_ALREADY_EXISTS, msg.string());
1065 }
1066 }
1067
1068 status_t err;
1069
1070 // Always set to async, as we know the deferred surface is for preview streaming.
1071 sp<Surface> consumerSurface = new Surface(bufferProducer, /*useAsync*/true);
1072
1073 // Finish the deferred stream configuration with the surface.
1074 err = mDevice->setConsumerSurface(streamId, consumerSurface);
1075 if (err == OK) {
1076 sp<IBinder> binder = IInterface::asBinder(bufferProducer);
1077 mStreamMap.add(binder, streamId);
1078 mDeferredStreams.removeItemsAt(index);
1079 } else if (err == NO_INIT) {
1080 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
1081 "Camera %d: Deferred surface is invalid: %s (%d)",
1082 mCameraId, strerror(-err), err);
1083 } else {
1084 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
1085 "Camera %d: Error setting output stream deferred surface: %s (%d)",
1086 mCameraId, strerror(-err), err);
1087 }
1088
1089 return res;
1090 }
1091
dump(int fd,const Vector<String16> & args)1092 status_t CameraDeviceClient::dump(int fd, const Vector<String16>& args) {
1093 return BasicClient::dump(fd, args);
1094 }
1095
dumpClient(int fd,const Vector<String16> & args)1096 status_t CameraDeviceClient::dumpClient(int fd, const Vector<String16>& args) {
1097 String8 result;
1098 result.appendFormat("CameraDeviceClient[%d] (%p) dump:\n",
1099 mCameraId,
1100 (getRemoteCallback() != NULL ?
1101 IInterface::asBinder(getRemoteCallback()).get() : NULL) );
1102 result.appendFormat(" Current client UID %u\n", mClientUid);
1103
1104 result.append(" State:\n");
1105 result.appendFormat(" Request ID counter: %d\n", mRequestIdCounter);
1106 if (mInputStream.configured) {
1107 result.appendFormat(" Current input stream ID: %d\n",
1108 mInputStream.id);
1109 } else {
1110 result.append(" No input stream configured.\n");
1111 }
1112 if (!mStreamMap.isEmpty()) {
1113 result.append(" Current output stream IDs:\n");
1114 for (size_t i = 0; i < mStreamMap.size(); i++) {
1115 result.appendFormat(" Stream %d\n", mStreamMap.valueAt(i));
1116 }
1117 } else if (!mDeferredStreams.isEmpty()) {
1118 result.append(" Current deferred surface output stream IDs:\n");
1119 for (auto& streamId : mDeferredStreams) {
1120 result.appendFormat(" Stream %d\n", streamId);
1121 }
1122 } else {
1123 result.append(" No output streams configured.\n");
1124 }
1125 write(fd, result.string(), result.size());
1126 // TODO: print dynamic/request section from most recent requests
1127 mFrameProcessor->dump(fd, args);
1128
1129 return dumpDevice(fd, args);
1130 }
1131
notifyError(int32_t errorCode,const CaptureResultExtras & resultExtras)1132 void CameraDeviceClient::notifyError(int32_t errorCode,
1133 const CaptureResultExtras& resultExtras) {
1134 // Thread safe. Don't bother locking.
1135 sp<hardware::camera2::ICameraDeviceCallbacks> remoteCb = getRemoteCallback();
1136
1137 if (remoteCb != 0) {
1138 remoteCb->onDeviceError(errorCode, resultExtras);
1139 }
1140 }
1141
notifyRepeatingRequestError(long lastFrameNumber)1142 void CameraDeviceClient::notifyRepeatingRequestError(long lastFrameNumber) {
1143 sp<hardware::camera2::ICameraDeviceCallbacks> remoteCb = getRemoteCallback();
1144
1145 if (remoteCb != 0) {
1146 remoteCb->onRepeatingRequestError(lastFrameNumber);
1147 }
1148
1149 Mutex::Autolock idLock(mStreamingRequestIdLock);
1150 mStreamingRequestId = REQUEST_ID_NONE;
1151 }
1152
notifyIdle()1153 void CameraDeviceClient::notifyIdle() {
1154 // Thread safe. Don't bother locking.
1155 sp<hardware::camera2::ICameraDeviceCallbacks> remoteCb = getRemoteCallback();
1156
1157 if (remoteCb != 0) {
1158 remoteCb->onDeviceIdle();
1159 }
1160 Camera2ClientBase::notifyIdle();
1161 }
1162
notifyShutter(const CaptureResultExtras & resultExtras,nsecs_t timestamp)1163 void CameraDeviceClient::notifyShutter(const CaptureResultExtras& resultExtras,
1164 nsecs_t timestamp) {
1165 // Thread safe. Don't bother locking.
1166 sp<hardware::camera2::ICameraDeviceCallbacks> remoteCb = getRemoteCallback();
1167 if (remoteCb != 0) {
1168 remoteCb->onCaptureStarted(resultExtras, timestamp);
1169 }
1170 Camera2ClientBase::notifyShutter(resultExtras, timestamp);
1171 }
1172
notifyPrepared(int streamId)1173 void CameraDeviceClient::notifyPrepared(int streamId) {
1174 // Thread safe. Don't bother locking.
1175 sp<hardware::camera2::ICameraDeviceCallbacks> remoteCb = getRemoteCallback();
1176 if (remoteCb != 0) {
1177 remoteCb->onPrepared(streamId);
1178 }
1179 }
1180
detachDevice()1181 void CameraDeviceClient::detachDevice() {
1182 if (mDevice == 0) return;
1183
1184 ALOGV("Camera %d: Stopping processors", mCameraId);
1185
1186 mFrameProcessor->removeListener(FRAME_PROCESSOR_LISTENER_MIN_ID,
1187 FRAME_PROCESSOR_LISTENER_MAX_ID,
1188 /*listener*/this);
1189 mFrameProcessor->requestExit();
1190 ALOGV("Camera %d: Waiting for threads", mCameraId);
1191 mFrameProcessor->join();
1192 ALOGV("Camera %d: Disconnecting device", mCameraId);
1193
1194 // WORKAROUND: HAL refuses to disconnect while there's streams in flight
1195 {
1196 mDevice->clearStreamingRequest();
1197
1198 status_t code;
1199 if ((code = mDevice->waitUntilDrained()) != OK) {
1200 ALOGE("%s: waitUntilDrained failed with code 0x%x", __FUNCTION__,
1201 code);
1202 }
1203 }
1204
1205 Camera2ClientBase::detachDevice();
1206 }
1207
1208 /** Device-related methods */
onResultAvailable(const CaptureResult & result)1209 void CameraDeviceClient::onResultAvailable(const CaptureResult& result) {
1210 ATRACE_CALL();
1211 ALOGV("%s", __FUNCTION__);
1212
1213 // Thread-safe. No lock necessary.
1214 sp<hardware::camera2::ICameraDeviceCallbacks> remoteCb = mRemoteCallback;
1215 if (remoteCb != NULL) {
1216 remoteCb->onResultReceived(result.mMetadata, result.mResultExtras);
1217 }
1218 }
1219
checkPidStatus(const char * checkLocation)1220 binder::Status CameraDeviceClient::checkPidStatus(const char* checkLocation) {
1221 if (mDisconnected) {
1222 return STATUS_ERROR(CameraService::ERROR_DISCONNECTED,
1223 "The camera device has been disconnected");
1224 }
1225 status_t res = checkPid(checkLocation);
1226 return (res == OK) ? binder::Status::ok() :
1227 STATUS_ERROR(CameraService::ERROR_PERMISSION_DENIED,
1228 "Attempt to use camera from a different process than original client");
1229 }
1230
1231 // TODO: move to Camera2ClientBase
enforceRequestPermissions(CameraMetadata & metadata)1232 bool CameraDeviceClient::enforceRequestPermissions(CameraMetadata& metadata) {
1233
1234 const int pid = IPCThreadState::self()->getCallingPid();
1235 const int selfPid = getpid();
1236 camera_metadata_entry_t entry;
1237
1238 /**
1239 * Mixin default important security values
1240 * - android.led.transmit = defaulted ON
1241 */
1242 CameraMetadata staticInfo = mDevice->info();
1243 entry = staticInfo.find(ANDROID_LED_AVAILABLE_LEDS);
1244 for(size_t i = 0; i < entry.count; ++i) {
1245 uint8_t led = entry.data.u8[i];
1246
1247 switch(led) {
1248 case ANDROID_LED_AVAILABLE_LEDS_TRANSMIT: {
1249 uint8_t transmitDefault = ANDROID_LED_TRANSMIT_ON;
1250 if (!metadata.exists(ANDROID_LED_TRANSMIT)) {
1251 metadata.update(ANDROID_LED_TRANSMIT,
1252 &transmitDefault, 1);
1253 }
1254 break;
1255 }
1256 }
1257 }
1258
1259 // We can do anything!
1260 if (pid == selfPid) {
1261 return true;
1262 }
1263
1264 /**
1265 * Permission check special fields in the request
1266 * - android.led.transmit = android.permission.CAMERA_DISABLE_TRANSMIT
1267 */
1268 entry = metadata.find(ANDROID_LED_TRANSMIT);
1269 if (entry.count > 0 && entry.data.u8[0] != ANDROID_LED_TRANSMIT_ON) {
1270 String16 permissionString =
1271 String16("android.permission.CAMERA_DISABLE_TRANSMIT_LED");
1272 if (!checkCallingPermission(permissionString)) {
1273 const int uid = IPCThreadState::self()->getCallingUid();
1274 ALOGE("Permission Denial: "
1275 "can't disable transmit LED pid=%d, uid=%d", pid, uid);
1276 return false;
1277 }
1278 }
1279
1280 return true;
1281 }
1282
getRotationTransformLocked(int32_t * transform)1283 status_t CameraDeviceClient::getRotationTransformLocked(int32_t* transform) {
1284 ALOGV("%s: begin", __FUNCTION__);
1285
1286 const CameraMetadata& staticInfo = mDevice->info();
1287 return CameraUtils::getRotationTransform(staticInfo, transform);
1288 }
1289
1290 } // namespace android
1291