blob: 896e0daa0bac62bc016dcc3e625c45d3fab056f4 [file] [log] [blame]
Avichal Rakeshe1857f82022-06-08 17:47:23 -07001/*
2 * Copyright (C) 2022 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 "ExtCamDevSsn"
18// #define LOG_NDEBUG 0
19#include <log/log.h>
20
21#include "ExternalCameraDeviceSession.h"
22
23#include <Exif.h>
24#include <ExternalCameraOfflineSession.h>
25#include <aidl/android/hardware/camera/device/CameraBlob.h>
26#include <aidl/android/hardware/camera/device/CameraBlobId.h>
27#include <aidl/android/hardware/camera/device/ErrorMsg.h>
28#include <aidl/android/hardware/camera/device/ShutterMsg.h>
29#include <aidl/android/hardware/camera/device/StreamBufferRet.h>
30#include <aidl/android/hardware/camera/device/StreamBuffersVal.h>
31#include <aidl/android/hardware/camera/device/StreamConfigurationMode.h>
32#include <aidl/android/hardware/camera/device/StreamRotation.h>
33#include <aidl/android/hardware/camera/device/StreamType.h>
34#include <aidl/android/hardware/graphics/common/Dataspace.h>
35#include <aidlcommonsupport/NativeHandle.h>
36#include <convert.h>
37#include <linux/videodev2.h>
38#include <sync/sync.h>
39#include <utils/Trace.h>
40#include <deque>
41
42#define HAVE_JPEG // required for libyuv.h to export MJPEG decode APIs
43#include <libyuv.h>
44#include <libyuv/convert.h>
45
46namespace android {
47namespace hardware {
48namespace camera {
49namespace device {
50namespace implementation {
51
52namespace {
53
54// Size of request/result metadata fast message queue. Change to 0 to always use hwbinder buffer.
55static constexpr size_t kMetadataMsgQueueSize = 1 << 18 /* 256kB */;
56
57const int kBadFramesAfterStreamOn = 1; // drop x frames after streamOn to get rid of some initial
58 // bad frames. TODO: develop a better bad frame detection
59 // method
60constexpr int MAX_RETRY = 15; // Allow retry some ioctl failures a few times to account for some
61 // webcam showing temporarily ioctl failures.
62constexpr int IOCTL_RETRY_SLEEP_US = 33000; // 33ms * MAX_RETRY = 0.5 seconds
63
64// Constants for tryLock during dumpstate
65static constexpr int kDumpLockRetries = 50;
66static constexpr int kDumpLockSleep = 60000;
67
68bool tryLock(Mutex& mutex) {
69 bool locked = false;
70 for (int i = 0; i < kDumpLockRetries; ++i) {
71 if (mutex.tryLock() == NO_ERROR) {
72 locked = true;
73 break;
74 }
75 usleep(kDumpLockSleep);
76 }
77 return locked;
78}
79
80bool tryLock(std::mutex& mutex) {
81 bool locked = false;
82 for (int i = 0; i < kDumpLockRetries; ++i) {
83 if (mutex.try_lock()) {
84 locked = true;
85 break;
86 }
87 usleep(kDumpLockSleep);
88 }
89 return locked;
90}
91
92} // anonymous namespace
93
94using ::aidl::android::hardware::camera::device::BufferRequestStatus;
95using ::aidl::android::hardware::camera::device::CameraBlob;
96using ::aidl::android::hardware::camera::device::CameraBlobId;
97using ::aidl::android::hardware::camera::device::ErrorMsg;
98using ::aidl::android::hardware::camera::device::ShutterMsg;
99using ::aidl::android::hardware::camera::device::StreamBuffer;
100using ::aidl::android::hardware::camera::device::StreamBufferRet;
101using ::aidl::android::hardware::camera::device::StreamBuffersVal;
102using ::aidl::android::hardware::camera::device::StreamConfigurationMode;
103using ::aidl::android::hardware::camera::device::StreamRotation;
104using ::aidl::android::hardware::camera::device::StreamType;
105using ::aidl::android::hardware::graphics::common::Dataspace;
106using ::android::hardware::camera::common::V1_0::helper::ExifUtils;
107
108// Static instances
109const int ExternalCameraDeviceSession::kMaxProcessedStream;
110const int ExternalCameraDeviceSession::kMaxStallStream;
111HandleImporter ExternalCameraDeviceSession::sHandleImporter;
112
113ExternalCameraDeviceSession::ExternalCameraDeviceSession(
114 const std::shared_ptr<ICameraDeviceCallback>& callback, const ExternalCameraConfig& cfg,
115 const std::vector<SupportedV4L2Format>& sortedFormats, const CroppingType& croppingType,
116 const common::V1_0::helper::CameraMetadata& chars, const std::string& cameraId,
117 unique_fd v4l2Fd)
118 : mCallback(callback),
119 mCfg(cfg),
120 mCameraCharacteristics(chars),
121 mSupportedFormats(sortedFormats),
122 mCroppingType(croppingType),
123 mCameraId(cameraId),
124 mV4l2Fd(std::move(v4l2Fd)),
125 mMaxThumbResolution(getMaxThumbResolution()),
126 mMaxJpegResolution(getMaxJpegResolution()) {}
127
128Size ExternalCameraDeviceSession::getMaxThumbResolution() const {
129 return getMaxThumbnailResolution(mCameraCharacteristics);
130}
131
132Size ExternalCameraDeviceSession::getMaxJpegResolution() const {
133 Size ret{0, 0};
134 for (auto& fmt : mSupportedFormats) {
135 if (fmt.width * fmt.height > ret.width * ret.height) {
136 ret = Size{fmt.width, fmt.height};
137 }
138 }
139 return ret;
140}
141
142bool ExternalCameraDeviceSession::initialize() {
143 if (mV4l2Fd.get() < 0) {
144 ALOGE("%s: invalid v4l2 device fd %d!", __FUNCTION__, mV4l2Fd.get());
145 return true;
146 }
147
148 struct v4l2_capability capability;
149 int ret = ioctl(mV4l2Fd.get(), VIDIOC_QUERYCAP, &capability);
150 std::string make, model;
151 if (ret < 0) {
152 ALOGW("%s v4l2 QUERYCAP failed", __FUNCTION__);
153 mExifMake = "Generic UVC webcam";
154 mExifModel = "Generic UVC webcam";
155 } else {
156 // capability.card is UTF-8 encoded
157 char card[32];
158 int j = 0;
159 for (int i = 0; i < 32; i++) {
160 if (capability.card[i] < 128) {
161 card[j++] = capability.card[i];
162 }
163 if (capability.card[i] == '\0') {
164 break;
165 }
166 }
167 if (j == 0 || card[j - 1] != '\0') {
168 mExifMake = "Generic UVC webcam";
169 mExifModel = "Generic UVC webcam";
170 } else {
171 mExifMake = card;
172 mExifModel = card;
173 }
174 }
175
176 initOutputThread();
177 if (mOutputThread == nullptr) {
178 ALOGE("%s: init OutputThread failed!", __FUNCTION__);
179 return true;
180 }
181 mOutputThread->setExifMakeModel(mExifMake, mExifModel);
182
183 status_t status = initDefaultRequests();
184 if (status != OK) {
185 ALOGE("%s: init default requests failed!", __FUNCTION__);
186 return true;
187 }
188
189 mRequestMetadataQueue =
190 std::make_unique<RequestMetadataQueue>(kMetadataMsgQueueSize, false /* non blocking */);
191 if (!mRequestMetadataQueue->isValid()) {
192 ALOGE("%s: invalid request fmq", __FUNCTION__);
193 return true;
194 }
195
196 mResultMetadataQueue =
197 std::make_shared<ResultMetadataQueue>(kMetadataMsgQueueSize, false /* non blocking */);
198 if (!mResultMetadataQueue->isValid()) {
199 ALOGE("%s: invalid result fmq", __FUNCTION__);
200 return true;
201 }
202
203 mOutputThread->run();
204 return false;
205}
206
207bool ExternalCameraDeviceSession::isInitFailed() {
208 Mutex::Autolock _l(mLock);
209 if (!mInitialized) {
210 mInitFail = initialize();
211 mInitialized = true;
212 }
213 return mInitFail;
214}
215
216void ExternalCameraDeviceSession::initOutputThread() {
217 // Grab a shared_ptr to 'this' from ndk::SharedRefBase::ref()
218 std::shared_ptr<ExternalCameraDeviceSession> thiz = ref<ExternalCameraDeviceSession>();
219
Avichal Rakesh740c2562022-12-13 13:25:24 -0800220 mBufferRequestThread = std::make_shared<BufferRequestThread>(/*parent=*/thiz, mCallback);
221 mBufferRequestThread->run();
Avichal Rakeshe1857f82022-06-08 17:47:23 -0700222 mOutputThread = std::make_shared<OutputThread>(/*parent=*/thiz, mCroppingType,
223 mCameraCharacteristics, mBufferRequestThread);
224}
225
226void ExternalCameraDeviceSession::closeOutputThread() {
Avichal Rakeshe1857f82022-06-08 17:47:23 -0700227 if (mOutputThread != nullptr) {
228 mOutputThread->flush();
229 mOutputThread->requestExitAndWait();
230 mOutputThread.reset();
231 }
232}
233
Tang Lee65382f62023-08-01 18:23:07 +0800234void ExternalCameraDeviceSession::closeBufferRequestThread() {
235 if (mBufferRequestThread != nullptr) {
236 mBufferRequestThread->requestExitAndWait();
237 mBufferRequestThread.reset();
238 }
239}
240
Avichal Rakeshe1857f82022-06-08 17:47:23 -0700241Status ExternalCameraDeviceSession::initStatus() const {
242 Mutex::Autolock _l(mLock);
243 Status status = Status::OK;
244 if (mInitFail || mClosed) {
245 ALOGI("%s: session initFailed %d closed %d", __FUNCTION__, mInitFail, mClosed);
246 status = Status::INTERNAL_ERROR;
247 }
248 return status;
249}
250
251ExternalCameraDeviceSession::~ExternalCameraDeviceSession() {
252 if (!isClosed()) {
253 ALOGE("ExternalCameraDeviceSession deleted before close!");
Tang Lee65382f62023-08-01 18:23:07 +0800254 closeImpl();
Avichal Rakeshe1857f82022-06-08 17:47:23 -0700255 }
256}
257
258ScopedAStatus ExternalCameraDeviceSession::constructDefaultRequestSettings(
259 RequestTemplate in_type, CameraMetadata* _aidl_return) {
260 CameraMetadata emptyMetadata;
261 Status status = initStatus();
262 if (status != Status::OK) {
263 return fromStatus(status);
264 }
265 switch (in_type) {
266 case RequestTemplate::PREVIEW:
267 case RequestTemplate::STILL_CAPTURE:
268 case RequestTemplate::VIDEO_RECORD:
269 case RequestTemplate::VIDEO_SNAPSHOT: {
270 *_aidl_return = mDefaultRequests[in_type];
271 break;
272 }
273 case RequestTemplate::MANUAL:
274 case RequestTemplate::ZERO_SHUTTER_LAG:
275 // Don't support MANUAL, ZSL templates
276 status = Status::ILLEGAL_ARGUMENT;
277 break;
278 default:
279 ALOGE("%s: unknown request template type %d", __FUNCTION__, static_cast<int>(in_type));
280 status = Status::ILLEGAL_ARGUMENT;
281 break;
282 }
283 return fromStatus(status);
284}
285
286ScopedAStatus ExternalCameraDeviceSession::configureStreams(
287 const StreamConfiguration& in_requestedConfiguration,
288 std::vector<HalStream>* _aidl_return) {
289 uint32_t blobBufferSize = 0;
290 _aidl_return->clear();
291 Mutex::Autolock _il(mInterfaceLock);
292
293 Status status =
294 isStreamCombinationSupported(in_requestedConfiguration, mSupportedFormats, mCfg);
295 if (status != Status::OK) {
296 return fromStatus(status);
297 }
298
299 status = initStatus();
300 if (status != Status::OK) {
301 return fromStatus(status);
302 }
303
304 {
305 std::lock_guard<std::mutex> lk(mInflightFramesLock);
306 if (!mInflightFrames.empty()) {
307 ALOGE("%s: trying to configureStreams while there are still %zu inflight frames!",
308 __FUNCTION__, mInflightFrames.size());
309 return fromStatus(Status::INTERNAL_ERROR);
310 }
311 }
312
313 Mutex::Autolock _l(mLock);
314 {
315 Mutex::Autolock _cl(mCbsLock);
316 // Add new streams
317 for (const auto& stream : in_requestedConfiguration.streams) {
318 if (mStreamMap.count(stream.id) == 0) {
319 mStreamMap[stream.id] = stream;
320 mCirculatingBuffers.emplace(stream.id, CirculatingBuffers{});
321 }
322 }
323
324 // Cleanup removed streams
325 for (auto it = mStreamMap.begin(); it != mStreamMap.end();) {
326 int id = it->first;
327 bool found = false;
328 for (const auto& stream : in_requestedConfiguration.streams) {
329 if (id == stream.id) {
330 found = true;
331 break;
332 }
333 }
334 if (!found) {
335 // Unmap all buffers of deleted stream
336 cleanupBuffersLocked(id);
337 it = mStreamMap.erase(it);
338 } else {
339 ++it;
340 }
341 }
342 }
343
344 // Now select a V4L2 format to produce all output streams
345 float desiredAr = (mCroppingType == VERTICAL) ? kMaxAspectRatio : kMinAspectRatio;
346 uint32_t maxDim = 0;
347 for (const auto& stream : in_requestedConfiguration.streams) {
348 float aspectRatio = ASPECT_RATIO(stream);
349 ALOGI("%s: request stream %dx%d", __FUNCTION__, stream.width, stream.height);
350 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
351 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
352 desiredAr = aspectRatio;
353 }
354
355 // The dimension that's not cropped
356 uint32_t dim = (mCroppingType == VERTICAL) ? stream.width : stream.height;
357 if (dim > maxDim) {
358 maxDim = dim;
359 }
360 }
361
362 // Find the smallest format that matches the desired aspect ratio and is wide/high enough
363 SupportedV4L2Format v4l2Fmt{.width = 0, .height = 0};
364 for (const auto& fmt : mSupportedFormats) {
365 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
366 if (dim >= maxDim) {
367 float aspectRatio = ASPECT_RATIO(fmt);
368 if (isAspectRatioClose(aspectRatio, desiredAr)) {
369 v4l2Fmt = fmt;
370 // since mSupportedFormats is sorted by width then height, the first matching fmt
371 // will be the smallest one with matching aspect ratio
372 break;
373 }
374 }
375 }
376
377 if (v4l2Fmt.width == 0) {
378 // Cannot find exact good aspect ratio candidate, try to find a close one
379 for (const auto& fmt : mSupportedFormats) {
380 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
381 if (dim >= maxDim) {
382 float aspectRatio = ASPECT_RATIO(fmt);
383 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
384 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
385 v4l2Fmt = fmt;
386 break;
387 }
388 }
389 }
390 }
391
392 if (v4l2Fmt.width == 0) {
393 ALOGE("%s: unable to find a resolution matching (%s at least %d, aspect ratio %f)",
394 __FUNCTION__, (mCroppingType == VERTICAL) ? "width" : "height", maxDim, desiredAr);
395 return fromStatus(Status::ILLEGAL_ARGUMENT);
396 }
397
398 if (configureV4l2StreamLocked(v4l2Fmt) != 0) {
399 ALOGE("V4L configuration failed!, format:%c%c%c%c, w %d, h %d", v4l2Fmt.fourcc & 0xFF,
400 (v4l2Fmt.fourcc >> 8) & 0xFF, (v4l2Fmt.fourcc >> 16) & 0xFF,
401 (v4l2Fmt.fourcc >> 24) & 0xFF, v4l2Fmt.width, v4l2Fmt.height);
402 return fromStatus(Status::INTERNAL_ERROR);
403 }
404
405 Size v4lSize = {v4l2Fmt.width, v4l2Fmt.height};
406 Size thumbSize{0, 0};
407 camera_metadata_ro_entry entry =
408 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
409 for (uint32_t i = 0; i < entry.count; i += 2) {
410 Size sz{entry.data.i32[i], entry.data.i32[i + 1]};
411 if (sz.width * sz.height > thumbSize.width * thumbSize.height) {
412 thumbSize = sz;
413 }
414 }
415
416 if (thumbSize.width * thumbSize.height == 0) {
417 ALOGE("%s: non-zero thumbnail size not available", __FUNCTION__);
418 return fromStatus(Status::INTERNAL_ERROR);
419 }
420
421 mBlobBufferSize = blobBufferSize;
422 status = mOutputThread->allocateIntermediateBuffers(
423 v4lSize, mMaxThumbResolution, in_requestedConfiguration.streams, blobBufferSize);
424 if (status != Status::OK) {
425 ALOGE("%s: allocating intermediate buffers failed!", __FUNCTION__);
426 return fromStatus(status);
427 }
428
429 std::vector<HalStream>& out = *_aidl_return;
430 out.resize(in_requestedConfiguration.streams.size());
431 for (size_t i = 0; i < in_requestedConfiguration.streams.size(); i++) {
432 out[i].overrideDataSpace = in_requestedConfiguration.streams[i].dataSpace;
433 out[i].id = in_requestedConfiguration.streams[i].id;
434 // TODO: double check should we add those CAMERA flags
435 mStreamMap[in_requestedConfiguration.streams[i].id].usage = out[i].producerUsage =
436 static_cast<BufferUsage>(((int64_t)in_requestedConfiguration.streams[i].usage) |
437 ((int64_t)BufferUsage::CPU_WRITE_OFTEN) |
438 ((int64_t)BufferUsage::CAMERA_OUTPUT));
439 out[i].consumerUsage = static_cast<BufferUsage>(0);
440 out[i].maxBuffers = static_cast<int32_t>(mV4L2BufferCount);
441
442 switch (in_requestedConfiguration.streams[i].format) {
443 case PixelFormat::BLOB:
444 case PixelFormat::YCBCR_420_888:
445 case PixelFormat::YV12: // Used by SurfaceTexture
446 case PixelFormat::Y16:
447 // No override
448 out[i].overrideFormat = in_requestedConfiguration.streams[i].format;
449 break;
450 case PixelFormat::IMPLEMENTATION_DEFINED:
451 // Implementation Defined
452 // This should look at the Stream's dataspace flag to determine the format or leave
453 // it as is if the rest of the system knows how to handle a private format. To keep
454 // this HAL generic, this is being overridden to YUV420
455 out[i].overrideFormat = PixelFormat::YCBCR_420_888;
456 // Save overridden format in mStreamMap
457 mStreamMap[in_requestedConfiguration.streams[i].id].format = out[i].overrideFormat;
458 break;
459 default:
460 ALOGE("%s: unsupported format 0x%x", __FUNCTION__,
461 in_requestedConfiguration.streams[i].format);
462 return fromStatus(Status::ILLEGAL_ARGUMENT);
463 }
464 }
465
466 mFirstRequest = true;
467 mLastStreamConfigCounter = in_requestedConfiguration.streamConfigCounter;
468 return fromStatus(Status::OK);
469}
470
471ScopedAStatus ExternalCameraDeviceSession::flush() {
472 ATRACE_CALL();
473 Mutex::Autolock _il(mInterfaceLock);
474 Status status = initStatus();
475 if (status != Status::OK) {
476 return fromStatus(status);
477 }
478 mOutputThread->flush();
479 return fromStatus(Status::OK);
480}
481
482ScopedAStatus ExternalCameraDeviceSession::getCaptureRequestMetadataQueue(
483 MQDescriptor<int8_t, SynchronizedReadWrite>* _aidl_return) {
484 Mutex::Autolock _il(mInterfaceLock);
485 *_aidl_return = mRequestMetadataQueue->dupeDesc();
486 return fromStatus(Status::OK);
487}
488
489ScopedAStatus ExternalCameraDeviceSession::getCaptureResultMetadataQueue(
490 MQDescriptor<int8_t, SynchronizedReadWrite>* _aidl_return) {
491 Mutex::Autolock _il(mInterfaceLock);
492 *_aidl_return = mResultMetadataQueue->dupeDesc();
493 return fromStatus(Status::OK);
494}
495
496ScopedAStatus ExternalCameraDeviceSession::isReconfigurationRequired(
497 const CameraMetadata& in_oldSessionParams, const CameraMetadata& in_newSessionParams,
498 bool* _aidl_return) {
499 // reconfiguration required if there is any change in the session params
500 *_aidl_return = in_oldSessionParams != in_newSessionParams;
501 return fromStatus(Status::OK);
502}
503
504ScopedAStatus ExternalCameraDeviceSession::processCaptureRequest(
505 const std::vector<CaptureRequest>& in_requests,
506 const std::vector<BufferCache>& in_cachesToRemove, int32_t* _aidl_return) {
507 Mutex::Autolock _il(mInterfaceLock);
508 updateBufferCaches(in_cachesToRemove);
509
510 int32_t& numRequestProcessed = *_aidl_return;
511 numRequestProcessed = 0;
512 Status s = Status::OK;
513 for (size_t i = 0; i < in_requests.size(); i++, numRequestProcessed++) {
514 s = processOneCaptureRequest(in_requests[i]);
515 if (s != Status::OK) {
516 break;
517 }
518 }
519
520 return fromStatus(s);
521}
522
523Status ExternalCameraDeviceSession::processOneCaptureRequest(const CaptureRequest& request) {
524 ATRACE_CALL();
525 Status status = initStatus();
526 if (status != Status::OK) {
527 return status;
528 }
529
530 if (request.inputBuffer.streamId != -1) {
531 ALOGE("%s: external camera does not support reprocessing!", __FUNCTION__);
532 return Status::ILLEGAL_ARGUMENT;
533 }
534
535 Mutex::Autolock _l(mLock);
536 if (!mV4l2Streaming) {
537 ALOGE("%s: cannot process request in streamOff state!", __FUNCTION__);
538 return Status::INTERNAL_ERROR;
539 }
540
541 const camera_metadata_t* rawSettings = nullptr;
542 bool converted;
543 CameraMetadata settingsFmq; // settings from FMQ
544
545 if (request.fmqSettingsSize > 0) {
546 // non-blocking read; client must write metadata before calling
547 // processOneCaptureRequest
548 settingsFmq.metadata.resize(request.fmqSettingsSize);
549 bool read = mRequestMetadataQueue->read(
550 reinterpret_cast<int8_t*>(settingsFmq.metadata.data()), request.fmqSettingsSize);
551 if (read) {
552 converted = convertFromAidl(settingsFmq, &rawSettings);
553 } else {
554 ALOGE("%s: capture request settings metadata couldn't be read from fmq!", __FUNCTION__);
555 converted = false;
556 }
557 } else {
558 converted = convertFromAidl(request.settings, &rawSettings);
559 }
560
561 if (converted && rawSettings != nullptr) {
562 mLatestReqSetting = rawSettings;
563 }
564
565 if (!converted) {
566 ALOGE("%s: capture request settings metadata is corrupt!", __FUNCTION__);
567 return Status::ILLEGAL_ARGUMENT;
568 }
569
570 if (mFirstRequest && rawSettings == nullptr) {
571 ALOGE("%s: capture request settings must not be null for first request!", __FUNCTION__);
572 return Status::ILLEGAL_ARGUMENT;
573 }
574
575 std::vector<buffer_handle_t*> allBufPtrs;
576 std::vector<int> allFences;
577 size_t numOutputBufs = request.outputBuffers.size();
578
579 if (numOutputBufs == 0) {
580 ALOGE("%s: capture request must have at least one output buffer!", __FUNCTION__);
581 return Status::ILLEGAL_ARGUMENT;
582 }
583
584 camera_metadata_entry fpsRange = mLatestReqSetting.find(ANDROID_CONTROL_AE_TARGET_FPS_RANGE);
585 if (fpsRange.count == 2) {
586 double requestFpsMax = fpsRange.data.i32[1];
587 double closestFps = 0.0;
588 double fpsError = 1000.0;
589 bool fpsSupported = false;
590 for (const auto& fr : mV4l2StreamingFmt.frameRates) {
591 double f = fr.getFramesPerSecond();
592 if (std::fabs(requestFpsMax - f) < 1.0) {
593 fpsSupported = true;
594 break;
595 }
596 if (std::fabs(requestFpsMax - f) < fpsError) {
597 fpsError = std::fabs(requestFpsMax - f);
598 closestFps = f;
599 }
600 }
601 if (!fpsSupported) {
602 /* This can happen in a few scenarios:
603 * 1. The application is sending an FPS range not supported by the configured outputs.
604 * 2. The application is sending a valid FPS range for all configured outputs, but
605 * the selected V4L2 size can only run at slower speed. This should be very rare
606 * though: for this to happen a sensor needs to support at least 3 different aspect
607 * ratio outputs, and when (at least) two outputs are both not the main aspect ratio
608 * of the webcam, a third size that's larger might be picked and runs into this
609 * issue.
610 */
611 ALOGW("%s: cannot reach fps %d! Will do %f instead", __FUNCTION__, fpsRange.data.i32[1],
612 closestFps);
613 requestFpsMax = closestFps;
614 }
615
616 if (requestFpsMax != mV4l2StreamingFps) {
617 {
618 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
619 while (mNumDequeuedV4l2Buffers != 0) {
620 // Wait until pipeline is idle before reconfigure stream
621 int waitRet = waitForV4L2BufferReturnLocked(lk);
622 if (waitRet != 0) {
623 ALOGE("%s: wait for pipeline idle failed!", __FUNCTION__);
624 return Status::INTERNAL_ERROR;
625 }
626 }
627 }
628 configureV4l2StreamLocked(mV4l2StreamingFmt, requestFpsMax);
629 }
630 }
631
632 status = importRequestLocked(request, allBufPtrs, allFences);
633 if (status != Status::OK) {
634 return status;
635 }
636
637 nsecs_t shutterTs = 0;
638 std::unique_ptr<V4L2Frame> frameIn = dequeueV4l2FrameLocked(&shutterTs);
639 if (frameIn == nullptr) {
640 ALOGE("%s: V4L2 deque frame failed!", __FUNCTION__);
641 return Status::INTERNAL_ERROR;
642 }
643
644 std::shared_ptr<HalRequest> halReq = std::make_shared<HalRequest>();
645 halReq->frameNumber = request.frameNumber;
646 halReq->setting = mLatestReqSetting;
647 halReq->frameIn = std::move(frameIn);
648 halReq->shutterTs = shutterTs;
649 halReq->buffers.resize(numOutputBufs);
650 for (size_t i = 0; i < numOutputBufs; i++) {
651 HalStreamBuffer& halBuf = halReq->buffers[i];
652 int streamId = halBuf.streamId = request.outputBuffers[i].streamId;
653 halBuf.bufferId = request.outputBuffers[i].bufferId;
654 const Stream& stream = mStreamMap[streamId];
655 halBuf.width = stream.width;
656 halBuf.height = stream.height;
657 halBuf.format = stream.format;
658 halBuf.usage = stream.usage;
659 halBuf.bufPtr = allBufPtrs[i];
660 halBuf.acquireFence = allFences[i];
661 halBuf.fenceTimeout = false;
662 }
663 {
664 std::lock_guard<std::mutex> lk(mInflightFramesLock);
665 mInflightFrames.insert(halReq->frameNumber);
666 }
667 // Send request to OutputThread for the rest of processing
668 mOutputThread->submitRequest(halReq);
669 mFirstRequest = false;
670 return Status::OK;
671}
672
673ScopedAStatus ExternalCameraDeviceSession::signalStreamFlush(
674 const std::vector<int32_t>& /*in_streamIds*/, int32_t in_streamConfigCounter) {
675 {
676 Mutex::Autolock _l(mLock);
677 if (in_streamConfigCounter < mLastStreamConfigCounter) {
678 // stale call. new streams have been configured since this call was issued.
679 // Do nothing.
680 return fromStatus(Status::OK);
681 }
682 }
683
684 // TODO: implement if needed.
685 return fromStatus(Status::OK);
686}
687
688ScopedAStatus ExternalCameraDeviceSession::switchToOffline(
689 const std::vector<int32_t>& in_streamsToKeep,
690 CameraOfflineSessionInfo* out_offlineSessionInfo,
691 std::shared_ptr<ICameraOfflineSession>* _aidl_return) {
692 std::vector<NotifyMsg> msgs;
693 std::vector<CaptureResult> results;
694 CameraOfflineSessionInfo info;
695 std::shared_ptr<ICameraOfflineSession> session;
696 Status st = switchToOffline(in_streamsToKeep, &msgs, &results, &info, &session);
697
698 mCallback->notify(msgs);
699 invokeProcessCaptureResultCallback(results, /* tryWriteFmq= */ true);
700 freeReleaseFences(results);
701
702 // setup return values
703 *out_offlineSessionInfo = info;
704 *_aidl_return = session;
705 return fromStatus(st);
706}
707
708Status ExternalCameraDeviceSession::switchToOffline(
709 const std::vector<int32_t>& offlineStreams, std::vector<NotifyMsg>* msgs,
710 std::vector<CaptureResult>* results, CameraOfflineSessionInfo* info,
711 std::shared_ptr<ICameraOfflineSession>* session) {
712 ATRACE_CALL();
713 if (offlineStreams.size() > 1) {
714 ALOGE("%s: more than one offline stream is not supported", __FUNCTION__);
715 return Status::ILLEGAL_ARGUMENT;
716 }
717
Greg Kaiser9b77fd12022-12-05 17:06:02 -0800718 if (msgs == nullptr || results == nullptr || info == nullptr || session == nullptr) {
719 ALOGE("%s, output arguments (%p, %p, %p, %p) must not be null", __FUNCTION__, msgs, results,
Avichal Rakeshe1857f82022-06-08 17:47:23 -0700720 info, session);
721 }
722
723 Mutex::Autolock _il(mInterfaceLock);
724 Status status = initStatus();
725 if (status != Status::OK) {
726 return status;
727 }
728
729 Mutex::Autolock _l(mLock);
730 for (auto streamId : offlineStreams) {
731 if (!supportOfflineLocked(streamId)) {
732 return Status::ILLEGAL_ARGUMENT;
733 }
734 }
735
736 // pause output thread and get all remaining inflight requests
737 auto remainingReqs = mOutputThread->switchToOffline();
738 std::vector<std::shared_ptr<HalRequest>> halReqs;
739
740 // Send out buffer/request error for remaining requests and filter requests
741 // to be handled in offline mode
742 for (auto& halReq : remainingReqs) {
743 bool dropReq = canDropRequest(offlineStreams, halReq);
744 if (dropReq) {
745 // Request is dropped completely. Just send request error and
746 // there is no need to send the request to offline session
747 processCaptureRequestError(halReq, msgs, results);
748 continue;
749 }
750
751 // All requests reach here must have at least one offline stream output
752 NotifyMsg shutter;
753 aidl::android::hardware::camera::device::ShutterMsg shutterMsg = {
754 .frameNumber = static_cast<int32_t>(halReq->frameNumber),
755 .timestamp = halReq->shutterTs};
756 shutter.set<NotifyMsg::Tag::shutter>(shutterMsg);
757 msgs->push_back(shutter);
758
759 std::vector<HalStreamBuffer> offlineBuffers;
760 for (const auto& buffer : halReq->buffers) {
761 bool dropBuffer = true;
762 for (auto offlineStreamId : offlineStreams) {
763 if (buffer.streamId == offlineStreamId) {
764 dropBuffer = false;
765 break;
766 }
767 }
768 if (dropBuffer) {
769 aidl::android::hardware::camera::device::ErrorMsg errorMsg = {
770 .frameNumber = static_cast<int32_t>(halReq->frameNumber),
771 .errorStreamId = buffer.streamId,
772 .errorCode = ErrorCode::ERROR_BUFFER};
773
774 NotifyMsg error;
775 error.set<NotifyMsg::Tag::error>(errorMsg);
776 msgs->push_back(error);
777
778 results->push_back({
779 .frameNumber = static_cast<int32_t>(halReq->frameNumber),
780 .outputBuffers = {},
781 .inputBuffer = {.streamId = -1},
782 .partialResult = 0, // buffer only result
783 });
784
785 CaptureResult& result = results->back();
786 result.outputBuffers.resize(1);
787 StreamBuffer& outputBuffer = result.outputBuffers[0];
788 outputBuffer.streamId = buffer.streamId;
789 outputBuffer.bufferId = buffer.bufferId;
790 outputBuffer.status = BufferStatus::ERROR;
791 if (buffer.acquireFence >= 0) {
792 native_handle_t* handle = native_handle_create(/*numFds*/ 1, /*numInts*/ 0);
793 handle->data[0] = buffer.acquireFence;
794 outputBuffer.releaseFence = android::makeToAidl(handle);
795 }
796 } else {
797 offlineBuffers.push_back(buffer);
798 }
799 }
800 halReq->buffers = offlineBuffers;
801 halReqs.push_back(halReq);
802 }
803
804 // convert hal requests to offline request
805 std::deque<std::shared_ptr<HalRequest>> offlineReqs(halReqs.size());
806 size_t i = 0;
807 for (auto& v4lReq : halReqs) {
808 offlineReqs[i] = std::make_shared<HalRequest>();
809 offlineReqs[i]->frameNumber = v4lReq->frameNumber;
810 offlineReqs[i]->setting = v4lReq->setting;
811 offlineReqs[i]->shutterTs = v4lReq->shutterTs;
812 offlineReqs[i]->buffers = v4lReq->buffers;
813 std::shared_ptr<V4L2Frame> v4l2Frame(static_cast<V4L2Frame*>(v4lReq->frameIn.get()));
814 offlineReqs[i]->frameIn = std::make_shared<AllocatedV4L2Frame>(v4l2Frame);
815 i++;
816 // enqueue V4L2 frame
817 enqueueV4l2Frame(v4l2Frame);
818 }
819
820 // Collect buffer caches/streams
821 std::vector<Stream> streamInfos(offlineStreams.size());
822 std::map<int, CirculatingBuffers> circulatingBuffers;
823 {
824 Mutex::Autolock _cbsl(mCbsLock);
825 for (auto streamId : offlineStreams) {
826 circulatingBuffers[streamId] = mCirculatingBuffers.at(streamId);
827 mCirculatingBuffers.erase(streamId);
828 streamInfos.push_back(mStreamMap.at(streamId));
829 mStreamMap.erase(streamId);
830 }
831 }
832
833 fillOfflineSessionInfo(offlineStreams, offlineReqs, circulatingBuffers, info);
834 // create the offline session object
835 bool afTrigger;
836 {
837 std::lock_guard<std::mutex> _lk(mAfTriggerLock);
838 afTrigger = mAfTrigger;
839 }
840
841 std::shared_ptr<ExternalCameraOfflineSession> sessionImpl =
842 ndk::SharedRefBase::make<ExternalCameraOfflineSession>(
843 mCroppingType, mCameraCharacteristics, mCameraId, mExifMake, mExifModel,
844 mBlobBufferSize, afTrigger, streamInfos, offlineReqs, circulatingBuffers);
845
846 bool initFailed = sessionImpl->initialize();
847 if (initFailed) {
848 ALOGE("%s: offline session initialize failed!", __FUNCTION__);
849 return Status::INTERNAL_ERROR;
850 }
851
852 // cleanup stream and buffer caches
853 {
854 Mutex::Autolock _cbsl(mCbsLock);
855 for (auto pair : mStreamMap) {
856 cleanupBuffersLocked(/*Stream ID*/ pair.first);
857 }
858 mCirculatingBuffers.clear();
859 }
860 mStreamMap.clear();
861
862 // update inflight records
863 {
864 std::lock_guard<std::mutex> _lk(mInflightFramesLock);
865 mInflightFrames.clear();
866 }
867
868 // stop v4l2 streaming
869 if (v4l2StreamOffLocked() != 0) {
870 ALOGE("%s: stop V4L2 streaming failed!", __FUNCTION__);
871 return Status::INTERNAL_ERROR;
872 }
873
874 // No need to return session if there is no offline requests left
875 if (!offlineReqs.empty()) {
876 *session = sessionImpl;
877 } else {
878 *session = nullptr;
879 }
880
881 return Status::OK;
882}
883
884#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
885#define UPDATE(md, tag, data, size) \
886 do { \
887 if ((md).update((tag), (data), (size))) { \
888 ALOGE("Update " #tag " failed!"); \
889 return BAD_VALUE; \
890 } \
891 } while (0)
892
893status_t ExternalCameraDeviceSession::initDefaultRequests() {
894 common::V1_0::helper::CameraMetadata md;
895
896 const uint8_t aberrationMode = ANDROID_COLOR_CORRECTION_ABERRATION_MODE_OFF;
897 UPDATE(md, ANDROID_COLOR_CORRECTION_ABERRATION_MODE, &aberrationMode, 1);
898
899 const int32_t exposureCompensation = 0;
900 UPDATE(md, ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION, &exposureCompensation, 1);
901
902 const uint8_t videoStabilizationMode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
903 UPDATE(md, ANDROID_CONTROL_VIDEO_STABILIZATION_MODE, &videoStabilizationMode, 1);
904
905 const uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO;
906 UPDATE(md, ANDROID_CONTROL_AWB_MODE, &awbMode, 1);
907
908 const uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON;
909 UPDATE(md, ANDROID_CONTROL_AE_MODE, &aeMode, 1);
910
911 const uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
912 UPDATE(md, ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
913
914 const uint8_t afMode = ANDROID_CONTROL_AF_MODE_AUTO;
915 UPDATE(md, ANDROID_CONTROL_AF_MODE, &afMode, 1);
916
917 const uint8_t afTrigger = ANDROID_CONTROL_AF_TRIGGER_IDLE;
918 UPDATE(md, ANDROID_CONTROL_AF_TRIGGER, &afTrigger, 1);
919
920 const uint8_t sceneMode = ANDROID_CONTROL_SCENE_MODE_DISABLED;
921 UPDATE(md, ANDROID_CONTROL_SCENE_MODE, &sceneMode, 1);
922
923 const uint8_t effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF;
924 UPDATE(md, ANDROID_CONTROL_EFFECT_MODE, &effectMode, 1);
925
926 const uint8_t flashMode = ANDROID_FLASH_MODE_OFF;
927 UPDATE(md, ANDROID_FLASH_MODE, &flashMode, 1);
928
929 const int32_t thumbnailSize[] = {240, 180};
930 UPDATE(md, ANDROID_JPEG_THUMBNAIL_SIZE, thumbnailSize, 2);
931
932 const uint8_t jpegQuality = 90;
933 UPDATE(md, ANDROID_JPEG_QUALITY, &jpegQuality, 1);
934 UPDATE(md, ANDROID_JPEG_THUMBNAIL_QUALITY, &jpegQuality, 1);
935
936 const int32_t jpegOrientation = 0;
937 UPDATE(md, ANDROID_JPEG_ORIENTATION, &jpegOrientation, 1);
938
939 const uint8_t oisMode = ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF;
940 UPDATE(md, ANDROID_LENS_OPTICAL_STABILIZATION_MODE, &oisMode, 1);
941
942 const uint8_t nrMode = ANDROID_NOISE_REDUCTION_MODE_OFF;
943 UPDATE(md, ANDROID_NOISE_REDUCTION_MODE, &nrMode, 1);
944
945 const int32_t testPatternModes = ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
946 UPDATE(md, ANDROID_SENSOR_TEST_PATTERN_MODE, &testPatternModes, 1);
947
948 const uint8_t fdMode = ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
949 UPDATE(md, ANDROID_STATISTICS_FACE_DETECT_MODE, &fdMode, 1);
950
951 const uint8_t hotpixelMode = ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF;
952 UPDATE(md, ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE, &hotpixelMode, 1);
953
954 bool support30Fps = false;
955 int32_t maxFps = std::numeric_limits<int32_t>::min();
956 for (const auto& supportedFormat : mSupportedFormats) {
957 for (const auto& fr : supportedFormat.frameRates) {
958 int32_t framerateInt = static_cast<int32_t>(fr.getFramesPerSecond());
959 if (maxFps < framerateInt) {
960 maxFps = framerateInt;
961 }
962 if (framerateInt == 30) {
963 support30Fps = true;
964 break;
965 }
966 }
967 if (support30Fps) {
968 break;
969 }
970 }
971
972 int32_t defaultFramerate = support30Fps ? 30 : maxFps;
973 int32_t defaultFpsRange[] = {defaultFramerate / 2, defaultFramerate};
974 UPDATE(md, ANDROID_CONTROL_AE_TARGET_FPS_RANGE, defaultFpsRange, ARRAY_SIZE(defaultFpsRange));
975
976 uint8_t antibandingMode = ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO;
977 UPDATE(md, ANDROID_CONTROL_AE_ANTIBANDING_MODE, &antibandingMode, 1);
978
979 const uint8_t controlMode = ANDROID_CONTROL_MODE_AUTO;
980 UPDATE(md, ANDROID_CONTROL_MODE, &controlMode, 1);
981
982 for (const auto& type : ndk::enum_range<RequestTemplate>()) {
983 common::V1_0::helper::CameraMetadata mdCopy = md;
984 uint8_t intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
985 switch (type) {
986 case RequestTemplate::PREVIEW:
987 intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
988 break;
989 case RequestTemplate::STILL_CAPTURE:
990 intent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE;
991 break;
992 case RequestTemplate::VIDEO_RECORD:
993 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD;
994 break;
995 case RequestTemplate::VIDEO_SNAPSHOT:
996 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT;
997 break;
998 default:
999 ALOGV("%s: unsupported RequestTemplate type %d", __FUNCTION__, type);
1000 continue;
1001 }
1002 UPDATE(mdCopy, ANDROID_CONTROL_CAPTURE_INTENT, &intent, 1);
1003 camera_metadata_t* mdPtr = mdCopy.release();
1004 uint8_t* rawMd = reinterpret_cast<uint8_t*>(mdPtr);
1005 CameraMetadata aidlMd;
1006 aidlMd.metadata.assign(rawMd, rawMd + get_camera_metadata_size(mdPtr));
1007 mDefaultRequests[type] = aidlMd;
1008 free_camera_metadata(mdPtr);
1009 }
1010 return OK;
1011}
1012
1013status_t ExternalCameraDeviceSession::fillCaptureResult(common::V1_0::helper::CameraMetadata& md,
1014 nsecs_t timestamp) {
1015 bool afTrigger = false;
1016 {
1017 std::lock_guard<std::mutex> lk(mAfTriggerLock);
1018 afTrigger = mAfTrigger;
1019 if (md.exists(ANDROID_CONTROL_AF_TRIGGER)) {
1020 camera_metadata_entry entry = md.find(ANDROID_CONTROL_AF_TRIGGER);
1021 if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_START) {
1022 mAfTrigger = afTrigger = true;
1023 } else if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_CANCEL) {
1024 mAfTrigger = afTrigger = false;
1025 }
1026 }
1027 }
1028
1029 // For USB camera, the USB camera handles everything and we don't have control
1030 // over AF. We only simply fake the AF metadata based on the request
1031 // received here.
1032 uint8_t afState;
1033 if (afTrigger) {
1034 afState = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
1035 } else {
1036 afState = ANDROID_CONTROL_AF_STATE_INACTIVE;
1037 }
1038 UPDATE(md, ANDROID_CONTROL_AF_STATE, &afState, 1);
1039
1040 camera_metadata_ro_entry activeArraySize =
1041 mCameraCharacteristics.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
1042
1043 return fillCaptureResultCommon(md, timestamp, activeArraySize);
1044}
1045
1046int ExternalCameraDeviceSession::configureV4l2StreamLocked(const SupportedV4L2Format& v4l2Fmt,
1047 double requestFps) {
1048 ATRACE_CALL();
1049 int ret = v4l2StreamOffLocked();
1050 if (ret != OK) {
1051 ALOGE("%s: stop v4l2 streaming failed: ret %d", __FUNCTION__, ret);
1052 return ret;
1053 }
1054
1055 // VIDIOC_S_FMT w/h/fmt
1056 v4l2_format fmt;
1057 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1058 fmt.fmt.pix.width = v4l2Fmt.width;
1059 fmt.fmt.pix.height = v4l2Fmt.height;
1060 fmt.fmt.pix.pixelformat = v4l2Fmt.fourcc;
1061
1062 {
1063 int numAttempt = 0;
1064 do {
1065 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt));
1066 if (numAttempt == MAX_RETRY) {
1067 break;
1068 }
1069 numAttempt++;
1070 if (ret < 0) {
1071 ALOGW("%s: VIDIOC_S_FMT failed, wait 33ms and try again", __FUNCTION__);
1072 usleep(IOCTL_RETRY_SLEEP_US); // sleep and try again
1073 }
1074 } while (ret < 0);
1075 if (ret < 0) {
1076 ALOGE("%s: S_FMT ioctl failed: %s", __FUNCTION__, strerror(errno));
1077 return -errno;
1078 }
1079 }
1080
1081 if (v4l2Fmt.width != fmt.fmt.pix.width || v4l2Fmt.height != fmt.fmt.pix.height ||
1082 v4l2Fmt.fourcc != fmt.fmt.pix.pixelformat) {
1083 ALOGE("%s: S_FMT expect %c%c%c%c %dx%d, got %c%c%c%c %dx%d instead!", __FUNCTION__,
1084 v4l2Fmt.fourcc & 0xFF, (v4l2Fmt.fourcc >> 8) & 0xFF, (v4l2Fmt.fourcc >> 16) & 0xFF,
1085 (v4l2Fmt.fourcc >> 24) & 0xFF, v4l2Fmt.width, v4l2Fmt.height,
1086 fmt.fmt.pix.pixelformat & 0xFF, (fmt.fmt.pix.pixelformat >> 8) & 0xFF,
1087 (fmt.fmt.pix.pixelformat >> 16) & 0xFF, (fmt.fmt.pix.pixelformat >> 24) & 0xFF,
1088 fmt.fmt.pix.width, fmt.fmt.pix.height);
1089 return -EINVAL;
1090 }
1091
1092 uint32_t bufferSize = fmt.fmt.pix.sizeimage;
1093 ALOGI("%s: V4L2 buffer size is %d", __FUNCTION__, bufferSize);
1094 uint32_t expectedMaxBufferSize = kMaxBytesPerPixel * fmt.fmt.pix.width * fmt.fmt.pix.height;
1095 if ((bufferSize == 0) || (bufferSize > expectedMaxBufferSize)) {
1096 ALOGE("%s: V4L2 buffer size: %u looks invalid. Expected maximum size: %u", __FUNCTION__,
1097 bufferSize, expectedMaxBufferSize);
1098 return -EINVAL;
1099 }
1100 mMaxV4L2BufferSize = bufferSize;
1101
1102 const double kDefaultFps = 30.0;
1103 double fps = std::numeric_limits<double>::max();
1104 if (requestFps != 0.0) {
1105 fps = requestFps;
1106 } else {
1107 double maxFps = -1.0;
1108 // Try to pick the slowest fps that is at least 30
1109 for (const auto& fr : v4l2Fmt.frameRates) {
1110 double f = fr.getFramesPerSecond();
1111 if (maxFps < f) {
1112 maxFps = f;
1113 }
1114 if (f >= kDefaultFps && f < fps) {
1115 fps = f;
1116 }
1117 }
1118 // No fps > 30 found, use the highest fps available within supported formats.
1119 if (fps == std::numeric_limits<double>::max()) {
1120 fps = maxFps;
1121 }
1122 }
1123
1124 int fpsRet = setV4l2FpsLocked(fps);
1125 if (fpsRet != 0 && fpsRet != -EINVAL) {
1126 ALOGE("%s: set fps failed: %s", __FUNCTION__, strerror(fpsRet));
1127 return fpsRet;
1128 }
1129
1130 uint32_t v4lBufferCount = (fps >= kDefaultFps) ? mCfg.numVideoBuffers : mCfg.numStillBuffers;
1131
1132 // VIDIOC_REQBUFS: create buffers
1133 v4l2_requestbuffers req_buffers{};
1134 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1135 req_buffers.memory = V4L2_MEMORY_MMAP;
1136 req_buffers.count = v4lBufferCount;
1137 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
1138 ALOGE("%s: VIDIOC_REQBUFS failed: %s", __FUNCTION__, strerror(errno));
1139 return -errno;
1140 }
1141
1142 // Driver can indeed return more buffer if it needs more to operate
1143 if (req_buffers.count < v4lBufferCount) {
1144 ALOGE("%s: VIDIOC_REQBUFS expected %d buffers, got %d instead", __FUNCTION__,
1145 v4lBufferCount, req_buffers.count);
1146 return NO_MEMORY;
1147 }
1148
1149 // VIDIOC_QUERYBUF: get buffer offset in the V4L2 fd
1150 // VIDIOC_QBUF: send buffer to driver
1151 mV4L2BufferCount = req_buffers.count;
1152 for (uint32_t i = 0; i < req_buffers.count; i++) {
1153 v4l2_buffer buffer = {
1154 .index = i, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .memory = V4L2_MEMORY_MMAP};
1155
1156 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QUERYBUF, &buffer)) < 0) {
1157 ALOGE("%s: QUERYBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
1158 return -errno;
1159 }
1160
1161 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1162 ALOGE("%s: QBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
1163 return -errno;
1164 }
1165 }
1166
1167 {
1168 // VIDIOC_STREAMON: start streaming
1169 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1170 int numAttempt = 0;
1171 do {
1172 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type));
1173 if (numAttempt == MAX_RETRY) {
1174 break;
1175 }
1176 if (ret < 0) {
1177 ALOGW("%s: VIDIOC_STREAMON failed, wait 33ms and try again", __FUNCTION__);
1178 usleep(IOCTL_RETRY_SLEEP_US); // sleep 100 ms and try again
1179 }
1180 } while (ret < 0);
1181
1182 if (ret < 0) {
1183 ALOGE("%s: VIDIOC_STREAMON ioctl failed: %s", __FUNCTION__, strerror(errno));
1184 return -errno;
1185 }
1186 }
1187
1188 // Swallow first few frames after streamOn to account for bad frames from some devices
1189 for (int i = 0; i < kBadFramesAfterStreamOn; i++) {
1190 v4l2_buffer buffer{};
1191 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1192 buffer.memory = V4L2_MEMORY_MMAP;
1193 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
1194 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
1195 return -errno;
1196 }
1197
1198 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1199 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, buffer.index, strerror(errno));
1200 return -errno;
1201 }
1202 }
1203
1204 ALOGI("%s: start V4L2 streaming %dx%d@%ffps", __FUNCTION__, v4l2Fmt.width, v4l2Fmt.height, fps);
1205 mV4l2StreamingFmt = v4l2Fmt;
1206 mV4l2Streaming = true;
1207 return OK;
1208}
1209
1210std::unique_ptr<V4L2Frame> ExternalCameraDeviceSession::dequeueV4l2FrameLocked(nsecs_t* shutterTs) {
1211 ATRACE_CALL();
1212 std::unique_ptr<V4L2Frame> ret = nullptr;
1213 if (shutterTs == nullptr) {
1214 ALOGE("%s: shutterTs must not be null!", __FUNCTION__);
1215 return ret;
1216 }
1217
1218 {
1219 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
1220 if (mNumDequeuedV4l2Buffers == mV4L2BufferCount) {
1221 int waitRet = waitForV4L2BufferReturnLocked(lk);
1222 if (waitRet != 0) {
1223 return ret;
1224 }
1225 }
1226 }
1227
1228 ATRACE_BEGIN("VIDIOC_DQBUF");
1229 v4l2_buffer buffer{};
1230 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1231 buffer.memory = V4L2_MEMORY_MMAP;
1232 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
1233 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
1234 return ret;
1235 }
1236 ATRACE_END();
1237
1238 if (buffer.index >= mV4L2BufferCount) {
1239 ALOGE("%s: Invalid buffer id: %d", __FUNCTION__, buffer.index);
1240 return ret;
1241 }
1242
1243 if (buffer.flags & V4L2_BUF_FLAG_ERROR) {
1244 ALOGE("%s: v4l2 buf error! buf flag 0x%x", __FUNCTION__, buffer.flags);
1245 // TODO: try to dequeue again
1246 }
1247
1248 if (buffer.bytesused > mMaxV4L2BufferSize) {
1249 ALOGE("%s: v4l2 buffer bytes used: %u maximum %u", __FUNCTION__, buffer.bytesused,
1250 mMaxV4L2BufferSize);
1251 return ret;
1252 }
1253
1254 if (buffer.flags & V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC) {
1255 // Ideally we should also check for V4L2_BUF_FLAG_TSTAMP_SRC_SOE, but
1256 // even V4L2_BUF_FLAG_TSTAMP_SRC_EOF is better than capture a timestamp now
1257 *shutterTs = static_cast<nsecs_t>(buffer.timestamp.tv_sec) * 1000000000LL +
1258 buffer.timestamp.tv_usec * 1000LL;
1259 } else {
1260 *shutterTs = systemTime(SYSTEM_TIME_MONOTONIC);
1261 }
1262
1263 {
1264 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1265 mNumDequeuedV4l2Buffers++;
1266 }
1267
1268 return std::make_unique<V4L2Frame>(mV4l2StreamingFmt.width, mV4l2StreamingFmt.height,
1269 mV4l2StreamingFmt.fourcc, buffer.index, mV4l2Fd.get(),
1270 buffer.bytesused, buffer.m.offset);
1271}
1272
1273void ExternalCameraDeviceSession::enqueueV4l2Frame(const std::shared_ptr<V4L2Frame>& frame) {
1274 ATRACE_CALL();
1275 frame->unmap();
1276 ATRACE_BEGIN("VIDIOC_QBUF");
1277 v4l2_buffer buffer{};
1278 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1279 buffer.memory = V4L2_MEMORY_MMAP;
1280 buffer.index = frame->mBufferIndex;
1281 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1282 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, frame->mBufferIndex, strerror(errno));
1283 return;
1284 }
1285 ATRACE_END();
1286
1287 {
1288 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1289 mNumDequeuedV4l2Buffers--;
1290 }
1291 mV4L2BufferReturned.notify_one();
1292}
1293
1294bool ExternalCameraDeviceSession::isSupported(
1295 const Stream& stream, const std::vector<SupportedV4L2Format>& supportedFormats,
1296 const ExternalCameraConfig& devCfg) {
1297 Dataspace ds = stream.dataSpace;
1298 PixelFormat fmt = stream.format;
1299 uint32_t width = stream.width;
1300 uint32_t height = stream.height;
1301 // TODO: check usage flags
1302
1303 if (stream.streamType != StreamType::OUTPUT) {
1304 ALOGE("%s: does not support non-output stream type", __FUNCTION__);
1305 return false;
1306 }
1307
1308 if (stream.rotation != StreamRotation::ROTATION_0) {
1309 ALOGE("%s: does not support stream rotation", __FUNCTION__);
1310 return false;
1311 }
1312
1313 switch (fmt) {
1314 case PixelFormat::BLOB:
1315 if (ds != Dataspace::JFIF) {
1316 ALOGI("%s: BLOB format does not support dataSpace %x", __FUNCTION__, ds);
1317 return false;
1318 }
1319 break;
1320 case PixelFormat::IMPLEMENTATION_DEFINED:
1321 case PixelFormat::YCBCR_420_888:
1322 case PixelFormat::YV12:
1323 // TODO: check what dataspace we can support here.
1324 // intentional no-ops.
1325 break;
1326 case PixelFormat::Y16:
1327 if (!devCfg.depthEnabled) {
1328 ALOGI("%s: Depth is not Enabled", __FUNCTION__);
1329 return false;
1330 }
1331 if (!(static_cast<int32_t>(ds) & static_cast<int32_t>(Dataspace::DEPTH))) {
1332 ALOGI("%s: Y16 supports only dataSpace DEPTH", __FUNCTION__);
1333 return false;
1334 }
1335 break;
1336 default:
1337 ALOGI("%s: does not support format %x", __FUNCTION__, fmt);
1338 return false;
1339 }
1340
1341 // Assume we can convert any V4L2 format to any of supported output format for now, i.e.
1342 // ignoring v4l2Fmt.fourcc for now. Might need more subtle check if we support more v4l format
1343 // in the futrue.
1344 for (const auto& v4l2Fmt : supportedFormats) {
1345 if (width == v4l2Fmt.width && height == v4l2Fmt.height) {
1346 return true;
1347 }
1348 }
1349 ALOGI("%s: resolution %dx%d is not supported", __FUNCTION__, width, height);
1350 return false;
1351}
1352
1353Status ExternalCameraDeviceSession::importRequestLocked(const CaptureRequest& request,
1354 std::vector<buffer_handle_t*>& allBufPtrs,
1355 std::vector<int>& allFences) {
1356 return importRequestLockedImpl(request, allBufPtrs, allFences);
1357}
1358
1359Status ExternalCameraDeviceSession::importRequestLockedImpl(
1360 const CaptureRequest& request, std::vector<buffer_handle_t*>& allBufPtrs,
1361 std::vector<int>& allFences) {
1362 size_t numOutputBufs = request.outputBuffers.size();
1363 size_t numBufs = numOutputBufs;
1364 // Validate all I/O buffers
1365 std::vector<buffer_handle_t> allBufs;
1366 std::vector<uint64_t> allBufIds;
1367 allBufs.resize(numBufs);
1368 allBufIds.resize(numBufs);
1369 allBufPtrs.resize(numBufs);
1370 allFences.resize(numBufs);
1371 std::vector<int32_t> streamIds(numBufs);
1372
1373 for (size_t i = 0; i < numOutputBufs; i++) {
1374 allBufs[i] = ::android::makeFromAidl(request.outputBuffers[i].buffer);
1375 allBufIds[i] = request.outputBuffers[i].bufferId;
1376 allBufPtrs[i] = &allBufs[i];
1377 streamIds[i] = request.outputBuffers[i].streamId;
1378 }
1379
1380 {
1381 Mutex::Autolock _l(mCbsLock);
1382 for (size_t i = 0; i < numBufs; i++) {
1383 Status st = importBufferLocked(streamIds[i], allBufIds[i], allBufs[i], &allBufPtrs[i]);
1384 if (st != Status::OK) {
1385 // Detailed error logs printed in importBuffer
1386 return st;
1387 }
1388 }
1389 }
1390
1391 // All buffers are imported. Now validate output buffer acquire fences
1392 for (size_t i = 0; i < numOutputBufs; i++) {
1393 if (!sHandleImporter.importFence(
1394 ::android::makeFromAidl(request.outputBuffers[i].acquireFence), allFences[i])) {
1395 ALOGE("%s: output buffer %zu acquire fence is invalid", __FUNCTION__, i);
1396 cleanupInflightFences(allFences, i);
1397 return Status::INTERNAL_ERROR;
1398 }
1399 }
1400 return Status::OK;
1401}
1402
1403Status ExternalCameraDeviceSession::importBuffer(int32_t streamId, uint64_t bufId,
1404 buffer_handle_t buf,
1405 /*out*/ buffer_handle_t** outBufPtr) {
1406 Mutex::Autolock _l(mCbsLock);
1407 return importBufferLocked(streamId, bufId, buf, outBufPtr);
1408}
1409
1410Status ExternalCameraDeviceSession::importBufferLocked(int32_t streamId, uint64_t bufId,
1411 buffer_handle_t buf,
1412 buffer_handle_t** outBufPtr) {
1413 return importBufferImpl(mCirculatingBuffers, sHandleImporter, streamId, bufId, buf, outBufPtr);
1414}
1415
1416ScopedAStatus ExternalCameraDeviceSession::close() {
Tang Lee65382f62023-08-01 18:23:07 +08001417 closeImpl();
Avichal Rakeshe1857f82022-06-08 17:47:23 -07001418 return fromStatus(Status::OK);
1419}
1420
Tang Lee65382f62023-08-01 18:23:07 +08001421void ExternalCameraDeviceSession::closeImpl() {
Avichal Rakeshe1857f82022-06-08 17:47:23 -07001422 Mutex::Autolock _il(mInterfaceLock);
1423 bool closed = isClosed();
1424 if (!closed) {
Tang Lee65382f62023-08-01 18:23:07 +08001425 closeOutputThread();
1426 closeBufferRequestThread();
Avichal Rakeshe1857f82022-06-08 17:47:23 -07001427
1428 Mutex::Autolock _l(mLock);
1429 // free all buffers
1430 {
1431 Mutex::Autolock _cbsl(mCbsLock);
1432 for (auto pair : mStreamMap) {
1433 cleanupBuffersLocked(/*Stream ID*/ pair.first);
1434 }
1435 }
1436 v4l2StreamOffLocked();
1437 ALOGV("%s: closing V4L2 camera FD %d", __FUNCTION__, mV4l2Fd.get());
1438 mV4l2Fd.reset();
1439 mClosed = true;
1440 }
1441}
1442
1443bool ExternalCameraDeviceSession::isClosed() {
1444 Mutex::Autolock _l(mLock);
1445 return mClosed;
1446}
1447
1448ScopedAStatus ExternalCameraDeviceSession::repeatingRequestEnd(
1449 int32_t /*in_frameNumber*/, const std::vector<int32_t>& /*in_streamIds*/) {
1450 // TODO: Figure this one out.
1451 return fromStatus(Status::OK);
1452}
1453
1454int ExternalCameraDeviceSession::v4l2StreamOffLocked() {
1455 if (!mV4l2Streaming) {
1456 return OK;
1457 }
1458
1459 {
1460 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1461 if (mNumDequeuedV4l2Buffers != 0) {
1462 ALOGE("%s: there are %zu inflight V4L buffers", __FUNCTION__, mNumDequeuedV4l2Buffers);
1463 return -1;
1464 }
1465 }
1466 mV4L2BufferCount = 0;
1467
1468 // VIDIOC_STREAMOFF
1469 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1470 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMOFF, &capture_type)) < 0) {
1471 ALOGE("%s: STREAMOFF failed: %s", __FUNCTION__, strerror(errno));
1472 return -errno;
1473 }
1474
1475 // VIDIOC_REQBUFS: clear buffers
1476 v4l2_requestbuffers req_buffers{};
1477 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1478 req_buffers.memory = V4L2_MEMORY_MMAP;
1479 req_buffers.count = 0;
1480 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
1481 ALOGE("%s: REQBUFS failed: %s", __FUNCTION__, strerror(errno));
1482 return -errno;
1483 }
1484
1485 mV4l2Streaming = false;
1486 return OK;
1487}
1488
1489int ExternalCameraDeviceSession::setV4l2FpsLocked(double fps) {
1490 // VIDIOC_G_PARM/VIDIOC_S_PARM: set fps
1491 v4l2_streamparm streamparm = {.type = V4L2_BUF_TYPE_VIDEO_CAPTURE};
1492 // The following line checks that the driver knows about framerate get/set.
1493 int ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_G_PARM, &streamparm));
1494 if (ret != 0) {
1495 if (errno == -EINVAL) {
1496 ALOGW("%s: device does not support VIDIOC_G_PARM", __FUNCTION__);
1497 }
1498 return -errno;
1499 }
1500 // Now check if the device is able to accept a capture framerate set.
1501 if (!(streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME)) {
1502 ALOGW("%s: device does not support V4L2_CAP_TIMEPERFRAME", __FUNCTION__);
1503 return -EINVAL;
1504 }
1505
1506 // fps is float, approximate by a fraction.
1507 const int kFrameRatePrecision = 10000;
1508 streamparm.parm.capture.timeperframe.numerator = kFrameRatePrecision;
1509 streamparm.parm.capture.timeperframe.denominator = (fps * kFrameRatePrecision);
1510
1511 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_PARM, &streamparm)) < 0) {
1512 ALOGE("%s: failed to set framerate to %f: %s", __FUNCTION__, fps, strerror(errno));
1513 return -1;
1514 }
1515
1516 double retFps = streamparm.parm.capture.timeperframe.denominator /
1517 static_cast<double>(streamparm.parm.capture.timeperframe.numerator);
1518 if (std::fabs(fps - retFps) > 1.0) {
1519 ALOGE("%s: expect fps %f, got %f instead", __FUNCTION__, fps, retFps);
1520 return -1;
1521 }
1522 mV4l2StreamingFps = fps;
1523 return 0;
1524}
1525
1526void ExternalCameraDeviceSession::cleanupInflightFences(std::vector<int>& allFences,
1527 size_t numFences) {
1528 for (size_t j = 0; j < numFences; j++) {
1529 sHandleImporter.closeFence(allFences[j]);
1530 }
1531}
1532
1533void ExternalCameraDeviceSession::cleanupBuffersLocked(int id) {
1534 for (auto& pair : mCirculatingBuffers.at(id)) {
1535 sHandleImporter.freeBuffer(pair.second);
1536 }
1537 mCirculatingBuffers[id].clear();
1538 mCirculatingBuffers.erase(id);
1539}
1540
1541void ExternalCameraDeviceSession::notifyShutter(int32_t frameNumber, nsecs_t shutterTs) {
1542 NotifyMsg msg;
1543 msg.set<NotifyMsg::Tag::shutter>(ShutterMsg{
1544 .frameNumber = frameNumber,
1545 .timestamp = shutterTs,
1546 });
1547 mCallback->notify({msg});
1548}
1549void ExternalCameraDeviceSession::notifyError(int32_t frameNumber, int32_t streamId, ErrorCode ec) {
1550 NotifyMsg msg;
1551 msg.set<NotifyMsg::Tag::error>(ErrorMsg{
1552 .frameNumber = frameNumber,
1553 .errorStreamId = streamId,
1554 .errorCode = ec,
1555 });
1556 mCallback->notify({msg});
1557}
1558
1559void ExternalCameraDeviceSession::invokeProcessCaptureResultCallback(
1560 std::vector<CaptureResult>& results, bool tryWriteFmq) {
1561 if (mProcessCaptureResultLock.tryLock() != OK) {
1562 const nsecs_t NS_TO_SECOND = 1000000000;
1563 ALOGV("%s: previous call is not finished! waiting 1s...", __FUNCTION__);
1564 if (mProcessCaptureResultLock.timedLock(/* 1s */ NS_TO_SECOND) != OK) {
1565 ALOGE("%s: cannot acquire lock in 1s, cannot proceed", __FUNCTION__);
1566 return;
1567 }
1568 }
1569 if (tryWriteFmq && mResultMetadataQueue->availableToWrite() > 0) {
1570 for (CaptureResult& result : results) {
1571 CameraMetadata& md = result.result;
1572 if (!md.metadata.empty()) {
1573 if (mResultMetadataQueue->write(reinterpret_cast<int8_t*>(md.metadata.data()),
1574 md.metadata.size())) {
1575 result.fmqResultSize = md.metadata.size();
1576 md.metadata.resize(0);
1577 } else {
1578 ALOGW("%s: couldn't utilize fmq, fall back to hwbinder", __FUNCTION__);
1579 result.fmqResultSize = 0;
1580 }
1581 } else {
1582 result.fmqResultSize = 0;
1583 }
1584 }
1585 }
1586 auto status = mCallback->processCaptureResult(results);
1587 if (!status.isOk()) {
1588 ALOGE("%s: processCaptureResult ERROR : %d:%d", __FUNCTION__, status.getExceptionCode(),
1589 status.getServiceSpecificError());
1590 }
1591
1592 mProcessCaptureResultLock.unlock();
1593}
1594
1595int ExternalCameraDeviceSession::waitForV4L2BufferReturnLocked(std::unique_lock<std::mutex>& lk) {
1596 ATRACE_CALL();
1597 auto timeout = std::chrono::seconds(kBufferWaitTimeoutSec);
1598 mLock.unlock();
1599 auto st = mV4L2BufferReturned.wait_for(lk, timeout);
1600 // Here we introduce an order where mV4l2BufferLock is acquired before mLock, while
1601 // the normal lock acquisition order is reversed. This is fine because in most of
1602 // cases we are protected by mInterfaceLock. The only thread that can cause deadlock
1603 // is the OutputThread, where we do need to make sure we don't acquire mLock then
1604 // mV4l2BufferLock
1605 mLock.lock();
1606 if (st == std::cv_status::timeout) {
1607 ALOGE("%s: wait for V4L2 buffer return timeout!", __FUNCTION__);
1608 return -1;
1609 }
1610 return 0;
1611}
1612
1613bool ExternalCameraDeviceSession::supportOfflineLocked(int32_t streamId) {
1614 const Stream& stream = mStreamMap[streamId];
1615 if (stream.format == PixelFormat::BLOB &&
1616 static_cast<int32_t>(stream.dataSpace) == static_cast<int32_t>(Dataspace::JFIF)) {
1617 return true;
1618 }
1619 // TODO: support YUV output stream?
1620 return false;
1621}
1622
1623bool ExternalCameraDeviceSession::canDropRequest(const std::vector<int32_t>& offlineStreams,
1624 std::shared_ptr<HalRequest> halReq) {
1625 for (const auto& buffer : halReq->buffers) {
1626 for (auto offlineStreamId : offlineStreams) {
1627 if (buffer.streamId == offlineStreamId) {
1628 return false;
1629 }
1630 }
1631 }
1632 // Only drop a request completely if it has no offline output
1633 return true;
1634}
1635
1636void ExternalCameraDeviceSession::fillOfflineSessionInfo(
1637 const std::vector<int32_t>& offlineStreams,
1638 std::deque<std::shared_ptr<HalRequest>>& offlineReqs,
1639 const std::map<int, CirculatingBuffers>& circulatingBuffers,
1640 CameraOfflineSessionInfo* info) {
1641 if (info == nullptr) {
1642 ALOGE("%s: output info must not be null!", __FUNCTION__);
1643 return;
1644 }
1645
1646 info->offlineStreams.resize(offlineStreams.size());
1647 info->offlineRequests.resize(offlineReqs.size());
1648
1649 // Fill in offline reqs and count outstanding buffers
1650 for (size_t i = 0; i < offlineReqs.size(); i++) {
1651 info->offlineRequests[i].frameNumber = offlineReqs[i]->frameNumber;
1652 info->offlineRequests[i].pendingStreams.resize(offlineReqs[i]->buffers.size());
1653 for (size_t bIdx = 0; bIdx < offlineReqs[i]->buffers.size(); bIdx++) {
1654 int32_t streamId = offlineReqs[i]->buffers[bIdx].streamId;
1655 info->offlineRequests[i].pendingStreams[bIdx] = streamId;
1656 }
1657 }
1658
1659 for (size_t i = 0; i < offlineStreams.size(); i++) {
1660 int32_t streamId = offlineStreams[i];
1661 info->offlineStreams[i].id = streamId;
1662 // outstanding buffers are 0 since we are doing hal buffer management and
1663 // offline session will ask for those buffers later
1664 info->offlineStreams[i].numOutstandingBuffers = 0;
1665 const CirculatingBuffers& bufIdMap = circulatingBuffers.at(streamId);
1666 info->offlineStreams[i].circulatingBufferIds.resize(bufIdMap.size());
1667 size_t bIdx = 0;
1668 for (const auto& pair : bufIdMap) {
1669 // Fill in bufferId
1670 info->offlineStreams[i].circulatingBufferIds[bIdx++] = pair.first;
1671 }
1672 }
1673}
1674
1675Status ExternalCameraDeviceSession::isStreamCombinationSupported(
1676 const StreamConfiguration& config, const std::vector<SupportedV4L2Format>& supportedFormats,
1677 const ExternalCameraConfig& devCfg) {
1678 if (config.operationMode != StreamConfigurationMode::NORMAL_MODE) {
1679 ALOGE("%s: unsupported operation mode: %d", __FUNCTION__, config.operationMode);
1680 return Status::ILLEGAL_ARGUMENT;
1681 }
1682
1683 if (config.streams.size() == 0) {
1684 ALOGE("%s: cannot configure zero stream", __FUNCTION__);
1685 return Status::ILLEGAL_ARGUMENT;
1686 }
1687
1688 int numProcessedStream = 0;
1689 int numStallStream = 0;
1690 for (const auto& stream : config.streams) {
1691 // Check if the format/width/height combo is supported
1692 if (!isSupported(stream, supportedFormats, devCfg)) {
1693 return Status::ILLEGAL_ARGUMENT;
1694 }
1695 if (stream.format == PixelFormat::BLOB) {
1696 numStallStream++;
1697 } else {
1698 numProcessedStream++;
1699 }
1700 }
1701
1702 if (numProcessedStream > kMaxProcessedStream) {
1703 ALOGE("%s: too many processed streams (expect <= %d, got %d)", __FUNCTION__,
1704 kMaxProcessedStream, numProcessedStream);
1705 return Status::ILLEGAL_ARGUMENT;
1706 }
1707
1708 if (numStallStream > kMaxStallStream) {
1709 ALOGE("%s: too many stall streams (expect <= %d, got %d)", __FUNCTION__, kMaxStallStream,
1710 numStallStream);
1711 return Status::ILLEGAL_ARGUMENT;
1712 }
1713
1714 return Status::OK;
1715}
1716void ExternalCameraDeviceSession::updateBufferCaches(
1717 const std::vector<BufferCache>& cachesToRemove) {
1718 Mutex::Autolock _l(mCbsLock);
1719 for (auto& cache : cachesToRemove) {
1720 auto cbsIt = mCirculatingBuffers.find(cache.streamId);
1721 if (cbsIt == mCirculatingBuffers.end()) {
1722 // The stream could have been removed
1723 continue;
1724 }
1725 CirculatingBuffers& cbs = cbsIt->second;
1726 auto it = cbs.find(cache.bufferId);
1727 if (it != cbs.end()) {
1728 sHandleImporter.freeBuffer(it->second);
1729 cbs.erase(it);
1730 } else {
1731 ALOGE("%s: stream %d buffer %" PRIu64 " is not cached", __FUNCTION__, cache.streamId,
1732 cache.bufferId);
1733 }
1734 }
1735}
1736
1737Status ExternalCameraDeviceSession::processCaptureRequestError(
1738 const std::shared_ptr<HalRequest>& req, std::vector<NotifyMsg>* outMsgs,
1739 std::vector<CaptureResult>* outResults) {
1740 ATRACE_CALL();
1741 // Return V4L2 buffer to V4L2 buffer queue
1742 std::shared_ptr<V4L2Frame> v4l2Frame = std::static_pointer_cast<V4L2Frame>(req->frameIn);
1743 enqueueV4l2Frame(v4l2Frame);
1744
1745 if (outMsgs == nullptr) {
1746 notifyShutter(req->frameNumber, req->shutterTs);
1747 notifyError(/*frameNum*/ req->frameNumber, /*stream*/ -1, ErrorCode::ERROR_REQUEST);
1748 } else {
1749 NotifyMsg shutter;
1750 shutter.set<NotifyMsg::Tag::shutter>(
1751 ShutterMsg{.frameNumber = req->frameNumber, .timestamp = req->shutterTs});
1752
1753 NotifyMsg error;
1754 error.set<NotifyMsg::Tag::error>(ErrorMsg{.frameNumber = req->frameNumber,
1755 .errorStreamId = -1,
1756 .errorCode = ErrorCode::ERROR_REQUEST});
1757 outMsgs->push_back(shutter);
1758 outMsgs->push_back(error);
1759 }
1760
1761 // Fill output buffers
1762 CaptureResult result;
1763 result.frameNumber = req->frameNumber;
1764 result.partialResult = 1;
1765 result.inputBuffer.streamId = -1;
1766 result.outputBuffers.resize(req->buffers.size());
1767 for (size_t i = 0; i < req->buffers.size(); i++) {
1768 result.outputBuffers[i].streamId = req->buffers[i].streamId;
1769 result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
1770 result.outputBuffers[i].status = BufferStatus::ERROR;
1771 if (req->buffers[i].acquireFence >= 0) {
1772 native_handle_t* handle = native_handle_create(/*numFds*/ 1, /*numInts*/ 0);
1773 handle->data[0] = req->buffers[i].acquireFence;
1774 result.outputBuffers[i].releaseFence = ::android::makeToAidl(handle);
1775 }
1776 }
1777
1778 // update inflight records
1779 {
1780 std::lock_guard<std::mutex> lk(mInflightFramesLock);
1781 mInflightFrames.erase(req->frameNumber);
1782 }
1783
1784 if (outResults == nullptr) {
1785 // Callback into framework
1786 std::vector<CaptureResult> results(1);
1787 results[0] = std::move(result);
1788 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */ true);
1789 freeReleaseFences(results);
1790 } else {
1791 outResults->push_back(std::move(result));
1792 }
1793 return Status::OK;
1794}
1795
1796Status ExternalCameraDeviceSession::processCaptureResult(std::shared_ptr<HalRequest>& req) {
1797 ATRACE_CALL();
1798 // Return V4L2 buffer to V4L2 buffer queue
1799 std::shared_ptr<V4L2Frame> v4l2Frame = std::static_pointer_cast<V4L2Frame>(req->frameIn);
1800 enqueueV4l2Frame(v4l2Frame);
1801
1802 // NotifyShutter
1803 notifyShutter(req->frameNumber, req->shutterTs);
1804
1805 // Fill output buffers;
1806 std::vector<CaptureResult> results(1);
1807 CaptureResult& result = results[0];
1808 result.frameNumber = req->frameNumber;
1809 result.partialResult = 1;
1810 result.inputBuffer.streamId = -1;
1811 result.outputBuffers.resize(req->buffers.size());
1812 for (size_t i = 0; i < req->buffers.size(); i++) {
1813 result.outputBuffers[i].streamId = req->buffers[i].streamId;
1814 result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
1815 if (req->buffers[i].fenceTimeout) {
1816 result.outputBuffers[i].status = BufferStatus::ERROR;
1817 if (req->buffers[i].acquireFence >= 0) {
1818 native_handle_t* handle = native_handle_create(/*numFds*/ 1, /*numInts*/ 0);
1819 handle->data[0] = req->buffers[i].acquireFence;
1820 result.outputBuffers[i].releaseFence = ::android::makeToAidl(handle);
1821 }
1822 notifyError(req->frameNumber, req->buffers[i].streamId, ErrorCode::ERROR_BUFFER);
1823 } else {
1824 result.outputBuffers[i].status = BufferStatus::OK;
1825 // TODO: refactor
1826 if (req->buffers[i].acquireFence >= 0) {
1827 native_handle_t* handle = native_handle_create(/*numFds*/ 1, /*numInts*/ 0);
1828 handle->data[0] = req->buffers[i].acquireFence;
1829 result.outputBuffers[i].releaseFence = ::android::makeToAidl(handle);
1830 }
1831 }
1832 }
1833
1834 // Fill capture result metadata
1835 fillCaptureResult(req->setting, req->shutterTs);
1836 const camera_metadata_t* rawResult = req->setting.getAndLock();
1837 convertToAidl(rawResult, &result.result);
1838 req->setting.unlock(rawResult);
1839
1840 // update inflight records
1841 {
1842 std::lock_guard<std::mutex> lk(mInflightFramesLock);
1843 mInflightFrames.erase(req->frameNumber);
1844 }
1845
1846 // Callback into framework
1847 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */ true);
1848 freeReleaseFences(results);
1849 return Status::OK;
1850}
1851
1852ssize_t ExternalCameraDeviceSession::getJpegBufferSize(int32_t width, int32_t height) const {
1853 // Constant from camera3.h
1854 const ssize_t kMinJpegBufferSize = 256 * 1024 + sizeof(CameraBlob);
1855 // Get max jpeg size (area-wise).
1856 if (mMaxJpegResolution.width == 0) {
1857 ALOGE("%s: No supported JPEG stream", __FUNCTION__);
1858 return BAD_VALUE;
1859 }
1860
1861 // Get max jpeg buffer size
1862 ssize_t maxJpegBufferSize = 0;
1863 camera_metadata_ro_entry jpegBufMaxSize = mCameraCharacteristics.find(ANDROID_JPEG_MAX_SIZE);
1864 if (jpegBufMaxSize.count == 0) {
1865 ALOGE("%s: Can't find maximum JPEG size in static metadata!", __FUNCTION__);
1866 return BAD_VALUE;
1867 }
1868 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
1869
1870 if (maxJpegBufferSize <= kMinJpegBufferSize) {
1871 ALOGE("%s: ANDROID_JPEG_MAX_SIZE (%zd) <= kMinJpegBufferSize (%zd)", __FUNCTION__,
1872 maxJpegBufferSize, kMinJpegBufferSize);
1873 return BAD_VALUE;
1874 }
1875
1876 // Calculate final jpeg buffer size for the given resolution.
1877 float scaleFactor =
1878 ((float)(width * height)) / (mMaxJpegResolution.width * mMaxJpegResolution.height);
1879 ssize_t jpegBufferSize =
1880 scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) + kMinJpegBufferSize;
1881 if (jpegBufferSize > maxJpegBufferSize) {
1882 jpegBufferSize = maxJpegBufferSize;
1883 }
1884
1885 return jpegBufferSize;
1886}
1887binder_status_t ExternalCameraDeviceSession::dump(int fd, const char** /*args*/,
1888 uint32_t /*numArgs*/) {
1889 bool intfLocked = tryLock(mInterfaceLock);
1890 if (!intfLocked) {
1891 dprintf(fd, "!! ExternalCameraDeviceSession interface may be deadlocked !!\n");
1892 }
1893
1894 if (isClosed()) {
1895 dprintf(fd, "External camera %s is closed\n", mCameraId.c_str());
1896 return STATUS_OK;
1897 }
1898
1899 bool streaming = false;
1900 size_t v4L2BufferCount = 0;
1901 SupportedV4L2Format streamingFmt;
1902 {
1903 bool sessionLocked = tryLock(mLock);
1904 if (!sessionLocked) {
1905 dprintf(fd, "!! ExternalCameraDeviceSession mLock may be deadlocked !!\n");
1906 }
1907 streaming = mV4l2Streaming;
1908 streamingFmt = mV4l2StreamingFmt;
1909 v4L2BufferCount = mV4L2BufferCount;
1910
1911 if (sessionLocked) {
1912 mLock.unlock();
1913 }
1914 }
1915
1916 std::unordered_set<uint32_t> inflightFrames;
1917 {
1918 bool iffLocked = tryLock(mInflightFramesLock);
1919 if (!iffLocked) {
1920 dprintf(fd,
1921 "!! ExternalCameraDeviceSession mInflightFramesLock may be deadlocked !!\n");
1922 }
1923 inflightFrames = mInflightFrames;
1924 if (iffLocked) {
1925 mInflightFramesLock.unlock();
1926 }
1927 }
1928
1929 dprintf(fd, "External camera %s V4L2 FD %d, cropping type %s, %s\n", mCameraId.c_str(),
1930 mV4l2Fd.get(), (mCroppingType == VERTICAL) ? "vertical" : "horizontal",
1931 streaming ? "streaming" : "not streaming");
1932
1933 if (streaming) {
1934 // TODO: dump fps later
1935 dprintf(fd, "Current V4L2 format %c%c%c%c %dx%d @ %ffps\n", streamingFmt.fourcc & 0xFF,
1936 (streamingFmt.fourcc >> 8) & 0xFF, (streamingFmt.fourcc >> 16) & 0xFF,
1937 (streamingFmt.fourcc >> 24) & 0xFF, streamingFmt.width, streamingFmt.height,
1938 mV4l2StreamingFps);
1939
1940 size_t numDequeuedV4l2Buffers = 0;
1941 {
1942 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1943 numDequeuedV4l2Buffers = mNumDequeuedV4l2Buffers;
1944 }
1945 dprintf(fd, "V4L2 buffer queue size %zu, dequeued %zu\n", v4L2BufferCount,
1946 numDequeuedV4l2Buffers);
1947 }
1948
1949 dprintf(fd, "In-flight frames (not sorted):");
1950 for (const auto& frameNumber : inflightFrames) {
1951 dprintf(fd, "%d, ", frameNumber);
1952 }
1953 dprintf(fd, "\n");
1954 mOutputThread->dump(fd);
1955 dprintf(fd, "\n");
1956
1957 if (intfLocked) {
1958 mInterfaceLock.unlock();
1959 }
1960
1961 return STATUS_OK;
1962}
1963
1964// Start ExternalCameraDeviceSession::BufferRequestThread functions
1965ExternalCameraDeviceSession::BufferRequestThread::BufferRequestThread(
1966 std::weak_ptr<OutputThreadInterface> parent,
1967 std::shared_ptr<ICameraDeviceCallback> callbacks)
1968 : mParent(parent), mCallbacks(callbacks) {}
1969
1970int ExternalCameraDeviceSession::BufferRequestThread::requestBufferStart(
1971 const std::vector<HalStreamBuffer>& bufReqs) {
1972 if (bufReqs.empty()) {
1973 ALOGE("%s: bufReqs is empty!", __FUNCTION__);
1974 return -1;
1975 }
1976
1977 {
1978 std::lock_guard<std::mutex> lk(mLock);
1979 if (mRequestingBuffer) {
1980 ALOGE("%s: BufferRequestThread does not support more than one concurrent request!",
1981 __FUNCTION__);
1982 return -1;
1983 }
1984
1985 mBufferReqs = bufReqs;
1986 mRequestingBuffer = true;
1987 }
1988 mRequestCond.notify_one();
1989 return 0;
1990}
1991
1992int ExternalCameraDeviceSession::BufferRequestThread::waitForBufferRequestDone(
1993 std::vector<HalStreamBuffer>* outBufReqs) {
1994 std::unique_lock<std::mutex> lk(mLock);
1995 if (!mRequestingBuffer) {
1996 ALOGE("%s: no pending buffer request!", __FUNCTION__);
1997 return -1;
1998 }
1999
2000 if (mPendingReturnBufferReqs.empty()) {
2001 std::chrono::milliseconds timeout = std::chrono::milliseconds(kReqProcTimeoutMs);
2002 auto st = mRequestDoneCond.wait_for(lk, timeout);
2003 if (st == std::cv_status::timeout) {
2004 ALOGE("%s: wait for buffer request finish timeout!", __FUNCTION__);
2005 return -1;
2006 }
2007 }
2008 mRequestingBuffer = false;
2009 *outBufReqs = std::move(mPendingReturnBufferReqs);
2010 mPendingReturnBufferReqs.clear();
2011 return 0;
2012}
2013
2014void ExternalCameraDeviceSession::BufferRequestThread::waitForNextRequest() {
2015 ATRACE_CALL();
2016 std::unique_lock<std::mutex> lk(mLock);
2017 int waitTimes = 0;
2018 while (mBufferReqs.empty()) {
2019 if (exitPending()) {
2020 return;
2021 }
2022 auto timeout = std::chrono::milliseconds(kReqWaitTimeoutMs);
2023 auto st = mRequestCond.wait_for(lk, timeout);
2024 if (st == std::cv_status::timeout) {
2025 waitTimes++;
2026 if (waitTimes == kReqWaitTimesWarn) {
2027 // BufferRequestThread just wait forever for new buffer request
2028 // But it will print some periodic warning indicating it's waiting
2029 ALOGV("%s: still waiting for new buffer request", __FUNCTION__);
2030 waitTimes = 0;
2031 }
2032 }
2033 }
2034
2035 // Fill in BufferRequest
2036 mHalBufferReqs.resize(mBufferReqs.size());
2037 for (size_t i = 0; i < mHalBufferReqs.size(); i++) {
2038 mHalBufferReqs[i].streamId = mBufferReqs[i].streamId;
2039 mHalBufferReqs[i].numBuffersRequested = 1;
2040 }
2041}
2042
2043bool ExternalCameraDeviceSession::BufferRequestThread::threadLoop() {
2044 waitForNextRequest();
2045 if (exitPending()) {
2046 return false;
2047 }
2048
2049 ATRACE_BEGIN("AIDL requestStreamBuffers");
2050 BufferRequestStatus status;
2051 std::vector<StreamBufferRet> bufRets;
2052 ScopedAStatus ret = mCallbacks->requestStreamBuffers(mHalBufferReqs, &bufRets, &status);
2053 if (!ret.isOk()) {
2054 ALOGE("%s: Transaction error: %d:%d", __FUNCTION__, ret.getExceptionCode(),
2055 ret.getServiceSpecificError());
2056 return false;
2057 }
2058
2059 std::unique_lock<std::mutex> lk(mLock);
2060 if (status == BufferRequestStatus::OK || status == BufferRequestStatus::FAILED_PARTIAL) {
2061 if (bufRets.size() != mHalBufferReqs.size()) {
2062 ALOGE("%s: expect %zu buffer requests returned, only got %zu", __FUNCTION__,
2063 mHalBufferReqs.size(), bufRets.size());
2064 return false;
2065 }
2066
2067 auto parent = mParent.lock();
2068 if (parent == nullptr) {
2069 ALOGE("%s: session has been disconnected!", __FUNCTION__);
2070 return false;
2071 }
2072
2073 std::vector<int> importedFences;
2074 importedFences.resize(bufRets.size());
2075 for (size_t i = 0; i < bufRets.size(); i++) {
2076 int streamId = bufRets[i].streamId;
2077 switch (bufRets[i].val.getTag()) {
2078 case StreamBuffersVal::Tag::error:
2079 continue;
2080 case StreamBuffersVal::Tag::buffers: {
2081 const std::vector<StreamBuffer>& hBufs =
2082 bufRets[i].val.get<StreamBuffersVal::Tag::buffers>();
2083 if (hBufs.size() != 1) {
2084 ALOGE("%s: expect 1 buffer returned, got %zu!", __FUNCTION__, hBufs.size());
2085 return false;
2086 }
2087 const StreamBuffer& hBuf = hBufs[0];
2088
2089 mBufferReqs[i].bufferId = hBuf.bufferId;
2090 // TODO: create a batch import API so we don't need to lock/unlock mCbsLock
2091 // repeatedly?
2092 lk.unlock();
2093 Status s =
2094 parent->importBuffer(streamId, hBuf.bufferId, makeFromAidl(hBuf.buffer),
2095 /*out*/ &mBufferReqs[i].bufPtr);
2096 lk.lock();
2097
2098 if (s != Status::OK) {
2099 ALOGE("%s: stream %d import buffer failed!", __FUNCTION__, streamId);
2100 cleanupInflightFences(importedFences, i - 1);
2101 return false;
2102 }
2103 if (!sHandleImporter.importFence(makeFromAidl(hBuf.acquireFence),
2104 mBufferReqs[i].acquireFence)) {
2105 ALOGE("%s: stream %d import fence failed!", __FUNCTION__, streamId);
2106 cleanupInflightFences(importedFences, i - 1);
2107 return false;
2108 }
2109 importedFences[i] = mBufferReqs[i].acquireFence;
2110 } break;
2111 default:
2112 ALOGE("%s: Unknown StreamBuffersVal!", __FUNCTION__);
2113 return false;
2114 }
2115 }
2116 } else {
2117 ALOGE("%s: requestStreamBuffers call failed!", __FUNCTION__);
2118 }
2119
2120 mPendingReturnBufferReqs = std::move(mBufferReqs);
2121 mBufferReqs.clear();
2122
2123 lk.unlock();
2124 mRequestDoneCond.notify_one();
2125 return true;
2126}
2127
2128// End ExternalCameraDeviceSession::BufferRequestThread functions
2129
2130// Start ExternalCameraDeviceSession::OutputThread functions
2131
2132ExternalCameraDeviceSession::OutputThread::OutputThread(
2133 std::weak_ptr<OutputThreadInterface> parent, CroppingType ct,
2134 const common::V1_0::helper::CameraMetadata& chars,
2135 std::shared_ptr<BufferRequestThread> bufReqThread)
2136 : mParent(parent),
2137 mCroppingType(ct),
2138 mCameraCharacteristics(chars),
2139 mBufferRequestThread(bufReqThread) {}
2140
2141ExternalCameraDeviceSession::OutputThread::~OutputThread() {}
2142
2143Status ExternalCameraDeviceSession::OutputThread::allocateIntermediateBuffers(
2144 const Size& v4lSize, const Size& thumbSize, const std::vector<Stream>& streams,
2145 uint32_t blobBufferSize) {
2146 std::lock_guard<std::mutex> lk(mBufferLock);
2147 if (!mScaledYu12Frames.empty()) {
2148 ALOGE("%s: intermediate buffer pool has %zu inflight buffers! (expect 0)", __FUNCTION__,
2149 mScaledYu12Frames.size());
2150 return Status::INTERNAL_ERROR;
2151 }
2152
2153 // Allocating intermediate YU12 frame
2154 if (mYu12Frame == nullptr || mYu12Frame->mWidth != v4lSize.width ||
2155 mYu12Frame->mHeight != v4lSize.height) {
2156 mYu12Frame.reset();
2157 mYu12Frame = std::make_shared<AllocatedFrame>(v4lSize.width, v4lSize.height);
2158 int ret = mYu12Frame->allocate(&mYu12FrameLayout);
2159 if (ret != 0) {
2160 ALOGE("%s: allocating YU12 frame failed!", __FUNCTION__);
2161 return Status::INTERNAL_ERROR;
2162 }
2163 }
2164
2165 // Allocating intermediate YU12 thumbnail frame
2166 if (mYu12ThumbFrame == nullptr || mYu12ThumbFrame->mWidth != thumbSize.width ||
2167 mYu12ThumbFrame->mHeight != thumbSize.height) {
2168 mYu12ThumbFrame.reset();
2169 mYu12ThumbFrame = std::make_shared<AllocatedFrame>(thumbSize.width, thumbSize.height);
2170 int ret = mYu12ThumbFrame->allocate(&mYu12ThumbFrameLayout);
2171 if (ret != 0) {
2172 ALOGE("%s: allocating YU12 thumb frame failed!", __FUNCTION__);
2173 return Status::INTERNAL_ERROR;
2174 }
2175 }
2176
2177 // Allocating scaled buffers
2178 for (const auto& stream : streams) {
2179 Size sz = {stream.width, stream.height};
2180 if (sz == v4lSize) {
2181 continue; // Don't need an intermediate buffer same size as v4lBuffer
2182 }
2183 if (mIntermediateBuffers.count(sz) == 0) {
2184 // Create new intermediate buffer
2185 std::shared_ptr<AllocatedFrame> buf =
2186 std::make_shared<AllocatedFrame>(stream.width, stream.height);
2187 int ret = buf->allocate();
2188 if (ret != 0) {
2189 ALOGE("%s: allocating intermediate YU12 frame %dx%d failed!", __FUNCTION__,
2190 stream.width, stream.height);
2191 return Status::INTERNAL_ERROR;
2192 }
2193 mIntermediateBuffers[sz] = buf;
2194 }
2195 }
2196
2197 // Remove unconfigured buffers
2198 auto it = mIntermediateBuffers.begin();
2199 while (it != mIntermediateBuffers.end()) {
2200 bool configured = false;
2201 auto sz = it->first;
2202 for (const auto& stream : streams) {
2203 if (stream.width == sz.width && stream.height == sz.height) {
2204 configured = true;
2205 break;
2206 }
2207 }
2208 if (configured) {
2209 it++;
2210 } else {
2211 it = mIntermediateBuffers.erase(it);
2212 }
2213 }
2214
2215 // Allocate mute test pattern frame
2216 mMuteTestPatternFrame.resize(mYu12Frame->mWidth * mYu12Frame->mHeight * 3);
2217
2218 mBlobBufferSize = blobBufferSize;
2219 return Status::OK;
2220}
2221
2222Status ExternalCameraDeviceSession::OutputThread::submitRequest(
2223 const std::shared_ptr<HalRequest>& req) {
2224 std::unique_lock<std::mutex> lk(mRequestListLock);
2225 mRequestList.push_back(req);
2226 lk.unlock();
2227 mRequestCond.notify_one();
2228 return Status::OK;
2229}
2230
2231void ExternalCameraDeviceSession::OutputThread::flush() {
2232 ATRACE_CALL();
2233 auto parent = mParent.lock();
2234 if (parent == nullptr) {
2235 ALOGE("%s: session has been disconnected!", __FUNCTION__);
2236 return;
2237 }
2238
2239 std::unique_lock<std::mutex> lk(mRequestListLock);
2240 std::list<std::shared_ptr<HalRequest>> reqs = std::move(mRequestList);
2241 mRequestList.clear();
2242 if (mProcessingRequest) {
2243 auto timeout = std::chrono::seconds(kFlushWaitTimeoutSec);
2244 auto st = mRequestDoneCond.wait_for(lk, timeout);
2245 if (st == std::cv_status::timeout) {
2246 ALOGE("%s: wait for inflight request finish timeout!", __FUNCTION__);
2247 }
2248 }
2249
2250 ALOGV("%s: flushing inflight requests", __FUNCTION__);
2251 lk.unlock();
2252 for (const auto& req : reqs) {
2253 parent->processCaptureRequestError(req);
2254 }
2255}
2256
2257void ExternalCameraDeviceSession::OutputThread::dump(int fd) {
2258 std::lock_guard<std::mutex> lk(mRequestListLock);
2259 if (mProcessingRequest) {
2260 dprintf(fd, "OutputThread processing frame %d\n", mProcessingFrameNumber);
2261 } else {
2262 dprintf(fd, "OutputThread not processing any frames\n");
2263 }
2264 dprintf(fd, "OutputThread request list contains frame: ");
2265 for (const auto& req : mRequestList) {
2266 dprintf(fd, "%d, ", req->frameNumber);
2267 }
2268 dprintf(fd, "\n");
2269}
2270
2271void ExternalCameraDeviceSession::OutputThread::setExifMakeModel(const std::string& make,
2272 const std::string& model) {
2273 mExifMake = make;
2274 mExifModel = model;
2275}
2276
2277std::list<std::shared_ptr<HalRequest>>
2278ExternalCameraDeviceSession::OutputThread::switchToOffline() {
2279 ATRACE_CALL();
2280 auto parent = mParent.lock();
2281 if (parent == nullptr) {
2282 ALOGE("%s: session has been disconnected!", __FUNCTION__);
2283 return {};
2284 }
2285
2286 std::unique_lock<std::mutex> lk(mRequestListLock);
2287 std::list<std::shared_ptr<HalRequest>> reqs = std::move(mRequestList);
2288 mRequestList.clear();
2289 if (mProcessingRequest) {
2290 auto timeout = std::chrono::seconds(kFlushWaitTimeoutSec);
2291 auto st = mRequestDoneCond.wait_for(lk, timeout);
2292 if (st == std::cv_status::timeout) {
2293 ALOGE("%s: wait for inflight request finish timeout!", __FUNCTION__);
2294 }
2295 }
2296 lk.unlock();
2297 clearIntermediateBuffers();
2298 ALOGV("%s: returning %zu request for offline processing", __FUNCTION__, reqs.size());
2299 return reqs;
2300}
2301
2302int ExternalCameraDeviceSession::OutputThread::requestBufferStart(
2303 const std::vector<HalStreamBuffer>& bufs) {
2304 if (mBufferRequestThread == nullptr) {
2305 return 0;
2306 }
2307 return mBufferRequestThread->requestBufferStart(bufs);
2308}
2309
2310int ExternalCameraDeviceSession::OutputThread::waitForBufferRequestDone(
2311 std::vector<HalStreamBuffer>* outBufs) {
2312 if (mBufferRequestThread == nullptr) {
2313 return 0;
2314 }
2315 return mBufferRequestThread->waitForBufferRequestDone(outBufs);
2316}
2317
2318void ExternalCameraDeviceSession::OutputThread::waitForNextRequest(
2319 std::shared_ptr<HalRequest>* out) {
2320 ATRACE_CALL();
2321 if (out == nullptr) {
2322 ALOGE("%s: out is null", __FUNCTION__);
2323 return;
2324 }
2325
2326 std::unique_lock<std::mutex> lk(mRequestListLock);
2327 int waitTimes = 0;
2328 while (mRequestList.empty()) {
2329 if (exitPending()) {
2330 return;
2331 }
2332 auto timeout = std::chrono::milliseconds(kReqWaitTimeoutMs);
2333 auto st = mRequestCond.wait_for(lk, timeout);
2334 if (st == std::cv_status::timeout) {
2335 waitTimes++;
2336 if (waitTimes == kReqWaitTimesMax) {
2337 // no new request, return
2338 return;
2339 }
2340 }
2341 }
2342 *out = mRequestList.front();
2343 mRequestList.pop_front();
2344 mProcessingRequest = true;
2345 mProcessingFrameNumber = (*out)->frameNumber;
2346}
2347
2348void ExternalCameraDeviceSession::OutputThread::signalRequestDone() {
2349 std::unique_lock<std::mutex> lk(mRequestListLock);
2350 mProcessingRequest = false;
2351 mProcessingFrameNumber = 0;
2352 lk.unlock();
2353 mRequestDoneCond.notify_one();
2354}
2355
2356int ExternalCameraDeviceSession::OutputThread::cropAndScaleLocked(
2357 std::shared_ptr<AllocatedFrame>& in, const Size& outSz, YCbCrLayout* out) {
2358 Size inSz = {in->mWidth, in->mHeight};
2359
2360 int ret;
2361 if (inSz == outSz) {
2362 ret = in->getLayout(out);
2363 if (ret != 0) {
2364 ALOGE("%s: failed to get input image layout", __FUNCTION__);
2365 return ret;
2366 }
2367 return ret;
2368 }
2369
2370 // Cropping to output aspect ratio
2371 IMapper::Rect inputCrop;
2372 ret = getCropRect(mCroppingType, inSz, outSz, &inputCrop);
2373 if (ret != 0) {
2374 ALOGE("%s: failed to compute crop rect for output size %dx%d", __FUNCTION__, outSz.width,
2375 outSz.height);
2376 return ret;
2377 }
2378
2379 YCbCrLayout croppedLayout;
2380 ret = in->getCroppedLayout(inputCrop, &croppedLayout);
2381 if (ret != 0) {
2382 ALOGE("%s: failed to crop input image %dx%d to output size %dx%d", __FUNCTION__, inSz.width,
2383 inSz.height, outSz.width, outSz.height);
2384 return ret;
2385 }
2386
2387 if ((mCroppingType == VERTICAL && inSz.width == outSz.width) ||
2388 (mCroppingType == HORIZONTAL && inSz.height == outSz.height)) {
2389 // No scale is needed
2390 *out = croppedLayout;
2391 return 0;
2392 }
2393
2394 auto it = mScaledYu12Frames.find(outSz);
2395 std::shared_ptr<AllocatedFrame> scaledYu12Buf;
2396 if (it != mScaledYu12Frames.end()) {
2397 scaledYu12Buf = it->second;
2398 } else {
2399 it = mIntermediateBuffers.find(outSz);
2400 if (it == mIntermediateBuffers.end()) {
2401 ALOGE("%s: failed to find intermediate buffer size %dx%d", __FUNCTION__, outSz.width,
2402 outSz.height);
2403 return -1;
2404 }
2405 scaledYu12Buf = it->second;
2406 }
2407 // Scale
2408 YCbCrLayout outLayout;
2409 ret = scaledYu12Buf->getLayout(&outLayout);
2410 if (ret != 0) {
2411 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
2412 return ret;
2413 }
2414
2415 ret = libyuv::I420Scale(
2416 static_cast<uint8_t*>(croppedLayout.y), croppedLayout.yStride,
2417 static_cast<uint8_t*>(croppedLayout.cb), croppedLayout.cStride,
2418 static_cast<uint8_t*>(croppedLayout.cr), croppedLayout.cStride, inputCrop.width,
2419 inputCrop.height, static_cast<uint8_t*>(outLayout.y), outLayout.yStride,
2420 static_cast<uint8_t*>(outLayout.cb), outLayout.cStride,
2421 static_cast<uint8_t*>(outLayout.cr), outLayout.cStride, outSz.width, outSz.height,
2422 // TODO: b/72261744 see if we can use better filter without losing too much perf
2423 libyuv::FilterMode::kFilterNone);
2424
2425 if (ret != 0) {
2426 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d", __FUNCTION__,
2427 inputCrop.width, inputCrop.height, outSz.width, outSz.height, ret);
2428 return ret;
2429 }
2430
2431 *out = outLayout;
2432 mScaledYu12Frames.insert({outSz, scaledYu12Buf});
2433 return 0;
2434}
2435
2436int ExternalCameraDeviceSession::OutputThread::cropAndScaleThumbLocked(
2437 std::shared_ptr<AllocatedFrame>& in, const Size& outSz, YCbCrLayout* out) {
2438 Size inSz{in->mWidth, in->mHeight};
2439
2440 if ((outSz.width * outSz.height) > (mYu12ThumbFrame->mWidth * mYu12ThumbFrame->mHeight)) {
2441 ALOGE("%s: Requested thumbnail size too big (%d,%d) > (%d,%d)", __FUNCTION__, outSz.width,
2442 outSz.height, mYu12ThumbFrame->mWidth, mYu12ThumbFrame->mHeight);
2443 return -1;
2444 }
2445
2446 int ret;
2447
2448 /* This will crop-and-zoom the input YUV frame to the thumbnail size
2449 * Based on the following logic:
2450 * 1) Square pixels come in, square pixels come out, therefore single
2451 * scale factor is computed to either make input bigger or smaller
2452 * depending on if we are upscaling or downscaling
2453 * 2) That single scale factor would either make height too tall or width
2454 * too wide so we need to crop the input either horizontally or vertically
2455 * but not both
2456 */
2457
2458 /* Convert the input and output dimensions into floats for ease of math */
2459 float fWin = static_cast<float>(inSz.width);
2460 float fHin = static_cast<float>(inSz.height);
2461 float fWout = static_cast<float>(outSz.width);
2462 float fHout = static_cast<float>(outSz.height);
2463
2464 /* Compute the one scale factor from (1) above, it will be the smaller of
2465 * the two possibilities. */
2466 float scaleFactor = std::min(fHin / fHout, fWin / fWout);
2467
2468 /* Since we are crop-and-zooming (as opposed to letter/pillar boxing) we can
2469 * simply multiply the output by our scaleFactor to get the cropped input
2470 * size. Note that at least one of {fWcrop, fHcrop} is going to wind up
2471 * being {fWin, fHin} respectively because fHout or fWout cancels out the
2472 * scaleFactor calculation above.
2473 *
2474 * Specifically:
2475 * if ( fHin / fHout ) < ( fWin / fWout ) we crop the sides off
2476 * input, in which case
2477 * scaleFactor = fHin / fHout
2478 * fWcrop = fHin / fHout * fWout
2479 * fHcrop = fHin
2480 *
2481 * Note that fWcrop <= fWin ( because ( fHin / fHout ) * fWout < fWin, which
2482 * is just the inequality above with both sides multiplied by fWout
2483 *
2484 * on the other hand if ( fWin / fWout ) < ( fHin / fHout) we crop the top
2485 * and the bottom off of input, and
2486 * scaleFactor = fWin / fWout
2487 * fWcrop = fWin
2488 * fHCrop = fWin / fWout * fHout
2489 */
2490 float fWcrop = scaleFactor * fWout;
2491 float fHcrop = scaleFactor * fHout;
2492
2493 /* Convert to integer and truncate to an even number */
2494 Size cropSz = {.width = 2 * static_cast<int32_t>(fWcrop / 2.0f),
2495 .height = 2 * static_cast<int32_t>(fHcrop / 2.0f)};
2496
2497 /* Convert to a centered rectange with even top/left */
2498 IMapper::Rect inputCrop{.left = 2 * static_cast<int32_t>((inSz.width - cropSz.width) / 4),
2499 .top = 2 * static_cast<int32_t>((inSz.height - cropSz.height) / 4),
2500 .width = static_cast<int32_t>(cropSz.width),
2501 .height = static_cast<int32_t>(cropSz.height)};
2502
2503 if ((inputCrop.top < 0) || (inputCrop.top >= static_cast<int32_t>(inSz.height)) ||
2504 (inputCrop.left < 0) || (inputCrop.left >= static_cast<int32_t>(inSz.width)) ||
2505 (inputCrop.width <= 0) ||
2506 (inputCrop.width + inputCrop.left > static_cast<int32_t>(inSz.width)) ||
2507 (inputCrop.height <= 0) ||
2508 (inputCrop.height + inputCrop.top > static_cast<int32_t>(inSz.height))) {
2509 ALOGE("%s: came up with really wrong crop rectangle", __FUNCTION__);
2510 ALOGE("%s: input layout %dx%d to for output size %dx%d", __FUNCTION__, inSz.width,
2511 inSz.height, outSz.width, outSz.height);
2512 ALOGE("%s: computed input crop +%d,+%d %dx%d", __FUNCTION__, inputCrop.left, inputCrop.top,
2513 inputCrop.width, inputCrop.height);
2514 return -1;
2515 }
2516
2517 YCbCrLayout inputLayout;
2518 ret = in->getCroppedLayout(inputCrop, &inputLayout);
2519 if (ret != 0) {
2520 ALOGE("%s: failed to crop input layout %dx%d to for output size %dx%d", __FUNCTION__,
2521 inSz.width, inSz.height, outSz.width, outSz.height);
2522 ALOGE("%s: computed input crop +%d,+%d %dx%d", __FUNCTION__, inputCrop.left, inputCrop.top,
2523 inputCrop.width, inputCrop.height);
2524 return ret;
2525 }
2526 ALOGV("%s: crop input layout %dx%d to for output size %dx%d", __FUNCTION__, inSz.width,
2527 inSz.height, outSz.width, outSz.height);
2528 ALOGV("%s: computed input crop +%d,+%d %dx%d", __FUNCTION__, inputCrop.left, inputCrop.top,
2529 inputCrop.width, inputCrop.height);
2530
2531 // Scale
2532 YCbCrLayout outFullLayout;
2533
2534 ret = mYu12ThumbFrame->getLayout(&outFullLayout);
2535 if (ret != 0) {
2536 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
2537 return ret;
2538 }
2539
2540 ret = libyuv::I420Scale(static_cast<uint8_t*>(inputLayout.y), inputLayout.yStride,
2541 static_cast<uint8_t*>(inputLayout.cb), inputLayout.cStride,
2542 static_cast<uint8_t*>(inputLayout.cr), inputLayout.cStride,
2543 inputCrop.width, inputCrop.height,
2544 static_cast<uint8_t*>(outFullLayout.y), outFullLayout.yStride,
2545 static_cast<uint8_t*>(outFullLayout.cb), outFullLayout.cStride,
2546 static_cast<uint8_t*>(outFullLayout.cr), outFullLayout.cStride,
2547 outSz.width, outSz.height, libyuv::FilterMode::kFilterNone);
2548
2549 if (ret != 0) {
2550 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d", __FUNCTION__,
2551 inputCrop.width, inputCrop.height, outSz.width, outSz.height, ret);
2552 return ret;
2553 }
2554
2555 *out = outFullLayout;
2556 return 0;
2557}
2558
2559int ExternalCameraDeviceSession::OutputThread::createJpegLocked(
2560 HalStreamBuffer& halBuf, const common::V1_0::helper::CameraMetadata& setting) {
2561 ATRACE_CALL();
2562 int ret;
2563 auto lfail = [&](auto... args) {
2564 ALOGE(args...);
2565
2566 return 1;
2567 };
2568 auto parent = mParent.lock();
2569 if (parent == nullptr) {
2570 ALOGE("%s: session has been disconnected!", __FUNCTION__);
2571 return 1;
2572 }
2573
2574 ALOGV("%s: HAL buffer sid: %d bid: %" PRIu64 " w: %u h: %u", __FUNCTION__, halBuf.streamId,
2575 static_cast<uint64_t>(halBuf.bufferId), halBuf.width, halBuf.height);
2576 ALOGV("%s: HAL buffer fmt: %x usage: %" PRIx64 " ptr: %p", __FUNCTION__, halBuf.format,
2577 static_cast<uint64_t>(halBuf.usage), halBuf.bufPtr);
2578 ALOGV("%s: YV12 buffer %d x %d", __FUNCTION__, mYu12Frame->mWidth, mYu12Frame->mHeight);
2579
2580 int jpegQuality, thumbQuality;
2581 Size thumbSize;
2582 bool outputThumbnail = true;
2583
2584 if (setting.exists(ANDROID_JPEG_QUALITY)) {
2585 camera_metadata_ro_entry entry = setting.find(ANDROID_JPEG_QUALITY);
2586 jpegQuality = entry.data.u8[0];
2587 } else {
2588 return lfail("%s: ANDROID_JPEG_QUALITY not set", __FUNCTION__);
2589 }
2590
2591 if (setting.exists(ANDROID_JPEG_THUMBNAIL_QUALITY)) {
2592 camera_metadata_ro_entry entry = setting.find(ANDROID_JPEG_THUMBNAIL_QUALITY);
2593 thumbQuality = entry.data.u8[0];
2594 } else {
2595 return lfail("%s: ANDROID_JPEG_THUMBNAIL_QUALITY not set", __FUNCTION__);
2596 }
2597
2598 if (setting.exists(ANDROID_JPEG_THUMBNAIL_SIZE)) {
2599 camera_metadata_ro_entry entry = setting.find(ANDROID_JPEG_THUMBNAIL_SIZE);
2600 thumbSize = Size{.width = entry.data.i32[0], .height = entry.data.i32[1]};
2601 if (thumbSize.width == 0 && thumbSize.height == 0) {
2602 outputThumbnail = false;
2603 }
2604 } else {
2605 return lfail("%s: ANDROID_JPEG_THUMBNAIL_SIZE not set", __FUNCTION__);
2606 }
2607
2608 /* Cropped and scaled YU12 buffer for main and thumbnail */
2609 YCbCrLayout yu12Main;
2610 Size jpegSize{halBuf.width, halBuf.height};
2611
2612 /* Compute temporary buffer sizes accounting for the following:
2613 * thumbnail can't exceed APP1 size of 64K
2614 * main image needs to hold APP1, headers, and at most a poorly
2615 * compressed image */
2616 const ssize_t maxThumbCodeSize = 64 * 1024;
2617 const ssize_t maxJpegCodeSize =
2618 mBlobBufferSize == 0 ? parent->getJpegBufferSize(jpegSize.width, jpegSize.height)
2619 : mBlobBufferSize;
2620
2621 /* Check that getJpegBufferSize did not return an error */
2622 if (maxJpegCodeSize < 0) {
2623 return lfail("%s: getJpegBufferSize returned %zd", __FUNCTION__, maxJpegCodeSize);
2624 }
2625
2626 /* Hold actual thumbnail and main image code sizes */
2627 size_t thumbCodeSize = 0, jpegCodeSize = 0;
2628 /* Temporary thumbnail code buffer */
2629 std::vector<uint8_t> thumbCode(outputThumbnail ? maxThumbCodeSize : 0);
2630
2631 YCbCrLayout yu12Thumb;
2632 if (outputThumbnail) {
2633 ret = cropAndScaleThumbLocked(mYu12Frame, thumbSize, &yu12Thumb);
2634
2635 if (ret != 0) {
2636 return lfail("%s: crop and scale thumbnail failed!", __FUNCTION__);
2637 }
2638 }
2639
2640 /* Scale and crop main jpeg */
2641 ret = cropAndScaleLocked(mYu12Frame, jpegSize, &yu12Main);
2642
2643 if (ret != 0) {
2644 return lfail("%s: crop and scale main failed!", __FUNCTION__);
2645 }
2646
2647 /* Encode the thumbnail image */
2648 if (outputThumbnail) {
2649 ret = encodeJpegYU12(thumbSize, yu12Thumb, thumbQuality, 0, 0, &thumbCode[0],
2650 maxThumbCodeSize, thumbCodeSize);
2651
2652 if (ret != 0) {
2653 return lfail("%s: thumbnail encodeJpegYU12 failed with %d", __FUNCTION__, ret);
2654 }
2655 }
2656
2657 /* Combine camera characteristics with request settings to form EXIF
2658 * metadata */
2659 common::V1_0::helper::CameraMetadata meta(mCameraCharacteristics);
2660 meta.append(setting);
2661
2662 /* Generate EXIF object */
2663 std::unique_ptr<ExifUtils> utils(ExifUtils::create());
2664 /* Make sure it's initialized */
2665 utils->initialize();
2666
2667 utils->setFromMetadata(meta, jpegSize.width, jpegSize.height);
2668 utils->setMake(mExifMake);
2669 utils->setModel(mExifModel);
2670
2671 ret = utils->generateApp1(outputThumbnail ? &thumbCode[0] : nullptr, thumbCodeSize);
2672
2673 if (!ret) {
2674 return lfail("%s: generating APP1 failed", __FUNCTION__);
2675 }
2676
2677 /* Get internal buffer */
2678 size_t exifDataSize = utils->getApp1Length();
2679 const uint8_t* exifData = utils->getApp1Buffer();
2680
2681 /* Lock the HAL jpeg code buffer */
2682 void* bufPtr = sHandleImporter.lock(*(halBuf.bufPtr), static_cast<uint64_t>(halBuf.usage),
2683 maxJpegCodeSize);
2684
2685 if (!bufPtr) {
2686 return lfail("%s: could not lock %zu bytes", __FUNCTION__, maxJpegCodeSize);
2687 }
2688
2689 /* Encode the main jpeg image */
2690 ret = encodeJpegYU12(jpegSize, yu12Main, jpegQuality, exifData, exifDataSize, bufPtr,
2691 maxJpegCodeSize, jpegCodeSize);
2692
2693 /* TODO: Not sure this belongs here, maybe better to pass jpegCodeSize out
2694 * and do this when returning buffer to parent */
2695 CameraBlob blob{CameraBlobId::JPEG, static_cast<int32_t>(jpegCodeSize)};
2696 void* blobDst = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(bufPtr) + maxJpegCodeSize -
2697 sizeof(CameraBlob));
2698 memcpy(blobDst, &blob, sizeof(CameraBlob));
2699
2700 /* Unlock the HAL jpeg code buffer */
2701 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
2702 if (relFence >= 0) {
2703 halBuf.acquireFence = relFence;
2704 }
2705
2706 /* Check if our JPEG actually succeeded */
2707 if (ret != 0) {
2708 return lfail("%s: encodeJpegYU12 failed with %d", __FUNCTION__, ret);
2709 }
2710
2711 ALOGV("%s: encoded JPEG (ret:%d) with Q:%d max size: %zu", __FUNCTION__, ret, jpegQuality,
2712 maxJpegCodeSize);
2713
2714 return 0;
2715}
2716
2717void ExternalCameraDeviceSession::OutputThread::clearIntermediateBuffers() {
2718 std::lock_guard<std::mutex> lk(mBufferLock);
2719 mYu12Frame.reset();
2720 mYu12ThumbFrame.reset();
2721 mIntermediateBuffers.clear();
2722 mMuteTestPatternFrame.clear();
2723 mBlobBufferSize = 0;
2724}
2725
2726bool ExternalCameraDeviceSession::OutputThread::threadLoop() {
2727 std::shared_ptr<HalRequest> req;
2728 auto parent = mParent.lock();
2729 if (parent == nullptr) {
2730 ALOGE("%s: session has been disconnected!", __FUNCTION__);
2731 return false;
2732 }
2733
2734 // TODO: maybe we need to setup a sensor thread to dq/enq v4l frames
2735 // regularly to prevent v4l buffer queue filled with stale buffers
2736 // when app doesn't program a preview request
2737 waitForNextRequest(&req);
2738 if (req == nullptr) {
2739 // No new request, wait again
2740 return true;
2741 }
2742
2743 auto onDeviceError = [&](auto... args) {
2744 ALOGE(args...);
2745 parent->notifyError(req->frameNumber, /*stream*/ -1, ErrorCode::ERROR_DEVICE);
2746 signalRequestDone();
2747 return false;
2748 };
2749
2750 if (req->frameIn->mFourcc != V4L2_PIX_FMT_MJPEG && req->frameIn->mFourcc != V4L2_PIX_FMT_Z16) {
2751 return onDeviceError("%s: do not support V4L2 format %c%c%c%c", __FUNCTION__,
2752 req->frameIn->mFourcc & 0xFF, (req->frameIn->mFourcc >> 8) & 0xFF,
2753 (req->frameIn->mFourcc >> 16) & 0xFF,
2754 (req->frameIn->mFourcc >> 24) & 0xFF);
2755 }
2756
2757 int res = requestBufferStart(req->buffers);
2758 if (res != 0) {
2759 ALOGE("%s: send BufferRequest failed! res %d", __FUNCTION__, res);
2760 return onDeviceError("%s: failed to send buffer request!", __FUNCTION__);
2761 }
2762
2763 std::unique_lock<std::mutex> lk(mBufferLock);
2764 // Convert input V4L2 frame to YU12 of the same size
2765 // TODO: see if we can save some computation by converting to YV12 here
2766 uint8_t* inData;
2767 size_t inDataSize;
2768 if (req->frameIn->getData(&inData, &inDataSize) != 0) {
2769 lk.unlock();
2770 return onDeviceError("%s: V4L2 buffer map failed", __FUNCTION__);
2771 }
2772
2773 // Process camera mute state
2774 auto testPatternMode = req->setting.find(ANDROID_SENSOR_TEST_PATTERN_MODE);
2775 if (testPatternMode.count == 1) {
2776 if (mCameraMuted != (testPatternMode.data.u8[0] != ANDROID_SENSOR_TEST_PATTERN_MODE_OFF)) {
2777 mCameraMuted = !mCameraMuted;
2778 // Get solid color for test pattern, if any was set
2779 if (testPatternMode.data.u8[0] == ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
2780 auto entry = req->setting.find(ANDROID_SENSOR_TEST_PATTERN_DATA);
2781 if (entry.count == 4) {
2782 // Update the mute frame if the pattern color has changed
2783 if (memcmp(entry.data.i32, mTestPatternData, sizeof(mTestPatternData)) != 0) {
2784 memcpy(mTestPatternData, entry.data.i32, sizeof(mTestPatternData));
2785 // Fill the mute frame with the solid color, use only 8 MSB of RGGB as RGB
2786 for (int i = 0; i < mMuteTestPatternFrame.size(); i += 3) {
2787 mMuteTestPatternFrame[i] = entry.data.i32[0] >> 24;
2788 mMuteTestPatternFrame[i + 1] = entry.data.i32[1] >> 24;
2789 mMuteTestPatternFrame[i + 2] = entry.data.i32[3] >> 24;
2790 }
2791 }
2792 }
2793 }
2794 }
2795 }
2796
2797 // TODO: in some special case maybe we can decode jpg directly to gralloc output?
2798 if (req->frameIn->mFourcc == V4L2_PIX_FMT_MJPEG) {
2799 ATRACE_BEGIN("MJPGtoI420");
2800 res = 0;
2801 if (mCameraMuted) {
2802 res = libyuv::ConvertToI420(
2803 mMuteTestPatternFrame.data(), mMuteTestPatternFrame.size(),
2804 static_cast<uint8_t*>(mYu12FrameLayout.y), mYu12FrameLayout.yStride,
2805 static_cast<uint8_t*>(mYu12FrameLayout.cb), mYu12FrameLayout.cStride,
2806 static_cast<uint8_t*>(mYu12FrameLayout.cr), mYu12FrameLayout.cStride, 0, 0,
2807 mYu12Frame->mWidth, mYu12Frame->mHeight, mYu12Frame->mWidth,
2808 mYu12Frame->mHeight, libyuv::kRotate0, libyuv::FOURCC_RAW);
2809 } else {
2810 res = libyuv::MJPGToI420(
2811 inData, inDataSize, static_cast<uint8_t*>(mYu12FrameLayout.y),
2812 mYu12FrameLayout.yStride, static_cast<uint8_t*>(mYu12FrameLayout.cb),
2813 mYu12FrameLayout.cStride, static_cast<uint8_t*>(mYu12FrameLayout.cr),
2814 mYu12FrameLayout.cStride, mYu12Frame->mWidth, mYu12Frame->mHeight,
2815 mYu12Frame->mWidth, mYu12Frame->mHeight);
2816 }
2817 ATRACE_END();
2818
2819 if (res != 0) {
2820 // For some webcam, the first few V4L2 frames might be malformed...
2821 ALOGE("%s: Convert V4L2 frame to YU12 failed! res %d", __FUNCTION__, res);
2822 lk.unlock();
2823 Status st = parent->processCaptureRequestError(req);
2824 if (st != Status::OK) {
2825 return onDeviceError("%s: failed to process capture request error!", __FUNCTION__);
2826 }
2827 signalRequestDone();
2828 return true;
2829 }
2830 }
2831
2832 ATRACE_BEGIN("Wait for BufferRequest done");
2833 res = waitForBufferRequestDone(&req->buffers);
2834 ATRACE_END();
2835
2836 if (res != 0) {
2837 ALOGE("%s: wait for BufferRequest done failed! res %d", __FUNCTION__, res);
2838 lk.unlock();
2839 return onDeviceError("%s: failed to process buffer request error!", __FUNCTION__);
2840 }
2841
2842 ALOGV("%s processing new request", __FUNCTION__);
2843 const int kSyncWaitTimeoutMs = 500;
2844 for (auto& halBuf : req->buffers) {
2845 if (*(halBuf.bufPtr) == nullptr) {
2846 ALOGW("%s: buffer for stream %d missing", __FUNCTION__, halBuf.streamId);
2847 halBuf.fenceTimeout = true;
2848 } else if (halBuf.acquireFence >= 0) {
2849 int ret = sync_wait(halBuf.acquireFence, kSyncWaitTimeoutMs);
2850 if (ret) {
2851 halBuf.fenceTimeout = true;
2852 } else {
2853 ::close(halBuf.acquireFence);
2854 halBuf.acquireFence = -1;
2855 }
2856 }
2857
2858 if (halBuf.fenceTimeout) {
2859 continue;
2860 }
2861
2862 // Gralloc lockYCbCr the buffer
2863 switch (halBuf.format) {
2864 case PixelFormat::BLOB: {
2865 int ret = createJpegLocked(halBuf, req->setting);
2866
2867 if (ret != 0) {
2868 lk.unlock();
2869 return onDeviceError("%s: createJpegLocked failed with %d", __FUNCTION__, ret);
2870 }
2871 } break;
2872 case PixelFormat::Y16: {
2873 void* outLayout = sHandleImporter.lock(
2874 *(halBuf.bufPtr), static_cast<uint64_t>(halBuf.usage), inDataSize);
2875
2876 std::memcpy(outLayout, inData, inDataSize);
2877
2878 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
2879 if (relFence >= 0) {
2880 halBuf.acquireFence = relFence;
2881 }
2882 } break;
2883 case PixelFormat::YCBCR_420_888:
2884 case PixelFormat::YV12: {
Devin Moore5e154092023-09-13 16:18:30 +00002885 android::Rect outRect{0, 0, static_cast<int32_t>(halBuf.width),
Avichal Rakeshe1857f82022-06-08 17:47:23 -07002886 static_cast<int32_t>(halBuf.height)};
Devin Moore5e154092023-09-13 16:18:30 +00002887 android_ycbcr result = sHandleImporter.lockYCbCr(
Avichal Rakeshe1857f82022-06-08 17:47:23 -07002888 *(halBuf.bufPtr), static_cast<uint64_t>(halBuf.usage), outRect);
Devin Moore5e154092023-09-13 16:18:30 +00002889 ALOGV("%s: outLayout y %p cb %p cr %p y_str %zu c_str %zu c_step %zu", __FUNCTION__,
2890 result.y, result.cb, result.cr, result.ystride, result.cstride,
2891 result.chroma_step);
2892 if (result.ystride > UINT32_MAX || result.cstride > UINT32_MAX ||
2893 result.chroma_step > UINT32_MAX) {
2894 return onDeviceError("%s: lockYCbCr failed. Unexpected values!", __FUNCTION__);
2895 }
2896 YCbCrLayout outLayout = {.y = result.y,
2897 .cb = result.cb,
2898 .cr = result.cr,
2899 .yStride = static_cast<uint32_t>(result.ystride),
2900 .cStride = static_cast<uint32_t>(result.cstride),
2901 .chromaStep = static_cast<uint32_t>(result.chroma_step)};
Avichal Rakeshe1857f82022-06-08 17:47:23 -07002902
2903 // Convert to output buffer size/format
2904 uint32_t outputFourcc = getFourCcFromLayout(outLayout);
2905 ALOGV("%s: converting to format %c%c%c%c", __FUNCTION__, outputFourcc & 0xFF,
2906 (outputFourcc >> 8) & 0xFF, (outputFourcc >> 16) & 0xFF,
2907 (outputFourcc >> 24) & 0xFF);
2908
2909 YCbCrLayout cropAndScaled;
2910 ATRACE_BEGIN("cropAndScaleLocked");
2911 int ret = cropAndScaleLocked(mYu12Frame, Size{halBuf.width, halBuf.height},
2912 &cropAndScaled);
2913 ATRACE_END();
2914 if (ret != 0) {
2915 lk.unlock();
2916 return onDeviceError("%s: crop and scale failed!", __FUNCTION__);
2917 }
2918
2919 Size sz{halBuf.width, halBuf.height};
2920 ATRACE_BEGIN("formatConvert");
2921 ret = formatConvert(cropAndScaled, outLayout, sz, outputFourcc);
2922 ATRACE_END();
2923 if (ret != 0) {
2924 lk.unlock();
2925 return onDeviceError("%s: format conversion failed!", __FUNCTION__);
2926 }
2927 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
2928 if (relFence >= 0) {
2929 halBuf.acquireFence = relFence;
2930 }
2931 } break;
2932 default:
2933 lk.unlock();
2934 return onDeviceError("%s: unknown output format %x", __FUNCTION__, halBuf.format);
2935 }
2936 } // for each buffer
2937 mScaledYu12Frames.clear();
2938
2939 // Don't hold the lock while calling back to parent
2940 lk.unlock();
2941 Status st = parent->processCaptureResult(req);
2942 if (st != Status::OK) {
2943 return onDeviceError("%s: failed to process capture result!", __FUNCTION__);
2944 }
2945 signalRequestDone();
2946 return true;
2947}
2948
2949// End ExternalCameraDeviceSession::OutputThread functions
2950
2951} // namespace implementation
2952} // namespace device
2953} // namespace camera
2954} // namespace hardware
2955} // namespace android