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