blob: 01d7371b81539d470a17f8d76192473f4896493c [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 {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800163 bool sessionLocked = tryLock(mLock);
164 if (!sessionLocked) {
165 dprintf(fd, "!! ExternalCameraDeviceSession mLock may be deadlocked !!\n");
166 }
167 streaming = mV4l2Streaming;
168 streamingFmt = mV4l2StreamingFmt;
169 v4L2BufferCount = mV4L2BufferCount;
170 inflightFrames = mInflightFrames;
171 if (sessionLocked) {
172 mLock.unlock();
173 }
174 }
175
176 dprintf(fd, "External camera %s V4L2 FD %d, cropping type %s, %s\n",
177 mCameraId.c_str(), mV4l2Fd.get(),
178 (mCroppingType == VERTICAL) ? "vertical" : "horizontal",
179 streaming ? "streaming" : "not streaming");
180 if (streaming) {
181 // TODO: dump fps later
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800182 dprintf(fd, "Current V4L2 format %c%c%c%c %dx%d @ %ffps\n",
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800183 streamingFmt.fourcc & 0xFF,
184 (streamingFmt.fourcc >> 8) & 0xFF,
185 (streamingFmt.fourcc >> 16) & 0xFF,
186 (streamingFmt.fourcc >> 24) & 0xFF,
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800187 streamingFmt.width, streamingFmt.height,
188 mV4l2StreamingFps);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800189
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
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800224Status ExternalCameraDeviceSession::constructDefaultRequestSettingsRaw(RequestTemplate type,
225 V3_2::CameraMetadata *outMetadata) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700226 CameraMetadata emptyMd;
227 Status status = initStatus();
228 if (status != Status::OK) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800229 return status;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700230 }
231
232 switch (type) {
233 case RequestTemplate::PREVIEW:
234 case RequestTemplate::STILL_CAPTURE:
235 case RequestTemplate::VIDEO_RECORD:
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800236 case RequestTemplate::VIDEO_SNAPSHOT: {
237 *outMetadata = mDefaultRequests[type];
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700238 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800239 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700240 case RequestTemplate::MANUAL:
241 case RequestTemplate::ZERO_SHUTTER_LAG:
Eino-Ville Talvala0a2a9fc2018-02-05 16:27:15 -0800242 // Don't support MANUAL, ZSL templates
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800243 status = Status::ILLEGAL_ARGUMENT;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700244 break;
245 default:
246 ALOGE("%s: unknown request template type %d", __FUNCTION__, static_cast<int>(type));
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800247 status = Status::ILLEGAL_ARGUMENT;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700248 break;
249 }
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800250 return status;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700251}
252
253Return<void> ExternalCameraDeviceSession::configureStreams(
254 const V3_2::StreamConfiguration& streams,
255 ICameraDeviceSession::configureStreams_cb _hidl_cb) {
256 V3_2::HalStreamConfiguration outStreams;
257 V3_3::HalStreamConfiguration outStreams_v33;
258 Mutex::Autolock _il(mInterfaceLock);
259
260 Status status = configureStreams(streams, &outStreams_v33);
261 size_t size = outStreams_v33.streams.size();
262 outStreams.streams.resize(size);
263 for (size_t i = 0; i < size; i++) {
264 outStreams.streams[i] = outStreams_v33.streams[i].v3_2;
265 }
266 _hidl_cb(status, outStreams);
267 return Void();
268}
269
270Return<void> ExternalCameraDeviceSession::configureStreams_3_3(
271 const V3_2::StreamConfiguration& streams,
272 ICameraDeviceSession::configureStreams_3_3_cb _hidl_cb) {
273 V3_3::HalStreamConfiguration outStreams;
274 Mutex::Autolock _il(mInterfaceLock);
275
276 Status status = configureStreams(streams, &outStreams);
277 _hidl_cb(status, outStreams);
278 return Void();
279}
280
281Return<void> ExternalCameraDeviceSession::configureStreams_3_4(
282 const V3_4::StreamConfiguration& requestedConfiguration,
283 ICameraDeviceSession::configureStreams_3_4_cb _hidl_cb) {
284 V3_2::StreamConfiguration config_v32;
285 V3_3::HalStreamConfiguration outStreams_v33;
286 Mutex::Autolock _il(mInterfaceLock);
287
288 config_v32.operationMode = requestedConfiguration.operationMode;
289 config_v32.streams.resize(requestedConfiguration.streams.size());
290 for (size_t i = 0; i < config_v32.streams.size(); i++) {
291 config_v32.streams[i] = requestedConfiguration.streams[i].v3_2;
292 }
293
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700294 Status status = configureStreams(config_v32, &outStreams_v33);
295
296 V3_4::HalStreamConfiguration outStreams;
297 outStreams.streams.resize(outStreams_v33.streams.size());
298 for (size_t i = 0; i < outStreams.streams.size(); i++) {
299 outStreams.streams[i].v3_3 = outStreams_v33.streams[i];
300 }
301 _hidl_cb(status, outStreams);
302 return Void();
303}
304
305Return<void> ExternalCameraDeviceSession::getCaptureRequestMetadataQueue(
306 ICameraDeviceSession::getCaptureRequestMetadataQueue_cb _hidl_cb) {
307 Mutex::Autolock _il(mInterfaceLock);
308 _hidl_cb(*mRequestMetadataQueue->getDesc());
309 return Void();
310}
311
312Return<void> ExternalCameraDeviceSession::getCaptureResultMetadataQueue(
313 ICameraDeviceSession::getCaptureResultMetadataQueue_cb _hidl_cb) {
314 Mutex::Autolock _il(mInterfaceLock);
315 _hidl_cb(*mResultMetadataQueue->getDesc());
316 return Void();
317}
318
319Return<void> ExternalCameraDeviceSession::processCaptureRequest(
320 const hidl_vec<CaptureRequest>& requests,
321 const hidl_vec<BufferCache>& cachesToRemove,
322 ICameraDeviceSession::processCaptureRequest_cb _hidl_cb) {
323 Mutex::Autolock _il(mInterfaceLock);
324 updateBufferCaches(cachesToRemove);
325
326 uint32_t numRequestProcessed = 0;
327 Status s = Status::OK;
328 for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
329 s = processOneCaptureRequest(requests[i]);
330 if (s != Status::OK) {
331 break;
332 }
333 }
334
335 _hidl_cb(s, numRequestProcessed);
336 return Void();
337}
338
339Return<void> ExternalCameraDeviceSession::processCaptureRequest_3_4(
340 const hidl_vec<V3_4::CaptureRequest>& requests,
341 const hidl_vec<V3_2::BufferCache>& cachesToRemove,
342 ICameraDeviceSession::processCaptureRequest_3_4_cb _hidl_cb) {
343 Mutex::Autolock _il(mInterfaceLock);
344 updateBufferCaches(cachesToRemove);
345
346 uint32_t numRequestProcessed = 0;
347 Status s = Status::OK;
348 for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
349 s = processOneCaptureRequest(requests[i].v3_2);
350 if (s != Status::OK) {
351 break;
352 }
353 }
354
355 _hidl_cb(s, numRequestProcessed);
356 return Void();
357}
358
359Return<Status> ExternalCameraDeviceSession::flush() {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -0800360 Mutex::Autolock _il(mInterfaceLock);
361 Status status = initStatus();
362 if (status != Status::OK) {
363 return status;
364 }
365 mOutputThread->flush();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700366 return Status::OK;
367}
368
369Return<void> ExternalCameraDeviceSession::close() {
370 Mutex::Autolock _il(mInterfaceLock);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800371 bool closed = isClosed();
372 if (!closed) {
373 mOutputThread->flush();
374 mOutputThread->requestExit();
375 mOutputThread->join();
376
377 Mutex::Autolock _l(mLock);
378 // free all buffers
379 for(auto pair : mStreamMap) {
380 cleanupBuffersLocked(/*Stream ID*/pair.first);
381 }
382 v4l2StreamOffLocked();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700383 ALOGV("%s: closing V4L2 camera FD %d", __FUNCTION__, mV4l2Fd.get());
384 mV4l2Fd.reset();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700385 mClosed = true;
386 }
387 return Void();
388}
389
390Status ExternalCameraDeviceSession::importRequest(
391 const CaptureRequest& request,
392 hidl_vec<buffer_handle_t*>& allBufPtrs,
393 hidl_vec<int>& allFences) {
394 size_t numOutputBufs = request.outputBuffers.size();
395 size_t numBufs = numOutputBufs;
396 // Validate all I/O buffers
397 hidl_vec<buffer_handle_t> allBufs;
398 hidl_vec<uint64_t> allBufIds;
399 allBufs.resize(numBufs);
400 allBufIds.resize(numBufs);
401 allBufPtrs.resize(numBufs);
402 allFences.resize(numBufs);
403 std::vector<int32_t> streamIds(numBufs);
404
405 for (size_t i = 0; i < numOutputBufs; i++) {
406 allBufs[i] = request.outputBuffers[i].buffer.getNativeHandle();
407 allBufIds[i] = request.outputBuffers[i].bufferId;
408 allBufPtrs[i] = &allBufs[i];
409 streamIds[i] = request.outputBuffers[i].streamId;
410 }
411
412 for (size_t i = 0; i < numBufs; i++) {
413 buffer_handle_t buf = allBufs[i];
414 uint64_t bufId = allBufIds[i];
415 CirculatingBuffers& cbs = mCirculatingBuffers[streamIds[i]];
416 if (cbs.count(bufId) == 0) {
417 if (buf == nullptr) {
418 ALOGE("%s: bufferId %" PRIu64 " has null buffer handle!", __FUNCTION__, bufId);
419 return Status::ILLEGAL_ARGUMENT;
420 }
421 // Register a newly seen buffer
422 buffer_handle_t importedBuf = buf;
423 sHandleImporter.importBuffer(importedBuf);
424 if (importedBuf == nullptr) {
425 ALOGE("%s: output buffer %zu is invalid!", __FUNCTION__, i);
426 return Status::INTERNAL_ERROR;
427 } else {
428 cbs[bufId] = importedBuf;
429 }
430 }
431 allBufPtrs[i] = &cbs[bufId];
432 }
433
434 // All buffers are imported. Now validate output buffer acquire fences
435 for (size_t i = 0; i < numOutputBufs; i++) {
436 if (!sHandleImporter.importFence(
437 request.outputBuffers[i].acquireFence, allFences[i])) {
438 ALOGE("%s: output buffer %zu acquire fence is invalid", __FUNCTION__, i);
439 cleanupInflightFences(allFences, i);
440 return Status::INTERNAL_ERROR;
441 }
442 }
443 return Status::OK;
444}
445
446void ExternalCameraDeviceSession::cleanupInflightFences(
447 hidl_vec<int>& allFences, size_t numFences) {
448 for (size_t j = 0; j < numFences; j++) {
449 sHandleImporter.closeFence(allFences[j]);
450 }
451}
452
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800453int ExternalCameraDeviceSession::waitForV4L2BufferReturnLocked(std::unique_lock<std::mutex>& lk) {
454 std::chrono::seconds timeout = std::chrono::seconds(kBufferWaitTimeoutSec);
455 mLock.unlock();
456 auto st = mV4L2BufferReturned.wait_for(lk, timeout);
457 // Here we introduce a order where mV4l2BufferLock is acquired before mLock, while
458 // the normal lock acquisition order is reversed. This is fine because in most of
459 // cases we are protected by mInterfaceLock. The only thread that can cause deadlock
460 // is the OutputThread, where we do need to make sure we don't acquire mLock then
461 // mV4l2BufferLock
462 mLock.lock();
463 if (st == std::cv_status::timeout) {
464 ALOGE("%s: wait for V4L2 buffer return timeout!", __FUNCTION__);
465 return -1;
466 }
467 return 0;
468}
469
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700470Status ExternalCameraDeviceSession::processOneCaptureRequest(const CaptureRequest& request) {
471 Status status = initStatus();
472 if (status != Status::OK) {
473 return status;
474 }
475
476 if (request.inputBuffer.streamId != -1) {
477 ALOGE("%s: external camera does not support reprocessing!", __FUNCTION__);
478 return Status::ILLEGAL_ARGUMENT;
479 }
480
481 Mutex::Autolock _l(mLock);
482 if (!mV4l2Streaming) {
483 ALOGE("%s: cannot process request in streamOff state!", __FUNCTION__);
484 return Status::INTERNAL_ERROR;
485 }
486
487 const camera_metadata_t *rawSettings = nullptr;
488 bool converted = true;
489 CameraMetadata settingsFmq; // settings from FMQ
490 if (request.fmqSettingsSize > 0) {
491 // non-blocking read; client must write metadata before calling
492 // processOneCaptureRequest
493 settingsFmq.resize(request.fmqSettingsSize);
494 bool read = mRequestMetadataQueue->read(settingsFmq.data(), request.fmqSettingsSize);
495 if (read) {
496 converted = V3_2::implementation::convertFromHidl(settingsFmq, &rawSettings);
497 } else {
498 ALOGE("%s: capture request settings metadata couldn't be read from fmq!", __FUNCTION__);
499 converted = false;
500 }
501 } else {
502 converted = V3_2::implementation::convertFromHidl(request.settings, &rawSettings);
503 }
504
505 if (converted && rawSettings != nullptr) {
506 mLatestReqSetting = rawSettings;
507 }
508
509 if (!converted) {
510 ALOGE("%s: capture request settings metadata is corrupt!", __FUNCTION__);
511 return Status::ILLEGAL_ARGUMENT;
512 }
513
514 if (mFirstRequest && rawSettings == nullptr) {
515 ALOGE("%s: capture request settings must not be null for first request!",
516 __FUNCTION__);
517 return Status::ILLEGAL_ARGUMENT;
518 }
519
520 hidl_vec<buffer_handle_t*> allBufPtrs;
521 hidl_vec<int> allFences;
522 size_t numOutputBufs = request.outputBuffers.size();
523
524 if (numOutputBufs == 0) {
525 ALOGE("%s: capture request must have at least one output buffer!", __FUNCTION__);
526 return Status::ILLEGAL_ARGUMENT;
527 }
528
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800529 camera_metadata_entry fpsRange = mLatestReqSetting.find(ANDROID_CONTROL_AE_TARGET_FPS_RANGE);
530 if (fpsRange.count == 2) {
531 double requestFpsMax = fpsRange.data.i32[1];
532 double closestFps = 0.0;
533 double fpsError = 1000.0;
534 bool fpsSupported = false;
535 for (const auto& fr : mV4l2StreamingFmt.frameRates) {
536 double f = fr.getDouble();
537 if (std::fabs(requestFpsMax - f) < 1.0) {
538 fpsSupported = true;
539 break;
540 }
541 if (std::fabs(requestFpsMax - f) < fpsError) {
542 fpsError = std::fabs(requestFpsMax - f);
543 closestFps = f;
544 }
545 }
546 if (!fpsSupported) {
547 /* This can happen in a few scenarios:
548 * 1. The application is sending a FPS range not supported by the configured outputs.
549 * 2. The application is sending a valid FPS range for all cofigured outputs, but
550 * the selected V4L2 size can only run at slower speed. This should be very rare
551 * though: for this to happen a sensor needs to support at least 3 different aspect
552 * ratio outputs, and when (at least) two outputs are both not the main aspect ratio
553 * of the webcam, a third size that's larger might be picked and runs into this
554 * issue.
555 */
556 ALOGW("%s: cannot reach fps %d! Will do %f instead",
557 __FUNCTION__, fpsRange.data.i32[1], closestFps);
558 requestFpsMax = closestFps;
559 }
560
561 if (requestFpsMax != mV4l2StreamingFps) {
562 {
563 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
564 while (mNumDequeuedV4l2Buffers != 0) {
565 // Wait until pipeline is idle before reconfigure stream
566 int waitRet = waitForV4L2BufferReturnLocked(lk);
567 if (waitRet != 0) {
568 ALOGE("%s: wait for pipeline idle failed!", __FUNCTION__);
569 return Status::INTERNAL_ERROR;
570 }
571 }
572 }
573 configureV4l2StreamLocked(mV4l2StreamingFmt, requestFpsMax);
574 }
575 }
576
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700577 status = importRequest(request, allBufPtrs, allFences);
578 if (status != Status::OK) {
579 return status;
580 }
581
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800582 nsecs_t shutterTs = 0;
583 sp<V4L2Frame> frameIn = dequeueV4l2FrameLocked(&shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700584 if ( frameIn == nullptr) {
585 ALOGE("%s: V4L2 deque frame failed!", __FUNCTION__);
586 return Status::INTERNAL_ERROR;
587 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700588
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800589 std::shared_ptr<HalRequest> halReq = std::make_shared<HalRequest>();
590 halReq->frameNumber = request.frameNumber;
591 halReq->setting = mLatestReqSetting;
592 halReq->frameIn = frameIn;
593 halReq->shutterTs = shutterTs;
594 halReq->buffers.resize(numOutputBufs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700595 for (size_t i = 0; i < numOutputBufs; i++) {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800596 HalStreamBuffer& halBuf = halReq->buffers[i];
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700597 int streamId = halBuf.streamId = request.outputBuffers[i].streamId;
598 halBuf.bufferId = request.outputBuffers[i].bufferId;
599 const Stream& stream = mStreamMap[streamId];
600 halBuf.width = stream.width;
601 halBuf.height = stream.height;
602 halBuf.format = stream.format;
603 halBuf.usage = stream.usage;
604 halBuf.bufPtr = allBufPtrs[i];
605 halBuf.acquireFence = allFences[i];
606 halBuf.fenceTimeout = false;
607 }
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800608 mInflightFrames.insert(halReq->frameNumber);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700609 // Send request to OutputThread for the rest of processing
610 mOutputThread->submitRequest(halReq);
611 mFirstRequest = false;
612 return Status::OK;
613}
614
615void ExternalCameraDeviceSession::notifyShutter(uint32_t frameNumber, nsecs_t shutterTs) {
616 NotifyMsg msg;
617 msg.type = MsgType::SHUTTER;
618 msg.msg.shutter.frameNumber = frameNumber;
619 msg.msg.shutter.timestamp = shutterTs;
620 mCallback->notify({msg});
621}
622
623void ExternalCameraDeviceSession::notifyError(
624 uint32_t frameNumber, int32_t streamId, ErrorCode ec) {
625 NotifyMsg msg;
626 msg.type = MsgType::ERROR;
627 msg.msg.error.frameNumber = frameNumber;
628 msg.msg.error.errorStreamId = streamId;
629 msg.msg.error.errorCode = ec;
630 mCallback->notify({msg});
631}
632
633//TODO: refactor with processCaptureResult
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800634Status ExternalCameraDeviceSession::processCaptureRequestError(
635 const std::shared_ptr<HalRequest>& req) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700636 // Return V4L2 buffer to V4L2 buffer queue
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800637 enqueueV4l2Frame(req->frameIn);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700638
639 // NotifyShutter
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800640 notifyShutter(req->frameNumber, req->shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700641
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800642 notifyError(/*frameNum*/req->frameNumber, /*stream*/-1, ErrorCode::ERROR_REQUEST);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700643
644 // Fill output buffers
645 hidl_vec<CaptureResult> results;
646 results.resize(1);
647 CaptureResult& result = results[0];
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800648 result.frameNumber = req->frameNumber;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700649 result.partialResult = 1;
650 result.inputBuffer.streamId = -1;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800651 result.outputBuffers.resize(req->buffers.size());
652 for (size_t i = 0; i < req->buffers.size(); i++) {
653 result.outputBuffers[i].streamId = req->buffers[i].streamId;
654 result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700655 result.outputBuffers[i].status = BufferStatus::ERROR;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800656 if (req->buffers[i].acquireFence >= 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700657 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800658 handle->data[0] = req->buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800659 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700660 }
661 }
662
663 // update inflight records
664 {
665 Mutex::Autolock _l(mLock);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800666 mInflightFrames.erase(req->frameNumber);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700667 }
668
669 // Callback into framework
670 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
671 freeReleaseFences(results);
672 return Status::OK;
673}
674
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800675Status ExternalCameraDeviceSession::processCaptureResult(std::shared_ptr<HalRequest>& req) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700676 // Return V4L2 buffer to V4L2 buffer queue
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800677 enqueueV4l2Frame(req->frameIn);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700678
679 // NotifyShutter
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800680 notifyShutter(req->frameNumber, req->shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700681
682 // Fill output buffers
683 hidl_vec<CaptureResult> results;
684 results.resize(1);
685 CaptureResult& result = results[0];
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800686 result.frameNumber = req->frameNumber;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700687 result.partialResult = 1;
688 result.inputBuffer.streamId = -1;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800689 result.outputBuffers.resize(req->buffers.size());
690 for (size_t i = 0; i < req->buffers.size(); i++) {
691 result.outputBuffers[i].streamId = req->buffers[i].streamId;
692 result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
693 if (req->buffers[i].fenceTimeout) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700694 result.outputBuffers[i].status = BufferStatus::ERROR;
695 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800696 handle->data[0] = req->buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800697 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800698 notifyError(req->frameNumber, req->buffers[i].streamId, ErrorCode::ERROR_BUFFER);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700699 } else {
700 result.outputBuffers[i].status = BufferStatus::OK;
701 // TODO: refactor
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800702 if (req->buffers[i].acquireFence > 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700703 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800704 handle->data[0] = req->buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800705 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700706 }
707 }
708 }
709
710 // Fill capture result metadata
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800711 fillCaptureResult(req->setting, req->shutterTs);
712 const camera_metadata_t *rawResult = req->setting.getAndLock();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700713 V3_2::implementation::convertToHidl(rawResult, &result.result);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800714 req->setting.unlock(rawResult);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700715
716 // update inflight records
717 {
718 Mutex::Autolock _l(mLock);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800719 mInflightFrames.erase(req->frameNumber);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700720 }
721
722 // Callback into framework
723 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
724 freeReleaseFences(results);
725 return Status::OK;
726}
727
728void ExternalCameraDeviceSession::invokeProcessCaptureResultCallback(
729 hidl_vec<CaptureResult> &results, bool tryWriteFmq) {
730 if (mProcessCaptureResultLock.tryLock() != OK) {
731 const nsecs_t NS_TO_SECOND = 1000000000;
732 ALOGV("%s: previous call is not finished! waiting 1s...", __FUNCTION__);
733 if (mProcessCaptureResultLock.timedLock(/* 1s */NS_TO_SECOND) != OK) {
734 ALOGE("%s: cannot acquire lock in 1s, cannot proceed",
735 __FUNCTION__);
736 return;
737 }
738 }
739 if (tryWriteFmq && mResultMetadataQueue->availableToWrite() > 0) {
740 for (CaptureResult &result : results) {
741 if (result.result.size() > 0) {
742 if (mResultMetadataQueue->write(result.result.data(), result.result.size())) {
743 result.fmqResultSize = result.result.size();
744 result.result.resize(0);
745 } else {
746 ALOGW("%s: couldn't utilize fmq, fall back to hwbinder", __FUNCTION__);
747 result.fmqResultSize = 0;
748 }
749 } else {
750 result.fmqResultSize = 0;
751 }
752 }
753 }
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -0800754 auto status = mCallback->processCaptureResult(results);
755 if (!status.isOk()) {
756 ALOGE("%s: processCaptureResult ERROR : %s", __FUNCTION__,
757 status.description().c_str());
758 }
759
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700760 mProcessCaptureResultLock.unlock();
761}
762
763void ExternalCameraDeviceSession::freeReleaseFences(hidl_vec<CaptureResult>& results) {
764 for (auto& result : results) {
765 if (result.inputBuffer.releaseFence.getNativeHandle() != nullptr) {
766 native_handle_t* handle = const_cast<native_handle_t*>(
767 result.inputBuffer.releaseFence.getNativeHandle());
768 native_handle_close(handle);
769 native_handle_delete(handle);
770 }
771 for (auto& buf : result.outputBuffers) {
772 if (buf.releaseFence.getNativeHandle() != nullptr) {
773 native_handle_t* handle = const_cast<native_handle_t*>(
774 buf.releaseFence.getNativeHandle());
775 native_handle_close(handle);
776 native_handle_delete(handle);
777 }
778 }
779 }
780 return;
781}
782
783ExternalCameraDeviceSession::OutputThread::OutputThread(
784 wp<ExternalCameraDeviceSession> parent,
785 CroppingType ct) : mParent(parent), mCroppingType(ct) {}
786
787ExternalCameraDeviceSession::OutputThread::~OutputThread() {}
788
789uint32_t ExternalCameraDeviceSession::OutputThread::getFourCcFromLayout(
790 const YCbCrLayout& layout) {
791 intptr_t cb = reinterpret_cast<intptr_t>(layout.cb);
792 intptr_t cr = reinterpret_cast<intptr_t>(layout.cr);
793 if (std::abs(cb - cr) == 1 && layout.chromaStep == 2) {
794 // Interleaved format
795 if (layout.cb > layout.cr) {
796 return V4L2_PIX_FMT_NV21;
797 } else {
798 return V4L2_PIX_FMT_NV12;
799 }
800 } else if (layout.chromaStep == 1) {
801 // Planar format
802 if (layout.cb > layout.cr) {
803 return V4L2_PIX_FMT_YVU420; // YV12
804 } else {
805 return V4L2_PIX_FMT_YUV420; // YU12
806 }
807 } else {
808 return FLEX_YUV_GENERIC;
809 }
810}
811
812int ExternalCameraDeviceSession::OutputThread::getCropRect(
813 CroppingType ct, const Size& inSize, const Size& outSize, IMapper::Rect* out) {
814 if (out == nullptr) {
815 ALOGE("%s: out is null", __FUNCTION__);
816 return -1;
817 }
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800818
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700819 uint32_t inW = inSize.width;
820 uint32_t inH = inSize.height;
821 uint32_t outW = outSize.width;
822 uint32_t outH = outSize.height;
823
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800824 // Handle special case where aspect ratio is close to input but scaled
825 // dimension is slightly larger than input
826 float arIn = ASPECT_RATIO(inSize);
827 float arOut = ASPECT_RATIO(outSize);
828 if (isAspectRatioClose(arIn, arOut)) {
829 out->left = 0;
830 out->top = 0;
831 out->width = inW;
832 out->height = inH;
833 return 0;
834 }
835
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700836 if (ct == VERTICAL) {
837 uint64_t scaledOutH = static_cast<uint64_t>(outH) * inW / outW;
838 if (scaledOutH > inH) {
839 ALOGE("%s: Output size %dx%d cannot be vertically cropped from input size %dx%d",
840 __FUNCTION__, outW, outH, inW, inH);
841 return -1;
842 }
843 scaledOutH = scaledOutH & ~0x1; // make it multiple of 2
844
845 out->left = 0;
846 out->top = ((inH - scaledOutH) / 2) & ~0x1;
847 out->width = inW;
848 out->height = static_cast<int32_t>(scaledOutH);
849 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledH %d",
850 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutH));
851 } else {
852 uint64_t scaledOutW = static_cast<uint64_t>(outW) * inH / outH;
853 if (scaledOutW > inW) {
854 ALOGE("%s: Output size %dx%d cannot be horizontally cropped from input size %dx%d",
855 __FUNCTION__, outW, outH, inW, inH);
856 return -1;
857 }
858 scaledOutW = scaledOutW & ~0x1; // make it multiple of 2
859
860 out->left = ((inW - scaledOutW) / 2) & ~0x1;
861 out->top = 0;
862 out->width = static_cast<int32_t>(scaledOutW);
863 out->height = inH;
864 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledW %d",
865 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutW));
866 }
867
868 return 0;
869}
870
871int ExternalCameraDeviceSession::OutputThread::cropAndScaleLocked(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800872 sp<AllocatedFrame>& in, const Size& outSz, YCbCrLayout* out) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700873 Size inSz = {in->mWidth, in->mHeight};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800874
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700875 int ret;
876 if (inSz == outSz) {
877 ret = in->getLayout(out);
878 if (ret != 0) {
879 ALOGE("%s: failed to get input image layout", __FUNCTION__);
880 return ret;
881 }
882 return ret;
883 }
884
885 // Cropping to output aspect ratio
886 IMapper::Rect inputCrop;
887 ret = getCropRect(mCroppingType, inSz, outSz, &inputCrop);
888 if (ret != 0) {
889 ALOGE("%s: failed to compute crop rect for output size %dx%d",
890 __FUNCTION__, outSz.width, outSz.height);
891 return ret;
892 }
893
894 YCbCrLayout croppedLayout;
895 ret = in->getCroppedLayout(inputCrop, &croppedLayout);
896 if (ret != 0) {
897 ALOGE("%s: failed to crop input image %dx%d to output size %dx%d",
898 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
899 return ret;
900 }
901
902 if ((mCroppingType == VERTICAL && inSz.width == outSz.width) ||
903 (mCroppingType == HORIZONTAL && inSz.height == outSz.height)) {
904 // No scale is needed
905 *out = croppedLayout;
906 return 0;
907 }
908
909 auto it = mScaledYu12Frames.find(outSz);
910 sp<AllocatedFrame> scaledYu12Buf;
911 if (it != mScaledYu12Frames.end()) {
912 scaledYu12Buf = it->second;
913 } else {
914 it = mIntermediateBuffers.find(outSz);
915 if (it == mIntermediateBuffers.end()) {
916 ALOGE("%s: failed to find intermediate buffer size %dx%d",
917 __FUNCTION__, outSz.width, outSz.height);
918 return -1;
919 }
920 scaledYu12Buf = it->second;
921 }
922 // Scale
923 YCbCrLayout outLayout;
924 ret = scaledYu12Buf->getLayout(&outLayout);
925 if (ret != 0) {
926 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
927 return ret;
928 }
929
930 ret = libyuv::I420Scale(
931 static_cast<uint8_t*>(croppedLayout.y),
932 croppedLayout.yStride,
933 static_cast<uint8_t*>(croppedLayout.cb),
934 croppedLayout.cStride,
935 static_cast<uint8_t*>(croppedLayout.cr),
936 croppedLayout.cStride,
937 inputCrop.width,
938 inputCrop.height,
939 static_cast<uint8_t*>(outLayout.y),
940 outLayout.yStride,
941 static_cast<uint8_t*>(outLayout.cb),
942 outLayout.cStride,
943 static_cast<uint8_t*>(outLayout.cr),
944 outLayout.cStride,
945 outSz.width,
946 outSz.height,
947 // TODO: b/72261744 see if we can use better filter without losing too much perf
948 libyuv::FilterMode::kFilterNone);
949
950 if (ret != 0) {
951 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
952 __FUNCTION__, inputCrop.width, inputCrop.height,
953 outSz.width, outSz.height, ret);
954 return ret;
955 }
956
957 *out = outLayout;
958 mScaledYu12Frames.insert({outSz, scaledYu12Buf});
959 return 0;
960}
961
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800962
963int ExternalCameraDeviceSession::OutputThread::cropAndScaleThumbLocked(
964 sp<AllocatedFrame>& in, const Size &outSz, YCbCrLayout* out) {
965 Size inSz {in->mWidth, in->mHeight};
966
967 if ((outSz.width * outSz.height) >
968 (mYu12ThumbFrame->mWidth * mYu12ThumbFrame->mHeight)) {
969 ALOGE("%s: Requested thumbnail size too big (%d,%d) > (%d,%d)",
970 __FUNCTION__, outSz.width, outSz.height,
971 mYu12ThumbFrame->mWidth, mYu12ThumbFrame->mHeight);
972 return -1;
973 }
974
975 int ret;
976
977 /* This will crop-and-zoom the input YUV frame to the thumbnail size
978 * Based on the following logic:
979 * 1) Square pixels come in, square pixels come out, therefore single
980 * scale factor is computed to either make input bigger or smaller
981 * depending on if we are upscaling or downscaling
982 * 2) That single scale factor would either make height too tall or width
983 * too wide so we need to crop the input either horizontally or vertically
984 * but not both
985 */
986
987 /* Convert the input and output dimensions into floats for ease of math */
988 float fWin = static_cast<float>(inSz.width);
989 float fHin = static_cast<float>(inSz.height);
990 float fWout = static_cast<float>(outSz.width);
991 float fHout = static_cast<float>(outSz.height);
992
993 /* Compute the one scale factor from (1) above, it will be the smaller of
994 * the two possibilities. */
995 float scaleFactor = std::min( fHin / fHout, fWin / fWout );
996
997 /* Since we are crop-and-zooming (as opposed to letter/pillar boxing) we can
998 * simply multiply the output by our scaleFactor to get the cropped input
999 * size. Note that at least one of {fWcrop, fHcrop} is going to wind up
1000 * being {fWin, fHin} respectively because fHout or fWout cancels out the
1001 * scaleFactor calculation above.
1002 *
1003 * Specifically:
1004 * if ( fHin / fHout ) < ( fWin / fWout ) we crop the sides off
1005 * input, in which case
1006 * scaleFactor = fHin / fHout
1007 * fWcrop = fHin / fHout * fWout
1008 * fHcrop = fHin
1009 *
1010 * Note that fWcrop <= fWin ( because ( fHin / fHout ) * fWout < fWin, which
1011 * is just the inequality above with both sides multiplied by fWout
1012 *
1013 * on the other hand if ( fWin / fWout ) < ( fHin / fHout) we crop the top
1014 * and the bottom off of input, and
1015 * scaleFactor = fWin / fWout
1016 * fWcrop = fWin
1017 * fHCrop = fWin / fWout * fHout
1018 */
1019 float fWcrop = scaleFactor * fWout;
1020 float fHcrop = scaleFactor * fHout;
1021
1022 /* Convert to integer and truncate to an even number */
1023 Size cropSz = { 2*static_cast<uint32_t>(fWcrop/2.0f),
1024 2*static_cast<uint32_t>(fHcrop/2.0f) };
1025
1026 /* Convert to a centered rectange with even top/left */
1027 IMapper::Rect inputCrop {
1028 2*static_cast<int32_t>((inSz.width - cropSz.width)/4),
1029 2*static_cast<int32_t>((inSz.height - cropSz.height)/4),
1030 static_cast<int32_t>(cropSz.width),
1031 static_cast<int32_t>(cropSz.height) };
1032
1033 if ((inputCrop.top < 0) ||
1034 (inputCrop.top >= static_cast<int32_t>(inSz.height)) ||
1035 (inputCrop.left < 0) ||
1036 (inputCrop.left >= static_cast<int32_t>(inSz.width)) ||
1037 (inputCrop.width <= 0) ||
1038 (inputCrop.width + inputCrop.left > static_cast<int32_t>(inSz.width)) ||
1039 (inputCrop.height <= 0) ||
1040 (inputCrop.height + inputCrop.top > static_cast<int32_t>(inSz.height)))
1041 {
1042 ALOGE("%s: came up with really wrong crop rectangle",__FUNCTION__);
1043 ALOGE("%s: input layout %dx%d to for output size %dx%d",
1044 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1045 ALOGE("%s: computed input crop +%d,+%d %dx%d",
1046 __FUNCTION__, inputCrop.left, inputCrop.top,
1047 inputCrop.width, inputCrop.height);
1048 return -1;
1049 }
1050
1051 YCbCrLayout inputLayout;
1052 ret = in->getCroppedLayout(inputCrop, &inputLayout);
1053 if (ret != 0) {
1054 ALOGE("%s: failed to crop input layout %dx%d to for output size %dx%d",
1055 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1056 ALOGE("%s: computed input crop +%d,+%d %dx%d",
1057 __FUNCTION__, inputCrop.left, inputCrop.top,
1058 inputCrop.width, inputCrop.height);
1059 return ret;
1060 }
1061 ALOGV("%s: crop input layout %dx%d to for output size %dx%d",
1062 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1063 ALOGV("%s: computed input crop +%d,+%d %dx%d",
1064 __FUNCTION__, inputCrop.left, inputCrop.top,
1065 inputCrop.width, inputCrop.height);
1066
1067
1068 // Scale
1069 YCbCrLayout outFullLayout;
1070
1071 ret = mYu12ThumbFrame->getLayout(&outFullLayout);
1072 if (ret != 0) {
1073 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
1074 return ret;
1075 }
1076
1077
1078 ret = libyuv::I420Scale(
1079 static_cast<uint8_t*>(inputLayout.y),
1080 inputLayout.yStride,
1081 static_cast<uint8_t*>(inputLayout.cb),
1082 inputLayout.cStride,
1083 static_cast<uint8_t*>(inputLayout.cr),
1084 inputLayout.cStride,
1085 inputCrop.width,
1086 inputCrop.height,
1087 static_cast<uint8_t*>(outFullLayout.y),
1088 outFullLayout.yStride,
1089 static_cast<uint8_t*>(outFullLayout.cb),
1090 outFullLayout.cStride,
1091 static_cast<uint8_t*>(outFullLayout.cr),
1092 outFullLayout.cStride,
1093 outSz.width,
1094 outSz.height,
1095 libyuv::FilterMode::kFilterNone);
1096
1097 if (ret != 0) {
1098 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
1099 __FUNCTION__, inputCrop.width, inputCrop.height,
1100 outSz.width, outSz.height, ret);
1101 return ret;
1102 }
1103
1104 *out = outFullLayout;
1105 return 0;
1106}
1107
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001108int ExternalCameraDeviceSession::OutputThread::formatConvertLocked(
1109 const YCbCrLayout& in, const YCbCrLayout& out, Size sz, uint32_t format) {
1110 int ret = 0;
1111 switch (format) {
1112 case V4L2_PIX_FMT_NV21:
1113 ret = libyuv::I420ToNV21(
1114 static_cast<uint8_t*>(in.y),
1115 in.yStride,
1116 static_cast<uint8_t*>(in.cb),
1117 in.cStride,
1118 static_cast<uint8_t*>(in.cr),
1119 in.cStride,
1120 static_cast<uint8_t*>(out.y),
1121 out.yStride,
1122 static_cast<uint8_t*>(out.cr),
1123 out.cStride,
1124 sz.width,
1125 sz.height);
1126 if (ret != 0) {
1127 ALOGE("%s: convert to NV21 buffer failed! ret %d",
1128 __FUNCTION__, ret);
1129 return ret;
1130 }
1131 break;
1132 case V4L2_PIX_FMT_NV12:
1133 ret = libyuv::I420ToNV12(
1134 static_cast<uint8_t*>(in.y),
1135 in.yStride,
1136 static_cast<uint8_t*>(in.cb),
1137 in.cStride,
1138 static_cast<uint8_t*>(in.cr),
1139 in.cStride,
1140 static_cast<uint8_t*>(out.y),
1141 out.yStride,
1142 static_cast<uint8_t*>(out.cb),
1143 out.cStride,
1144 sz.width,
1145 sz.height);
1146 if (ret != 0) {
1147 ALOGE("%s: convert to NV12 buffer failed! ret %d",
1148 __FUNCTION__, ret);
1149 return ret;
1150 }
1151 break;
1152 case V4L2_PIX_FMT_YVU420: // YV12
1153 case V4L2_PIX_FMT_YUV420: // YU12
1154 // TODO: maybe we can speed up here by somehow save this copy?
1155 ret = libyuv::I420Copy(
1156 static_cast<uint8_t*>(in.y),
1157 in.yStride,
1158 static_cast<uint8_t*>(in.cb),
1159 in.cStride,
1160 static_cast<uint8_t*>(in.cr),
1161 in.cStride,
1162 static_cast<uint8_t*>(out.y),
1163 out.yStride,
1164 static_cast<uint8_t*>(out.cb),
1165 out.cStride,
1166 static_cast<uint8_t*>(out.cr),
1167 out.cStride,
1168 sz.width,
1169 sz.height);
1170 if (ret != 0) {
1171 ALOGE("%s: copy to YV12 or YU12 buffer failed! ret %d",
1172 __FUNCTION__, ret);
1173 return ret;
1174 }
1175 break;
1176 case FLEX_YUV_GENERIC:
1177 // TODO: b/72261744 write to arbitrary flexible YUV layout. Slow.
1178 ALOGE("%s: unsupported flexible yuv layout"
1179 " y %p cb %p cr %p y_str %d c_str %d c_step %d",
1180 __FUNCTION__, out.y, out.cb, out.cr,
1181 out.yStride, out.cStride, out.chromaStep);
1182 return -1;
1183 default:
1184 ALOGE("%s: unknown YUV format 0x%x!", __FUNCTION__, format);
1185 return -1;
1186 }
1187 return 0;
1188}
1189
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001190int ExternalCameraDeviceSession::OutputThread::encodeJpegYU12(
1191 const Size & inSz, const YCbCrLayout& inLayout,
1192 int jpegQuality, const void *app1Buffer, size_t app1Size,
1193 void *out, const size_t maxOutSize, size_t &actualCodeSize)
1194{
1195 /* libjpeg is a C library so we use C-style "inheritance" by
1196 * putting libjpeg's jpeg_destination_mgr first in our custom
1197 * struct. This allows us to cast jpeg_destination_mgr* to
1198 * CustomJpegDestMgr* when we get it passed to us in a callback */
1199 struct CustomJpegDestMgr {
1200 struct jpeg_destination_mgr mgr;
1201 JOCTET *mBuffer;
1202 size_t mBufferSize;
1203 size_t mEncodedSize;
1204 bool mSuccess;
1205 } dmgr;
1206
1207 jpeg_compress_struct cinfo = {};
1208 jpeg_error_mgr jerr;
1209
1210 /* Initialize error handling with standard callbacks, but
1211 * then override output_message (to print to ALOG) and
1212 * error_exit to set a flag and print a message instead
1213 * of killing the whole process */
1214 cinfo.err = jpeg_std_error(&jerr);
1215
1216 cinfo.err->output_message = [](j_common_ptr cinfo) {
1217 char buffer[JMSG_LENGTH_MAX];
1218
1219 /* Create the message */
1220 (*cinfo->err->format_message)(cinfo, buffer);
1221 ALOGE("libjpeg error: %s", buffer);
1222 };
1223 cinfo.err->error_exit = [](j_common_ptr cinfo) {
1224 (*cinfo->err->output_message)(cinfo);
1225 if(cinfo->client_data) {
1226 auto & dmgr =
1227 *reinterpret_cast<CustomJpegDestMgr*>(cinfo->client_data);
1228 dmgr.mSuccess = false;
1229 }
1230 };
1231 /* Now that we initialized some callbacks, let's create our compressor */
1232 jpeg_create_compress(&cinfo);
1233
1234 /* Initialize our destination manager */
1235 dmgr.mBuffer = static_cast<JOCTET*>(out);
1236 dmgr.mBufferSize = maxOutSize;
1237 dmgr.mEncodedSize = 0;
1238 dmgr.mSuccess = true;
1239 cinfo.client_data = static_cast<void*>(&dmgr);
1240
1241 /* These lambdas become C-style function pointers and as per C++11 spec
1242 * may not capture anything */
1243 dmgr.mgr.init_destination = [](j_compress_ptr cinfo) {
1244 auto & dmgr = reinterpret_cast<CustomJpegDestMgr&>(*cinfo->dest);
1245 dmgr.mgr.next_output_byte = dmgr.mBuffer;
1246 dmgr.mgr.free_in_buffer = dmgr.mBufferSize;
1247 ALOGV("%s:%d jpeg start: %p [%zu]",
1248 __FUNCTION__, __LINE__, dmgr.mBuffer, dmgr.mBufferSize);
1249 };
1250
1251 dmgr.mgr.empty_output_buffer = [](j_compress_ptr cinfo __unused) {
1252 ALOGV("%s:%d Out of buffer", __FUNCTION__, __LINE__);
1253 return 0;
1254 };
1255
1256 dmgr.mgr.term_destination = [](j_compress_ptr cinfo) {
1257 auto & dmgr = reinterpret_cast<CustomJpegDestMgr&>(*cinfo->dest);
1258 dmgr.mEncodedSize = dmgr.mBufferSize - dmgr.mgr.free_in_buffer;
1259 ALOGV("%s:%d Done with jpeg: %zu", __FUNCTION__, __LINE__, dmgr.mEncodedSize);
1260 };
1261 cinfo.dest = reinterpret_cast<struct jpeg_destination_mgr*>(&dmgr);
1262
1263 /* We are going to be using JPEG in raw data mode, so we are passing
1264 * straight subsampled planar YCbCr and it will not touch our pixel
1265 * data or do any scaling or anything */
1266 cinfo.image_width = inSz.width;
1267 cinfo.image_height = inSz.height;
1268 cinfo.input_components = 3;
1269 cinfo.in_color_space = JCS_YCbCr;
1270
1271 /* Initialize defaults and then override what we want */
1272 jpeg_set_defaults(&cinfo);
1273
1274 jpeg_set_quality(&cinfo, jpegQuality, 1);
1275 jpeg_set_colorspace(&cinfo, JCS_YCbCr);
1276 cinfo.raw_data_in = 1;
1277 cinfo.dct_method = JDCT_IFAST;
1278
1279 /* Configure sampling factors. The sampling factor is JPEG subsampling 420
1280 * because the source format is YUV420. Note that libjpeg sampling factors
1281 * are... a little weird. Sampling of Y=2,U=1,V=1 means there is 1 U and
1282 * 1 V value for each 2 Y values */
1283 cinfo.comp_info[0].h_samp_factor = 2;
1284 cinfo.comp_info[0].v_samp_factor = 2;
1285 cinfo.comp_info[1].h_samp_factor = 1;
1286 cinfo.comp_info[1].v_samp_factor = 1;
1287 cinfo.comp_info[2].h_samp_factor = 1;
1288 cinfo.comp_info[2].v_samp_factor = 1;
1289
1290 /* Let's not hardcode YUV420 in 6 places... 5 was enough */
1291 int maxVSampFactor = std::max( {
1292 cinfo.comp_info[0].v_samp_factor,
1293 cinfo.comp_info[1].v_samp_factor,
1294 cinfo.comp_info[2].v_samp_factor
1295 });
1296 int cVSubSampling = cinfo.comp_info[0].v_samp_factor /
1297 cinfo.comp_info[1].v_samp_factor;
1298
1299 /* Start the compressor */
1300 jpeg_start_compress(&cinfo, TRUE);
1301
1302 /* Compute our macroblock height, so we can pad our input to be vertically
1303 * macroblock aligned.
1304 * TODO: Does it need to be horizontally MCU aligned too? */
1305
1306 size_t mcuV = DCTSIZE*maxVSampFactor;
1307 size_t paddedHeight = mcuV * ((inSz.height + mcuV - 1) / mcuV);
1308
1309 /* libjpeg uses arrays of row pointers, which makes it really easy to pad
1310 * data vertically (unfortunately doesn't help horizontally) */
1311 std::vector<JSAMPROW> yLines (paddedHeight);
1312 std::vector<JSAMPROW> cbLines(paddedHeight/cVSubSampling);
1313 std::vector<JSAMPROW> crLines(paddedHeight/cVSubSampling);
1314
1315 uint8_t *py = static_cast<uint8_t*>(inLayout.y);
1316 uint8_t *pcr = static_cast<uint8_t*>(inLayout.cr);
1317 uint8_t *pcb = static_cast<uint8_t*>(inLayout.cb);
1318
1319 for(uint32_t i = 0; i < paddedHeight; i++)
1320 {
1321 /* Once we are in the padding territory we still point to the last line
1322 * effectively replicating it several times ~ CLAMP_TO_EDGE */
1323 int li = std::min(i, inSz.height - 1);
1324 yLines[i] = static_cast<JSAMPROW>(py + li * inLayout.yStride);
1325 if(i < paddedHeight / cVSubSampling)
1326 {
1327 crLines[i] = static_cast<JSAMPROW>(pcr + li * inLayout.cStride);
1328 cbLines[i] = static_cast<JSAMPROW>(pcb + li * inLayout.cStride);
1329 }
1330 }
1331
1332 /* If APP1 data was passed in, use it */
1333 if(app1Buffer && app1Size)
1334 {
1335 jpeg_write_marker(&cinfo, JPEG_APP0 + 1,
1336 static_cast<const JOCTET*>(app1Buffer), app1Size);
1337 }
1338
1339 /* While we still have padded height left to go, keep giving it one
1340 * macroblock at a time. */
1341 while (cinfo.next_scanline < cinfo.image_height) {
1342 const uint32_t batchSize = DCTSIZE * maxVSampFactor;
1343 const uint32_t nl = cinfo.next_scanline;
1344 JSAMPARRAY planes[3]{ &yLines[nl],
1345 &cbLines[nl/cVSubSampling],
1346 &crLines[nl/cVSubSampling] };
1347
1348 uint32_t done = jpeg_write_raw_data(&cinfo, planes, batchSize);
1349
1350 if (done != batchSize) {
1351 ALOGE("%s: compressed %u lines, expected %u (total %u/%u)",
1352 __FUNCTION__, done, batchSize, cinfo.next_scanline,
1353 cinfo.image_height);
1354 return -1;
1355 }
1356 }
1357
1358 /* This will flush everything */
1359 jpeg_finish_compress(&cinfo);
1360
1361 /* Grab the actual code size and set it */
1362 actualCodeSize = dmgr.mEncodedSize;
1363
1364 return 0;
1365}
1366
1367/*
1368 * TODO: There needs to be a mechanism to discover allocated buffer size
1369 * in the HAL.
1370 *
1371 * This is very fragile because it is duplicated computation from:
1372 * frameworks/av/services/camera/libcameraservice/device3/Camera3Device.cpp
1373 *
1374 */
1375
1376/* This assumes mSupportedFormats have all been declared as supporting
1377 * HAL_PIXEL_FORMAT_BLOB to the framework */
1378Size ExternalCameraDeviceSession::getMaxJpegResolution() const {
1379 Size ret { 0, 0 };
1380 for(auto & fmt : mSupportedFormats) {
1381 if(fmt.width * fmt.height > ret.width * ret.height) {
1382 ret = Size { fmt.width, fmt.height };
1383 }
1384 }
1385 return ret;
1386}
1387
1388Size ExternalCameraDeviceSession::getMaxThumbResolution() const {
1389 Size thumbSize { 0, 0 };
1390 camera_metadata_ro_entry entry =
1391 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
1392 for(uint32_t i = 0; i < entry.count; i += 2) {
1393 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
1394 static_cast<uint32_t>(entry.data.i32[i+1]) };
1395 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
1396 thumbSize = sz;
1397 }
1398 }
1399
1400 if (thumbSize.width * thumbSize.height == 0) {
1401 ALOGW("%s: non-zero thumbnail size not available", __FUNCTION__);
1402 }
1403
1404 return thumbSize;
1405}
1406
1407
1408ssize_t ExternalCameraDeviceSession::getJpegBufferSize(
1409 uint32_t width, uint32_t height) const {
1410 // Constant from camera3.h
1411 const ssize_t kMinJpegBufferSize = 256 * 1024 + sizeof(CameraBlob);
1412 // Get max jpeg size (area-wise).
1413 if (mMaxJpegResolution.width == 0) {
1414 ALOGE("%s: Do not have a single supported JPEG stream",
1415 __FUNCTION__);
1416 return BAD_VALUE;
1417 }
1418
1419 // Get max jpeg buffer size
1420 ssize_t maxJpegBufferSize = 0;
1421 camera_metadata_ro_entry jpegBufMaxSize =
1422 mCameraCharacteristics.find(ANDROID_JPEG_MAX_SIZE);
1423 if (jpegBufMaxSize.count == 0) {
1424 ALOGE("%s: Can't find maximum JPEG size in static metadata!",
1425 __FUNCTION__);
1426 return BAD_VALUE;
1427 }
1428 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
1429
1430 if (maxJpegBufferSize <= kMinJpegBufferSize) {
1431 ALOGE("%s: ANDROID_JPEG_MAX_SIZE (%zd) <= kMinJpegBufferSize (%zd)",
1432 __FUNCTION__, maxJpegBufferSize, kMinJpegBufferSize);
1433 return BAD_VALUE;
1434 }
1435
1436 // Calculate final jpeg buffer size for the given resolution.
1437 float scaleFactor = ((float) (width * height)) /
1438 (mMaxJpegResolution.width * mMaxJpegResolution.height);
1439 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
1440 kMinJpegBufferSize;
1441 if (jpegBufferSize > maxJpegBufferSize) {
1442 jpegBufferSize = maxJpegBufferSize;
1443 }
1444
1445 return jpegBufferSize;
1446}
1447
1448int ExternalCameraDeviceSession::OutputThread::createJpegLocked(
1449 HalStreamBuffer &halBuf,
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001450 const std::shared_ptr<HalRequest>& req)
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001451{
1452 int ret;
1453 auto lfail = [&](auto... args) {
1454 ALOGE(args...);
1455
1456 return 1;
1457 };
1458 auto parent = mParent.promote();
1459 if (parent == nullptr) {
1460 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1461 return 1;
1462 }
1463
1464 ALOGV("%s: HAL buffer sid: %d bid: %" PRIu64 " w: %u h: %u",
1465 __FUNCTION__, halBuf.streamId, static_cast<uint64_t>(halBuf.bufferId),
1466 halBuf.width, halBuf.height);
1467 ALOGV("%s: HAL buffer fmt: %x usage: %" PRIx64 " ptr: %p",
1468 __FUNCTION__, halBuf.format, static_cast<uint64_t>(halBuf.usage),
1469 halBuf.bufPtr);
1470 ALOGV("%s: YV12 buffer %d x %d",
1471 __FUNCTION__,
1472 mYu12Frame->mWidth, mYu12Frame->mHeight);
1473
1474 int jpegQuality, thumbQuality;
1475 Size thumbSize;
1476
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001477 if (req->setting.exists(ANDROID_JPEG_QUALITY)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001478 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001479 req->setting.find(ANDROID_JPEG_QUALITY);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001480 jpegQuality = entry.data.u8[0];
1481 } else {
1482 return lfail("%s: ANDROID_JPEG_QUALITY not set",__FUNCTION__);
1483 }
1484
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001485 if (req->setting.exists(ANDROID_JPEG_THUMBNAIL_QUALITY)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001486 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001487 req->setting.find(ANDROID_JPEG_THUMBNAIL_QUALITY);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001488 thumbQuality = entry.data.u8[0];
1489 } else {
1490 return lfail(
1491 "%s: ANDROID_JPEG_THUMBNAIL_QUALITY not set",
1492 __FUNCTION__);
1493 }
1494
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001495 if (req->setting.exists(ANDROID_JPEG_THUMBNAIL_SIZE)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001496 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001497 req->setting.find(ANDROID_JPEG_THUMBNAIL_SIZE);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001498 thumbSize = Size { static_cast<uint32_t>(entry.data.i32[0]),
1499 static_cast<uint32_t>(entry.data.i32[1])
1500 };
1501 } else {
1502 return lfail(
1503 "%s: ANDROID_JPEG_THUMBNAIL_SIZE not set", __FUNCTION__);
1504 }
1505
1506 /* Cropped and scaled YU12 buffer for main and thumbnail */
1507 YCbCrLayout yu12Main;
1508 Size jpegSize { halBuf.width, halBuf.height };
1509
1510 /* Compute temporary buffer sizes accounting for the following:
1511 * thumbnail can't exceed APP1 size of 64K
1512 * main image needs to hold APP1, headers, and at most a poorly
1513 * compressed image */
1514 const ssize_t maxThumbCodeSize = 64 * 1024;
1515 const ssize_t maxJpegCodeSize = parent->getJpegBufferSize(jpegSize.width,
1516 jpegSize.height);
1517
1518 /* Check that getJpegBufferSize did not return an error */
1519 if (maxJpegCodeSize < 0) {
1520 return lfail(
1521 "%s: getJpegBufferSize returned %zd",__FUNCTION__,maxJpegCodeSize);
1522 }
1523
1524
1525 /* Hold actual thumbnail and main image code sizes */
1526 size_t thumbCodeSize = 0, jpegCodeSize = 0;
1527 /* Temporary thumbnail code buffer */
1528 std::vector<uint8_t> thumbCode(maxThumbCodeSize);
1529
1530 YCbCrLayout yu12Thumb;
1531 ret = cropAndScaleThumbLocked(mYu12Frame, thumbSize, &yu12Thumb);
1532
1533 if (ret != 0) {
1534 return lfail(
1535 "%s: crop and scale thumbnail failed!", __FUNCTION__);
1536 }
1537
1538 /* Scale and crop main jpeg */
1539 ret = cropAndScaleLocked(mYu12Frame, jpegSize, &yu12Main);
1540
1541 if (ret != 0) {
1542 return lfail("%s: crop and scale main failed!", __FUNCTION__);
1543 }
1544
1545 /* Encode the thumbnail image */
1546 ret = encodeJpegYU12(thumbSize, yu12Thumb,
1547 thumbQuality, 0, 0,
1548 &thumbCode[0], maxThumbCodeSize, thumbCodeSize);
1549
1550 if (ret != 0) {
1551 return lfail("%s: encodeJpegYU12 failed with %d",__FUNCTION__, ret);
1552 }
1553
1554 /* Combine camera characteristics with request settings to form EXIF
1555 * metadata */
1556 common::V1_0::helper::CameraMetadata meta(parent->mCameraCharacteristics);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001557 meta.append(req->setting);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001558
1559 /* Generate EXIF object */
1560 std::unique_ptr<ExifUtils> utils(ExifUtils::create());
1561 /* Make sure it's initialized */
1562 utils->initialize();
1563
1564 utils->setFromMetadata(meta, jpegSize.width, jpegSize.height);
1565
1566 /* Check if we made a non-zero-sized thumbnail. Currently not possible
1567 * that we got this far and the code is size 0, but if this code moves
1568 * around it might become relevant again */
1569
1570 ret = utils->generateApp1(thumbCodeSize ? &thumbCode[0] : 0, thumbCodeSize);
1571
1572 if (!ret) {
1573 return lfail("%s: generating APP1 failed", __FUNCTION__);
1574 }
1575
1576 /* Get internal buffer */
1577 size_t exifDataSize = utils->getApp1Length();
1578 const uint8_t* exifData = utils->getApp1Buffer();
1579
1580 /* Lock the HAL jpeg code buffer */
1581 void *bufPtr = sHandleImporter.lock(
1582 *(halBuf.bufPtr), halBuf.usage, maxJpegCodeSize);
1583
1584 if (!bufPtr) {
1585 return lfail("%s: could not lock %zu bytes", __FUNCTION__, maxJpegCodeSize);
1586 }
1587
1588 /* Encode the main jpeg image */
1589 ret = encodeJpegYU12(jpegSize, yu12Main,
1590 jpegQuality, exifData, exifDataSize,
1591 bufPtr, maxJpegCodeSize, jpegCodeSize);
1592
1593 /* TODO: Not sure this belongs here, maybe better to pass jpegCodeSize out
1594 * and do this when returning buffer to parent */
1595 CameraBlob blob { CameraBlobId::JPEG, static_cast<uint32_t>(jpegCodeSize) };
1596 void *blobDst =
1597 reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(bufPtr) +
1598 maxJpegCodeSize -
1599 sizeof(CameraBlob));
1600 memcpy(blobDst, &blob, sizeof(CameraBlob));
1601
1602 /* Unlock the HAL jpeg code buffer */
1603 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
1604 if (relFence > 0) {
1605 halBuf.acquireFence = relFence;
1606 }
1607
1608 /* Check if our JPEG actually succeeded */
1609 if (ret != 0) {
1610 return lfail(
1611 "%s: encodeJpegYU12 failed with %d",__FUNCTION__, ret);
1612 }
1613
1614 ALOGV("%s: encoded JPEG (ret:%d) with Q:%d max size: %zu",
1615 __FUNCTION__, ret, jpegQuality, maxJpegCodeSize);
1616
1617 return 0;
1618}
1619
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001620bool ExternalCameraDeviceSession::OutputThread::threadLoop() {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001621 std::shared_ptr<HalRequest> req;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001622 auto parent = mParent.promote();
1623 if (parent == nullptr) {
1624 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1625 return false;
1626 }
1627
1628 // TODO: maybe we need to setup a sensor thread to dq/enq v4l frames
1629 // regularly to prevent v4l buffer queue filled with stale buffers
1630 // when app doesn't program a preveiw request
1631 waitForNextRequest(&req);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001632 if (req == nullptr) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001633 // No new request, wait again
1634 return true;
1635 }
1636
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001637 auto onDeviceError = [&](auto... args) {
1638 ALOGE(args...);
1639 parent->notifyError(
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001640 req->frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001641 signalRequestDone();
1642 return false;
1643 };
1644
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001645 if (req->frameIn->mFourcc != V4L2_PIX_FMT_MJPEG) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001646 return onDeviceError("%s: do not support V4L2 format %c%c%c%c", __FUNCTION__,
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001647 req->frameIn->mFourcc & 0xFF,
1648 (req->frameIn->mFourcc >> 8) & 0xFF,
1649 (req->frameIn->mFourcc >> 16) & 0xFF,
1650 (req->frameIn->mFourcc >> 24) & 0xFF);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001651 }
1652
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001653 std::unique_lock<std::mutex> lk(mBufferLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001654 // Convert input V4L2 frame to YU12 of the same size
1655 // TODO: see if we can save some computation by converting to YV12 here
1656 uint8_t* inData;
1657 size_t inDataSize;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001658 req->frameIn->map(&inData, &inDataSize);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001659 // TODO: profile
1660 // TODO: in some special case maybe we can decode jpg directly to gralloc output?
1661 int res = libyuv::MJPGToI420(
1662 inData, inDataSize,
1663 static_cast<uint8_t*>(mYu12FrameLayout.y),
1664 mYu12FrameLayout.yStride,
1665 static_cast<uint8_t*>(mYu12FrameLayout.cb),
1666 mYu12FrameLayout.cStride,
1667 static_cast<uint8_t*>(mYu12FrameLayout.cr),
1668 mYu12FrameLayout.cStride,
1669 mYu12Frame->mWidth, mYu12Frame->mHeight,
1670 mYu12Frame->mWidth, mYu12Frame->mHeight);
1671
1672 if (res != 0) {
1673 // For some webcam, the first few V4L2 frames might be malformed...
1674 ALOGE("%s: Convert V4L2 frame to YU12 failed! res %d", __FUNCTION__, res);
1675 lk.unlock();
1676 Status st = parent->processCaptureRequestError(req);
1677 if (st != Status::OK) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001678 return onDeviceError("%s: failed to process capture request error!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001679 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001680 signalRequestDone();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001681 return true;
1682 }
1683
1684 ALOGV("%s processing new request", __FUNCTION__);
1685 const int kSyncWaitTimeoutMs = 500;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001686 for (auto& halBuf : req->buffers) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001687 if (halBuf.acquireFence != -1) {
1688 int ret = sync_wait(halBuf.acquireFence, kSyncWaitTimeoutMs);
1689 if (ret) {
1690 halBuf.fenceTimeout = true;
1691 } else {
1692 ::close(halBuf.acquireFence);
Yin-Chia Yeh1e089662018-02-02 15:57:58 -08001693 halBuf.acquireFence = -1;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001694 }
1695 }
1696
1697 if (halBuf.fenceTimeout) {
1698 continue;
1699 }
1700
1701 // Gralloc lockYCbCr the buffer
1702 switch (halBuf.format) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001703 case PixelFormat::BLOB: {
1704 int ret = createJpegLocked(halBuf, req);
1705
1706 if(ret != 0) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001707 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001708 return onDeviceError("%s: createJpegLocked failed with %d",
1709 __FUNCTION__, ret);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001710 }
1711 } break;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001712 case PixelFormat::YCBCR_420_888:
1713 case PixelFormat::YV12: {
1714 IMapper::Rect outRect {0, 0,
1715 static_cast<int32_t>(halBuf.width),
1716 static_cast<int32_t>(halBuf.height)};
1717 YCbCrLayout outLayout = sHandleImporter.lockYCbCr(
1718 *(halBuf.bufPtr), halBuf.usage, outRect);
1719 ALOGV("%s: outLayout y %p cb %p cr %p y_str %d c_str %d c_step %d",
1720 __FUNCTION__, outLayout.y, outLayout.cb, outLayout.cr,
1721 outLayout.yStride, outLayout.cStride, outLayout.chromaStep);
1722
1723 // Convert to output buffer size/format
1724 uint32_t outputFourcc = getFourCcFromLayout(outLayout);
1725 ALOGV("%s: converting to format %c%c%c%c", __FUNCTION__,
1726 outputFourcc & 0xFF,
1727 (outputFourcc >> 8) & 0xFF,
1728 (outputFourcc >> 16) & 0xFF,
1729 (outputFourcc >> 24) & 0xFF);
1730
1731 YCbCrLayout cropAndScaled;
1732 int ret = cropAndScaleLocked(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001733 mYu12Frame,
1734 Size { halBuf.width, halBuf.height },
1735 &cropAndScaled);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001736 if (ret != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001737 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001738 return onDeviceError("%s: crop and scale failed!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001739 }
1740
1741 Size sz {halBuf.width, halBuf.height};
1742 ret = formatConvertLocked(cropAndScaled, outLayout, sz, outputFourcc);
1743 if (ret != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001744 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001745 return onDeviceError("%s: format coversion failed!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001746 }
1747 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
1748 if (relFence > 0) {
1749 halBuf.acquireFence = relFence;
1750 }
1751 } break;
1752 default:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001753 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001754 return onDeviceError("%s: unknown output format %x", __FUNCTION__, halBuf.format);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001755 }
1756 } // for each buffer
1757 mScaledYu12Frames.clear();
1758
1759 // Don't hold the lock while calling back to parent
1760 lk.unlock();
1761 Status st = parent->processCaptureResult(req);
1762 if (st != Status::OK) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001763 return onDeviceError("%s: failed to process capture result!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001764 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001765 signalRequestDone();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001766 return true;
1767}
1768
1769Status ExternalCameraDeviceSession::OutputThread::allocateIntermediateBuffers(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001770 const Size& v4lSize, const Size& thumbSize,
1771 const hidl_vec<Stream>& streams) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001772 std::lock_guard<std::mutex> lk(mBufferLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001773 if (mScaledYu12Frames.size() != 0) {
1774 ALOGE("%s: intermediate buffer pool has %zu inflight buffers! (expect 0)",
1775 __FUNCTION__, mScaledYu12Frames.size());
1776 return Status::INTERNAL_ERROR;
1777 }
1778
1779 // Allocating intermediate YU12 frame
1780 if (mYu12Frame == nullptr || mYu12Frame->mWidth != v4lSize.width ||
1781 mYu12Frame->mHeight != v4lSize.height) {
1782 mYu12Frame.clear();
1783 mYu12Frame = new AllocatedFrame(v4lSize.width, v4lSize.height);
1784 int ret = mYu12Frame->allocate(&mYu12FrameLayout);
1785 if (ret != 0) {
1786 ALOGE("%s: allocating YU12 frame failed!", __FUNCTION__);
1787 return Status::INTERNAL_ERROR;
1788 }
1789 }
1790
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001791 // Allocating intermediate YU12 thumbnail frame
1792 if (mYu12ThumbFrame == nullptr ||
1793 mYu12ThumbFrame->mWidth != thumbSize.width ||
1794 mYu12ThumbFrame->mHeight != thumbSize.height) {
1795 mYu12ThumbFrame.clear();
1796 mYu12ThumbFrame = new AllocatedFrame(thumbSize.width, thumbSize.height);
1797 int ret = mYu12ThumbFrame->allocate(&mYu12ThumbFrameLayout);
1798 if (ret != 0) {
1799 ALOGE("%s: allocating YU12 thumb frame failed!", __FUNCTION__);
1800 return Status::INTERNAL_ERROR;
1801 }
1802 }
1803
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001804 // Allocating scaled buffers
1805 for (const auto& stream : streams) {
1806 Size sz = {stream.width, stream.height};
1807 if (sz == v4lSize) {
1808 continue; // Don't need an intermediate buffer same size as v4lBuffer
1809 }
1810 if (mIntermediateBuffers.count(sz) == 0) {
1811 // Create new intermediate buffer
1812 sp<AllocatedFrame> buf = new AllocatedFrame(stream.width, stream.height);
1813 int ret = buf->allocate();
1814 if (ret != 0) {
1815 ALOGE("%s: allocating intermediate YU12 frame %dx%d failed!",
1816 __FUNCTION__, stream.width, stream.height);
1817 return Status::INTERNAL_ERROR;
1818 }
1819 mIntermediateBuffers[sz] = buf;
1820 }
1821 }
1822
1823 // Remove unconfigured buffers
1824 auto it = mIntermediateBuffers.begin();
1825 while (it != mIntermediateBuffers.end()) {
1826 bool configured = false;
1827 auto sz = it->first;
1828 for (const auto& stream : streams) {
1829 if (stream.width == sz.width && stream.height == sz.height) {
1830 configured = true;
1831 break;
1832 }
1833 }
1834 if (configured) {
1835 it++;
1836 } else {
1837 it = mIntermediateBuffers.erase(it);
1838 }
1839 }
1840 return Status::OK;
1841}
1842
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001843Status ExternalCameraDeviceSession::OutputThread::submitRequest(
1844 const std::shared_ptr<HalRequest>& req) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001845 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001846 mRequestList.push_back(req);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001847 lk.unlock();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001848 mRequestCond.notify_one();
1849 return Status::OK;
1850}
1851
1852void ExternalCameraDeviceSession::OutputThread::flush() {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001853 auto parent = mParent.promote();
1854 if (parent == nullptr) {
1855 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1856 return;
1857 }
1858
1859 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001860 std::list<std::shared_ptr<HalRequest>> reqs = std::move(mRequestList);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001861 mRequestList.clear();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001862 if (mProcessingRequest) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001863 std::chrono::seconds timeout = std::chrono::seconds(kFlushWaitTimeoutSec);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001864 auto st = mRequestDoneCond.wait_for(lk, timeout);
1865 if (st == std::cv_status::timeout) {
1866 ALOGE("%s: wait for inflight request finish timeout!", __FUNCTION__);
1867 }
1868 }
1869
1870 lk.unlock();
1871 for (const auto& req : reqs) {
1872 parent->processCaptureRequestError(req);
1873 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001874}
1875
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001876void ExternalCameraDeviceSession::OutputThread::waitForNextRequest(
1877 std::shared_ptr<HalRequest>* out) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001878 if (out == nullptr) {
1879 ALOGE("%s: out is null", __FUNCTION__);
1880 return;
1881 }
1882
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001883 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001884 int waitTimes = 0;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001885 while (mRequestList.empty()) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001886 if (exitPending()) {
1887 return;
1888 }
1889 std::chrono::milliseconds timeout = std::chrono::milliseconds(kReqWaitTimeoutMs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001890 auto st = mRequestCond.wait_for(lk, timeout);
1891 if (st == std::cv_status::timeout) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001892 waitTimes++;
1893 if (waitTimes == kReqWaitTimesMax) {
1894 // no new request, return
1895 return;
1896 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001897 }
1898 }
1899 *out = mRequestList.front();
1900 mRequestList.pop_front();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001901 mProcessingRequest = true;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001902 mProcessingFrameNumer = (*out)->frameNumber;
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001903}
1904
1905void ExternalCameraDeviceSession::OutputThread::signalRequestDone() {
1906 std::unique_lock<std::mutex> lk(mRequestListLock);
1907 mProcessingRequest = false;
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001908 mProcessingFrameNumer = 0;
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001909 lk.unlock();
1910 mRequestDoneCond.notify_one();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001911}
1912
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001913void ExternalCameraDeviceSession::OutputThread::dump(int fd) {
1914 std::lock_guard<std::mutex> lk(mRequestListLock);
1915 if (mProcessingRequest) {
1916 dprintf(fd, "OutputThread processing frame %d\n", mProcessingFrameNumer);
1917 } else {
1918 dprintf(fd, "OutputThread not processing any frames\n");
1919 }
1920 dprintf(fd, "OutputThread request list contains frame: ");
1921 for (const auto& req : mRequestList) {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001922 dprintf(fd, "%d, ", req->frameNumber);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001923 }
1924 dprintf(fd, "\n");
1925}
1926
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001927void ExternalCameraDeviceSession::cleanupBuffersLocked(int id) {
1928 for (auto& pair : mCirculatingBuffers.at(id)) {
1929 sHandleImporter.freeBuffer(pair.second);
1930 }
1931 mCirculatingBuffers[id].clear();
1932 mCirculatingBuffers.erase(id);
1933}
1934
1935void ExternalCameraDeviceSession::updateBufferCaches(const hidl_vec<BufferCache>& cachesToRemove) {
1936 Mutex::Autolock _l(mLock);
1937 for (auto& cache : cachesToRemove) {
1938 auto cbsIt = mCirculatingBuffers.find(cache.streamId);
1939 if (cbsIt == mCirculatingBuffers.end()) {
1940 // The stream could have been removed
1941 continue;
1942 }
1943 CirculatingBuffers& cbs = cbsIt->second;
1944 auto it = cbs.find(cache.bufferId);
1945 if (it != cbs.end()) {
1946 sHandleImporter.freeBuffer(it->second);
1947 cbs.erase(it);
1948 } else {
1949 ALOGE("%s: stream %d buffer %" PRIu64 " is not cached",
1950 __FUNCTION__, cache.streamId, cache.bufferId);
1951 }
1952 }
1953}
1954
1955bool ExternalCameraDeviceSession::isSupported(const Stream& stream) {
1956 int32_t ds = static_cast<int32_t>(stream.dataSpace);
1957 PixelFormat fmt = stream.format;
1958 uint32_t width = stream.width;
1959 uint32_t height = stream.height;
1960 // TODO: check usage flags
1961
1962 if (stream.streamType != StreamType::OUTPUT) {
1963 ALOGE("%s: does not support non-output stream type", __FUNCTION__);
1964 return false;
1965 }
1966
1967 if (stream.rotation != StreamRotation::ROTATION_0) {
1968 ALOGE("%s: does not support stream rotation", __FUNCTION__);
1969 return false;
1970 }
1971
1972 if (ds & Dataspace::DEPTH) {
1973 ALOGI("%s: does not support depth output", __FUNCTION__);
1974 return false;
1975 }
1976
1977 switch (fmt) {
1978 case PixelFormat::BLOB:
1979 if (ds != static_cast<int32_t>(Dataspace::V0_JFIF)) {
1980 ALOGI("%s: BLOB format does not support dataSpace %x", __FUNCTION__, ds);
1981 return false;
1982 }
1983 case PixelFormat::IMPLEMENTATION_DEFINED:
1984 case PixelFormat::YCBCR_420_888:
1985 case PixelFormat::YV12:
1986 // TODO: check what dataspace we can support here.
1987 // intentional no-ops.
1988 break;
1989 default:
1990 ALOGI("%s: does not support format %x", __FUNCTION__, fmt);
1991 return false;
1992 }
1993
1994 // Assume we can convert any V4L2 format to any of supported output format for now, i.e,
1995 // ignoring v4l2Fmt.fourcc for now. Might need more subtle check if we support more v4l format
1996 // in the futrue.
1997 for (const auto& v4l2Fmt : mSupportedFormats) {
1998 if (width == v4l2Fmt.width && height == v4l2Fmt.height) {
1999 return true;
2000 }
2001 }
2002 ALOGI("%s: resolution %dx%d is not supported", __FUNCTION__, width, height);
2003 return false;
2004}
2005
2006int ExternalCameraDeviceSession::v4l2StreamOffLocked() {
2007 if (!mV4l2Streaming) {
2008 return OK;
2009 }
2010
2011 {
2012 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2013 if (mNumDequeuedV4l2Buffers != 0) {
2014 ALOGE("%s: there are %zu inflight V4L buffers",
2015 __FUNCTION__, mNumDequeuedV4l2Buffers);
2016 return -1;
2017 }
2018 }
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002019 mV4L2BufferCount = 0;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002020
2021 // VIDIOC_STREAMOFF
2022 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2023 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMOFF, &capture_type)) < 0) {
2024 ALOGE("%s: STREAMOFF failed: %s", __FUNCTION__, strerror(errno));
2025 return -errno;
2026 }
2027
2028 // VIDIOC_REQBUFS: clear buffers
2029 v4l2_requestbuffers req_buffers{};
2030 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2031 req_buffers.memory = V4L2_MEMORY_MMAP;
2032 req_buffers.count = 0;
2033 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
2034 ALOGE("%s: REQBUFS failed: %s", __FUNCTION__, strerror(errno));
2035 return -errno;
2036 }
2037
2038 mV4l2Streaming = false;
2039 return OK;
2040}
2041
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002042int ExternalCameraDeviceSession::setV4l2FpsLocked(double fps) {
2043 // VIDIOC_G_PARM/VIDIOC_S_PARM: set fps
2044 v4l2_streamparm streamparm = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
2045 // The following line checks that the driver knows about framerate get/set.
2046 int ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_G_PARM, &streamparm));
2047 if (ret != 0) {
2048 if (errno == -EINVAL) {
2049 ALOGW("%s: device does not support VIDIOC_G_PARM", __FUNCTION__);
2050 }
2051 return -errno;
2052 }
2053 // Now check if the device is able to accept a capture framerate set.
2054 if (!(streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME)) {
2055 ALOGW("%s: device does not support V4L2_CAP_TIMEPERFRAME", __FUNCTION__);
2056 return -EINVAL;
2057 }
2058
2059 // fps is float, approximate by a fraction.
2060 const int kFrameRatePrecision = 10000;
2061 streamparm.parm.capture.timeperframe.numerator = kFrameRatePrecision;
2062 streamparm.parm.capture.timeperframe.denominator =
2063 (fps * kFrameRatePrecision);
2064
2065 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_PARM, &streamparm)) < 0) {
2066 ALOGE("%s: failed to set framerate to %f: %s", __FUNCTION__, fps, strerror(errno));
2067 return -1;
2068 }
2069
2070 double retFps = streamparm.parm.capture.timeperframe.denominator /
2071 static_cast<double>(streamparm.parm.capture.timeperframe.numerator);
2072 if (std::fabs(fps - retFps) > 1.0) {
2073 ALOGE("%s: expect fps %f, got %f instead", __FUNCTION__, fps, retFps);
2074 return -1;
2075 }
2076 mV4l2StreamingFps = fps;
2077 return 0;
2078}
2079
2080int ExternalCameraDeviceSession::configureV4l2StreamLocked(
2081 const SupportedV4L2Format& v4l2Fmt, double requestFps) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002082 int ret = v4l2StreamOffLocked();
2083 if (ret != OK) {
2084 ALOGE("%s: stop v4l2 streaming failed: ret %d", __FUNCTION__, ret);
2085 return ret;
2086 }
2087
2088 // VIDIOC_S_FMT w/h/fmt
2089 v4l2_format fmt;
2090 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2091 fmt.fmt.pix.width = v4l2Fmt.width;
2092 fmt.fmt.pix.height = v4l2Fmt.height;
2093 fmt.fmt.pix.pixelformat = v4l2Fmt.fourcc;
2094 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt));
2095 if (ret < 0) {
2096 ALOGE("%s: S_FMT ioctl failed: %s", __FUNCTION__, strerror(errno));
2097 return -errno;
2098 }
2099
2100 if (v4l2Fmt.width != fmt.fmt.pix.width || v4l2Fmt.height != fmt.fmt.pix.height ||
2101 v4l2Fmt.fourcc != fmt.fmt.pix.pixelformat) {
2102 ALOGE("%s: S_FMT expect %c%c%c%c %dx%d, got %c%c%c%c %dx%d instead!", __FUNCTION__,
2103 v4l2Fmt.fourcc & 0xFF,
2104 (v4l2Fmt.fourcc >> 8) & 0xFF,
2105 (v4l2Fmt.fourcc >> 16) & 0xFF,
2106 (v4l2Fmt.fourcc >> 24) & 0xFF,
2107 v4l2Fmt.width, v4l2Fmt.height,
2108 fmt.fmt.pix.pixelformat & 0xFF,
2109 (fmt.fmt.pix.pixelformat >> 8) & 0xFF,
2110 (fmt.fmt.pix.pixelformat >> 16) & 0xFF,
2111 (fmt.fmt.pix.pixelformat >> 24) & 0xFF,
2112 fmt.fmt.pix.width, fmt.fmt.pix.height);
2113 return -EINVAL;
2114 }
2115 uint32_t bufferSize = fmt.fmt.pix.sizeimage;
2116 ALOGI("%s: V4L2 buffer size is %d", __FUNCTION__, bufferSize);
2117
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002118 const double kDefaultFps = 30.0;
2119 double fps = 1000.0;
2120 if (requestFps != 0.0) {
2121 fps = requestFps;
2122 } else {
2123 double maxFps = -1.0;
2124 // Try to pick the slowest fps that is at least 30
2125 for (const auto& fr : v4l2Fmt.frameRates) {
2126 double f = fr.getDouble();
2127 if (maxFps < f) {
2128 maxFps = f;
2129 }
2130 if (f >= kDefaultFps && f < fps) {
2131 fps = f;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002132 }
2133 }
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002134 if (fps == 1000.0) {
2135 fps = maxFps;
2136 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002137 }
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002138
2139 int fpsRet = setV4l2FpsLocked(fps);
2140 if (fpsRet != 0 && fpsRet != -EINVAL) {
2141 ALOGE("%s: set fps failed: %s", __FUNCTION__, strerror(fpsRet));
2142 return fpsRet;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002143 }
2144
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -08002145 uint32_t v4lBufferCount = (fps >= kDefaultFps) ?
2146 mCfg.numVideoBuffers : mCfg.numStillBuffers;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002147 // VIDIOC_REQBUFS: create buffers
2148 v4l2_requestbuffers req_buffers{};
2149 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2150 req_buffers.memory = V4L2_MEMORY_MMAP;
2151 req_buffers.count = v4lBufferCount;
2152 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
2153 ALOGE("%s: VIDIOC_REQBUFS failed: %s", __FUNCTION__, strerror(errno));
2154 return -errno;
2155 }
2156
2157 // Driver can indeed return more buffer if it needs more to operate
2158 if (req_buffers.count < v4lBufferCount) {
2159 ALOGE("%s: VIDIOC_REQBUFS expected %d buffers, got %d instead",
2160 __FUNCTION__, v4lBufferCount, req_buffers.count);
2161 return NO_MEMORY;
2162 }
2163
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002164 // VIDIOC_QUERYBUF: get buffer offset in the V4L2 fd
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002165 // VIDIOC_QBUF: send buffer to driver
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002166 mV4L2BufferCount = req_buffers.count;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002167 for (uint32_t i = 0; i < req_buffers.count; i++) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002168 v4l2_buffer buffer = {
2169 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
2170 .index = i,
2171 .memory = V4L2_MEMORY_MMAP};
2172
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002173 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QUERYBUF, &buffer)) < 0) {
2174 ALOGE("%s: QUERYBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
2175 return -errno;
2176 }
2177
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002178 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2179 ALOGE("%s: QBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
2180 return -errno;
2181 }
2182 }
2183
2184 // VIDIOC_STREAMON: start streaming
2185 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2186 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type)) < 0) {
2187 ALOGE("%s: VIDIOC_STREAMON failed: %s", __FUNCTION__, strerror(errno));
2188 return -errno;
2189 }
2190
2191 // Swallow first few frames after streamOn to account for bad frames from some devices
2192 for (int i = 0; i < kBadFramesAfterStreamOn; i++) {
2193 v4l2_buffer buffer{};
2194 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2195 buffer.memory = V4L2_MEMORY_MMAP;
2196 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
2197 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
2198 return -errno;
2199 }
2200
2201 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2202 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, buffer.index, strerror(errno));
2203 return -errno;
2204 }
2205 }
2206
2207 mV4l2StreamingFmt = v4l2Fmt;
2208 mV4l2Streaming = true;
2209 return OK;
2210}
2211
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002212sp<V4L2Frame> ExternalCameraDeviceSession::dequeueV4l2FrameLocked(/*out*/nsecs_t* shutterTs) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002213 sp<V4L2Frame> ret = nullptr;
2214
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002215 if (shutterTs == nullptr) {
2216 ALOGE("%s: shutterTs must not be null!", __FUNCTION__);
2217 return ret;
2218 }
2219
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002220 {
2221 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002222 if (mNumDequeuedV4l2Buffers == mV4L2BufferCount) {
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002223 int waitRet = waitForV4L2BufferReturnLocked(lk);
2224 if (waitRet != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002225 return ret;
2226 }
2227 }
2228 }
2229
2230 v4l2_buffer buffer{};
2231 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2232 buffer.memory = V4L2_MEMORY_MMAP;
2233 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
2234 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
2235 return ret;
2236 }
2237
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002238 if (buffer.index >= mV4L2BufferCount) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002239 ALOGE("%s: Invalid buffer id: %d", __FUNCTION__, buffer.index);
2240 return ret;
2241 }
2242
2243 if (buffer.flags & V4L2_BUF_FLAG_ERROR) {
2244 ALOGE("%s: v4l2 buf error! buf flag 0x%x", __FUNCTION__, buffer.flags);
2245 // TODO: try to dequeue again
2246 }
2247
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002248 if (buffer.flags & V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC) {
2249 // Ideally we should also check for V4L2_BUF_FLAG_TSTAMP_SRC_SOE, but
2250 // even V4L2_BUF_FLAG_TSTAMP_SRC_EOF is better than capture a timestamp now
2251 *shutterTs = static_cast<nsecs_t>(buffer.timestamp.tv_sec)*1000000000LL +
2252 buffer.timestamp.tv_usec * 1000LL;
2253 } else {
2254 *shutterTs = systemTime(SYSTEM_TIME_MONOTONIC);
2255 }
2256
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002257 {
2258 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2259 mNumDequeuedV4l2Buffers++;
2260 }
2261 return new V4L2Frame(
2262 mV4l2StreamingFmt.width, mV4l2StreamingFmt.height, mV4l2StreamingFmt.fourcc,
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002263 buffer.index, mV4l2Fd.get(), buffer.bytesused, buffer.m.offset);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002264}
2265
2266void ExternalCameraDeviceSession::enqueueV4l2Frame(const sp<V4L2Frame>& frame) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002267 {
2268 // Release mLock before acquiring mV4l2BufferLock to avoid potential
2269 // deadlock
2270 Mutex::Autolock _l(mLock);
2271 frame->unmap();
2272 v4l2_buffer buffer{};
2273 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2274 buffer.memory = V4L2_MEMORY_MMAP;
2275 buffer.index = frame->mBufferIndex;
2276 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2277 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__,
2278 frame->mBufferIndex, strerror(errno));
2279 return;
2280 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002281 }
2282
2283 {
2284 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2285 mNumDequeuedV4l2Buffers--;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002286 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002287 mV4L2BufferReturned.notify_one();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002288}
2289
2290Status ExternalCameraDeviceSession::configureStreams(
2291 const V3_2::StreamConfiguration& config, V3_3::HalStreamConfiguration* out) {
2292 if (config.operationMode != StreamConfigurationMode::NORMAL_MODE) {
2293 ALOGE("%s: unsupported operation mode: %d", __FUNCTION__, config.operationMode);
2294 return Status::ILLEGAL_ARGUMENT;
2295 }
2296
2297 if (config.streams.size() == 0) {
2298 ALOGE("%s: cannot configure zero stream", __FUNCTION__);
2299 return Status::ILLEGAL_ARGUMENT;
2300 }
2301
2302 int numProcessedStream = 0;
2303 int numStallStream = 0;
2304 for (const auto& stream : config.streams) {
2305 // Check if the format/width/height combo is supported
2306 if (!isSupported(stream)) {
2307 return Status::ILLEGAL_ARGUMENT;
2308 }
2309 if (stream.format == PixelFormat::BLOB) {
2310 numStallStream++;
2311 } else {
2312 numProcessedStream++;
2313 }
2314 }
2315
2316 if (numProcessedStream > kMaxProcessedStream) {
2317 ALOGE("%s: too many processed streams (expect <= %d, got %d)", __FUNCTION__,
2318 kMaxProcessedStream, numProcessedStream);
2319 return Status::ILLEGAL_ARGUMENT;
2320 }
2321
2322 if (numStallStream > kMaxStallStream) {
2323 ALOGE("%s: too many stall streams (expect <= %d, got %d)", __FUNCTION__,
2324 kMaxStallStream, numStallStream);
2325 return Status::ILLEGAL_ARGUMENT;
2326 }
2327
2328 Status status = initStatus();
2329 if (status != Status::OK) {
2330 return status;
2331 }
2332
2333 Mutex::Autolock _l(mLock);
2334 if (!mInflightFrames.empty()) {
2335 ALOGE("%s: trying to configureStreams while there are still %zu inflight frames!",
2336 __FUNCTION__, mInflightFrames.size());
2337 return Status::INTERNAL_ERROR;
2338 }
2339
2340 // Add new streams
2341 for (const auto& stream : config.streams) {
2342 if (mStreamMap.count(stream.id) == 0) {
2343 mStreamMap[stream.id] = stream;
2344 mCirculatingBuffers.emplace(stream.id, CirculatingBuffers{});
2345 }
2346 }
2347
2348 // Cleanup removed streams
2349 for(auto it = mStreamMap.begin(); it != mStreamMap.end();) {
2350 int id = it->first;
2351 bool found = false;
2352 for (const auto& stream : config.streams) {
2353 if (id == stream.id) {
2354 found = true;
2355 break;
2356 }
2357 }
2358 if (!found) {
2359 // Unmap all buffers of deleted stream
2360 cleanupBuffersLocked(id);
2361 it = mStreamMap.erase(it);
2362 } else {
2363 ++it;
2364 }
2365 }
2366
2367 // Now select a V4L2 format to produce all output streams
2368 float desiredAr = (mCroppingType == VERTICAL) ? kMaxAspectRatio : kMinAspectRatio;
2369 uint32_t maxDim = 0;
2370 for (const auto& stream : config.streams) {
2371 float aspectRatio = ASPECT_RATIO(stream);
2372 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2373 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2374 desiredAr = aspectRatio;
2375 }
2376
2377 // The dimension that's not cropped
2378 uint32_t dim = (mCroppingType == VERTICAL) ? stream.width : stream.height;
2379 if (dim > maxDim) {
2380 maxDim = dim;
2381 }
2382 }
2383 // Find the smallest format that matches the desired aspect ratio and is wide/high enough
2384 SupportedV4L2Format v4l2Fmt {.width = 0, .height = 0};
2385 for (const auto& fmt : mSupportedFormats) {
2386 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2387 if (dim >= maxDim) {
2388 float aspectRatio = ASPECT_RATIO(fmt);
2389 if (isAspectRatioClose(aspectRatio, desiredAr)) {
2390 v4l2Fmt = fmt;
2391 // since mSupportedFormats is sorted by width then height, the first matching fmt
2392 // will be the smallest one with matching aspect ratio
2393 break;
2394 }
2395 }
2396 }
2397 if (v4l2Fmt.width == 0) {
2398 // Cannot find exact good aspect ratio candidate, try to find a close one
2399 for (const auto& fmt : mSupportedFormats) {
2400 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2401 if (dim >= maxDim) {
2402 float aspectRatio = ASPECT_RATIO(fmt);
2403 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2404 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2405 v4l2Fmt = fmt;
2406 break;
2407 }
2408 }
2409 }
2410 }
2411
2412 if (v4l2Fmt.width == 0) {
2413 ALOGE("%s: unable to find a resolution matching (%s at least %d, aspect ratio %f)"
2414 , __FUNCTION__, (mCroppingType == VERTICAL) ? "width" : "height",
2415 maxDim, desiredAr);
2416 return Status::ILLEGAL_ARGUMENT;
2417 }
2418
2419 if (configureV4l2StreamLocked(v4l2Fmt) != 0) {
2420 ALOGE("V4L configuration failed!, format:%c%c%c%c, w %d, h %d",
2421 v4l2Fmt.fourcc & 0xFF,
2422 (v4l2Fmt.fourcc >> 8) & 0xFF,
2423 (v4l2Fmt.fourcc >> 16) & 0xFF,
2424 (v4l2Fmt.fourcc >> 24) & 0xFF,
2425 v4l2Fmt.width, v4l2Fmt.height);
2426 return Status::INTERNAL_ERROR;
2427 }
2428
2429 Size v4lSize = {v4l2Fmt.width, v4l2Fmt.height};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08002430 Size thumbSize { 0, 0 };
2431 camera_metadata_ro_entry entry =
2432 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
2433 for(uint32_t i = 0; i < entry.count; i += 2) {
2434 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
2435 static_cast<uint32_t>(entry.data.i32[i+1]) };
2436 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
2437 thumbSize = sz;
2438 }
2439 }
2440
2441 if (thumbSize.width * thumbSize.height == 0) {
2442 ALOGE("%s: non-zero thumbnail size not available", __FUNCTION__);
2443 return Status::INTERNAL_ERROR;
2444 }
2445
2446 status = mOutputThread->allocateIntermediateBuffers(v4lSize,
2447 mMaxThumbResolution, config.streams);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002448 if (status != Status::OK) {
2449 ALOGE("%s: allocating intermediate buffers failed!", __FUNCTION__);
2450 return status;
2451 }
2452
2453 out->streams.resize(config.streams.size());
2454 for (size_t i = 0; i < config.streams.size(); i++) {
2455 out->streams[i].overrideDataSpace = config.streams[i].dataSpace;
2456 out->streams[i].v3_2.id = config.streams[i].id;
2457 // TODO: double check should we add those CAMERA flags
2458 mStreamMap[config.streams[i].id].usage =
2459 out->streams[i].v3_2.producerUsage = config.streams[i].usage |
2460 BufferUsage::CPU_WRITE_OFTEN |
2461 BufferUsage::CAMERA_OUTPUT;
2462 out->streams[i].v3_2.consumerUsage = 0;
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002463 out->streams[i].v3_2.maxBuffers = mV4L2BufferCount;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002464
2465 switch (config.streams[i].format) {
2466 case PixelFormat::BLOB:
2467 case PixelFormat::YCBCR_420_888:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002468 case PixelFormat::YV12: // Used by SurfaceTexture
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002469 // No override
2470 out->streams[i].v3_2.overrideFormat = config.streams[i].format;
2471 break;
2472 case PixelFormat::IMPLEMENTATION_DEFINED:
2473 // Override based on VIDEO or not
2474 out->streams[i].v3_2.overrideFormat =
2475 (config.streams[i].usage & BufferUsage::VIDEO_ENCODER) ?
2476 PixelFormat::YCBCR_420_888 : PixelFormat::YV12;
2477 // Save overridden formt in mStreamMap
2478 mStreamMap[config.streams[i].id].format = out->streams[i].v3_2.overrideFormat;
2479 break;
2480 default:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002481 ALOGE("%s: unsupported format 0x%x", __FUNCTION__, config.streams[i].format);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002482 return Status::ILLEGAL_ARGUMENT;
2483 }
2484 }
2485
2486 mFirstRequest = true;
2487 return Status::OK;
2488}
2489
2490bool ExternalCameraDeviceSession::isClosed() {
2491 Mutex::Autolock _l(mLock);
2492 return mClosed;
2493}
2494
2495#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
2496#define UPDATE(md, tag, data, size) \
2497do { \
2498 if ((md).update((tag), (data), (size))) { \
2499 ALOGE("Update " #tag " failed!"); \
2500 return BAD_VALUE; \
2501 } \
2502} while (0)
2503
2504status_t ExternalCameraDeviceSession::initDefaultRequests() {
2505 ::android::hardware::camera::common::V1_0::helper::CameraMetadata md;
2506
2507 const uint8_t aberrationMode = ANDROID_COLOR_CORRECTION_ABERRATION_MODE_OFF;
2508 UPDATE(md, ANDROID_COLOR_CORRECTION_ABERRATION_MODE, &aberrationMode, 1);
2509
2510 const int32_t exposureCompensation = 0;
2511 UPDATE(md, ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION, &exposureCompensation, 1);
2512
2513 const uint8_t videoStabilizationMode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
2514 UPDATE(md, ANDROID_CONTROL_VIDEO_STABILIZATION_MODE, &videoStabilizationMode, 1);
2515
2516 const uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO;
2517 UPDATE(md, ANDROID_CONTROL_AWB_MODE, &awbMode, 1);
2518
2519 const uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON;
2520 UPDATE(md, ANDROID_CONTROL_AE_MODE, &aeMode, 1);
2521
2522 const uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
2523 UPDATE(md, ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
2524
2525 const uint8_t afMode = ANDROID_CONTROL_AF_MODE_AUTO;
2526 UPDATE(md, ANDROID_CONTROL_AF_MODE, &afMode, 1);
2527
2528 const uint8_t afTrigger = ANDROID_CONTROL_AF_TRIGGER_IDLE;
2529 UPDATE(md, ANDROID_CONTROL_AF_TRIGGER, &afTrigger, 1);
2530
2531 const uint8_t sceneMode = ANDROID_CONTROL_SCENE_MODE_DISABLED;
2532 UPDATE(md, ANDROID_CONTROL_SCENE_MODE, &sceneMode, 1);
2533
2534 const uint8_t effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF;
2535 UPDATE(md, ANDROID_CONTROL_EFFECT_MODE, &effectMode, 1);
2536
2537 const uint8_t flashMode = ANDROID_FLASH_MODE_OFF;
2538 UPDATE(md, ANDROID_FLASH_MODE, &flashMode, 1);
2539
2540 const int32_t thumbnailSize[] = {240, 180};
2541 UPDATE(md, ANDROID_JPEG_THUMBNAIL_SIZE, thumbnailSize, 2);
2542
2543 const uint8_t jpegQuality = 90;
2544 UPDATE(md, ANDROID_JPEG_QUALITY, &jpegQuality, 1);
2545 UPDATE(md, ANDROID_JPEG_THUMBNAIL_QUALITY, &jpegQuality, 1);
2546
2547 const int32_t jpegOrientation = 0;
2548 UPDATE(md, ANDROID_JPEG_ORIENTATION, &jpegOrientation, 1);
2549
2550 const uint8_t oisMode = ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF;
2551 UPDATE(md, ANDROID_LENS_OPTICAL_STABILIZATION_MODE, &oisMode, 1);
2552
2553 const uint8_t nrMode = ANDROID_NOISE_REDUCTION_MODE_OFF;
2554 UPDATE(md, ANDROID_NOISE_REDUCTION_MODE, &nrMode, 1);
2555
2556 const uint8_t fdMode = ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
2557 UPDATE(md, ANDROID_STATISTICS_FACE_DETECT_MODE, &fdMode, 1);
2558
2559 const uint8_t hotpixelMode = ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF;
2560 UPDATE(md, ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE, &hotpixelMode, 1);
2561
2562 bool support30Fps = false;
2563 int32_t maxFps = std::numeric_limits<int32_t>::min();
2564 for (const auto& supportedFormat : mSupportedFormats) {
Yin-Chia Yeh134093a2018-02-12 14:05:48 -08002565 for (const auto& fr : supportedFormat.frameRates) {
2566 int32_t framerateInt = static_cast<int32_t>(fr.getDouble());
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002567 if (maxFps < framerateInt) {
2568 maxFps = framerateInt;
2569 }
2570 if (framerateInt == 30) {
2571 support30Fps = true;
2572 break;
2573 }
2574 }
2575 if (support30Fps) {
2576 break;
2577 }
2578 }
2579 int32_t defaultFramerate = support30Fps ? 30 : maxFps;
2580 int32_t defaultFpsRange[] = {defaultFramerate, defaultFramerate};
2581 UPDATE(md, ANDROID_CONTROL_AE_TARGET_FPS_RANGE, defaultFpsRange, ARRAY_SIZE(defaultFpsRange));
2582
2583 uint8_t antibandingMode = ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO;
2584 UPDATE(md, ANDROID_CONTROL_AE_ANTIBANDING_MODE, &antibandingMode, 1);
2585
2586 const uint8_t controlMode = ANDROID_CONTROL_MODE_AUTO;
2587 UPDATE(md, ANDROID_CONTROL_MODE, &controlMode, 1);
2588
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002589 auto requestTemplates = hidl_enum_iterator<RequestTemplate>();
2590 for (RequestTemplate type : requestTemplates) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002591 ::android::hardware::camera::common::V1_0::helper::CameraMetadata mdCopy = md;
2592 uint8_t intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2593 switch (type) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002594 case RequestTemplate::PREVIEW:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002595 intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2596 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002597 case RequestTemplate::STILL_CAPTURE:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002598 intent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE;
2599 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002600 case RequestTemplate::VIDEO_RECORD:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002601 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD;
2602 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002603 case RequestTemplate::VIDEO_SNAPSHOT:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002604 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT;
2605 break;
2606 default:
Yuriy Romanenko083de0c2018-01-26 16:05:54 -08002607 ALOGV("%s: unsupported RequestTemplate type %d", __FUNCTION__, type);
2608 continue;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002609 }
2610 UPDATE(mdCopy, ANDROID_CONTROL_CAPTURE_INTENT, &intent, 1);
2611
2612 camera_metadata_t* rawMd = mdCopy.release();
2613 CameraMetadata hidlMd;
2614 hidlMd.setToExternal(
2615 (uint8_t*) rawMd, get_camera_metadata_size(rawMd));
2616 mDefaultRequests[type] = hidlMd;
2617 free_camera_metadata(rawMd);
2618 }
2619
2620 return OK;
2621}
2622
2623status_t ExternalCameraDeviceSession::fillCaptureResult(
2624 common::V1_0::helper::CameraMetadata &md, nsecs_t timestamp) {
2625 // android.control
2626 // For USB camera, we don't know the AE state. Set the state to converged to
2627 // indicate the frame should be good to use. Then apps don't have to wait the
2628 // AE state.
2629 const uint8_t aeState = ANDROID_CONTROL_AE_STATE_CONVERGED;
2630 UPDATE(md, ANDROID_CONTROL_AE_STATE, &aeState, 1);
2631
2632 const uint8_t ae_lock = ANDROID_CONTROL_AE_LOCK_OFF;
2633 UPDATE(md, ANDROID_CONTROL_AE_LOCK, &ae_lock, 1);
2634
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002635 bool afTrigger = mAfTrigger;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002636 if (md.exists(ANDROID_CONTROL_AF_TRIGGER)) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002637 Mutex::Autolock _l(mLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002638 camera_metadata_entry entry = md.find(ANDROID_CONTROL_AF_TRIGGER);
2639 if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_START) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002640 mAfTrigger = afTrigger = true;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002641 } else if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_CANCEL) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002642 mAfTrigger = afTrigger = false;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002643 }
2644 }
2645
2646 // For USB camera, the USB camera handles everything and we don't have control
2647 // over AF. We only simply fake the AF metadata based on the request
2648 // received here.
2649 uint8_t afState;
2650 if (afTrigger) {
2651 afState = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
2652 } else {
2653 afState = ANDROID_CONTROL_AF_STATE_INACTIVE;
2654 }
2655 UPDATE(md, ANDROID_CONTROL_AF_STATE, &afState, 1);
2656
2657 // Set AWB state to converged to indicate the frame should be good to use.
2658 const uint8_t awbState = ANDROID_CONTROL_AWB_STATE_CONVERGED;
2659 UPDATE(md, ANDROID_CONTROL_AWB_STATE, &awbState, 1);
2660
2661 const uint8_t awbLock = ANDROID_CONTROL_AWB_LOCK_OFF;
2662 UPDATE(md, ANDROID_CONTROL_AWB_LOCK, &awbLock, 1);
2663
2664 camera_metadata_ro_entry active_array_size =
2665 mCameraCharacteristics.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
2666
2667 if (active_array_size.count == 0) {
2668 ALOGE("%s: cannot find active array size!", __FUNCTION__);
2669 return -EINVAL;
2670 }
2671
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002672 const uint8_t flashState = ANDROID_FLASH_STATE_UNAVAILABLE;
2673 UPDATE(md, ANDROID_FLASH_STATE, &flashState, 1);
2674
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002675 // android.scaler
2676 const int32_t crop_region[] = {
2677 active_array_size.data.i32[0], active_array_size.data.i32[1],
2678 active_array_size.data.i32[2], active_array_size.data.i32[3],
2679 };
2680 UPDATE(md, ANDROID_SCALER_CROP_REGION, crop_region, ARRAY_SIZE(crop_region));
2681
2682 // android.sensor
2683 UPDATE(md, ANDROID_SENSOR_TIMESTAMP, &timestamp, 1);
2684
2685 // android.statistics
2686 const uint8_t lensShadingMapMode = ANDROID_STATISTICS_LENS_SHADING_MAP_MODE_OFF;
2687 UPDATE(md, ANDROID_STATISTICS_LENS_SHADING_MAP_MODE, &lensShadingMapMode, 1);
2688
2689 const uint8_t sceneFlicker = ANDROID_STATISTICS_SCENE_FLICKER_NONE;
2690 UPDATE(md, ANDROID_STATISTICS_SCENE_FLICKER, &sceneFlicker, 1);
2691
2692 return OK;
2693}
2694
2695#undef ARRAY_SIZE
2696#undef UPDATE
2697
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002698} // namespace implementation
2699} // namespace V3_4
2700} // namespace device
2701} // namespace camera
2702} // namespace hardware
2703} // namespace android