blob: 0ede8897c3edd4ea5501f014b366f4c952727179 [file] [log] [blame]
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#define LOG_TAG "ExtCamDevSsn@3.4"
17//#define LOG_NDEBUG 0
Yin-Chia Yehe99cf202018-02-28 11:30:38 -080018#define ATRACE_TAG ATRACE_TAG_CAMERA
Yin-Chia Yeh19030592017-10-19 17:30:11 -070019#include <log/log.h>
20
21#include <inttypes.h>
22#include "ExternalCameraDeviceSession.h"
23
24#include "android-base/macros.h"
Yin-Chia Yeh19030592017-10-19 17:30:11 -070025#include <utils/Timers.h>
Yin-Chia Yehe99cf202018-02-28 11:30:38 -080026#include <utils/Trace.h>
Yin-Chia Yeh19030592017-10-19 17:30:11 -070027#include <linux/videodev2.h>
28#include <sync/sync.h>
29
30#define HAVE_JPEG // required for libyuv.h to export MJPEG decode APIs
31#include <libyuv.h>
32
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -080033#include <jpeglib.h>
34
35
Yin-Chia Yeh19030592017-10-19 17:30:11 -070036namespace android {
37namespace hardware {
38namespace camera {
39namespace device {
40namespace V3_4 {
41namespace implementation {
42
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080043namespace {
Yin-Chia Yeh19030592017-10-19 17:30:11 -070044// Size of request/result metadata fast message queue. Change to 0 to always use hwbinder buffer.
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080045static constexpr size_t kMetadataMsgQueueSize = 1 << 18 /* 256kB */;
46
Yin-Chia Yeh19030592017-10-19 17:30:11 -070047const int kBadFramesAfterStreamOn = 1; // drop x frames after streamOn to get rid of some initial
48 // bad frames. TODO: develop a better bad frame detection
49 // method
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -080050constexpr int MAX_RETRY = 15; // Allow retry some ioctl failures a few times to account for some
51 // webcam showing temporarily ioctl failures.
52constexpr int IOCTL_RETRY_SLEEP_US = 33000; // 33ms * MAX_RETRY = 5 seconds
Yin-Chia Yeh19030592017-10-19 17:30:11 -070053
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -080054// Constants for tryLock during dumpstate
55static constexpr int kDumpLockRetries = 50;
56static constexpr int kDumpLockSleep = 60000;
57
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -080058bool tryLock(Mutex& mutex)
59{
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -080060 bool locked = false;
61 for (int i = 0; i < kDumpLockRetries; ++i) {
62 if (mutex.tryLock() == NO_ERROR) {
63 locked = true;
64 break;
65 }
66 usleep(kDumpLockSleep);
67 }
68 return locked;
69}
70
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -080071bool tryLock(std::mutex& mutex)
72{
73 bool locked = false;
74 for (int i = 0; i < kDumpLockRetries; ++i) {
75 if (mutex.try_lock()) {
76 locked = true;
77 break;
78 }
79 usleep(kDumpLockSleep);
80 }
81 return locked;
82}
83
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080084} // Anonymous namespace
Yin-Chia Yeh19030592017-10-19 17:30:11 -070085
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080086// Static instances
87const int ExternalCameraDeviceSession::kMaxProcessedStream;
88const int ExternalCameraDeviceSession::kMaxStallStream;
Yin-Chia Yeh19030592017-10-19 17:30:11 -070089HandleImporter ExternalCameraDeviceSession::sHandleImporter;
90
Yin-Chia Yeh19030592017-10-19 17:30:11 -070091ExternalCameraDeviceSession::ExternalCameraDeviceSession(
92 const sp<ICameraDeviceCallback>& callback,
Yin-Chia Yeh17982492018-02-05 17:41:01 -080093 const ExternalCameraConfig& cfg,
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080094 const std::vector<SupportedV4L2Format>& sortedFormats,
95 const CroppingType& croppingType,
Yin-Chia Yeh19030592017-10-19 17:30:11 -070096 const common::V1_0::helper::CameraMetadata& chars,
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -080097 const std::string& cameraId,
Yin-Chia Yeh19030592017-10-19 17:30:11 -070098 unique_fd v4l2Fd) :
99 mCallback(callback),
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -0800100 mCfg(cfg),
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700101 mCameraCharacteristics(chars),
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -0800102 mSupportedFormats(sortedFormats),
103 mCroppingType(croppingType),
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800104 mCameraId(cameraId),
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700105 mV4l2Fd(std::move(v4l2Fd)),
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800106 mOutputThread(new OutputThread(this, mCroppingType)),
107 mMaxThumbResolution(getMaxThumbResolution()),
108 mMaxJpegResolution(getMaxJpegResolution()) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700109 mInitFail = initialize();
110}
111
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700112bool ExternalCameraDeviceSession::initialize() {
113 if (mV4l2Fd.get() < 0) {
114 ALOGE("%s: invalid v4l2 device fd %d!", __FUNCTION__, mV4l2Fd.get());
115 return true;
116 }
117
118 status_t status = initDefaultRequests();
119 if (status != OK) {
120 ALOGE("%s: init default requests failed!", __FUNCTION__);
121 return true;
122 }
123
124 mRequestMetadataQueue = std::make_unique<RequestMetadataQueue>(
125 kMetadataMsgQueueSize, false /* non blocking */);
126 if (!mRequestMetadataQueue->isValid()) {
127 ALOGE("%s: invalid request fmq", __FUNCTION__);
128 return true;
129 }
130 mResultMetadataQueue = std::make_shared<RequestMetadataQueue>(
131 kMetadataMsgQueueSize, false /* non blocking */);
132 if (!mResultMetadataQueue->isValid()) {
133 ALOGE("%s: invalid result fmq", __FUNCTION__);
134 return true;
135 }
136
137 // TODO: check is PRIORITY_DISPLAY enough?
138 mOutputThread->run("ExtCamOut", PRIORITY_DISPLAY);
139 return false;
140}
141
142Status ExternalCameraDeviceSession::initStatus() const {
143 Mutex::Autolock _l(mLock);
144 Status status = Status::OK;
145 if (mInitFail || mClosed) {
146 ALOGI("%s: sesssion initFailed %d closed %d", __FUNCTION__, mInitFail, mClosed);
147 status = Status::INTERNAL_ERROR;
148 }
149 return status;
150}
151
152ExternalCameraDeviceSession::~ExternalCameraDeviceSession() {
153 if (!isClosed()) {
154 ALOGE("ExternalCameraDeviceSession deleted before close!");
155 close();
156 }
157}
158
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800159
160void ExternalCameraDeviceSession::dumpState(const native_handle_t* handle) {
161 if (handle->numFds != 1 || handle->numInts != 0) {
162 ALOGE("%s: handle must contain 1 FD and 0 integers! Got %d FDs and %d ints",
163 __FUNCTION__, handle->numFds, handle->numInts);
164 return;
165 }
166 int fd = handle->data[0];
167
168 bool intfLocked = tryLock(mInterfaceLock);
169 if (!intfLocked) {
170 dprintf(fd, "!! ExternalCameraDeviceSession interface may be deadlocked !!\n");
171 }
172
173 if (isClosed()) {
174 dprintf(fd, "External camera %s is closed\n", mCameraId.c_str());
175 return;
176 }
177
178 bool streaming = false;
179 size_t v4L2BufferCount = 0;
180 SupportedV4L2Format streamingFmt;
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800181 {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800182 bool sessionLocked = tryLock(mLock);
183 if (!sessionLocked) {
184 dprintf(fd, "!! ExternalCameraDeviceSession mLock may be deadlocked !!\n");
185 }
186 streaming = mV4l2Streaming;
187 streamingFmt = mV4l2StreamingFmt;
188 v4L2BufferCount = mV4L2BufferCount;
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -0800189
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800190 if (sessionLocked) {
191 mLock.unlock();
192 }
193 }
194
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -0800195 std::unordered_set<uint32_t> inflightFrames;
196 {
197 bool iffLocked = tryLock(mInflightFramesLock);
198 if (!iffLocked) {
199 dprintf(fd,
200 "!! ExternalCameraDeviceSession mInflightFramesLock may be deadlocked !!\n");
201 }
202 inflightFrames = mInflightFrames;
203 if (iffLocked) {
204 mInflightFramesLock.unlock();
205 }
206 }
207
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800208 dprintf(fd, "External camera %s V4L2 FD %d, cropping type %s, %s\n",
209 mCameraId.c_str(), mV4l2Fd.get(),
210 (mCroppingType == VERTICAL) ? "vertical" : "horizontal",
211 streaming ? "streaming" : "not streaming");
212 if (streaming) {
213 // TODO: dump fps later
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800214 dprintf(fd, "Current V4L2 format %c%c%c%c %dx%d @ %ffps\n",
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800215 streamingFmt.fourcc & 0xFF,
216 (streamingFmt.fourcc >> 8) & 0xFF,
217 (streamingFmt.fourcc >> 16) & 0xFF,
218 (streamingFmt.fourcc >> 24) & 0xFF,
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800219 streamingFmt.width, streamingFmt.height,
220 mV4l2StreamingFps);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800221
222 size_t numDequeuedV4l2Buffers = 0;
223 {
224 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
225 numDequeuedV4l2Buffers = mNumDequeuedV4l2Buffers;
226 }
227 dprintf(fd, "V4L2 buffer queue size %zu, dequeued %zu\n",
228 v4L2BufferCount, numDequeuedV4l2Buffers);
229 }
230
231 dprintf(fd, "In-flight frames (not sorted):");
232 for (const auto& frameNumber : inflightFrames) {
233 dprintf(fd, "%d, ", frameNumber);
234 }
235 dprintf(fd, "\n");
236 mOutputThread->dump(fd);
237 dprintf(fd, "\n");
238
239 if (intfLocked) {
240 mInterfaceLock.unlock();
241 }
242
243 return;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700244}
245
246Return<void> ExternalCameraDeviceSession::constructDefaultRequestSettings(
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800247 V3_2::RequestTemplate type,
248 V3_2::ICameraDeviceSession::constructDefaultRequestSettings_cb _hidl_cb) {
249 V3_2::CameraMetadata outMetadata;
250 Status status = constructDefaultRequestSettingsRaw(
251 static_cast<RequestTemplate>(type), &outMetadata);
252 _hidl_cb(status, outMetadata);
253 return Void();
254}
255
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800256Status ExternalCameraDeviceSession::constructDefaultRequestSettingsRaw(RequestTemplate type,
257 V3_2::CameraMetadata *outMetadata) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700258 CameraMetadata emptyMd;
259 Status status = initStatus();
260 if (status != Status::OK) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800261 return status;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700262 }
263
264 switch (type) {
265 case RequestTemplate::PREVIEW:
266 case RequestTemplate::STILL_CAPTURE:
267 case RequestTemplate::VIDEO_RECORD:
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800268 case RequestTemplate::VIDEO_SNAPSHOT: {
269 *outMetadata = mDefaultRequests[type];
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700270 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800271 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700272 case RequestTemplate::MANUAL:
273 case RequestTemplate::ZERO_SHUTTER_LAG:
Eino-Ville Talvala0a2a9fc2018-02-05 16:27:15 -0800274 // Don't support MANUAL, ZSL templates
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800275 status = Status::ILLEGAL_ARGUMENT;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700276 break;
277 default:
278 ALOGE("%s: unknown request template type %d", __FUNCTION__, static_cast<int>(type));
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800279 status = Status::ILLEGAL_ARGUMENT;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700280 break;
281 }
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800282 return status;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700283}
284
285Return<void> ExternalCameraDeviceSession::configureStreams(
286 const V3_2::StreamConfiguration& streams,
287 ICameraDeviceSession::configureStreams_cb _hidl_cb) {
288 V3_2::HalStreamConfiguration outStreams;
289 V3_3::HalStreamConfiguration outStreams_v33;
290 Mutex::Autolock _il(mInterfaceLock);
291
292 Status status = configureStreams(streams, &outStreams_v33);
293 size_t size = outStreams_v33.streams.size();
294 outStreams.streams.resize(size);
295 for (size_t i = 0; i < size; i++) {
296 outStreams.streams[i] = outStreams_v33.streams[i].v3_2;
297 }
298 _hidl_cb(status, outStreams);
299 return Void();
300}
301
302Return<void> ExternalCameraDeviceSession::configureStreams_3_3(
303 const V3_2::StreamConfiguration& streams,
304 ICameraDeviceSession::configureStreams_3_3_cb _hidl_cb) {
305 V3_3::HalStreamConfiguration outStreams;
306 Mutex::Autolock _il(mInterfaceLock);
307
308 Status status = configureStreams(streams, &outStreams);
309 _hidl_cb(status, outStreams);
310 return Void();
311}
312
313Return<void> ExternalCameraDeviceSession::configureStreams_3_4(
314 const V3_4::StreamConfiguration& requestedConfiguration,
315 ICameraDeviceSession::configureStreams_3_4_cb _hidl_cb) {
316 V3_2::StreamConfiguration config_v32;
317 V3_3::HalStreamConfiguration outStreams_v33;
318 Mutex::Autolock _il(mInterfaceLock);
319
320 config_v32.operationMode = requestedConfiguration.operationMode;
321 config_v32.streams.resize(requestedConfiguration.streams.size());
322 for (size_t i = 0; i < config_v32.streams.size(); i++) {
323 config_v32.streams[i] = requestedConfiguration.streams[i].v3_2;
324 }
325
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700326 Status status = configureStreams(config_v32, &outStreams_v33);
327
328 V3_4::HalStreamConfiguration outStreams;
329 outStreams.streams.resize(outStreams_v33.streams.size());
330 for (size_t i = 0; i < outStreams.streams.size(); i++) {
331 outStreams.streams[i].v3_3 = outStreams_v33.streams[i];
332 }
333 _hidl_cb(status, outStreams);
334 return Void();
335}
336
337Return<void> ExternalCameraDeviceSession::getCaptureRequestMetadataQueue(
338 ICameraDeviceSession::getCaptureRequestMetadataQueue_cb _hidl_cb) {
339 Mutex::Autolock _il(mInterfaceLock);
340 _hidl_cb(*mRequestMetadataQueue->getDesc());
341 return Void();
342}
343
344Return<void> ExternalCameraDeviceSession::getCaptureResultMetadataQueue(
345 ICameraDeviceSession::getCaptureResultMetadataQueue_cb _hidl_cb) {
346 Mutex::Autolock _il(mInterfaceLock);
347 _hidl_cb(*mResultMetadataQueue->getDesc());
348 return Void();
349}
350
351Return<void> ExternalCameraDeviceSession::processCaptureRequest(
352 const hidl_vec<CaptureRequest>& requests,
353 const hidl_vec<BufferCache>& cachesToRemove,
354 ICameraDeviceSession::processCaptureRequest_cb _hidl_cb) {
355 Mutex::Autolock _il(mInterfaceLock);
356 updateBufferCaches(cachesToRemove);
357
358 uint32_t numRequestProcessed = 0;
359 Status s = Status::OK;
360 for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
361 s = processOneCaptureRequest(requests[i]);
362 if (s != Status::OK) {
363 break;
364 }
365 }
366
367 _hidl_cb(s, numRequestProcessed);
368 return Void();
369}
370
371Return<void> ExternalCameraDeviceSession::processCaptureRequest_3_4(
372 const hidl_vec<V3_4::CaptureRequest>& requests,
373 const hidl_vec<V3_2::BufferCache>& cachesToRemove,
374 ICameraDeviceSession::processCaptureRequest_3_4_cb _hidl_cb) {
375 Mutex::Autolock _il(mInterfaceLock);
376 updateBufferCaches(cachesToRemove);
377
378 uint32_t numRequestProcessed = 0;
379 Status s = Status::OK;
380 for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
381 s = processOneCaptureRequest(requests[i].v3_2);
382 if (s != Status::OK) {
383 break;
384 }
385 }
386
387 _hidl_cb(s, numRequestProcessed);
388 return Void();
389}
390
391Return<Status> ExternalCameraDeviceSession::flush() {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -0800392 ATRACE_CALL();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -0800393 Mutex::Autolock _il(mInterfaceLock);
394 Status status = initStatus();
395 if (status != Status::OK) {
396 return status;
397 }
398 mOutputThread->flush();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700399 return Status::OK;
400}
401
402Return<void> ExternalCameraDeviceSession::close() {
403 Mutex::Autolock _il(mInterfaceLock);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800404 bool closed = isClosed();
405 if (!closed) {
406 mOutputThread->flush();
407 mOutputThread->requestExit();
408 mOutputThread->join();
409
410 Mutex::Autolock _l(mLock);
411 // free all buffers
412 for(auto pair : mStreamMap) {
413 cleanupBuffersLocked(/*Stream ID*/pair.first);
414 }
415 v4l2StreamOffLocked();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700416 ALOGV("%s: closing V4L2 camera FD %d", __FUNCTION__, mV4l2Fd.get());
417 mV4l2Fd.reset();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700418 mClosed = true;
419 }
420 return Void();
421}
422
423Status ExternalCameraDeviceSession::importRequest(
424 const CaptureRequest& request,
425 hidl_vec<buffer_handle_t*>& allBufPtrs,
426 hidl_vec<int>& allFences) {
427 size_t numOutputBufs = request.outputBuffers.size();
428 size_t numBufs = numOutputBufs;
429 // Validate all I/O buffers
430 hidl_vec<buffer_handle_t> allBufs;
431 hidl_vec<uint64_t> allBufIds;
432 allBufs.resize(numBufs);
433 allBufIds.resize(numBufs);
434 allBufPtrs.resize(numBufs);
435 allFences.resize(numBufs);
436 std::vector<int32_t> streamIds(numBufs);
437
438 for (size_t i = 0; i < numOutputBufs; i++) {
439 allBufs[i] = request.outputBuffers[i].buffer.getNativeHandle();
440 allBufIds[i] = request.outputBuffers[i].bufferId;
441 allBufPtrs[i] = &allBufs[i];
442 streamIds[i] = request.outputBuffers[i].streamId;
443 }
444
445 for (size_t i = 0; i < numBufs; i++) {
446 buffer_handle_t buf = allBufs[i];
447 uint64_t bufId = allBufIds[i];
448 CirculatingBuffers& cbs = mCirculatingBuffers[streamIds[i]];
449 if (cbs.count(bufId) == 0) {
450 if (buf == nullptr) {
451 ALOGE("%s: bufferId %" PRIu64 " has null buffer handle!", __FUNCTION__, bufId);
452 return Status::ILLEGAL_ARGUMENT;
453 }
454 // Register a newly seen buffer
455 buffer_handle_t importedBuf = buf;
456 sHandleImporter.importBuffer(importedBuf);
457 if (importedBuf == nullptr) {
458 ALOGE("%s: output buffer %zu is invalid!", __FUNCTION__, i);
459 return Status::INTERNAL_ERROR;
460 } else {
461 cbs[bufId] = importedBuf;
462 }
463 }
464 allBufPtrs[i] = &cbs[bufId];
465 }
466
467 // All buffers are imported. Now validate output buffer acquire fences
468 for (size_t i = 0; i < numOutputBufs; i++) {
469 if (!sHandleImporter.importFence(
470 request.outputBuffers[i].acquireFence, allFences[i])) {
471 ALOGE("%s: output buffer %zu acquire fence is invalid", __FUNCTION__, i);
472 cleanupInflightFences(allFences, i);
473 return Status::INTERNAL_ERROR;
474 }
475 }
476 return Status::OK;
477}
478
479void ExternalCameraDeviceSession::cleanupInflightFences(
480 hidl_vec<int>& allFences, size_t numFences) {
481 for (size_t j = 0; j < numFences; j++) {
482 sHandleImporter.closeFence(allFences[j]);
483 }
484}
485
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800486int ExternalCameraDeviceSession::waitForV4L2BufferReturnLocked(std::unique_lock<std::mutex>& lk) {
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -0800487 ATRACE_CALL();
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800488 std::chrono::seconds timeout = std::chrono::seconds(kBufferWaitTimeoutSec);
489 mLock.unlock();
490 auto st = mV4L2BufferReturned.wait_for(lk, timeout);
491 // Here we introduce a order where mV4l2BufferLock is acquired before mLock, while
492 // the normal lock acquisition order is reversed. This is fine because in most of
493 // cases we are protected by mInterfaceLock. The only thread that can cause deadlock
494 // is the OutputThread, where we do need to make sure we don't acquire mLock then
495 // mV4l2BufferLock
496 mLock.lock();
497 if (st == std::cv_status::timeout) {
498 ALOGE("%s: wait for V4L2 buffer return timeout!", __FUNCTION__);
499 return -1;
500 }
501 return 0;
502}
503
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700504Status ExternalCameraDeviceSession::processOneCaptureRequest(const CaptureRequest& request) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -0800505 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700506 Status status = initStatus();
507 if (status != Status::OK) {
508 return status;
509 }
510
511 if (request.inputBuffer.streamId != -1) {
512 ALOGE("%s: external camera does not support reprocessing!", __FUNCTION__);
513 return Status::ILLEGAL_ARGUMENT;
514 }
515
516 Mutex::Autolock _l(mLock);
517 if (!mV4l2Streaming) {
518 ALOGE("%s: cannot process request in streamOff state!", __FUNCTION__);
519 return Status::INTERNAL_ERROR;
520 }
521
522 const camera_metadata_t *rawSettings = nullptr;
523 bool converted = true;
524 CameraMetadata settingsFmq; // settings from FMQ
525 if (request.fmqSettingsSize > 0) {
526 // non-blocking read; client must write metadata before calling
527 // processOneCaptureRequest
528 settingsFmq.resize(request.fmqSettingsSize);
529 bool read = mRequestMetadataQueue->read(settingsFmq.data(), request.fmqSettingsSize);
530 if (read) {
531 converted = V3_2::implementation::convertFromHidl(settingsFmq, &rawSettings);
532 } else {
533 ALOGE("%s: capture request settings metadata couldn't be read from fmq!", __FUNCTION__);
534 converted = false;
535 }
536 } else {
537 converted = V3_2::implementation::convertFromHidl(request.settings, &rawSettings);
538 }
539
540 if (converted && rawSettings != nullptr) {
541 mLatestReqSetting = rawSettings;
542 }
543
544 if (!converted) {
545 ALOGE("%s: capture request settings metadata is corrupt!", __FUNCTION__);
546 return Status::ILLEGAL_ARGUMENT;
547 }
548
549 if (mFirstRequest && rawSettings == nullptr) {
550 ALOGE("%s: capture request settings must not be null for first request!",
551 __FUNCTION__);
552 return Status::ILLEGAL_ARGUMENT;
553 }
554
555 hidl_vec<buffer_handle_t*> allBufPtrs;
556 hidl_vec<int> allFences;
557 size_t numOutputBufs = request.outputBuffers.size();
558
559 if (numOutputBufs == 0) {
560 ALOGE("%s: capture request must have at least one output buffer!", __FUNCTION__);
561 return Status::ILLEGAL_ARGUMENT;
562 }
563
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800564 camera_metadata_entry fpsRange = mLatestReqSetting.find(ANDROID_CONTROL_AE_TARGET_FPS_RANGE);
565 if (fpsRange.count == 2) {
566 double requestFpsMax = fpsRange.data.i32[1];
567 double closestFps = 0.0;
568 double fpsError = 1000.0;
569 bool fpsSupported = false;
570 for (const auto& fr : mV4l2StreamingFmt.frameRates) {
571 double f = fr.getDouble();
572 if (std::fabs(requestFpsMax - f) < 1.0) {
573 fpsSupported = true;
574 break;
575 }
576 if (std::fabs(requestFpsMax - f) < fpsError) {
577 fpsError = std::fabs(requestFpsMax - f);
578 closestFps = f;
579 }
580 }
581 if (!fpsSupported) {
582 /* This can happen in a few scenarios:
583 * 1. The application is sending a FPS range not supported by the configured outputs.
584 * 2. The application is sending a valid FPS range for all cofigured outputs, but
585 * the selected V4L2 size can only run at slower speed. This should be very rare
586 * though: for this to happen a sensor needs to support at least 3 different aspect
587 * ratio outputs, and when (at least) two outputs are both not the main aspect ratio
588 * of the webcam, a third size that's larger might be picked and runs into this
589 * issue.
590 */
591 ALOGW("%s: cannot reach fps %d! Will do %f instead",
592 __FUNCTION__, fpsRange.data.i32[1], closestFps);
593 requestFpsMax = closestFps;
594 }
595
596 if (requestFpsMax != mV4l2StreamingFps) {
597 {
598 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
599 while (mNumDequeuedV4l2Buffers != 0) {
600 // Wait until pipeline is idle before reconfigure stream
601 int waitRet = waitForV4L2BufferReturnLocked(lk);
602 if (waitRet != 0) {
603 ALOGE("%s: wait for pipeline idle failed!", __FUNCTION__);
604 return Status::INTERNAL_ERROR;
605 }
606 }
607 }
608 configureV4l2StreamLocked(mV4l2StreamingFmt, requestFpsMax);
609 }
610 }
611
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700612 status = importRequest(request, allBufPtrs, allFences);
613 if (status != Status::OK) {
614 return status;
615 }
616
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800617 nsecs_t shutterTs = 0;
618 sp<V4L2Frame> frameIn = dequeueV4l2FrameLocked(&shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700619 if ( frameIn == nullptr) {
620 ALOGE("%s: V4L2 deque frame failed!", __FUNCTION__);
621 return Status::INTERNAL_ERROR;
622 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700623
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800624 std::shared_ptr<HalRequest> halReq = std::make_shared<HalRequest>();
625 halReq->frameNumber = request.frameNumber;
626 halReq->setting = mLatestReqSetting;
627 halReq->frameIn = frameIn;
628 halReq->shutterTs = shutterTs;
629 halReq->buffers.resize(numOutputBufs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700630 for (size_t i = 0; i < numOutputBufs; i++) {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800631 HalStreamBuffer& halBuf = halReq->buffers[i];
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700632 int streamId = halBuf.streamId = request.outputBuffers[i].streamId;
633 halBuf.bufferId = request.outputBuffers[i].bufferId;
634 const Stream& stream = mStreamMap[streamId];
635 halBuf.width = stream.width;
636 halBuf.height = stream.height;
637 halBuf.format = stream.format;
638 halBuf.usage = stream.usage;
639 halBuf.bufPtr = allBufPtrs[i];
640 halBuf.acquireFence = allFences[i];
641 halBuf.fenceTimeout = false;
642 }
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -0800643 {
644 std::lock_guard<std::mutex> lk(mInflightFramesLock);
645 mInflightFrames.insert(halReq->frameNumber);
646 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700647 // Send request to OutputThread for the rest of processing
648 mOutputThread->submitRequest(halReq);
649 mFirstRequest = false;
650 return Status::OK;
651}
652
653void ExternalCameraDeviceSession::notifyShutter(uint32_t frameNumber, nsecs_t shutterTs) {
654 NotifyMsg msg;
655 msg.type = MsgType::SHUTTER;
656 msg.msg.shutter.frameNumber = frameNumber;
657 msg.msg.shutter.timestamp = shutterTs;
658 mCallback->notify({msg});
659}
660
661void ExternalCameraDeviceSession::notifyError(
662 uint32_t frameNumber, int32_t streamId, ErrorCode ec) {
663 NotifyMsg msg;
664 msg.type = MsgType::ERROR;
665 msg.msg.error.frameNumber = frameNumber;
666 msg.msg.error.errorStreamId = streamId;
667 msg.msg.error.errorCode = ec;
668 mCallback->notify({msg});
669}
670
671//TODO: refactor with processCaptureResult
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800672Status ExternalCameraDeviceSession::processCaptureRequestError(
673 const std::shared_ptr<HalRequest>& req) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -0800674 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700675 // Return V4L2 buffer to V4L2 buffer queue
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800676 enqueueV4l2Frame(req->frameIn);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700677
678 // NotifyShutter
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800679 notifyShutter(req->frameNumber, req->shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700680
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800681 notifyError(/*frameNum*/req->frameNumber, /*stream*/-1, ErrorCode::ERROR_REQUEST);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700682
683 // Fill output buffers
684 hidl_vec<CaptureResult> results;
685 results.resize(1);
686 CaptureResult& result = results[0];
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800687 result.frameNumber = req->frameNumber;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700688 result.partialResult = 1;
689 result.inputBuffer.streamId = -1;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800690 result.outputBuffers.resize(req->buffers.size());
691 for (size_t i = 0; i < req->buffers.size(); i++) {
692 result.outputBuffers[i].streamId = req->buffers[i].streamId;
693 result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700694 result.outputBuffers[i].status = BufferStatus::ERROR;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800695 if (req->buffers[i].acquireFence >= 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700696 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800697 handle->data[0] = req->buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800698 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700699 }
700 }
701
702 // update inflight records
703 {
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -0800704 std::lock_guard<std::mutex> lk(mInflightFramesLock);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800705 mInflightFrames.erase(req->frameNumber);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700706 }
707
708 // Callback into framework
709 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
710 freeReleaseFences(results);
711 return Status::OK;
712}
713
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800714Status ExternalCameraDeviceSession::processCaptureResult(std::shared_ptr<HalRequest>& req) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -0800715 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700716 // Return V4L2 buffer to V4L2 buffer queue
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800717 enqueueV4l2Frame(req->frameIn);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700718
719 // NotifyShutter
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800720 notifyShutter(req->frameNumber, req->shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700721
722 // Fill output buffers
723 hidl_vec<CaptureResult> results;
724 results.resize(1);
725 CaptureResult& result = results[0];
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800726 result.frameNumber = req->frameNumber;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700727 result.partialResult = 1;
728 result.inputBuffer.streamId = -1;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800729 result.outputBuffers.resize(req->buffers.size());
730 for (size_t i = 0; i < req->buffers.size(); i++) {
731 result.outputBuffers[i].streamId = req->buffers[i].streamId;
732 result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
733 if (req->buffers[i].fenceTimeout) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700734 result.outputBuffers[i].status = BufferStatus::ERROR;
735 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800736 handle->data[0] = req->buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800737 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800738 notifyError(req->frameNumber, req->buffers[i].streamId, ErrorCode::ERROR_BUFFER);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700739 } else {
740 result.outputBuffers[i].status = BufferStatus::OK;
741 // TODO: refactor
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800742 if (req->buffers[i].acquireFence > 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700743 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800744 handle->data[0] = req->buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800745 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700746 }
747 }
748 }
749
750 // Fill capture result metadata
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800751 fillCaptureResult(req->setting, req->shutterTs);
752 const camera_metadata_t *rawResult = req->setting.getAndLock();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700753 V3_2::implementation::convertToHidl(rawResult, &result.result);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800754 req->setting.unlock(rawResult);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700755
756 // update inflight records
757 {
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -0800758 std::lock_guard<std::mutex> lk(mInflightFramesLock);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800759 mInflightFrames.erase(req->frameNumber);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700760 }
761
762 // Callback into framework
763 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
764 freeReleaseFences(results);
765 return Status::OK;
766}
767
768void ExternalCameraDeviceSession::invokeProcessCaptureResultCallback(
769 hidl_vec<CaptureResult> &results, bool tryWriteFmq) {
770 if (mProcessCaptureResultLock.tryLock() != OK) {
771 const nsecs_t NS_TO_SECOND = 1000000000;
772 ALOGV("%s: previous call is not finished! waiting 1s...", __FUNCTION__);
773 if (mProcessCaptureResultLock.timedLock(/* 1s */NS_TO_SECOND) != OK) {
774 ALOGE("%s: cannot acquire lock in 1s, cannot proceed",
775 __FUNCTION__);
776 return;
777 }
778 }
779 if (tryWriteFmq && mResultMetadataQueue->availableToWrite() > 0) {
780 for (CaptureResult &result : results) {
781 if (result.result.size() > 0) {
782 if (mResultMetadataQueue->write(result.result.data(), result.result.size())) {
783 result.fmqResultSize = result.result.size();
784 result.result.resize(0);
785 } else {
786 ALOGW("%s: couldn't utilize fmq, fall back to hwbinder", __FUNCTION__);
787 result.fmqResultSize = 0;
788 }
789 } else {
790 result.fmqResultSize = 0;
791 }
792 }
793 }
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -0800794 auto status = mCallback->processCaptureResult(results);
795 if (!status.isOk()) {
796 ALOGE("%s: processCaptureResult ERROR : %s", __FUNCTION__,
797 status.description().c_str());
798 }
799
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700800 mProcessCaptureResultLock.unlock();
801}
802
803void ExternalCameraDeviceSession::freeReleaseFences(hidl_vec<CaptureResult>& results) {
804 for (auto& result : results) {
805 if (result.inputBuffer.releaseFence.getNativeHandle() != nullptr) {
806 native_handle_t* handle = const_cast<native_handle_t*>(
807 result.inputBuffer.releaseFence.getNativeHandle());
808 native_handle_close(handle);
809 native_handle_delete(handle);
810 }
811 for (auto& buf : result.outputBuffers) {
812 if (buf.releaseFence.getNativeHandle() != nullptr) {
813 native_handle_t* handle = const_cast<native_handle_t*>(
814 buf.releaseFence.getNativeHandle());
815 native_handle_close(handle);
816 native_handle_delete(handle);
817 }
818 }
819 }
820 return;
821}
822
823ExternalCameraDeviceSession::OutputThread::OutputThread(
824 wp<ExternalCameraDeviceSession> parent,
825 CroppingType ct) : mParent(parent), mCroppingType(ct) {}
826
827ExternalCameraDeviceSession::OutputThread::~OutputThread() {}
828
829uint32_t ExternalCameraDeviceSession::OutputThread::getFourCcFromLayout(
830 const YCbCrLayout& layout) {
831 intptr_t cb = reinterpret_cast<intptr_t>(layout.cb);
832 intptr_t cr = reinterpret_cast<intptr_t>(layout.cr);
833 if (std::abs(cb - cr) == 1 && layout.chromaStep == 2) {
834 // Interleaved format
835 if (layout.cb > layout.cr) {
836 return V4L2_PIX_FMT_NV21;
837 } else {
838 return V4L2_PIX_FMT_NV12;
839 }
840 } else if (layout.chromaStep == 1) {
841 // Planar format
842 if (layout.cb > layout.cr) {
843 return V4L2_PIX_FMT_YVU420; // YV12
844 } else {
845 return V4L2_PIX_FMT_YUV420; // YU12
846 }
847 } else {
848 return FLEX_YUV_GENERIC;
849 }
850}
851
852int ExternalCameraDeviceSession::OutputThread::getCropRect(
853 CroppingType ct, const Size& inSize, const Size& outSize, IMapper::Rect* out) {
854 if (out == nullptr) {
855 ALOGE("%s: out is null", __FUNCTION__);
856 return -1;
857 }
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800858
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700859 uint32_t inW = inSize.width;
860 uint32_t inH = inSize.height;
861 uint32_t outW = outSize.width;
862 uint32_t outH = outSize.height;
863
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800864 // Handle special case where aspect ratio is close to input but scaled
865 // dimension is slightly larger than input
866 float arIn = ASPECT_RATIO(inSize);
867 float arOut = ASPECT_RATIO(outSize);
868 if (isAspectRatioClose(arIn, arOut)) {
869 out->left = 0;
870 out->top = 0;
871 out->width = inW;
872 out->height = inH;
873 return 0;
874 }
875
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700876 if (ct == VERTICAL) {
877 uint64_t scaledOutH = static_cast<uint64_t>(outH) * inW / outW;
878 if (scaledOutH > inH) {
879 ALOGE("%s: Output size %dx%d cannot be vertically cropped from input size %dx%d",
880 __FUNCTION__, outW, outH, inW, inH);
881 return -1;
882 }
883 scaledOutH = scaledOutH & ~0x1; // make it multiple of 2
884
885 out->left = 0;
886 out->top = ((inH - scaledOutH) / 2) & ~0x1;
887 out->width = inW;
888 out->height = static_cast<int32_t>(scaledOutH);
889 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledH %d",
890 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutH));
891 } else {
892 uint64_t scaledOutW = static_cast<uint64_t>(outW) * inH / outH;
893 if (scaledOutW > inW) {
894 ALOGE("%s: Output size %dx%d cannot be horizontally cropped from input size %dx%d",
895 __FUNCTION__, outW, outH, inW, inH);
896 return -1;
897 }
898 scaledOutW = scaledOutW & ~0x1; // make it multiple of 2
899
900 out->left = ((inW - scaledOutW) / 2) & ~0x1;
901 out->top = 0;
902 out->width = static_cast<int32_t>(scaledOutW);
903 out->height = inH;
904 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledW %d",
905 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutW));
906 }
907
908 return 0;
909}
910
911int ExternalCameraDeviceSession::OutputThread::cropAndScaleLocked(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800912 sp<AllocatedFrame>& in, const Size& outSz, YCbCrLayout* out) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700913 Size inSz = {in->mWidth, in->mHeight};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800914
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700915 int ret;
916 if (inSz == outSz) {
917 ret = in->getLayout(out);
918 if (ret != 0) {
919 ALOGE("%s: failed to get input image layout", __FUNCTION__);
920 return ret;
921 }
922 return ret;
923 }
924
925 // Cropping to output aspect ratio
926 IMapper::Rect inputCrop;
927 ret = getCropRect(mCroppingType, inSz, outSz, &inputCrop);
928 if (ret != 0) {
929 ALOGE("%s: failed to compute crop rect for output size %dx%d",
930 __FUNCTION__, outSz.width, outSz.height);
931 return ret;
932 }
933
934 YCbCrLayout croppedLayout;
935 ret = in->getCroppedLayout(inputCrop, &croppedLayout);
936 if (ret != 0) {
937 ALOGE("%s: failed to crop input image %dx%d to output size %dx%d",
938 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
939 return ret;
940 }
941
942 if ((mCroppingType == VERTICAL && inSz.width == outSz.width) ||
943 (mCroppingType == HORIZONTAL && inSz.height == outSz.height)) {
944 // No scale is needed
945 *out = croppedLayout;
946 return 0;
947 }
948
949 auto it = mScaledYu12Frames.find(outSz);
950 sp<AllocatedFrame> scaledYu12Buf;
951 if (it != mScaledYu12Frames.end()) {
952 scaledYu12Buf = it->second;
953 } else {
954 it = mIntermediateBuffers.find(outSz);
955 if (it == mIntermediateBuffers.end()) {
956 ALOGE("%s: failed to find intermediate buffer size %dx%d",
957 __FUNCTION__, outSz.width, outSz.height);
958 return -1;
959 }
960 scaledYu12Buf = it->second;
961 }
962 // Scale
963 YCbCrLayout outLayout;
964 ret = scaledYu12Buf->getLayout(&outLayout);
965 if (ret != 0) {
966 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
967 return ret;
968 }
969
970 ret = libyuv::I420Scale(
971 static_cast<uint8_t*>(croppedLayout.y),
972 croppedLayout.yStride,
973 static_cast<uint8_t*>(croppedLayout.cb),
974 croppedLayout.cStride,
975 static_cast<uint8_t*>(croppedLayout.cr),
976 croppedLayout.cStride,
977 inputCrop.width,
978 inputCrop.height,
979 static_cast<uint8_t*>(outLayout.y),
980 outLayout.yStride,
981 static_cast<uint8_t*>(outLayout.cb),
982 outLayout.cStride,
983 static_cast<uint8_t*>(outLayout.cr),
984 outLayout.cStride,
985 outSz.width,
986 outSz.height,
987 // TODO: b/72261744 see if we can use better filter without losing too much perf
988 libyuv::FilterMode::kFilterNone);
989
990 if (ret != 0) {
991 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
992 __FUNCTION__, inputCrop.width, inputCrop.height,
993 outSz.width, outSz.height, ret);
994 return ret;
995 }
996
997 *out = outLayout;
998 mScaledYu12Frames.insert({outSz, scaledYu12Buf});
999 return 0;
1000}
1001
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001002
1003int ExternalCameraDeviceSession::OutputThread::cropAndScaleThumbLocked(
1004 sp<AllocatedFrame>& in, const Size &outSz, YCbCrLayout* out) {
1005 Size inSz {in->mWidth, in->mHeight};
1006
1007 if ((outSz.width * outSz.height) >
1008 (mYu12ThumbFrame->mWidth * mYu12ThumbFrame->mHeight)) {
1009 ALOGE("%s: Requested thumbnail size too big (%d,%d) > (%d,%d)",
1010 __FUNCTION__, outSz.width, outSz.height,
1011 mYu12ThumbFrame->mWidth, mYu12ThumbFrame->mHeight);
1012 return -1;
1013 }
1014
1015 int ret;
1016
1017 /* This will crop-and-zoom the input YUV frame to the thumbnail size
1018 * Based on the following logic:
1019 * 1) Square pixels come in, square pixels come out, therefore single
1020 * scale factor is computed to either make input bigger or smaller
1021 * depending on if we are upscaling or downscaling
1022 * 2) That single scale factor would either make height too tall or width
1023 * too wide so we need to crop the input either horizontally or vertically
1024 * but not both
1025 */
1026
1027 /* Convert the input and output dimensions into floats for ease of math */
1028 float fWin = static_cast<float>(inSz.width);
1029 float fHin = static_cast<float>(inSz.height);
1030 float fWout = static_cast<float>(outSz.width);
1031 float fHout = static_cast<float>(outSz.height);
1032
1033 /* Compute the one scale factor from (1) above, it will be the smaller of
1034 * the two possibilities. */
1035 float scaleFactor = std::min( fHin / fHout, fWin / fWout );
1036
1037 /* Since we are crop-and-zooming (as opposed to letter/pillar boxing) we can
1038 * simply multiply the output by our scaleFactor to get the cropped input
1039 * size. Note that at least one of {fWcrop, fHcrop} is going to wind up
1040 * being {fWin, fHin} respectively because fHout or fWout cancels out the
1041 * scaleFactor calculation above.
1042 *
1043 * Specifically:
1044 * if ( fHin / fHout ) < ( fWin / fWout ) we crop the sides off
1045 * input, in which case
1046 * scaleFactor = fHin / fHout
1047 * fWcrop = fHin / fHout * fWout
1048 * fHcrop = fHin
1049 *
1050 * Note that fWcrop <= fWin ( because ( fHin / fHout ) * fWout < fWin, which
1051 * is just the inequality above with both sides multiplied by fWout
1052 *
1053 * on the other hand if ( fWin / fWout ) < ( fHin / fHout) we crop the top
1054 * and the bottom off of input, and
1055 * scaleFactor = fWin / fWout
1056 * fWcrop = fWin
1057 * fHCrop = fWin / fWout * fHout
1058 */
1059 float fWcrop = scaleFactor * fWout;
1060 float fHcrop = scaleFactor * fHout;
1061
1062 /* Convert to integer and truncate to an even number */
1063 Size cropSz = { 2*static_cast<uint32_t>(fWcrop/2.0f),
1064 2*static_cast<uint32_t>(fHcrop/2.0f) };
1065
1066 /* Convert to a centered rectange with even top/left */
1067 IMapper::Rect inputCrop {
1068 2*static_cast<int32_t>((inSz.width - cropSz.width)/4),
1069 2*static_cast<int32_t>((inSz.height - cropSz.height)/4),
1070 static_cast<int32_t>(cropSz.width),
1071 static_cast<int32_t>(cropSz.height) };
1072
1073 if ((inputCrop.top < 0) ||
1074 (inputCrop.top >= static_cast<int32_t>(inSz.height)) ||
1075 (inputCrop.left < 0) ||
1076 (inputCrop.left >= static_cast<int32_t>(inSz.width)) ||
1077 (inputCrop.width <= 0) ||
1078 (inputCrop.width + inputCrop.left > static_cast<int32_t>(inSz.width)) ||
1079 (inputCrop.height <= 0) ||
1080 (inputCrop.height + inputCrop.top > static_cast<int32_t>(inSz.height)))
1081 {
1082 ALOGE("%s: came up with really wrong crop rectangle",__FUNCTION__);
1083 ALOGE("%s: input layout %dx%d to for output size %dx%d",
1084 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1085 ALOGE("%s: computed input crop +%d,+%d %dx%d",
1086 __FUNCTION__, inputCrop.left, inputCrop.top,
1087 inputCrop.width, inputCrop.height);
1088 return -1;
1089 }
1090
1091 YCbCrLayout inputLayout;
1092 ret = in->getCroppedLayout(inputCrop, &inputLayout);
1093 if (ret != 0) {
1094 ALOGE("%s: failed to crop input layout %dx%d to for output size %dx%d",
1095 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1096 ALOGE("%s: computed input crop +%d,+%d %dx%d",
1097 __FUNCTION__, inputCrop.left, inputCrop.top,
1098 inputCrop.width, inputCrop.height);
1099 return ret;
1100 }
1101 ALOGV("%s: crop input layout %dx%d to for output size %dx%d",
1102 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1103 ALOGV("%s: computed input crop +%d,+%d %dx%d",
1104 __FUNCTION__, inputCrop.left, inputCrop.top,
1105 inputCrop.width, inputCrop.height);
1106
1107
1108 // Scale
1109 YCbCrLayout outFullLayout;
1110
1111 ret = mYu12ThumbFrame->getLayout(&outFullLayout);
1112 if (ret != 0) {
1113 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
1114 return ret;
1115 }
1116
1117
1118 ret = libyuv::I420Scale(
1119 static_cast<uint8_t*>(inputLayout.y),
1120 inputLayout.yStride,
1121 static_cast<uint8_t*>(inputLayout.cb),
1122 inputLayout.cStride,
1123 static_cast<uint8_t*>(inputLayout.cr),
1124 inputLayout.cStride,
1125 inputCrop.width,
1126 inputCrop.height,
1127 static_cast<uint8_t*>(outFullLayout.y),
1128 outFullLayout.yStride,
1129 static_cast<uint8_t*>(outFullLayout.cb),
1130 outFullLayout.cStride,
1131 static_cast<uint8_t*>(outFullLayout.cr),
1132 outFullLayout.cStride,
1133 outSz.width,
1134 outSz.height,
1135 libyuv::FilterMode::kFilterNone);
1136
1137 if (ret != 0) {
1138 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
1139 __FUNCTION__, inputCrop.width, inputCrop.height,
1140 outSz.width, outSz.height, ret);
1141 return ret;
1142 }
1143
1144 *out = outFullLayout;
1145 return 0;
1146}
1147
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001148int ExternalCameraDeviceSession::OutputThread::formatConvertLocked(
1149 const YCbCrLayout& in, const YCbCrLayout& out, Size sz, uint32_t format) {
1150 int ret = 0;
1151 switch (format) {
1152 case V4L2_PIX_FMT_NV21:
1153 ret = libyuv::I420ToNV21(
1154 static_cast<uint8_t*>(in.y),
1155 in.yStride,
1156 static_cast<uint8_t*>(in.cb),
1157 in.cStride,
1158 static_cast<uint8_t*>(in.cr),
1159 in.cStride,
1160 static_cast<uint8_t*>(out.y),
1161 out.yStride,
1162 static_cast<uint8_t*>(out.cr),
1163 out.cStride,
1164 sz.width,
1165 sz.height);
1166 if (ret != 0) {
1167 ALOGE("%s: convert to NV21 buffer failed! ret %d",
1168 __FUNCTION__, ret);
1169 return ret;
1170 }
1171 break;
1172 case V4L2_PIX_FMT_NV12:
1173 ret = libyuv::I420ToNV12(
1174 static_cast<uint8_t*>(in.y),
1175 in.yStride,
1176 static_cast<uint8_t*>(in.cb),
1177 in.cStride,
1178 static_cast<uint8_t*>(in.cr),
1179 in.cStride,
1180 static_cast<uint8_t*>(out.y),
1181 out.yStride,
1182 static_cast<uint8_t*>(out.cb),
1183 out.cStride,
1184 sz.width,
1185 sz.height);
1186 if (ret != 0) {
1187 ALOGE("%s: convert to NV12 buffer failed! ret %d",
1188 __FUNCTION__, ret);
1189 return ret;
1190 }
1191 break;
1192 case V4L2_PIX_FMT_YVU420: // YV12
1193 case V4L2_PIX_FMT_YUV420: // YU12
1194 // TODO: maybe we can speed up here by somehow save this copy?
1195 ret = libyuv::I420Copy(
1196 static_cast<uint8_t*>(in.y),
1197 in.yStride,
1198 static_cast<uint8_t*>(in.cb),
1199 in.cStride,
1200 static_cast<uint8_t*>(in.cr),
1201 in.cStride,
1202 static_cast<uint8_t*>(out.y),
1203 out.yStride,
1204 static_cast<uint8_t*>(out.cb),
1205 out.cStride,
1206 static_cast<uint8_t*>(out.cr),
1207 out.cStride,
1208 sz.width,
1209 sz.height);
1210 if (ret != 0) {
1211 ALOGE("%s: copy to YV12 or YU12 buffer failed! ret %d",
1212 __FUNCTION__, ret);
1213 return ret;
1214 }
1215 break;
1216 case FLEX_YUV_GENERIC:
1217 // TODO: b/72261744 write to arbitrary flexible YUV layout. Slow.
1218 ALOGE("%s: unsupported flexible yuv layout"
1219 " y %p cb %p cr %p y_str %d c_str %d c_step %d",
1220 __FUNCTION__, out.y, out.cb, out.cr,
1221 out.yStride, out.cStride, out.chromaStep);
1222 return -1;
1223 default:
1224 ALOGE("%s: unknown YUV format 0x%x!", __FUNCTION__, format);
1225 return -1;
1226 }
1227 return 0;
1228}
1229
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001230int ExternalCameraDeviceSession::OutputThread::encodeJpegYU12(
1231 const Size & inSz, const YCbCrLayout& inLayout,
1232 int jpegQuality, const void *app1Buffer, size_t app1Size,
1233 void *out, const size_t maxOutSize, size_t &actualCodeSize)
1234{
1235 /* libjpeg is a C library so we use C-style "inheritance" by
1236 * putting libjpeg's jpeg_destination_mgr first in our custom
1237 * struct. This allows us to cast jpeg_destination_mgr* to
1238 * CustomJpegDestMgr* when we get it passed to us in a callback */
1239 struct CustomJpegDestMgr {
1240 struct jpeg_destination_mgr mgr;
1241 JOCTET *mBuffer;
1242 size_t mBufferSize;
1243 size_t mEncodedSize;
1244 bool mSuccess;
1245 } dmgr;
1246
1247 jpeg_compress_struct cinfo = {};
1248 jpeg_error_mgr jerr;
1249
1250 /* Initialize error handling with standard callbacks, but
1251 * then override output_message (to print to ALOG) and
1252 * error_exit to set a flag and print a message instead
1253 * of killing the whole process */
1254 cinfo.err = jpeg_std_error(&jerr);
1255
1256 cinfo.err->output_message = [](j_common_ptr cinfo) {
1257 char buffer[JMSG_LENGTH_MAX];
1258
1259 /* Create the message */
1260 (*cinfo->err->format_message)(cinfo, buffer);
1261 ALOGE("libjpeg error: %s", buffer);
1262 };
1263 cinfo.err->error_exit = [](j_common_ptr cinfo) {
1264 (*cinfo->err->output_message)(cinfo);
1265 if(cinfo->client_data) {
1266 auto & dmgr =
1267 *reinterpret_cast<CustomJpegDestMgr*>(cinfo->client_data);
1268 dmgr.mSuccess = false;
1269 }
1270 };
1271 /* Now that we initialized some callbacks, let's create our compressor */
1272 jpeg_create_compress(&cinfo);
1273
1274 /* Initialize our destination manager */
1275 dmgr.mBuffer = static_cast<JOCTET*>(out);
1276 dmgr.mBufferSize = maxOutSize;
1277 dmgr.mEncodedSize = 0;
1278 dmgr.mSuccess = true;
1279 cinfo.client_data = static_cast<void*>(&dmgr);
1280
1281 /* These lambdas become C-style function pointers and as per C++11 spec
1282 * may not capture anything */
1283 dmgr.mgr.init_destination = [](j_compress_ptr cinfo) {
1284 auto & dmgr = reinterpret_cast<CustomJpegDestMgr&>(*cinfo->dest);
1285 dmgr.mgr.next_output_byte = dmgr.mBuffer;
1286 dmgr.mgr.free_in_buffer = dmgr.mBufferSize;
1287 ALOGV("%s:%d jpeg start: %p [%zu]",
1288 __FUNCTION__, __LINE__, dmgr.mBuffer, dmgr.mBufferSize);
1289 };
1290
1291 dmgr.mgr.empty_output_buffer = [](j_compress_ptr cinfo __unused) {
1292 ALOGV("%s:%d Out of buffer", __FUNCTION__, __LINE__);
1293 return 0;
1294 };
1295
1296 dmgr.mgr.term_destination = [](j_compress_ptr cinfo) {
1297 auto & dmgr = reinterpret_cast<CustomJpegDestMgr&>(*cinfo->dest);
1298 dmgr.mEncodedSize = dmgr.mBufferSize - dmgr.mgr.free_in_buffer;
1299 ALOGV("%s:%d Done with jpeg: %zu", __FUNCTION__, __LINE__, dmgr.mEncodedSize);
1300 };
1301 cinfo.dest = reinterpret_cast<struct jpeg_destination_mgr*>(&dmgr);
1302
1303 /* We are going to be using JPEG in raw data mode, so we are passing
1304 * straight subsampled planar YCbCr and it will not touch our pixel
1305 * data or do any scaling or anything */
1306 cinfo.image_width = inSz.width;
1307 cinfo.image_height = inSz.height;
1308 cinfo.input_components = 3;
1309 cinfo.in_color_space = JCS_YCbCr;
1310
1311 /* Initialize defaults and then override what we want */
1312 jpeg_set_defaults(&cinfo);
1313
1314 jpeg_set_quality(&cinfo, jpegQuality, 1);
1315 jpeg_set_colorspace(&cinfo, JCS_YCbCr);
1316 cinfo.raw_data_in = 1;
1317 cinfo.dct_method = JDCT_IFAST;
1318
1319 /* Configure sampling factors. The sampling factor is JPEG subsampling 420
1320 * because the source format is YUV420. Note that libjpeg sampling factors
1321 * are... a little weird. Sampling of Y=2,U=1,V=1 means there is 1 U and
1322 * 1 V value for each 2 Y values */
1323 cinfo.comp_info[0].h_samp_factor = 2;
1324 cinfo.comp_info[0].v_samp_factor = 2;
1325 cinfo.comp_info[1].h_samp_factor = 1;
1326 cinfo.comp_info[1].v_samp_factor = 1;
1327 cinfo.comp_info[2].h_samp_factor = 1;
1328 cinfo.comp_info[2].v_samp_factor = 1;
1329
1330 /* Let's not hardcode YUV420 in 6 places... 5 was enough */
1331 int maxVSampFactor = std::max( {
1332 cinfo.comp_info[0].v_samp_factor,
1333 cinfo.comp_info[1].v_samp_factor,
1334 cinfo.comp_info[2].v_samp_factor
1335 });
1336 int cVSubSampling = cinfo.comp_info[0].v_samp_factor /
1337 cinfo.comp_info[1].v_samp_factor;
1338
1339 /* Start the compressor */
1340 jpeg_start_compress(&cinfo, TRUE);
1341
1342 /* Compute our macroblock height, so we can pad our input to be vertically
1343 * macroblock aligned.
1344 * TODO: Does it need to be horizontally MCU aligned too? */
1345
1346 size_t mcuV = DCTSIZE*maxVSampFactor;
1347 size_t paddedHeight = mcuV * ((inSz.height + mcuV - 1) / mcuV);
1348
1349 /* libjpeg uses arrays of row pointers, which makes it really easy to pad
1350 * data vertically (unfortunately doesn't help horizontally) */
1351 std::vector<JSAMPROW> yLines (paddedHeight);
1352 std::vector<JSAMPROW> cbLines(paddedHeight/cVSubSampling);
1353 std::vector<JSAMPROW> crLines(paddedHeight/cVSubSampling);
1354
1355 uint8_t *py = static_cast<uint8_t*>(inLayout.y);
1356 uint8_t *pcr = static_cast<uint8_t*>(inLayout.cr);
1357 uint8_t *pcb = static_cast<uint8_t*>(inLayout.cb);
1358
1359 for(uint32_t i = 0; i < paddedHeight; i++)
1360 {
1361 /* Once we are in the padding territory we still point to the last line
1362 * effectively replicating it several times ~ CLAMP_TO_EDGE */
1363 int li = std::min(i, inSz.height - 1);
1364 yLines[i] = static_cast<JSAMPROW>(py + li * inLayout.yStride);
1365 if(i < paddedHeight / cVSubSampling)
1366 {
1367 crLines[i] = static_cast<JSAMPROW>(pcr + li * inLayout.cStride);
1368 cbLines[i] = static_cast<JSAMPROW>(pcb + li * inLayout.cStride);
1369 }
1370 }
1371
1372 /* If APP1 data was passed in, use it */
1373 if(app1Buffer && app1Size)
1374 {
1375 jpeg_write_marker(&cinfo, JPEG_APP0 + 1,
1376 static_cast<const JOCTET*>(app1Buffer), app1Size);
1377 }
1378
1379 /* While we still have padded height left to go, keep giving it one
1380 * macroblock at a time. */
1381 while (cinfo.next_scanline < cinfo.image_height) {
1382 const uint32_t batchSize = DCTSIZE * maxVSampFactor;
1383 const uint32_t nl = cinfo.next_scanline;
1384 JSAMPARRAY planes[3]{ &yLines[nl],
1385 &cbLines[nl/cVSubSampling],
1386 &crLines[nl/cVSubSampling] };
1387
1388 uint32_t done = jpeg_write_raw_data(&cinfo, planes, batchSize);
1389
1390 if (done != batchSize) {
1391 ALOGE("%s: compressed %u lines, expected %u (total %u/%u)",
1392 __FUNCTION__, done, batchSize, cinfo.next_scanline,
1393 cinfo.image_height);
1394 return -1;
1395 }
1396 }
1397
1398 /* This will flush everything */
1399 jpeg_finish_compress(&cinfo);
1400
1401 /* Grab the actual code size and set it */
1402 actualCodeSize = dmgr.mEncodedSize;
1403
1404 return 0;
1405}
1406
1407/*
1408 * TODO: There needs to be a mechanism to discover allocated buffer size
1409 * in the HAL.
1410 *
1411 * This is very fragile because it is duplicated computation from:
1412 * frameworks/av/services/camera/libcameraservice/device3/Camera3Device.cpp
1413 *
1414 */
1415
1416/* This assumes mSupportedFormats have all been declared as supporting
1417 * HAL_PIXEL_FORMAT_BLOB to the framework */
1418Size ExternalCameraDeviceSession::getMaxJpegResolution() const {
1419 Size ret { 0, 0 };
1420 for(auto & fmt : mSupportedFormats) {
1421 if(fmt.width * fmt.height > ret.width * ret.height) {
1422 ret = Size { fmt.width, fmt.height };
1423 }
1424 }
1425 return ret;
1426}
1427
1428Size ExternalCameraDeviceSession::getMaxThumbResolution() const {
1429 Size thumbSize { 0, 0 };
1430 camera_metadata_ro_entry entry =
1431 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
1432 for(uint32_t i = 0; i < entry.count; i += 2) {
1433 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
1434 static_cast<uint32_t>(entry.data.i32[i+1]) };
1435 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
1436 thumbSize = sz;
1437 }
1438 }
1439
1440 if (thumbSize.width * thumbSize.height == 0) {
1441 ALOGW("%s: non-zero thumbnail size not available", __FUNCTION__);
1442 }
1443
1444 return thumbSize;
1445}
1446
1447
1448ssize_t ExternalCameraDeviceSession::getJpegBufferSize(
1449 uint32_t width, uint32_t height) const {
1450 // Constant from camera3.h
1451 const ssize_t kMinJpegBufferSize = 256 * 1024 + sizeof(CameraBlob);
1452 // Get max jpeg size (area-wise).
1453 if (mMaxJpegResolution.width == 0) {
1454 ALOGE("%s: Do not have a single supported JPEG stream",
1455 __FUNCTION__);
1456 return BAD_VALUE;
1457 }
1458
1459 // Get max jpeg buffer size
1460 ssize_t maxJpegBufferSize = 0;
1461 camera_metadata_ro_entry jpegBufMaxSize =
1462 mCameraCharacteristics.find(ANDROID_JPEG_MAX_SIZE);
1463 if (jpegBufMaxSize.count == 0) {
1464 ALOGE("%s: Can't find maximum JPEG size in static metadata!",
1465 __FUNCTION__);
1466 return BAD_VALUE;
1467 }
1468 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
1469
1470 if (maxJpegBufferSize <= kMinJpegBufferSize) {
1471 ALOGE("%s: ANDROID_JPEG_MAX_SIZE (%zd) <= kMinJpegBufferSize (%zd)",
1472 __FUNCTION__, maxJpegBufferSize, kMinJpegBufferSize);
1473 return BAD_VALUE;
1474 }
1475
1476 // Calculate final jpeg buffer size for the given resolution.
1477 float scaleFactor = ((float) (width * height)) /
1478 (mMaxJpegResolution.width * mMaxJpegResolution.height);
1479 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
1480 kMinJpegBufferSize;
1481 if (jpegBufferSize > maxJpegBufferSize) {
1482 jpegBufferSize = maxJpegBufferSize;
1483 }
1484
1485 return jpegBufferSize;
1486}
1487
1488int ExternalCameraDeviceSession::OutputThread::createJpegLocked(
1489 HalStreamBuffer &halBuf,
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001490 const std::shared_ptr<HalRequest>& req)
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001491{
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001492 ATRACE_CALL();
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001493 int ret;
1494 auto lfail = [&](auto... args) {
1495 ALOGE(args...);
1496
1497 return 1;
1498 };
1499 auto parent = mParent.promote();
1500 if (parent == nullptr) {
1501 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1502 return 1;
1503 }
1504
1505 ALOGV("%s: HAL buffer sid: %d bid: %" PRIu64 " w: %u h: %u",
1506 __FUNCTION__, halBuf.streamId, static_cast<uint64_t>(halBuf.bufferId),
1507 halBuf.width, halBuf.height);
1508 ALOGV("%s: HAL buffer fmt: %x usage: %" PRIx64 " ptr: %p",
1509 __FUNCTION__, halBuf.format, static_cast<uint64_t>(halBuf.usage),
1510 halBuf.bufPtr);
1511 ALOGV("%s: YV12 buffer %d x %d",
1512 __FUNCTION__,
1513 mYu12Frame->mWidth, mYu12Frame->mHeight);
1514
1515 int jpegQuality, thumbQuality;
1516 Size thumbSize;
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001517 bool outputThumbnail = true;
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001518
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001519 if (req->setting.exists(ANDROID_JPEG_QUALITY)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001520 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001521 req->setting.find(ANDROID_JPEG_QUALITY);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001522 jpegQuality = entry.data.u8[0];
1523 } else {
1524 return lfail("%s: ANDROID_JPEG_QUALITY not set",__FUNCTION__);
1525 }
1526
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001527 if (req->setting.exists(ANDROID_JPEG_THUMBNAIL_QUALITY)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001528 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001529 req->setting.find(ANDROID_JPEG_THUMBNAIL_QUALITY);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001530 thumbQuality = entry.data.u8[0];
1531 } else {
1532 return lfail(
1533 "%s: ANDROID_JPEG_THUMBNAIL_QUALITY not set",
1534 __FUNCTION__);
1535 }
1536
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001537 if (req->setting.exists(ANDROID_JPEG_THUMBNAIL_SIZE)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001538 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001539 req->setting.find(ANDROID_JPEG_THUMBNAIL_SIZE);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001540 thumbSize = Size { static_cast<uint32_t>(entry.data.i32[0]),
1541 static_cast<uint32_t>(entry.data.i32[1])
1542 };
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001543 if (thumbSize.width == 0 && thumbSize.height == 0) {
1544 outputThumbnail = false;
1545 }
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001546 } else {
1547 return lfail(
1548 "%s: ANDROID_JPEG_THUMBNAIL_SIZE not set", __FUNCTION__);
1549 }
1550
1551 /* Cropped and scaled YU12 buffer for main and thumbnail */
1552 YCbCrLayout yu12Main;
1553 Size jpegSize { halBuf.width, halBuf.height };
1554
1555 /* Compute temporary buffer sizes accounting for the following:
1556 * thumbnail can't exceed APP1 size of 64K
1557 * main image needs to hold APP1, headers, and at most a poorly
1558 * compressed image */
1559 const ssize_t maxThumbCodeSize = 64 * 1024;
1560 const ssize_t maxJpegCodeSize = parent->getJpegBufferSize(jpegSize.width,
1561 jpegSize.height);
1562
1563 /* Check that getJpegBufferSize did not return an error */
1564 if (maxJpegCodeSize < 0) {
1565 return lfail(
1566 "%s: getJpegBufferSize returned %zd",__FUNCTION__,maxJpegCodeSize);
1567 }
1568
1569
1570 /* Hold actual thumbnail and main image code sizes */
1571 size_t thumbCodeSize = 0, jpegCodeSize = 0;
1572 /* Temporary thumbnail code buffer */
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001573 std::vector<uint8_t> thumbCode(outputThumbnail ? maxThumbCodeSize : 0);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001574
1575 YCbCrLayout yu12Thumb;
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001576 if (outputThumbnail) {
1577 ret = cropAndScaleThumbLocked(mYu12Frame, thumbSize, &yu12Thumb);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001578
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001579 if (ret != 0) {
1580 return lfail(
1581 "%s: crop and scale thumbnail failed!", __FUNCTION__);
1582 }
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001583 }
1584
1585 /* Scale and crop main jpeg */
1586 ret = cropAndScaleLocked(mYu12Frame, jpegSize, &yu12Main);
1587
1588 if (ret != 0) {
1589 return lfail("%s: crop and scale main failed!", __FUNCTION__);
1590 }
1591
1592 /* Encode the thumbnail image */
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001593 if (outputThumbnail) {
1594 ret = encodeJpegYU12(thumbSize, yu12Thumb,
1595 thumbQuality, 0, 0,
1596 &thumbCode[0], maxThumbCodeSize, thumbCodeSize);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001597
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001598 if (ret != 0) {
1599 return lfail("%s: thumbnail encodeJpegYU12 failed with %d",__FUNCTION__, ret);
1600 }
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001601 }
1602
1603 /* Combine camera characteristics with request settings to form EXIF
1604 * metadata */
1605 common::V1_0::helper::CameraMetadata meta(parent->mCameraCharacteristics);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001606 meta.append(req->setting);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001607
1608 /* Generate EXIF object */
1609 std::unique_ptr<ExifUtils> utils(ExifUtils::create());
1610 /* Make sure it's initialized */
1611 utils->initialize();
1612
1613 utils->setFromMetadata(meta, jpegSize.width, jpegSize.height);
1614
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001615 ret = utils->generateApp1(outputThumbnail ? &thumbCode[0] : 0, thumbCodeSize);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001616
1617 if (!ret) {
1618 return lfail("%s: generating APP1 failed", __FUNCTION__);
1619 }
1620
1621 /* Get internal buffer */
1622 size_t exifDataSize = utils->getApp1Length();
1623 const uint8_t* exifData = utils->getApp1Buffer();
1624
1625 /* Lock the HAL jpeg code buffer */
1626 void *bufPtr = sHandleImporter.lock(
1627 *(halBuf.bufPtr), halBuf.usage, maxJpegCodeSize);
1628
1629 if (!bufPtr) {
1630 return lfail("%s: could not lock %zu bytes", __FUNCTION__, maxJpegCodeSize);
1631 }
1632
1633 /* Encode the main jpeg image */
1634 ret = encodeJpegYU12(jpegSize, yu12Main,
1635 jpegQuality, exifData, exifDataSize,
1636 bufPtr, maxJpegCodeSize, jpegCodeSize);
1637
1638 /* TODO: Not sure this belongs here, maybe better to pass jpegCodeSize out
1639 * and do this when returning buffer to parent */
1640 CameraBlob blob { CameraBlobId::JPEG, static_cast<uint32_t>(jpegCodeSize) };
1641 void *blobDst =
1642 reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(bufPtr) +
1643 maxJpegCodeSize -
1644 sizeof(CameraBlob));
1645 memcpy(blobDst, &blob, sizeof(CameraBlob));
1646
1647 /* Unlock the HAL jpeg code buffer */
1648 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
1649 if (relFence > 0) {
1650 halBuf.acquireFence = relFence;
1651 }
1652
1653 /* Check if our JPEG actually succeeded */
1654 if (ret != 0) {
1655 return lfail(
1656 "%s: encodeJpegYU12 failed with %d",__FUNCTION__, ret);
1657 }
1658
1659 ALOGV("%s: encoded JPEG (ret:%d) with Q:%d max size: %zu",
1660 __FUNCTION__, ret, jpegQuality, maxJpegCodeSize);
1661
1662 return 0;
1663}
1664
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001665bool ExternalCameraDeviceSession::OutputThread::threadLoop() {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001666 std::shared_ptr<HalRequest> req;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001667 auto parent = mParent.promote();
1668 if (parent == nullptr) {
1669 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1670 return false;
1671 }
1672
1673 // TODO: maybe we need to setup a sensor thread to dq/enq v4l frames
1674 // regularly to prevent v4l buffer queue filled with stale buffers
1675 // when app doesn't program a preveiw request
1676 waitForNextRequest(&req);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001677 if (req == nullptr) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001678 // No new request, wait again
1679 return true;
1680 }
1681
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001682 auto onDeviceError = [&](auto... args) {
1683 ALOGE(args...);
1684 parent->notifyError(
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001685 req->frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001686 signalRequestDone();
1687 return false;
1688 };
1689
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001690 if (req->frameIn->mFourcc != V4L2_PIX_FMT_MJPEG) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001691 return onDeviceError("%s: do not support V4L2 format %c%c%c%c", __FUNCTION__,
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001692 req->frameIn->mFourcc & 0xFF,
1693 (req->frameIn->mFourcc >> 8) & 0xFF,
1694 (req->frameIn->mFourcc >> 16) & 0xFF,
1695 (req->frameIn->mFourcc >> 24) & 0xFF);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001696 }
1697
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001698 std::unique_lock<std::mutex> lk(mBufferLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001699 // Convert input V4L2 frame to YU12 of the same size
1700 // TODO: see if we can save some computation by converting to YV12 here
1701 uint8_t* inData;
1702 size_t inDataSize;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001703 req->frameIn->map(&inData, &inDataSize);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001704 // TODO: in some special case maybe we can decode jpg directly to gralloc output?
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001705 ATRACE_BEGIN("MJPGtoI420");
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001706 int res = libyuv::MJPGToI420(
1707 inData, inDataSize,
1708 static_cast<uint8_t*>(mYu12FrameLayout.y),
1709 mYu12FrameLayout.yStride,
1710 static_cast<uint8_t*>(mYu12FrameLayout.cb),
1711 mYu12FrameLayout.cStride,
1712 static_cast<uint8_t*>(mYu12FrameLayout.cr),
1713 mYu12FrameLayout.cStride,
1714 mYu12Frame->mWidth, mYu12Frame->mHeight,
1715 mYu12Frame->mWidth, mYu12Frame->mHeight);
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001716 ATRACE_END();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001717
1718 if (res != 0) {
1719 // For some webcam, the first few V4L2 frames might be malformed...
1720 ALOGE("%s: Convert V4L2 frame to YU12 failed! res %d", __FUNCTION__, res);
1721 lk.unlock();
1722 Status st = parent->processCaptureRequestError(req);
1723 if (st != Status::OK) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001724 return onDeviceError("%s: failed to process capture request error!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001725 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001726 signalRequestDone();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001727 return true;
1728 }
1729
1730 ALOGV("%s processing new request", __FUNCTION__);
1731 const int kSyncWaitTimeoutMs = 500;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001732 for (auto& halBuf : req->buffers) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001733 if (halBuf.acquireFence != -1) {
1734 int ret = sync_wait(halBuf.acquireFence, kSyncWaitTimeoutMs);
1735 if (ret) {
1736 halBuf.fenceTimeout = true;
1737 } else {
1738 ::close(halBuf.acquireFence);
Yin-Chia Yeh1e089662018-02-02 15:57:58 -08001739 halBuf.acquireFence = -1;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001740 }
1741 }
1742
1743 if (halBuf.fenceTimeout) {
1744 continue;
1745 }
1746
1747 // Gralloc lockYCbCr the buffer
1748 switch (halBuf.format) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001749 case PixelFormat::BLOB: {
1750 int ret = createJpegLocked(halBuf, req);
1751
1752 if(ret != 0) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001753 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001754 return onDeviceError("%s: createJpegLocked failed with %d",
1755 __FUNCTION__, ret);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001756 }
1757 } break;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001758 case PixelFormat::YCBCR_420_888:
1759 case PixelFormat::YV12: {
1760 IMapper::Rect outRect {0, 0,
1761 static_cast<int32_t>(halBuf.width),
1762 static_cast<int32_t>(halBuf.height)};
1763 YCbCrLayout outLayout = sHandleImporter.lockYCbCr(
1764 *(halBuf.bufPtr), halBuf.usage, outRect);
1765 ALOGV("%s: outLayout y %p cb %p cr %p y_str %d c_str %d c_step %d",
1766 __FUNCTION__, outLayout.y, outLayout.cb, outLayout.cr,
1767 outLayout.yStride, outLayout.cStride, outLayout.chromaStep);
1768
1769 // Convert to output buffer size/format
1770 uint32_t outputFourcc = getFourCcFromLayout(outLayout);
1771 ALOGV("%s: converting to format %c%c%c%c", __FUNCTION__,
1772 outputFourcc & 0xFF,
1773 (outputFourcc >> 8) & 0xFF,
1774 (outputFourcc >> 16) & 0xFF,
1775 (outputFourcc >> 24) & 0xFF);
1776
1777 YCbCrLayout cropAndScaled;
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001778 ATRACE_BEGIN("cropAndScaleLocked");
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001779 int ret = cropAndScaleLocked(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001780 mYu12Frame,
1781 Size { halBuf.width, halBuf.height },
1782 &cropAndScaled);
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001783 ATRACE_END();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001784 if (ret != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001785 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001786 return onDeviceError("%s: crop and scale failed!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001787 }
1788
1789 Size sz {halBuf.width, halBuf.height};
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001790 ATRACE_BEGIN("formatConvertLocked");
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001791 ret = formatConvertLocked(cropAndScaled, outLayout, sz, outputFourcc);
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001792 ATRACE_END();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001793 if (ret != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001794 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001795 return onDeviceError("%s: format coversion failed!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001796 }
1797 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
1798 if (relFence > 0) {
1799 halBuf.acquireFence = relFence;
1800 }
1801 } break;
1802 default:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001803 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001804 return onDeviceError("%s: unknown output format %x", __FUNCTION__, halBuf.format);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001805 }
1806 } // for each buffer
1807 mScaledYu12Frames.clear();
1808
1809 // Don't hold the lock while calling back to parent
1810 lk.unlock();
1811 Status st = parent->processCaptureResult(req);
1812 if (st != Status::OK) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001813 return onDeviceError("%s: failed to process capture result!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001814 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001815 signalRequestDone();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001816 return true;
1817}
1818
1819Status ExternalCameraDeviceSession::OutputThread::allocateIntermediateBuffers(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001820 const Size& v4lSize, const Size& thumbSize,
1821 const hidl_vec<Stream>& streams) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001822 std::lock_guard<std::mutex> lk(mBufferLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001823 if (mScaledYu12Frames.size() != 0) {
1824 ALOGE("%s: intermediate buffer pool has %zu inflight buffers! (expect 0)",
1825 __FUNCTION__, mScaledYu12Frames.size());
1826 return Status::INTERNAL_ERROR;
1827 }
1828
1829 // Allocating intermediate YU12 frame
1830 if (mYu12Frame == nullptr || mYu12Frame->mWidth != v4lSize.width ||
1831 mYu12Frame->mHeight != v4lSize.height) {
1832 mYu12Frame.clear();
1833 mYu12Frame = new AllocatedFrame(v4lSize.width, v4lSize.height);
1834 int ret = mYu12Frame->allocate(&mYu12FrameLayout);
1835 if (ret != 0) {
1836 ALOGE("%s: allocating YU12 frame failed!", __FUNCTION__);
1837 return Status::INTERNAL_ERROR;
1838 }
1839 }
1840
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001841 // Allocating intermediate YU12 thumbnail frame
1842 if (mYu12ThumbFrame == nullptr ||
1843 mYu12ThumbFrame->mWidth != thumbSize.width ||
1844 mYu12ThumbFrame->mHeight != thumbSize.height) {
1845 mYu12ThumbFrame.clear();
1846 mYu12ThumbFrame = new AllocatedFrame(thumbSize.width, thumbSize.height);
1847 int ret = mYu12ThumbFrame->allocate(&mYu12ThumbFrameLayout);
1848 if (ret != 0) {
1849 ALOGE("%s: allocating YU12 thumb frame failed!", __FUNCTION__);
1850 return Status::INTERNAL_ERROR;
1851 }
1852 }
1853
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001854 // Allocating scaled buffers
1855 for (const auto& stream : streams) {
1856 Size sz = {stream.width, stream.height};
1857 if (sz == v4lSize) {
1858 continue; // Don't need an intermediate buffer same size as v4lBuffer
1859 }
1860 if (mIntermediateBuffers.count(sz) == 0) {
1861 // Create new intermediate buffer
1862 sp<AllocatedFrame> buf = new AllocatedFrame(stream.width, stream.height);
1863 int ret = buf->allocate();
1864 if (ret != 0) {
1865 ALOGE("%s: allocating intermediate YU12 frame %dx%d failed!",
1866 __FUNCTION__, stream.width, stream.height);
1867 return Status::INTERNAL_ERROR;
1868 }
1869 mIntermediateBuffers[sz] = buf;
1870 }
1871 }
1872
1873 // Remove unconfigured buffers
1874 auto it = mIntermediateBuffers.begin();
1875 while (it != mIntermediateBuffers.end()) {
1876 bool configured = false;
1877 auto sz = it->first;
1878 for (const auto& stream : streams) {
1879 if (stream.width == sz.width && stream.height == sz.height) {
1880 configured = true;
1881 break;
1882 }
1883 }
1884 if (configured) {
1885 it++;
1886 } else {
1887 it = mIntermediateBuffers.erase(it);
1888 }
1889 }
1890 return Status::OK;
1891}
1892
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001893Status ExternalCameraDeviceSession::OutputThread::submitRequest(
1894 const std::shared_ptr<HalRequest>& req) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001895 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001896 mRequestList.push_back(req);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001897 lk.unlock();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001898 mRequestCond.notify_one();
1899 return Status::OK;
1900}
1901
1902void ExternalCameraDeviceSession::OutputThread::flush() {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001903 ATRACE_CALL();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001904 auto parent = mParent.promote();
1905 if (parent == nullptr) {
1906 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1907 return;
1908 }
1909
1910 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001911 std::list<std::shared_ptr<HalRequest>> reqs = std::move(mRequestList);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001912 mRequestList.clear();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001913 if (mProcessingRequest) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001914 std::chrono::seconds timeout = std::chrono::seconds(kFlushWaitTimeoutSec);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001915 auto st = mRequestDoneCond.wait_for(lk, timeout);
1916 if (st == std::cv_status::timeout) {
1917 ALOGE("%s: wait for inflight request finish timeout!", __FUNCTION__);
1918 }
1919 }
1920
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001921 ALOGV("%s: flusing inflight requests", __FUNCTION__);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001922 lk.unlock();
1923 for (const auto& req : reqs) {
1924 parent->processCaptureRequestError(req);
1925 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001926}
1927
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001928void ExternalCameraDeviceSession::OutputThread::waitForNextRequest(
1929 std::shared_ptr<HalRequest>* out) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001930 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001931 if (out == nullptr) {
1932 ALOGE("%s: out is null", __FUNCTION__);
1933 return;
1934 }
1935
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001936 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001937 int waitTimes = 0;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001938 while (mRequestList.empty()) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001939 if (exitPending()) {
1940 return;
1941 }
1942 std::chrono::milliseconds timeout = std::chrono::milliseconds(kReqWaitTimeoutMs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001943 auto st = mRequestCond.wait_for(lk, timeout);
1944 if (st == std::cv_status::timeout) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001945 waitTimes++;
1946 if (waitTimes == kReqWaitTimesMax) {
1947 // no new request, return
1948 return;
1949 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001950 }
1951 }
1952 *out = mRequestList.front();
1953 mRequestList.pop_front();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001954 mProcessingRequest = true;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001955 mProcessingFrameNumer = (*out)->frameNumber;
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001956}
1957
1958void ExternalCameraDeviceSession::OutputThread::signalRequestDone() {
1959 std::unique_lock<std::mutex> lk(mRequestListLock);
1960 mProcessingRequest = false;
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001961 mProcessingFrameNumer = 0;
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001962 lk.unlock();
1963 mRequestDoneCond.notify_one();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001964}
1965
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001966void ExternalCameraDeviceSession::OutputThread::dump(int fd) {
1967 std::lock_guard<std::mutex> lk(mRequestListLock);
1968 if (mProcessingRequest) {
1969 dprintf(fd, "OutputThread processing frame %d\n", mProcessingFrameNumer);
1970 } else {
1971 dprintf(fd, "OutputThread not processing any frames\n");
1972 }
1973 dprintf(fd, "OutputThread request list contains frame: ");
1974 for (const auto& req : mRequestList) {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001975 dprintf(fd, "%d, ", req->frameNumber);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001976 }
1977 dprintf(fd, "\n");
1978}
1979
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001980void ExternalCameraDeviceSession::cleanupBuffersLocked(int id) {
1981 for (auto& pair : mCirculatingBuffers.at(id)) {
1982 sHandleImporter.freeBuffer(pair.second);
1983 }
1984 mCirculatingBuffers[id].clear();
1985 mCirculatingBuffers.erase(id);
1986}
1987
1988void ExternalCameraDeviceSession::updateBufferCaches(const hidl_vec<BufferCache>& cachesToRemove) {
1989 Mutex::Autolock _l(mLock);
1990 for (auto& cache : cachesToRemove) {
1991 auto cbsIt = mCirculatingBuffers.find(cache.streamId);
1992 if (cbsIt == mCirculatingBuffers.end()) {
1993 // The stream could have been removed
1994 continue;
1995 }
1996 CirculatingBuffers& cbs = cbsIt->second;
1997 auto it = cbs.find(cache.bufferId);
1998 if (it != cbs.end()) {
1999 sHandleImporter.freeBuffer(it->second);
2000 cbs.erase(it);
2001 } else {
2002 ALOGE("%s: stream %d buffer %" PRIu64 " is not cached",
2003 __FUNCTION__, cache.streamId, cache.bufferId);
2004 }
2005 }
2006}
2007
2008bool ExternalCameraDeviceSession::isSupported(const Stream& stream) {
2009 int32_t ds = static_cast<int32_t>(stream.dataSpace);
2010 PixelFormat fmt = stream.format;
2011 uint32_t width = stream.width;
2012 uint32_t height = stream.height;
2013 // TODO: check usage flags
2014
2015 if (stream.streamType != StreamType::OUTPUT) {
2016 ALOGE("%s: does not support non-output stream type", __FUNCTION__);
2017 return false;
2018 }
2019
2020 if (stream.rotation != StreamRotation::ROTATION_0) {
2021 ALOGE("%s: does not support stream rotation", __FUNCTION__);
2022 return false;
2023 }
2024
2025 if (ds & Dataspace::DEPTH) {
2026 ALOGI("%s: does not support depth output", __FUNCTION__);
2027 return false;
2028 }
2029
2030 switch (fmt) {
2031 case PixelFormat::BLOB:
2032 if (ds != static_cast<int32_t>(Dataspace::V0_JFIF)) {
2033 ALOGI("%s: BLOB format does not support dataSpace %x", __FUNCTION__, ds);
2034 return false;
2035 }
2036 case PixelFormat::IMPLEMENTATION_DEFINED:
2037 case PixelFormat::YCBCR_420_888:
2038 case PixelFormat::YV12:
2039 // TODO: check what dataspace we can support here.
2040 // intentional no-ops.
2041 break;
2042 default:
2043 ALOGI("%s: does not support format %x", __FUNCTION__, fmt);
2044 return false;
2045 }
2046
2047 // Assume we can convert any V4L2 format to any of supported output format for now, i.e,
2048 // ignoring v4l2Fmt.fourcc for now. Might need more subtle check if we support more v4l format
2049 // in the futrue.
2050 for (const auto& v4l2Fmt : mSupportedFormats) {
2051 if (width == v4l2Fmt.width && height == v4l2Fmt.height) {
2052 return true;
2053 }
2054 }
2055 ALOGI("%s: resolution %dx%d is not supported", __FUNCTION__, width, height);
2056 return false;
2057}
2058
2059int ExternalCameraDeviceSession::v4l2StreamOffLocked() {
2060 if (!mV4l2Streaming) {
2061 return OK;
2062 }
2063
2064 {
2065 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2066 if (mNumDequeuedV4l2Buffers != 0) {
2067 ALOGE("%s: there are %zu inflight V4L buffers",
2068 __FUNCTION__, mNumDequeuedV4l2Buffers);
2069 return -1;
2070 }
2071 }
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002072 mV4L2BufferCount = 0;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002073
2074 // VIDIOC_STREAMOFF
2075 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2076 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMOFF, &capture_type)) < 0) {
2077 ALOGE("%s: STREAMOFF failed: %s", __FUNCTION__, strerror(errno));
2078 return -errno;
2079 }
2080
2081 // VIDIOC_REQBUFS: clear buffers
2082 v4l2_requestbuffers req_buffers{};
2083 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2084 req_buffers.memory = V4L2_MEMORY_MMAP;
2085 req_buffers.count = 0;
2086 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
2087 ALOGE("%s: REQBUFS failed: %s", __FUNCTION__, strerror(errno));
2088 return -errno;
2089 }
2090
2091 mV4l2Streaming = false;
2092 return OK;
2093}
2094
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002095int ExternalCameraDeviceSession::setV4l2FpsLocked(double fps) {
2096 // VIDIOC_G_PARM/VIDIOC_S_PARM: set fps
2097 v4l2_streamparm streamparm = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
2098 // The following line checks that the driver knows about framerate get/set.
2099 int ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_G_PARM, &streamparm));
2100 if (ret != 0) {
2101 if (errno == -EINVAL) {
2102 ALOGW("%s: device does not support VIDIOC_G_PARM", __FUNCTION__);
2103 }
2104 return -errno;
2105 }
2106 // Now check if the device is able to accept a capture framerate set.
2107 if (!(streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME)) {
2108 ALOGW("%s: device does not support V4L2_CAP_TIMEPERFRAME", __FUNCTION__);
2109 return -EINVAL;
2110 }
2111
2112 // fps is float, approximate by a fraction.
2113 const int kFrameRatePrecision = 10000;
2114 streamparm.parm.capture.timeperframe.numerator = kFrameRatePrecision;
2115 streamparm.parm.capture.timeperframe.denominator =
2116 (fps * kFrameRatePrecision);
2117
2118 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_PARM, &streamparm)) < 0) {
2119 ALOGE("%s: failed to set framerate to %f: %s", __FUNCTION__, fps, strerror(errno));
2120 return -1;
2121 }
2122
2123 double retFps = streamparm.parm.capture.timeperframe.denominator /
2124 static_cast<double>(streamparm.parm.capture.timeperframe.numerator);
2125 if (std::fabs(fps - retFps) > 1.0) {
2126 ALOGE("%s: expect fps %f, got %f instead", __FUNCTION__, fps, retFps);
2127 return -1;
2128 }
2129 mV4l2StreamingFps = fps;
2130 return 0;
2131}
2132
2133int ExternalCameraDeviceSession::configureV4l2StreamLocked(
2134 const SupportedV4L2Format& v4l2Fmt, double requestFps) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002135 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002136 int ret = v4l2StreamOffLocked();
2137 if (ret != OK) {
2138 ALOGE("%s: stop v4l2 streaming failed: ret %d", __FUNCTION__, ret);
2139 return ret;
2140 }
2141
2142 // VIDIOC_S_FMT w/h/fmt
2143 v4l2_format fmt;
2144 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2145 fmt.fmt.pix.width = v4l2Fmt.width;
2146 fmt.fmt.pix.height = v4l2Fmt.height;
2147 fmt.fmt.pix.pixelformat = v4l2Fmt.fourcc;
2148 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt));
2149 if (ret < 0) {
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08002150 int numAttempt = 0;
2151 while (ret < 0) {
2152 ALOGW("%s: VIDIOC_S_FMT failed, wait 33ms and try again", __FUNCTION__);
2153 usleep(IOCTL_RETRY_SLEEP_US); // sleep 100 ms and try again
2154 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt));
2155 if (numAttempt == MAX_RETRY) {
2156 break;
2157 }
2158 numAttempt++;
2159 }
2160 if (ret < 0) {
2161 ALOGE("%s: S_FMT ioctl failed: %s", __FUNCTION__, strerror(errno));
2162 return -errno;
2163 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002164 }
2165
2166 if (v4l2Fmt.width != fmt.fmt.pix.width || v4l2Fmt.height != fmt.fmt.pix.height ||
2167 v4l2Fmt.fourcc != fmt.fmt.pix.pixelformat) {
2168 ALOGE("%s: S_FMT expect %c%c%c%c %dx%d, got %c%c%c%c %dx%d instead!", __FUNCTION__,
2169 v4l2Fmt.fourcc & 0xFF,
2170 (v4l2Fmt.fourcc >> 8) & 0xFF,
2171 (v4l2Fmt.fourcc >> 16) & 0xFF,
2172 (v4l2Fmt.fourcc >> 24) & 0xFF,
2173 v4l2Fmt.width, v4l2Fmt.height,
2174 fmt.fmt.pix.pixelformat & 0xFF,
2175 (fmt.fmt.pix.pixelformat >> 8) & 0xFF,
2176 (fmt.fmt.pix.pixelformat >> 16) & 0xFF,
2177 (fmt.fmt.pix.pixelformat >> 24) & 0xFF,
2178 fmt.fmt.pix.width, fmt.fmt.pix.height);
2179 return -EINVAL;
2180 }
2181 uint32_t bufferSize = fmt.fmt.pix.sizeimage;
2182 ALOGI("%s: V4L2 buffer size is %d", __FUNCTION__, bufferSize);
2183
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002184 const double kDefaultFps = 30.0;
2185 double fps = 1000.0;
2186 if (requestFps != 0.0) {
2187 fps = requestFps;
2188 } else {
2189 double maxFps = -1.0;
2190 // Try to pick the slowest fps that is at least 30
2191 for (const auto& fr : v4l2Fmt.frameRates) {
2192 double f = fr.getDouble();
2193 if (maxFps < f) {
2194 maxFps = f;
2195 }
2196 if (f >= kDefaultFps && f < fps) {
2197 fps = f;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002198 }
2199 }
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002200 if (fps == 1000.0) {
2201 fps = maxFps;
2202 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002203 }
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002204
2205 int fpsRet = setV4l2FpsLocked(fps);
2206 if (fpsRet != 0 && fpsRet != -EINVAL) {
2207 ALOGE("%s: set fps failed: %s", __FUNCTION__, strerror(fpsRet));
2208 return fpsRet;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002209 }
2210
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -08002211 uint32_t v4lBufferCount = (fps >= kDefaultFps) ?
2212 mCfg.numVideoBuffers : mCfg.numStillBuffers;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002213 // VIDIOC_REQBUFS: create buffers
2214 v4l2_requestbuffers req_buffers{};
2215 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2216 req_buffers.memory = V4L2_MEMORY_MMAP;
2217 req_buffers.count = v4lBufferCount;
2218 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
2219 ALOGE("%s: VIDIOC_REQBUFS failed: %s", __FUNCTION__, strerror(errno));
2220 return -errno;
2221 }
2222
2223 // Driver can indeed return more buffer if it needs more to operate
2224 if (req_buffers.count < v4lBufferCount) {
2225 ALOGE("%s: VIDIOC_REQBUFS expected %d buffers, got %d instead",
2226 __FUNCTION__, v4lBufferCount, req_buffers.count);
2227 return NO_MEMORY;
2228 }
2229
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002230 // VIDIOC_QUERYBUF: get buffer offset in the V4L2 fd
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002231 // VIDIOC_QBUF: send buffer to driver
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002232 mV4L2BufferCount = req_buffers.count;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002233 for (uint32_t i = 0; i < req_buffers.count; i++) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002234 v4l2_buffer buffer = {
2235 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
2236 .index = i,
2237 .memory = V4L2_MEMORY_MMAP};
2238
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002239 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QUERYBUF, &buffer)) < 0) {
2240 ALOGE("%s: QUERYBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
2241 return -errno;
2242 }
2243
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002244 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2245 ALOGE("%s: QBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
2246 return -errno;
2247 }
2248 }
2249
2250 // VIDIOC_STREAMON: start streaming
2251 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08002252 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type));
2253 if (ret < 0) {
2254 int numAttempt = 0;
2255 while (ret < 0) {
2256 ALOGW("%s: VIDIOC_STREAMON failed, wait 33ms and try again", __FUNCTION__);
2257 usleep(IOCTL_RETRY_SLEEP_US); // sleep 100 ms and try again
2258 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type));
2259 if (numAttempt == MAX_RETRY) {
2260 break;
2261 }
2262 numAttempt++;
2263 }
2264 if (ret < 0) {
2265 ALOGE("%s: VIDIOC_STREAMON ioctl failed: %s", __FUNCTION__, strerror(errno));
2266 return -errno;
2267 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002268 }
2269
2270 // Swallow first few frames after streamOn to account for bad frames from some devices
2271 for (int i = 0; i < kBadFramesAfterStreamOn; i++) {
2272 v4l2_buffer buffer{};
2273 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2274 buffer.memory = V4L2_MEMORY_MMAP;
2275 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
2276 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
2277 return -errno;
2278 }
2279
2280 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2281 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, buffer.index, strerror(errno));
2282 return -errno;
2283 }
2284 }
2285
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08002286 ALOGI("%s: start V4L2 streaming %dx%d@%ffps",
2287 __FUNCTION__, v4l2Fmt.width, v4l2Fmt.height, fps);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002288 mV4l2StreamingFmt = v4l2Fmt;
2289 mV4l2Streaming = true;
2290 return OK;
2291}
2292
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002293sp<V4L2Frame> ExternalCameraDeviceSession::dequeueV4l2FrameLocked(/*out*/nsecs_t* shutterTs) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002294 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002295 sp<V4L2Frame> ret = nullptr;
2296
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002297 if (shutterTs == nullptr) {
2298 ALOGE("%s: shutterTs must not be null!", __FUNCTION__);
2299 return ret;
2300 }
2301
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002302 {
2303 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002304 if (mNumDequeuedV4l2Buffers == mV4L2BufferCount) {
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002305 int waitRet = waitForV4L2BufferReturnLocked(lk);
2306 if (waitRet != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002307 return ret;
2308 }
2309 }
2310 }
2311
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -08002312 ATRACE_BEGIN("VIDIOC_DQBUF");
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002313 v4l2_buffer buffer{};
2314 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2315 buffer.memory = V4L2_MEMORY_MMAP;
2316 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
2317 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
2318 return ret;
2319 }
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -08002320 ATRACE_END();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002321
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002322 if (buffer.index >= mV4L2BufferCount) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002323 ALOGE("%s: Invalid buffer id: %d", __FUNCTION__, buffer.index);
2324 return ret;
2325 }
2326
2327 if (buffer.flags & V4L2_BUF_FLAG_ERROR) {
2328 ALOGE("%s: v4l2 buf error! buf flag 0x%x", __FUNCTION__, buffer.flags);
2329 // TODO: try to dequeue again
2330 }
2331
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002332 if (buffer.flags & V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC) {
2333 // Ideally we should also check for V4L2_BUF_FLAG_TSTAMP_SRC_SOE, but
2334 // even V4L2_BUF_FLAG_TSTAMP_SRC_EOF is better than capture a timestamp now
2335 *shutterTs = static_cast<nsecs_t>(buffer.timestamp.tv_sec)*1000000000LL +
2336 buffer.timestamp.tv_usec * 1000LL;
2337 } else {
2338 *shutterTs = systemTime(SYSTEM_TIME_MONOTONIC);
2339 }
2340
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002341 {
2342 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2343 mNumDequeuedV4l2Buffers++;
2344 }
2345 return new V4L2Frame(
2346 mV4l2StreamingFmt.width, mV4l2StreamingFmt.height, mV4l2StreamingFmt.fourcc,
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002347 buffer.index, mV4l2Fd.get(), buffer.bytesused, buffer.m.offset);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002348}
2349
2350void ExternalCameraDeviceSession::enqueueV4l2Frame(const sp<V4L2Frame>& frame) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002351 ATRACE_CALL();
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -08002352 frame->unmap();
2353 ATRACE_BEGIN("VIDIOC_QBUF");
2354 v4l2_buffer buffer{};
2355 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2356 buffer.memory = V4L2_MEMORY_MMAP;
2357 buffer.index = frame->mBufferIndex;
2358 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2359 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__,
2360 frame->mBufferIndex, strerror(errno));
2361 return;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002362 }
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -08002363 ATRACE_END();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002364
2365 {
2366 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2367 mNumDequeuedV4l2Buffers--;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002368 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002369 mV4L2BufferReturned.notify_one();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002370}
2371
2372Status ExternalCameraDeviceSession::configureStreams(
2373 const V3_2::StreamConfiguration& config, V3_3::HalStreamConfiguration* out) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002374 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002375 if (config.operationMode != StreamConfigurationMode::NORMAL_MODE) {
2376 ALOGE("%s: unsupported operation mode: %d", __FUNCTION__, config.operationMode);
2377 return Status::ILLEGAL_ARGUMENT;
2378 }
2379
2380 if (config.streams.size() == 0) {
2381 ALOGE("%s: cannot configure zero stream", __FUNCTION__);
2382 return Status::ILLEGAL_ARGUMENT;
2383 }
2384
2385 int numProcessedStream = 0;
2386 int numStallStream = 0;
2387 for (const auto& stream : config.streams) {
2388 // Check if the format/width/height combo is supported
2389 if (!isSupported(stream)) {
2390 return Status::ILLEGAL_ARGUMENT;
2391 }
2392 if (stream.format == PixelFormat::BLOB) {
2393 numStallStream++;
2394 } else {
2395 numProcessedStream++;
2396 }
2397 }
2398
2399 if (numProcessedStream > kMaxProcessedStream) {
2400 ALOGE("%s: too many processed streams (expect <= %d, got %d)", __FUNCTION__,
2401 kMaxProcessedStream, numProcessedStream);
2402 return Status::ILLEGAL_ARGUMENT;
2403 }
2404
2405 if (numStallStream > kMaxStallStream) {
2406 ALOGE("%s: too many stall streams (expect <= %d, got %d)", __FUNCTION__,
2407 kMaxStallStream, numStallStream);
2408 return Status::ILLEGAL_ARGUMENT;
2409 }
2410
2411 Status status = initStatus();
2412 if (status != Status::OK) {
2413 return status;
2414 }
2415
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -08002416
2417 {
2418 std::lock_guard<std::mutex> lk(mInflightFramesLock);
2419 if (!mInflightFrames.empty()) {
2420 ALOGE("%s: trying to configureStreams while there are still %zu inflight frames!",
2421 __FUNCTION__, mInflightFrames.size());
2422 return Status::INTERNAL_ERROR;
2423 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002424 }
2425
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -08002426 Mutex::Autolock _l(mLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002427 // Add new streams
2428 for (const auto& stream : config.streams) {
2429 if (mStreamMap.count(stream.id) == 0) {
2430 mStreamMap[stream.id] = stream;
2431 mCirculatingBuffers.emplace(stream.id, CirculatingBuffers{});
2432 }
2433 }
2434
2435 // Cleanup removed streams
2436 for(auto it = mStreamMap.begin(); it != mStreamMap.end();) {
2437 int id = it->first;
2438 bool found = false;
2439 for (const auto& stream : config.streams) {
2440 if (id == stream.id) {
2441 found = true;
2442 break;
2443 }
2444 }
2445 if (!found) {
2446 // Unmap all buffers of deleted stream
2447 cleanupBuffersLocked(id);
2448 it = mStreamMap.erase(it);
2449 } else {
2450 ++it;
2451 }
2452 }
2453
2454 // Now select a V4L2 format to produce all output streams
2455 float desiredAr = (mCroppingType == VERTICAL) ? kMaxAspectRatio : kMinAspectRatio;
2456 uint32_t maxDim = 0;
2457 for (const auto& stream : config.streams) {
2458 float aspectRatio = ASPECT_RATIO(stream);
Yin-Chia Yehc15a1ca2018-03-02 14:16:52 -08002459 ALOGI("%s: request stream %dx%d", __FUNCTION__, stream.width, stream.height);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002460 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2461 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2462 desiredAr = aspectRatio;
2463 }
2464
2465 // The dimension that's not cropped
2466 uint32_t dim = (mCroppingType == VERTICAL) ? stream.width : stream.height;
2467 if (dim > maxDim) {
2468 maxDim = dim;
2469 }
2470 }
2471 // Find the smallest format that matches the desired aspect ratio and is wide/high enough
2472 SupportedV4L2Format v4l2Fmt {.width = 0, .height = 0};
2473 for (const auto& fmt : mSupportedFormats) {
2474 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2475 if (dim >= maxDim) {
2476 float aspectRatio = ASPECT_RATIO(fmt);
2477 if (isAspectRatioClose(aspectRatio, desiredAr)) {
2478 v4l2Fmt = fmt;
2479 // since mSupportedFormats is sorted by width then height, the first matching fmt
2480 // will be the smallest one with matching aspect ratio
2481 break;
2482 }
2483 }
2484 }
2485 if (v4l2Fmt.width == 0) {
2486 // Cannot find exact good aspect ratio candidate, try to find a close one
2487 for (const auto& fmt : mSupportedFormats) {
2488 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2489 if (dim >= maxDim) {
2490 float aspectRatio = ASPECT_RATIO(fmt);
2491 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2492 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2493 v4l2Fmt = fmt;
2494 break;
2495 }
2496 }
2497 }
2498 }
2499
2500 if (v4l2Fmt.width == 0) {
2501 ALOGE("%s: unable to find a resolution matching (%s at least %d, aspect ratio %f)"
2502 , __FUNCTION__, (mCroppingType == VERTICAL) ? "width" : "height",
2503 maxDim, desiredAr);
2504 return Status::ILLEGAL_ARGUMENT;
2505 }
2506
2507 if (configureV4l2StreamLocked(v4l2Fmt) != 0) {
2508 ALOGE("V4L configuration failed!, format:%c%c%c%c, w %d, h %d",
2509 v4l2Fmt.fourcc & 0xFF,
2510 (v4l2Fmt.fourcc >> 8) & 0xFF,
2511 (v4l2Fmt.fourcc >> 16) & 0xFF,
2512 (v4l2Fmt.fourcc >> 24) & 0xFF,
2513 v4l2Fmt.width, v4l2Fmt.height);
2514 return Status::INTERNAL_ERROR;
2515 }
2516
2517 Size v4lSize = {v4l2Fmt.width, v4l2Fmt.height};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08002518 Size thumbSize { 0, 0 };
2519 camera_metadata_ro_entry entry =
2520 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
2521 for(uint32_t i = 0; i < entry.count; i += 2) {
2522 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
2523 static_cast<uint32_t>(entry.data.i32[i+1]) };
2524 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
2525 thumbSize = sz;
2526 }
2527 }
2528
2529 if (thumbSize.width * thumbSize.height == 0) {
2530 ALOGE("%s: non-zero thumbnail size not available", __FUNCTION__);
2531 return Status::INTERNAL_ERROR;
2532 }
2533
2534 status = mOutputThread->allocateIntermediateBuffers(v4lSize,
2535 mMaxThumbResolution, config.streams);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002536 if (status != Status::OK) {
2537 ALOGE("%s: allocating intermediate buffers failed!", __FUNCTION__);
2538 return status;
2539 }
2540
2541 out->streams.resize(config.streams.size());
2542 for (size_t i = 0; i < config.streams.size(); i++) {
2543 out->streams[i].overrideDataSpace = config.streams[i].dataSpace;
2544 out->streams[i].v3_2.id = config.streams[i].id;
2545 // TODO: double check should we add those CAMERA flags
2546 mStreamMap[config.streams[i].id].usage =
2547 out->streams[i].v3_2.producerUsage = config.streams[i].usage |
2548 BufferUsage::CPU_WRITE_OFTEN |
2549 BufferUsage::CAMERA_OUTPUT;
2550 out->streams[i].v3_2.consumerUsage = 0;
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002551 out->streams[i].v3_2.maxBuffers = mV4L2BufferCount;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002552
2553 switch (config.streams[i].format) {
2554 case PixelFormat::BLOB:
2555 case PixelFormat::YCBCR_420_888:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002556 case PixelFormat::YV12: // Used by SurfaceTexture
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002557 // No override
2558 out->streams[i].v3_2.overrideFormat = config.streams[i].format;
2559 break;
2560 case PixelFormat::IMPLEMENTATION_DEFINED:
2561 // Override based on VIDEO or not
2562 out->streams[i].v3_2.overrideFormat =
2563 (config.streams[i].usage & BufferUsage::VIDEO_ENCODER) ?
2564 PixelFormat::YCBCR_420_888 : PixelFormat::YV12;
2565 // Save overridden formt in mStreamMap
2566 mStreamMap[config.streams[i].id].format = out->streams[i].v3_2.overrideFormat;
2567 break;
2568 default:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002569 ALOGE("%s: unsupported format 0x%x", __FUNCTION__, config.streams[i].format);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002570 return Status::ILLEGAL_ARGUMENT;
2571 }
2572 }
2573
2574 mFirstRequest = true;
2575 return Status::OK;
2576}
2577
2578bool ExternalCameraDeviceSession::isClosed() {
2579 Mutex::Autolock _l(mLock);
2580 return mClosed;
2581}
2582
2583#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
2584#define UPDATE(md, tag, data, size) \
2585do { \
2586 if ((md).update((tag), (data), (size))) { \
2587 ALOGE("Update " #tag " failed!"); \
2588 return BAD_VALUE; \
2589 } \
2590} while (0)
2591
2592status_t ExternalCameraDeviceSession::initDefaultRequests() {
2593 ::android::hardware::camera::common::V1_0::helper::CameraMetadata md;
2594
2595 const uint8_t aberrationMode = ANDROID_COLOR_CORRECTION_ABERRATION_MODE_OFF;
2596 UPDATE(md, ANDROID_COLOR_CORRECTION_ABERRATION_MODE, &aberrationMode, 1);
2597
2598 const int32_t exposureCompensation = 0;
2599 UPDATE(md, ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION, &exposureCompensation, 1);
2600
2601 const uint8_t videoStabilizationMode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
2602 UPDATE(md, ANDROID_CONTROL_VIDEO_STABILIZATION_MODE, &videoStabilizationMode, 1);
2603
2604 const uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO;
2605 UPDATE(md, ANDROID_CONTROL_AWB_MODE, &awbMode, 1);
2606
2607 const uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON;
2608 UPDATE(md, ANDROID_CONTROL_AE_MODE, &aeMode, 1);
2609
2610 const uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
2611 UPDATE(md, ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
2612
2613 const uint8_t afMode = ANDROID_CONTROL_AF_MODE_AUTO;
2614 UPDATE(md, ANDROID_CONTROL_AF_MODE, &afMode, 1);
2615
2616 const uint8_t afTrigger = ANDROID_CONTROL_AF_TRIGGER_IDLE;
2617 UPDATE(md, ANDROID_CONTROL_AF_TRIGGER, &afTrigger, 1);
2618
2619 const uint8_t sceneMode = ANDROID_CONTROL_SCENE_MODE_DISABLED;
2620 UPDATE(md, ANDROID_CONTROL_SCENE_MODE, &sceneMode, 1);
2621
2622 const uint8_t effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF;
2623 UPDATE(md, ANDROID_CONTROL_EFFECT_MODE, &effectMode, 1);
2624
2625 const uint8_t flashMode = ANDROID_FLASH_MODE_OFF;
2626 UPDATE(md, ANDROID_FLASH_MODE, &flashMode, 1);
2627
2628 const int32_t thumbnailSize[] = {240, 180};
2629 UPDATE(md, ANDROID_JPEG_THUMBNAIL_SIZE, thumbnailSize, 2);
2630
2631 const uint8_t jpegQuality = 90;
2632 UPDATE(md, ANDROID_JPEG_QUALITY, &jpegQuality, 1);
2633 UPDATE(md, ANDROID_JPEG_THUMBNAIL_QUALITY, &jpegQuality, 1);
2634
2635 const int32_t jpegOrientation = 0;
2636 UPDATE(md, ANDROID_JPEG_ORIENTATION, &jpegOrientation, 1);
2637
2638 const uint8_t oisMode = ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF;
2639 UPDATE(md, ANDROID_LENS_OPTICAL_STABILIZATION_MODE, &oisMode, 1);
2640
2641 const uint8_t nrMode = ANDROID_NOISE_REDUCTION_MODE_OFF;
2642 UPDATE(md, ANDROID_NOISE_REDUCTION_MODE, &nrMode, 1);
2643
Yin-Chia Yehc15a1ca2018-03-02 14:16:52 -08002644 const int32_t testPatternModes = ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2645 UPDATE(md, ANDROID_SENSOR_TEST_PATTERN_MODE, &testPatternModes, 1);
2646
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002647 const uint8_t fdMode = ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
2648 UPDATE(md, ANDROID_STATISTICS_FACE_DETECT_MODE, &fdMode, 1);
2649
2650 const uint8_t hotpixelMode = ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF;
2651 UPDATE(md, ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE, &hotpixelMode, 1);
2652
2653 bool support30Fps = false;
2654 int32_t maxFps = std::numeric_limits<int32_t>::min();
2655 for (const auto& supportedFormat : mSupportedFormats) {
Yin-Chia Yeh134093a2018-02-12 14:05:48 -08002656 for (const auto& fr : supportedFormat.frameRates) {
2657 int32_t framerateInt = static_cast<int32_t>(fr.getDouble());
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002658 if (maxFps < framerateInt) {
2659 maxFps = framerateInt;
2660 }
2661 if (framerateInt == 30) {
2662 support30Fps = true;
2663 break;
2664 }
2665 }
2666 if (support30Fps) {
2667 break;
2668 }
2669 }
2670 int32_t defaultFramerate = support30Fps ? 30 : maxFps;
Yin-Chia Yehc15a1ca2018-03-02 14:16:52 -08002671 int32_t defaultFpsRange[] = {defaultFramerate / 2, defaultFramerate};
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002672 UPDATE(md, ANDROID_CONTROL_AE_TARGET_FPS_RANGE, defaultFpsRange, ARRAY_SIZE(defaultFpsRange));
2673
2674 uint8_t antibandingMode = ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO;
2675 UPDATE(md, ANDROID_CONTROL_AE_ANTIBANDING_MODE, &antibandingMode, 1);
2676
2677 const uint8_t controlMode = ANDROID_CONTROL_MODE_AUTO;
2678 UPDATE(md, ANDROID_CONTROL_MODE, &controlMode, 1);
2679
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002680 auto requestTemplates = hidl_enum_iterator<RequestTemplate>();
2681 for (RequestTemplate type : requestTemplates) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002682 ::android::hardware::camera::common::V1_0::helper::CameraMetadata mdCopy = md;
2683 uint8_t intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2684 switch (type) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002685 case RequestTemplate::PREVIEW:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002686 intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2687 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002688 case RequestTemplate::STILL_CAPTURE:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002689 intent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE;
2690 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002691 case RequestTemplate::VIDEO_RECORD:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002692 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD;
2693 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002694 case RequestTemplate::VIDEO_SNAPSHOT:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002695 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT;
2696 break;
2697 default:
Yuriy Romanenko083de0c2018-01-26 16:05:54 -08002698 ALOGV("%s: unsupported RequestTemplate type %d", __FUNCTION__, type);
2699 continue;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002700 }
2701 UPDATE(mdCopy, ANDROID_CONTROL_CAPTURE_INTENT, &intent, 1);
2702
2703 camera_metadata_t* rawMd = mdCopy.release();
2704 CameraMetadata hidlMd;
2705 hidlMd.setToExternal(
2706 (uint8_t*) rawMd, get_camera_metadata_size(rawMd));
2707 mDefaultRequests[type] = hidlMd;
2708 free_camera_metadata(rawMd);
2709 }
2710
2711 return OK;
2712}
2713
2714status_t ExternalCameraDeviceSession::fillCaptureResult(
2715 common::V1_0::helper::CameraMetadata &md, nsecs_t timestamp) {
2716 // android.control
2717 // For USB camera, we don't know the AE state. Set the state to converged to
2718 // indicate the frame should be good to use. Then apps don't have to wait the
2719 // AE state.
2720 const uint8_t aeState = ANDROID_CONTROL_AE_STATE_CONVERGED;
2721 UPDATE(md, ANDROID_CONTROL_AE_STATE, &aeState, 1);
2722
2723 const uint8_t ae_lock = ANDROID_CONTROL_AE_LOCK_OFF;
2724 UPDATE(md, ANDROID_CONTROL_AE_LOCK, &ae_lock, 1);
2725
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -08002726 bool afTrigger = false;
2727 {
2728 std::lock_guard<std::mutex> lk(mAfTriggerLock);
2729 afTrigger = mAfTrigger;
2730 if (md.exists(ANDROID_CONTROL_AF_TRIGGER)) {
2731 camera_metadata_entry entry = md.find(ANDROID_CONTROL_AF_TRIGGER);
2732 if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_START) {
2733 mAfTrigger = afTrigger = true;
2734 } else if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_CANCEL) {
2735 mAfTrigger = afTrigger = false;
2736 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002737 }
2738 }
2739
2740 // For USB camera, the USB camera handles everything and we don't have control
2741 // over AF. We only simply fake the AF metadata based on the request
2742 // received here.
2743 uint8_t afState;
2744 if (afTrigger) {
2745 afState = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
2746 } else {
2747 afState = ANDROID_CONTROL_AF_STATE_INACTIVE;
2748 }
2749 UPDATE(md, ANDROID_CONTROL_AF_STATE, &afState, 1);
2750
2751 // Set AWB state to converged to indicate the frame should be good to use.
2752 const uint8_t awbState = ANDROID_CONTROL_AWB_STATE_CONVERGED;
2753 UPDATE(md, ANDROID_CONTROL_AWB_STATE, &awbState, 1);
2754
2755 const uint8_t awbLock = ANDROID_CONTROL_AWB_LOCK_OFF;
2756 UPDATE(md, ANDROID_CONTROL_AWB_LOCK, &awbLock, 1);
2757
2758 camera_metadata_ro_entry active_array_size =
2759 mCameraCharacteristics.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
2760
2761 if (active_array_size.count == 0) {
2762 ALOGE("%s: cannot find active array size!", __FUNCTION__);
2763 return -EINVAL;
2764 }
2765
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002766 const uint8_t flashState = ANDROID_FLASH_STATE_UNAVAILABLE;
2767 UPDATE(md, ANDROID_FLASH_STATE, &flashState, 1);
2768
Yin-Chia Yehc15a1ca2018-03-02 14:16:52 -08002769 // This means pipeline latency of X frame intervals. The maximum number is 4.
2770 const uint8_t requestPipelineMaxDepth = 4;
2771 UPDATE(md, ANDROID_REQUEST_PIPELINE_DEPTH, &requestPipelineMaxDepth, 1);
2772
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002773 // android.scaler
2774 const int32_t crop_region[] = {
2775 active_array_size.data.i32[0], active_array_size.data.i32[1],
2776 active_array_size.data.i32[2], active_array_size.data.i32[3],
2777 };
2778 UPDATE(md, ANDROID_SCALER_CROP_REGION, crop_region, ARRAY_SIZE(crop_region));
2779
2780 // android.sensor
2781 UPDATE(md, ANDROID_SENSOR_TIMESTAMP, &timestamp, 1);
2782
2783 // android.statistics
2784 const uint8_t lensShadingMapMode = ANDROID_STATISTICS_LENS_SHADING_MAP_MODE_OFF;
2785 UPDATE(md, ANDROID_STATISTICS_LENS_SHADING_MAP_MODE, &lensShadingMapMode, 1);
2786
2787 const uint8_t sceneFlicker = ANDROID_STATISTICS_SCENE_FLICKER_NONE;
2788 UPDATE(md, ANDROID_STATISTICS_SCENE_FLICKER, &sceneFlicker, 1);
2789
2790 return OK;
2791}
2792
2793#undef ARRAY_SIZE
2794#undef UPDATE
2795
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002796} // namespace implementation
2797} // namespace V3_4
2798} // namespace device
2799} // namespace camera
2800} // namespace hardware
2801} // namespace android