blob: 439143945a3d8da7194c7aa34068801183f63aca [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
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800540 std::shared_ptr<HalRequest> halReq = std::make_shared<HalRequest>();
541 halReq->frameNumber = request.frameNumber;
542 halReq->setting = mLatestReqSetting;
543 halReq->frameIn = frameIn;
544 halReq->shutterTs = shutterTs;
545 halReq->buffers.resize(numOutputBufs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700546 for (size_t i = 0; i < numOutputBufs; i++) {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800547 HalStreamBuffer& halBuf = halReq->buffers[i];
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700548 int streamId = halBuf.streamId = request.outputBuffers[i].streamId;
549 halBuf.bufferId = request.outputBuffers[i].bufferId;
550 const Stream& stream = mStreamMap[streamId];
551 halBuf.width = stream.width;
552 halBuf.height = stream.height;
553 halBuf.format = stream.format;
554 halBuf.usage = stream.usage;
555 halBuf.bufPtr = allBufPtrs[i];
556 halBuf.acquireFence = allFences[i];
557 halBuf.fenceTimeout = false;
558 }
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800559 mInflightFrames.insert(halReq->frameNumber);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700560 // Send request to OutputThread for the rest of processing
561 mOutputThread->submitRequest(halReq);
562 mFirstRequest = false;
563 return Status::OK;
564}
565
566void ExternalCameraDeviceSession::notifyShutter(uint32_t frameNumber, nsecs_t shutterTs) {
567 NotifyMsg msg;
568 msg.type = MsgType::SHUTTER;
569 msg.msg.shutter.frameNumber = frameNumber;
570 msg.msg.shutter.timestamp = shutterTs;
571 mCallback->notify({msg});
572}
573
574void ExternalCameraDeviceSession::notifyError(
575 uint32_t frameNumber, int32_t streamId, ErrorCode ec) {
576 NotifyMsg msg;
577 msg.type = MsgType::ERROR;
578 msg.msg.error.frameNumber = frameNumber;
579 msg.msg.error.errorStreamId = streamId;
580 msg.msg.error.errorCode = ec;
581 mCallback->notify({msg});
582}
583
584//TODO: refactor with processCaptureResult
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800585Status ExternalCameraDeviceSession::processCaptureRequestError(
586 const std::shared_ptr<HalRequest>& req) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700587 // Return V4L2 buffer to V4L2 buffer queue
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800588 enqueueV4l2Frame(req->frameIn);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700589
590 // NotifyShutter
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800591 notifyShutter(req->frameNumber, req->shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700592
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800593 notifyError(/*frameNum*/req->frameNumber, /*stream*/-1, ErrorCode::ERROR_REQUEST);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700594
595 // Fill output buffers
596 hidl_vec<CaptureResult> results;
597 results.resize(1);
598 CaptureResult& result = results[0];
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800599 result.frameNumber = req->frameNumber;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700600 result.partialResult = 1;
601 result.inputBuffer.streamId = -1;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800602 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;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700606 result.outputBuffers[i].status = BufferStatus::ERROR;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800607 if (req->buffers[i].acquireFence >= 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700608 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800609 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);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800617 mInflightFrames.erase(req->frameNumber);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700618 }
619
620 // Callback into framework
621 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
622 freeReleaseFences(results);
623 return Status::OK;
624}
625
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800626Status ExternalCameraDeviceSession::processCaptureResult(std::shared_ptr<HalRequest>& req) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700627 // Return V4L2 buffer to V4L2 buffer queue
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800628 enqueueV4l2Frame(req->frameIn);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700629
630 // NotifyShutter
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800631 notifyShutter(req->frameNumber, req->shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700632
633 // Fill output buffers
634 hidl_vec<CaptureResult> results;
635 results.resize(1);
636 CaptureResult& result = results[0];
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800637 result.frameNumber = req->frameNumber;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700638 result.partialResult = 1;
639 result.inputBuffer.streamId = -1;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800640 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) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700645 result.outputBuffers[i].status = BufferStatus::ERROR;
646 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800647 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 Yehe086fb72018-02-16 14:54:04 -0800649 notifyError(req->frameNumber, req->buffers[i].streamId, ErrorCode::ERROR_BUFFER);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700650 } else {
651 result.outputBuffers[i].status = BufferStatus::OK;
652 // TODO: refactor
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800653 if (req->buffers[i].acquireFence > 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700654 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800655 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
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800662 fillCaptureResult(req->setting, req->shutterTs);
663 const camera_metadata_t *rawResult = req->setting.getAndLock();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700664 V3_2::implementation::convertToHidl(rawResult, &result.result);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800665 req->setting.unlock(rawResult);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700666
667 // update inflight records
668 {
669 Mutex::Autolock _l(mLock);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800670 mInflightFrames.erase(req->frameNumber);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700671 }
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,
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001401 const std::shared_ptr<HalRequest>& req)
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001402{
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
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001428 if (req->setting.exists(ANDROID_JPEG_QUALITY)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001429 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001430 req->setting.find(ANDROID_JPEG_QUALITY);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001431 jpegQuality = entry.data.u8[0];
1432 } else {
1433 return lfail("%s: ANDROID_JPEG_QUALITY not set",__FUNCTION__);
1434 }
1435
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001436 if (req->setting.exists(ANDROID_JPEG_THUMBNAIL_QUALITY)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001437 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001438 req->setting.find(ANDROID_JPEG_THUMBNAIL_QUALITY);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001439 thumbQuality = entry.data.u8[0];
1440 } else {
1441 return lfail(
1442 "%s: ANDROID_JPEG_THUMBNAIL_QUALITY not set",
1443 __FUNCTION__);
1444 }
1445
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001446 if (req->setting.exists(ANDROID_JPEG_THUMBNAIL_SIZE)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001447 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001448 req->setting.find(ANDROID_JPEG_THUMBNAIL_SIZE);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001449 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);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001508 meta.append(req->setting);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001509
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() {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001572 std::shared_ptr<HalRequest> req;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001573 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);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001583 if (req == nullptr) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001584 // 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(
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001591 req->frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001592 signalRequestDone();
1593 return false;
1594 };
1595
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001596 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 Yehe086fb72018-02-16 14:54:04 -08001598 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;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001609 req->frameIn->map(&inData, &inDataSize);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001610 // 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;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001637 for (auto& halBuf : req->buffers) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001638 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
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001794Status ExternalCameraDeviceSession::OutputThread::submitRequest(
1795 const std::shared_ptr<HalRequest>& req) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001796 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001797 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);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001811 std::list<std::shared_ptr<HalRequest>> reqs = std::move(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
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001827void ExternalCameraDeviceSession::OutputThread::waitForNextRequest(
1828 std::shared_ptr<HalRequest>* out) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001829 if (out == nullptr) {
1830 ALOGE("%s: out is null", __FUNCTION__);
1831 return;
1832 }
1833
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001834 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001835 int waitTimes = 0;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001836 while (mRequestList.empty()) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001837 if (exitPending()) {
1838 return;
1839 }
1840 std::chrono::milliseconds timeout = std::chrono::milliseconds(kReqWaitTimeoutMs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001841 auto st = mRequestCond.wait_for(lk, timeout);
1842 if (st == std::cv_status::timeout) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001843 waitTimes++;
1844 if (waitTimes == kReqWaitTimesMax) {
1845 // no new request, return
1846 return;
1847 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001848 }
1849 }
1850 *out = mRequestList.front();
1851 mRequestList.pop_front();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001852 mProcessingRequest = true;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001853 mProcessingFrameNumer = (*out)->frameNumber;
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001854}
1855
1856void ExternalCameraDeviceSession::OutputThread::signalRequestDone() {
1857 std::unique_lock<std::mutex> lk(mRequestListLock);
1858 mProcessingRequest = false;
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001859 mProcessingFrameNumer = 0;
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001860 lk.unlock();
1861 mRequestDoneCond.notify_one();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001862}
1863
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001864void ExternalCameraDeviceSession::OutputThread::dump(int fd) {
1865 std::lock_guard<std::mutex> lk(mRequestListLock);
1866 if (mProcessingRequest) {
1867 dprintf(fd, "OutputThread processing frame %d\n", mProcessingFrameNumer);
1868 } else {
1869 dprintf(fd, "OutputThread not processing any frames\n");
1870 }
1871 dprintf(fd, "OutputThread request list contains frame: ");
1872 for (const auto& req : mRequestList) {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001873 dprintf(fd, "%d, ", req->frameNumber);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001874 }
1875 dprintf(fd, "\n");
1876}
1877
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001878void ExternalCameraDeviceSession::cleanupBuffersLocked(int id) {
1879 for (auto& pair : mCirculatingBuffers.at(id)) {
1880 sHandleImporter.freeBuffer(pair.second);
1881 }
1882 mCirculatingBuffers[id].clear();
1883 mCirculatingBuffers.erase(id);
1884}
1885
1886void ExternalCameraDeviceSession::updateBufferCaches(const hidl_vec<BufferCache>& cachesToRemove) {
1887 Mutex::Autolock _l(mLock);
1888 for (auto& cache : cachesToRemove) {
1889 auto cbsIt = mCirculatingBuffers.find(cache.streamId);
1890 if (cbsIt == mCirculatingBuffers.end()) {
1891 // The stream could have been removed
1892 continue;
1893 }
1894 CirculatingBuffers& cbs = cbsIt->second;
1895 auto it = cbs.find(cache.bufferId);
1896 if (it != cbs.end()) {
1897 sHandleImporter.freeBuffer(it->second);
1898 cbs.erase(it);
1899 } else {
1900 ALOGE("%s: stream %d buffer %" PRIu64 " is not cached",
1901 __FUNCTION__, cache.streamId, cache.bufferId);
1902 }
1903 }
1904}
1905
1906bool ExternalCameraDeviceSession::isSupported(const Stream& stream) {
1907 int32_t ds = static_cast<int32_t>(stream.dataSpace);
1908 PixelFormat fmt = stream.format;
1909 uint32_t width = stream.width;
1910 uint32_t height = stream.height;
1911 // TODO: check usage flags
1912
1913 if (stream.streamType != StreamType::OUTPUT) {
1914 ALOGE("%s: does not support non-output stream type", __FUNCTION__);
1915 return false;
1916 }
1917
1918 if (stream.rotation != StreamRotation::ROTATION_0) {
1919 ALOGE("%s: does not support stream rotation", __FUNCTION__);
1920 return false;
1921 }
1922
1923 if (ds & Dataspace::DEPTH) {
1924 ALOGI("%s: does not support depth output", __FUNCTION__);
1925 return false;
1926 }
1927
1928 switch (fmt) {
1929 case PixelFormat::BLOB:
1930 if (ds != static_cast<int32_t>(Dataspace::V0_JFIF)) {
1931 ALOGI("%s: BLOB format does not support dataSpace %x", __FUNCTION__, ds);
1932 return false;
1933 }
1934 case PixelFormat::IMPLEMENTATION_DEFINED:
1935 case PixelFormat::YCBCR_420_888:
1936 case PixelFormat::YV12:
1937 // TODO: check what dataspace we can support here.
1938 // intentional no-ops.
1939 break;
1940 default:
1941 ALOGI("%s: does not support format %x", __FUNCTION__, fmt);
1942 return false;
1943 }
1944
1945 // Assume we can convert any V4L2 format to any of supported output format for now, i.e,
1946 // ignoring v4l2Fmt.fourcc for now. Might need more subtle check if we support more v4l format
1947 // in the futrue.
1948 for (const auto& v4l2Fmt : mSupportedFormats) {
1949 if (width == v4l2Fmt.width && height == v4l2Fmt.height) {
1950 return true;
1951 }
1952 }
1953 ALOGI("%s: resolution %dx%d is not supported", __FUNCTION__, width, height);
1954 return false;
1955}
1956
1957int ExternalCameraDeviceSession::v4l2StreamOffLocked() {
1958 if (!mV4l2Streaming) {
1959 return OK;
1960 }
1961
1962 {
1963 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1964 if (mNumDequeuedV4l2Buffers != 0) {
1965 ALOGE("%s: there are %zu inflight V4L buffers",
1966 __FUNCTION__, mNumDequeuedV4l2Buffers);
1967 return -1;
1968 }
1969 }
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08001970 mV4L2BufferCount = 0;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001971
1972 // VIDIOC_STREAMOFF
1973 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1974 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMOFF, &capture_type)) < 0) {
1975 ALOGE("%s: STREAMOFF failed: %s", __FUNCTION__, strerror(errno));
1976 return -errno;
1977 }
1978
1979 // VIDIOC_REQBUFS: clear buffers
1980 v4l2_requestbuffers req_buffers{};
1981 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1982 req_buffers.memory = V4L2_MEMORY_MMAP;
1983 req_buffers.count = 0;
1984 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
1985 ALOGE("%s: REQBUFS failed: %s", __FUNCTION__, strerror(errno));
1986 return -errno;
1987 }
1988
1989 mV4l2Streaming = false;
1990 return OK;
1991}
1992
1993int ExternalCameraDeviceSession::configureV4l2StreamLocked(const SupportedV4L2Format& v4l2Fmt) {
1994 int ret = v4l2StreamOffLocked();
1995 if (ret != OK) {
1996 ALOGE("%s: stop v4l2 streaming failed: ret %d", __FUNCTION__, ret);
1997 return ret;
1998 }
1999
2000 // VIDIOC_S_FMT w/h/fmt
2001 v4l2_format fmt;
2002 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2003 fmt.fmt.pix.width = v4l2Fmt.width;
2004 fmt.fmt.pix.height = v4l2Fmt.height;
2005 fmt.fmt.pix.pixelformat = v4l2Fmt.fourcc;
2006 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt));
2007 if (ret < 0) {
2008 ALOGE("%s: S_FMT ioctl failed: %s", __FUNCTION__, strerror(errno));
2009 return -errno;
2010 }
2011
2012 if (v4l2Fmt.width != fmt.fmt.pix.width || v4l2Fmt.height != fmt.fmt.pix.height ||
2013 v4l2Fmt.fourcc != fmt.fmt.pix.pixelformat) {
2014 ALOGE("%s: S_FMT expect %c%c%c%c %dx%d, got %c%c%c%c %dx%d instead!", __FUNCTION__,
2015 v4l2Fmt.fourcc & 0xFF,
2016 (v4l2Fmt.fourcc >> 8) & 0xFF,
2017 (v4l2Fmt.fourcc >> 16) & 0xFF,
2018 (v4l2Fmt.fourcc >> 24) & 0xFF,
2019 v4l2Fmt.width, v4l2Fmt.height,
2020 fmt.fmt.pix.pixelformat & 0xFF,
2021 (fmt.fmt.pix.pixelformat >> 8) & 0xFF,
2022 (fmt.fmt.pix.pixelformat >> 16) & 0xFF,
2023 (fmt.fmt.pix.pixelformat >> 24) & 0xFF,
2024 fmt.fmt.pix.width, fmt.fmt.pix.height);
2025 return -EINVAL;
2026 }
2027 uint32_t bufferSize = fmt.fmt.pix.sizeimage;
2028 ALOGI("%s: V4L2 buffer size is %d", __FUNCTION__, bufferSize);
2029
2030 float maxFps = -1.f;
2031 float fps = 1000.f;
2032 const float kDefaultFps = 30.f;
2033 // Try to pick the slowest fps that is at least 30
Yin-Chia Yeh134093a2018-02-12 14:05:48 -08002034 for (const auto& fr : v4l2Fmt.frameRates) {
2035 double f = fr.getDouble();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002036 if (maxFps < f) {
2037 maxFps = f;
2038 }
2039 if (f >= kDefaultFps && f < fps) {
2040 fps = f;
2041 }
2042 }
2043 if (fps == 1000.f) {
2044 fps = maxFps;
2045 }
2046
2047 // VIDIOC_G_PARM/VIDIOC_S_PARM: set fps
2048 v4l2_streamparm streamparm = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
2049 // The following line checks that the driver knows about framerate get/set.
2050 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_G_PARM, &streamparm)) >= 0) {
2051 // Now check if the device is able to accept a capture framerate set.
2052 if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
2053 // |frame_rate| is float, approximate by a fraction.
2054 const int kFrameRatePrecision = 10000;
2055 streamparm.parm.capture.timeperframe.numerator = kFrameRatePrecision;
2056 streamparm.parm.capture.timeperframe.denominator =
2057 (fps * kFrameRatePrecision);
2058
2059 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_PARM, &streamparm)) < 0) {
2060 ALOGE("%s: failed to set framerate to %f", __FUNCTION__, fps);
2061 return UNKNOWN_ERROR;
2062 }
2063 }
2064 }
2065 float retFps = streamparm.parm.capture.timeperframe.denominator /
2066 streamparm.parm.capture.timeperframe.numerator;
2067 if (std::fabs(fps - retFps) > std::numeric_limits<float>::epsilon()) {
2068 ALOGE("%s: expect fps %f, got %f instead", __FUNCTION__, fps, retFps);
2069 return BAD_VALUE;
2070 }
2071
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -08002072 uint32_t v4lBufferCount = (fps >= kDefaultFps) ?
2073 mCfg.numVideoBuffers : mCfg.numStillBuffers;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002074 // VIDIOC_REQBUFS: create buffers
2075 v4l2_requestbuffers req_buffers{};
2076 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2077 req_buffers.memory = V4L2_MEMORY_MMAP;
2078 req_buffers.count = v4lBufferCount;
2079 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
2080 ALOGE("%s: VIDIOC_REQBUFS failed: %s", __FUNCTION__, strerror(errno));
2081 return -errno;
2082 }
2083
2084 // Driver can indeed return more buffer if it needs more to operate
2085 if (req_buffers.count < v4lBufferCount) {
2086 ALOGE("%s: VIDIOC_REQBUFS expected %d buffers, got %d instead",
2087 __FUNCTION__, v4lBufferCount, req_buffers.count);
2088 return NO_MEMORY;
2089 }
2090
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002091 // VIDIOC_QUERYBUF: get buffer offset in the V4L2 fd
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002092 // VIDIOC_QBUF: send buffer to driver
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002093 mV4L2BufferCount = req_buffers.count;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002094 for (uint32_t i = 0; i < req_buffers.count; i++) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002095 v4l2_buffer buffer = {
2096 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
2097 .index = i,
2098 .memory = V4L2_MEMORY_MMAP};
2099
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002100 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QUERYBUF, &buffer)) < 0) {
2101 ALOGE("%s: QUERYBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
2102 return -errno;
2103 }
2104
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002105 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2106 ALOGE("%s: QBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
2107 return -errno;
2108 }
2109 }
2110
2111 // VIDIOC_STREAMON: start streaming
2112 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2113 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type)) < 0) {
2114 ALOGE("%s: VIDIOC_STREAMON failed: %s", __FUNCTION__, strerror(errno));
2115 return -errno;
2116 }
2117
2118 // Swallow first few frames after streamOn to account for bad frames from some devices
2119 for (int i = 0; i < kBadFramesAfterStreamOn; i++) {
2120 v4l2_buffer buffer{};
2121 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2122 buffer.memory = V4L2_MEMORY_MMAP;
2123 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
2124 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
2125 return -errno;
2126 }
2127
2128 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2129 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, buffer.index, strerror(errno));
2130 return -errno;
2131 }
2132 }
2133
2134 mV4l2StreamingFmt = v4l2Fmt;
2135 mV4l2Streaming = true;
2136 return OK;
2137}
2138
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002139sp<V4L2Frame> ExternalCameraDeviceSession::dequeueV4l2FrameLocked(/*out*/nsecs_t* shutterTs) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002140 sp<V4L2Frame> ret = nullptr;
2141
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002142 if (shutterTs == nullptr) {
2143 ALOGE("%s: shutterTs must not be null!", __FUNCTION__);
2144 return ret;
2145 }
2146
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002147 {
2148 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002149 if (mNumDequeuedV4l2Buffers == mV4L2BufferCount) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002150 std::chrono::seconds timeout = std::chrono::seconds(kBufferWaitTimeoutSec);
2151 mLock.unlock();
2152 auto st = mV4L2BufferReturned.wait_for(lk, timeout);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002153 // Here we introduce a case where mV4l2BufferLock is acquired before mLock, while
2154 // the normal lock acquisition order is reversed, but this is fine because in most of
2155 // cases we are protected by mInterfaceLock. The only thread that can compete these
2156 // locks are the OutputThread, where we do need to make sure we don't acquire mLock then
2157 // mV4l2BufferLock
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002158 mLock.lock();
2159 if (st == std::cv_status::timeout) {
2160 ALOGE("%s: wait for V4L2 buffer return timeout!", __FUNCTION__);
2161 return ret;
2162 }
2163 }
2164 }
2165
2166 v4l2_buffer buffer{};
2167 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2168 buffer.memory = V4L2_MEMORY_MMAP;
2169 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
2170 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
2171 return ret;
2172 }
2173
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002174 if (buffer.index >= mV4L2BufferCount) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002175 ALOGE("%s: Invalid buffer id: %d", __FUNCTION__, buffer.index);
2176 return ret;
2177 }
2178
2179 if (buffer.flags & V4L2_BUF_FLAG_ERROR) {
2180 ALOGE("%s: v4l2 buf error! buf flag 0x%x", __FUNCTION__, buffer.flags);
2181 // TODO: try to dequeue again
2182 }
2183
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002184 if (buffer.flags & V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC) {
2185 // Ideally we should also check for V4L2_BUF_FLAG_TSTAMP_SRC_SOE, but
2186 // even V4L2_BUF_FLAG_TSTAMP_SRC_EOF is better than capture a timestamp now
2187 *shutterTs = static_cast<nsecs_t>(buffer.timestamp.tv_sec)*1000000000LL +
2188 buffer.timestamp.tv_usec * 1000LL;
2189 } else {
2190 *shutterTs = systemTime(SYSTEM_TIME_MONOTONIC);
2191 }
2192
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002193 {
2194 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2195 mNumDequeuedV4l2Buffers++;
2196 }
2197 return new V4L2Frame(
2198 mV4l2StreamingFmt.width, mV4l2StreamingFmt.height, mV4l2StreamingFmt.fourcc,
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002199 buffer.index, mV4l2Fd.get(), buffer.bytesused, buffer.m.offset);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002200}
2201
2202void ExternalCameraDeviceSession::enqueueV4l2Frame(const sp<V4L2Frame>& frame) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002203 {
2204 // Release mLock before acquiring mV4l2BufferLock to avoid potential
2205 // deadlock
2206 Mutex::Autolock _l(mLock);
2207 frame->unmap();
2208 v4l2_buffer buffer{};
2209 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2210 buffer.memory = V4L2_MEMORY_MMAP;
2211 buffer.index = frame->mBufferIndex;
2212 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2213 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__,
2214 frame->mBufferIndex, strerror(errno));
2215 return;
2216 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002217 }
2218
2219 {
2220 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2221 mNumDequeuedV4l2Buffers--;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002222 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002223 mV4L2BufferReturned.notify_one();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002224}
2225
2226Status ExternalCameraDeviceSession::configureStreams(
2227 const V3_2::StreamConfiguration& config, V3_3::HalStreamConfiguration* out) {
2228 if (config.operationMode != StreamConfigurationMode::NORMAL_MODE) {
2229 ALOGE("%s: unsupported operation mode: %d", __FUNCTION__, config.operationMode);
2230 return Status::ILLEGAL_ARGUMENT;
2231 }
2232
2233 if (config.streams.size() == 0) {
2234 ALOGE("%s: cannot configure zero stream", __FUNCTION__);
2235 return Status::ILLEGAL_ARGUMENT;
2236 }
2237
2238 int numProcessedStream = 0;
2239 int numStallStream = 0;
2240 for (const auto& stream : config.streams) {
2241 // Check if the format/width/height combo is supported
2242 if (!isSupported(stream)) {
2243 return Status::ILLEGAL_ARGUMENT;
2244 }
2245 if (stream.format == PixelFormat::BLOB) {
2246 numStallStream++;
2247 } else {
2248 numProcessedStream++;
2249 }
2250 }
2251
2252 if (numProcessedStream > kMaxProcessedStream) {
2253 ALOGE("%s: too many processed streams (expect <= %d, got %d)", __FUNCTION__,
2254 kMaxProcessedStream, numProcessedStream);
2255 return Status::ILLEGAL_ARGUMENT;
2256 }
2257
2258 if (numStallStream > kMaxStallStream) {
2259 ALOGE("%s: too many stall streams (expect <= %d, got %d)", __FUNCTION__,
2260 kMaxStallStream, numStallStream);
2261 return Status::ILLEGAL_ARGUMENT;
2262 }
2263
2264 Status status = initStatus();
2265 if (status != Status::OK) {
2266 return status;
2267 }
2268
2269 Mutex::Autolock _l(mLock);
2270 if (!mInflightFrames.empty()) {
2271 ALOGE("%s: trying to configureStreams while there are still %zu inflight frames!",
2272 __FUNCTION__, mInflightFrames.size());
2273 return Status::INTERNAL_ERROR;
2274 }
2275
2276 // Add new streams
2277 for (const auto& stream : config.streams) {
2278 if (mStreamMap.count(stream.id) == 0) {
2279 mStreamMap[stream.id] = stream;
2280 mCirculatingBuffers.emplace(stream.id, CirculatingBuffers{});
2281 }
2282 }
2283
2284 // Cleanup removed streams
2285 for(auto it = mStreamMap.begin(); it != mStreamMap.end();) {
2286 int id = it->first;
2287 bool found = false;
2288 for (const auto& stream : config.streams) {
2289 if (id == stream.id) {
2290 found = true;
2291 break;
2292 }
2293 }
2294 if (!found) {
2295 // Unmap all buffers of deleted stream
2296 cleanupBuffersLocked(id);
2297 it = mStreamMap.erase(it);
2298 } else {
2299 ++it;
2300 }
2301 }
2302
2303 // Now select a V4L2 format to produce all output streams
2304 float desiredAr = (mCroppingType == VERTICAL) ? kMaxAspectRatio : kMinAspectRatio;
2305 uint32_t maxDim = 0;
2306 for (const auto& stream : config.streams) {
2307 float aspectRatio = ASPECT_RATIO(stream);
2308 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2309 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2310 desiredAr = aspectRatio;
2311 }
2312
2313 // The dimension that's not cropped
2314 uint32_t dim = (mCroppingType == VERTICAL) ? stream.width : stream.height;
2315 if (dim > maxDim) {
2316 maxDim = dim;
2317 }
2318 }
2319 // Find the smallest format that matches the desired aspect ratio and is wide/high enough
2320 SupportedV4L2Format v4l2Fmt {.width = 0, .height = 0};
2321 for (const auto& fmt : mSupportedFormats) {
2322 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2323 if (dim >= maxDim) {
2324 float aspectRatio = ASPECT_RATIO(fmt);
2325 if (isAspectRatioClose(aspectRatio, desiredAr)) {
2326 v4l2Fmt = fmt;
2327 // since mSupportedFormats is sorted by width then height, the first matching fmt
2328 // will be the smallest one with matching aspect ratio
2329 break;
2330 }
2331 }
2332 }
2333 if (v4l2Fmt.width == 0) {
2334 // Cannot find exact good aspect ratio candidate, try to find a close one
2335 for (const auto& fmt : mSupportedFormats) {
2336 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2337 if (dim >= maxDim) {
2338 float aspectRatio = ASPECT_RATIO(fmt);
2339 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2340 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2341 v4l2Fmt = fmt;
2342 break;
2343 }
2344 }
2345 }
2346 }
2347
2348 if (v4l2Fmt.width == 0) {
2349 ALOGE("%s: unable to find a resolution matching (%s at least %d, aspect ratio %f)"
2350 , __FUNCTION__, (mCroppingType == VERTICAL) ? "width" : "height",
2351 maxDim, desiredAr);
2352 return Status::ILLEGAL_ARGUMENT;
2353 }
2354
2355 if (configureV4l2StreamLocked(v4l2Fmt) != 0) {
2356 ALOGE("V4L configuration failed!, format:%c%c%c%c, w %d, h %d",
2357 v4l2Fmt.fourcc & 0xFF,
2358 (v4l2Fmt.fourcc >> 8) & 0xFF,
2359 (v4l2Fmt.fourcc >> 16) & 0xFF,
2360 (v4l2Fmt.fourcc >> 24) & 0xFF,
2361 v4l2Fmt.width, v4l2Fmt.height);
2362 return Status::INTERNAL_ERROR;
2363 }
2364
2365 Size v4lSize = {v4l2Fmt.width, v4l2Fmt.height};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08002366 Size thumbSize { 0, 0 };
2367 camera_metadata_ro_entry entry =
2368 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
2369 for(uint32_t i = 0; i < entry.count; i += 2) {
2370 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
2371 static_cast<uint32_t>(entry.data.i32[i+1]) };
2372 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
2373 thumbSize = sz;
2374 }
2375 }
2376
2377 if (thumbSize.width * thumbSize.height == 0) {
2378 ALOGE("%s: non-zero thumbnail size not available", __FUNCTION__);
2379 return Status::INTERNAL_ERROR;
2380 }
2381
2382 status = mOutputThread->allocateIntermediateBuffers(v4lSize,
2383 mMaxThumbResolution, config.streams);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002384 if (status != Status::OK) {
2385 ALOGE("%s: allocating intermediate buffers failed!", __FUNCTION__);
2386 return status;
2387 }
2388
2389 out->streams.resize(config.streams.size());
2390 for (size_t i = 0; i < config.streams.size(); i++) {
2391 out->streams[i].overrideDataSpace = config.streams[i].dataSpace;
2392 out->streams[i].v3_2.id = config.streams[i].id;
2393 // TODO: double check should we add those CAMERA flags
2394 mStreamMap[config.streams[i].id].usage =
2395 out->streams[i].v3_2.producerUsage = config.streams[i].usage |
2396 BufferUsage::CPU_WRITE_OFTEN |
2397 BufferUsage::CAMERA_OUTPUT;
2398 out->streams[i].v3_2.consumerUsage = 0;
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002399 out->streams[i].v3_2.maxBuffers = mV4L2BufferCount;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002400
2401 switch (config.streams[i].format) {
2402 case PixelFormat::BLOB:
2403 case PixelFormat::YCBCR_420_888:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002404 case PixelFormat::YV12: // Used by SurfaceTexture
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002405 // No override
2406 out->streams[i].v3_2.overrideFormat = config.streams[i].format;
2407 break;
2408 case PixelFormat::IMPLEMENTATION_DEFINED:
2409 // Override based on VIDEO or not
2410 out->streams[i].v3_2.overrideFormat =
2411 (config.streams[i].usage & BufferUsage::VIDEO_ENCODER) ?
2412 PixelFormat::YCBCR_420_888 : PixelFormat::YV12;
2413 // Save overridden formt in mStreamMap
2414 mStreamMap[config.streams[i].id].format = out->streams[i].v3_2.overrideFormat;
2415 break;
2416 default:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002417 ALOGE("%s: unsupported format 0x%x", __FUNCTION__, config.streams[i].format);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002418 return Status::ILLEGAL_ARGUMENT;
2419 }
2420 }
2421
2422 mFirstRequest = true;
2423 return Status::OK;
2424}
2425
2426bool ExternalCameraDeviceSession::isClosed() {
2427 Mutex::Autolock _l(mLock);
2428 return mClosed;
2429}
2430
2431#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
2432#define UPDATE(md, tag, data, size) \
2433do { \
2434 if ((md).update((tag), (data), (size))) { \
2435 ALOGE("Update " #tag " failed!"); \
2436 return BAD_VALUE; \
2437 } \
2438} while (0)
2439
2440status_t ExternalCameraDeviceSession::initDefaultRequests() {
2441 ::android::hardware::camera::common::V1_0::helper::CameraMetadata md;
2442
2443 const uint8_t aberrationMode = ANDROID_COLOR_CORRECTION_ABERRATION_MODE_OFF;
2444 UPDATE(md, ANDROID_COLOR_CORRECTION_ABERRATION_MODE, &aberrationMode, 1);
2445
2446 const int32_t exposureCompensation = 0;
2447 UPDATE(md, ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION, &exposureCompensation, 1);
2448
2449 const uint8_t videoStabilizationMode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
2450 UPDATE(md, ANDROID_CONTROL_VIDEO_STABILIZATION_MODE, &videoStabilizationMode, 1);
2451
2452 const uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO;
2453 UPDATE(md, ANDROID_CONTROL_AWB_MODE, &awbMode, 1);
2454
2455 const uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON;
2456 UPDATE(md, ANDROID_CONTROL_AE_MODE, &aeMode, 1);
2457
2458 const uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
2459 UPDATE(md, ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
2460
2461 const uint8_t afMode = ANDROID_CONTROL_AF_MODE_AUTO;
2462 UPDATE(md, ANDROID_CONTROL_AF_MODE, &afMode, 1);
2463
2464 const uint8_t afTrigger = ANDROID_CONTROL_AF_TRIGGER_IDLE;
2465 UPDATE(md, ANDROID_CONTROL_AF_TRIGGER, &afTrigger, 1);
2466
2467 const uint8_t sceneMode = ANDROID_CONTROL_SCENE_MODE_DISABLED;
2468 UPDATE(md, ANDROID_CONTROL_SCENE_MODE, &sceneMode, 1);
2469
2470 const uint8_t effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF;
2471 UPDATE(md, ANDROID_CONTROL_EFFECT_MODE, &effectMode, 1);
2472
2473 const uint8_t flashMode = ANDROID_FLASH_MODE_OFF;
2474 UPDATE(md, ANDROID_FLASH_MODE, &flashMode, 1);
2475
2476 const int32_t thumbnailSize[] = {240, 180};
2477 UPDATE(md, ANDROID_JPEG_THUMBNAIL_SIZE, thumbnailSize, 2);
2478
2479 const uint8_t jpegQuality = 90;
2480 UPDATE(md, ANDROID_JPEG_QUALITY, &jpegQuality, 1);
2481 UPDATE(md, ANDROID_JPEG_THUMBNAIL_QUALITY, &jpegQuality, 1);
2482
2483 const int32_t jpegOrientation = 0;
2484 UPDATE(md, ANDROID_JPEG_ORIENTATION, &jpegOrientation, 1);
2485
2486 const uint8_t oisMode = ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF;
2487 UPDATE(md, ANDROID_LENS_OPTICAL_STABILIZATION_MODE, &oisMode, 1);
2488
2489 const uint8_t nrMode = ANDROID_NOISE_REDUCTION_MODE_OFF;
2490 UPDATE(md, ANDROID_NOISE_REDUCTION_MODE, &nrMode, 1);
2491
2492 const uint8_t fdMode = ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
2493 UPDATE(md, ANDROID_STATISTICS_FACE_DETECT_MODE, &fdMode, 1);
2494
2495 const uint8_t hotpixelMode = ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF;
2496 UPDATE(md, ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE, &hotpixelMode, 1);
2497
2498 bool support30Fps = false;
2499 int32_t maxFps = std::numeric_limits<int32_t>::min();
2500 for (const auto& supportedFormat : mSupportedFormats) {
Yin-Chia Yeh134093a2018-02-12 14:05:48 -08002501 for (const auto& fr : supportedFormat.frameRates) {
2502 int32_t framerateInt = static_cast<int32_t>(fr.getDouble());
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002503 if (maxFps < framerateInt) {
2504 maxFps = framerateInt;
2505 }
2506 if (framerateInt == 30) {
2507 support30Fps = true;
2508 break;
2509 }
2510 }
2511 if (support30Fps) {
2512 break;
2513 }
2514 }
2515 int32_t defaultFramerate = support30Fps ? 30 : maxFps;
2516 int32_t defaultFpsRange[] = {defaultFramerate, defaultFramerate};
2517 UPDATE(md, ANDROID_CONTROL_AE_TARGET_FPS_RANGE, defaultFpsRange, ARRAY_SIZE(defaultFpsRange));
2518
2519 uint8_t antibandingMode = ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO;
2520 UPDATE(md, ANDROID_CONTROL_AE_ANTIBANDING_MODE, &antibandingMode, 1);
2521
2522 const uint8_t controlMode = ANDROID_CONTROL_MODE_AUTO;
2523 UPDATE(md, ANDROID_CONTROL_MODE, &controlMode, 1);
2524
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002525 auto requestTemplates = hidl_enum_iterator<RequestTemplate>();
2526 for (RequestTemplate type : requestTemplates) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002527 ::android::hardware::camera::common::V1_0::helper::CameraMetadata mdCopy = md;
2528 uint8_t intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2529 switch (type) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002530 case RequestTemplate::PREVIEW:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002531 intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2532 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002533 case RequestTemplate::STILL_CAPTURE:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002534 intent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE;
2535 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002536 case RequestTemplate::VIDEO_RECORD:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002537 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD;
2538 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002539 case RequestTemplate::VIDEO_SNAPSHOT:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002540 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT;
2541 break;
2542 default:
Yuriy Romanenko083de0c2018-01-26 16:05:54 -08002543 ALOGV("%s: unsupported RequestTemplate type %d", __FUNCTION__, type);
2544 continue;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002545 }
2546 UPDATE(mdCopy, ANDROID_CONTROL_CAPTURE_INTENT, &intent, 1);
2547
2548 camera_metadata_t* rawMd = mdCopy.release();
2549 CameraMetadata hidlMd;
2550 hidlMd.setToExternal(
2551 (uint8_t*) rawMd, get_camera_metadata_size(rawMd));
2552 mDefaultRequests[type] = hidlMd;
2553 free_camera_metadata(rawMd);
2554 }
2555
2556 return OK;
2557}
2558
2559status_t ExternalCameraDeviceSession::fillCaptureResult(
2560 common::V1_0::helper::CameraMetadata &md, nsecs_t timestamp) {
2561 // android.control
2562 // For USB camera, we don't know the AE state. Set the state to converged to
2563 // indicate the frame should be good to use. Then apps don't have to wait the
2564 // AE state.
2565 const uint8_t aeState = ANDROID_CONTROL_AE_STATE_CONVERGED;
2566 UPDATE(md, ANDROID_CONTROL_AE_STATE, &aeState, 1);
2567
2568 const uint8_t ae_lock = ANDROID_CONTROL_AE_LOCK_OFF;
2569 UPDATE(md, ANDROID_CONTROL_AE_LOCK, &ae_lock, 1);
2570
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002571 bool afTrigger = mAfTrigger;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002572 if (md.exists(ANDROID_CONTROL_AF_TRIGGER)) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002573 Mutex::Autolock _l(mLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002574 camera_metadata_entry entry = md.find(ANDROID_CONTROL_AF_TRIGGER);
2575 if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_START) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002576 mAfTrigger = afTrigger = true;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002577 } else if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_CANCEL) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002578 mAfTrigger = afTrigger = false;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002579 }
2580 }
2581
2582 // For USB camera, the USB camera handles everything and we don't have control
2583 // over AF. We only simply fake the AF metadata based on the request
2584 // received here.
2585 uint8_t afState;
2586 if (afTrigger) {
2587 afState = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
2588 } else {
2589 afState = ANDROID_CONTROL_AF_STATE_INACTIVE;
2590 }
2591 UPDATE(md, ANDROID_CONTROL_AF_STATE, &afState, 1);
2592
2593 // Set AWB state to converged to indicate the frame should be good to use.
2594 const uint8_t awbState = ANDROID_CONTROL_AWB_STATE_CONVERGED;
2595 UPDATE(md, ANDROID_CONTROL_AWB_STATE, &awbState, 1);
2596
2597 const uint8_t awbLock = ANDROID_CONTROL_AWB_LOCK_OFF;
2598 UPDATE(md, ANDROID_CONTROL_AWB_LOCK, &awbLock, 1);
2599
2600 camera_metadata_ro_entry active_array_size =
2601 mCameraCharacteristics.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
2602
2603 if (active_array_size.count == 0) {
2604 ALOGE("%s: cannot find active array size!", __FUNCTION__);
2605 return -EINVAL;
2606 }
2607
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002608 const uint8_t flashState = ANDROID_FLASH_STATE_UNAVAILABLE;
2609 UPDATE(md, ANDROID_FLASH_STATE, &flashState, 1);
2610
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002611 // android.scaler
2612 const int32_t crop_region[] = {
2613 active_array_size.data.i32[0], active_array_size.data.i32[1],
2614 active_array_size.data.i32[2], active_array_size.data.i32[3],
2615 };
2616 UPDATE(md, ANDROID_SCALER_CROP_REGION, crop_region, ARRAY_SIZE(crop_region));
2617
2618 // android.sensor
2619 UPDATE(md, ANDROID_SENSOR_TIMESTAMP, &timestamp, 1);
2620
2621 // android.statistics
2622 const uint8_t lensShadingMapMode = ANDROID_STATISTICS_LENS_SHADING_MAP_MODE_OFF;
2623 UPDATE(md, ANDROID_STATISTICS_LENS_SHADING_MAP_MODE, &lensShadingMapMode, 1);
2624
2625 const uint8_t sceneFlicker = ANDROID_STATISTICS_SCENE_FLICKER_NONE;
2626 UPDATE(md, ANDROID_STATISTICS_SCENE_FLICKER, &sceneFlicker, 1);
2627
2628 return OK;
2629}
2630
2631#undef ARRAY_SIZE
2632#undef UPDATE
2633
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002634} // namespace implementation
2635} // namespace V3_4
2636} // namespace device
2637} // namespace camera
2638} // namespace hardware
2639} // namespace android