blob: 2c03d81f2204f5021f45c02ac008f10f21ed646c [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 Yeh4a3393c2018-02-14 12:47:16 -080054bool tryLock(Mutex& mutex)
55{
56 static const int kDumpLockRetries = 50;
57 static const int kDumpLockSleep = 60000;
58 bool locked = false;
59 for (int i = 0; i < kDumpLockRetries; ++i) {
60 if (mutex.tryLock() == NO_ERROR) {
61 locked = true;
62 break;
63 }
64 usleep(kDumpLockSleep);
65 }
66 return locked;
67}
68
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080069} // Anonymous namespace
Yin-Chia Yeh19030592017-10-19 17:30:11 -070070
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080071// Static instances
72const int ExternalCameraDeviceSession::kMaxProcessedStream;
73const int ExternalCameraDeviceSession::kMaxStallStream;
Yin-Chia Yeh19030592017-10-19 17:30:11 -070074HandleImporter ExternalCameraDeviceSession::sHandleImporter;
75
Yin-Chia Yeh19030592017-10-19 17:30:11 -070076ExternalCameraDeviceSession::ExternalCameraDeviceSession(
77 const sp<ICameraDeviceCallback>& callback,
Yin-Chia Yeh17982492018-02-05 17:41:01 -080078 const ExternalCameraConfig& cfg,
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080079 const std::vector<SupportedV4L2Format>& sortedFormats,
80 const CroppingType& croppingType,
Yin-Chia Yeh19030592017-10-19 17:30:11 -070081 const common::V1_0::helper::CameraMetadata& chars,
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -080082 const std::string& cameraId,
Yin-Chia Yeh19030592017-10-19 17:30:11 -070083 unique_fd v4l2Fd) :
84 mCallback(callback),
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080085 mCfg(cfg),
Yin-Chia Yeh19030592017-10-19 17:30:11 -070086 mCameraCharacteristics(chars),
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080087 mSupportedFormats(sortedFormats),
88 mCroppingType(croppingType),
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -080089 mCameraId(cameraId),
Yin-Chia Yeh19030592017-10-19 17:30:11 -070090 mV4l2Fd(std::move(v4l2Fd)),
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -080091 mOutputThread(new OutputThread(this, mCroppingType)),
92 mMaxThumbResolution(getMaxThumbResolution()),
93 mMaxJpegResolution(getMaxJpegResolution()) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -070094 mInitFail = initialize();
95}
96
Yin-Chia Yeh19030592017-10-19 17:30:11 -070097bool ExternalCameraDeviceSession::initialize() {
98 if (mV4l2Fd.get() < 0) {
99 ALOGE("%s: invalid v4l2 device fd %d!", __FUNCTION__, mV4l2Fd.get());
100 return true;
101 }
102
103 status_t status = initDefaultRequests();
104 if (status != OK) {
105 ALOGE("%s: init default requests failed!", __FUNCTION__);
106 return true;
107 }
108
109 mRequestMetadataQueue = std::make_unique<RequestMetadataQueue>(
110 kMetadataMsgQueueSize, false /* non blocking */);
111 if (!mRequestMetadataQueue->isValid()) {
112 ALOGE("%s: invalid request fmq", __FUNCTION__);
113 return true;
114 }
115 mResultMetadataQueue = std::make_shared<RequestMetadataQueue>(
116 kMetadataMsgQueueSize, false /* non blocking */);
117 if (!mResultMetadataQueue->isValid()) {
118 ALOGE("%s: invalid result fmq", __FUNCTION__);
119 return true;
120 }
121
122 // TODO: check is PRIORITY_DISPLAY enough?
123 mOutputThread->run("ExtCamOut", PRIORITY_DISPLAY);
124 return false;
125}
126
127Status ExternalCameraDeviceSession::initStatus() const {
128 Mutex::Autolock _l(mLock);
129 Status status = Status::OK;
130 if (mInitFail || mClosed) {
131 ALOGI("%s: sesssion initFailed %d closed %d", __FUNCTION__, mInitFail, mClosed);
132 status = Status::INTERNAL_ERROR;
133 }
134 return status;
135}
136
137ExternalCameraDeviceSession::~ExternalCameraDeviceSession() {
138 if (!isClosed()) {
139 ALOGE("ExternalCameraDeviceSession deleted before close!");
140 close();
141 }
142}
143
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800144
145void ExternalCameraDeviceSession::dumpState(const native_handle_t* handle) {
146 if (handle->numFds != 1 || handle->numInts != 0) {
147 ALOGE("%s: handle must contain 1 FD and 0 integers! Got %d FDs and %d ints",
148 __FUNCTION__, handle->numFds, handle->numInts);
149 return;
150 }
151 int fd = handle->data[0];
152
153 bool intfLocked = tryLock(mInterfaceLock);
154 if (!intfLocked) {
155 dprintf(fd, "!! ExternalCameraDeviceSession interface may be deadlocked !!\n");
156 }
157
158 if (isClosed()) {
159 dprintf(fd, "External camera %s is closed\n", mCameraId.c_str());
160 return;
161 }
162
163 bool streaming = false;
164 size_t v4L2BufferCount = 0;
165 SupportedV4L2Format streamingFmt;
166 std::unordered_set<uint32_t> inflightFrames;
167 {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800168 bool sessionLocked = tryLock(mLock);
169 if (!sessionLocked) {
170 dprintf(fd, "!! ExternalCameraDeviceSession mLock may be deadlocked !!\n");
171 }
172 streaming = mV4l2Streaming;
173 streamingFmt = mV4l2StreamingFmt;
174 v4L2BufferCount = mV4L2BufferCount;
175 inflightFrames = mInflightFrames;
176 if (sessionLocked) {
177 mLock.unlock();
178 }
179 }
180
181 dprintf(fd, "External camera %s V4L2 FD %d, cropping type %s, %s\n",
182 mCameraId.c_str(), mV4l2Fd.get(),
183 (mCroppingType == VERTICAL) ? "vertical" : "horizontal",
184 streaming ? "streaming" : "not streaming");
185 if (streaming) {
186 // TODO: dump fps later
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800187 dprintf(fd, "Current V4L2 format %c%c%c%c %dx%d @ %ffps\n",
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800188 streamingFmt.fourcc & 0xFF,
189 (streamingFmt.fourcc >> 8) & 0xFF,
190 (streamingFmt.fourcc >> 16) & 0xFF,
191 (streamingFmt.fourcc >> 24) & 0xFF,
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800192 streamingFmt.width, streamingFmt.height,
193 mV4l2StreamingFps);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800194
195 size_t numDequeuedV4l2Buffers = 0;
196 {
197 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
198 numDequeuedV4l2Buffers = mNumDequeuedV4l2Buffers;
199 }
200 dprintf(fd, "V4L2 buffer queue size %zu, dequeued %zu\n",
201 v4L2BufferCount, numDequeuedV4l2Buffers);
202 }
203
204 dprintf(fd, "In-flight frames (not sorted):");
205 for (const auto& frameNumber : inflightFrames) {
206 dprintf(fd, "%d, ", frameNumber);
207 }
208 dprintf(fd, "\n");
209 mOutputThread->dump(fd);
210 dprintf(fd, "\n");
211
212 if (intfLocked) {
213 mInterfaceLock.unlock();
214 }
215
216 return;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700217}
218
219Return<void> ExternalCameraDeviceSession::constructDefaultRequestSettings(
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800220 V3_2::RequestTemplate type,
221 V3_2::ICameraDeviceSession::constructDefaultRequestSettings_cb _hidl_cb) {
222 V3_2::CameraMetadata outMetadata;
223 Status status = constructDefaultRequestSettingsRaw(
224 static_cast<RequestTemplate>(type), &outMetadata);
225 _hidl_cb(status, outMetadata);
226 return Void();
227}
228
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800229Status ExternalCameraDeviceSession::constructDefaultRequestSettingsRaw(RequestTemplate type,
230 V3_2::CameraMetadata *outMetadata) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700231 CameraMetadata emptyMd;
232 Status status = initStatus();
233 if (status != Status::OK) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800234 return status;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700235 }
236
237 switch (type) {
238 case RequestTemplate::PREVIEW:
239 case RequestTemplate::STILL_CAPTURE:
240 case RequestTemplate::VIDEO_RECORD:
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800241 case RequestTemplate::VIDEO_SNAPSHOT: {
242 *outMetadata = mDefaultRequests[type];
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700243 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800244 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700245 case RequestTemplate::MANUAL:
246 case RequestTemplate::ZERO_SHUTTER_LAG:
Eino-Ville Talvala0a2a9fc2018-02-05 16:27:15 -0800247 // Don't support MANUAL, ZSL templates
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800248 status = Status::ILLEGAL_ARGUMENT;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700249 break;
250 default:
251 ALOGE("%s: unknown request template type %d", __FUNCTION__, static_cast<int>(type));
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800252 status = Status::ILLEGAL_ARGUMENT;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700253 break;
254 }
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800255 return status;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700256}
257
258Return<void> ExternalCameraDeviceSession::configureStreams(
259 const V3_2::StreamConfiguration& streams,
260 ICameraDeviceSession::configureStreams_cb _hidl_cb) {
261 V3_2::HalStreamConfiguration outStreams;
262 V3_3::HalStreamConfiguration outStreams_v33;
263 Mutex::Autolock _il(mInterfaceLock);
264
265 Status status = configureStreams(streams, &outStreams_v33);
266 size_t size = outStreams_v33.streams.size();
267 outStreams.streams.resize(size);
268 for (size_t i = 0; i < size; i++) {
269 outStreams.streams[i] = outStreams_v33.streams[i].v3_2;
270 }
271 _hidl_cb(status, outStreams);
272 return Void();
273}
274
275Return<void> ExternalCameraDeviceSession::configureStreams_3_3(
276 const V3_2::StreamConfiguration& streams,
277 ICameraDeviceSession::configureStreams_3_3_cb _hidl_cb) {
278 V3_3::HalStreamConfiguration outStreams;
279 Mutex::Autolock _il(mInterfaceLock);
280
281 Status status = configureStreams(streams, &outStreams);
282 _hidl_cb(status, outStreams);
283 return Void();
284}
285
286Return<void> ExternalCameraDeviceSession::configureStreams_3_4(
287 const V3_4::StreamConfiguration& requestedConfiguration,
288 ICameraDeviceSession::configureStreams_3_4_cb _hidl_cb) {
289 V3_2::StreamConfiguration config_v32;
290 V3_3::HalStreamConfiguration outStreams_v33;
291 Mutex::Autolock _il(mInterfaceLock);
292
293 config_v32.operationMode = requestedConfiguration.operationMode;
294 config_v32.streams.resize(requestedConfiguration.streams.size());
295 for (size_t i = 0; i < config_v32.streams.size(); i++) {
296 config_v32.streams[i] = requestedConfiguration.streams[i].v3_2;
297 }
298
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700299 Status status = configureStreams(config_v32, &outStreams_v33);
300
301 V3_4::HalStreamConfiguration outStreams;
302 outStreams.streams.resize(outStreams_v33.streams.size());
303 for (size_t i = 0; i < outStreams.streams.size(); i++) {
304 outStreams.streams[i].v3_3 = outStreams_v33.streams[i];
305 }
306 _hidl_cb(status, outStreams);
307 return Void();
308}
309
310Return<void> ExternalCameraDeviceSession::getCaptureRequestMetadataQueue(
311 ICameraDeviceSession::getCaptureRequestMetadataQueue_cb _hidl_cb) {
312 Mutex::Autolock _il(mInterfaceLock);
313 _hidl_cb(*mRequestMetadataQueue->getDesc());
314 return Void();
315}
316
317Return<void> ExternalCameraDeviceSession::getCaptureResultMetadataQueue(
318 ICameraDeviceSession::getCaptureResultMetadataQueue_cb _hidl_cb) {
319 Mutex::Autolock _il(mInterfaceLock);
320 _hidl_cb(*mResultMetadataQueue->getDesc());
321 return Void();
322}
323
324Return<void> ExternalCameraDeviceSession::processCaptureRequest(
325 const hidl_vec<CaptureRequest>& requests,
326 const hidl_vec<BufferCache>& cachesToRemove,
327 ICameraDeviceSession::processCaptureRequest_cb _hidl_cb) {
328 Mutex::Autolock _il(mInterfaceLock);
329 updateBufferCaches(cachesToRemove);
330
331 uint32_t numRequestProcessed = 0;
332 Status s = Status::OK;
333 for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
334 s = processOneCaptureRequest(requests[i]);
335 if (s != Status::OK) {
336 break;
337 }
338 }
339
340 _hidl_cb(s, numRequestProcessed);
341 return Void();
342}
343
344Return<void> ExternalCameraDeviceSession::processCaptureRequest_3_4(
345 const hidl_vec<V3_4::CaptureRequest>& requests,
346 const hidl_vec<V3_2::BufferCache>& cachesToRemove,
347 ICameraDeviceSession::processCaptureRequest_3_4_cb _hidl_cb) {
348 Mutex::Autolock _il(mInterfaceLock);
349 updateBufferCaches(cachesToRemove);
350
351 uint32_t numRequestProcessed = 0;
352 Status s = Status::OK;
353 for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
354 s = processOneCaptureRequest(requests[i].v3_2);
355 if (s != Status::OK) {
356 break;
357 }
358 }
359
360 _hidl_cb(s, numRequestProcessed);
361 return Void();
362}
363
364Return<Status> ExternalCameraDeviceSession::flush() {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -0800365 ATRACE_CALL();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -0800366 Mutex::Autolock _il(mInterfaceLock);
367 Status status = initStatus();
368 if (status != Status::OK) {
369 return status;
370 }
371 mOutputThread->flush();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700372 return Status::OK;
373}
374
375Return<void> ExternalCameraDeviceSession::close() {
376 Mutex::Autolock _il(mInterfaceLock);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800377 bool closed = isClosed();
378 if (!closed) {
379 mOutputThread->flush();
380 mOutputThread->requestExit();
381 mOutputThread->join();
382
383 Mutex::Autolock _l(mLock);
384 // free all buffers
385 for(auto pair : mStreamMap) {
386 cleanupBuffersLocked(/*Stream ID*/pair.first);
387 }
388 v4l2StreamOffLocked();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700389 ALOGV("%s: closing V4L2 camera FD %d", __FUNCTION__, mV4l2Fd.get());
390 mV4l2Fd.reset();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700391 mClosed = true;
392 }
393 return Void();
394}
395
396Status ExternalCameraDeviceSession::importRequest(
397 const CaptureRequest& request,
398 hidl_vec<buffer_handle_t*>& allBufPtrs,
399 hidl_vec<int>& allFences) {
400 size_t numOutputBufs = request.outputBuffers.size();
401 size_t numBufs = numOutputBufs;
402 // Validate all I/O buffers
403 hidl_vec<buffer_handle_t> allBufs;
404 hidl_vec<uint64_t> allBufIds;
405 allBufs.resize(numBufs);
406 allBufIds.resize(numBufs);
407 allBufPtrs.resize(numBufs);
408 allFences.resize(numBufs);
409 std::vector<int32_t> streamIds(numBufs);
410
411 for (size_t i = 0; i < numOutputBufs; i++) {
412 allBufs[i] = request.outputBuffers[i].buffer.getNativeHandle();
413 allBufIds[i] = request.outputBuffers[i].bufferId;
414 allBufPtrs[i] = &allBufs[i];
415 streamIds[i] = request.outputBuffers[i].streamId;
416 }
417
418 for (size_t i = 0; i < numBufs; i++) {
419 buffer_handle_t buf = allBufs[i];
420 uint64_t bufId = allBufIds[i];
421 CirculatingBuffers& cbs = mCirculatingBuffers[streamIds[i]];
422 if (cbs.count(bufId) == 0) {
423 if (buf == nullptr) {
424 ALOGE("%s: bufferId %" PRIu64 " has null buffer handle!", __FUNCTION__, bufId);
425 return Status::ILLEGAL_ARGUMENT;
426 }
427 // Register a newly seen buffer
428 buffer_handle_t importedBuf = buf;
429 sHandleImporter.importBuffer(importedBuf);
430 if (importedBuf == nullptr) {
431 ALOGE("%s: output buffer %zu is invalid!", __FUNCTION__, i);
432 return Status::INTERNAL_ERROR;
433 } else {
434 cbs[bufId] = importedBuf;
435 }
436 }
437 allBufPtrs[i] = &cbs[bufId];
438 }
439
440 // All buffers are imported. Now validate output buffer acquire fences
441 for (size_t i = 0; i < numOutputBufs; i++) {
442 if (!sHandleImporter.importFence(
443 request.outputBuffers[i].acquireFence, allFences[i])) {
444 ALOGE("%s: output buffer %zu acquire fence is invalid", __FUNCTION__, i);
445 cleanupInflightFences(allFences, i);
446 return Status::INTERNAL_ERROR;
447 }
448 }
449 return Status::OK;
450}
451
452void ExternalCameraDeviceSession::cleanupInflightFences(
453 hidl_vec<int>& allFences, size_t numFences) {
454 for (size_t j = 0; j < numFences; j++) {
455 sHandleImporter.closeFence(allFences[j]);
456 }
457}
458
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800459int ExternalCameraDeviceSession::waitForV4L2BufferReturnLocked(std::unique_lock<std::mutex>& lk) {
460 std::chrono::seconds timeout = std::chrono::seconds(kBufferWaitTimeoutSec);
461 mLock.unlock();
462 auto st = mV4L2BufferReturned.wait_for(lk, timeout);
463 // Here we introduce a order where mV4l2BufferLock is acquired before mLock, while
464 // the normal lock acquisition order is reversed. This is fine because in most of
465 // cases we are protected by mInterfaceLock. The only thread that can cause deadlock
466 // is the OutputThread, where we do need to make sure we don't acquire mLock then
467 // mV4l2BufferLock
468 mLock.lock();
469 if (st == std::cv_status::timeout) {
470 ALOGE("%s: wait for V4L2 buffer return timeout!", __FUNCTION__);
471 return -1;
472 }
473 return 0;
474}
475
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700476Status ExternalCameraDeviceSession::processOneCaptureRequest(const CaptureRequest& request) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -0800477 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700478 Status status = initStatus();
479 if (status != Status::OK) {
480 return status;
481 }
482
483 if (request.inputBuffer.streamId != -1) {
484 ALOGE("%s: external camera does not support reprocessing!", __FUNCTION__);
485 return Status::ILLEGAL_ARGUMENT;
486 }
487
488 Mutex::Autolock _l(mLock);
489 if (!mV4l2Streaming) {
490 ALOGE("%s: cannot process request in streamOff state!", __FUNCTION__);
491 return Status::INTERNAL_ERROR;
492 }
493
494 const camera_metadata_t *rawSettings = nullptr;
495 bool converted = true;
496 CameraMetadata settingsFmq; // settings from FMQ
497 if (request.fmqSettingsSize > 0) {
498 // non-blocking read; client must write metadata before calling
499 // processOneCaptureRequest
500 settingsFmq.resize(request.fmqSettingsSize);
501 bool read = mRequestMetadataQueue->read(settingsFmq.data(), request.fmqSettingsSize);
502 if (read) {
503 converted = V3_2::implementation::convertFromHidl(settingsFmq, &rawSettings);
504 } else {
505 ALOGE("%s: capture request settings metadata couldn't be read from fmq!", __FUNCTION__);
506 converted = false;
507 }
508 } else {
509 converted = V3_2::implementation::convertFromHidl(request.settings, &rawSettings);
510 }
511
512 if (converted && rawSettings != nullptr) {
513 mLatestReqSetting = rawSettings;
514 }
515
516 if (!converted) {
517 ALOGE("%s: capture request settings metadata is corrupt!", __FUNCTION__);
518 return Status::ILLEGAL_ARGUMENT;
519 }
520
521 if (mFirstRequest && rawSettings == nullptr) {
522 ALOGE("%s: capture request settings must not be null for first request!",
523 __FUNCTION__);
524 return Status::ILLEGAL_ARGUMENT;
525 }
526
527 hidl_vec<buffer_handle_t*> allBufPtrs;
528 hidl_vec<int> allFences;
529 size_t numOutputBufs = request.outputBuffers.size();
530
531 if (numOutputBufs == 0) {
532 ALOGE("%s: capture request must have at least one output buffer!", __FUNCTION__);
533 return Status::ILLEGAL_ARGUMENT;
534 }
535
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800536 camera_metadata_entry fpsRange = mLatestReqSetting.find(ANDROID_CONTROL_AE_TARGET_FPS_RANGE);
537 if (fpsRange.count == 2) {
538 double requestFpsMax = fpsRange.data.i32[1];
539 double closestFps = 0.0;
540 double fpsError = 1000.0;
541 bool fpsSupported = false;
542 for (const auto& fr : mV4l2StreamingFmt.frameRates) {
543 double f = fr.getDouble();
544 if (std::fabs(requestFpsMax - f) < 1.0) {
545 fpsSupported = true;
546 break;
547 }
548 if (std::fabs(requestFpsMax - f) < fpsError) {
549 fpsError = std::fabs(requestFpsMax - f);
550 closestFps = f;
551 }
552 }
553 if (!fpsSupported) {
554 /* This can happen in a few scenarios:
555 * 1. The application is sending a FPS range not supported by the configured outputs.
556 * 2. The application is sending a valid FPS range for all cofigured outputs, but
557 * the selected V4L2 size can only run at slower speed. This should be very rare
558 * though: for this to happen a sensor needs to support at least 3 different aspect
559 * ratio outputs, and when (at least) two outputs are both not the main aspect ratio
560 * of the webcam, a third size that's larger might be picked and runs into this
561 * issue.
562 */
563 ALOGW("%s: cannot reach fps %d! Will do %f instead",
564 __FUNCTION__, fpsRange.data.i32[1], closestFps);
565 requestFpsMax = closestFps;
566 }
567
568 if (requestFpsMax != mV4l2StreamingFps) {
569 {
570 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
571 while (mNumDequeuedV4l2Buffers != 0) {
572 // Wait until pipeline is idle before reconfigure stream
573 int waitRet = waitForV4L2BufferReturnLocked(lk);
574 if (waitRet != 0) {
575 ALOGE("%s: wait for pipeline idle failed!", __FUNCTION__);
576 return Status::INTERNAL_ERROR;
577 }
578 }
579 }
580 configureV4l2StreamLocked(mV4l2StreamingFmt, requestFpsMax);
581 }
582 }
583
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700584 status = importRequest(request, allBufPtrs, allFences);
585 if (status != Status::OK) {
586 return status;
587 }
588
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800589 nsecs_t shutterTs = 0;
590 sp<V4L2Frame> frameIn = dequeueV4l2FrameLocked(&shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700591 if ( frameIn == nullptr) {
592 ALOGE("%s: V4L2 deque frame failed!", __FUNCTION__);
593 return Status::INTERNAL_ERROR;
594 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700595
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800596 std::shared_ptr<HalRequest> halReq = std::make_shared<HalRequest>();
597 halReq->frameNumber = request.frameNumber;
598 halReq->setting = mLatestReqSetting;
599 halReq->frameIn = frameIn;
600 halReq->shutterTs = shutterTs;
601 halReq->buffers.resize(numOutputBufs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700602 for (size_t i = 0; i < numOutputBufs; i++) {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800603 HalStreamBuffer& halBuf = halReq->buffers[i];
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700604 int streamId = halBuf.streamId = request.outputBuffers[i].streamId;
605 halBuf.bufferId = request.outputBuffers[i].bufferId;
606 const Stream& stream = mStreamMap[streamId];
607 halBuf.width = stream.width;
608 halBuf.height = stream.height;
609 halBuf.format = stream.format;
610 halBuf.usage = stream.usage;
611 halBuf.bufPtr = allBufPtrs[i];
612 halBuf.acquireFence = allFences[i];
613 halBuf.fenceTimeout = false;
614 }
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800615 mInflightFrames.insert(halReq->frameNumber);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700616 // Send request to OutputThread for the rest of processing
617 mOutputThread->submitRequest(halReq);
618 mFirstRequest = false;
619 return Status::OK;
620}
621
622void ExternalCameraDeviceSession::notifyShutter(uint32_t frameNumber, nsecs_t shutterTs) {
623 NotifyMsg msg;
624 msg.type = MsgType::SHUTTER;
625 msg.msg.shutter.frameNumber = frameNumber;
626 msg.msg.shutter.timestamp = shutterTs;
627 mCallback->notify({msg});
628}
629
630void ExternalCameraDeviceSession::notifyError(
631 uint32_t frameNumber, int32_t streamId, ErrorCode ec) {
632 NotifyMsg msg;
633 msg.type = MsgType::ERROR;
634 msg.msg.error.frameNumber = frameNumber;
635 msg.msg.error.errorStreamId = streamId;
636 msg.msg.error.errorCode = ec;
637 mCallback->notify({msg});
638}
639
640//TODO: refactor with processCaptureResult
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800641Status ExternalCameraDeviceSession::processCaptureRequestError(
642 const std::shared_ptr<HalRequest>& req) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -0800643 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700644 // Return V4L2 buffer to V4L2 buffer queue
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800645 enqueueV4l2Frame(req->frameIn);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700646
647 // NotifyShutter
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800648 notifyShutter(req->frameNumber, req->shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700649
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800650 notifyError(/*frameNum*/req->frameNumber, /*stream*/-1, ErrorCode::ERROR_REQUEST);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700651
652 // Fill output buffers
653 hidl_vec<CaptureResult> results;
654 results.resize(1);
655 CaptureResult& result = results[0];
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800656 result.frameNumber = req->frameNumber;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700657 result.partialResult = 1;
658 result.inputBuffer.streamId = -1;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800659 result.outputBuffers.resize(req->buffers.size());
660 for (size_t i = 0; i < req->buffers.size(); i++) {
661 result.outputBuffers[i].streamId = req->buffers[i].streamId;
662 result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700663 result.outputBuffers[i].status = BufferStatus::ERROR;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800664 if (req->buffers[i].acquireFence >= 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700665 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800666 handle->data[0] = req->buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800667 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700668 }
669 }
670
671 // update inflight records
672 {
673 Mutex::Autolock _l(mLock);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800674 mInflightFrames.erase(req->frameNumber);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700675 }
676
677 // Callback into framework
678 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
679 freeReleaseFences(results);
680 return Status::OK;
681}
682
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800683Status ExternalCameraDeviceSession::processCaptureResult(std::shared_ptr<HalRequest>& req) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -0800684 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700685 // Return V4L2 buffer to V4L2 buffer queue
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800686 enqueueV4l2Frame(req->frameIn);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700687
688 // NotifyShutter
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800689 notifyShutter(req->frameNumber, req->shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700690
691 // Fill output buffers
692 hidl_vec<CaptureResult> results;
693 results.resize(1);
694 CaptureResult& result = results[0];
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800695 result.frameNumber = req->frameNumber;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700696 result.partialResult = 1;
697 result.inputBuffer.streamId = -1;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800698 result.outputBuffers.resize(req->buffers.size());
699 for (size_t i = 0; i < req->buffers.size(); i++) {
700 result.outputBuffers[i].streamId = req->buffers[i].streamId;
701 result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
702 if (req->buffers[i].fenceTimeout) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700703 result.outputBuffers[i].status = BufferStatus::ERROR;
704 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800705 handle->data[0] = req->buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800706 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800707 notifyError(req->frameNumber, req->buffers[i].streamId, ErrorCode::ERROR_BUFFER);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700708 } else {
709 result.outputBuffers[i].status = BufferStatus::OK;
710 // TODO: refactor
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800711 if (req->buffers[i].acquireFence > 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700712 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800713 handle->data[0] = req->buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800714 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700715 }
716 }
717 }
718
719 // Fill capture result metadata
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800720 fillCaptureResult(req->setting, req->shutterTs);
721 const camera_metadata_t *rawResult = req->setting.getAndLock();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700722 V3_2::implementation::convertToHidl(rawResult, &result.result);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800723 req->setting.unlock(rawResult);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700724
725 // update inflight records
726 {
727 Mutex::Autolock _l(mLock);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800728 mInflightFrames.erase(req->frameNumber);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700729 }
730
731 // Callback into framework
732 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
733 freeReleaseFences(results);
734 return Status::OK;
735}
736
737void ExternalCameraDeviceSession::invokeProcessCaptureResultCallback(
738 hidl_vec<CaptureResult> &results, bool tryWriteFmq) {
739 if (mProcessCaptureResultLock.tryLock() != OK) {
740 const nsecs_t NS_TO_SECOND = 1000000000;
741 ALOGV("%s: previous call is not finished! waiting 1s...", __FUNCTION__);
742 if (mProcessCaptureResultLock.timedLock(/* 1s */NS_TO_SECOND) != OK) {
743 ALOGE("%s: cannot acquire lock in 1s, cannot proceed",
744 __FUNCTION__);
745 return;
746 }
747 }
748 if (tryWriteFmq && mResultMetadataQueue->availableToWrite() > 0) {
749 for (CaptureResult &result : results) {
750 if (result.result.size() > 0) {
751 if (mResultMetadataQueue->write(result.result.data(), result.result.size())) {
752 result.fmqResultSize = result.result.size();
753 result.result.resize(0);
754 } else {
755 ALOGW("%s: couldn't utilize fmq, fall back to hwbinder", __FUNCTION__);
756 result.fmqResultSize = 0;
757 }
758 } else {
759 result.fmqResultSize = 0;
760 }
761 }
762 }
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -0800763 auto status = mCallback->processCaptureResult(results);
764 if (!status.isOk()) {
765 ALOGE("%s: processCaptureResult ERROR : %s", __FUNCTION__,
766 status.description().c_str());
767 }
768
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700769 mProcessCaptureResultLock.unlock();
770}
771
772void ExternalCameraDeviceSession::freeReleaseFences(hidl_vec<CaptureResult>& results) {
773 for (auto& result : results) {
774 if (result.inputBuffer.releaseFence.getNativeHandle() != nullptr) {
775 native_handle_t* handle = const_cast<native_handle_t*>(
776 result.inputBuffer.releaseFence.getNativeHandle());
777 native_handle_close(handle);
778 native_handle_delete(handle);
779 }
780 for (auto& buf : result.outputBuffers) {
781 if (buf.releaseFence.getNativeHandle() != nullptr) {
782 native_handle_t* handle = const_cast<native_handle_t*>(
783 buf.releaseFence.getNativeHandle());
784 native_handle_close(handle);
785 native_handle_delete(handle);
786 }
787 }
788 }
789 return;
790}
791
792ExternalCameraDeviceSession::OutputThread::OutputThread(
793 wp<ExternalCameraDeviceSession> parent,
794 CroppingType ct) : mParent(parent), mCroppingType(ct) {}
795
796ExternalCameraDeviceSession::OutputThread::~OutputThread() {}
797
798uint32_t ExternalCameraDeviceSession::OutputThread::getFourCcFromLayout(
799 const YCbCrLayout& layout) {
800 intptr_t cb = reinterpret_cast<intptr_t>(layout.cb);
801 intptr_t cr = reinterpret_cast<intptr_t>(layout.cr);
802 if (std::abs(cb - cr) == 1 && layout.chromaStep == 2) {
803 // Interleaved format
804 if (layout.cb > layout.cr) {
805 return V4L2_PIX_FMT_NV21;
806 } else {
807 return V4L2_PIX_FMT_NV12;
808 }
809 } else if (layout.chromaStep == 1) {
810 // Planar format
811 if (layout.cb > layout.cr) {
812 return V4L2_PIX_FMT_YVU420; // YV12
813 } else {
814 return V4L2_PIX_FMT_YUV420; // YU12
815 }
816 } else {
817 return FLEX_YUV_GENERIC;
818 }
819}
820
821int ExternalCameraDeviceSession::OutputThread::getCropRect(
822 CroppingType ct, const Size& inSize, const Size& outSize, IMapper::Rect* out) {
823 if (out == nullptr) {
824 ALOGE("%s: out is null", __FUNCTION__);
825 return -1;
826 }
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800827
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700828 uint32_t inW = inSize.width;
829 uint32_t inH = inSize.height;
830 uint32_t outW = outSize.width;
831 uint32_t outH = outSize.height;
832
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800833 // Handle special case where aspect ratio is close to input but scaled
834 // dimension is slightly larger than input
835 float arIn = ASPECT_RATIO(inSize);
836 float arOut = ASPECT_RATIO(outSize);
837 if (isAspectRatioClose(arIn, arOut)) {
838 out->left = 0;
839 out->top = 0;
840 out->width = inW;
841 out->height = inH;
842 return 0;
843 }
844
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700845 if (ct == VERTICAL) {
846 uint64_t scaledOutH = static_cast<uint64_t>(outH) * inW / outW;
847 if (scaledOutH > inH) {
848 ALOGE("%s: Output size %dx%d cannot be vertically cropped from input size %dx%d",
849 __FUNCTION__, outW, outH, inW, inH);
850 return -1;
851 }
852 scaledOutH = scaledOutH & ~0x1; // make it multiple of 2
853
854 out->left = 0;
855 out->top = ((inH - scaledOutH) / 2) & ~0x1;
856 out->width = inW;
857 out->height = static_cast<int32_t>(scaledOutH);
858 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledH %d",
859 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutH));
860 } else {
861 uint64_t scaledOutW = static_cast<uint64_t>(outW) * inH / outH;
862 if (scaledOutW > inW) {
863 ALOGE("%s: Output size %dx%d cannot be horizontally cropped from input size %dx%d",
864 __FUNCTION__, outW, outH, inW, inH);
865 return -1;
866 }
867 scaledOutW = scaledOutW & ~0x1; // make it multiple of 2
868
869 out->left = ((inW - scaledOutW) / 2) & ~0x1;
870 out->top = 0;
871 out->width = static_cast<int32_t>(scaledOutW);
872 out->height = inH;
873 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledW %d",
874 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutW));
875 }
876
877 return 0;
878}
879
880int ExternalCameraDeviceSession::OutputThread::cropAndScaleLocked(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800881 sp<AllocatedFrame>& in, const Size& outSz, YCbCrLayout* out) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700882 Size inSz = {in->mWidth, in->mHeight};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800883
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700884 int ret;
885 if (inSz == outSz) {
886 ret = in->getLayout(out);
887 if (ret != 0) {
888 ALOGE("%s: failed to get input image layout", __FUNCTION__);
889 return ret;
890 }
891 return ret;
892 }
893
894 // Cropping to output aspect ratio
895 IMapper::Rect inputCrop;
896 ret = getCropRect(mCroppingType, inSz, outSz, &inputCrop);
897 if (ret != 0) {
898 ALOGE("%s: failed to compute crop rect for output size %dx%d",
899 __FUNCTION__, outSz.width, outSz.height);
900 return ret;
901 }
902
903 YCbCrLayout croppedLayout;
904 ret = in->getCroppedLayout(inputCrop, &croppedLayout);
905 if (ret != 0) {
906 ALOGE("%s: failed to crop input image %dx%d to output size %dx%d",
907 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
908 return ret;
909 }
910
911 if ((mCroppingType == VERTICAL && inSz.width == outSz.width) ||
912 (mCroppingType == HORIZONTAL && inSz.height == outSz.height)) {
913 // No scale is needed
914 *out = croppedLayout;
915 return 0;
916 }
917
918 auto it = mScaledYu12Frames.find(outSz);
919 sp<AllocatedFrame> scaledYu12Buf;
920 if (it != mScaledYu12Frames.end()) {
921 scaledYu12Buf = it->second;
922 } else {
923 it = mIntermediateBuffers.find(outSz);
924 if (it == mIntermediateBuffers.end()) {
925 ALOGE("%s: failed to find intermediate buffer size %dx%d",
926 __FUNCTION__, outSz.width, outSz.height);
927 return -1;
928 }
929 scaledYu12Buf = it->second;
930 }
931 // Scale
932 YCbCrLayout outLayout;
933 ret = scaledYu12Buf->getLayout(&outLayout);
934 if (ret != 0) {
935 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
936 return ret;
937 }
938
939 ret = libyuv::I420Scale(
940 static_cast<uint8_t*>(croppedLayout.y),
941 croppedLayout.yStride,
942 static_cast<uint8_t*>(croppedLayout.cb),
943 croppedLayout.cStride,
944 static_cast<uint8_t*>(croppedLayout.cr),
945 croppedLayout.cStride,
946 inputCrop.width,
947 inputCrop.height,
948 static_cast<uint8_t*>(outLayout.y),
949 outLayout.yStride,
950 static_cast<uint8_t*>(outLayout.cb),
951 outLayout.cStride,
952 static_cast<uint8_t*>(outLayout.cr),
953 outLayout.cStride,
954 outSz.width,
955 outSz.height,
956 // TODO: b/72261744 see if we can use better filter without losing too much perf
957 libyuv::FilterMode::kFilterNone);
958
959 if (ret != 0) {
960 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
961 __FUNCTION__, inputCrop.width, inputCrop.height,
962 outSz.width, outSz.height, ret);
963 return ret;
964 }
965
966 *out = outLayout;
967 mScaledYu12Frames.insert({outSz, scaledYu12Buf});
968 return 0;
969}
970
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800971
972int ExternalCameraDeviceSession::OutputThread::cropAndScaleThumbLocked(
973 sp<AllocatedFrame>& in, const Size &outSz, YCbCrLayout* out) {
974 Size inSz {in->mWidth, in->mHeight};
975
976 if ((outSz.width * outSz.height) >
977 (mYu12ThumbFrame->mWidth * mYu12ThumbFrame->mHeight)) {
978 ALOGE("%s: Requested thumbnail size too big (%d,%d) > (%d,%d)",
979 __FUNCTION__, outSz.width, outSz.height,
980 mYu12ThumbFrame->mWidth, mYu12ThumbFrame->mHeight);
981 return -1;
982 }
983
984 int ret;
985
986 /* This will crop-and-zoom the input YUV frame to the thumbnail size
987 * Based on the following logic:
988 * 1) Square pixels come in, square pixels come out, therefore single
989 * scale factor is computed to either make input bigger or smaller
990 * depending on if we are upscaling or downscaling
991 * 2) That single scale factor would either make height too tall or width
992 * too wide so we need to crop the input either horizontally or vertically
993 * but not both
994 */
995
996 /* Convert the input and output dimensions into floats for ease of math */
997 float fWin = static_cast<float>(inSz.width);
998 float fHin = static_cast<float>(inSz.height);
999 float fWout = static_cast<float>(outSz.width);
1000 float fHout = static_cast<float>(outSz.height);
1001
1002 /* Compute the one scale factor from (1) above, it will be the smaller of
1003 * the two possibilities. */
1004 float scaleFactor = std::min( fHin / fHout, fWin / fWout );
1005
1006 /* Since we are crop-and-zooming (as opposed to letter/pillar boxing) we can
1007 * simply multiply the output by our scaleFactor to get the cropped input
1008 * size. Note that at least one of {fWcrop, fHcrop} is going to wind up
1009 * being {fWin, fHin} respectively because fHout or fWout cancels out the
1010 * scaleFactor calculation above.
1011 *
1012 * Specifically:
1013 * if ( fHin / fHout ) < ( fWin / fWout ) we crop the sides off
1014 * input, in which case
1015 * scaleFactor = fHin / fHout
1016 * fWcrop = fHin / fHout * fWout
1017 * fHcrop = fHin
1018 *
1019 * Note that fWcrop <= fWin ( because ( fHin / fHout ) * fWout < fWin, which
1020 * is just the inequality above with both sides multiplied by fWout
1021 *
1022 * on the other hand if ( fWin / fWout ) < ( fHin / fHout) we crop the top
1023 * and the bottom off of input, and
1024 * scaleFactor = fWin / fWout
1025 * fWcrop = fWin
1026 * fHCrop = fWin / fWout * fHout
1027 */
1028 float fWcrop = scaleFactor * fWout;
1029 float fHcrop = scaleFactor * fHout;
1030
1031 /* Convert to integer and truncate to an even number */
1032 Size cropSz = { 2*static_cast<uint32_t>(fWcrop/2.0f),
1033 2*static_cast<uint32_t>(fHcrop/2.0f) };
1034
1035 /* Convert to a centered rectange with even top/left */
1036 IMapper::Rect inputCrop {
1037 2*static_cast<int32_t>((inSz.width - cropSz.width)/4),
1038 2*static_cast<int32_t>((inSz.height - cropSz.height)/4),
1039 static_cast<int32_t>(cropSz.width),
1040 static_cast<int32_t>(cropSz.height) };
1041
1042 if ((inputCrop.top < 0) ||
1043 (inputCrop.top >= static_cast<int32_t>(inSz.height)) ||
1044 (inputCrop.left < 0) ||
1045 (inputCrop.left >= static_cast<int32_t>(inSz.width)) ||
1046 (inputCrop.width <= 0) ||
1047 (inputCrop.width + inputCrop.left > static_cast<int32_t>(inSz.width)) ||
1048 (inputCrop.height <= 0) ||
1049 (inputCrop.height + inputCrop.top > static_cast<int32_t>(inSz.height)))
1050 {
1051 ALOGE("%s: came up with really wrong crop rectangle",__FUNCTION__);
1052 ALOGE("%s: input layout %dx%d to for output size %dx%d",
1053 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1054 ALOGE("%s: computed input crop +%d,+%d %dx%d",
1055 __FUNCTION__, inputCrop.left, inputCrop.top,
1056 inputCrop.width, inputCrop.height);
1057 return -1;
1058 }
1059
1060 YCbCrLayout inputLayout;
1061 ret = in->getCroppedLayout(inputCrop, &inputLayout);
1062 if (ret != 0) {
1063 ALOGE("%s: failed to crop input layout %dx%d to for output size %dx%d",
1064 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1065 ALOGE("%s: computed input crop +%d,+%d %dx%d",
1066 __FUNCTION__, inputCrop.left, inputCrop.top,
1067 inputCrop.width, inputCrop.height);
1068 return ret;
1069 }
1070 ALOGV("%s: crop input layout %dx%d to for output size %dx%d",
1071 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1072 ALOGV("%s: computed input crop +%d,+%d %dx%d",
1073 __FUNCTION__, inputCrop.left, inputCrop.top,
1074 inputCrop.width, inputCrop.height);
1075
1076
1077 // Scale
1078 YCbCrLayout outFullLayout;
1079
1080 ret = mYu12ThumbFrame->getLayout(&outFullLayout);
1081 if (ret != 0) {
1082 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
1083 return ret;
1084 }
1085
1086
1087 ret = libyuv::I420Scale(
1088 static_cast<uint8_t*>(inputLayout.y),
1089 inputLayout.yStride,
1090 static_cast<uint8_t*>(inputLayout.cb),
1091 inputLayout.cStride,
1092 static_cast<uint8_t*>(inputLayout.cr),
1093 inputLayout.cStride,
1094 inputCrop.width,
1095 inputCrop.height,
1096 static_cast<uint8_t*>(outFullLayout.y),
1097 outFullLayout.yStride,
1098 static_cast<uint8_t*>(outFullLayout.cb),
1099 outFullLayout.cStride,
1100 static_cast<uint8_t*>(outFullLayout.cr),
1101 outFullLayout.cStride,
1102 outSz.width,
1103 outSz.height,
1104 libyuv::FilterMode::kFilterNone);
1105
1106 if (ret != 0) {
1107 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
1108 __FUNCTION__, inputCrop.width, inputCrop.height,
1109 outSz.width, outSz.height, ret);
1110 return ret;
1111 }
1112
1113 *out = outFullLayout;
1114 return 0;
1115}
1116
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001117int ExternalCameraDeviceSession::OutputThread::formatConvertLocked(
1118 const YCbCrLayout& in, const YCbCrLayout& out, Size sz, uint32_t format) {
1119 int ret = 0;
1120 switch (format) {
1121 case V4L2_PIX_FMT_NV21:
1122 ret = libyuv::I420ToNV21(
1123 static_cast<uint8_t*>(in.y),
1124 in.yStride,
1125 static_cast<uint8_t*>(in.cb),
1126 in.cStride,
1127 static_cast<uint8_t*>(in.cr),
1128 in.cStride,
1129 static_cast<uint8_t*>(out.y),
1130 out.yStride,
1131 static_cast<uint8_t*>(out.cr),
1132 out.cStride,
1133 sz.width,
1134 sz.height);
1135 if (ret != 0) {
1136 ALOGE("%s: convert to NV21 buffer failed! ret %d",
1137 __FUNCTION__, ret);
1138 return ret;
1139 }
1140 break;
1141 case V4L2_PIX_FMT_NV12:
1142 ret = libyuv::I420ToNV12(
1143 static_cast<uint8_t*>(in.y),
1144 in.yStride,
1145 static_cast<uint8_t*>(in.cb),
1146 in.cStride,
1147 static_cast<uint8_t*>(in.cr),
1148 in.cStride,
1149 static_cast<uint8_t*>(out.y),
1150 out.yStride,
1151 static_cast<uint8_t*>(out.cb),
1152 out.cStride,
1153 sz.width,
1154 sz.height);
1155 if (ret != 0) {
1156 ALOGE("%s: convert to NV12 buffer failed! ret %d",
1157 __FUNCTION__, ret);
1158 return ret;
1159 }
1160 break;
1161 case V4L2_PIX_FMT_YVU420: // YV12
1162 case V4L2_PIX_FMT_YUV420: // YU12
1163 // TODO: maybe we can speed up here by somehow save this copy?
1164 ret = libyuv::I420Copy(
1165 static_cast<uint8_t*>(in.y),
1166 in.yStride,
1167 static_cast<uint8_t*>(in.cb),
1168 in.cStride,
1169 static_cast<uint8_t*>(in.cr),
1170 in.cStride,
1171 static_cast<uint8_t*>(out.y),
1172 out.yStride,
1173 static_cast<uint8_t*>(out.cb),
1174 out.cStride,
1175 static_cast<uint8_t*>(out.cr),
1176 out.cStride,
1177 sz.width,
1178 sz.height);
1179 if (ret != 0) {
1180 ALOGE("%s: copy to YV12 or YU12 buffer failed! ret %d",
1181 __FUNCTION__, ret);
1182 return ret;
1183 }
1184 break;
1185 case FLEX_YUV_GENERIC:
1186 // TODO: b/72261744 write to arbitrary flexible YUV layout. Slow.
1187 ALOGE("%s: unsupported flexible yuv layout"
1188 " y %p cb %p cr %p y_str %d c_str %d c_step %d",
1189 __FUNCTION__, out.y, out.cb, out.cr,
1190 out.yStride, out.cStride, out.chromaStep);
1191 return -1;
1192 default:
1193 ALOGE("%s: unknown YUV format 0x%x!", __FUNCTION__, format);
1194 return -1;
1195 }
1196 return 0;
1197}
1198
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001199int ExternalCameraDeviceSession::OutputThread::encodeJpegYU12(
1200 const Size & inSz, const YCbCrLayout& inLayout,
1201 int jpegQuality, const void *app1Buffer, size_t app1Size,
1202 void *out, const size_t maxOutSize, size_t &actualCodeSize)
1203{
1204 /* libjpeg is a C library so we use C-style "inheritance" by
1205 * putting libjpeg's jpeg_destination_mgr first in our custom
1206 * struct. This allows us to cast jpeg_destination_mgr* to
1207 * CustomJpegDestMgr* when we get it passed to us in a callback */
1208 struct CustomJpegDestMgr {
1209 struct jpeg_destination_mgr mgr;
1210 JOCTET *mBuffer;
1211 size_t mBufferSize;
1212 size_t mEncodedSize;
1213 bool mSuccess;
1214 } dmgr;
1215
1216 jpeg_compress_struct cinfo = {};
1217 jpeg_error_mgr jerr;
1218
1219 /* Initialize error handling with standard callbacks, but
1220 * then override output_message (to print to ALOG) and
1221 * error_exit to set a flag and print a message instead
1222 * of killing the whole process */
1223 cinfo.err = jpeg_std_error(&jerr);
1224
1225 cinfo.err->output_message = [](j_common_ptr cinfo) {
1226 char buffer[JMSG_LENGTH_MAX];
1227
1228 /* Create the message */
1229 (*cinfo->err->format_message)(cinfo, buffer);
1230 ALOGE("libjpeg error: %s", buffer);
1231 };
1232 cinfo.err->error_exit = [](j_common_ptr cinfo) {
1233 (*cinfo->err->output_message)(cinfo);
1234 if(cinfo->client_data) {
1235 auto & dmgr =
1236 *reinterpret_cast<CustomJpegDestMgr*>(cinfo->client_data);
1237 dmgr.mSuccess = false;
1238 }
1239 };
1240 /* Now that we initialized some callbacks, let's create our compressor */
1241 jpeg_create_compress(&cinfo);
1242
1243 /* Initialize our destination manager */
1244 dmgr.mBuffer = static_cast<JOCTET*>(out);
1245 dmgr.mBufferSize = maxOutSize;
1246 dmgr.mEncodedSize = 0;
1247 dmgr.mSuccess = true;
1248 cinfo.client_data = static_cast<void*>(&dmgr);
1249
1250 /* These lambdas become C-style function pointers and as per C++11 spec
1251 * may not capture anything */
1252 dmgr.mgr.init_destination = [](j_compress_ptr cinfo) {
1253 auto & dmgr = reinterpret_cast<CustomJpegDestMgr&>(*cinfo->dest);
1254 dmgr.mgr.next_output_byte = dmgr.mBuffer;
1255 dmgr.mgr.free_in_buffer = dmgr.mBufferSize;
1256 ALOGV("%s:%d jpeg start: %p [%zu]",
1257 __FUNCTION__, __LINE__, dmgr.mBuffer, dmgr.mBufferSize);
1258 };
1259
1260 dmgr.mgr.empty_output_buffer = [](j_compress_ptr cinfo __unused) {
1261 ALOGV("%s:%d Out of buffer", __FUNCTION__, __LINE__);
1262 return 0;
1263 };
1264
1265 dmgr.mgr.term_destination = [](j_compress_ptr cinfo) {
1266 auto & dmgr = reinterpret_cast<CustomJpegDestMgr&>(*cinfo->dest);
1267 dmgr.mEncodedSize = dmgr.mBufferSize - dmgr.mgr.free_in_buffer;
1268 ALOGV("%s:%d Done with jpeg: %zu", __FUNCTION__, __LINE__, dmgr.mEncodedSize);
1269 };
1270 cinfo.dest = reinterpret_cast<struct jpeg_destination_mgr*>(&dmgr);
1271
1272 /* We are going to be using JPEG in raw data mode, so we are passing
1273 * straight subsampled planar YCbCr and it will not touch our pixel
1274 * data or do any scaling or anything */
1275 cinfo.image_width = inSz.width;
1276 cinfo.image_height = inSz.height;
1277 cinfo.input_components = 3;
1278 cinfo.in_color_space = JCS_YCbCr;
1279
1280 /* Initialize defaults and then override what we want */
1281 jpeg_set_defaults(&cinfo);
1282
1283 jpeg_set_quality(&cinfo, jpegQuality, 1);
1284 jpeg_set_colorspace(&cinfo, JCS_YCbCr);
1285 cinfo.raw_data_in = 1;
1286 cinfo.dct_method = JDCT_IFAST;
1287
1288 /* Configure sampling factors. The sampling factor is JPEG subsampling 420
1289 * because the source format is YUV420. Note that libjpeg sampling factors
1290 * are... a little weird. Sampling of Y=2,U=1,V=1 means there is 1 U and
1291 * 1 V value for each 2 Y values */
1292 cinfo.comp_info[0].h_samp_factor = 2;
1293 cinfo.comp_info[0].v_samp_factor = 2;
1294 cinfo.comp_info[1].h_samp_factor = 1;
1295 cinfo.comp_info[1].v_samp_factor = 1;
1296 cinfo.comp_info[2].h_samp_factor = 1;
1297 cinfo.comp_info[2].v_samp_factor = 1;
1298
1299 /* Let's not hardcode YUV420 in 6 places... 5 was enough */
1300 int maxVSampFactor = std::max( {
1301 cinfo.comp_info[0].v_samp_factor,
1302 cinfo.comp_info[1].v_samp_factor,
1303 cinfo.comp_info[2].v_samp_factor
1304 });
1305 int cVSubSampling = cinfo.comp_info[0].v_samp_factor /
1306 cinfo.comp_info[1].v_samp_factor;
1307
1308 /* Start the compressor */
1309 jpeg_start_compress(&cinfo, TRUE);
1310
1311 /* Compute our macroblock height, so we can pad our input to be vertically
1312 * macroblock aligned.
1313 * TODO: Does it need to be horizontally MCU aligned too? */
1314
1315 size_t mcuV = DCTSIZE*maxVSampFactor;
1316 size_t paddedHeight = mcuV * ((inSz.height + mcuV - 1) / mcuV);
1317
1318 /* libjpeg uses arrays of row pointers, which makes it really easy to pad
1319 * data vertically (unfortunately doesn't help horizontally) */
1320 std::vector<JSAMPROW> yLines (paddedHeight);
1321 std::vector<JSAMPROW> cbLines(paddedHeight/cVSubSampling);
1322 std::vector<JSAMPROW> crLines(paddedHeight/cVSubSampling);
1323
1324 uint8_t *py = static_cast<uint8_t*>(inLayout.y);
1325 uint8_t *pcr = static_cast<uint8_t*>(inLayout.cr);
1326 uint8_t *pcb = static_cast<uint8_t*>(inLayout.cb);
1327
1328 for(uint32_t i = 0; i < paddedHeight; i++)
1329 {
1330 /* Once we are in the padding territory we still point to the last line
1331 * effectively replicating it several times ~ CLAMP_TO_EDGE */
1332 int li = std::min(i, inSz.height - 1);
1333 yLines[i] = static_cast<JSAMPROW>(py + li * inLayout.yStride);
1334 if(i < paddedHeight / cVSubSampling)
1335 {
1336 crLines[i] = static_cast<JSAMPROW>(pcr + li * inLayout.cStride);
1337 cbLines[i] = static_cast<JSAMPROW>(pcb + li * inLayout.cStride);
1338 }
1339 }
1340
1341 /* If APP1 data was passed in, use it */
1342 if(app1Buffer && app1Size)
1343 {
1344 jpeg_write_marker(&cinfo, JPEG_APP0 + 1,
1345 static_cast<const JOCTET*>(app1Buffer), app1Size);
1346 }
1347
1348 /* While we still have padded height left to go, keep giving it one
1349 * macroblock at a time. */
1350 while (cinfo.next_scanline < cinfo.image_height) {
1351 const uint32_t batchSize = DCTSIZE * maxVSampFactor;
1352 const uint32_t nl = cinfo.next_scanline;
1353 JSAMPARRAY planes[3]{ &yLines[nl],
1354 &cbLines[nl/cVSubSampling],
1355 &crLines[nl/cVSubSampling] };
1356
1357 uint32_t done = jpeg_write_raw_data(&cinfo, planes, batchSize);
1358
1359 if (done != batchSize) {
1360 ALOGE("%s: compressed %u lines, expected %u (total %u/%u)",
1361 __FUNCTION__, done, batchSize, cinfo.next_scanline,
1362 cinfo.image_height);
1363 return -1;
1364 }
1365 }
1366
1367 /* This will flush everything */
1368 jpeg_finish_compress(&cinfo);
1369
1370 /* Grab the actual code size and set it */
1371 actualCodeSize = dmgr.mEncodedSize;
1372
1373 return 0;
1374}
1375
1376/*
1377 * TODO: There needs to be a mechanism to discover allocated buffer size
1378 * in the HAL.
1379 *
1380 * This is very fragile because it is duplicated computation from:
1381 * frameworks/av/services/camera/libcameraservice/device3/Camera3Device.cpp
1382 *
1383 */
1384
1385/* This assumes mSupportedFormats have all been declared as supporting
1386 * HAL_PIXEL_FORMAT_BLOB to the framework */
1387Size ExternalCameraDeviceSession::getMaxJpegResolution() const {
1388 Size ret { 0, 0 };
1389 for(auto & fmt : mSupportedFormats) {
1390 if(fmt.width * fmt.height > ret.width * ret.height) {
1391 ret = Size { fmt.width, fmt.height };
1392 }
1393 }
1394 return ret;
1395}
1396
1397Size ExternalCameraDeviceSession::getMaxThumbResolution() const {
1398 Size thumbSize { 0, 0 };
1399 camera_metadata_ro_entry entry =
1400 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
1401 for(uint32_t i = 0; i < entry.count; i += 2) {
1402 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
1403 static_cast<uint32_t>(entry.data.i32[i+1]) };
1404 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
1405 thumbSize = sz;
1406 }
1407 }
1408
1409 if (thumbSize.width * thumbSize.height == 0) {
1410 ALOGW("%s: non-zero thumbnail size not available", __FUNCTION__);
1411 }
1412
1413 return thumbSize;
1414}
1415
1416
1417ssize_t ExternalCameraDeviceSession::getJpegBufferSize(
1418 uint32_t width, uint32_t height) const {
1419 // Constant from camera3.h
1420 const ssize_t kMinJpegBufferSize = 256 * 1024 + sizeof(CameraBlob);
1421 // Get max jpeg size (area-wise).
1422 if (mMaxJpegResolution.width == 0) {
1423 ALOGE("%s: Do not have a single supported JPEG stream",
1424 __FUNCTION__);
1425 return BAD_VALUE;
1426 }
1427
1428 // Get max jpeg buffer size
1429 ssize_t maxJpegBufferSize = 0;
1430 camera_metadata_ro_entry jpegBufMaxSize =
1431 mCameraCharacteristics.find(ANDROID_JPEG_MAX_SIZE);
1432 if (jpegBufMaxSize.count == 0) {
1433 ALOGE("%s: Can't find maximum JPEG size in static metadata!",
1434 __FUNCTION__);
1435 return BAD_VALUE;
1436 }
1437 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
1438
1439 if (maxJpegBufferSize <= kMinJpegBufferSize) {
1440 ALOGE("%s: ANDROID_JPEG_MAX_SIZE (%zd) <= kMinJpegBufferSize (%zd)",
1441 __FUNCTION__, maxJpegBufferSize, kMinJpegBufferSize);
1442 return BAD_VALUE;
1443 }
1444
1445 // Calculate final jpeg buffer size for the given resolution.
1446 float scaleFactor = ((float) (width * height)) /
1447 (mMaxJpegResolution.width * mMaxJpegResolution.height);
1448 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
1449 kMinJpegBufferSize;
1450 if (jpegBufferSize > maxJpegBufferSize) {
1451 jpegBufferSize = maxJpegBufferSize;
1452 }
1453
1454 return jpegBufferSize;
1455}
1456
1457int ExternalCameraDeviceSession::OutputThread::createJpegLocked(
1458 HalStreamBuffer &halBuf,
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001459 const std::shared_ptr<HalRequest>& req)
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001460{
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001461 ATRACE_CALL();
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001462 int ret;
1463 auto lfail = [&](auto... args) {
1464 ALOGE(args...);
1465
1466 return 1;
1467 };
1468 auto parent = mParent.promote();
1469 if (parent == nullptr) {
1470 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1471 return 1;
1472 }
1473
1474 ALOGV("%s: HAL buffer sid: %d bid: %" PRIu64 " w: %u h: %u",
1475 __FUNCTION__, halBuf.streamId, static_cast<uint64_t>(halBuf.bufferId),
1476 halBuf.width, halBuf.height);
1477 ALOGV("%s: HAL buffer fmt: %x usage: %" PRIx64 " ptr: %p",
1478 __FUNCTION__, halBuf.format, static_cast<uint64_t>(halBuf.usage),
1479 halBuf.bufPtr);
1480 ALOGV("%s: YV12 buffer %d x %d",
1481 __FUNCTION__,
1482 mYu12Frame->mWidth, mYu12Frame->mHeight);
1483
1484 int jpegQuality, thumbQuality;
1485 Size thumbSize;
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001486 bool outputThumbnail = true;
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001487
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001488 if (req->setting.exists(ANDROID_JPEG_QUALITY)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001489 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001490 req->setting.find(ANDROID_JPEG_QUALITY);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001491 jpegQuality = entry.data.u8[0];
1492 } else {
1493 return lfail("%s: ANDROID_JPEG_QUALITY not set",__FUNCTION__);
1494 }
1495
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001496 if (req->setting.exists(ANDROID_JPEG_THUMBNAIL_QUALITY)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001497 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001498 req->setting.find(ANDROID_JPEG_THUMBNAIL_QUALITY);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001499 thumbQuality = entry.data.u8[0];
1500 } else {
1501 return lfail(
1502 "%s: ANDROID_JPEG_THUMBNAIL_QUALITY not set",
1503 __FUNCTION__);
1504 }
1505
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001506 if (req->setting.exists(ANDROID_JPEG_THUMBNAIL_SIZE)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001507 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001508 req->setting.find(ANDROID_JPEG_THUMBNAIL_SIZE);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001509 thumbSize = Size { static_cast<uint32_t>(entry.data.i32[0]),
1510 static_cast<uint32_t>(entry.data.i32[1])
1511 };
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001512 if (thumbSize.width == 0 && thumbSize.height == 0) {
1513 outputThumbnail = false;
1514 }
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001515 } else {
1516 return lfail(
1517 "%s: ANDROID_JPEG_THUMBNAIL_SIZE not set", __FUNCTION__);
1518 }
1519
1520 /* Cropped and scaled YU12 buffer for main and thumbnail */
1521 YCbCrLayout yu12Main;
1522 Size jpegSize { halBuf.width, halBuf.height };
1523
1524 /* Compute temporary buffer sizes accounting for the following:
1525 * thumbnail can't exceed APP1 size of 64K
1526 * main image needs to hold APP1, headers, and at most a poorly
1527 * compressed image */
1528 const ssize_t maxThumbCodeSize = 64 * 1024;
1529 const ssize_t maxJpegCodeSize = parent->getJpegBufferSize(jpegSize.width,
1530 jpegSize.height);
1531
1532 /* Check that getJpegBufferSize did not return an error */
1533 if (maxJpegCodeSize < 0) {
1534 return lfail(
1535 "%s: getJpegBufferSize returned %zd",__FUNCTION__,maxJpegCodeSize);
1536 }
1537
1538
1539 /* Hold actual thumbnail and main image code sizes */
1540 size_t thumbCodeSize = 0, jpegCodeSize = 0;
1541 /* Temporary thumbnail code buffer */
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001542 std::vector<uint8_t> thumbCode(outputThumbnail ? maxThumbCodeSize : 0);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001543
1544 YCbCrLayout yu12Thumb;
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001545 if (outputThumbnail) {
1546 ret = cropAndScaleThumbLocked(mYu12Frame, thumbSize, &yu12Thumb);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001547
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001548 if (ret != 0) {
1549 return lfail(
1550 "%s: crop and scale thumbnail failed!", __FUNCTION__);
1551 }
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001552 }
1553
1554 /* Scale and crop main jpeg */
1555 ret = cropAndScaleLocked(mYu12Frame, jpegSize, &yu12Main);
1556
1557 if (ret != 0) {
1558 return lfail("%s: crop and scale main failed!", __FUNCTION__);
1559 }
1560
1561 /* Encode the thumbnail image */
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001562 if (outputThumbnail) {
1563 ret = encodeJpegYU12(thumbSize, yu12Thumb,
1564 thumbQuality, 0, 0,
1565 &thumbCode[0], maxThumbCodeSize, thumbCodeSize);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001566
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001567 if (ret != 0) {
1568 return lfail("%s: thumbnail encodeJpegYU12 failed with %d",__FUNCTION__, ret);
1569 }
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001570 }
1571
1572 /* Combine camera characteristics with request settings to form EXIF
1573 * metadata */
1574 common::V1_0::helper::CameraMetadata meta(parent->mCameraCharacteristics);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001575 meta.append(req->setting);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001576
1577 /* Generate EXIF object */
1578 std::unique_ptr<ExifUtils> utils(ExifUtils::create());
1579 /* Make sure it's initialized */
1580 utils->initialize();
1581
1582 utils->setFromMetadata(meta, jpegSize.width, jpegSize.height);
1583
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001584 ret = utils->generateApp1(outputThumbnail ? &thumbCode[0] : 0, thumbCodeSize);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001585
1586 if (!ret) {
1587 return lfail("%s: generating APP1 failed", __FUNCTION__);
1588 }
1589
1590 /* Get internal buffer */
1591 size_t exifDataSize = utils->getApp1Length();
1592 const uint8_t* exifData = utils->getApp1Buffer();
1593
1594 /* Lock the HAL jpeg code buffer */
1595 void *bufPtr = sHandleImporter.lock(
1596 *(halBuf.bufPtr), halBuf.usage, maxJpegCodeSize);
1597
1598 if (!bufPtr) {
1599 return lfail("%s: could not lock %zu bytes", __FUNCTION__, maxJpegCodeSize);
1600 }
1601
1602 /* Encode the main jpeg image */
1603 ret = encodeJpegYU12(jpegSize, yu12Main,
1604 jpegQuality, exifData, exifDataSize,
1605 bufPtr, maxJpegCodeSize, jpegCodeSize);
1606
1607 /* TODO: Not sure this belongs here, maybe better to pass jpegCodeSize out
1608 * and do this when returning buffer to parent */
1609 CameraBlob blob { CameraBlobId::JPEG, static_cast<uint32_t>(jpegCodeSize) };
1610 void *blobDst =
1611 reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(bufPtr) +
1612 maxJpegCodeSize -
1613 sizeof(CameraBlob));
1614 memcpy(blobDst, &blob, sizeof(CameraBlob));
1615
1616 /* Unlock the HAL jpeg code buffer */
1617 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
1618 if (relFence > 0) {
1619 halBuf.acquireFence = relFence;
1620 }
1621
1622 /* Check if our JPEG actually succeeded */
1623 if (ret != 0) {
1624 return lfail(
1625 "%s: encodeJpegYU12 failed with %d",__FUNCTION__, ret);
1626 }
1627
1628 ALOGV("%s: encoded JPEG (ret:%d) with Q:%d max size: %zu",
1629 __FUNCTION__, ret, jpegQuality, maxJpegCodeSize);
1630
1631 return 0;
1632}
1633
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001634bool ExternalCameraDeviceSession::OutputThread::threadLoop() {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001635 std::shared_ptr<HalRequest> req;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001636 auto parent = mParent.promote();
1637 if (parent == nullptr) {
1638 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1639 return false;
1640 }
1641
1642 // TODO: maybe we need to setup a sensor thread to dq/enq v4l frames
1643 // regularly to prevent v4l buffer queue filled with stale buffers
1644 // when app doesn't program a preveiw request
1645 waitForNextRequest(&req);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001646 if (req == nullptr) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001647 // No new request, wait again
1648 return true;
1649 }
1650
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001651 auto onDeviceError = [&](auto... args) {
1652 ALOGE(args...);
1653 parent->notifyError(
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001654 req->frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001655 signalRequestDone();
1656 return false;
1657 };
1658
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001659 if (req->frameIn->mFourcc != V4L2_PIX_FMT_MJPEG) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001660 return onDeviceError("%s: do not support V4L2 format %c%c%c%c", __FUNCTION__,
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001661 req->frameIn->mFourcc & 0xFF,
1662 (req->frameIn->mFourcc >> 8) & 0xFF,
1663 (req->frameIn->mFourcc >> 16) & 0xFF,
1664 (req->frameIn->mFourcc >> 24) & 0xFF);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001665 }
1666
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001667 std::unique_lock<std::mutex> lk(mBufferLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001668 // Convert input V4L2 frame to YU12 of the same size
1669 // TODO: see if we can save some computation by converting to YV12 here
1670 uint8_t* inData;
1671 size_t inDataSize;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001672 req->frameIn->map(&inData, &inDataSize);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001673 // TODO: in some special case maybe we can decode jpg directly to gralloc output?
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001674 ATRACE_BEGIN("MJPGtoI420");
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001675 int res = libyuv::MJPGToI420(
1676 inData, inDataSize,
1677 static_cast<uint8_t*>(mYu12FrameLayout.y),
1678 mYu12FrameLayout.yStride,
1679 static_cast<uint8_t*>(mYu12FrameLayout.cb),
1680 mYu12FrameLayout.cStride,
1681 static_cast<uint8_t*>(mYu12FrameLayout.cr),
1682 mYu12FrameLayout.cStride,
1683 mYu12Frame->mWidth, mYu12Frame->mHeight,
1684 mYu12Frame->mWidth, mYu12Frame->mHeight);
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001685 ATRACE_END();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001686
1687 if (res != 0) {
1688 // For some webcam, the first few V4L2 frames might be malformed...
1689 ALOGE("%s: Convert V4L2 frame to YU12 failed! res %d", __FUNCTION__, res);
1690 lk.unlock();
1691 Status st = parent->processCaptureRequestError(req);
1692 if (st != Status::OK) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001693 return onDeviceError("%s: failed to process capture request error!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001694 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001695 signalRequestDone();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001696 return true;
1697 }
1698
1699 ALOGV("%s processing new request", __FUNCTION__);
1700 const int kSyncWaitTimeoutMs = 500;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001701 for (auto& halBuf : req->buffers) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001702 if (halBuf.acquireFence != -1) {
1703 int ret = sync_wait(halBuf.acquireFence, kSyncWaitTimeoutMs);
1704 if (ret) {
1705 halBuf.fenceTimeout = true;
1706 } else {
1707 ::close(halBuf.acquireFence);
Yin-Chia Yeh1e089662018-02-02 15:57:58 -08001708 halBuf.acquireFence = -1;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001709 }
1710 }
1711
1712 if (halBuf.fenceTimeout) {
1713 continue;
1714 }
1715
1716 // Gralloc lockYCbCr the buffer
1717 switch (halBuf.format) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001718 case PixelFormat::BLOB: {
1719 int ret = createJpegLocked(halBuf, req);
1720
1721 if(ret != 0) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001722 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001723 return onDeviceError("%s: createJpegLocked failed with %d",
1724 __FUNCTION__, ret);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001725 }
1726 } break;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001727 case PixelFormat::YCBCR_420_888:
1728 case PixelFormat::YV12: {
1729 IMapper::Rect outRect {0, 0,
1730 static_cast<int32_t>(halBuf.width),
1731 static_cast<int32_t>(halBuf.height)};
1732 YCbCrLayout outLayout = sHandleImporter.lockYCbCr(
1733 *(halBuf.bufPtr), halBuf.usage, outRect);
1734 ALOGV("%s: outLayout y %p cb %p cr %p y_str %d c_str %d c_step %d",
1735 __FUNCTION__, outLayout.y, outLayout.cb, outLayout.cr,
1736 outLayout.yStride, outLayout.cStride, outLayout.chromaStep);
1737
1738 // Convert to output buffer size/format
1739 uint32_t outputFourcc = getFourCcFromLayout(outLayout);
1740 ALOGV("%s: converting to format %c%c%c%c", __FUNCTION__,
1741 outputFourcc & 0xFF,
1742 (outputFourcc >> 8) & 0xFF,
1743 (outputFourcc >> 16) & 0xFF,
1744 (outputFourcc >> 24) & 0xFF);
1745
1746 YCbCrLayout cropAndScaled;
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001747 ATRACE_BEGIN("cropAndScaleLocked");
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001748 int ret = cropAndScaleLocked(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001749 mYu12Frame,
1750 Size { halBuf.width, halBuf.height },
1751 &cropAndScaled);
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001752 ATRACE_END();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001753 if (ret != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001754 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001755 return onDeviceError("%s: crop and scale failed!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001756 }
1757
1758 Size sz {halBuf.width, halBuf.height};
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001759 ATRACE_BEGIN("formatConvertLocked");
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001760 ret = formatConvertLocked(cropAndScaled, outLayout, sz, outputFourcc);
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001761 ATRACE_END();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001762 if (ret != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001763 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001764 return onDeviceError("%s: format coversion failed!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001765 }
1766 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
1767 if (relFence > 0) {
1768 halBuf.acquireFence = relFence;
1769 }
1770 } break;
1771 default:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001772 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001773 return onDeviceError("%s: unknown output format %x", __FUNCTION__, halBuf.format);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001774 }
1775 } // for each buffer
1776 mScaledYu12Frames.clear();
1777
1778 // Don't hold the lock while calling back to parent
1779 lk.unlock();
1780 Status st = parent->processCaptureResult(req);
1781 if (st != Status::OK) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001782 return onDeviceError("%s: failed to process capture result!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001783 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001784 signalRequestDone();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001785 return true;
1786}
1787
1788Status ExternalCameraDeviceSession::OutputThread::allocateIntermediateBuffers(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001789 const Size& v4lSize, const Size& thumbSize,
1790 const hidl_vec<Stream>& streams) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001791 std::lock_guard<std::mutex> lk(mBufferLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001792 if (mScaledYu12Frames.size() != 0) {
1793 ALOGE("%s: intermediate buffer pool has %zu inflight buffers! (expect 0)",
1794 __FUNCTION__, mScaledYu12Frames.size());
1795 return Status::INTERNAL_ERROR;
1796 }
1797
1798 // Allocating intermediate YU12 frame
1799 if (mYu12Frame == nullptr || mYu12Frame->mWidth != v4lSize.width ||
1800 mYu12Frame->mHeight != v4lSize.height) {
1801 mYu12Frame.clear();
1802 mYu12Frame = new AllocatedFrame(v4lSize.width, v4lSize.height);
1803 int ret = mYu12Frame->allocate(&mYu12FrameLayout);
1804 if (ret != 0) {
1805 ALOGE("%s: allocating YU12 frame failed!", __FUNCTION__);
1806 return Status::INTERNAL_ERROR;
1807 }
1808 }
1809
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001810 // Allocating intermediate YU12 thumbnail frame
1811 if (mYu12ThumbFrame == nullptr ||
1812 mYu12ThumbFrame->mWidth != thumbSize.width ||
1813 mYu12ThumbFrame->mHeight != thumbSize.height) {
1814 mYu12ThumbFrame.clear();
1815 mYu12ThumbFrame = new AllocatedFrame(thumbSize.width, thumbSize.height);
1816 int ret = mYu12ThumbFrame->allocate(&mYu12ThumbFrameLayout);
1817 if (ret != 0) {
1818 ALOGE("%s: allocating YU12 thumb frame failed!", __FUNCTION__);
1819 return Status::INTERNAL_ERROR;
1820 }
1821 }
1822
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001823 // Allocating scaled buffers
1824 for (const auto& stream : streams) {
1825 Size sz = {stream.width, stream.height};
1826 if (sz == v4lSize) {
1827 continue; // Don't need an intermediate buffer same size as v4lBuffer
1828 }
1829 if (mIntermediateBuffers.count(sz) == 0) {
1830 // Create new intermediate buffer
1831 sp<AllocatedFrame> buf = new AllocatedFrame(stream.width, stream.height);
1832 int ret = buf->allocate();
1833 if (ret != 0) {
1834 ALOGE("%s: allocating intermediate YU12 frame %dx%d failed!",
1835 __FUNCTION__, stream.width, stream.height);
1836 return Status::INTERNAL_ERROR;
1837 }
1838 mIntermediateBuffers[sz] = buf;
1839 }
1840 }
1841
1842 // Remove unconfigured buffers
1843 auto it = mIntermediateBuffers.begin();
1844 while (it != mIntermediateBuffers.end()) {
1845 bool configured = false;
1846 auto sz = it->first;
1847 for (const auto& stream : streams) {
1848 if (stream.width == sz.width && stream.height == sz.height) {
1849 configured = true;
1850 break;
1851 }
1852 }
1853 if (configured) {
1854 it++;
1855 } else {
1856 it = mIntermediateBuffers.erase(it);
1857 }
1858 }
1859 return Status::OK;
1860}
1861
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001862Status ExternalCameraDeviceSession::OutputThread::submitRequest(
1863 const std::shared_ptr<HalRequest>& req) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001864 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001865 mRequestList.push_back(req);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001866 lk.unlock();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001867 mRequestCond.notify_one();
1868 return Status::OK;
1869}
1870
1871void ExternalCameraDeviceSession::OutputThread::flush() {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001872 ATRACE_CALL();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001873 auto parent = mParent.promote();
1874 if (parent == nullptr) {
1875 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1876 return;
1877 }
1878
1879 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001880 std::list<std::shared_ptr<HalRequest>> reqs = std::move(mRequestList);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001881 mRequestList.clear();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001882 if (mProcessingRequest) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001883 std::chrono::seconds timeout = std::chrono::seconds(kFlushWaitTimeoutSec);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001884 auto st = mRequestDoneCond.wait_for(lk, timeout);
1885 if (st == std::cv_status::timeout) {
1886 ALOGE("%s: wait for inflight request finish timeout!", __FUNCTION__);
1887 }
1888 }
1889
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001890 ALOGV("%s: flusing inflight requests", __FUNCTION__);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001891 lk.unlock();
1892 for (const auto& req : reqs) {
1893 parent->processCaptureRequestError(req);
1894 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001895}
1896
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001897void ExternalCameraDeviceSession::OutputThread::waitForNextRequest(
1898 std::shared_ptr<HalRequest>* out) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001899 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001900 if (out == nullptr) {
1901 ALOGE("%s: out is null", __FUNCTION__);
1902 return;
1903 }
1904
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001905 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001906 int waitTimes = 0;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001907 while (mRequestList.empty()) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001908 if (exitPending()) {
1909 return;
1910 }
1911 std::chrono::milliseconds timeout = std::chrono::milliseconds(kReqWaitTimeoutMs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001912 auto st = mRequestCond.wait_for(lk, timeout);
1913 if (st == std::cv_status::timeout) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001914 waitTimes++;
1915 if (waitTimes == kReqWaitTimesMax) {
1916 // no new request, return
1917 return;
1918 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001919 }
1920 }
1921 *out = mRequestList.front();
1922 mRequestList.pop_front();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001923 mProcessingRequest = true;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001924 mProcessingFrameNumer = (*out)->frameNumber;
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001925}
1926
1927void ExternalCameraDeviceSession::OutputThread::signalRequestDone() {
1928 std::unique_lock<std::mutex> lk(mRequestListLock);
1929 mProcessingRequest = false;
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001930 mProcessingFrameNumer = 0;
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001931 lk.unlock();
1932 mRequestDoneCond.notify_one();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001933}
1934
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001935void ExternalCameraDeviceSession::OutputThread::dump(int fd) {
1936 std::lock_guard<std::mutex> lk(mRequestListLock);
1937 if (mProcessingRequest) {
1938 dprintf(fd, "OutputThread processing frame %d\n", mProcessingFrameNumer);
1939 } else {
1940 dprintf(fd, "OutputThread not processing any frames\n");
1941 }
1942 dprintf(fd, "OutputThread request list contains frame: ");
1943 for (const auto& req : mRequestList) {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001944 dprintf(fd, "%d, ", req->frameNumber);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001945 }
1946 dprintf(fd, "\n");
1947}
1948
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001949void ExternalCameraDeviceSession::cleanupBuffersLocked(int id) {
1950 for (auto& pair : mCirculatingBuffers.at(id)) {
1951 sHandleImporter.freeBuffer(pair.second);
1952 }
1953 mCirculatingBuffers[id].clear();
1954 mCirculatingBuffers.erase(id);
1955}
1956
1957void ExternalCameraDeviceSession::updateBufferCaches(const hidl_vec<BufferCache>& cachesToRemove) {
1958 Mutex::Autolock _l(mLock);
1959 for (auto& cache : cachesToRemove) {
1960 auto cbsIt = mCirculatingBuffers.find(cache.streamId);
1961 if (cbsIt == mCirculatingBuffers.end()) {
1962 // The stream could have been removed
1963 continue;
1964 }
1965 CirculatingBuffers& cbs = cbsIt->second;
1966 auto it = cbs.find(cache.bufferId);
1967 if (it != cbs.end()) {
1968 sHandleImporter.freeBuffer(it->second);
1969 cbs.erase(it);
1970 } else {
1971 ALOGE("%s: stream %d buffer %" PRIu64 " is not cached",
1972 __FUNCTION__, cache.streamId, cache.bufferId);
1973 }
1974 }
1975}
1976
1977bool ExternalCameraDeviceSession::isSupported(const Stream& stream) {
1978 int32_t ds = static_cast<int32_t>(stream.dataSpace);
1979 PixelFormat fmt = stream.format;
1980 uint32_t width = stream.width;
1981 uint32_t height = stream.height;
1982 // TODO: check usage flags
1983
1984 if (stream.streamType != StreamType::OUTPUT) {
1985 ALOGE("%s: does not support non-output stream type", __FUNCTION__);
1986 return false;
1987 }
1988
1989 if (stream.rotation != StreamRotation::ROTATION_0) {
1990 ALOGE("%s: does not support stream rotation", __FUNCTION__);
1991 return false;
1992 }
1993
1994 if (ds & Dataspace::DEPTH) {
1995 ALOGI("%s: does not support depth output", __FUNCTION__);
1996 return false;
1997 }
1998
1999 switch (fmt) {
2000 case PixelFormat::BLOB:
2001 if (ds != static_cast<int32_t>(Dataspace::V0_JFIF)) {
2002 ALOGI("%s: BLOB format does not support dataSpace %x", __FUNCTION__, ds);
2003 return false;
2004 }
2005 case PixelFormat::IMPLEMENTATION_DEFINED:
2006 case PixelFormat::YCBCR_420_888:
2007 case PixelFormat::YV12:
2008 // TODO: check what dataspace we can support here.
2009 // intentional no-ops.
2010 break;
2011 default:
2012 ALOGI("%s: does not support format %x", __FUNCTION__, fmt);
2013 return false;
2014 }
2015
2016 // Assume we can convert any V4L2 format to any of supported output format for now, i.e,
2017 // ignoring v4l2Fmt.fourcc for now. Might need more subtle check if we support more v4l format
2018 // in the futrue.
2019 for (const auto& v4l2Fmt : mSupportedFormats) {
2020 if (width == v4l2Fmt.width && height == v4l2Fmt.height) {
2021 return true;
2022 }
2023 }
2024 ALOGI("%s: resolution %dx%d is not supported", __FUNCTION__, width, height);
2025 return false;
2026}
2027
2028int ExternalCameraDeviceSession::v4l2StreamOffLocked() {
2029 if (!mV4l2Streaming) {
2030 return OK;
2031 }
2032
2033 {
2034 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2035 if (mNumDequeuedV4l2Buffers != 0) {
2036 ALOGE("%s: there are %zu inflight V4L buffers",
2037 __FUNCTION__, mNumDequeuedV4l2Buffers);
2038 return -1;
2039 }
2040 }
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002041 mV4L2BufferCount = 0;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002042
2043 // VIDIOC_STREAMOFF
2044 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2045 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMOFF, &capture_type)) < 0) {
2046 ALOGE("%s: STREAMOFF failed: %s", __FUNCTION__, strerror(errno));
2047 return -errno;
2048 }
2049
2050 // VIDIOC_REQBUFS: clear buffers
2051 v4l2_requestbuffers req_buffers{};
2052 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2053 req_buffers.memory = V4L2_MEMORY_MMAP;
2054 req_buffers.count = 0;
2055 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
2056 ALOGE("%s: REQBUFS failed: %s", __FUNCTION__, strerror(errno));
2057 return -errno;
2058 }
2059
2060 mV4l2Streaming = false;
2061 return OK;
2062}
2063
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002064int ExternalCameraDeviceSession::setV4l2FpsLocked(double fps) {
2065 // VIDIOC_G_PARM/VIDIOC_S_PARM: set fps
2066 v4l2_streamparm streamparm = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
2067 // The following line checks that the driver knows about framerate get/set.
2068 int ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_G_PARM, &streamparm));
2069 if (ret != 0) {
2070 if (errno == -EINVAL) {
2071 ALOGW("%s: device does not support VIDIOC_G_PARM", __FUNCTION__);
2072 }
2073 return -errno;
2074 }
2075 // Now check if the device is able to accept a capture framerate set.
2076 if (!(streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME)) {
2077 ALOGW("%s: device does not support V4L2_CAP_TIMEPERFRAME", __FUNCTION__);
2078 return -EINVAL;
2079 }
2080
2081 // fps is float, approximate by a fraction.
2082 const int kFrameRatePrecision = 10000;
2083 streamparm.parm.capture.timeperframe.numerator = kFrameRatePrecision;
2084 streamparm.parm.capture.timeperframe.denominator =
2085 (fps * kFrameRatePrecision);
2086
2087 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_PARM, &streamparm)) < 0) {
2088 ALOGE("%s: failed to set framerate to %f: %s", __FUNCTION__, fps, strerror(errno));
2089 return -1;
2090 }
2091
2092 double retFps = streamparm.parm.capture.timeperframe.denominator /
2093 static_cast<double>(streamparm.parm.capture.timeperframe.numerator);
2094 if (std::fabs(fps - retFps) > 1.0) {
2095 ALOGE("%s: expect fps %f, got %f instead", __FUNCTION__, fps, retFps);
2096 return -1;
2097 }
2098 mV4l2StreamingFps = fps;
2099 return 0;
2100}
2101
2102int ExternalCameraDeviceSession::configureV4l2StreamLocked(
2103 const SupportedV4L2Format& v4l2Fmt, double requestFps) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002104 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002105 int ret = v4l2StreamOffLocked();
2106 if (ret != OK) {
2107 ALOGE("%s: stop v4l2 streaming failed: ret %d", __FUNCTION__, ret);
2108 return ret;
2109 }
2110
2111 // VIDIOC_S_FMT w/h/fmt
2112 v4l2_format fmt;
2113 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2114 fmt.fmt.pix.width = v4l2Fmt.width;
2115 fmt.fmt.pix.height = v4l2Fmt.height;
2116 fmt.fmt.pix.pixelformat = v4l2Fmt.fourcc;
2117 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt));
2118 if (ret < 0) {
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08002119 int numAttempt = 0;
2120 while (ret < 0) {
2121 ALOGW("%s: VIDIOC_S_FMT failed, wait 33ms and try again", __FUNCTION__);
2122 usleep(IOCTL_RETRY_SLEEP_US); // sleep 100 ms and try again
2123 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt));
2124 if (numAttempt == MAX_RETRY) {
2125 break;
2126 }
2127 numAttempt++;
2128 }
2129 if (ret < 0) {
2130 ALOGE("%s: S_FMT ioctl failed: %s", __FUNCTION__, strerror(errno));
2131 return -errno;
2132 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002133 }
2134
2135 if (v4l2Fmt.width != fmt.fmt.pix.width || v4l2Fmt.height != fmt.fmt.pix.height ||
2136 v4l2Fmt.fourcc != fmt.fmt.pix.pixelformat) {
2137 ALOGE("%s: S_FMT expect %c%c%c%c %dx%d, got %c%c%c%c %dx%d instead!", __FUNCTION__,
2138 v4l2Fmt.fourcc & 0xFF,
2139 (v4l2Fmt.fourcc >> 8) & 0xFF,
2140 (v4l2Fmt.fourcc >> 16) & 0xFF,
2141 (v4l2Fmt.fourcc >> 24) & 0xFF,
2142 v4l2Fmt.width, v4l2Fmt.height,
2143 fmt.fmt.pix.pixelformat & 0xFF,
2144 (fmt.fmt.pix.pixelformat >> 8) & 0xFF,
2145 (fmt.fmt.pix.pixelformat >> 16) & 0xFF,
2146 (fmt.fmt.pix.pixelformat >> 24) & 0xFF,
2147 fmt.fmt.pix.width, fmt.fmt.pix.height);
2148 return -EINVAL;
2149 }
2150 uint32_t bufferSize = fmt.fmt.pix.sizeimage;
2151 ALOGI("%s: V4L2 buffer size is %d", __FUNCTION__, bufferSize);
Emilian Peevbc0e1652018-04-03 13:28:46 +01002152 uint32_t expectedMaxBufferSize = kMaxBytesPerPixel * fmt.fmt.pix.width * fmt.fmt.pix.height;
2153 if ((bufferSize == 0) || (bufferSize > expectedMaxBufferSize)) {
2154 ALOGE("%s: V4L2 buffer size: %u looks invalid. Expected maximum size: %u", __FUNCTION__,
2155 bufferSize, expectedMaxBufferSize);
2156 return -EINVAL;
2157 }
2158 mMaxV4L2BufferSize = bufferSize;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002159
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002160 const double kDefaultFps = 30.0;
2161 double fps = 1000.0;
2162 if (requestFps != 0.0) {
2163 fps = requestFps;
2164 } else {
2165 double maxFps = -1.0;
2166 // Try to pick the slowest fps that is at least 30
2167 for (const auto& fr : v4l2Fmt.frameRates) {
2168 double f = fr.getDouble();
2169 if (maxFps < f) {
2170 maxFps = f;
2171 }
2172 if (f >= kDefaultFps && f < fps) {
2173 fps = f;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002174 }
2175 }
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002176 if (fps == 1000.0) {
2177 fps = maxFps;
2178 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002179 }
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002180
2181 int fpsRet = setV4l2FpsLocked(fps);
2182 if (fpsRet != 0 && fpsRet != -EINVAL) {
2183 ALOGE("%s: set fps failed: %s", __FUNCTION__, strerror(fpsRet));
2184 return fpsRet;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002185 }
2186
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -08002187 uint32_t v4lBufferCount = (fps >= kDefaultFps) ?
2188 mCfg.numVideoBuffers : mCfg.numStillBuffers;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002189 // VIDIOC_REQBUFS: create buffers
2190 v4l2_requestbuffers req_buffers{};
2191 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2192 req_buffers.memory = V4L2_MEMORY_MMAP;
2193 req_buffers.count = v4lBufferCount;
2194 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
2195 ALOGE("%s: VIDIOC_REQBUFS failed: %s", __FUNCTION__, strerror(errno));
2196 return -errno;
2197 }
2198
2199 // Driver can indeed return more buffer if it needs more to operate
2200 if (req_buffers.count < v4lBufferCount) {
2201 ALOGE("%s: VIDIOC_REQBUFS expected %d buffers, got %d instead",
2202 __FUNCTION__, v4lBufferCount, req_buffers.count);
2203 return NO_MEMORY;
2204 }
2205
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002206 // VIDIOC_QUERYBUF: get buffer offset in the V4L2 fd
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002207 // VIDIOC_QBUF: send buffer to driver
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002208 mV4L2BufferCount = req_buffers.count;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002209 for (uint32_t i = 0; i < req_buffers.count; i++) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002210 v4l2_buffer buffer = {
2211 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
2212 .index = i,
2213 .memory = V4L2_MEMORY_MMAP};
2214
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002215 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QUERYBUF, &buffer)) < 0) {
2216 ALOGE("%s: QUERYBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
2217 return -errno;
2218 }
2219
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002220 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2221 ALOGE("%s: QBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
2222 return -errno;
2223 }
2224 }
2225
2226 // VIDIOC_STREAMON: start streaming
2227 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08002228 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type));
2229 if (ret < 0) {
2230 int numAttempt = 0;
2231 while (ret < 0) {
2232 ALOGW("%s: VIDIOC_STREAMON failed, wait 33ms and try again", __FUNCTION__);
2233 usleep(IOCTL_RETRY_SLEEP_US); // sleep 100 ms and try again
2234 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type));
2235 if (numAttempt == MAX_RETRY) {
2236 break;
2237 }
2238 numAttempt++;
2239 }
2240 if (ret < 0) {
2241 ALOGE("%s: VIDIOC_STREAMON ioctl failed: %s", __FUNCTION__, strerror(errno));
2242 return -errno;
2243 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002244 }
2245
2246 // Swallow first few frames after streamOn to account for bad frames from some devices
2247 for (int i = 0; i < kBadFramesAfterStreamOn; i++) {
2248 v4l2_buffer buffer{};
2249 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2250 buffer.memory = V4L2_MEMORY_MMAP;
2251 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
2252 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
2253 return -errno;
2254 }
2255
2256 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2257 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, buffer.index, strerror(errno));
2258 return -errno;
2259 }
2260 }
2261
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08002262 ALOGI("%s: start V4L2 streaming %dx%d@%ffps",
2263 __FUNCTION__, v4l2Fmt.width, v4l2Fmt.height, fps);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002264 mV4l2StreamingFmt = v4l2Fmt;
2265 mV4l2Streaming = true;
2266 return OK;
2267}
2268
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002269sp<V4L2Frame> ExternalCameraDeviceSession::dequeueV4l2FrameLocked(/*out*/nsecs_t* shutterTs) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002270 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002271 sp<V4L2Frame> ret = nullptr;
2272
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002273 if (shutterTs == nullptr) {
2274 ALOGE("%s: shutterTs must not be null!", __FUNCTION__);
2275 return ret;
2276 }
2277
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002278 {
2279 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002280 if (mNumDequeuedV4l2Buffers == mV4L2BufferCount) {
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002281 int waitRet = waitForV4L2BufferReturnLocked(lk);
2282 if (waitRet != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002283 return ret;
2284 }
2285 }
2286 }
2287
2288 v4l2_buffer buffer{};
2289 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2290 buffer.memory = V4L2_MEMORY_MMAP;
2291 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
2292 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
2293 return ret;
2294 }
2295
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002296 if (buffer.index >= mV4L2BufferCount) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002297 ALOGE("%s: Invalid buffer id: %d", __FUNCTION__, buffer.index);
2298 return ret;
2299 }
2300
2301 if (buffer.flags & V4L2_BUF_FLAG_ERROR) {
2302 ALOGE("%s: v4l2 buf error! buf flag 0x%x", __FUNCTION__, buffer.flags);
2303 // TODO: try to dequeue again
2304 }
2305
Emilian Peevbc0e1652018-04-03 13:28:46 +01002306 if (buffer.bytesused > mMaxV4L2BufferSize) {
2307 ALOGE("%s: v4l2 buffer bytes used: %u maximum %u", __FUNCTION__, buffer.bytesused,
2308 mMaxV4L2BufferSize);
2309 return ret;
2310 }
2311
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002312 if (buffer.flags & V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC) {
2313 // Ideally we should also check for V4L2_BUF_FLAG_TSTAMP_SRC_SOE, but
2314 // even V4L2_BUF_FLAG_TSTAMP_SRC_EOF is better than capture a timestamp now
2315 *shutterTs = static_cast<nsecs_t>(buffer.timestamp.tv_sec)*1000000000LL +
2316 buffer.timestamp.tv_usec * 1000LL;
2317 } else {
2318 *shutterTs = systemTime(SYSTEM_TIME_MONOTONIC);
2319 }
2320
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002321 {
2322 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2323 mNumDequeuedV4l2Buffers++;
2324 }
2325 return new V4L2Frame(
2326 mV4l2StreamingFmt.width, mV4l2StreamingFmt.height, mV4l2StreamingFmt.fourcc,
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002327 buffer.index, mV4l2Fd.get(), buffer.bytesused, buffer.m.offset);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002328}
2329
2330void ExternalCameraDeviceSession::enqueueV4l2Frame(const sp<V4L2Frame>& frame) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002331 ATRACE_CALL();
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002332 {
2333 // Release mLock before acquiring mV4l2BufferLock to avoid potential
2334 // deadlock
2335 Mutex::Autolock _l(mLock);
2336 frame->unmap();
2337 v4l2_buffer buffer{};
2338 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2339 buffer.memory = V4L2_MEMORY_MMAP;
2340 buffer.index = frame->mBufferIndex;
2341 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2342 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__,
2343 frame->mBufferIndex, strerror(errno));
2344 return;
2345 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002346 }
2347
2348 {
2349 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2350 mNumDequeuedV4l2Buffers--;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002351 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002352 mV4L2BufferReturned.notify_one();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002353}
2354
2355Status ExternalCameraDeviceSession::configureStreams(
2356 const V3_2::StreamConfiguration& config, V3_3::HalStreamConfiguration* out) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002357 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002358 if (config.operationMode != StreamConfigurationMode::NORMAL_MODE) {
2359 ALOGE("%s: unsupported operation mode: %d", __FUNCTION__, config.operationMode);
2360 return Status::ILLEGAL_ARGUMENT;
2361 }
2362
2363 if (config.streams.size() == 0) {
2364 ALOGE("%s: cannot configure zero stream", __FUNCTION__);
2365 return Status::ILLEGAL_ARGUMENT;
2366 }
2367
2368 int numProcessedStream = 0;
2369 int numStallStream = 0;
2370 for (const auto& stream : config.streams) {
2371 // Check if the format/width/height combo is supported
2372 if (!isSupported(stream)) {
2373 return Status::ILLEGAL_ARGUMENT;
2374 }
2375 if (stream.format == PixelFormat::BLOB) {
2376 numStallStream++;
2377 } else {
2378 numProcessedStream++;
2379 }
2380 }
2381
2382 if (numProcessedStream > kMaxProcessedStream) {
2383 ALOGE("%s: too many processed streams (expect <= %d, got %d)", __FUNCTION__,
2384 kMaxProcessedStream, numProcessedStream);
2385 return Status::ILLEGAL_ARGUMENT;
2386 }
2387
2388 if (numStallStream > kMaxStallStream) {
2389 ALOGE("%s: too many stall streams (expect <= %d, got %d)", __FUNCTION__,
2390 kMaxStallStream, numStallStream);
2391 return Status::ILLEGAL_ARGUMENT;
2392 }
2393
2394 Status status = initStatus();
2395 if (status != Status::OK) {
2396 return status;
2397 }
2398
2399 Mutex::Autolock _l(mLock);
2400 if (!mInflightFrames.empty()) {
2401 ALOGE("%s: trying to configureStreams while there are still %zu inflight frames!",
2402 __FUNCTION__, mInflightFrames.size());
2403 return Status::INTERNAL_ERROR;
2404 }
2405
2406 // Add new streams
2407 for (const auto& stream : config.streams) {
2408 if (mStreamMap.count(stream.id) == 0) {
2409 mStreamMap[stream.id] = stream;
2410 mCirculatingBuffers.emplace(stream.id, CirculatingBuffers{});
2411 }
2412 }
2413
2414 // Cleanup removed streams
2415 for(auto it = mStreamMap.begin(); it != mStreamMap.end();) {
2416 int id = it->first;
2417 bool found = false;
2418 for (const auto& stream : config.streams) {
2419 if (id == stream.id) {
2420 found = true;
2421 break;
2422 }
2423 }
2424 if (!found) {
2425 // Unmap all buffers of deleted stream
2426 cleanupBuffersLocked(id);
2427 it = mStreamMap.erase(it);
2428 } else {
2429 ++it;
2430 }
2431 }
2432
2433 // Now select a V4L2 format to produce all output streams
2434 float desiredAr = (mCroppingType == VERTICAL) ? kMaxAspectRatio : kMinAspectRatio;
2435 uint32_t maxDim = 0;
2436 for (const auto& stream : config.streams) {
2437 float aspectRatio = ASPECT_RATIO(stream);
Yin-Chia Yehc15a1ca2018-03-02 14:16:52 -08002438 ALOGI("%s: request stream %dx%d", __FUNCTION__, stream.width, stream.height);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002439 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2440 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2441 desiredAr = aspectRatio;
2442 }
2443
2444 // The dimension that's not cropped
2445 uint32_t dim = (mCroppingType == VERTICAL) ? stream.width : stream.height;
2446 if (dim > maxDim) {
2447 maxDim = dim;
2448 }
2449 }
2450 // Find the smallest format that matches the desired aspect ratio and is wide/high enough
2451 SupportedV4L2Format v4l2Fmt {.width = 0, .height = 0};
2452 for (const auto& fmt : mSupportedFormats) {
2453 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2454 if (dim >= maxDim) {
2455 float aspectRatio = ASPECT_RATIO(fmt);
2456 if (isAspectRatioClose(aspectRatio, desiredAr)) {
2457 v4l2Fmt = fmt;
2458 // since mSupportedFormats is sorted by width then height, the first matching fmt
2459 // will be the smallest one with matching aspect ratio
2460 break;
2461 }
2462 }
2463 }
2464 if (v4l2Fmt.width == 0) {
2465 // Cannot find exact good aspect ratio candidate, try to find a close one
2466 for (const auto& fmt : mSupportedFormats) {
2467 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2468 if (dim >= maxDim) {
2469 float aspectRatio = ASPECT_RATIO(fmt);
2470 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2471 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2472 v4l2Fmt = fmt;
2473 break;
2474 }
2475 }
2476 }
2477 }
2478
2479 if (v4l2Fmt.width == 0) {
2480 ALOGE("%s: unable to find a resolution matching (%s at least %d, aspect ratio %f)"
2481 , __FUNCTION__, (mCroppingType == VERTICAL) ? "width" : "height",
2482 maxDim, desiredAr);
2483 return Status::ILLEGAL_ARGUMENT;
2484 }
2485
2486 if (configureV4l2StreamLocked(v4l2Fmt) != 0) {
2487 ALOGE("V4L configuration failed!, format:%c%c%c%c, w %d, h %d",
2488 v4l2Fmt.fourcc & 0xFF,
2489 (v4l2Fmt.fourcc >> 8) & 0xFF,
2490 (v4l2Fmt.fourcc >> 16) & 0xFF,
2491 (v4l2Fmt.fourcc >> 24) & 0xFF,
2492 v4l2Fmt.width, v4l2Fmt.height);
2493 return Status::INTERNAL_ERROR;
2494 }
2495
2496 Size v4lSize = {v4l2Fmt.width, v4l2Fmt.height};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08002497 Size thumbSize { 0, 0 };
2498 camera_metadata_ro_entry entry =
2499 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
2500 for(uint32_t i = 0; i < entry.count; i += 2) {
2501 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
2502 static_cast<uint32_t>(entry.data.i32[i+1]) };
2503 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
2504 thumbSize = sz;
2505 }
2506 }
2507
2508 if (thumbSize.width * thumbSize.height == 0) {
2509 ALOGE("%s: non-zero thumbnail size not available", __FUNCTION__);
2510 return Status::INTERNAL_ERROR;
2511 }
2512
2513 status = mOutputThread->allocateIntermediateBuffers(v4lSize,
2514 mMaxThumbResolution, config.streams);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002515 if (status != Status::OK) {
2516 ALOGE("%s: allocating intermediate buffers failed!", __FUNCTION__);
2517 return status;
2518 }
2519
2520 out->streams.resize(config.streams.size());
2521 for (size_t i = 0; i < config.streams.size(); i++) {
2522 out->streams[i].overrideDataSpace = config.streams[i].dataSpace;
2523 out->streams[i].v3_2.id = config.streams[i].id;
2524 // TODO: double check should we add those CAMERA flags
2525 mStreamMap[config.streams[i].id].usage =
2526 out->streams[i].v3_2.producerUsage = config.streams[i].usage |
2527 BufferUsage::CPU_WRITE_OFTEN |
2528 BufferUsage::CAMERA_OUTPUT;
2529 out->streams[i].v3_2.consumerUsage = 0;
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002530 out->streams[i].v3_2.maxBuffers = mV4L2BufferCount;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002531
2532 switch (config.streams[i].format) {
2533 case PixelFormat::BLOB:
2534 case PixelFormat::YCBCR_420_888:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002535 case PixelFormat::YV12: // Used by SurfaceTexture
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002536 // No override
2537 out->streams[i].v3_2.overrideFormat = config.streams[i].format;
2538 break;
2539 case PixelFormat::IMPLEMENTATION_DEFINED:
2540 // Override based on VIDEO or not
2541 out->streams[i].v3_2.overrideFormat =
2542 (config.streams[i].usage & BufferUsage::VIDEO_ENCODER) ?
2543 PixelFormat::YCBCR_420_888 : PixelFormat::YV12;
2544 // Save overridden formt in mStreamMap
2545 mStreamMap[config.streams[i].id].format = out->streams[i].v3_2.overrideFormat;
2546 break;
2547 default:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002548 ALOGE("%s: unsupported format 0x%x", __FUNCTION__, config.streams[i].format);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002549 return Status::ILLEGAL_ARGUMENT;
2550 }
2551 }
2552
2553 mFirstRequest = true;
2554 return Status::OK;
2555}
2556
2557bool ExternalCameraDeviceSession::isClosed() {
2558 Mutex::Autolock _l(mLock);
2559 return mClosed;
2560}
2561
2562#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
2563#define UPDATE(md, tag, data, size) \
2564do { \
2565 if ((md).update((tag), (data), (size))) { \
2566 ALOGE("Update " #tag " failed!"); \
2567 return BAD_VALUE; \
2568 } \
2569} while (0)
2570
2571status_t ExternalCameraDeviceSession::initDefaultRequests() {
2572 ::android::hardware::camera::common::V1_0::helper::CameraMetadata md;
2573
2574 const uint8_t aberrationMode = ANDROID_COLOR_CORRECTION_ABERRATION_MODE_OFF;
2575 UPDATE(md, ANDROID_COLOR_CORRECTION_ABERRATION_MODE, &aberrationMode, 1);
2576
2577 const int32_t exposureCompensation = 0;
2578 UPDATE(md, ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION, &exposureCompensation, 1);
2579
2580 const uint8_t videoStabilizationMode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
2581 UPDATE(md, ANDROID_CONTROL_VIDEO_STABILIZATION_MODE, &videoStabilizationMode, 1);
2582
2583 const uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO;
2584 UPDATE(md, ANDROID_CONTROL_AWB_MODE, &awbMode, 1);
2585
2586 const uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON;
2587 UPDATE(md, ANDROID_CONTROL_AE_MODE, &aeMode, 1);
2588
2589 const uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
2590 UPDATE(md, ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
2591
2592 const uint8_t afMode = ANDROID_CONTROL_AF_MODE_AUTO;
2593 UPDATE(md, ANDROID_CONTROL_AF_MODE, &afMode, 1);
2594
2595 const uint8_t afTrigger = ANDROID_CONTROL_AF_TRIGGER_IDLE;
2596 UPDATE(md, ANDROID_CONTROL_AF_TRIGGER, &afTrigger, 1);
2597
2598 const uint8_t sceneMode = ANDROID_CONTROL_SCENE_MODE_DISABLED;
2599 UPDATE(md, ANDROID_CONTROL_SCENE_MODE, &sceneMode, 1);
2600
2601 const uint8_t effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF;
2602 UPDATE(md, ANDROID_CONTROL_EFFECT_MODE, &effectMode, 1);
2603
2604 const uint8_t flashMode = ANDROID_FLASH_MODE_OFF;
2605 UPDATE(md, ANDROID_FLASH_MODE, &flashMode, 1);
2606
2607 const int32_t thumbnailSize[] = {240, 180};
2608 UPDATE(md, ANDROID_JPEG_THUMBNAIL_SIZE, thumbnailSize, 2);
2609
2610 const uint8_t jpegQuality = 90;
2611 UPDATE(md, ANDROID_JPEG_QUALITY, &jpegQuality, 1);
2612 UPDATE(md, ANDROID_JPEG_THUMBNAIL_QUALITY, &jpegQuality, 1);
2613
2614 const int32_t jpegOrientation = 0;
2615 UPDATE(md, ANDROID_JPEG_ORIENTATION, &jpegOrientation, 1);
2616
2617 const uint8_t oisMode = ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF;
2618 UPDATE(md, ANDROID_LENS_OPTICAL_STABILIZATION_MODE, &oisMode, 1);
2619
2620 const uint8_t nrMode = ANDROID_NOISE_REDUCTION_MODE_OFF;
2621 UPDATE(md, ANDROID_NOISE_REDUCTION_MODE, &nrMode, 1);
2622
Yin-Chia Yehc15a1ca2018-03-02 14:16:52 -08002623 const int32_t testPatternModes = ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2624 UPDATE(md, ANDROID_SENSOR_TEST_PATTERN_MODE, &testPatternModes, 1);
2625
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002626 const uint8_t fdMode = ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
2627 UPDATE(md, ANDROID_STATISTICS_FACE_DETECT_MODE, &fdMode, 1);
2628
2629 const uint8_t hotpixelMode = ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF;
2630 UPDATE(md, ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE, &hotpixelMode, 1);
2631
2632 bool support30Fps = false;
2633 int32_t maxFps = std::numeric_limits<int32_t>::min();
2634 for (const auto& supportedFormat : mSupportedFormats) {
Yin-Chia Yeh134093a2018-02-12 14:05:48 -08002635 for (const auto& fr : supportedFormat.frameRates) {
2636 int32_t framerateInt = static_cast<int32_t>(fr.getDouble());
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002637 if (maxFps < framerateInt) {
2638 maxFps = framerateInt;
2639 }
2640 if (framerateInt == 30) {
2641 support30Fps = true;
2642 break;
2643 }
2644 }
2645 if (support30Fps) {
2646 break;
2647 }
2648 }
2649 int32_t defaultFramerate = support30Fps ? 30 : maxFps;
Yin-Chia Yehc15a1ca2018-03-02 14:16:52 -08002650 int32_t defaultFpsRange[] = {defaultFramerate / 2, defaultFramerate};
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002651 UPDATE(md, ANDROID_CONTROL_AE_TARGET_FPS_RANGE, defaultFpsRange, ARRAY_SIZE(defaultFpsRange));
2652
2653 uint8_t antibandingMode = ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO;
2654 UPDATE(md, ANDROID_CONTROL_AE_ANTIBANDING_MODE, &antibandingMode, 1);
2655
2656 const uint8_t controlMode = ANDROID_CONTROL_MODE_AUTO;
2657 UPDATE(md, ANDROID_CONTROL_MODE, &controlMode, 1);
2658
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002659 auto requestTemplates = hidl_enum_iterator<RequestTemplate>();
2660 for (RequestTemplate type : requestTemplates) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002661 ::android::hardware::camera::common::V1_0::helper::CameraMetadata mdCopy = md;
2662 uint8_t intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2663 switch (type) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002664 case RequestTemplate::PREVIEW:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002665 intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2666 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002667 case RequestTemplate::STILL_CAPTURE:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002668 intent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE;
2669 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002670 case RequestTemplate::VIDEO_RECORD:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002671 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD;
2672 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002673 case RequestTemplate::VIDEO_SNAPSHOT:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002674 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT;
2675 break;
2676 default:
Yuriy Romanenko083de0c2018-01-26 16:05:54 -08002677 ALOGV("%s: unsupported RequestTemplate type %d", __FUNCTION__, type);
2678 continue;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002679 }
2680 UPDATE(mdCopy, ANDROID_CONTROL_CAPTURE_INTENT, &intent, 1);
2681
2682 camera_metadata_t* rawMd = mdCopy.release();
2683 CameraMetadata hidlMd;
2684 hidlMd.setToExternal(
2685 (uint8_t*) rawMd, get_camera_metadata_size(rawMd));
2686 mDefaultRequests[type] = hidlMd;
2687 free_camera_metadata(rawMd);
2688 }
2689
2690 return OK;
2691}
2692
2693status_t ExternalCameraDeviceSession::fillCaptureResult(
2694 common::V1_0::helper::CameraMetadata &md, nsecs_t timestamp) {
2695 // android.control
2696 // For USB camera, we don't know the AE state. Set the state to converged to
2697 // indicate the frame should be good to use. Then apps don't have to wait the
2698 // AE state.
2699 const uint8_t aeState = ANDROID_CONTROL_AE_STATE_CONVERGED;
2700 UPDATE(md, ANDROID_CONTROL_AE_STATE, &aeState, 1);
2701
2702 const uint8_t ae_lock = ANDROID_CONTROL_AE_LOCK_OFF;
2703 UPDATE(md, ANDROID_CONTROL_AE_LOCK, &ae_lock, 1);
2704
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002705 bool afTrigger = mAfTrigger;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002706 if (md.exists(ANDROID_CONTROL_AF_TRIGGER)) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002707 Mutex::Autolock _l(mLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002708 camera_metadata_entry entry = md.find(ANDROID_CONTROL_AF_TRIGGER);
2709 if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_START) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002710 mAfTrigger = afTrigger = true;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002711 } else if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_CANCEL) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002712 mAfTrigger = afTrigger = false;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002713 }
2714 }
2715
2716 // For USB camera, the USB camera handles everything and we don't have control
2717 // over AF. We only simply fake the AF metadata based on the request
2718 // received here.
2719 uint8_t afState;
2720 if (afTrigger) {
2721 afState = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
2722 } else {
2723 afState = ANDROID_CONTROL_AF_STATE_INACTIVE;
2724 }
2725 UPDATE(md, ANDROID_CONTROL_AF_STATE, &afState, 1);
2726
2727 // Set AWB state to converged to indicate the frame should be good to use.
2728 const uint8_t awbState = ANDROID_CONTROL_AWB_STATE_CONVERGED;
2729 UPDATE(md, ANDROID_CONTROL_AWB_STATE, &awbState, 1);
2730
2731 const uint8_t awbLock = ANDROID_CONTROL_AWB_LOCK_OFF;
2732 UPDATE(md, ANDROID_CONTROL_AWB_LOCK, &awbLock, 1);
2733
2734 camera_metadata_ro_entry active_array_size =
2735 mCameraCharacteristics.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
2736
2737 if (active_array_size.count == 0) {
2738 ALOGE("%s: cannot find active array size!", __FUNCTION__);
2739 return -EINVAL;
2740 }
2741
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002742 const uint8_t flashState = ANDROID_FLASH_STATE_UNAVAILABLE;
2743 UPDATE(md, ANDROID_FLASH_STATE, &flashState, 1);
2744
Yin-Chia Yehc15a1ca2018-03-02 14:16:52 -08002745 // This means pipeline latency of X frame intervals. The maximum number is 4.
2746 const uint8_t requestPipelineMaxDepth = 4;
2747 UPDATE(md, ANDROID_REQUEST_PIPELINE_DEPTH, &requestPipelineMaxDepth, 1);
2748
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002749 // android.scaler
2750 const int32_t crop_region[] = {
2751 active_array_size.data.i32[0], active_array_size.data.i32[1],
2752 active_array_size.data.i32[2], active_array_size.data.i32[3],
2753 };
2754 UPDATE(md, ANDROID_SCALER_CROP_REGION, crop_region, ARRAY_SIZE(crop_region));
2755
2756 // android.sensor
2757 UPDATE(md, ANDROID_SENSOR_TIMESTAMP, &timestamp, 1);
2758
2759 // android.statistics
2760 const uint8_t lensShadingMapMode = ANDROID_STATISTICS_LENS_SHADING_MAP_MODE_OFF;
2761 UPDATE(md, ANDROID_STATISTICS_LENS_SHADING_MAP_MODE, &lensShadingMapMode, 1);
2762
2763 const uint8_t sceneFlicker = ANDROID_STATISTICS_SCENE_FLICKER_NONE;
2764 UPDATE(md, ANDROID_STATISTICS_SCENE_FLICKER, &sceneFlicker, 1);
2765
2766 return OK;
2767}
2768
2769#undef ARRAY_SIZE
2770#undef UPDATE
2771
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002772} // namespace implementation
2773} // namespace V3_4
2774} // namespace device
2775} // namespace camera
2776} // namespace hardware
2777} // namespace android