1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "Camera3-DepthCompositeStream"
18 #define ATRACE_TAG ATRACE_TAG_CAMERA
19 //#define LOG_NDEBUG 0
20
21 #include "api1/client2/JpegProcessor.h"
22 #include "common/CameraProviderManager.h"
23 #include "dlfcn.h"
24 #include <gui/Surface.h>
25 #include <utils/Log.h>
26 #include <utils/Trace.h>
27
28 #include "DepthCompositeStream.h"
29
30 namespace android {
31 namespace camera3 {
32
DepthCompositeStream(wp<CameraDeviceBase> device,wp<hardware::camera2::ICameraDeviceCallbacks> cb)33 DepthCompositeStream::DepthCompositeStream(wp<CameraDeviceBase> device,
34 wp<hardware::camera2::ICameraDeviceCallbacks> cb) :
35 CompositeStream(device, cb),
36 mBlobStreamId(-1),
37 mBlobSurfaceId(-1),
38 mDepthStreamId(-1),
39 mDepthSurfaceId(-1),
40 mBlobWidth(0),
41 mBlobHeight(0),
42 mDepthBufferAcquired(false),
43 mBlobBufferAcquired(false),
44 mProducerListener(new ProducerListener()),
45 mMaxJpegSize(-1),
46 mIsLogicalCamera(false),
47 mDepthPhotoLibHandle(nullptr),
48 mDepthPhotoProcess(nullptr) {
49 sp<CameraDeviceBase> cameraDevice = device.promote();
50 if (cameraDevice.get() != nullptr) {
51 CameraMetadata staticInfo = cameraDevice->info();
52 auto entry = staticInfo.find(ANDROID_JPEG_MAX_SIZE);
53 if (entry.count > 0) {
54 mMaxJpegSize = entry.data.i32[0];
55 } else {
56 ALOGW("%s: Maximum jpeg size absent from camera characteristics", __FUNCTION__);
57 }
58
59 entry = staticInfo.find(ANDROID_LENS_INTRINSIC_CALIBRATION);
60 if (entry.count == 5) {
61 mIntrinsicCalibration.reserve(5);
62 mIntrinsicCalibration.insert(mIntrinsicCalibration.end(), entry.data.f,
63 entry.data.f + 5);
64 } else {
65 ALOGW("%s: Intrinsic calibration absent from camera characteristics!", __FUNCTION__);
66 }
67
68 entry = staticInfo.find(ANDROID_LENS_DISTORTION);
69 if (entry.count == 5) {
70 mLensDistortion.reserve(5);
71 mLensDistortion.insert(mLensDistortion.end(), entry.data.f, entry.data.f + 5);
72 } else {
73 ALOGW("%s: Lens distortion absent from camera characteristics!", __FUNCTION__);
74 }
75
76 entry = staticInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
77 for (size_t i = 0; i < entry.count; ++i) {
78 uint8_t capability = entry.data.u8[i];
79 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_LOGICAL_MULTI_CAMERA) {
80 mIsLogicalCamera = true;
81 break;
82 }
83 }
84
85 getSupportedDepthSizes(staticInfo, &mSupportedDepthSizes);
86
87 mDepthPhotoLibHandle = dlopen(camera3::kDepthPhotoLibrary, RTLD_NOW | RTLD_LOCAL);
88 if (mDepthPhotoLibHandle != nullptr) {
89 mDepthPhotoProcess = reinterpret_cast<camera3::process_depth_photo_frame> (
90 dlsym(mDepthPhotoLibHandle, camera3::kDepthPhotoProcessFunction));
91 if (mDepthPhotoProcess == nullptr) {
92 ALOGE("%s: Failed to link to depth photo process function: %s", __FUNCTION__,
93 dlerror());
94 }
95 } else {
96 ALOGE("%s: Failed to link to depth photo library: %s", __FUNCTION__, dlerror());
97 }
98
99 }
100 }
101
~DepthCompositeStream()102 DepthCompositeStream::~DepthCompositeStream() {
103 mBlobConsumer.clear(),
104 mBlobSurface.clear(),
105 mBlobStreamId = -1;
106 mBlobSurfaceId = -1;
107 mDepthConsumer.clear();
108 mDepthSurface.clear();
109 mDepthConsumer = nullptr;
110 mDepthSurface = nullptr;
111 if (mDepthPhotoLibHandle != nullptr) {
112 dlclose(mDepthPhotoLibHandle);
113 mDepthPhotoLibHandle = nullptr;
114 }
115 mDepthPhotoProcess = nullptr;
116 }
117
compilePendingInputLocked()118 void DepthCompositeStream::compilePendingInputLocked() {
119 CpuConsumer::LockedBuffer imgBuffer;
120
121 while (!mInputJpegBuffers.empty() && !mBlobBufferAcquired) {
122 auto it = mInputJpegBuffers.begin();
123 auto res = mBlobConsumer->lockNextBuffer(&imgBuffer);
124 if (res == NOT_ENOUGH_DATA) {
125 // Can not lock any more buffers.
126 break;
127 } else if (res != OK) {
128 ALOGE("%s: Error locking blob image buffer: %s (%d)", __FUNCTION__,
129 strerror(-res), res);
130 mPendingInputFrames[*it].error = true;
131 mInputJpegBuffers.erase(it);
132 continue;
133 }
134
135 if (*it != imgBuffer.timestamp) {
136 ALOGW("%s: Expecting jpeg buffer with time stamp: %" PRId64 " received buffer with "
137 "time stamp: %" PRId64, __FUNCTION__, *it, imgBuffer.timestamp);
138 }
139
140 if ((mPendingInputFrames.find(imgBuffer.timestamp) != mPendingInputFrames.end()) &&
141 (mPendingInputFrames[imgBuffer.timestamp].error)) {
142 mBlobConsumer->unlockBuffer(imgBuffer);
143 } else {
144 mPendingInputFrames[imgBuffer.timestamp].jpegBuffer = imgBuffer;
145 mBlobBufferAcquired = true;
146 }
147 mInputJpegBuffers.erase(it);
148 }
149
150 while (!mInputDepthBuffers.empty() && !mDepthBufferAcquired) {
151 auto it = mInputDepthBuffers.begin();
152 auto res = mDepthConsumer->lockNextBuffer(&imgBuffer);
153 if (res == NOT_ENOUGH_DATA) {
154 // Can not lock any more buffers.
155 break;
156 } else if (res != OK) {
157 ALOGE("%s: Error receiving depth image buffer: %s (%d)", __FUNCTION__,
158 strerror(-res), res);
159 mPendingInputFrames[*it].error = true;
160 mInputDepthBuffers.erase(it);
161 continue;
162 }
163
164 if (*it != imgBuffer.timestamp) {
165 ALOGW("%s: Expecting depth buffer with time stamp: %" PRId64 " received buffer with "
166 "time stamp: %" PRId64, __FUNCTION__, *it, imgBuffer.timestamp);
167 }
168
169 if ((mPendingInputFrames.find(imgBuffer.timestamp) != mPendingInputFrames.end()) &&
170 (mPendingInputFrames[imgBuffer.timestamp].error)) {
171 mDepthConsumer->unlockBuffer(imgBuffer);
172 } else {
173 mPendingInputFrames[imgBuffer.timestamp].depthBuffer = imgBuffer;
174 mDepthBufferAcquired = true;
175 }
176 mInputDepthBuffers.erase(it);
177 }
178
179 while (!mCaptureResults.empty()) {
180 auto it = mCaptureResults.begin();
181 // Negative timestamp indicates that something went wrong during the capture result
182 // collection process.
183 if (it->first >= 0) {
184 mPendingInputFrames[it->first].frameNumber = std::get<0>(it->second);
185 mPendingInputFrames[it->first].result = std::get<1>(it->second);
186 }
187 mCaptureResults.erase(it);
188 }
189
190 while (!mFrameNumberMap.empty()) {
191 auto it = mFrameNumberMap.begin();
192 mPendingInputFrames[it->second].frameNumber = it->first;
193 mFrameNumberMap.erase(it);
194 }
195
196 auto it = mErrorFrameNumbers.begin();
197 while (it != mErrorFrameNumbers.end()) {
198 bool frameFound = false;
199 for (auto &inputFrame : mPendingInputFrames) {
200 if (inputFrame.second.frameNumber == *it) {
201 inputFrame.second.error = true;
202 frameFound = true;
203 break;
204 }
205 }
206
207 if (frameFound) {
208 it = mErrorFrameNumbers.erase(it);
209 } else {
210 ALOGW("%s: Not able to find failing input with frame number: %" PRId64, __FUNCTION__,
211 *it);
212 it++;
213 }
214 }
215 }
216
getNextReadyInputLocked(int64_t * currentTs)217 bool DepthCompositeStream::getNextReadyInputLocked(int64_t *currentTs /*inout*/) {
218 if (currentTs == nullptr) {
219 return false;
220 }
221
222 bool newInputAvailable = false;
223 for (const auto& it : mPendingInputFrames) {
224 if ((!it.second.error) && (it.second.depthBuffer.data != nullptr) &&
225 (it.second.jpegBuffer.data != nullptr) && (it.first < *currentTs)) {
226 *currentTs = it.first;
227 newInputAvailable = true;
228 }
229 }
230
231 return newInputAvailable;
232 }
233
getNextFailingInputLocked(int64_t * currentTs)234 int64_t DepthCompositeStream::getNextFailingInputLocked(int64_t *currentTs /*inout*/) {
235 int64_t ret = -1;
236 if (currentTs == nullptr) {
237 return ret;
238 }
239
240 for (const auto& it : mPendingInputFrames) {
241 if (it.second.error && !it.second.errorNotified && (it.first < *currentTs)) {
242 *currentTs = it.first;
243 ret = it.second.frameNumber;
244 }
245 }
246
247 return ret;
248 }
249
processInputFrame(const InputFrame & inputFrame)250 status_t DepthCompositeStream::processInputFrame(const InputFrame &inputFrame) {
251 status_t res;
252 sp<ANativeWindow> outputANW = mOutputSurface;
253 ANativeWindowBuffer *anb;
254 int fenceFd;
255 void *dstBuffer;
256
257 auto jpegSize = android::camera2::JpegProcessor::findJpegSize(inputFrame.jpegBuffer.data,
258 inputFrame.jpegBuffer.width);
259 if (jpegSize == 0) {
260 ALOGW("%s: Failed to find input jpeg size, default to using entire buffer!", __FUNCTION__);
261 jpegSize = inputFrame.jpegBuffer.width;
262 }
263
264 size_t maxDepthJpegSize;
265 if (mMaxJpegSize > 0) {
266 maxDepthJpegSize = mMaxJpegSize;
267 } else {
268 maxDepthJpegSize = std::max<size_t> (jpegSize,
269 inputFrame.depthBuffer.width * inputFrame.depthBuffer.height * 3 / 2);
270 }
271 uint8_t jpegQuality = 100;
272 auto entry = inputFrame.result.find(ANDROID_JPEG_QUALITY);
273 if (entry.count > 0) {
274 jpegQuality = entry.data.u8[0];
275 }
276
277 // The final depth photo will consist of the main jpeg buffer, the depth map buffer (also in
278 // jpeg format) and confidence map (jpeg as well). Assume worst case that all 3 jpeg need
279 // max jpeg size.
280 size_t finalJpegBufferSize = maxDepthJpegSize * 3;
281
282 if ((res = native_window_set_buffers_dimensions(mOutputSurface.get(), finalJpegBufferSize, 1))
283 != OK) {
284 ALOGE("%s: Unable to configure stream buffer dimensions"
285 " %zux%u for stream %d", __FUNCTION__, finalJpegBufferSize, 1U, mBlobStreamId);
286 return res;
287 }
288
289 res = outputANW->dequeueBuffer(mOutputSurface.get(), &anb, &fenceFd);
290 if (res != OK) {
291 ALOGE("%s: Error retrieving output buffer: %s (%d)", __FUNCTION__, strerror(-res),
292 res);
293 return res;
294 }
295
296 sp<GraphicBuffer> gb = GraphicBuffer::from(anb);
297 res = gb->lockAsync(GRALLOC_USAGE_SW_WRITE_OFTEN, &dstBuffer, fenceFd);
298 if (res != OK) {
299 ALOGE("%s: Error trying to lock output buffer fence: %s (%d)", __FUNCTION__,
300 strerror(-res), res);
301 outputANW->cancelBuffer(mOutputSurface.get(), anb, /*fence*/ -1);
302 return res;
303 }
304
305 if ((gb->getWidth() < finalJpegBufferSize) || (gb->getHeight() != 1)) {
306 ALOGE("%s: Blob buffer size mismatch, expected %dx%d received %zux%u", __FUNCTION__,
307 gb->getWidth(), gb->getHeight(), finalJpegBufferSize, 1U);
308 outputANW->cancelBuffer(mOutputSurface.get(), anb, /*fence*/ -1);
309 return BAD_VALUE;
310 }
311
312 DepthPhotoInputFrame depthPhoto;
313 depthPhoto.mMainJpegBuffer = reinterpret_cast<const char*> (inputFrame.jpegBuffer.data);
314 depthPhoto.mMainJpegWidth = mBlobWidth;
315 depthPhoto.mMainJpegHeight = mBlobHeight;
316 depthPhoto.mMainJpegSize = jpegSize;
317 depthPhoto.mDepthMapBuffer = reinterpret_cast<uint16_t*> (inputFrame.depthBuffer.data);
318 depthPhoto.mDepthMapWidth = inputFrame.depthBuffer.width;
319 depthPhoto.mDepthMapHeight = inputFrame.depthBuffer.height;
320 depthPhoto.mDepthMapStride = inputFrame.depthBuffer.stride;
321 depthPhoto.mJpegQuality = jpegQuality;
322 depthPhoto.mIsLogical = mIsLogicalCamera;
323 depthPhoto.mMaxJpegSize = maxDepthJpegSize;
324 // The camera intrinsic calibration layout is as follows:
325 // [focalLengthX, focalLengthY, opticalCenterX, opticalCenterY, skew]
326 if (mIntrinsicCalibration.size() == 5) {
327 memcpy(depthPhoto.mIntrinsicCalibration, mIntrinsicCalibration.data(),
328 sizeof(depthPhoto.mIntrinsicCalibration));
329 depthPhoto.mIsIntrinsicCalibrationValid = 1;
330 } else {
331 depthPhoto.mIsIntrinsicCalibrationValid = 0;
332 }
333 // The camera lens distortion contains the following lens correction coefficients.
334 // [kappa_1, kappa_2, kappa_3 kappa_4, kappa_5]
335 if (mLensDistortion.size() == 5) {
336 memcpy(depthPhoto.mLensDistortion, mLensDistortion.data(),
337 sizeof(depthPhoto.mLensDistortion));
338 depthPhoto.mIsLensDistortionValid = 1;
339 } else {
340 depthPhoto.mIsLensDistortionValid = 0;
341 }
342 entry = inputFrame.result.find(ANDROID_JPEG_ORIENTATION);
343 if (entry.count > 0) {
344 // The camera jpeg orientation values must be within [0, 90, 180, 270].
345 switch (entry.data.i32[0]) {
346 case 0:
347 case 90:
348 case 180:
349 case 270:
350 depthPhoto.mOrientation = static_cast<DepthPhotoOrientation> (entry.data.i32[0]);
351 break;
352 default:
353 ALOGE("%s: Unexpected jpeg orientation value: %d, default to 0 degrees",
354 __FUNCTION__, entry.data.i32[0]);
355 }
356 }
357
358 size_t actualJpegSize = 0;
359 res = mDepthPhotoProcess(depthPhoto, finalJpegBufferSize, dstBuffer, &actualJpegSize);
360 if (res != 0) {
361 ALOGE("%s: Depth photo processing failed: %s (%d)", __FUNCTION__, strerror(-res), res);
362 outputANW->cancelBuffer(mOutputSurface.get(), anb, /*fence*/ -1);
363 return res;
364 }
365
366 size_t finalJpegSize = actualJpegSize + sizeof(struct camera3_jpeg_blob);
367 if (finalJpegSize > finalJpegBufferSize) {
368 ALOGE("%s: Final jpeg buffer not large enough for the jpeg blob header", __FUNCTION__);
369 outputANW->cancelBuffer(mOutputSurface.get(), anb, /*fence*/ -1);
370 return NO_MEMORY;
371 }
372
373 ALOGV("%s: Final jpeg size: %zu", __func__, finalJpegSize);
374 uint8_t* header = static_cast<uint8_t *> (dstBuffer) +
375 (gb->getWidth() - sizeof(struct camera3_jpeg_blob));
376 struct camera3_jpeg_blob *blob = reinterpret_cast<struct camera3_jpeg_blob*> (header);
377 blob->jpeg_blob_id = CAMERA3_JPEG_BLOB_ID;
378 blob->jpeg_size = actualJpegSize;
379 outputANW->queueBuffer(mOutputSurface.get(), anb, /*fence*/ -1);
380
381 return res;
382 }
383
releaseInputFrameLocked(InputFrame * inputFrame)384 void DepthCompositeStream::releaseInputFrameLocked(InputFrame *inputFrame /*out*/) {
385 if (inputFrame == nullptr) {
386 return;
387 }
388
389 if (inputFrame->depthBuffer.data != nullptr) {
390 mDepthConsumer->unlockBuffer(inputFrame->depthBuffer);
391 inputFrame->depthBuffer.data = nullptr;
392 mDepthBufferAcquired = false;
393 }
394
395 if (inputFrame->jpegBuffer.data != nullptr) {
396 mBlobConsumer->unlockBuffer(inputFrame->jpegBuffer);
397 inputFrame->jpegBuffer.data = nullptr;
398 mBlobBufferAcquired = false;
399 }
400
401 if ((inputFrame->error || mErrorState) && !inputFrame->errorNotified) {
402 notifyError(inputFrame->frameNumber);
403 inputFrame->errorNotified = true;
404 }
405 }
406
releaseInputFramesLocked(int64_t currentTs)407 void DepthCompositeStream::releaseInputFramesLocked(int64_t currentTs) {
408 auto it = mPendingInputFrames.begin();
409 while (it != mPendingInputFrames.end()) {
410 if (it->first <= currentTs) {
411 releaseInputFrameLocked(&it->second);
412 it = mPendingInputFrames.erase(it);
413 } else {
414 it++;
415 }
416 }
417 }
418
threadLoop()419 bool DepthCompositeStream::threadLoop() {
420 int64_t currentTs = INT64_MAX;
421 bool newInputAvailable = false;
422
423 {
424 Mutex::Autolock l(mMutex);
425
426 if (mErrorState) {
427 // In case we landed in error state, return any pending buffers and
428 // halt all further processing.
429 compilePendingInputLocked();
430 releaseInputFramesLocked(currentTs);
431 return false;
432 }
433
434 while (!newInputAvailable) {
435 compilePendingInputLocked();
436 newInputAvailable = getNextReadyInputLocked(¤tTs);
437 if (!newInputAvailable) {
438 auto failingFrameNumber = getNextFailingInputLocked(¤tTs);
439 if (failingFrameNumber >= 0) {
440 // We cannot erase 'mPendingInputFrames[currentTs]' at this point because it is
441 // possible for two internal stream buffers to fail. In such scenario the
442 // composite stream should notify the client about a stream buffer error only
443 // once and this information is kept within 'errorNotified'.
444 // Any present failed input frames will be removed on a subsequent call to
445 // 'releaseInputFramesLocked()'.
446 releaseInputFrameLocked(&mPendingInputFrames[currentTs]);
447 currentTs = INT64_MAX;
448 }
449
450 auto ret = mInputReadyCondition.waitRelative(mMutex, kWaitDuration);
451 if (ret == TIMED_OUT) {
452 return true;
453 } else if (ret != OK) {
454 ALOGE("%s: Timed wait on condition failed: %s (%d)", __FUNCTION__,
455 strerror(-ret), ret);
456 return false;
457 }
458 }
459 }
460 }
461
462 auto res = processInputFrame(mPendingInputFrames[currentTs]);
463 Mutex::Autolock l(mMutex);
464 if (res != OK) {
465 ALOGE("%s: Failed processing frame with timestamp: %" PRIu64 ": %s (%d)", __FUNCTION__,
466 currentTs, strerror(-res), res);
467 mPendingInputFrames[currentTs].error = true;
468 }
469
470 releaseInputFramesLocked(currentTs);
471
472 return true;
473 }
474
isDepthCompositeStream(const sp<Surface> & surface)475 bool DepthCompositeStream::isDepthCompositeStream(const sp<Surface> &surface) {
476 ANativeWindow *anw = surface.get();
477 status_t err;
478 int format;
479 if ((err = anw->query(anw, NATIVE_WINDOW_FORMAT, &format)) != OK) {
480 String8 msg = String8::format("Failed to query Surface format: %s (%d)", strerror(-err),
481 err);
482 ALOGE("%s: %s", __FUNCTION__, msg.string());
483 return false;
484 }
485
486 int dataspace;
487 if ((err = anw->query(anw, NATIVE_WINDOW_DEFAULT_DATASPACE, &dataspace)) != OK) {
488 String8 msg = String8::format("Failed to query Surface dataspace: %s (%d)", strerror(-err),
489 err);
490 ALOGE("%s: %s", __FUNCTION__, msg.string());
491 return false;
492 }
493
494 if ((format == HAL_PIXEL_FORMAT_BLOB) && (dataspace == HAL_DATASPACE_DYNAMIC_DEPTH)) {
495 return true;
496 }
497
498 return false;
499 }
500
createInternalStreams(const std::vector<sp<Surface>> & consumers,bool,uint32_t width,uint32_t height,int format,camera3_stream_rotation_t rotation,int * id,const String8 & physicalCameraId,std::vector<int> * surfaceIds,int,bool)501 status_t DepthCompositeStream::createInternalStreams(const std::vector<sp<Surface>>& consumers,
502 bool /*hasDeferredConsumer*/, uint32_t width, uint32_t height, int format,
503 camera3_stream_rotation_t rotation, int *id, const String8& physicalCameraId,
504 std::vector<int> *surfaceIds, int /*streamSetId*/, bool /*isShared*/) {
505 if (mSupportedDepthSizes.empty()) {
506 ALOGE("%s: This camera device doesn't support any depth map streams!", __FUNCTION__);
507 return INVALID_OPERATION;
508 }
509
510 size_t depthWidth, depthHeight;
511 auto ret = getMatchingDepthSize(width, height, mSupportedDepthSizes, &depthWidth, &depthHeight);
512 if (ret != OK) {
513 ALOGE("%s: Failed to find an appropriate depth stream size!", __FUNCTION__);
514 return ret;
515 }
516
517 sp<CameraDeviceBase> device = mDevice.promote();
518 if (!device.get()) {
519 ALOGE("%s: Invalid camera device!", __FUNCTION__);
520 return NO_INIT;
521 }
522
523 sp<IGraphicBufferProducer> producer;
524 sp<IGraphicBufferConsumer> consumer;
525 BufferQueue::createBufferQueue(&producer, &consumer);
526 mBlobConsumer = new CpuConsumer(consumer, /*maxLockedBuffers*/1, /*controlledByApp*/ true);
527 mBlobConsumer->setFrameAvailableListener(this);
528 mBlobConsumer->setName(String8("Camera3-JpegCompositeStream"));
529 mBlobSurface = new Surface(producer);
530
531 ret = device->createStream(mBlobSurface, width, height, format, kJpegDataSpace, rotation,
532 id, physicalCameraId, surfaceIds);
533 if (ret == OK) {
534 mBlobStreamId = *id;
535 mBlobSurfaceId = (*surfaceIds)[0];
536 mOutputSurface = consumers[0];
537 } else {
538 return ret;
539 }
540
541 BufferQueue::createBufferQueue(&producer, &consumer);
542 mDepthConsumer = new CpuConsumer(consumer, /*maxLockedBuffers*/ 1, /*controlledByApp*/ true);
543 mDepthConsumer->setFrameAvailableListener(this);
544 mDepthConsumer->setName(String8("Camera3-DepthCompositeStream"));
545 mDepthSurface = new Surface(producer);
546 std::vector<int> depthSurfaceId;
547 ret = device->createStream(mDepthSurface, depthWidth, depthHeight, kDepthMapPixelFormat,
548 kDepthMapDataSpace, rotation, &mDepthStreamId, physicalCameraId, &depthSurfaceId);
549 if (ret == OK) {
550 mDepthSurfaceId = depthSurfaceId[0];
551 } else {
552 return ret;
553 }
554
555 ret = registerCompositeStreamListener(getStreamId());
556 if (ret != OK) {
557 ALOGE("%s: Failed to register blob stream listener!", __FUNCTION__);
558 return ret;
559 }
560
561 ret = registerCompositeStreamListener(mDepthStreamId);
562 if (ret != OK) {
563 ALOGE("%s: Failed to register depth stream listener!", __FUNCTION__);
564 return ret;
565 }
566
567 mBlobWidth = width;
568 mBlobHeight = height;
569
570 return ret;
571 }
572
configureStream()573 status_t DepthCompositeStream::configureStream() {
574 if (isRunning()) {
575 // Processing thread is already running, nothing more to do.
576 return NO_ERROR;
577 }
578
579 if ((mDepthPhotoLibHandle == nullptr) || (mDepthPhotoProcess == nullptr)) {
580 ALOGE("%s: Depth photo library is not present!", __FUNCTION__);
581 return NO_INIT;
582 }
583
584 if (mOutputSurface.get() == nullptr) {
585 ALOGE("%s: No valid output surface set!", __FUNCTION__);
586 return NO_INIT;
587 }
588
589 auto res = mOutputSurface->connect(NATIVE_WINDOW_API_CAMERA, mProducerListener);
590 if (res != OK) {
591 ALOGE("%s: Unable to connect to native window for stream %d",
592 __FUNCTION__, mBlobStreamId);
593 return res;
594 }
595
596 if ((res = native_window_set_buffers_format(mOutputSurface.get(), HAL_PIXEL_FORMAT_BLOB))
597 != OK) {
598 ALOGE("%s: Unable to configure stream buffer format for stream %d", __FUNCTION__,
599 mBlobStreamId);
600 return res;
601 }
602
603 int maxProducerBuffers;
604 ANativeWindow *anw = mBlobSurface.get();
605 if ((res = anw->query(anw, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &maxProducerBuffers)) != OK) {
606 ALOGE("%s: Unable to query consumer undequeued"
607 " buffer count for stream %d", __FUNCTION__, mBlobStreamId);
608 return res;
609 }
610
611 ANativeWindow *anwConsumer = mOutputSurface.get();
612 int maxConsumerBuffers;
613 if ((res = anwConsumer->query(anwConsumer, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
614 &maxConsumerBuffers)) != OK) {
615 ALOGE("%s: Unable to query consumer undequeued"
616 " buffer count for stream %d", __FUNCTION__, mBlobStreamId);
617 return res;
618 }
619
620 if ((res = native_window_set_buffer_count(
621 anwConsumer, maxProducerBuffers + maxConsumerBuffers)) != OK) {
622 ALOGE("%s: Unable to set buffer count for stream %d", __FUNCTION__, mBlobStreamId);
623 return res;
624 }
625
626 run("DepthCompositeStreamProc");
627
628 return NO_ERROR;
629 }
630
deleteInternalStreams()631 status_t DepthCompositeStream::deleteInternalStreams() {
632 // The 'CameraDeviceClient' parent will delete the blob stream
633 requestExit();
634
635 auto ret = join();
636 if (ret != OK) {
637 ALOGE("%s: Failed to join with the main processing thread: %s (%d)", __FUNCTION__,
638 strerror(-ret), ret);
639 }
640
641 sp<CameraDeviceBase> device = mDevice.promote();
642 if (!device.get()) {
643 ALOGE("%s: Invalid camera device!", __FUNCTION__);
644 return NO_INIT;
645 }
646
647 if (mDepthStreamId >= 0) {
648 ret = device->deleteStream(mDepthStreamId);
649 mDepthStreamId = -1;
650 }
651
652 if (mOutputSurface != nullptr) {
653 mOutputSurface->disconnect(NATIVE_WINDOW_API_CAMERA);
654 mOutputSurface.clear();
655 }
656
657 return ret;
658 }
659
onFrameAvailable(const BufferItem & item)660 void DepthCompositeStream::onFrameAvailable(const BufferItem& item) {
661 if (item.mDataSpace == kJpegDataSpace) {
662 ALOGV("%s: Jpeg buffer with ts: %" PRIu64 " ms. arrived!",
663 __func__, ns2ms(item.mTimestamp));
664
665 Mutex::Autolock l(mMutex);
666 if (!mErrorState) {
667 mInputJpegBuffers.push_back(item.mTimestamp);
668 mInputReadyCondition.signal();
669 }
670 } else if (item.mDataSpace == kDepthMapDataSpace) {
671 ALOGV("%s: Depth buffer with ts: %" PRIu64 " ms. arrived!", __func__,
672 ns2ms(item.mTimestamp));
673
674 Mutex::Autolock l(mMutex);
675 if (!mErrorState) {
676 mInputDepthBuffers.push_back(item.mTimestamp);
677 mInputReadyCondition.signal();
678 }
679 } else {
680 ALOGE("%s: Unexpected data space: 0x%x", __FUNCTION__, item.mDataSpace);
681 }
682 }
683
insertGbp(SurfaceMap * outSurfaceMap,Vector<int32_t> * outputStreamIds,int32_t * currentStreamId)684 status_t DepthCompositeStream::insertGbp(SurfaceMap* /*out*/outSurfaceMap,
685 Vector<int32_t> * /*out*/outputStreamIds, int32_t* /*out*/currentStreamId) {
686 if (outSurfaceMap->find(mDepthStreamId) == outSurfaceMap->end()) {
687 (*outSurfaceMap)[mDepthStreamId] = std::vector<size_t>();
688 outputStreamIds->push_back(mDepthStreamId);
689 }
690 (*outSurfaceMap)[mDepthStreamId].push_back(mDepthSurfaceId);
691
692 if (outSurfaceMap->find(mBlobStreamId) == outSurfaceMap->end()) {
693 (*outSurfaceMap)[mBlobStreamId] = std::vector<size_t>();
694 outputStreamIds->push_back(mBlobStreamId);
695 }
696 (*outSurfaceMap)[mBlobStreamId].push_back(mBlobSurfaceId);
697
698 if (currentStreamId != nullptr) {
699 *currentStreamId = mBlobStreamId;
700 }
701
702 return NO_ERROR;
703 }
704
onResultError(const CaptureResultExtras & resultExtras)705 void DepthCompositeStream::onResultError(const CaptureResultExtras& resultExtras) {
706 // Processing can continue even in case of result errors.
707 // At the moment depth composite stream processing relies mainly on static camera
708 // characteristics data. The actual result data can be used for the jpeg quality but
709 // in case it is absent we can default to maximum.
710 eraseResult(resultExtras.frameNumber);
711 }
712
onStreamBufferError(const CaptureResultExtras & resultExtras)713 bool DepthCompositeStream::onStreamBufferError(const CaptureResultExtras& resultExtras) {
714 bool ret = false;
715 // Buffer errors concerning internal composite streams should not be directly visible to
716 // camera clients. They must only receive a single buffer error with the public composite
717 // stream id.
718 if ((resultExtras.errorStreamId == mDepthStreamId) ||
719 (resultExtras.errorStreamId == mBlobStreamId)) {
720 flagAnErrorFrameNumber(resultExtras.frameNumber);
721 ret = true;
722 }
723
724 return ret;
725 }
726
getMatchingDepthSize(size_t width,size_t height,const std::vector<std::tuple<size_t,size_t>> & supporedDepthSizes,size_t * depthWidth,size_t * depthHeight)727 status_t DepthCompositeStream::getMatchingDepthSize(size_t width, size_t height,
728 const std::vector<std::tuple<size_t, size_t>>& supporedDepthSizes,
729 size_t *depthWidth /*out*/, size_t *depthHeight /*out*/) {
730 if ((depthWidth == nullptr) || (depthHeight == nullptr)) {
731 return BAD_VALUE;
732 }
733
734 float arTol = CameraProviderManager::kDepthARTolerance;
735 *depthWidth = *depthHeight = 0;
736
737 float aspectRatio = static_cast<float> (width) / static_cast<float> (height);
738 for (const auto& it : supporedDepthSizes) {
739 auto currentWidth = std::get<0>(it);
740 auto currentHeight = std::get<1>(it);
741 if ((currentWidth == width) && (currentHeight == height)) {
742 *depthWidth = width;
743 *depthHeight = height;
744 break;
745 } else {
746 float currentRatio = static_cast<float> (currentWidth) /
747 static_cast<float> (currentHeight);
748 auto currentSize = currentWidth * currentHeight;
749 auto oldSize = (*depthWidth) * (*depthHeight);
750 if ((fabs(aspectRatio - currentRatio) <= arTol) && (currentSize > oldSize)) {
751 *depthWidth = currentWidth;
752 *depthHeight = currentHeight;
753 }
754 }
755 }
756
757 return ((*depthWidth > 0) && (*depthHeight > 0)) ? OK : BAD_VALUE;
758 }
759
getSupportedDepthSizes(const CameraMetadata & ch,std::vector<std::tuple<size_t,size_t>> * depthSizes)760 void DepthCompositeStream::getSupportedDepthSizes(const CameraMetadata& ch,
761 std::vector<std::tuple<size_t, size_t>>* depthSizes /*out*/) {
762 if (depthSizes == nullptr) {
763 return;
764 }
765
766 auto entry = ch.find(ANDROID_DEPTH_AVAILABLE_DEPTH_STREAM_CONFIGURATIONS);
767 if (entry.count > 0) {
768 // Depth stream dimensions have four int32_t components
769 // (pixelformat, width, height, type)
770 size_t entryCount = entry.count / 4;
771 depthSizes->reserve(entryCount);
772 for (size_t i = 0; i < entry.count; i += 4) {
773 if ((entry.data.i32[i] == kDepthMapPixelFormat) &&
774 (entry.data.i32[i+3] ==
775 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT)) {
776 depthSizes->push_back(std::make_tuple(entry.data.i32[i+1],
777 entry.data.i32[i+2]));
778 }
779 }
780 }
781 }
782
getCompositeStreamInfo(const OutputStreamInfo & streamInfo,const CameraMetadata & ch,std::vector<OutputStreamInfo> * compositeOutput)783 status_t DepthCompositeStream::getCompositeStreamInfo(const OutputStreamInfo &streamInfo,
784 const CameraMetadata& ch, std::vector<OutputStreamInfo>* compositeOutput /*out*/) {
785 if (compositeOutput == nullptr) {
786 return BAD_VALUE;
787 }
788
789 std::vector<std::tuple<size_t, size_t>> depthSizes;
790 getSupportedDepthSizes(ch, &depthSizes);
791 if (depthSizes.empty()) {
792 ALOGE("%s: No depth stream configurations present", __FUNCTION__);
793 return BAD_VALUE;
794 }
795
796 size_t depthWidth, depthHeight;
797 auto ret = getMatchingDepthSize(streamInfo.width, streamInfo.height, depthSizes, &depthWidth,
798 &depthHeight);
799 if (ret != OK) {
800 ALOGE("%s: No matching depth stream size found", __FUNCTION__);
801 return ret;
802 }
803
804 compositeOutput->clear();
805 compositeOutput->insert(compositeOutput->end(), 2, streamInfo);
806
807 // Jpeg/Blob stream info
808 (*compositeOutput)[0].dataSpace = kJpegDataSpace;
809 (*compositeOutput)[0].consumerUsage = GRALLOC_USAGE_SW_READ_OFTEN;
810
811 // Depth stream info
812 (*compositeOutput)[1].width = depthWidth;
813 (*compositeOutput)[1].height = depthHeight;
814 (*compositeOutput)[1].format = kDepthMapPixelFormat;
815 (*compositeOutput)[1].dataSpace = kDepthMapDataSpace;
816 (*compositeOutput)[1].consumerUsage = GRALLOC_USAGE_SW_READ_OFTEN;
817
818 return NO_ERROR;
819 }
820
821 }; // namespace camera3
822 }; // namespace android
823