blob: c9629744c2fe2359d70779eb46eba8ad03a4276c [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() {
227 closeOutputThreadImpl();
228}
229
230void ExternalCameraDeviceSession::closeOutputThreadImpl() {
231 if (mOutputThread != nullptr) {
232 mOutputThread->flush();
233 mOutputThread->requestExitAndWait();
234 mOutputThread.reset();
235 }
236}
237
238Status ExternalCameraDeviceSession::initStatus() const {
239 Mutex::Autolock _l(mLock);
240 Status status = Status::OK;
241 if (mInitFail || mClosed) {
242 ALOGI("%s: session initFailed %d closed %d", __FUNCTION__, mInitFail, mClosed);
243 status = Status::INTERNAL_ERROR;
244 }
245 return status;
246}
247
248ExternalCameraDeviceSession::~ExternalCameraDeviceSession() {
249 if (!isClosed()) {
250 ALOGE("ExternalCameraDeviceSession deleted before close!");
251 close(/*callerIsDtor*/ true);
252 }
253}
254
255ScopedAStatus ExternalCameraDeviceSession::constructDefaultRequestSettings(
256 RequestTemplate in_type, CameraMetadata* _aidl_return) {
257 CameraMetadata emptyMetadata;
258 Status status = initStatus();
259 if (status != Status::OK) {
260 return fromStatus(status);
261 }
262 switch (in_type) {
263 case RequestTemplate::PREVIEW:
264 case RequestTemplate::STILL_CAPTURE:
265 case RequestTemplate::VIDEO_RECORD:
266 case RequestTemplate::VIDEO_SNAPSHOT: {
267 *_aidl_return = mDefaultRequests[in_type];
268 break;
269 }
270 case RequestTemplate::MANUAL:
271 case RequestTemplate::ZERO_SHUTTER_LAG:
272 // Don't support MANUAL, ZSL templates
273 status = Status::ILLEGAL_ARGUMENT;
274 break;
275 default:
276 ALOGE("%s: unknown request template type %d", __FUNCTION__, static_cast<int>(in_type));
277 status = Status::ILLEGAL_ARGUMENT;
278 break;
279 }
280 return fromStatus(status);
281}
282
283ScopedAStatus ExternalCameraDeviceSession::configureStreams(
284 const StreamConfiguration& in_requestedConfiguration,
285 std::vector<HalStream>* _aidl_return) {
286 uint32_t blobBufferSize = 0;
287 _aidl_return->clear();
288 Mutex::Autolock _il(mInterfaceLock);
289
290 Status status =
291 isStreamCombinationSupported(in_requestedConfiguration, mSupportedFormats, mCfg);
292 if (status != Status::OK) {
293 return fromStatus(status);
294 }
295
296 status = initStatus();
297 if (status != Status::OK) {
298 return fromStatus(status);
299 }
300
301 {
302 std::lock_guard<std::mutex> lk(mInflightFramesLock);
303 if (!mInflightFrames.empty()) {
304 ALOGE("%s: trying to configureStreams while there are still %zu inflight frames!",
305 __FUNCTION__, mInflightFrames.size());
306 return fromStatus(Status::INTERNAL_ERROR);
307 }
308 }
309
310 Mutex::Autolock _l(mLock);
311 {
312 Mutex::Autolock _cl(mCbsLock);
313 // Add new streams
314 for (const auto& stream : in_requestedConfiguration.streams) {
315 if (mStreamMap.count(stream.id) == 0) {
316 mStreamMap[stream.id] = stream;
317 mCirculatingBuffers.emplace(stream.id, CirculatingBuffers{});
318 }
319 }
320
321 // Cleanup removed streams
322 for (auto it = mStreamMap.begin(); it != mStreamMap.end();) {
323 int id = it->first;
324 bool found = false;
325 for (const auto& stream : in_requestedConfiguration.streams) {
326 if (id == stream.id) {
327 found = true;
328 break;
329 }
330 }
331 if (!found) {
332 // Unmap all buffers of deleted stream
333 cleanupBuffersLocked(id);
334 it = mStreamMap.erase(it);
335 } else {
336 ++it;
337 }
338 }
339 }
340
341 // Now select a V4L2 format to produce all output streams
342 float desiredAr = (mCroppingType == VERTICAL) ? kMaxAspectRatio : kMinAspectRatio;
343 uint32_t maxDim = 0;
344 for (const auto& stream : in_requestedConfiguration.streams) {
345 float aspectRatio = ASPECT_RATIO(stream);
346 ALOGI("%s: request stream %dx%d", __FUNCTION__, stream.width, stream.height);
347 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
348 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
349 desiredAr = aspectRatio;
350 }
351
352 // The dimension that's not cropped
353 uint32_t dim = (mCroppingType == VERTICAL) ? stream.width : stream.height;
354 if (dim > maxDim) {
355 maxDim = dim;
356 }
357 }
358
359 // Find the smallest format that matches the desired aspect ratio and is wide/high enough
360 SupportedV4L2Format v4l2Fmt{.width = 0, .height = 0};
361 for (const auto& fmt : mSupportedFormats) {
362 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
363 if (dim >= maxDim) {
364 float aspectRatio = ASPECT_RATIO(fmt);
365 if (isAspectRatioClose(aspectRatio, desiredAr)) {
366 v4l2Fmt = fmt;
367 // since mSupportedFormats is sorted by width then height, the first matching fmt
368 // will be the smallest one with matching aspect ratio
369 break;
370 }
371 }
372 }
373
374 if (v4l2Fmt.width == 0) {
375 // Cannot find exact good aspect ratio candidate, try to find a close one
376 for (const auto& fmt : mSupportedFormats) {
377 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
378 if (dim >= maxDim) {
379 float aspectRatio = ASPECT_RATIO(fmt);
380 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
381 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
382 v4l2Fmt = fmt;
383 break;
384 }
385 }
386 }
387 }
388
389 if (v4l2Fmt.width == 0) {
390 ALOGE("%s: unable to find a resolution matching (%s at least %d, aspect ratio %f)",
391 __FUNCTION__, (mCroppingType == VERTICAL) ? "width" : "height", maxDim, desiredAr);
392 return fromStatus(Status::ILLEGAL_ARGUMENT);
393 }
394
395 if (configureV4l2StreamLocked(v4l2Fmt) != 0) {
396 ALOGE("V4L configuration failed!, format:%c%c%c%c, w %d, h %d", v4l2Fmt.fourcc & 0xFF,
397 (v4l2Fmt.fourcc >> 8) & 0xFF, (v4l2Fmt.fourcc >> 16) & 0xFF,
398 (v4l2Fmt.fourcc >> 24) & 0xFF, v4l2Fmt.width, v4l2Fmt.height);
399 return fromStatus(Status::INTERNAL_ERROR);
400 }
401
402 Size v4lSize = {v4l2Fmt.width, v4l2Fmt.height};
403 Size thumbSize{0, 0};
404 camera_metadata_ro_entry entry =
405 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
406 for (uint32_t i = 0; i < entry.count; i += 2) {
407 Size sz{entry.data.i32[i], entry.data.i32[i + 1]};
408 if (sz.width * sz.height > thumbSize.width * thumbSize.height) {
409 thumbSize = sz;
410 }
411 }
412
413 if (thumbSize.width * thumbSize.height == 0) {
414 ALOGE("%s: non-zero thumbnail size not available", __FUNCTION__);
415 return fromStatus(Status::INTERNAL_ERROR);
416 }
417
418 mBlobBufferSize = blobBufferSize;
419 status = mOutputThread->allocateIntermediateBuffers(
420 v4lSize, mMaxThumbResolution, in_requestedConfiguration.streams, blobBufferSize);
421 if (status != Status::OK) {
422 ALOGE("%s: allocating intermediate buffers failed!", __FUNCTION__);
423 return fromStatus(status);
424 }
425
426 std::vector<HalStream>& out = *_aidl_return;
427 out.resize(in_requestedConfiguration.streams.size());
428 for (size_t i = 0; i < in_requestedConfiguration.streams.size(); i++) {
429 out[i].overrideDataSpace = in_requestedConfiguration.streams[i].dataSpace;
430 out[i].id = in_requestedConfiguration.streams[i].id;
431 // TODO: double check should we add those CAMERA flags
432 mStreamMap[in_requestedConfiguration.streams[i].id].usage = out[i].producerUsage =
433 static_cast<BufferUsage>(((int64_t)in_requestedConfiguration.streams[i].usage) |
434 ((int64_t)BufferUsage::CPU_WRITE_OFTEN) |
435 ((int64_t)BufferUsage::CAMERA_OUTPUT));
436 out[i].consumerUsage = static_cast<BufferUsage>(0);
437 out[i].maxBuffers = static_cast<int32_t>(mV4L2BufferCount);
438
439 switch (in_requestedConfiguration.streams[i].format) {
440 case PixelFormat::BLOB:
441 case PixelFormat::YCBCR_420_888:
442 case PixelFormat::YV12: // Used by SurfaceTexture
443 case PixelFormat::Y16:
444 // No override
445 out[i].overrideFormat = in_requestedConfiguration.streams[i].format;
446 break;
447 case PixelFormat::IMPLEMENTATION_DEFINED:
448 // Implementation Defined
449 // This should look at the Stream's dataspace flag to determine the format or leave
450 // it as is if the rest of the system knows how to handle a private format. To keep
451 // this HAL generic, this is being overridden to YUV420
452 out[i].overrideFormat = PixelFormat::YCBCR_420_888;
453 // Save overridden format in mStreamMap
454 mStreamMap[in_requestedConfiguration.streams[i].id].format = out[i].overrideFormat;
455 break;
456 default:
457 ALOGE("%s: unsupported format 0x%x", __FUNCTION__,
458 in_requestedConfiguration.streams[i].format);
459 return fromStatus(Status::ILLEGAL_ARGUMENT);
460 }
461 }
462
463 mFirstRequest = true;
464 mLastStreamConfigCounter = in_requestedConfiguration.streamConfigCounter;
465 return fromStatus(Status::OK);
466}
467
468ScopedAStatus ExternalCameraDeviceSession::flush() {
469 ATRACE_CALL();
470 Mutex::Autolock _il(mInterfaceLock);
471 Status status = initStatus();
472 if (status != Status::OK) {
473 return fromStatus(status);
474 }
475 mOutputThread->flush();
476 return fromStatus(Status::OK);
477}
478
479ScopedAStatus ExternalCameraDeviceSession::getCaptureRequestMetadataQueue(
480 MQDescriptor<int8_t, SynchronizedReadWrite>* _aidl_return) {
481 Mutex::Autolock _il(mInterfaceLock);
482 *_aidl_return = mRequestMetadataQueue->dupeDesc();
483 return fromStatus(Status::OK);
484}
485
486ScopedAStatus ExternalCameraDeviceSession::getCaptureResultMetadataQueue(
487 MQDescriptor<int8_t, SynchronizedReadWrite>* _aidl_return) {
488 Mutex::Autolock _il(mInterfaceLock);
489 *_aidl_return = mResultMetadataQueue->dupeDesc();
490 return fromStatus(Status::OK);
491}
492
493ScopedAStatus ExternalCameraDeviceSession::isReconfigurationRequired(
494 const CameraMetadata& in_oldSessionParams, const CameraMetadata& in_newSessionParams,
495 bool* _aidl_return) {
496 // reconfiguration required if there is any change in the session params
497 *_aidl_return = in_oldSessionParams != in_newSessionParams;
498 return fromStatus(Status::OK);
499}
500
501ScopedAStatus ExternalCameraDeviceSession::processCaptureRequest(
502 const std::vector<CaptureRequest>& in_requests,
503 const std::vector<BufferCache>& in_cachesToRemove, int32_t* _aidl_return) {
504 Mutex::Autolock _il(mInterfaceLock);
505 updateBufferCaches(in_cachesToRemove);
506
507 int32_t& numRequestProcessed = *_aidl_return;
508 numRequestProcessed = 0;
509 Status s = Status::OK;
510 for (size_t i = 0; i < in_requests.size(); i++, numRequestProcessed++) {
511 s = processOneCaptureRequest(in_requests[i]);
512 if (s != Status::OK) {
513 break;
514 }
515 }
516
517 return fromStatus(s);
518}
519
520Status ExternalCameraDeviceSession::processOneCaptureRequest(const CaptureRequest& request) {
521 ATRACE_CALL();
522 Status status = initStatus();
523 if (status != Status::OK) {
524 return status;
525 }
526
527 if (request.inputBuffer.streamId != -1) {
528 ALOGE("%s: external camera does not support reprocessing!", __FUNCTION__);
529 return Status::ILLEGAL_ARGUMENT;
530 }
531
532 Mutex::Autolock _l(mLock);
533 if (!mV4l2Streaming) {
534 ALOGE("%s: cannot process request in streamOff state!", __FUNCTION__);
535 return Status::INTERNAL_ERROR;
536 }
537
538 const camera_metadata_t* rawSettings = nullptr;
539 bool converted;
540 CameraMetadata settingsFmq; // settings from FMQ
541
542 if (request.fmqSettingsSize > 0) {
543 // non-blocking read; client must write metadata before calling
544 // processOneCaptureRequest
545 settingsFmq.metadata.resize(request.fmqSettingsSize);
546 bool read = mRequestMetadataQueue->read(
547 reinterpret_cast<int8_t*>(settingsFmq.metadata.data()), request.fmqSettingsSize);
548 if (read) {
549 converted = convertFromAidl(settingsFmq, &rawSettings);
550 } else {
551 ALOGE("%s: capture request settings metadata couldn't be read from fmq!", __FUNCTION__);
552 converted = false;
553 }
554 } else {
555 converted = convertFromAidl(request.settings, &rawSettings);
556 }
557
558 if (converted && rawSettings != nullptr) {
559 mLatestReqSetting = rawSettings;
560 }
561
562 if (!converted) {
563 ALOGE("%s: capture request settings metadata is corrupt!", __FUNCTION__);
564 return Status::ILLEGAL_ARGUMENT;
565 }
566
567 if (mFirstRequest && rawSettings == nullptr) {
568 ALOGE("%s: capture request settings must not be null for first request!", __FUNCTION__);
569 return Status::ILLEGAL_ARGUMENT;
570 }
571
572 std::vector<buffer_handle_t*> allBufPtrs;
573 std::vector<int> allFences;
574 size_t numOutputBufs = request.outputBuffers.size();
575
576 if (numOutputBufs == 0) {
577 ALOGE("%s: capture request must have at least one output buffer!", __FUNCTION__);
578 return Status::ILLEGAL_ARGUMENT;
579 }
580
581 camera_metadata_entry fpsRange = mLatestReqSetting.find(ANDROID_CONTROL_AE_TARGET_FPS_RANGE);
582 if (fpsRange.count == 2) {
583 double requestFpsMax = fpsRange.data.i32[1];
584 double closestFps = 0.0;
585 double fpsError = 1000.0;
586 bool fpsSupported = false;
587 for (const auto& fr : mV4l2StreamingFmt.frameRates) {
588 double f = fr.getFramesPerSecond();
589 if (std::fabs(requestFpsMax - f) < 1.0) {
590 fpsSupported = true;
591 break;
592 }
593 if (std::fabs(requestFpsMax - f) < fpsError) {
594 fpsError = std::fabs(requestFpsMax - f);
595 closestFps = f;
596 }
597 }
598 if (!fpsSupported) {
599 /* This can happen in a few scenarios:
600 * 1. The application is sending an FPS range not supported by the configured outputs.
601 * 2. The application is sending a valid FPS range for all configured outputs, but
602 * the selected V4L2 size can only run at slower speed. This should be very rare
603 * though: for this to happen a sensor needs to support at least 3 different aspect
604 * ratio outputs, and when (at least) two outputs are both not the main aspect ratio
605 * of the webcam, a third size that's larger might be picked and runs into this
606 * issue.
607 */
608 ALOGW("%s: cannot reach fps %d! Will do %f instead", __FUNCTION__, fpsRange.data.i32[1],
609 closestFps);
610 requestFpsMax = closestFps;
611 }
612
613 if (requestFpsMax != mV4l2StreamingFps) {
614 {
615 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
616 while (mNumDequeuedV4l2Buffers != 0) {
617 // Wait until pipeline is idle before reconfigure stream
618 int waitRet = waitForV4L2BufferReturnLocked(lk);
619 if (waitRet != 0) {
620 ALOGE("%s: wait for pipeline idle failed!", __FUNCTION__);
621 return Status::INTERNAL_ERROR;
622 }
623 }
624 }
625 configureV4l2StreamLocked(mV4l2StreamingFmt, requestFpsMax);
626 }
627 }
628
629 status = importRequestLocked(request, allBufPtrs, allFences);
630 if (status != Status::OK) {
631 return status;
632 }
633
634 nsecs_t shutterTs = 0;
635 std::unique_ptr<V4L2Frame> frameIn = dequeueV4l2FrameLocked(&shutterTs);
636 if (frameIn == nullptr) {
637 ALOGE("%s: V4L2 deque frame failed!", __FUNCTION__);
638 return Status::INTERNAL_ERROR;
639 }
640
641 std::shared_ptr<HalRequest> halReq = std::make_shared<HalRequest>();
642 halReq->frameNumber = request.frameNumber;
643 halReq->setting = mLatestReqSetting;
644 halReq->frameIn = std::move(frameIn);
645 halReq->shutterTs = shutterTs;
646 halReq->buffers.resize(numOutputBufs);
647 for (size_t i = 0; i < numOutputBufs; i++) {
648 HalStreamBuffer& halBuf = halReq->buffers[i];
649 int streamId = halBuf.streamId = request.outputBuffers[i].streamId;
650 halBuf.bufferId = request.outputBuffers[i].bufferId;
651 const Stream& stream = mStreamMap[streamId];
652 halBuf.width = stream.width;
653 halBuf.height = stream.height;
654 halBuf.format = stream.format;
655 halBuf.usage = stream.usage;
656 halBuf.bufPtr = allBufPtrs[i];
657 halBuf.acquireFence = allFences[i];
658 halBuf.fenceTimeout = false;
659 }
660 {
661 std::lock_guard<std::mutex> lk(mInflightFramesLock);
662 mInflightFrames.insert(halReq->frameNumber);
663 }
664 // Send request to OutputThread for the rest of processing
665 mOutputThread->submitRequest(halReq);
666 mFirstRequest = false;
667 return Status::OK;
668}
669
670ScopedAStatus ExternalCameraDeviceSession::signalStreamFlush(
671 const std::vector<int32_t>& /*in_streamIds*/, int32_t in_streamConfigCounter) {
672 {
673 Mutex::Autolock _l(mLock);
674 if (in_streamConfigCounter < mLastStreamConfigCounter) {
675 // stale call. new streams have been configured since this call was issued.
676 // Do nothing.
677 return fromStatus(Status::OK);
678 }
679 }
680
681 // TODO: implement if needed.
682 return fromStatus(Status::OK);
683}
684
685ScopedAStatus ExternalCameraDeviceSession::switchToOffline(
686 const std::vector<int32_t>& in_streamsToKeep,
687 CameraOfflineSessionInfo* out_offlineSessionInfo,
688 std::shared_ptr<ICameraOfflineSession>* _aidl_return) {
689 std::vector<NotifyMsg> msgs;
690 std::vector<CaptureResult> results;
691 CameraOfflineSessionInfo info;
692 std::shared_ptr<ICameraOfflineSession> session;
693 Status st = switchToOffline(in_streamsToKeep, &msgs, &results, &info, &session);
694
695 mCallback->notify(msgs);
696 invokeProcessCaptureResultCallback(results, /* tryWriteFmq= */ true);
697 freeReleaseFences(results);
698
699 // setup return values
700 *out_offlineSessionInfo = info;
701 *_aidl_return = session;
702 return fromStatus(st);
703}
704
705Status ExternalCameraDeviceSession::switchToOffline(
706 const std::vector<int32_t>& offlineStreams, std::vector<NotifyMsg>* msgs,
707 std::vector<CaptureResult>* results, CameraOfflineSessionInfo* info,
708 std::shared_ptr<ICameraOfflineSession>* session) {
709 ATRACE_CALL();
710 if (offlineStreams.size() > 1) {
711 ALOGE("%s: more than one offline stream is not supported", __FUNCTION__);
712 return Status::ILLEGAL_ARGUMENT;
713 }
714
Greg Kaiser9b77fd12022-12-05 17:06:02 -0800715 if (msgs == nullptr || results == nullptr || info == nullptr || session == nullptr) {
716 ALOGE("%s, output arguments (%p, %p, %p, %p) must not be null", __FUNCTION__, msgs, results,
Avichal Rakeshe1857f82022-06-08 17:47:23 -0700717 info, session);
718 }
719
720 Mutex::Autolock _il(mInterfaceLock);
721 Status status = initStatus();
722 if (status != Status::OK) {
723 return status;
724 }
725
726 Mutex::Autolock _l(mLock);
727 for (auto streamId : offlineStreams) {
728 if (!supportOfflineLocked(streamId)) {
729 return Status::ILLEGAL_ARGUMENT;
730 }
731 }
732
733 // pause output thread and get all remaining inflight requests
734 auto remainingReqs = mOutputThread->switchToOffline();
735 std::vector<std::shared_ptr<HalRequest>> halReqs;
736
737 // Send out buffer/request error for remaining requests and filter requests
738 // to be handled in offline mode
739 for (auto& halReq : remainingReqs) {
740 bool dropReq = canDropRequest(offlineStreams, halReq);
741 if (dropReq) {
742 // Request is dropped completely. Just send request error and
743 // there is no need to send the request to offline session
744 processCaptureRequestError(halReq, msgs, results);
745 continue;
746 }
747
748 // All requests reach here must have at least one offline stream output
749 NotifyMsg shutter;
750 aidl::android::hardware::camera::device::ShutterMsg shutterMsg = {
751 .frameNumber = static_cast<int32_t>(halReq->frameNumber),
752 .timestamp = halReq->shutterTs};
753 shutter.set<NotifyMsg::Tag::shutter>(shutterMsg);
754 msgs->push_back(shutter);
755
756 std::vector<HalStreamBuffer> offlineBuffers;
757 for (const auto& buffer : halReq->buffers) {
758 bool dropBuffer = true;
759 for (auto offlineStreamId : offlineStreams) {
760 if (buffer.streamId == offlineStreamId) {
761 dropBuffer = false;
762 break;
763 }
764 }
765 if (dropBuffer) {
766 aidl::android::hardware::camera::device::ErrorMsg errorMsg = {
767 .frameNumber = static_cast<int32_t>(halReq->frameNumber),
768 .errorStreamId = buffer.streamId,
769 .errorCode = ErrorCode::ERROR_BUFFER};
770
771 NotifyMsg error;
772 error.set<NotifyMsg::Tag::error>(errorMsg);
773 msgs->push_back(error);
774
775 results->push_back({
776 .frameNumber = static_cast<int32_t>(halReq->frameNumber),
777 .outputBuffers = {},
778 .inputBuffer = {.streamId = -1},
779 .partialResult = 0, // buffer only result
780 });
781
782 CaptureResult& result = results->back();
783 result.outputBuffers.resize(1);
784 StreamBuffer& outputBuffer = result.outputBuffers[0];
785 outputBuffer.streamId = buffer.streamId;
786 outputBuffer.bufferId = buffer.bufferId;
787 outputBuffer.status = BufferStatus::ERROR;
788 if (buffer.acquireFence >= 0) {
789 native_handle_t* handle = native_handle_create(/*numFds*/ 1, /*numInts*/ 0);
790 handle->data[0] = buffer.acquireFence;
791 outputBuffer.releaseFence = android::makeToAidl(handle);
792 }
793 } else {
794 offlineBuffers.push_back(buffer);
795 }
796 }
797 halReq->buffers = offlineBuffers;
798 halReqs.push_back(halReq);
799 }
800
801 // convert hal requests to offline request
802 std::deque<std::shared_ptr<HalRequest>> offlineReqs(halReqs.size());
803 size_t i = 0;
804 for (auto& v4lReq : halReqs) {
805 offlineReqs[i] = std::make_shared<HalRequest>();
806 offlineReqs[i]->frameNumber = v4lReq->frameNumber;
807 offlineReqs[i]->setting = v4lReq->setting;
808 offlineReqs[i]->shutterTs = v4lReq->shutterTs;
809 offlineReqs[i]->buffers = v4lReq->buffers;
810 std::shared_ptr<V4L2Frame> v4l2Frame(static_cast<V4L2Frame*>(v4lReq->frameIn.get()));
811 offlineReqs[i]->frameIn = std::make_shared<AllocatedV4L2Frame>(v4l2Frame);
812 i++;
813 // enqueue V4L2 frame
814 enqueueV4l2Frame(v4l2Frame);
815 }
816
817 // Collect buffer caches/streams
818 std::vector<Stream> streamInfos(offlineStreams.size());
819 std::map<int, CirculatingBuffers> circulatingBuffers;
820 {
821 Mutex::Autolock _cbsl(mCbsLock);
822 for (auto streamId : offlineStreams) {
823 circulatingBuffers[streamId] = mCirculatingBuffers.at(streamId);
824 mCirculatingBuffers.erase(streamId);
825 streamInfos.push_back(mStreamMap.at(streamId));
826 mStreamMap.erase(streamId);
827 }
828 }
829
830 fillOfflineSessionInfo(offlineStreams, offlineReqs, circulatingBuffers, info);
831 // create the offline session object
832 bool afTrigger;
833 {
834 std::lock_guard<std::mutex> _lk(mAfTriggerLock);
835 afTrigger = mAfTrigger;
836 }
837
838 std::shared_ptr<ExternalCameraOfflineSession> sessionImpl =
839 ndk::SharedRefBase::make<ExternalCameraOfflineSession>(
840 mCroppingType, mCameraCharacteristics, mCameraId, mExifMake, mExifModel,
841 mBlobBufferSize, afTrigger, streamInfos, offlineReqs, circulatingBuffers);
842
843 bool initFailed = sessionImpl->initialize();
844 if (initFailed) {
845 ALOGE("%s: offline session initialize failed!", __FUNCTION__);
846 return Status::INTERNAL_ERROR;
847 }
848
849 // cleanup stream and buffer caches
850 {
851 Mutex::Autolock _cbsl(mCbsLock);
852 for (auto pair : mStreamMap) {
853 cleanupBuffersLocked(/*Stream ID*/ pair.first);
854 }
855 mCirculatingBuffers.clear();
856 }
857 mStreamMap.clear();
858
859 // update inflight records
860 {
861 std::lock_guard<std::mutex> _lk(mInflightFramesLock);
862 mInflightFrames.clear();
863 }
864
865 // stop v4l2 streaming
866 if (v4l2StreamOffLocked() != 0) {
867 ALOGE("%s: stop V4L2 streaming failed!", __FUNCTION__);
868 return Status::INTERNAL_ERROR;
869 }
870
871 // No need to return session if there is no offline requests left
872 if (!offlineReqs.empty()) {
873 *session = sessionImpl;
874 } else {
875 *session = nullptr;
876 }
877
878 return Status::OK;
879}
880
881#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
882#define UPDATE(md, tag, data, size) \
883 do { \
884 if ((md).update((tag), (data), (size))) { \
885 ALOGE("Update " #tag " failed!"); \
886 return BAD_VALUE; \
887 } \
888 } while (0)
889
890status_t ExternalCameraDeviceSession::initDefaultRequests() {
891 common::V1_0::helper::CameraMetadata md;
892
893 const uint8_t aberrationMode = ANDROID_COLOR_CORRECTION_ABERRATION_MODE_OFF;
894 UPDATE(md, ANDROID_COLOR_CORRECTION_ABERRATION_MODE, &aberrationMode, 1);
895
896 const int32_t exposureCompensation = 0;
897 UPDATE(md, ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION, &exposureCompensation, 1);
898
899 const uint8_t videoStabilizationMode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
900 UPDATE(md, ANDROID_CONTROL_VIDEO_STABILIZATION_MODE, &videoStabilizationMode, 1);
901
902 const uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO;
903 UPDATE(md, ANDROID_CONTROL_AWB_MODE, &awbMode, 1);
904
905 const uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON;
906 UPDATE(md, ANDROID_CONTROL_AE_MODE, &aeMode, 1);
907
908 const uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
909 UPDATE(md, ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
910
911 const uint8_t afMode = ANDROID_CONTROL_AF_MODE_AUTO;
912 UPDATE(md, ANDROID_CONTROL_AF_MODE, &afMode, 1);
913
914 const uint8_t afTrigger = ANDROID_CONTROL_AF_TRIGGER_IDLE;
915 UPDATE(md, ANDROID_CONTROL_AF_TRIGGER, &afTrigger, 1);
916
917 const uint8_t sceneMode = ANDROID_CONTROL_SCENE_MODE_DISABLED;
918 UPDATE(md, ANDROID_CONTROL_SCENE_MODE, &sceneMode, 1);
919
920 const uint8_t effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF;
921 UPDATE(md, ANDROID_CONTROL_EFFECT_MODE, &effectMode, 1);
922
923 const uint8_t flashMode = ANDROID_FLASH_MODE_OFF;
924 UPDATE(md, ANDROID_FLASH_MODE, &flashMode, 1);
925
926 const int32_t thumbnailSize[] = {240, 180};
927 UPDATE(md, ANDROID_JPEG_THUMBNAIL_SIZE, thumbnailSize, 2);
928
929 const uint8_t jpegQuality = 90;
930 UPDATE(md, ANDROID_JPEG_QUALITY, &jpegQuality, 1);
931 UPDATE(md, ANDROID_JPEG_THUMBNAIL_QUALITY, &jpegQuality, 1);
932
933 const int32_t jpegOrientation = 0;
934 UPDATE(md, ANDROID_JPEG_ORIENTATION, &jpegOrientation, 1);
935
936 const uint8_t oisMode = ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF;
937 UPDATE(md, ANDROID_LENS_OPTICAL_STABILIZATION_MODE, &oisMode, 1);
938
939 const uint8_t nrMode = ANDROID_NOISE_REDUCTION_MODE_OFF;
940 UPDATE(md, ANDROID_NOISE_REDUCTION_MODE, &nrMode, 1);
941
942 const int32_t testPatternModes = ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
943 UPDATE(md, ANDROID_SENSOR_TEST_PATTERN_MODE, &testPatternModes, 1);
944
945 const uint8_t fdMode = ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
946 UPDATE(md, ANDROID_STATISTICS_FACE_DETECT_MODE, &fdMode, 1);
947
948 const uint8_t hotpixelMode = ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF;
949 UPDATE(md, ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE, &hotpixelMode, 1);
950
951 bool support30Fps = false;
952 int32_t maxFps = std::numeric_limits<int32_t>::min();
953 for (const auto& supportedFormat : mSupportedFormats) {
954 for (const auto& fr : supportedFormat.frameRates) {
955 int32_t framerateInt = static_cast<int32_t>(fr.getFramesPerSecond());
956 if (maxFps < framerateInt) {
957 maxFps = framerateInt;
958 }
959 if (framerateInt == 30) {
960 support30Fps = true;
961 break;
962 }
963 }
964 if (support30Fps) {
965 break;
966 }
967 }
968
969 int32_t defaultFramerate = support30Fps ? 30 : maxFps;
970 int32_t defaultFpsRange[] = {defaultFramerate / 2, defaultFramerate};
971 UPDATE(md, ANDROID_CONTROL_AE_TARGET_FPS_RANGE, defaultFpsRange, ARRAY_SIZE(defaultFpsRange));
972
973 uint8_t antibandingMode = ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO;
974 UPDATE(md, ANDROID_CONTROL_AE_ANTIBANDING_MODE, &antibandingMode, 1);
975
976 const uint8_t controlMode = ANDROID_CONTROL_MODE_AUTO;
977 UPDATE(md, ANDROID_CONTROL_MODE, &controlMode, 1);
978
979 for (const auto& type : ndk::enum_range<RequestTemplate>()) {
980 common::V1_0::helper::CameraMetadata mdCopy = md;
981 uint8_t intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
982 switch (type) {
983 case RequestTemplate::PREVIEW:
984 intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
985 break;
986 case RequestTemplate::STILL_CAPTURE:
987 intent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE;
988 break;
989 case RequestTemplate::VIDEO_RECORD:
990 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD;
991 break;
992 case RequestTemplate::VIDEO_SNAPSHOT:
993 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT;
994 break;
995 default:
996 ALOGV("%s: unsupported RequestTemplate type %d", __FUNCTION__, type);
997 continue;
998 }
999 UPDATE(mdCopy, ANDROID_CONTROL_CAPTURE_INTENT, &intent, 1);
1000 camera_metadata_t* mdPtr = mdCopy.release();
1001 uint8_t* rawMd = reinterpret_cast<uint8_t*>(mdPtr);
1002 CameraMetadata aidlMd;
1003 aidlMd.metadata.assign(rawMd, rawMd + get_camera_metadata_size(mdPtr));
1004 mDefaultRequests[type] = aidlMd;
1005 free_camera_metadata(mdPtr);
1006 }
1007 return OK;
1008}
1009
1010status_t ExternalCameraDeviceSession::fillCaptureResult(common::V1_0::helper::CameraMetadata& md,
1011 nsecs_t timestamp) {
1012 bool afTrigger = false;
1013 {
1014 std::lock_guard<std::mutex> lk(mAfTriggerLock);
1015 afTrigger = mAfTrigger;
1016 if (md.exists(ANDROID_CONTROL_AF_TRIGGER)) {
1017 camera_metadata_entry entry = md.find(ANDROID_CONTROL_AF_TRIGGER);
1018 if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_START) {
1019 mAfTrigger = afTrigger = true;
1020 } else if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_CANCEL) {
1021 mAfTrigger = afTrigger = false;
1022 }
1023 }
1024 }
1025
1026 // For USB camera, the USB camera handles everything and we don't have control
1027 // over AF. We only simply fake the AF metadata based on the request
1028 // received here.
1029 uint8_t afState;
1030 if (afTrigger) {
1031 afState = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
1032 } else {
1033 afState = ANDROID_CONTROL_AF_STATE_INACTIVE;
1034 }
1035 UPDATE(md, ANDROID_CONTROL_AF_STATE, &afState, 1);
1036
1037 camera_metadata_ro_entry activeArraySize =
1038 mCameraCharacteristics.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
1039
1040 return fillCaptureResultCommon(md, timestamp, activeArraySize);
1041}
1042
1043int ExternalCameraDeviceSession::configureV4l2StreamLocked(const SupportedV4L2Format& v4l2Fmt,
1044 double requestFps) {
1045 ATRACE_CALL();
1046 int ret = v4l2StreamOffLocked();
1047 if (ret != OK) {
1048 ALOGE("%s: stop v4l2 streaming failed: ret %d", __FUNCTION__, ret);
1049 return ret;
1050 }
1051
1052 // VIDIOC_S_FMT w/h/fmt
1053 v4l2_format fmt;
1054 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1055 fmt.fmt.pix.width = v4l2Fmt.width;
1056 fmt.fmt.pix.height = v4l2Fmt.height;
1057 fmt.fmt.pix.pixelformat = v4l2Fmt.fourcc;
1058
1059 {
1060 int numAttempt = 0;
1061 do {
1062 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt));
1063 if (numAttempt == MAX_RETRY) {
1064 break;
1065 }
1066 numAttempt++;
1067 if (ret < 0) {
1068 ALOGW("%s: VIDIOC_S_FMT failed, wait 33ms and try again", __FUNCTION__);
1069 usleep(IOCTL_RETRY_SLEEP_US); // sleep and try again
1070 }
1071 } while (ret < 0);
1072 if (ret < 0) {
1073 ALOGE("%s: S_FMT ioctl failed: %s", __FUNCTION__, strerror(errno));
1074 return -errno;
1075 }
1076 }
1077
1078 if (v4l2Fmt.width != fmt.fmt.pix.width || v4l2Fmt.height != fmt.fmt.pix.height ||
1079 v4l2Fmt.fourcc != fmt.fmt.pix.pixelformat) {
1080 ALOGE("%s: S_FMT expect %c%c%c%c %dx%d, got %c%c%c%c %dx%d instead!", __FUNCTION__,
1081 v4l2Fmt.fourcc & 0xFF, (v4l2Fmt.fourcc >> 8) & 0xFF, (v4l2Fmt.fourcc >> 16) & 0xFF,
1082 (v4l2Fmt.fourcc >> 24) & 0xFF, v4l2Fmt.width, v4l2Fmt.height,
1083 fmt.fmt.pix.pixelformat & 0xFF, (fmt.fmt.pix.pixelformat >> 8) & 0xFF,
1084 (fmt.fmt.pix.pixelformat >> 16) & 0xFF, (fmt.fmt.pix.pixelformat >> 24) & 0xFF,
1085 fmt.fmt.pix.width, fmt.fmt.pix.height);
1086 return -EINVAL;
1087 }
1088
1089 uint32_t bufferSize = fmt.fmt.pix.sizeimage;
1090 ALOGI("%s: V4L2 buffer size is %d", __FUNCTION__, bufferSize);
1091 uint32_t expectedMaxBufferSize = kMaxBytesPerPixel * fmt.fmt.pix.width * fmt.fmt.pix.height;
1092 if ((bufferSize == 0) || (bufferSize > expectedMaxBufferSize)) {
1093 ALOGE("%s: V4L2 buffer size: %u looks invalid. Expected maximum size: %u", __FUNCTION__,
1094 bufferSize, expectedMaxBufferSize);
1095 return -EINVAL;
1096 }
1097 mMaxV4L2BufferSize = bufferSize;
1098
1099 const double kDefaultFps = 30.0;
1100 double fps = std::numeric_limits<double>::max();
1101 if (requestFps != 0.0) {
1102 fps = requestFps;
1103 } else {
1104 double maxFps = -1.0;
1105 // Try to pick the slowest fps that is at least 30
1106 for (const auto& fr : v4l2Fmt.frameRates) {
1107 double f = fr.getFramesPerSecond();
1108 if (maxFps < f) {
1109 maxFps = f;
1110 }
1111 if (f >= kDefaultFps && f < fps) {
1112 fps = f;
1113 }
1114 }
1115 // No fps > 30 found, use the highest fps available within supported formats.
1116 if (fps == std::numeric_limits<double>::max()) {
1117 fps = maxFps;
1118 }
1119 }
1120
1121 int fpsRet = setV4l2FpsLocked(fps);
1122 if (fpsRet != 0 && fpsRet != -EINVAL) {
1123 ALOGE("%s: set fps failed: %s", __FUNCTION__, strerror(fpsRet));
1124 return fpsRet;
1125 }
1126
1127 uint32_t v4lBufferCount = (fps >= kDefaultFps) ? mCfg.numVideoBuffers : mCfg.numStillBuffers;
1128
1129 // VIDIOC_REQBUFS: create buffers
1130 v4l2_requestbuffers req_buffers{};
1131 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1132 req_buffers.memory = V4L2_MEMORY_MMAP;
1133 req_buffers.count = v4lBufferCount;
1134 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
1135 ALOGE("%s: VIDIOC_REQBUFS failed: %s", __FUNCTION__, strerror(errno));
1136 return -errno;
1137 }
1138
1139 // Driver can indeed return more buffer if it needs more to operate
1140 if (req_buffers.count < v4lBufferCount) {
1141 ALOGE("%s: VIDIOC_REQBUFS expected %d buffers, got %d instead", __FUNCTION__,
1142 v4lBufferCount, req_buffers.count);
1143 return NO_MEMORY;
1144 }
1145
1146 // VIDIOC_QUERYBUF: get buffer offset in the V4L2 fd
1147 // VIDIOC_QBUF: send buffer to driver
1148 mV4L2BufferCount = req_buffers.count;
1149 for (uint32_t i = 0; i < req_buffers.count; i++) {
1150 v4l2_buffer buffer = {
1151 .index = i, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .memory = V4L2_MEMORY_MMAP};
1152
1153 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QUERYBUF, &buffer)) < 0) {
1154 ALOGE("%s: QUERYBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
1155 return -errno;
1156 }
1157
1158 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1159 ALOGE("%s: QBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
1160 return -errno;
1161 }
1162 }
1163
1164 {
1165 // VIDIOC_STREAMON: start streaming
1166 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1167 int numAttempt = 0;
1168 do {
1169 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type));
1170 if (numAttempt == MAX_RETRY) {
1171 break;
1172 }
1173 if (ret < 0) {
1174 ALOGW("%s: VIDIOC_STREAMON failed, wait 33ms and try again", __FUNCTION__);
1175 usleep(IOCTL_RETRY_SLEEP_US); // sleep 100 ms and try again
1176 }
1177 } while (ret < 0);
1178
1179 if (ret < 0) {
1180 ALOGE("%s: VIDIOC_STREAMON ioctl failed: %s", __FUNCTION__, strerror(errno));
1181 return -errno;
1182 }
1183 }
1184
1185 // Swallow first few frames after streamOn to account for bad frames from some devices
1186 for (int i = 0; i < kBadFramesAfterStreamOn; i++) {
1187 v4l2_buffer buffer{};
1188 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1189 buffer.memory = V4L2_MEMORY_MMAP;
1190 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
1191 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
1192 return -errno;
1193 }
1194
1195 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1196 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, buffer.index, strerror(errno));
1197 return -errno;
1198 }
1199 }
1200
1201 ALOGI("%s: start V4L2 streaming %dx%d@%ffps", __FUNCTION__, v4l2Fmt.width, v4l2Fmt.height, fps);
1202 mV4l2StreamingFmt = v4l2Fmt;
1203 mV4l2Streaming = true;
1204 return OK;
1205}
1206
1207std::unique_ptr<V4L2Frame> ExternalCameraDeviceSession::dequeueV4l2FrameLocked(nsecs_t* shutterTs) {
1208 ATRACE_CALL();
1209 std::unique_ptr<V4L2Frame> ret = nullptr;
1210 if (shutterTs == nullptr) {
1211 ALOGE("%s: shutterTs must not be null!", __FUNCTION__);
1212 return ret;
1213 }
1214
1215 {
1216 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
1217 if (mNumDequeuedV4l2Buffers == mV4L2BufferCount) {
1218 int waitRet = waitForV4L2BufferReturnLocked(lk);
1219 if (waitRet != 0) {
1220 return ret;
1221 }
1222 }
1223 }
1224
1225 ATRACE_BEGIN("VIDIOC_DQBUF");
1226 v4l2_buffer buffer{};
1227 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1228 buffer.memory = V4L2_MEMORY_MMAP;
1229 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
1230 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
1231 return ret;
1232 }
1233 ATRACE_END();
1234
1235 if (buffer.index >= mV4L2BufferCount) {
1236 ALOGE("%s: Invalid buffer id: %d", __FUNCTION__, buffer.index);
1237 return ret;
1238 }
1239
1240 if (buffer.flags & V4L2_BUF_FLAG_ERROR) {
1241 ALOGE("%s: v4l2 buf error! buf flag 0x%x", __FUNCTION__, buffer.flags);
1242 // TODO: try to dequeue again
1243 }
1244
1245 if (buffer.bytesused > mMaxV4L2BufferSize) {
1246 ALOGE("%s: v4l2 buffer bytes used: %u maximum %u", __FUNCTION__, buffer.bytesused,
1247 mMaxV4L2BufferSize);
1248 return ret;
1249 }
1250
1251 if (buffer.flags & V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC) {
1252 // Ideally we should also check for V4L2_BUF_FLAG_TSTAMP_SRC_SOE, but
1253 // even V4L2_BUF_FLAG_TSTAMP_SRC_EOF is better than capture a timestamp now
1254 *shutterTs = static_cast<nsecs_t>(buffer.timestamp.tv_sec) * 1000000000LL +
1255 buffer.timestamp.tv_usec * 1000LL;
1256 } else {
1257 *shutterTs = systemTime(SYSTEM_TIME_MONOTONIC);
1258 }
1259
1260 {
1261 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1262 mNumDequeuedV4l2Buffers++;
1263 }
1264
1265 return std::make_unique<V4L2Frame>(mV4l2StreamingFmt.width, mV4l2StreamingFmt.height,
1266 mV4l2StreamingFmt.fourcc, buffer.index, mV4l2Fd.get(),
1267 buffer.bytesused, buffer.m.offset);
1268}
1269
1270void ExternalCameraDeviceSession::enqueueV4l2Frame(const std::shared_ptr<V4L2Frame>& frame) {
1271 ATRACE_CALL();
1272 frame->unmap();
1273 ATRACE_BEGIN("VIDIOC_QBUF");
1274 v4l2_buffer buffer{};
1275 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1276 buffer.memory = V4L2_MEMORY_MMAP;
1277 buffer.index = frame->mBufferIndex;
1278 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1279 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, frame->mBufferIndex, strerror(errno));
1280 return;
1281 }
1282 ATRACE_END();
1283
1284 {
1285 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1286 mNumDequeuedV4l2Buffers--;
1287 }
1288 mV4L2BufferReturned.notify_one();
1289}
1290
1291bool ExternalCameraDeviceSession::isSupported(
1292 const Stream& stream, const std::vector<SupportedV4L2Format>& supportedFormats,
1293 const ExternalCameraConfig& devCfg) {
1294 Dataspace ds = stream.dataSpace;
1295 PixelFormat fmt = stream.format;
1296 uint32_t width = stream.width;
1297 uint32_t height = stream.height;
1298 // TODO: check usage flags
1299
1300 if (stream.streamType != StreamType::OUTPUT) {
1301 ALOGE("%s: does not support non-output stream type", __FUNCTION__);
1302 return false;
1303 }
1304
1305 if (stream.rotation != StreamRotation::ROTATION_0) {
1306 ALOGE("%s: does not support stream rotation", __FUNCTION__);
1307 return false;
1308 }
1309
1310 switch (fmt) {
1311 case PixelFormat::BLOB:
1312 if (ds != Dataspace::JFIF) {
1313 ALOGI("%s: BLOB format does not support dataSpace %x", __FUNCTION__, ds);
1314 return false;
1315 }
1316 break;
1317 case PixelFormat::IMPLEMENTATION_DEFINED:
1318 case PixelFormat::YCBCR_420_888:
1319 case PixelFormat::YV12:
1320 // TODO: check what dataspace we can support here.
1321 // intentional no-ops.
1322 break;
1323 case PixelFormat::Y16:
1324 if (!devCfg.depthEnabled) {
1325 ALOGI("%s: Depth is not Enabled", __FUNCTION__);
1326 return false;
1327 }
1328 if (!(static_cast<int32_t>(ds) & static_cast<int32_t>(Dataspace::DEPTH))) {
1329 ALOGI("%s: Y16 supports only dataSpace DEPTH", __FUNCTION__);
1330 return false;
1331 }
1332 break;
1333 default:
1334 ALOGI("%s: does not support format %x", __FUNCTION__, fmt);
1335 return false;
1336 }
1337
1338 // Assume we can convert any V4L2 format to any of supported output format for now, i.e.
1339 // ignoring v4l2Fmt.fourcc for now. Might need more subtle check if we support more v4l format
1340 // in the futrue.
1341 for (const auto& v4l2Fmt : supportedFormats) {
1342 if (width == v4l2Fmt.width && height == v4l2Fmt.height) {
1343 return true;
1344 }
1345 }
1346 ALOGI("%s: resolution %dx%d is not supported", __FUNCTION__, width, height);
1347 return false;
1348}
1349
1350Status ExternalCameraDeviceSession::importRequestLocked(const CaptureRequest& request,
1351 std::vector<buffer_handle_t*>& allBufPtrs,
1352 std::vector<int>& allFences) {
1353 return importRequestLockedImpl(request, allBufPtrs, allFences);
1354}
1355
1356Status ExternalCameraDeviceSession::importRequestLockedImpl(
1357 const CaptureRequest& request, std::vector<buffer_handle_t*>& allBufPtrs,
1358 std::vector<int>& allFences) {
1359 size_t numOutputBufs = request.outputBuffers.size();
1360 size_t numBufs = numOutputBufs;
1361 // Validate all I/O buffers
1362 std::vector<buffer_handle_t> allBufs;
1363 std::vector<uint64_t> allBufIds;
1364 allBufs.resize(numBufs);
1365 allBufIds.resize(numBufs);
1366 allBufPtrs.resize(numBufs);
1367 allFences.resize(numBufs);
1368 std::vector<int32_t> streamIds(numBufs);
1369
1370 for (size_t i = 0; i < numOutputBufs; i++) {
1371 allBufs[i] = ::android::makeFromAidl(request.outputBuffers[i].buffer);
1372 allBufIds[i] = request.outputBuffers[i].bufferId;
1373 allBufPtrs[i] = &allBufs[i];
1374 streamIds[i] = request.outputBuffers[i].streamId;
1375 }
1376
1377 {
1378 Mutex::Autolock _l(mCbsLock);
1379 for (size_t i = 0; i < numBufs; i++) {
1380 Status st = importBufferLocked(streamIds[i], allBufIds[i], allBufs[i], &allBufPtrs[i]);
1381 if (st != Status::OK) {
1382 // Detailed error logs printed in importBuffer
1383 return st;
1384 }
1385 }
1386 }
1387
1388 // All buffers are imported. Now validate output buffer acquire fences
1389 for (size_t i = 0; i < numOutputBufs; i++) {
1390 if (!sHandleImporter.importFence(
1391 ::android::makeFromAidl(request.outputBuffers[i].acquireFence), allFences[i])) {
1392 ALOGE("%s: output buffer %zu acquire fence is invalid", __FUNCTION__, i);
1393 cleanupInflightFences(allFences, i);
1394 return Status::INTERNAL_ERROR;
1395 }
1396 }
1397 return Status::OK;
1398}
1399
1400Status ExternalCameraDeviceSession::importBuffer(int32_t streamId, uint64_t bufId,
1401 buffer_handle_t buf,
1402 /*out*/ buffer_handle_t** outBufPtr) {
1403 Mutex::Autolock _l(mCbsLock);
1404 return importBufferLocked(streamId, bufId, buf, outBufPtr);
1405}
1406
1407Status ExternalCameraDeviceSession::importBufferLocked(int32_t streamId, uint64_t bufId,
1408 buffer_handle_t buf,
1409 buffer_handle_t** outBufPtr) {
1410 return importBufferImpl(mCirculatingBuffers, sHandleImporter, streamId, bufId, buf, outBufPtr);
1411}
1412
1413ScopedAStatus ExternalCameraDeviceSession::close() {
1414 close(false);
1415 return fromStatus(Status::OK);
1416}
1417
1418void ExternalCameraDeviceSession::close(bool callerIsDtor) {
1419 Mutex::Autolock _il(mInterfaceLock);
1420 bool closed = isClosed();
1421 if (!closed) {
1422 if (callerIsDtor) {
1423 closeOutputThreadImpl();
1424 } else {
1425 closeOutputThread();
1426 }
1427
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: {
2885 IMapper::Rect outRect{0, 0, static_cast<int32_t>(halBuf.width),
2886 static_cast<int32_t>(halBuf.height)};
2887 YCbCrLayout outLayout = sHandleImporter.lockYCbCr(
2888 *(halBuf.bufPtr), static_cast<uint64_t>(halBuf.usage), outRect);
2889 ALOGV("%s: outLayout y %p cb %p cr %p y_str %d c_str %d c_step %d", __FUNCTION__,
2890 outLayout.y, outLayout.cb, outLayout.cr, outLayout.yStride, outLayout.cStride,
2891 outLayout.chromaStep);
2892
2893 // Convert to output buffer size/format
2894 uint32_t outputFourcc = getFourCcFromLayout(outLayout);
2895 ALOGV("%s: converting to format %c%c%c%c", __FUNCTION__, outputFourcc & 0xFF,
2896 (outputFourcc >> 8) & 0xFF, (outputFourcc >> 16) & 0xFF,
2897 (outputFourcc >> 24) & 0xFF);
2898
2899 YCbCrLayout cropAndScaled;
2900 ATRACE_BEGIN("cropAndScaleLocked");
2901 int ret = cropAndScaleLocked(mYu12Frame, Size{halBuf.width, halBuf.height},
2902 &cropAndScaled);
2903 ATRACE_END();
2904 if (ret != 0) {
2905 lk.unlock();
2906 return onDeviceError("%s: crop and scale failed!", __FUNCTION__);
2907 }
2908
2909 Size sz{halBuf.width, halBuf.height};
2910 ATRACE_BEGIN("formatConvert");
2911 ret = formatConvert(cropAndScaled, outLayout, sz, outputFourcc);
2912 ATRACE_END();
2913 if (ret != 0) {
2914 lk.unlock();
2915 return onDeviceError("%s: format conversion failed!", __FUNCTION__);
2916 }
2917 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
2918 if (relFence >= 0) {
2919 halBuf.acquireFence = relFence;
2920 }
2921 } break;
2922 default:
2923 lk.unlock();
2924 return onDeviceError("%s: unknown output format %x", __FUNCTION__, halBuf.format);
2925 }
2926 } // for each buffer
2927 mScaledYu12Frames.clear();
2928
2929 // Don't hold the lock while calling back to parent
2930 lk.unlock();
2931 Status st = parent->processCaptureResult(req);
2932 if (st != Status::OK) {
2933 return onDeviceError("%s: failed to process capture result!", __FUNCTION__);
2934 }
2935 signalRequestDone();
2936 return true;
2937}
2938
2939// End ExternalCameraDeviceSession::OutputThread functions
2940
2941} // namespace implementation
2942} // namespace device
2943} // namespace camera
2944} // namespace hardware
2945} // namespace android