blob: cffc40e20eb4045cd5d3aa62b162b90255028650 [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
18#include <log/log.h>
19
20#include <inttypes.h>
21#include "ExternalCameraDeviceSession.h"
22
23#include "android-base/macros.h"
Yin-Chia Yeh19030592017-10-19 17:30:11 -070024#include <utils/Timers.h>
Yin-Chia Yeh19030592017-10-19 17:30:11 -070025#include <linux/videodev2.h>
26#include <sync/sync.h>
27
28#define HAVE_JPEG // required for libyuv.h to export MJPEG decode APIs
29#include <libyuv.h>
30
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -080031#include <jpeglib.h>
32
33
Yin-Chia Yeh19030592017-10-19 17:30:11 -070034namespace android {
35namespace hardware {
36namespace camera {
37namespace device {
38namespace V3_4 {
39namespace implementation {
40
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080041namespace {
Yin-Chia Yeh19030592017-10-19 17:30:11 -070042// Size of request/result metadata fast message queue. Change to 0 to always use hwbinder buffer.
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080043static constexpr size_t kMetadataMsgQueueSize = 1 << 18 /* 256kB */;
44
Yin-Chia Yeh19030592017-10-19 17:30:11 -070045const int kBadFramesAfterStreamOn = 1; // drop x frames after streamOn to get rid of some initial
46 // bad frames. TODO: develop a better bad frame detection
47 // method
48
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -080049bool tryLock(Mutex& mutex)
50{
51 static const int kDumpLockRetries = 50;
52 static const int kDumpLockSleep = 60000;
53 bool locked = false;
54 for (int i = 0; i < kDumpLockRetries; ++i) {
55 if (mutex.tryLock() == NO_ERROR) {
56 locked = true;
57 break;
58 }
59 usleep(kDumpLockSleep);
60 }
61 return locked;
62}
63
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080064} // Anonymous namespace
Yin-Chia Yeh19030592017-10-19 17:30:11 -070065
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080066// Static instances
67const int ExternalCameraDeviceSession::kMaxProcessedStream;
68const int ExternalCameraDeviceSession::kMaxStallStream;
Yin-Chia Yeh19030592017-10-19 17:30:11 -070069HandleImporter ExternalCameraDeviceSession::sHandleImporter;
70
Yin-Chia Yeh19030592017-10-19 17:30:11 -070071ExternalCameraDeviceSession::ExternalCameraDeviceSession(
72 const sp<ICameraDeviceCallback>& callback,
Yin-Chia Yeh17982492018-02-05 17:41:01 -080073 const ExternalCameraConfig& cfg,
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080074 const std::vector<SupportedV4L2Format>& sortedFormats,
75 const CroppingType& croppingType,
Yin-Chia Yeh19030592017-10-19 17:30:11 -070076 const common::V1_0::helper::CameraMetadata& chars,
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -080077 const std::string& cameraId,
Yin-Chia Yeh19030592017-10-19 17:30:11 -070078 unique_fd v4l2Fd) :
79 mCallback(callback),
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080080 mCfg(cfg),
Yin-Chia Yeh19030592017-10-19 17:30:11 -070081 mCameraCharacteristics(chars),
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080082 mSupportedFormats(sortedFormats),
83 mCroppingType(croppingType),
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -080084 mCameraId(cameraId),
Yin-Chia Yeh19030592017-10-19 17:30:11 -070085 mV4l2Fd(std::move(v4l2Fd)),
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -080086 mOutputThread(new OutputThread(this, mCroppingType)),
87 mMaxThumbResolution(getMaxThumbResolution()),
88 mMaxJpegResolution(getMaxJpegResolution()) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -070089 mInitFail = initialize();
90}
91
Yin-Chia Yeh19030592017-10-19 17:30:11 -070092bool ExternalCameraDeviceSession::initialize() {
93 if (mV4l2Fd.get() < 0) {
94 ALOGE("%s: invalid v4l2 device fd %d!", __FUNCTION__, mV4l2Fd.get());
95 return true;
96 }
97
98 status_t status = initDefaultRequests();
99 if (status != OK) {
100 ALOGE("%s: init default requests failed!", __FUNCTION__);
101 return true;
102 }
103
104 mRequestMetadataQueue = std::make_unique<RequestMetadataQueue>(
105 kMetadataMsgQueueSize, false /* non blocking */);
106 if (!mRequestMetadataQueue->isValid()) {
107 ALOGE("%s: invalid request fmq", __FUNCTION__);
108 return true;
109 }
110 mResultMetadataQueue = std::make_shared<RequestMetadataQueue>(
111 kMetadataMsgQueueSize, false /* non blocking */);
112 if (!mResultMetadataQueue->isValid()) {
113 ALOGE("%s: invalid result fmq", __FUNCTION__);
114 return true;
115 }
116
117 // TODO: check is PRIORITY_DISPLAY enough?
118 mOutputThread->run("ExtCamOut", PRIORITY_DISPLAY);
119 return false;
120}
121
122Status ExternalCameraDeviceSession::initStatus() const {
123 Mutex::Autolock _l(mLock);
124 Status status = Status::OK;
125 if (mInitFail || mClosed) {
126 ALOGI("%s: sesssion initFailed %d closed %d", __FUNCTION__, mInitFail, mClosed);
127 status = Status::INTERNAL_ERROR;
128 }
129 return status;
130}
131
132ExternalCameraDeviceSession::~ExternalCameraDeviceSession() {
133 if (!isClosed()) {
134 ALOGE("ExternalCameraDeviceSession deleted before close!");
135 close();
136 }
137}
138
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800139
140void ExternalCameraDeviceSession::dumpState(const native_handle_t* handle) {
141 if (handle->numFds != 1 || handle->numInts != 0) {
142 ALOGE("%s: handle must contain 1 FD and 0 integers! Got %d FDs and %d ints",
143 __FUNCTION__, handle->numFds, handle->numInts);
144 return;
145 }
146 int fd = handle->data[0];
147
148 bool intfLocked = tryLock(mInterfaceLock);
149 if (!intfLocked) {
150 dprintf(fd, "!! ExternalCameraDeviceSession interface may be deadlocked !!\n");
151 }
152
153 if (isClosed()) {
154 dprintf(fd, "External camera %s is closed\n", mCameraId.c_str());
155 return;
156 }
157
158 bool streaming = false;
159 size_t v4L2BufferCount = 0;
160 SupportedV4L2Format streamingFmt;
161 std::unordered_set<uint32_t> inflightFrames;
162 {
163 Mutex::Autolock _l(mLock);
164 bool sessionLocked = tryLock(mLock);
165 if (!sessionLocked) {
166 dprintf(fd, "!! ExternalCameraDeviceSession mLock may be deadlocked !!\n");
167 }
168 streaming = mV4l2Streaming;
169 streamingFmt = mV4l2StreamingFmt;
170 v4L2BufferCount = mV4L2BufferCount;
171 inflightFrames = mInflightFrames;
172 if (sessionLocked) {
173 mLock.unlock();
174 }
175 }
176
177 dprintf(fd, "External camera %s V4L2 FD %d, cropping type %s, %s\n",
178 mCameraId.c_str(), mV4l2Fd.get(),
179 (mCroppingType == VERTICAL) ? "vertical" : "horizontal",
180 streaming ? "streaming" : "not streaming");
181 if (streaming) {
182 // TODO: dump fps later
183 dprintf(fd, "Current V4L2 format %c%c%c%c %dx%d\n",
184 streamingFmt.fourcc & 0xFF,
185 (streamingFmt.fourcc >> 8) & 0xFF,
186 (streamingFmt.fourcc >> 16) & 0xFF,
187 (streamingFmt.fourcc >> 24) & 0xFF,
188 streamingFmt.width, streamingFmt.height);
189
190 size_t numDequeuedV4l2Buffers = 0;
191 {
192 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
193 numDequeuedV4l2Buffers = mNumDequeuedV4l2Buffers;
194 }
195 dprintf(fd, "V4L2 buffer queue size %zu, dequeued %zu\n",
196 v4L2BufferCount, numDequeuedV4l2Buffers);
197 }
198
199 dprintf(fd, "In-flight frames (not sorted):");
200 for (const auto& frameNumber : inflightFrames) {
201 dprintf(fd, "%d, ", frameNumber);
202 }
203 dprintf(fd, "\n");
204 mOutputThread->dump(fd);
205 dprintf(fd, "\n");
206
207 if (intfLocked) {
208 mInterfaceLock.unlock();
209 }
210
211 return;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700212}
213
214Return<void> ExternalCameraDeviceSession::constructDefaultRequestSettings(
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800215 V3_2::RequestTemplate type,
216 V3_2::ICameraDeviceSession::constructDefaultRequestSettings_cb _hidl_cb) {
217 V3_2::CameraMetadata outMetadata;
218 Status status = constructDefaultRequestSettingsRaw(
219 static_cast<RequestTemplate>(type), &outMetadata);
220 _hidl_cb(status, outMetadata);
221 return Void();
222}
223
224Return<void> ExternalCameraDeviceSession::constructDefaultRequestSettings_3_4(
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700225 RequestTemplate type,
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800226 ICameraDeviceSession::constructDefaultRequestSettings_cb _hidl_cb) {
227 V3_2::CameraMetadata outMetadata;
228 Status status = constructDefaultRequestSettingsRaw(type, &outMetadata);
229 _hidl_cb(status, outMetadata);
230 return Void();
231}
232
233Status ExternalCameraDeviceSession::constructDefaultRequestSettingsRaw(RequestTemplate type,
234 V3_2::CameraMetadata *outMetadata) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700235 CameraMetadata emptyMd;
236 Status status = initStatus();
237 if (status != Status::OK) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800238 return status;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700239 }
240
241 switch (type) {
242 case RequestTemplate::PREVIEW:
243 case RequestTemplate::STILL_CAPTURE:
244 case RequestTemplate::VIDEO_RECORD:
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800245 case RequestTemplate::VIDEO_SNAPSHOT: {
246 *outMetadata = mDefaultRequests[type];
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700247 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800248 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700249 case RequestTemplate::MANUAL:
250 case RequestTemplate::ZERO_SHUTTER_LAG:
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800251 case RequestTemplate::MOTION_TRACKING_PREVIEW:
252 case RequestTemplate::MOTION_TRACKING_BEST:
253 // Don't support MANUAL, ZSL, MOTION_TRACKING_* templates
254 status = Status::ILLEGAL_ARGUMENT;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700255 break;
256 default:
257 ALOGE("%s: unknown request template type %d", __FUNCTION__, static_cast<int>(type));
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800258 status = Status::ILLEGAL_ARGUMENT;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700259 break;
260 }
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800261 return status;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700262}
263
264Return<void> ExternalCameraDeviceSession::configureStreams(
265 const V3_2::StreamConfiguration& streams,
266 ICameraDeviceSession::configureStreams_cb _hidl_cb) {
267 V3_2::HalStreamConfiguration outStreams;
268 V3_3::HalStreamConfiguration outStreams_v33;
269 Mutex::Autolock _il(mInterfaceLock);
270
271 Status status = configureStreams(streams, &outStreams_v33);
272 size_t size = outStreams_v33.streams.size();
273 outStreams.streams.resize(size);
274 for (size_t i = 0; i < size; i++) {
275 outStreams.streams[i] = outStreams_v33.streams[i].v3_2;
276 }
277 _hidl_cb(status, outStreams);
278 return Void();
279}
280
281Return<void> ExternalCameraDeviceSession::configureStreams_3_3(
282 const V3_2::StreamConfiguration& streams,
283 ICameraDeviceSession::configureStreams_3_3_cb _hidl_cb) {
284 V3_3::HalStreamConfiguration outStreams;
285 Mutex::Autolock _il(mInterfaceLock);
286
287 Status status = configureStreams(streams, &outStreams);
288 _hidl_cb(status, outStreams);
289 return Void();
290}
291
292Return<void> ExternalCameraDeviceSession::configureStreams_3_4(
293 const V3_4::StreamConfiguration& requestedConfiguration,
294 ICameraDeviceSession::configureStreams_3_4_cb _hidl_cb) {
295 V3_2::StreamConfiguration config_v32;
296 V3_3::HalStreamConfiguration outStreams_v33;
297 Mutex::Autolock _il(mInterfaceLock);
298
299 config_v32.operationMode = requestedConfiguration.operationMode;
300 config_v32.streams.resize(requestedConfiguration.streams.size());
301 for (size_t i = 0; i < config_v32.streams.size(); i++) {
302 config_v32.streams[i] = requestedConfiguration.streams[i].v3_2;
303 }
304
305 // Ignore requestedConfiguration.sessionParams. External camera does not support it
306 Status status = configureStreams(config_v32, &outStreams_v33);
307
308 V3_4::HalStreamConfiguration outStreams;
309 outStreams.streams.resize(outStreams_v33.streams.size());
310 for (size_t i = 0; i < outStreams.streams.size(); i++) {
311 outStreams.streams[i].v3_3 = outStreams_v33.streams[i];
312 }
313 _hidl_cb(status, outStreams);
314 return Void();
315}
316
317Return<void> ExternalCameraDeviceSession::getCaptureRequestMetadataQueue(
318 ICameraDeviceSession::getCaptureRequestMetadataQueue_cb _hidl_cb) {
319 Mutex::Autolock _il(mInterfaceLock);
320 _hidl_cb(*mRequestMetadataQueue->getDesc());
321 return Void();
322}
323
324Return<void> ExternalCameraDeviceSession::getCaptureResultMetadataQueue(
325 ICameraDeviceSession::getCaptureResultMetadataQueue_cb _hidl_cb) {
326 Mutex::Autolock _il(mInterfaceLock);
327 _hidl_cb(*mResultMetadataQueue->getDesc());
328 return Void();
329}
330
331Return<void> ExternalCameraDeviceSession::processCaptureRequest(
332 const hidl_vec<CaptureRequest>& requests,
333 const hidl_vec<BufferCache>& cachesToRemove,
334 ICameraDeviceSession::processCaptureRequest_cb _hidl_cb) {
335 Mutex::Autolock _il(mInterfaceLock);
336 updateBufferCaches(cachesToRemove);
337
338 uint32_t numRequestProcessed = 0;
339 Status s = Status::OK;
340 for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
341 s = processOneCaptureRequest(requests[i]);
342 if (s != Status::OK) {
343 break;
344 }
345 }
346
347 _hidl_cb(s, numRequestProcessed);
348 return Void();
349}
350
351Return<void> ExternalCameraDeviceSession::processCaptureRequest_3_4(
352 const hidl_vec<V3_4::CaptureRequest>& requests,
353 const hidl_vec<V3_2::BufferCache>& cachesToRemove,
354 ICameraDeviceSession::processCaptureRequest_3_4_cb _hidl_cb) {
355 Mutex::Autolock _il(mInterfaceLock);
356 updateBufferCaches(cachesToRemove);
357
358 uint32_t numRequestProcessed = 0;
359 Status s = Status::OK;
360 for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
361 s = processOneCaptureRequest(requests[i].v3_2);
362 if (s != Status::OK) {
363 break;
364 }
365 }
366
367 _hidl_cb(s, numRequestProcessed);
368 return Void();
369}
370
371Return<Status> ExternalCameraDeviceSession::flush() {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -0800372 Mutex::Autolock _il(mInterfaceLock);
373 Status status = initStatus();
374 if (status != Status::OK) {
375 return status;
376 }
377 mOutputThread->flush();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700378 return Status::OK;
379}
380
381Return<void> ExternalCameraDeviceSession::close() {
382 Mutex::Autolock _il(mInterfaceLock);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800383 bool closed = isClosed();
384 if (!closed) {
385 mOutputThread->flush();
386 mOutputThread->requestExit();
387 mOutputThread->join();
388
389 Mutex::Autolock _l(mLock);
390 // free all buffers
391 for(auto pair : mStreamMap) {
392 cleanupBuffersLocked(/*Stream ID*/pair.first);
393 }
394 v4l2StreamOffLocked();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700395 ALOGV("%s: closing V4L2 camera FD %d", __FUNCTION__, mV4l2Fd.get());
396 mV4l2Fd.reset();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700397 mClosed = true;
398 }
399 return Void();
400}
401
402Status ExternalCameraDeviceSession::importRequest(
403 const CaptureRequest& request,
404 hidl_vec<buffer_handle_t*>& allBufPtrs,
405 hidl_vec<int>& allFences) {
406 size_t numOutputBufs = request.outputBuffers.size();
407 size_t numBufs = numOutputBufs;
408 // Validate all I/O buffers
409 hidl_vec<buffer_handle_t> allBufs;
410 hidl_vec<uint64_t> allBufIds;
411 allBufs.resize(numBufs);
412 allBufIds.resize(numBufs);
413 allBufPtrs.resize(numBufs);
414 allFences.resize(numBufs);
415 std::vector<int32_t> streamIds(numBufs);
416
417 for (size_t i = 0; i < numOutputBufs; i++) {
418 allBufs[i] = request.outputBuffers[i].buffer.getNativeHandle();
419 allBufIds[i] = request.outputBuffers[i].bufferId;
420 allBufPtrs[i] = &allBufs[i];
421 streamIds[i] = request.outputBuffers[i].streamId;
422 }
423
424 for (size_t i = 0; i < numBufs; i++) {
425 buffer_handle_t buf = allBufs[i];
426 uint64_t bufId = allBufIds[i];
427 CirculatingBuffers& cbs = mCirculatingBuffers[streamIds[i]];
428 if (cbs.count(bufId) == 0) {
429 if (buf == nullptr) {
430 ALOGE("%s: bufferId %" PRIu64 " has null buffer handle!", __FUNCTION__, bufId);
431 return Status::ILLEGAL_ARGUMENT;
432 }
433 // Register a newly seen buffer
434 buffer_handle_t importedBuf = buf;
435 sHandleImporter.importBuffer(importedBuf);
436 if (importedBuf == nullptr) {
437 ALOGE("%s: output buffer %zu is invalid!", __FUNCTION__, i);
438 return Status::INTERNAL_ERROR;
439 } else {
440 cbs[bufId] = importedBuf;
441 }
442 }
443 allBufPtrs[i] = &cbs[bufId];
444 }
445
446 // All buffers are imported. Now validate output buffer acquire fences
447 for (size_t i = 0; i < numOutputBufs; i++) {
448 if (!sHandleImporter.importFence(
449 request.outputBuffers[i].acquireFence, allFences[i])) {
450 ALOGE("%s: output buffer %zu acquire fence is invalid", __FUNCTION__, i);
451 cleanupInflightFences(allFences, i);
452 return Status::INTERNAL_ERROR;
453 }
454 }
455 return Status::OK;
456}
457
458void ExternalCameraDeviceSession::cleanupInflightFences(
459 hidl_vec<int>& allFences, size_t numFences) {
460 for (size_t j = 0; j < numFences; j++) {
461 sHandleImporter.closeFence(allFences[j]);
462 }
463}
464
465Status ExternalCameraDeviceSession::processOneCaptureRequest(const CaptureRequest& request) {
466 Status status = initStatus();
467 if (status != Status::OK) {
468 return status;
469 }
470
471 if (request.inputBuffer.streamId != -1) {
472 ALOGE("%s: external camera does not support reprocessing!", __FUNCTION__);
473 return Status::ILLEGAL_ARGUMENT;
474 }
475
476 Mutex::Autolock _l(mLock);
477 if (!mV4l2Streaming) {
478 ALOGE("%s: cannot process request in streamOff state!", __FUNCTION__);
479 return Status::INTERNAL_ERROR;
480 }
481
482 const camera_metadata_t *rawSettings = nullptr;
483 bool converted = true;
484 CameraMetadata settingsFmq; // settings from FMQ
485 if (request.fmqSettingsSize > 0) {
486 // non-blocking read; client must write metadata before calling
487 // processOneCaptureRequest
488 settingsFmq.resize(request.fmqSettingsSize);
489 bool read = mRequestMetadataQueue->read(settingsFmq.data(), request.fmqSettingsSize);
490 if (read) {
491 converted = V3_2::implementation::convertFromHidl(settingsFmq, &rawSettings);
492 } else {
493 ALOGE("%s: capture request settings metadata couldn't be read from fmq!", __FUNCTION__);
494 converted = false;
495 }
496 } else {
497 converted = V3_2::implementation::convertFromHidl(request.settings, &rawSettings);
498 }
499
500 if (converted && rawSettings != nullptr) {
501 mLatestReqSetting = rawSettings;
502 }
503
504 if (!converted) {
505 ALOGE("%s: capture request settings metadata is corrupt!", __FUNCTION__);
506 return Status::ILLEGAL_ARGUMENT;
507 }
508
509 if (mFirstRequest && rawSettings == nullptr) {
510 ALOGE("%s: capture request settings must not be null for first request!",
511 __FUNCTION__);
512 return Status::ILLEGAL_ARGUMENT;
513 }
514
515 hidl_vec<buffer_handle_t*> allBufPtrs;
516 hidl_vec<int> allFences;
517 size_t numOutputBufs = request.outputBuffers.size();
518
519 if (numOutputBufs == 0) {
520 ALOGE("%s: capture request must have at least one output buffer!", __FUNCTION__);
521 return Status::ILLEGAL_ARGUMENT;
522 }
523
524 status = importRequest(request, allBufPtrs, allFences);
525 if (status != Status::OK) {
526 return status;
527 }
528
529 // TODO: program fps range per capture request here
530 // or limit the set of availableFpsRange
531
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800532
533 nsecs_t shutterTs = 0;
534 sp<V4L2Frame> frameIn = dequeueV4l2FrameLocked(&shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700535 if ( frameIn == nullptr) {
536 ALOGE("%s: V4L2 deque frame failed!", __FUNCTION__);
537 return Status::INTERNAL_ERROR;
538 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700539
540 // TODO: reduce object copy in this path
541 HalRequest halReq = {
542 .frameNumber = request.frameNumber,
543 .setting = mLatestReqSetting,
544 .frameIn = frameIn,
545 .shutterTs = shutterTs};
546 halReq.buffers.resize(numOutputBufs);
547 for (size_t i = 0; i < numOutputBufs; i++) {
548 HalStreamBuffer& halBuf = halReq.buffers[i];
549 int streamId = halBuf.streamId = request.outputBuffers[i].streamId;
550 halBuf.bufferId = request.outputBuffers[i].bufferId;
551 const Stream& stream = mStreamMap[streamId];
552 halBuf.width = stream.width;
553 halBuf.height = stream.height;
554 halBuf.format = stream.format;
555 halBuf.usage = stream.usage;
556 halBuf.bufPtr = allBufPtrs[i];
557 halBuf.acquireFence = allFences[i];
558 halBuf.fenceTimeout = false;
559 }
560 mInflightFrames.insert(halReq.frameNumber);
561 // Send request to OutputThread for the rest of processing
562 mOutputThread->submitRequest(halReq);
563 mFirstRequest = false;
564 return Status::OK;
565}
566
567void ExternalCameraDeviceSession::notifyShutter(uint32_t frameNumber, nsecs_t shutterTs) {
568 NotifyMsg msg;
569 msg.type = MsgType::SHUTTER;
570 msg.msg.shutter.frameNumber = frameNumber;
571 msg.msg.shutter.timestamp = shutterTs;
572 mCallback->notify({msg});
573}
574
575void ExternalCameraDeviceSession::notifyError(
576 uint32_t frameNumber, int32_t streamId, ErrorCode ec) {
577 NotifyMsg msg;
578 msg.type = MsgType::ERROR;
579 msg.msg.error.frameNumber = frameNumber;
580 msg.msg.error.errorStreamId = streamId;
581 msg.msg.error.errorCode = ec;
582 mCallback->notify({msg});
583}
584
585//TODO: refactor with processCaptureResult
Yin-Chia Yeh190e5602018-02-13 17:43:13 -0800586Status ExternalCameraDeviceSession::processCaptureRequestError(const HalRequest& req) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700587 // Return V4L2 buffer to V4L2 buffer queue
588 enqueueV4l2Frame(req.frameIn);
589
590 // NotifyShutter
591 notifyShutter(req.frameNumber, req.shutterTs);
592
593 notifyError(/*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_REQUEST);
594
595 // Fill output buffers
596 hidl_vec<CaptureResult> results;
597 results.resize(1);
598 CaptureResult& result = results[0];
599 result.frameNumber = req.frameNumber;
600 result.partialResult = 1;
601 result.inputBuffer.streamId = -1;
602 result.outputBuffers.resize(req.buffers.size());
603 for (size_t i = 0; i < req.buffers.size(); i++) {
604 result.outputBuffers[i].streamId = req.buffers[i].streamId;
605 result.outputBuffers[i].bufferId = req.buffers[i].bufferId;
606 result.outputBuffers[i].status = BufferStatus::ERROR;
607 if (req.buffers[i].acquireFence >= 0) {
608 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
609 handle->data[0] = req.buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800610 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700611 }
612 }
613
614 // update inflight records
615 {
616 Mutex::Autolock _l(mLock);
617 mInflightFrames.erase(req.frameNumber);
618 }
619
620 // Callback into framework
621 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
622 freeReleaseFences(results);
623 return Status::OK;
624}
625
626Status ExternalCameraDeviceSession::processCaptureResult(HalRequest& req) {
627 // Return V4L2 buffer to V4L2 buffer queue
628 enqueueV4l2Frame(req.frameIn);
629
630 // NotifyShutter
631 notifyShutter(req.frameNumber, req.shutterTs);
632
633 // Fill output buffers
634 hidl_vec<CaptureResult> results;
635 results.resize(1);
636 CaptureResult& result = results[0];
637 result.frameNumber = req.frameNumber;
638 result.partialResult = 1;
639 result.inputBuffer.streamId = -1;
640 result.outputBuffers.resize(req.buffers.size());
641 for (size_t i = 0; i < req.buffers.size(); i++) {
642 result.outputBuffers[i].streamId = req.buffers[i].streamId;
643 result.outputBuffers[i].bufferId = req.buffers[i].bufferId;
644 if (req.buffers[i].fenceTimeout) {
645 result.outputBuffers[i].status = BufferStatus::ERROR;
646 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
647 handle->data[0] = req.buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800648 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700649 notifyError(req.frameNumber, req.buffers[i].streamId, ErrorCode::ERROR_BUFFER);
650 } else {
651 result.outputBuffers[i].status = BufferStatus::OK;
652 // TODO: refactor
653 if (req.buffers[i].acquireFence > 0) {
654 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
655 handle->data[0] = req.buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800656 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700657 }
658 }
659 }
660
661 // Fill capture result metadata
662 fillCaptureResult(req.setting, req.shutterTs);
663 const camera_metadata_t *rawResult = req.setting.getAndLock();
664 V3_2::implementation::convertToHidl(rawResult, &result.result);
665 req.setting.unlock(rawResult);
666
667 // update inflight records
668 {
669 Mutex::Autolock _l(mLock);
670 mInflightFrames.erase(req.frameNumber);
671 }
672
673 // Callback into framework
674 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
675 freeReleaseFences(results);
676 return Status::OK;
677}
678
679void ExternalCameraDeviceSession::invokeProcessCaptureResultCallback(
680 hidl_vec<CaptureResult> &results, bool tryWriteFmq) {
681 if (mProcessCaptureResultLock.tryLock() != OK) {
682 const nsecs_t NS_TO_SECOND = 1000000000;
683 ALOGV("%s: previous call is not finished! waiting 1s...", __FUNCTION__);
684 if (mProcessCaptureResultLock.timedLock(/* 1s */NS_TO_SECOND) != OK) {
685 ALOGE("%s: cannot acquire lock in 1s, cannot proceed",
686 __FUNCTION__);
687 return;
688 }
689 }
690 if (tryWriteFmq && mResultMetadataQueue->availableToWrite() > 0) {
691 for (CaptureResult &result : results) {
692 if (result.result.size() > 0) {
693 if (mResultMetadataQueue->write(result.result.data(), result.result.size())) {
694 result.fmqResultSize = result.result.size();
695 result.result.resize(0);
696 } else {
697 ALOGW("%s: couldn't utilize fmq, fall back to hwbinder", __FUNCTION__);
698 result.fmqResultSize = 0;
699 }
700 } else {
701 result.fmqResultSize = 0;
702 }
703 }
704 }
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -0800705 auto status = mCallback->processCaptureResult(results);
706 if (!status.isOk()) {
707 ALOGE("%s: processCaptureResult ERROR : %s", __FUNCTION__,
708 status.description().c_str());
709 }
710
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700711 mProcessCaptureResultLock.unlock();
712}
713
714void ExternalCameraDeviceSession::freeReleaseFences(hidl_vec<CaptureResult>& results) {
715 for (auto& result : results) {
716 if (result.inputBuffer.releaseFence.getNativeHandle() != nullptr) {
717 native_handle_t* handle = const_cast<native_handle_t*>(
718 result.inputBuffer.releaseFence.getNativeHandle());
719 native_handle_close(handle);
720 native_handle_delete(handle);
721 }
722 for (auto& buf : result.outputBuffers) {
723 if (buf.releaseFence.getNativeHandle() != nullptr) {
724 native_handle_t* handle = const_cast<native_handle_t*>(
725 buf.releaseFence.getNativeHandle());
726 native_handle_close(handle);
727 native_handle_delete(handle);
728 }
729 }
730 }
731 return;
732}
733
734ExternalCameraDeviceSession::OutputThread::OutputThread(
735 wp<ExternalCameraDeviceSession> parent,
736 CroppingType ct) : mParent(parent), mCroppingType(ct) {}
737
738ExternalCameraDeviceSession::OutputThread::~OutputThread() {}
739
740uint32_t ExternalCameraDeviceSession::OutputThread::getFourCcFromLayout(
741 const YCbCrLayout& layout) {
742 intptr_t cb = reinterpret_cast<intptr_t>(layout.cb);
743 intptr_t cr = reinterpret_cast<intptr_t>(layout.cr);
744 if (std::abs(cb - cr) == 1 && layout.chromaStep == 2) {
745 // Interleaved format
746 if (layout.cb > layout.cr) {
747 return V4L2_PIX_FMT_NV21;
748 } else {
749 return V4L2_PIX_FMT_NV12;
750 }
751 } else if (layout.chromaStep == 1) {
752 // Planar format
753 if (layout.cb > layout.cr) {
754 return V4L2_PIX_FMT_YVU420; // YV12
755 } else {
756 return V4L2_PIX_FMT_YUV420; // YU12
757 }
758 } else {
759 return FLEX_YUV_GENERIC;
760 }
761}
762
763int ExternalCameraDeviceSession::OutputThread::getCropRect(
764 CroppingType ct, const Size& inSize, const Size& outSize, IMapper::Rect* out) {
765 if (out == nullptr) {
766 ALOGE("%s: out is null", __FUNCTION__);
767 return -1;
768 }
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800769
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700770 uint32_t inW = inSize.width;
771 uint32_t inH = inSize.height;
772 uint32_t outW = outSize.width;
773 uint32_t outH = outSize.height;
774
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800775 // Handle special case where aspect ratio is close to input but scaled
776 // dimension is slightly larger than input
777 float arIn = ASPECT_RATIO(inSize);
778 float arOut = ASPECT_RATIO(outSize);
779 if (isAspectRatioClose(arIn, arOut)) {
780 out->left = 0;
781 out->top = 0;
782 out->width = inW;
783 out->height = inH;
784 return 0;
785 }
786
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700787 if (ct == VERTICAL) {
788 uint64_t scaledOutH = static_cast<uint64_t>(outH) * inW / outW;
789 if (scaledOutH > inH) {
790 ALOGE("%s: Output size %dx%d cannot be vertically cropped from input size %dx%d",
791 __FUNCTION__, outW, outH, inW, inH);
792 return -1;
793 }
794 scaledOutH = scaledOutH & ~0x1; // make it multiple of 2
795
796 out->left = 0;
797 out->top = ((inH - scaledOutH) / 2) & ~0x1;
798 out->width = inW;
799 out->height = static_cast<int32_t>(scaledOutH);
800 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledH %d",
801 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutH));
802 } else {
803 uint64_t scaledOutW = static_cast<uint64_t>(outW) * inH / outH;
804 if (scaledOutW > inW) {
805 ALOGE("%s: Output size %dx%d cannot be horizontally cropped from input size %dx%d",
806 __FUNCTION__, outW, outH, inW, inH);
807 return -1;
808 }
809 scaledOutW = scaledOutW & ~0x1; // make it multiple of 2
810
811 out->left = ((inW - scaledOutW) / 2) & ~0x1;
812 out->top = 0;
813 out->width = static_cast<int32_t>(scaledOutW);
814 out->height = inH;
815 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledW %d",
816 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutW));
817 }
818
819 return 0;
820}
821
822int ExternalCameraDeviceSession::OutputThread::cropAndScaleLocked(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800823 sp<AllocatedFrame>& in, const Size& outSz, YCbCrLayout* out) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700824 Size inSz = {in->mWidth, in->mHeight};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800825
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700826 int ret;
827 if (inSz == outSz) {
828 ret = in->getLayout(out);
829 if (ret != 0) {
830 ALOGE("%s: failed to get input image layout", __FUNCTION__);
831 return ret;
832 }
833 return ret;
834 }
835
836 // Cropping to output aspect ratio
837 IMapper::Rect inputCrop;
838 ret = getCropRect(mCroppingType, inSz, outSz, &inputCrop);
839 if (ret != 0) {
840 ALOGE("%s: failed to compute crop rect for output size %dx%d",
841 __FUNCTION__, outSz.width, outSz.height);
842 return ret;
843 }
844
845 YCbCrLayout croppedLayout;
846 ret = in->getCroppedLayout(inputCrop, &croppedLayout);
847 if (ret != 0) {
848 ALOGE("%s: failed to crop input image %dx%d to output size %dx%d",
849 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
850 return ret;
851 }
852
853 if ((mCroppingType == VERTICAL && inSz.width == outSz.width) ||
854 (mCroppingType == HORIZONTAL && inSz.height == outSz.height)) {
855 // No scale is needed
856 *out = croppedLayout;
857 return 0;
858 }
859
860 auto it = mScaledYu12Frames.find(outSz);
861 sp<AllocatedFrame> scaledYu12Buf;
862 if (it != mScaledYu12Frames.end()) {
863 scaledYu12Buf = it->second;
864 } else {
865 it = mIntermediateBuffers.find(outSz);
866 if (it == mIntermediateBuffers.end()) {
867 ALOGE("%s: failed to find intermediate buffer size %dx%d",
868 __FUNCTION__, outSz.width, outSz.height);
869 return -1;
870 }
871 scaledYu12Buf = it->second;
872 }
873 // Scale
874 YCbCrLayout outLayout;
875 ret = scaledYu12Buf->getLayout(&outLayout);
876 if (ret != 0) {
877 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
878 return ret;
879 }
880
881 ret = libyuv::I420Scale(
882 static_cast<uint8_t*>(croppedLayout.y),
883 croppedLayout.yStride,
884 static_cast<uint8_t*>(croppedLayout.cb),
885 croppedLayout.cStride,
886 static_cast<uint8_t*>(croppedLayout.cr),
887 croppedLayout.cStride,
888 inputCrop.width,
889 inputCrop.height,
890 static_cast<uint8_t*>(outLayout.y),
891 outLayout.yStride,
892 static_cast<uint8_t*>(outLayout.cb),
893 outLayout.cStride,
894 static_cast<uint8_t*>(outLayout.cr),
895 outLayout.cStride,
896 outSz.width,
897 outSz.height,
898 // TODO: b/72261744 see if we can use better filter without losing too much perf
899 libyuv::FilterMode::kFilterNone);
900
901 if (ret != 0) {
902 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
903 __FUNCTION__, inputCrop.width, inputCrop.height,
904 outSz.width, outSz.height, ret);
905 return ret;
906 }
907
908 *out = outLayout;
909 mScaledYu12Frames.insert({outSz, scaledYu12Buf});
910 return 0;
911}
912
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800913
914int ExternalCameraDeviceSession::OutputThread::cropAndScaleThumbLocked(
915 sp<AllocatedFrame>& in, const Size &outSz, YCbCrLayout* out) {
916 Size inSz {in->mWidth, in->mHeight};
917
918 if ((outSz.width * outSz.height) >
919 (mYu12ThumbFrame->mWidth * mYu12ThumbFrame->mHeight)) {
920 ALOGE("%s: Requested thumbnail size too big (%d,%d) > (%d,%d)",
921 __FUNCTION__, outSz.width, outSz.height,
922 mYu12ThumbFrame->mWidth, mYu12ThumbFrame->mHeight);
923 return -1;
924 }
925
926 int ret;
927
928 /* This will crop-and-zoom the input YUV frame to the thumbnail size
929 * Based on the following logic:
930 * 1) Square pixels come in, square pixels come out, therefore single
931 * scale factor is computed to either make input bigger or smaller
932 * depending on if we are upscaling or downscaling
933 * 2) That single scale factor would either make height too tall or width
934 * too wide so we need to crop the input either horizontally or vertically
935 * but not both
936 */
937
938 /* Convert the input and output dimensions into floats for ease of math */
939 float fWin = static_cast<float>(inSz.width);
940 float fHin = static_cast<float>(inSz.height);
941 float fWout = static_cast<float>(outSz.width);
942 float fHout = static_cast<float>(outSz.height);
943
944 /* Compute the one scale factor from (1) above, it will be the smaller of
945 * the two possibilities. */
946 float scaleFactor = std::min( fHin / fHout, fWin / fWout );
947
948 /* Since we are crop-and-zooming (as opposed to letter/pillar boxing) we can
949 * simply multiply the output by our scaleFactor to get the cropped input
950 * size. Note that at least one of {fWcrop, fHcrop} is going to wind up
951 * being {fWin, fHin} respectively because fHout or fWout cancels out the
952 * scaleFactor calculation above.
953 *
954 * Specifically:
955 * if ( fHin / fHout ) < ( fWin / fWout ) we crop the sides off
956 * input, in which case
957 * scaleFactor = fHin / fHout
958 * fWcrop = fHin / fHout * fWout
959 * fHcrop = fHin
960 *
961 * Note that fWcrop <= fWin ( because ( fHin / fHout ) * fWout < fWin, which
962 * is just the inequality above with both sides multiplied by fWout
963 *
964 * on the other hand if ( fWin / fWout ) < ( fHin / fHout) we crop the top
965 * and the bottom off of input, and
966 * scaleFactor = fWin / fWout
967 * fWcrop = fWin
968 * fHCrop = fWin / fWout * fHout
969 */
970 float fWcrop = scaleFactor * fWout;
971 float fHcrop = scaleFactor * fHout;
972
973 /* Convert to integer and truncate to an even number */
974 Size cropSz = { 2*static_cast<uint32_t>(fWcrop/2.0f),
975 2*static_cast<uint32_t>(fHcrop/2.0f) };
976
977 /* Convert to a centered rectange with even top/left */
978 IMapper::Rect inputCrop {
979 2*static_cast<int32_t>((inSz.width - cropSz.width)/4),
980 2*static_cast<int32_t>((inSz.height - cropSz.height)/4),
981 static_cast<int32_t>(cropSz.width),
982 static_cast<int32_t>(cropSz.height) };
983
984 if ((inputCrop.top < 0) ||
985 (inputCrop.top >= static_cast<int32_t>(inSz.height)) ||
986 (inputCrop.left < 0) ||
987 (inputCrop.left >= static_cast<int32_t>(inSz.width)) ||
988 (inputCrop.width <= 0) ||
989 (inputCrop.width + inputCrop.left > static_cast<int32_t>(inSz.width)) ||
990 (inputCrop.height <= 0) ||
991 (inputCrop.height + inputCrop.top > static_cast<int32_t>(inSz.height)))
992 {
993 ALOGE("%s: came up with really wrong crop rectangle",__FUNCTION__);
994 ALOGE("%s: input layout %dx%d to for output size %dx%d",
995 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
996 ALOGE("%s: computed input crop +%d,+%d %dx%d",
997 __FUNCTION__, inputCrop.left, inputCrop.top,
998 inputCrop.width, inputCrop.height);
999 return -1;
1000 }
1001
1002 YCbCrLayout inputLayout;
1003 ret = in->getCroppedLayout(inputCrop, &inputLayout);
1004 if (ret != 0) {
1005 ALOGE("%s: failed to crop input layout %dx%d to for output size %dx%d",
1006 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1007 ALOGE("%s: computed input crop +%d,+%d %dx%d",
1008 __FUNCTION__, inputCrop.left, inputCrop.top,
1009 inputCrop.width, inputCrop.height);
1010 return ret;
1011 }
1012 ALOGV("%s: crop input layout %dx%d to for output size %dx%d",
1013 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1014 ALOGV("%s: computed input crop +%d,+%d %dx%d",
1015 __FUNCTION__, inputCrop.left, inputCrop.top,
1016 inputCrop.width, inputCrop.height);
1017
1018
1019 // Scale
1020 YCbCrLayout outFullLayout;
1021
1022 ret = mYu12ThumbFrame->getLayout(&outFullLayout);
1023 if (ret != 0) {
1024 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
1025 return ret;
1026 }
1027
1028
1029 ret = libyuv::I420Scale(
1030 static_cast<uint8_t*>(inputLayout.y),
1031 inputLayout.yStride,
1032 static_cast<uint8_t*>(inputLayout.cb),
1033 inputLayout.cStride,
1034 static_cast<uint8_t*>(inputLayout.cr),
1035 inputLayout.cStride,
1036 inputCrop.width,
1037 inputCrop.height,
1038 static_cast<uint8_t*>(outFullLayout.y),
1039 outFullLayout.yStride,
1040 static_cast<uint8_t*>(outFullLayout.cb),
1041 outFullLayout.cStride,
1042 static_cast<uint8_t*>(outFullLayout.cr),
1043 outFullLayout.cStride,
1044 outSz.width,
1045 outSz.height,
1046 libyuv::FilterMode::kFilterNone);
1047
1048 if (ret != 0) {
1049 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
1050 __FUNCTION__, inputCrop.width, inputCrop.height,
1051 outSz.width, outSz.height, ret);
1052 return ret;
1053 }
1054
1055 *out = outFullLayout;
1056 return 0;
1057}
1058
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001059int ExternalCameraDeviceSession::OutputThread::formatConvertLocked(
1060 const YCbCrLayout& in, const YCbCrLayout& out, Size sz, uint32_t format) {
1061 int ret = 0;
1062 switch (format) {
1063 case V4L2_PIX_FMT_NV21:
1064 ret = libyuv::I420ToNV21(
1065 static_cast<uint8_t*>(in.y),
1066 in.yStride,
1067 static_cast<uint8_t*>(in.cb),
1068 in.cStride,
1069 static_cast<uint8_t*>(in.cr),
1070 in.cStride,
1071 static_cast<uint8_t*>(out.y),
1072 out.yStride,
1073 static_cast<uint8_t*>(out.cr),
1074 out.cStride,
1075 sz.width,
1076 sz.height);
1077 if (ret != 0) {
1078 ALOGE("%s: convert to NV21 buffer failed! ret %d",
1079 __FUNCTION__, ret);
1080 return ret;
1081 }
1082 break;
1083 case V4L2_PIX_FMT_NV12:
1084 ret = libyuv::I420ToNV12(
1085 static_cast<uint8_t*>(in.y),
1086 in.yStride,
1087 static_cast<uint8_t*>(in.cb),
1088 in.cStride,
1089 static_cast<uint8_t*>(in.cr),
1090 in.cStride,
1091 static_cast<uint8_t*>(out.y),
1092 out.yStride,
1093 static_cast<uint8_t*>(out.cb),
1094 out.cStride,
1095 sz.width,
1096 sz.height);
1097 if (ret != 0) {
1098 ALOGE("%s: convert to NV12 buffer failed! ret %d",
1099 __FUNCTION__, ret);
1100 return ret;
1101 }
1102 break;
1103 case V4L2_PIX_FMT_YVU420: // YV12
1104 case V4L2_PIX_FMT_YUV420: // YU12
1105 // TODO: maybe we can speed up here by somehow save this copy?
1106 ret = libyuv::I420Copy(
1107 static_cast<uint8_t*>(in.y),
1108 in.yStride,
1109 static_cast<uint8_t*>(in.cb),
1110 in.cStride,
1111 static_cast<uint8_t*>(in.cr),
1112 in.cStride,
1113 static_cast<uint8_t*>(out.y),
1114 out.yStride,
1115 static_cast<uint8_t*>(out.cb),
1116 out.cStride,
1117 static_cast<uint8_t*>(out.cr),
1118 out.cStride,
1119 sz.width,
1120 sz.height);
1121 if (ret != 0) {
1122 ALOGE("%s: copy to YV12 or YU12 buffer failed! ret %d",
1123 __FUNCTION__, ret);
1124 return ret;
1125 }
1126 break;
1127 case FLEX_YUV_GENERIC:
1128 // TODO: b/72261744 write to arbitrary flexible YUV layout. Slow.
1129 ALOGE("%s: unsupported flexible yuv layout"
1130 " y %p cb %p cr %p y_str %d c_str %d c_step %d",
1131 __FUNCTION__, out.y, out.cb, out.cr,
1132 out.yStride, out.cStride, out.chromaStep);
1133 return -1;
1134 default:
1135 ALOGE("%s: unknown YUV format 0x%x!", __FUNCTION__, format);
1136 return -1;
1137 }
1138 return 0;
1139}
1140
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001141int ExternalCameraDeviceSession::OutputThread::encodeJpegYU12(
1142 const Size & inSz, const YCbCrLayout& inLayout,
1143 int jpegQuality, const void *app1Buffer, size_t app1Size,
1144 void *out, const size_t maxOutSize, size_t &actualCodeSize)
1145{
1146 /* libjpeg is a C library so we use C-style "inheritance" by
1147 * putting libjpeg's jpeg_destination_mgr first in our custom
1148 * struct. This allows us to cast jpeg_destination_mgr* to
1149 * CustomJpegDestMgr* when we get it passed to us in a callback */
1150 struct CustomJpegDestMgr {
1151 struct jpeg_destination_mgr mgr;
1152 JOCTET *mBuffer;
1153 size_t mBufferSize;
1154 size_t mEncodedSize;
1155 bool mSuccess;
1156 } dmgr;
1157
1158 jpeg_compress_struct cinfo = {};
1159 jpeg_error_mgr jerr;
1160
1161 /* Initialize error handling with standard callbacks, but
1162 * then override output_message (to print to ALOG) and
1163 * error_exit to set a flag and print a message instead
1164 * of killing the whole process */
1165 cinfo.err = jpeg_std_error(&jerr);
1166
1167 cinfo.err->output_message = [](j_common_ptr cinfo) {
1168 char buffer[JMSG_LENGTH_MAX];
1169
1170 /* Create the message */
1171 (*cinfo->err->format_message)(cinfo, buffer);
1172 ALOGE("libjpeg error: %s", buffer);
1173 };
1174 cinfo.err->error_exit = [](j_common_ptr cinfo) {
1175 (*cinfo->err->output_message)(cinfo);
1176 if(cinfo->client_data) {
1177 auto & dmgr =
1178 *reinterpret_cast<CustomJpegDestMgr*>(cinfo->client_data);
1179 dmgr.mSuccess = false;
1180 }
1181 };
1182 /* Now that we initialized some callbacks, let's create our compressor */
1183 jpeg_create_compress(&cinfo);
1184
1185 /* Initialize our destination manager */
1186 dmgr.mBuffer = static_cast<JOCTET*>(out);
1187 dmgr.mBufferSize = maxOutSize;
1188 dmgr.mEncodedSize = 0;
1189 dmgr.mSuccess = true;
1190 cinfo.client_data = static_cast<void*>(&dmgr);
1191
1192 /* These lambdas become C-style function pointers and as per C++11 spec
1193 * may not capture anything */
1194 dmgr.mgr.init_destination = [](j_compress_ptr cinfo) {
1195 auto & dmgr = reinterpret_cast<CustomJpegDestMgr&>(*cinfo->dest);
1196 dmgr.mgr.next_output_byte = dmgr.mBuffer;
1197 dmgr.mgr.free_in_buffer = dmgr.mBufferSize;
1198 ALOGV("%s:%d jpeg start: %p [%zu]",
1199 __FUNCTION__, __LINE__, dmgr.mBuffer, dmgr.mBufferSize);
1200 };
1201
1202 dmgr.mgr.empty_output_buffer = [](j_compress_ptr cinfo __unused) {
1203 ALOGV("%s:%d Out of buffer", __FUNCTION__, __LINE__);
1204 return 0;
1205 };
1206
1207 dmgr.mgr.term_destination = [](j_compress_ptr cinfo) {
1208 auto & dmgr = reinterpret_cast<CustomJpegDestMgr&>(*cinfo->dest);
1209 dmgr.mEncodedSize = dmgr.mBufferSize - dmgr.mgr.free_in_buffer;
1210 ALOGV("%s:%d Done with jpeg: %zu", __FUNCTION__, __LINE__, dmgr.mEncodedSize);
1211 };
1212 cinfo.dest = reinterpret_cast<struct jpeg_destination_mgr*>(&dmgr);
1213
1214 /* We are going to be using JPEG in raw data mode, so we are passing
1215 * straight subsampled planar YCbCr and it will not touch our pixel
1216 * data or do any scaling or anything */
1217 cinfo.image_width = inSz.width;
1218 cinfo.image_height = inSz.height;
1219 cinfo.input_components = 3;
1220 cinfo.in_color_space = JCS_YCbCr;
1221
1222 /* Initialize defaults and then override what we want */
1223 jpeg_set_defaults(&cinfo);
1224
1225 jpeg_set_quality(&cinfo, jpegQuality, 1);
1226 jpeg_set_colorspace(&cinfo, JCS_YCbCr);
1227 cinfo.raw_data_in = 1;
1228 cinfo.dct_method = JDCT_IFAST;
1229
1230 /* Configure sampling factors. The sampling factor is JPEG subsampling 420
1231 * because the source format is YUV420. Note that libjpeg sampling factors
1232 * are... a little weird. Sampling of Y=2,U=1,V=1 means there is 1 U and
1233 * 1 V value for each 2 Y values */
1234 cinfo.comp_info[0].h_samp_factor = 2;
1235 cinfo.comp_info[0].v_samp_factor = 2;
1236 cinfo.comp_info[1].h_samp_factor = 1;
1237 cinfo.comp_info[1].v_samp_factor = 1;
1238 cinfo.comp_info[2].h_samp_factor = 1;
1239 cinfo.comp_info[2].v_samp_factor = 1;
1240
1241 /* Let's not hardcode YUV420 in 6 places... 5 was enough */
1242 int maxVSampFactor = std::max( {
1243 cinfo.comp_info[0].v_samp_factor,
1244 cinfo.comp_info[1].v_samp_factor,
1245 cinfo.comp_info[2].v_samp_factor
1246 });
1247 int cVSubSampling = cinfo.comp_info[0].v_samp_factor /
1248 cinfo.comp_info[1].v_samp_factor;
1249
1250 /* Start the compressor */
1251 jpeg_start_compress(&cinfo, TRUE);
1252
1253 /* Compute our macroblock height, so we can pad our input to be vertically
1254 * macroblock aligned.
1255 * TODO: Does it need to be horizontally MCU aligned too? */
1256
1257 size_t mcuV = DCTSIZE*maxVSampFactor;
1258 size_t paddedHeight = mcuV * ((inSz.height + mcuV - 1) / mcuV);
1259
1260 /* libjpeg uses arrays of row pointers, which makes it really easy to pad
1261 * data vertically (unfortunately doesn't help horizontally) */
1262 std::vector<JSAMPROW> yLines (paddedHeight);
1263 std::vector<JSAMPROW> cbLines(paddedHeight/cVSubSampling);
1264 std::vector<JSAMPROW> crLines(paddedHeight/cVSubSampling);
1265
1266 uint8_t *py = static_cast<uint8_t*>(inLayout.y);
1267 uint8_t *pcr = static_cast<uint8_t*>(inLayout.cr);
1268 uint8_t *pcb = static_cast<uint8_t*>(inLayout.cb);
1269
1270 for(uint32_t i = 0; i < paddedHeight; i++)
1271 {
1272 /* Once we are in the padding territory we still point to the last line
1273 * effectively replicating it several times ~ CLAMP_TO_EDGE */
1274 int li = std::min(i, inSz.height - 1);
1275 yLines[i] = static_cast<JSAMPROW>(py + li * inLayout.yStride);
1276 if(i < paddedHeight / cVSubSampling)
1277 {
1278 crLines[i] = static_cast<JSAMPROW>(pcr + li * inLayout.cStride);
1279 cbLines[i] = static_cast<JSAMPROW>(pcb + li * inLayout.cStride);
1280 }
1281 }
1282
1283 /* If APP1 data was passed in, use it */
1284 if(app1Buffer && app1Size)
1285 {
1286 jpeg_write_marker(&cinfo, JPEG_APP0 + 1,
1287 static_cast<const JOCTET*>(app1Buffer), app1Size);
1288 }
1289
1290 /* While we still have padded height left to go, keep giving it one
1291 * macroblock at a time. */
1292 while (cinfo.next_scanline < cinfo.image_height) {
1293 const uint32_t batchSize = DCTSIZE * maxVSampFactor;
1294 const uint32_t nl = cinfo.next_scanline;
1295 JSAMPARRAY planes[3]{ &yLines[nl],
1296 &cbLines[nl/cVSubSampling],
1297 &crLines[nl/cVSubSampling] };
1298
1299 uint32_t done = jpeg_write_raw_data(&cinfo, planes, batchSize);
1300
1301 if (done != batchSize) {
1302 ALOGE("%s: compressed %u lines, expected %u (total %u/%u)",
1303 __FUNCTION__, done, batchSize, cinfo.next_scanline,
1304 cinfo.image_height);
1305 return -1;
1306 }
1307 }
1308
1309 /* This will flush everything */
1310 jpeg_finish_compress(&cinfo);
1311
1312 /* Grab the actual code size and set it */
1313 actualCodeSize = dmgr.mEncodedSize;
1314
1315 return 0;
1316}
1317
1318/*
1319 * TODO: There needs to be a mechanism to discover allocated buffer size
1320 * in the HAL.
1321 *
1322 * This is very fragile because it is duplicated computation from:
1323 * frameworks/av/services/camera/libcameraservice/device3/Camera3Device.cpp
1324 *
1325 */
1326
1327/* This assumes mSupportedFormats have all been declared as supporting
1328 * HAL_PIXEL_FORMAT_BLOB to the framework */
1329Size ExternalCameraDeviceSession::getMaxJpegResolution() const {
1330 Size ret { 0, 0 };
1331 for(auto & fmt : mSupportedFormats) {
1332 if(fmt.width * fmt.height > ret.width * ret.height) {
1333 ret = Size { fmt.width, fmt.height };
1334 }
1335 }
1336 return ret;
1337}
1338
1339Size ExternalCameraDeviceSession::getMaxThumbResolution() const {
1340 Size thumbSize { 0, 0 };
1341 camera_metadata_ro_entry entry =
1342 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
1343 for(uint32_t i = 0; i < entry.count; i += 2) {
1344 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
1345 static_cast<uint32_t>(entry.data.i32[i+1]) };
1346 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
1347 thumbSize = sz;
1348 }
1349 }
1350
1351 if (thumbSize.width * thumbSize.height == 0) {
1352 ALOGW("%s: non-zero thumbnail size not available", __FUNCTION__);
1353 }
1354
1355 return thumbSize;
1356}
1357
1358
1359ssize_t ExternalCameraDeviceSession::getJpegBufferSize(
1360 uint32_t width, uint32_t height) const {
1361 // Constant from camera3.h
1362 const ssize_t kMinJpegBufferSize = 256 * 1024 + sizeof(CameraBlob);
1363 // Get max jpeg size (area-wise).
1364 if (mMaxJpegResolution.width == 0) {
1365 ALOGE("%s: Do not have a single supported JPEG stream",
1366 __FUNCTION__);
1367 return BAD_VALUE;
1368 }
1369
1370 // Get max jpeg buffer size
1371 ssize_t maxJpegBufferSize = 0;
1372 camera_metadata_ro_entry jpegBufMaxSize =
1373 mCameraCharacteristics.find(ANDROID_JPEG_MAX_SIZE);
1374 if (jpegBufMaxSize.count == 0) {
1375 ALOGE("%s: Can't find maximum JPEG size in static metadata!",
1376 __FUNCTION__);
1377 return BAD_VALUE;
1378 }
1379 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
1380
1381 if (maxJpegBufferSize <= kMinJpegBufferSize) {
1382 ALOGE("%s: ANDROID_JPEG_MAX_SIZE (%zd) <= kMinJpegBufferSize (%zd)",
1383 __FUNCTION__, maxJpegBufferSize, kMinJpegBufferSize);
1384 return BAD_VALUE;
1385 }
1386
1387 // Calculate final jpeg buffer size for the given resolution.
1388 float scaleFactor = ((float) (width * height)) /
1389 (mMaxJpegResolution.width * mMaxJpegResolution.height);
1390 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
1391 kMinJpegBufferSize;
1392 if (jpegBufferSize > maxJpegBufferSize) {
1393 jpegBufferSize = maxJpegBufferSize;
1394 }
1395
1396 return jpegBufferSize;
1397}
1398
1399int ExternalCameraDeviceSession::OutputThread::createJpegLocked(
1400 HalStreamBuffer &halBuf,
1401 HalRequest &req)
1402{
1403 int ret;
1404 auto lfail = [&](auto... args) {
1405 ALOGE(args...);
1406
1407 return 1;
1408 };
1409 auto parent = mParent.promote();
1410 if (parent == nullptr) {
1411 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1412 return 1;
1413 }
1414
1415 ALOGV("%s: HAL buffer sid: %d bid: %" PRIu64 " w: %u h: %u",
1416 __FUNCTION__, halBuf.streamId, static_cast<uint64_t>(halBuf.bufferId),
1417 halBuf.width, halBuf.height);
1418 ALOGV("%s: HAL buffer fmt: %x usage: %" PRIx64 " ptr: %p",
1419 __FUNCTION__, halBuf.format, static_cast<uint64_t>(halBuf.usage),
1420 halBuf.bufPtr);
1421 ALOGV("%s: YV12 buffer %d x %d",
1422 __FUNCTION__,
1423 mYu12Frame->mWidth, mYu12Frame->mHeight);
1424
1425 int jpegQuality, thumbQuality;
1426 Size thumbSize;
1427
1428 if (req.setting.exists(ANDROID_JPEG_QUALITY)) {
1429 camera_metadata_entry entry =
1430 req.setting.find(ANDROID_JPEG_QUALITY);
1431 jpegQuality = entry.data.u8[0];
1432 } else {
1433 return lfail("%s: ANDROID_JPEG_QUALITY not set",__FUNCTION__);
1434 }
1435
1436 if (req.setting.exists(ANDROID_JPEG_THUMBNAIL_QUALITY)) {
1437 camera_metadata_entry entry =
1438 req.setting.find(ANDROID_JPEG_THUMBNAIL_QUALITY);
1439 thumbQuality = entry.data.u8[0];
1440 } else {
1441 return lfail(
1442 "%s: ANDROID_JPEG_THUMBNAIL_QUALITY not set",
1443 __FUNCTION__);
1444 }
1445
1446 if (req.setting.exists(ANDROID_JPEG_THUMBNAIL_SIZE)) {
1447 camera_metadata_entry entry =
1448 req.setting.find(ANDROID_JPEG_THUMBNAIL_SIZE);
1449 thumbSize = Size { static_cast<uint32_t>(entry.data.i32[0]),
1450 static_cast<uint32_t>(entry.data.i32[1])
1451 };
1452 } else {
1453 return lfail(
1454 "%s: ANDROID_JPEG_THUMBNAIL_SIZE not set", __FUNCTION__);
1455 }
1456
1457 /* Cropped and scaled YU12 buffer for main and thumbnail */
1458 YCbCrLayout yu12Main;
1459 Size jpegSize { halBuf.width, halBuf.height };
1460
1461 /* Compute temporary buffer sizes accounting for the following:
1462 * thumbnail can't exceed APP1 size of 64K
1463 * main image needs to hold APP1, headers, and at most a poorly
1464 * compressed image */
1465 const ssize_t maxThumbCodeSize = 64 * 1024;
1466 const ssize_t maxJpegCodeSize = parent->getJpegBufferSize(jpegSize.width,
1467 jpegSize.height);
1468
1469 /* Check that getJpegBufferSize did not return an error */
1470 if (maxJpegCodeSize < 0) {
1471 return lfail(
1472 "%s: getJpegBufferSize returned %zd",__FUNCTION__,maxJpegCodeSize);
1473 }
1474
1475
1476 /* Hold actual thumbnail and main image code sizes */
1477 size_t thumbCodeSize = 0, jpegCodeSize = 0;
1478 /* Temporary thumbnail code buffer */
1479 std::vector<uint8_t> thumbCode(maxThumbCodeSize);
1480
1481 YCbCrLayout yu12Thumb;
1482 ret = cropAndScaleThumbLocked(mYu12Frame, thumbSize, &yu12Thumb);
1483
1484 if (ret != 0) {
1485 return lfail(
1486 "%s: crop and scale thumbnail failed!", __FUNCTION__);
1487 }
1488
1489 /* Scale and crop main jpeg */
1490 ret = cropAndScaleLocked(mYu12Frame, jpegSize, &yu12Main);
1491
1492 if (ret != 0) {
1493 return lfail("%s: crop and scale main failed!", __FUNCTION__);
1494 }
1495
1496 /* Encode the thumbnail image */
1497 ret = encodeJpegYU12(thumbSize, yu12Thumb,
1498 thumbQuality, 0, 0,
1499 &thumbCode[0], maxThumbCodeSize, thumbCodeSize);
1500
1501 if (ret != 0) {
1502 return lfail("%s: encodeJpegYU12 failed with %d",__FUNCTION__, ret);
1503 }
1504
1505 /* Combine camera characteristics with request settings to form EXIF
1506 * metadata */
1507 common::V1_0::helper::CameraMetadata meta(parent->mCameraCharacteristics);
1508 meta.append(req.setting);
1509
1510 /* Generate EXIF object */
1511 std::unique_ptr<ExifUtils> utils(ExifUtils::create());
1512 /* Make sure it's initialized */
1513 utils->initialize();
1514
1515 utils->setFromMetadata(meta, jpegSize.width, jpegSize.height);
1516
1517 /* Check if we made a non-zero-sized thumbnail. Currently not possible
1518 * that we got this far and the code is size 0, but if this code moves
1519 * around it might become relevant again */
1520
1521 ret = utils->generateApp1(thumbCodeSize ? &thumbCode[0] : 0, thumbCodeSize);
1522
1523 if (!ret) {
1524 return lfail("%s: generating APP1 failed", __FUNCTION__);
1525 }
1526
1527 /* Get internal buffer */
1528 size_t exifDataSize = utils->getApp1Length();
1529 const uint8_t* exifData = utils->getApp1Buffer();
1530
1531 /* Lock the HAL jpeg code buffer */
1532 void *bufPtr = sHandleImporter.lock(
1533 *(halBuf.bufPtr), halBuf.usage, maxJpegCodeSize);
1534
1535 if (!bufPtr) {
1536 return lfail("%s: could not lock %zu bytes", __FUNCTION__, maxJpegCodeSize);
1537 }
1538
1539 /* Encode the main jpeg image */
1540 ret = encodeJpegYU12(jpegSize, yu12Main,
1541 jpegQuality, exifData, exifDataSize,
1542 bufPtr, maxJpegCodeSize, jpegCodeSize);
1543
1544 /* TODO: Not sure this belongs here, maybe better to pass jpegCodeSize out
1545 * and do this when returning buffer to parent */
1546 CameraBlob blob { CameraBlobId::JPEG, static_cast<uint32_t>(jpegCodeSize) };
1547 void *blobDst =
1548 reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(bufPtr) +
1549 maxJpegCodeSize -
1550 sizeof(CameraBlob));
1551 memcpy(blobDst, &blob, sizeof(CameraBlob));
1552
1553 /* Unlock the HAL jpeg code buffer */
1554 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
1555 if (relFence > 0) {
1556 halBuf.acquireFence = relFence;
1557 }
1558
1559 /* Check if our JPEG actually succeeded */
1560 if (ret != 0) {
1561 return lfail(
1562 "%s: encodeJpegYU12 failed with %d",__FUNCTION__, ret);
1563 }
1564
1565 ALOGV("%s: encoded JPEG (ret:%d) with Q:%d max size: %zu",
1566 __FUNCTION__, ret, jpegQuality, maxJpegCodeSize);
1567
1568 return 0;
1569}
1570
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001571bool ExternalCameraDeviceSession::OutputThread::threadLoop() {
1572 HalRequest req;
1573 auto parent = mParent.promote();
1574 if (parent == nullptr) {
1575 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1576 return false;
1577 }
1578
1579 // TODO: maybe we need to setup a sensor thread to dq/enq v4l frames
1580 // regularly to prevent v4l buffer queue filled with stale buffers
1581 // when app doesn't program a preveiw request
1582 waitForNextRequest(&req);
1583 if (req.frameIn == nullptr) {
1584 // No new request, wait again
1585 return true;
1586 }
1587
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001588 auto onDeviceError = [&](auto... args) {
1589 ALOGE(args...);
1590 parent->notifyError(
1591 req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1592 signalRequestDone();
1593 return false;
1594 };
1595
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001596 if (req.frameIn->mFourcc != V4L2_PIX_FMT_MJPEG) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001597 return onDeviceError("%s: do not support V4L2 format %c%c%c%c", __FUNCTION__,
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001598 req.frameIn->mFourcc & 0xFF,
1599 (req.frameIn->mFourcc >> 8) & 0xFF,
1600 (req.frameIn->mFourcc >> 16) & 0xFF,
1601 (req.frameIn->mFourcc >> 24) & 0xFF);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001602 }
1603
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001604 std::unique_lock<std::mutex> lk(mBufferLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001605 // Convert input V4L2 frame to YU12 of the same size
1606 // TODO: see if we can save some computation by converting to YV12 here
1607 uint8_t* inData;
1608 size_t inDataSize;
1609 req.frameIn->map(&inData, &inDataSize);
1610 // TODO: profile
1611 // TODO: in some special case maybe we can decode jpg directly to gralloc output?
1612 int res = libyuv::MJPGToI420(
1613 inData, inDataSize,
1614 static_cast<uint8_t*>(mYu12FrameLayout.y),
1615 mYu12FrameLayout.yStride,
1616 static_cast<uint8_t*>(mYu12FrameLayout.cb),
1617 mYu12FrameLayout.cStride,
1618 static_cast<uint8_t*>(mYu12FrameLayout.cr),
1619 mYu12FrameLayout.cStride,
1620 mYu12Frame->mWidth, mYu12Frame->mHeight,
1621 mYu12Frame->mWidth, mYu12Frame->mHeight);
1622
1623 if (res != 0) {
1624 // For some webcam, the first few V4L2 frames might be malformed...
1625 ALOGE("%s: Convert V4L2 frame to YU12 failed! res %d", __FUNCTION__, res);
1626 lk.unlock();
1627 Status st = parent->processCaptureRequestError(req);
1628 if (st != Status::OK) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001629 return onDeviceError("%s: failed to process capture request error!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001630 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001631 signalRequestDone();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001632 return true;
1633 }
1634
1635 ALOGV("%s processing new request", __FUNCTION__);
1636 const int kSyncWaitTimeoutMs = 500;
1637 for (auto& halBuf : req.buffers) {
1638 if (halBuf.acquireFence != -1) {
1639 int ret = sync_wait(halBuf.acquireFence, kSyncWaitTimeoutMs);
1640 if (ret) {
1641 halBuf.fenceTimeout = true;
1642 } else {
1643 ::close(halBuf.acquireFence);
Yin-Chia Yeh1e089662018-02-02 15:57:58 -08001644 halBuf.acquireFence = -1;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001645 }
1646 }
1647
1648 if (halBuf.fenceTimeout) {
1649 continue;
1650 }
1651
1652 // Gralloc lockYCbCr the buffer
1653 switch (halBuf.format) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001654 case PixelFormat::BLOB: {
1655 int ret = createJpegLocked(halBuf, req);
1656
1657 if(ret != 0) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001658 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001659 return onDeviceError("%s: createJpegLocked failed with %d",
1660 __FUNCTION__, ret);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001661 }
1662 } break;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001663 case PixelFormat::YCBCR_420_888:
1664 case PixelFormat::YV12: {
1665 IMapper::Rect outRect {0, 0,
1666 static_cast<int32_t>(halBuf.width),
1667 static_cast<int32_t>(halBuf.height)};
1668 YCbCrLayout outLayout = sHandleImporter.lockYCbCr(
1669 *(halBuf.bufPtr), halBuf.usage, outRect);
1670 ALOGV("%s: outLayout y %p cb %p cr %p y_str %d c_str %d c_step %d",
1671 __FUNCTION__, outLayout.y, outLayout.cb, outLayout.cr,
1672 outLayout.yStride, outLayout.cStride, outLayout.chromaStep);
1673
1674 // Convert to output buffer size/format
1675 uint32_t outputFourcc = getFourCcFromLayout(outLayout);
1676 ALOGV("%s: converting to format %c%c%c%c", __FUNCTION__,
1677 outputFourcc & 0xFF,
1678 (outputFourcc >> 8) & 0xFF,
1679 (outputFourcc >> 16) & 0xFF,
1680 (outputFourcc >> 24) & 0xFF);
1681
1682 YCbCrLayout cropAndScaled;
1683 int ret = cropAndScaleLocked(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001684 mYu12Frame,
1685 Size { halBuf.width, halBuf.height },
1686 &cropAndScaled);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001687 if (ret != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001688 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001689 return onDeviceError("%s: crop and scale failed!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001690 }
1691
1692 Size sz {halBuf.width, halBuf.height};
1693 ret = formatConvertLocked(cropAndScaled, outLayout, sz, outputFourcc);
1694 if (ret != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001695 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001696 return onDeviceError("%s: format coversion failed!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001697 }
1698 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
1699 if (relFence > 0) {
1700 halBuf.acquireFence = relFence;
1701 }
1702 } break;
1703 default:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001704 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001705 return onDeviceError("%s: unknown output format %x", __FUNCTION__, halBuf.format);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001706 }
1707 } // for each buffer
1708 mScaledYu12Frames.clear();
1709
1710 // Don't hold the lock while calling back to parent
1711 lk.unlock();
1712 Status st = parent->processCaptureResult(req);
1713 if (st != Status::OK) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001714 return onDeviceError("%s: failed to process capture result!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001715 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001716 signalRequestDone();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001717 return true;
1718}
1719
1720Status ExternalCameraDeviceSession::OutputThread::allocateIntermediateBuffers(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001721 const Size& v4lSize, const Size& thumbSize,
1722 const hidl_vec<Stream>& streams) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001723 std::lock_guard<std::mutex> lk(mBufferLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001724 if (mScaledYu12Frames.size() != 0) {
1725 ALOGE("%s: intermediate buffer pool has %zu inflight buffers! (expect 0)",
1726 __FUNCTION__, mScaledYu12Frames.size());
1727 return Status::INTERNAL_ERROR;
1728 }
1729
1730 // Allocating intermediate YU12 frame
1731 if (mYu12Frame == nullptr || mYu12Frame->mWidth != v4lSize.width ||
1732 mYu12Frame->mHeight != v4lSize.height) {
1733 mYu12Frame.clear();
1734 mYu12Frame = new AllocatedFrame(v4lSize.width, v4lSize.height);
1735 int ret = mYu12Frame->allocate(&mYu12FrameLayout);
1736 if (ret != 0) {
1737 ALOGE("%s: allocating YU12 frame failed!", __FUNCTION__);
1738 return Status::INTERNAL_ERROR;
1739 }
1740 }
1741
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001742 // Allocating intermediate YU12 thumbnail frame
1743 if (mYu12ThumbFrame == nullptr ||
1744 mYu12ThumbFrame->mWidth != thumbSize.width ||
1745 mYu12ThumbFrame->mHeight != thumbSize.height) {
1746 mYu12ThumbFrame.clear();
1747 mYu12ThumbFrame = new AllocatedFrame(thumbSize.width, thumbSize.height);
1748 int ret = mYu12ThumbFrame->allocate(&mYu12ThumbFrameLayout);
1749 if (ret != 0) {
1750 ALOGE("%s: allocating YU12 thumb frame failed!", __FUNCTION__);
1751 return Status::INTERNAL_ERROR;
1752 }
1753 }
1754
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001755 // Allocating scaled buffers
1756 for (const auto& stream : streams) {
1757 Size sz = {stream.width, stream.height};
1758 if (sz == v4lSize) {
1759 continue; // Don't need an intermediate buffer same size as v4lBuffer
1760 }
1761 if (mIntermediateBuffers.count(sz) == 0) {
1762 // Create new intermediate buffer
1763 sp<AllocatedFrame> buf = new AllocatedFrame(stream.width, stream.height);
1764 int ret = buf->allocate();
1765 if (ret != 0) {
1766 ALOGE("%s: allocating intermediate YU12 frame %dx%d failed!",
1767 __FUNCTION__, stream.width, stream.height);
1768 return Status::INTERNAL_ERROR;
1769 }
1770 mIntermediateBuffers[sz] = buf;
1771 }
1772 }
1773
1774 // Remove unconfigured buffers
1775 auto it = mIntermediateBuffers.begin();
1776 while (it != mIntermediateBuffers.end()) {
1777 bool configured = false;
1778 auto sz = it->first;
1779 for (const auto& stream : streams) {
1780 if (stream.width == sz.width && stream.height == sz.height) {
1781 configured = true;
1782 break;
1783 }
1784 }
1785 if (configured) {
1786 it++;
1787 } else {
1788 it = mIntermediateBuffers.erase(it);
1789 }
1790 }
1791 return Status::OK;
1792}
1793
1794Status ExternalCameraDeviceSession::OutputThread::submitRequest(const HalRequest& req) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001795 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001796 // TODO: reduce object copy in this path
1797 mRequestList.push_back(req);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001798 lk.unlock();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001799 mRequestCond.notify_one();
1800 return Status::OK;
1801}
1802
1803void ExternalCameraDeviceSession::OutputThread::flush() {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001804 auto parent = mParent.promote();
1805 if (parent == nullptr) {
1806 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1807 return;
1808 }
1809
1810 std::unique_lock<std::mutex> lk(mRequestListLock);
1811 std::list<HalRequest> reqs = mRequestList;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001812 mRequestList.clear();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001813 if (mProcessingRequest) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001814 std::chrono::seconds timeout = std::chrono::seconds(kFlushWaitTimeoutSec);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001815 auto st = mRequestDoneCond.wait_for(lk, timeout);
1816 if (st == std::cv_status::timeout) {
1817 ALOGE("%s: wait for inflight request finish timeout!", __FUNCTION__);
1818 }
1819 }
1820
1821 lk.unlock();
1822 for (const auto& req : reqs) {
1823 parent->processCaptureRequestError(req);
1824 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001825}
1826
1827void ExternalCameraDeviceSession::OutputThread::waitForNextRequest(HalRequest* out) {
1828 if (out == nullptr) {
1829 ALOGE("%s: out is null", __FUNCTION__);
1830 return;
1831 }
1832
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001833 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001834 int waitTimes = 0;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001835 while (mRequestList.empty()) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001836 if (exitPending()) {
1837 return;
1838 }
1839 std::chrono::milliseconds timeout = std::chrono::milliseconds(kReqWaitTimeoutMs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001840 auto st = mRequestCond.wait_for(lk, timeout);
1841 if (st == std::cv_status::timeout) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001842 waitTimes++;
1843 if (waitTimes == kReqWaitTimesMax) {
1844 // no new request, return
1845 return;
1846 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001847 }
1848 }
1849 *out = mRequestList.front();
1850 mRequestList.pop_front();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001851 mProcessingRequest = true;
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001852 mProcessingFrameNumer = out->frameNumber;
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001853}
1854
1855void ExternalCameraDeviceSession::OutputThread::signalRequestDone() {
1856 std::unique_lock<std::mutex> lk(mRequestListLock);
1857 mProcessingRequest = false;
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001858 mProcessingFrameNumer = 0;
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001859 lk.unlock();
1860 mRequestDoneCond.notify_one();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001861}
1862
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001863void ExternalCameraDeviceSession::OutputThread::dump(int fd) {
1864 std::lock_guard<std::mutex> lk(mRequestListLock);
1865 if (mProcessingRequest) {
1866 dprintf(fd, "OutputThread processing frame %d\n", mProcessingFrameNumer);
1867 } else {
1868 dprintf(fd, "OutputThread not processing any frames\n");
1869 }
1870 dprintf(fd, "OutputThread request list contains frame: ");
1871 for (const auto& req : mRequestList) {
1872 dprintf(fd, "%d, ", req.frameNumber);
1873 }
1874 dprintf(fd, "\n");
1875}
1876
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001877void ExternalCameraDeviceSession::cleanupBuffersLocked(int id) {
1878 for (auto& pair : mCirculatingBuffers.at(id)) {
1879 sHandleImporter.freeBuffer(pair.second);
1880 }
1881 mCirculatingBuffers[id].clear();
1882 mCirculatingBuffers.erase(id);
1883}
1884
1885void ExternalCameraDeviceSession::updateBufferCaches(const hidl_vec<BufferCache>& cachesToRemove) {
1886 Mutex::Autolock _l(mLock);
1887 for (auto& cache : cachesToRemove) {
1888 auto cbsIt = mCirculatingBuffers.find(cache.streamId);
1889 if (cbsIt == mCirculatingBuffers.end()) {
1890 // The stream could have been removed
1891 continue;
1892 }
1893 CirculatingBuffers& cbs = cbsIt->second;
1894 auto it = cbs.find(cache.bufferId);
1895 if (it != cbs.end()) {
1896 sHandleImporter.freeBuffer(it->second);
1897 cbs.erase(it);
1898 } else {
1899 ALOGE("%s: stream %d buffer %" PRIu64 " is not cached",
1900 __FUNCTION__, cache.streamId, cache.bufferId);
1901 }
1902 }
1903}
1904
1905bool ExternalCameraDeviceSession::isSupported(const Stream& stream) {
1906 int32_t ds = static_cast<int32_t>(stream.dataSpace);
1907 PixelFormat fmt = stream.format;
1908 uint32_t width = stream.width;
1909 uint32_t height = stream.height;
1910 // TODO: check usage flags
1911
1912 if (stream.streamType != StreamType::OUTPUT) {
1913 ALOGE("%s: does not support non-output stream type", __FUNCTION__);
1914 return false;
1915 }
1916
1917 if (stream.rotation != StreamRotation::ROTATION_0) {
1918 ALOGE("%s: does not support stream rotation", __FUNCTION__);
1919 return false;
1920 }
1921
1922 if (ds & Dataspace::DEPTH) {
1923 ALOGI("%s: does not support depth output", __FUNCTION__);
1924 return false;
1925 }
1926
1927 switch (fmt) {
1928 case PixelFormat::BLOB:
1929 if (ds != static_cast<int32_t>(Dataspace::V0_JFIF)) {
1930 ALOGI("%s: BLOB format does not support dataSpace %x", __FUNCTION__, ds);
1931 return false;
1932 }
1933 case PixelFormat::IMPLEMENTATION_DEFINED:
1934 case PixelFormat::YCBCR_420_888:
1935 case PixelFormat::YV12:
1936 // TODO: check what dataspace we can support here.
1937 // intentional no-ops.
1938 break;
1939 default:
1940 ALOGI("%s: does not support format %x", __FUNCTION__, fmt);
1941 return false;
1942 }
1943
1944 // Assume we can convert any V4L2 format to any of supported output format for now, i.e,
1945 // ignoring v4l2Fmt.fourcc for now. Might need more subtle check if we support more v4l format
1946 // in the futrue.
1947 for (const auto& v4l2Fmt : mSupportedFormats) {
1948 if (width == v4l2Fmt.width && height == v4l2Fmt.height) {
1949 return true;
1950 }
1951 }
1952 ALOGI("%s: resolution %dx%d is not supported", __FUNCTION__, width, height);
1953 return false;
1954}
1955
1956int ExternalCameraDeviceSession::v4l2StreamOffLocked() {
1957 if (!mV4l2Streaming) {
1958 return OK;
1959 }
1960
1961 {
1962 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1963 if (mNumDequeuedV4l2Buffers != 0) {
1964 ALOGE("%s: there are %zu inflight V4L buffers",
1965 __FUNCTION__, mNumDequeuedV4l2Buffers);
1966 return -1;
1967 }
1968 }
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08001969 mV4L2BufferCount = 0;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001970
1971 // VIDIOC_STREAMOFF
1972 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1973 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMOFF, &capture_type)) < 0) {
1974 ALOGE("%s: STREAMOFF failed: %s", __FUNCTION__, strerror(errno));
1975 return -errno;
1976 }
1977
1978 // VIDIOC_REQBUFS: clear buffers
1979 v4l2_requestbuffers req_buffers{};
1980 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1981 req_buffers.memory = V4L2_MEMORY_MMAP;
1982 req_buffers.count = 0;
1983 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
1984 ALOGE("%s: REQBUFS failed: %s", __FUNCTION__, strerror(errno));
1985 return -errno;
1986 }
1987
1988 mV4l2Streaming = false;
1989 return OK;
1990}
1991
1992int ExternalCameraDeviceSession::configureV4l2StreamLocked(const SupportedV4L2Format& v4l2Fmt) {
1993 int ret = v4l2StreamOffLocked();
1994 if (ret != OK) {
1995 ALOGE("%s: stop v4l2 streaming failed: ret %d", __FUNCTION__, ret);
1996 return ret;
1997 }
1998
1999 // VIDIOC_S_FMT w/h/fmt
2000 v4l2_format fmt;
2001 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2002 fmt.fmt.pix.width = v4l2Fmt.width;
2003 fmt.fmt.pix.height = v4l2Fmt.height;
2004 fmt.fmt.pix.pixelformat = v4l2Fmt.fourcc;
2005 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt));
2006 if (ret < 0) {
2007 ALOGE("%s: S_FMT ioctl failed: %s", __FUNCTION__, strerror(errno));
2008 return -errno;
2009 }
2010
2011 if (v4l2Fmt.width != fmt.fmt.pix.width || v4l2Fmt.height != fmt.fmt.pix.height ||
2012 v4l2Fmt.fourcc != fmt.fmt.pix.pixelformat) {
2013 ALOGE("%s: S_FMT expect %c%c%c%c %dx%d, got %c%c%c%c %dx%d instead!", __FUNCTION__,
2014 v4l2Fmt.fourcc & 0xFF,
2015 (v4l2Fmt.fourcc >> 8) & 0xFF,
2016 (v4l2Fmt.fourcc >> 16) & 0xFF,
2017 (v4l2Fmt.fourcc >> 24) & 0xFF,
2018 v4l2Fmt.width, v4l2Fmt.height,
2019 fmt.fmt.pix.pixelformat & 0xFF,
2020 (fmt.fmt.pix.pixelformat >> 8) & 0xFF,
2021 (fmt.fmt.pix.pixelformat >> 16) & 0xFF,
2022 (fmt.fmt.pix.pixelformat >> 24) & 0xFF,
2023 fmt.fmt.pix.width, fmt.fmt.pix.height);
2024 return -EINVAL;
2025 }
2026 uint32_t bufferSize = fmt.fmt.pix.sizeimage;
2027 ALOGI("%s: V4L2 buffer size is %d", __FUNCTION__, bufferSize);
2028
2029 float maxFps = -1.f;
2030 float fps = 1000.f;
2031 const float kDefaultFps = 30.f;
2032 // Try to pick the slowest fps that is at least 30
Yin-Chia Yeh134093a2018-02-12 14:05:48 -08002033 for (const auto& fr : v4l2Fmt.frameRates) {
2034 double f = fr.getDouble();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002035 if (maxFps < f) {
2036 maxFps = f;
2037 }
2038 if (f >= kDefaultFps && f < fps) {
2039 fps = f;
2040 }
2041 }
2042 if (fps == 1000.f) {
2043 fps = maxFps;
2044 }
2045
2046 // VIDIOC_G_PARM/VIDIOC_S_PARM: set fps
2047 v4l2_streamparm streamparm = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
2048 // The following line checks that the driver knows about framerate get/set.
2049 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_G_PARM, &streamparm)) >= 0) {
2050 // Now check if the device is able to accept a capture framerate set.
2051 if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
2052 // |frame_rate| is float, approximate by a fraction.
2053 const int kFrameRatePrecision = 10000;
2054 streamparm.parm.capture.timeperframe.numerator = kFrameRatePrecision;
2055 streamparm.parm.capture.timeperframe.denominator =
2056 (fps * kFrameRatePrecision);
2057
2058 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_PARM, &streamparm)) < 0) {
2059 ALOGE("%s: failed to set framerate to %f", __FUNCTION__, fps);
2060 return UNKNOWN_ERROR;
2061 }
2062 }
2063 }
2064 float retFps = streamparm.parm.capture.timeperframe.denominator /
2065 streamparm.parm.capture.timeperframe.numerator;
2066 if (std::fabs(fps - retFps) > std::numeric_limits<float>::epsilon()) {
2067 ALOGE("%s: expect fps %f, got %f instead", __FUNCTION__, fps, retFps);
2068 return BAD_VALUE;
2069 }
2070
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -08002071 uint32_t v4lBufferCount = (fps >= kDefaultFps) ?
2072 mCfg.numVideoBuffers : mCfg.numStillBuffers;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002073 // VIDIOC_REQBUFS: create buffers
2074 v4l2_requestbuffers req_buffers{};
2075 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2076 req_buffers.memory = V4L2_MEMORY_MMAP;
2077 req_buffers.count = v4lBufferCount;
2078 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
2079 ALOGE("%s: VIDIOC_REQBUFS failed: %s", __FUNCTION__, strerror(errno));
2080 return -errno;
2081 }
2082
2083 // Driver can indeed return more buffer if it needs more to operate
2084 if (req_buffers.count < v4lBufferCount) {
2085 ALOGE("%s: VIDIOC_REQBUFS expected %d buffers, got %d instead",
2086 __FUNCTION__, v4lBufferCount, req_buffers.count);
2087 return NO_MEMORY;
2088 }
2089
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002090 // VIDIOC_QUERYBUF: get buffer offset in the V4L2 fd
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002091 // VIDIOC_QBUF: send buffer to driver
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002092 mV4L2BufferCount = req_buffers.count;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002093 for (uint32_t i = 0; i < req_buffers.count; i++) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002094 v4l2_buffer buffer = {
2095 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
2096 .index = i,
2097 .memory = V4L2_MEMORY_MMAP};
2098
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002099 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QUERYBUF, &buffer)) < 0) {
2100 ALOGE("%s: QUERYBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
2101 return -errno;
2102 }
2103
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002104 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2105 ALOGE("%s: QBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
2106 return -errno;
2107 }
2108 }
2109
2110 // VIDIOC_STREAMON: start streaming
2111 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2112 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type)) < 0) {
2113 ALOGE("%s: VIDIOC_STREAMON failed: %s", __FUNCTION__, strerror(errno));
2114 return -errno;
2115 }
2116
2117 // Swallow first few frames after streamOn to account for bad frames from some devices
2118 for (int i = 0; i < kBadFramesAfterStreamOn; i++) {
2119 v4l2_buffer buffer{};
2120 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2121 buffer.memory = V4L2_MEMORY_MMAP;
2122 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
2123 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
2124 return -errno;
2125 }
2126
2127 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2128 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, buffer.index, strerror(errno));
2129 return -errno;
2130 }
2131 }
2132
2133 mV4l2StreamingFmt = v4l2Fmt;
2134 mV4l2Streaming = true;
2135 return OK;
2136}
2137
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002138sp<V4L2Frame> ExternalCameraDeviceSession::dequeueV4l2FrameLocked(/*out*/nsecs_t* shutterTs) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002139 sp<V4L2Frame> ret = nullptr;
2140
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002141 if (shutterTs == nullptr) {
2142 ALOGE("%s: shutterTs must not be null!", __FUNCTION__);
2143 return ret;
2144 }
2145
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002146 {
2147 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002148 if (mNumDequeuedV4l2Buffers == mV4L2BufferCount) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002149 std::chrono::seconds timeout = std::chrono::seconds(kBufferWaitTimeoutSec);
2150 mLock.unlock();
2151 auto st = mV4L2BufferReturned.wait_for(lk, timeout);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002152 // Here we introduce a case where mV4l2BufferLock is acquired before mLock, while
2153 // the normal lock acquisition order is reversed, but this is fine because in most of
2154 // cases we are protected by mInterfaceLock. The only thread that can compete these
2155 // locks are the OutputThread, where we do need to make sure we don't acquire mLock then
2156 // mV4l2BufferLock
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002157 mLock.lock();
2158 if (st == std::cv_status::timeout) {
2159 ALOGE("%s: wait for V4L2 buffer return timeout!", __FUNCTION__);
2160 return ret;
2161 }
2162 }
2163 }
2164
2165 v4l2_buffer buffer{};
2166 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2167 buffer.memory = V4L2_MEMORY_MMAP;
2168 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
2169 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
2170 return ret;
2171 }
2172
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002173 if (buffer.index >= mV4L2BufferCount) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002174 ALOGE("%s: Invalid buffer id: %d", __FUNCTION__, buffer.index);
2175 return ret;
2176 }
2177
2178 if (buffer.flags & V4L2_BUF_FLAG_ERROR) {
2179 ALOGE("%s: v4l2 buf error! buf flag 0x%x", __FUNCTION__, buffer.flags);
2180 // TODO: try to dequeue again
2181 }
2182
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002183 if (buffer.flags & V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC) {
2184 // Ideally we should also check for V4L2_BUF_FLAG_TSTAMP_SRC_SOE, but
2185 // even V4L2_BUF_FLAG_TSTAMP_SRC_EOF is better than capture a timestamp now
2186 *shutterTs = static_cast<nsecs_t>(buffer.timestamp.tv_sec)*1000000000LL +
2187 buffer.timestamp.tv_usec * 1000LL;
2188 } else {
2189 *shutterTs = systemTime(SYSTEM_TIME_MONOTONIC);
2190 }
2191
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002192 {
2193 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2194 mNumDequeuedV4l2Buffers++;
2195 }
2196 return new V4L2Frame(
2197 mV4l2StreamingFmt.width, mV4l2StreamingFmt.height, mV4l2StreamingFmt.fourcc,
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002198 buffer.index, mV4l2Fd.get(), buffer.bytesused, buffer.m.offset);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002199}
2200
2201void ExternalCameraDeviceSession::enqueueV4l2Frame(const sp<V4L2Frame>& frame) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002202 {
2203 // Release mLock before acquiring mV4l2BufferLock to avoid potential
2204 // deadlock
2205 Mutex::Autolock _l(mLock);
2206 frame->unmap();
2207 v4l2_buffer buffer{};
2208 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2209 buffer.memory = V4L2_MEMORY_MMAP;
2210 buffer.index = frame->mBufferIndex;
2211 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2212 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__,
2213 frame->mBufferIndex, strerror(errno));
2214 return;
2215 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002216 }
2217
2218 {
2219 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2220 mNumDequeuedV4l2Buffers--;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002221 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002222 mV4L2BufferReturned.notify_one();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002223}
2224
2225Status ExternalCameraDeviceSession::configureStreams(
2226 const V3_2::StreamConfiguration& config, V3_3::HalStreamConfiguration* out) {
2227 if (config.operationMode != StreamConfigurationMode::NORMAL_MODE) {
2228 ALOGE("%s: unsupported operation mode: %d", __FUNCTION__, config.operationMode);
2229 return Status::ILLEGAL_ARGUMENT;
2230 }
2231
2232 if (config.streams.size() == 0) {
2233 ALOGE("%s: cannot configure zero stream", __FUNCTION__);
2234 return Status::ILLEGAL_ARGUMENT;
2235 }
2236
2237 int numProcessedStream = 0;
2238 int numStallStream = 0;
2239 for (const auto& stream : config.streams) {
2240 // Check if the format/width/height combo is supported
2241 if (!isSupported(stream)) {
2242 return Status::ILLEGAL_ARGUMENT;
2243 }
2244 if (stream.format == PixelFormat::BLOB) {
2245 numStallStream++;
2246 } else {
2247 numProcessedStream++;
2248 }
2249 }
2250
2251 if (numProcessedStream > kMaxProcessedStream) {
2252 ALOGE("%s: too many processed streams (expect <= %d, got %d)", __FUNCTION__,
2253 kMaxProcessedStream, numProcessedStream);
2254 return Status::ILLEGAL_ARGUMENT;
2255 }
2256
2257 if (numStallStream > kMaxStallStream) {
2258 ALOGE("%s: too many stall streams (expect <= %d, got %d)", __FUNCTION__,
2259 kMaxStallStream, numStallStream);
2260 return Status::ILLEGAL_ARGUMENT;
2261 }
2262
2263 Status status = initStatus();
2264 if (status != Status::OK) {
2265 return status;
2266 }
2267
2268 Mutex::Autolock _l(mLock);
2269 if (!mInflightFrames.empty()) {
2270 ALOGE("%s: trying to configureStreams while there are still %zu inflight frames!",
2271 __FUNCTION__, mInflightFrames.size());
2272 return Status::INTERNAL_ERROR;
2273 }
2274
2275 // Add new streams
2276 for (const auto& stream : config.streams) {
2277 if (mStreamMap.count(stream.id) == 0) {
2278 mStreamMap[stream.id] = stream;
2279 mCirculatingBuffers.emplace(stream.id, CirculatingBuffers{});
2280 }
2281 }
2282
2283 // Cleanup removed streams
2284 for(auto it = mStreamMap.begin(); it != mStreamMap.end();) {
2285 int id = it->first;
2286 bool found = false;
2287 for (const auto& stream : config.streams) {
2288 if (id == stream.id) {
2289 found = true;
2290 break;
2291 }
2292 }
2293 if (!found) {
2294 // Unmap all buffers of deleted stream
2295 cleanupBuffersLocked(id);
2296 it = mStreamMap.erase(it);
2297 } else {
2298 ++it;
2299 }
2300 }
2301
2302 // Now select a V4L2 format to produce all output streams
2303 float desiredAr = (mCroppingType == VERTICAL) ? kMaxAspectRatio : kMinAspectRatio;
2304 uint32_t maxDim = 0;
2305 for (const auto& stream : config.streams) {
2306 float aspectRatio = ASPECT_RATIO(stream);
2307 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2308 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2309 desiredAr = aspectRatio;
2310 }
2311
2312 // The dimension that's not cropped
2313 uint32_t dim = (mCroppingType == VERTICAL) ? stream.width : stream.height;
2314 if (dim > maxDim) {
2315 maxDim = dim;
2316 }
2317 }
2318 // Find the smallest format that matches the desired aspect ratio and is wide/high enough
2319 SupportedV4L2Format v4l2Fmt {.width = 0, .height = 0};
2320 for (const auto& fmt : mSupportedFormats) {
2321 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2322 if (dim >= maxDim) {
2323 float aspectRatio = ASPECT_RATIO(fmt);
2324 if (isAspectRatioClose(aspectRatio, desiredAr)) {
2325 v4l2Fmt = fmt;
2326 // since mSupportedFormats is sorted by width then height, the first matching fmt
2327 // will be the smallest one with matching aspect ratio
2328 break;
2329 }
2330 }
2331 }
2332 if (v4l2Fmt.width == 0) {
2333 // Cannot find exact good aspect ratio candidate, try to find a close one
2334 for (const auto& fmt : mSupportedFormats) {
2335 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2336 if (dim >= maxDim) {
2337 float aspectRatio = ASPECT_RATIO(fmt);
2338 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2339 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2340 v4l2Fmt = fmt;
2341 break;
2342 }
2343 }
2344 }
2345 }
2346
2347 if (v4l2Fmt.width == 0) {
2348 ALOGE("%s: unable to find a resolution matching (%s at least %d, aspect ratio %f)"
2349 , __FUNCTION__, (mCroppingType == VERTICAL) ? "width" : "height",
2350 maxDim, desiredAr);
2351 return Status::ILLEGAL_ARGUMENT;
2352 }
2353
2354 if (configureV4l2StreamLocked(v4l2Fmt) != 0) {
2355 ALOGE("V4L configuration failed!, format:%c%c%c%c, w %d, h %d",
2356 v4l2Fmt.fourcc & 0xFF,
2357 (v4l2Fmt.fourcc >> 8) & 0xFF,
2358 (v4l2Fmt.fourcc >> 16) & 0xFF,
2359 (v4l2Fmt.fourcc >> 24) & 0xFF,
2360 v4l2Fmt.width, v4l2Fmt.height);
2361 return Status::INTERNAL_ERROR;
2362 }
2363
2364 Size v4lSize = {v4l2Fmt.width, v4l2Fmt.height};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08002365 Size thumbSize { 0, 0 };
2366 camera_metadata_ro_entry entry =
2367 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
2368 for(uint32_t i = 0; i < entry.count; i += 2) {
2369 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
2370 static_cast<uint32_t>(entry.data.i32[i+1]) };
2371 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
2372 thumbSize = sz;
2373 }
2374 }
2375
2376 if (thumbSize.width * thumbSize.height == 0) {
2377 ALOGE("%s: non-zero thumbnail size not available", __FUNCTION__);
2378 return Status::INTERNAL_ERROR;
2379 }
2380
2381 status = mOutputThread->allocateIntermediateBuffers(v4lSize,
2382 mMaxThumbResolution, config.streams);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002383 if (status != Status::OK) {
2384 ALOGE("%s: allocating intermediate buffers failed!", __FUNCTION__);
2385 return status;
2386 }
2387
2388 out->streams.resize(config.streams.size());
2389 for (size_t i = 0; i < config.streams.size(); i++) {
2390 out->streams[i].overrideDataSpace = config.streams[i].dataSpace;
2391 out->streams[i].v3_2.id = config.streams[i].id;
2392 // TODO: double check should we add those CAMERA flags
2393 mStreamMap[config.streams[i].id].usage =
2394 out->streams[i].v3_2.producerUsage = config.streams[i].usage |
2395 BufferUsage::CPU_WRITE_OFTEN |
2396 BufferUsage::CAMERA_OUTPUT;
2397 out->streams[i].v3_2.consumerUsage = 0;
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002398 out->streams[i].v3_2.maxBuffers = mV4L2BufferCount;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002399
2400 switch (config.streams[i].format) {
2401 case PixelFormat::BLOB:
2402 case PixelFormat::YCBCR_420_888:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002403 case PixelFormat::YV12: // Used by SurfaceTexture
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002404 // No override
2405 out->streams[i].v3_2.overrideFormat = config.streams[i].format;
2406 break;
2407 case PixelFormat::IMPLEMENTATION_DEFINED:
2408 // Override based on VIDEO or not
2409 out->streams[i].v3_2.overrideFormat =
2410 (config.streams[i].usage & BufferUsage::VIDEO_ENCODER) ?
2411 PixelFormat::YCBCR_420_888 : PixelFormat::YV12;
2412 // Save overridden formt in mStreamMap
2413 mStreamMap[config.streams[i].id].format = out->streams[i].v3_2.overrideFormat;
2414 break;
2415 default:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002416 ALOGE("%s: unsupported format 0x%x", __FUNCTION__, config.streams[i].format);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002417 return Status::ILLEGAL_ARGUMENT;
2418 }
2419 }
2420
2421 mFirstRequest = true;
2422 return Status::OK;
2423}
2424
2425bool ExternalCameraDeviceSession::isClosed() {
2426 Mutex::Autolock _l(mLock);
2427 return mClosed;
2428}
2429
2430#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
2431#define UPDATE(md, tag, data, size) \
2432do { \
2433 if ((md).update((tag), (data), (size))) { \
2434 ALOGE("Update " #tag " failed!"); \
2435 return BAD_VALUE; \
2436 } \
2437} while (0)
2438
2439status_t ExternalCameraDeviceSession::initDefaultRequests() {
2440 ::android::hardware::camera::common::V1_0::helper::CameraMetadata md;
2441
2442 const uint8_t aberrationMode = ANDROID_COLOR_CORRECTION_ABERRATION_MODE_OFF;
2443 UPDATE(md, ANDROID_COLOR_CORRECTION_ABERRATION_MODE, &aberrationMode, 1);
2444
2445 const int32_t exposureCompensation = 0;
2446 UPDATE(md, ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION, &exposureCompensation, 1);
2447
2448 const uint8_t videoStabilizationMode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
2449 UPDATE(md, ANDROID_CONTROL_VIDEO_STABILIZATION_MODE, &videoStabilizationMode, 1);
2450
2451 const uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO;
2452 UPDATE(md, ANDROID_CONTROL_AWB_MODE, &awbMode, 1);
2453
2454 const uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON;
2455 UPDATE(md, ANDROID_CONTROL_AE_MODE, &aeMode, 1);
2456
2457 const uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
2458 UPDATE(md, ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
2459
2460 const uint8_t afMode = ANDROID_CONTROL_AF_MODE_AUTO;
2461 UPDATE(md, ANDROID_CONTROL_AF_MODE, &afMode, 1);
2462
2463 const uint8_t afTrigger = ANDROID_CONTROL_AF_TRIGGER_IDLE;
2464 UPDATE(md, ANDROID_CONTROL_AF_TRIGGER, &afTrigger, 1);
2465
2466 const uint8_t sceneMode = ANDROID_CONTROL_SCENE_MODE_DISABLED;
2467 UPDATE(md, ANDROID_CONTROL_SCENE_MODE, &sceneMode, 1);
2468
2469 const uint8_t effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF;
2470 UPDATE(md, ANDROID_CONTROL_EFFECT_MODE, &effectMode, 1);
2471
2472 const uint8_t flashMode = ANDROID_FLASH_MODE_OFF;
2473 UPDATE(md, ANDROID_FLASH_MODE, &flashMode, 1);
2474
2475 const int32_t thumbnailSize[] = {240, 180};
2476 UPDATE(md, ANDROID_JPEG_THUMBNAIL_SIZE, thumbnailSize, 2);
2477
2478 const uint8_t jpegQuality = 90;
2479 UPDATE(md, ANDROID_JPEG_QUALITY, &jpegQuality, 1);
2480 UPDATE(md, ANDROID_JPEG_THUMBNAIL_QUALITY, &jpegQuality, 1);
2481
2482 const int32_t jpegOrientation = 0;
2483 UPDATE(md, ANDROID_JPEG_ORIENTATION, &jpegOrientation, 1);
2484
2485 const uint8_t oisMode = ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF;
2486 UPDATE(md, ANDROID_LENS_OPTICAL_STABILIZATION_MODE, &oisMode, 1);
2487
2488 const uint8_t nrMode = ANDROID_NOISE_REDUCTION_MODE_OFF;
2489 UPDATE(md, ANDROID_NOISE_REDUCTION_MODE, &nrMode, 1);
2490
2491 const uint8_t fdMode = ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
2492 UPDATE(md, ANDROID_STATISTICS_FACE_DETECT_MODE, &fdMode, 1);
2493
2494 const uint8_t hotpixelMode = ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF;
2495 UPDATE(md, ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE, &hotpixelMode, 1);
2496
2497 bool support30Fps = false;
2498 int32_t maxFps = std::numeric_limits<int32_t>::min();
2499 for (const auto& supportedFormat : mSupportedFormats) {
Yin-Chia Yeh134093a2018-02-12 14:05:48 -08002500 for (const auto& fr : supportedFormat.frameRates) {
2501 int32_t framerateInt = static_cast<int32_t>(fr.getDouble());
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002502 if (maxFps < framerateInt) {
2503 maxFps = framerateInt;
2504 }
2505 if (framerateInt == 30) {
2506 support30Fps = true;
2507 break;
2508 }
2509 }
2510 if (support30Fps) {
2511 break;
2512 }
2513 }
2514 int32_t defaultFramerate = support30Fps ? 30 : maxFps;
2515 int32_t defaultFpsRange[] = {defaultFramerate, defaultFramerate};
2516 UPDATE(md, ANDROID_CONTROL_AE_TARGET_FPS_RANGE, defaultFpsRange, ARRAY_SIZE(defaultFpsRange));
2517
2518 uint8_t antibandingMode = ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO;
2519 UPDATE(md, ANDROID_CONTROL_AE_ANTIBANDING_MODE, &antibandingMode, 1);
2520
2521 const uint8_t controlMode = ANDROID_CONTROL_MODE_AUTO;
2522 UPDATE(md, ANDROID_CONTROL_MODE, &controlMode, 1);
2523
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002524 auto requestTemplates = hidl_enum_iterator<RequestTemplate>();
2525 for (RequestTemplate type : requestTemplates) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002526 ::android::hardware::camera::common::V1_0::helper::CameraMetadata mdCopy = md;
2527 uint8_t intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2528 switch (type) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002529 case RequestTemplate::PREVIEW:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002530 intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2531 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002532 case RequestTemplate::STILL_CAPTURE:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002533 intent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE;
2534 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002535 case RequestTemplate::VIDEO_RECORD:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002536 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD;
2537 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002538 case RequestTemplate::VIDEO_SNAPSHOT:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002539 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT;
2540 break;
2541 default:
Yuriy Romanenko083de0c2018-01-26 16:05:54 -08002542 ALOGV("%s: unsupported RequestTemplate type %d", __FUNCTION__, type);
2543 continue;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002544 }
2545 UPDATE(mdCopy, ANDROID_CONTROL_CAPTURE_INTENT, &intent, 1);
2546
2547 camera_metadata_t* rawMd = mdCopy.release();
2548 CameraMetadata hidlMd;
2549 hidlMd.setToExternal(
2550 (uint8_t*) rawMd, get_camera_metadata_size(rawMd));
2551 mDefaultRequests[type] = hidlMd;
2552 free_camera_metadata(rawMd);
2553 }
2554
2555 return OK;
2556}
2557
2558status_t ExternalCameraDeviceSession::fillCaptureResult(
2559 common::V1_0::helper::CameraMetadata &md, nsecs_t timestamp) {
2560 // android.control
2561 // For USB camera, we don't know the AE state. Set the state to converged to
2562 // indicate the frame should be good to use. Then apps don't have to wait the
2563 // AE state.
2564 const uint8_t aeState = ANDROID_CONTROL_AE_STATE_CONVERGED;
2565 UPDATE(md, ANDROID_CONTROL_AE_STATE, &aeState, 1);
2566
2567 const uint8_t ae_lock = ANDROID_CONTROL_AE_LOCK_OFF;
2568 UPDATE(md, ANDROID_CONTROL_AE_LOCK, &ae_lock, 1);
2569
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002570 bool afTrigger = mAfTrigger;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002571 if (md.exists(ANDROID_CONTROL_AF_TRIGGER)) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002572 Mutex::Autolock _l(mLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002573 camera_metadata_entry entry = md.find(ANDROID_CONTROL_AF_TRIGGER);
2574 if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_START) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002575 mAfTrigger = afTrigger = true;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002576 } else if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_CANCEL) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002577 mAfTrigger = afTrigger = false;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002578 }
2579 }
2580
2581 // For USB camera, the USB camera handles everything and we don't have control
2582 // over AF. We only simply fake the AF metadata based on the request
2583 // received here.
2584 uint8_t afState;
2585 if (afTrigger) {
2586 afState = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
2587 } else {
2588 afState = ANDROID_CONTROL_AF_STATE_INACTIVE;
2589 }
2590 UPDATE(md, ANDROID_CONTROL_AF_STATE, &afState, 1);
2591
2592 // Set AWB state to converged to indicate the frame should be good to use.
2593 const uint8_t awbState = ANDROID_CONTROL_AWB_STATE_CONVERGED;
2594 UPDATE(md, ANDROID_CONTROL_AWB_STATE, &awbState, 1);
2595
2596 const uint8_t awbLock = ANDROID_CONTROL_AWB_LOCK_OFF;
2597 UPDATE(md, ANDROID_CONTROL_AWB_LOCK, &awbLock, 1);
2598
2599 camera_metadata_ro_entry active_array_size =
2600 mCameraCharacteristics.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
2601
2602 if (active_array_size.count == 0) {
2603 ALOGE("%s: cannot find active array size!", __FUNCTION__);
2604 return -EINVAL;
2605 }
2606
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002607 const uint8_t flashState = ANDROID_FLASH_STATE_UNAVAILABLE;
2608 UPDATE(md, ANDROID_FLASH_STATE, &flashState, 1);
2609
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002610 // android.scaler
2611 const int32_t crop_region[] = {
2612 active_array_size.data.i32[0], active_array_size.data.i32[1],
2613 active_array_size.data.i32[2], active_array_size.data.i32[3],
2614 };
2615 UPDATE(md, ANDROID_SCALER_CROP_REGION, crop_region, ARRAY_SIZE(crop_region));
2616
2617 // android.sensor
2618 UPDATE(md, ANDROID_SENSOR_TIMESTAMP, &timestamp, 1);
2619
2620 // android.statistics
2621 const uint8_t lensShadingMapMode = ANDROID_STATISTICS_LENS_SHADING_MAP_MODE_OFF;
2622 UPDATE(md, ANDROID_STATISTICS_LENS_SHADING_MAP_MODE, &lensShadingMapMode, 1);
2623
2624 const uint8_t sceneFlicker = ANDROID_STATISTICS_SCENE_FLICKER_NONE;
2625 UPDATE(md, ANDROID_STATISTICS_SCENE_FLICKER, &sceneFlicker, 1);
2626
2627 return OK;
2628}
2629
2630#undef ARRAY_SIZE
2631#undef UPDATE
2632
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002633} // namespace implementation
2634} // namespace V3_4
2635} // namespace device
2636} // namespace camera
2637} // namespace hardware
2638} // namespace android