blob: 55694398e7ed9773462c0652702eb5cdfbb48d91 [file] [log] [blame]
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#define LOG_TAG "ExtCamDevSsn@3.4"
17//#define LOG_NDEBUG 0
Yin-Chia Yehe99cf202018-02-28 11:30:38 -080018#define ATRACE_TAG ATRACE_TAG_CAMERA
Yin-Chia Yeh19030592017-10-19 17:30:11 -070019#include <log/log.h>
20
21#include <inttypes.h>
22#include "ExternalCameraDeviceSession.h"
23
24#include "android-base/macros.h"
Yin-Chia Yeh19030592017-10-19 17:30:11 -070025#include <utils/Timers.h>
Yin-Chia Yehe99cf202018-02-28 11:30:38 -080026#include <utils/Trace.h>
Yin-Chia Yeh19030592017-10-19 17:30:11 -070027#include <linux/videodev2.h>
28#include <sync/sync.h>
29
30#define HAVE_JPEG // required for libyuv.h to export MJPEG decode APIs
31#include <libyuv.h>
32
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -080033#include <jpeglib.h>
34
35
Yin-Chia Yeh19030592017-10-19 17:30:11 -070036namespace android {
37namespace hardware {
38namespace camera {
39namespace device {
40namespace V3_4 {
41namespace implementation {
42
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080043namespace {
Yin-Chia Yeh19030592017-10-19 17:30:11 -070044// Size of request/result metadata fast message queue. Change to 0 to always use hwbinder buffer.
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080045static constexpr size_t kMetadataMsgQueueSize = 1 << 18 /* 256kB */;
46
Yin-Chia Yeh19030592017-10-19 17:30:11 -070047const int kBadFramesAfterStreamOn = 1; // drop x frames after streamOn to get rid of some initial
48 // bad frames. TODO: develop a better bad frame detection
49 // method
50
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -080051bool tryLock(Mutex& mutex)
52{
53 static const int kDumpLockRetries = 50;
54 static const int kDumpLockSleep = 60000;
55 bool locked = false;
56 for (int i = 0; i < kDumpLockRetries; ++i) {
57 if (mutex.tryLock() == NO_ERROR) {
58 locked = true;
59 break;
60 }
61 usleep(kDumpLockSleep);
62 }
63 return locked;
64}
65
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080066} // Anonymous namespace
Yin-Chia Yeh19030592017-10-19 17:30:11 -070067
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080068// Static instances
69const int ExternalCameraDeviceSession::kMaxProcessedStream;
70const int ExternalCameraDeviceSession::kMaxStallStream;
Yin-Chia Yeh19030592017-10-19 17:30:11 -070071HandleImporter ExternalCameraDeviceSession::sHandleImporter;
72
Yin-Chia Yeh19030592017-10-19 17:30:11 -070073ExternalCameraDeviceSession::ExternalCameraDeviceSession(
74 const sp<ICameraDeviceCallback>& callback,
Yin-Chia Yeh17982492018-02-05 17:41:01 -080075 const ExternalCameraConfig& cfg,
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080076 const std::vector<SupportedV4L2Format>& sortedFormats,
77 const CroppingType& croppingType,
Yin-Chia Yeh19030592017-10-19 17:30:11 -070078 const common::V1_0::helper::CameraMetadata& chars,
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -080079 const std::string& cameraId,
Yin-Chia Yeh19030592017-10-19 17:30:11 -070080 unique_fd v4l2Fd) :
81 mCallback(callback),
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080082 mCfg(cfg),
Yin-Chia Yeh19030592017-10-19 17:30:11 -070083 mCameraCharacteristics(chars),
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080084 mSupportedFormats(sortedFormats),
85 mCroppingType(croppingType),
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -080086 mCameraId(cameraId),
Yin-Chia Yeh19030592017-10-19 17:30:11 -070087 mV4l2Fd(std::move(v4l2Fd)),
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -080088 mOutputThread(new OutputThread(this, mCroppingType)),
89 mMaxThumbResolution(getMaxThumbResolution()),
90 mMaxJpegResolution(getMaxJpegResolution()) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -070091 mInitFail = initialize();
92}
93
Yin-Chia Yeh19030592017-10-19 17:30:11 -070094bool ExternalCameraDeviceSession::initialize() {
95 if (mV4l2Fd.get() < 0) {
96 ALOGE("%s: invalid v4l2 device fd %d!", __FUNCTION__, mV4l2Fd.get());
97 return true;
98 }
99
100 status_t status = initDefaultRequests();
101 if (status != OK) {
102 ALOGE("%s: init default requests failed!", __FUNCTION__);
103 return true;
104 }
105
106 mRequestMetadataQueue = std::make_unique<RequestMetadataQueue>(
107 kMetadataMsgQueueSize, false /* non blocking */);
108 if (!mRequestMetadataQueue->isValid()) {
109 ALOGE("%s: invalid request fmq", __FUNCTION__);
110 return true;
111 }
112 mResultMetadataQueue = std::make_shared<RequestMetadataQueue>(
113 kMetadataMsgQueueSize, false /* non blocking */);
114 if (!mResultMetadataQueue->isValid()) {
115 ALOGE("%s: invalid result fmq", __FUNCTION__);
116 return true;
117 }
118
119 // TODO: check is PRIORITY_DISPLAY enough?
120 mOutputThread->run("ExtCamOut", PRIORITY_DISPLAY);
121 return false;
122}
123
124Status ExternalCameraDeviceSession::initStatus() const {
125 Mutex::Autolock _l(mLock);
126 Status status = Status::OK;
127 if (mInitFail || mClosed) {
128 ALOGI("%s: sesssion initFailed %d closed %d", __FUNCTION__, mInitFail, mClosed);
129 status = Status::INTERNAL_ERROR;
130 }
131 return status;
132}
133
134ExternalCameraDeviceSession::~ExternalCameraDeviceSession() {
135 if (!isClosed()) {
136 ALOGE("ExternalCameraDeviceSession deleted before close!");
137 close();
138 }
139}
140
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800141
142void ExternalCameraDeviceSession::dumpState(const native_handle_t* handle) {
143 if (handle->numFds != 1 || handle->numInts != 0) {
144 ALOGE("%s: handle must contain 1 FD and 0 integers! Got %d FDs and %d ints",
145 __FUNCTION__, handle->numFds, handle->numInts);
146 return;
147 }
148 int fd = handle->data[0];
149
150 bool intfLocked = tryLock(mInterfaceLock);
151 if (!intfLocked) {
152 dprintf(fd, "!! ExternalCameraDeviceSession interface may be deadlocked !!\n");
153 }
154
155 if (isClosed()) {
156 dprintf(fd, "External camera %s is closed\n", mCameraId.c_str());
157 return;
158 }
159
160 bool streaming = false;
161 size_t v4L2BufferCount = 0;
162 SupportedV4L2Format streamingFmt;
163 std::unordered_set<uint32_t> inflightFrames;
164 {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800165 bool sessionLocked = tryLock(mLock);
166 if (!sessionLocked) {
167 dprintf(fd, "!! ExternalCameraDeviceSession mLock may be deadlocked !!\n");
168 }
169 streaming = mV4l2Streaming;
170 streamingFmt = mV4l2StreamingFmt;
171 v4L2BufferCount = mV4L2BufferCount;
172 inflightFrames = mInflightFrames;
173 if (sessionLocked) {
174 mLock.unlock();
175 }
176 }
177
178 dprintf(fd, "External camera %s V4L2 FD %d, cropping type %s, %s\n",
179 mCameraId.c_str(), mV4l2Fd.get(),
180 (mCroppingType == VERTICAL) ? "vertical" : "horizontal",
181 streaming ? "streaming" : "not streaming");
182 if (streaming) {
183 // TODO: dump fps later
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800184 dprintf(fd, "Current V4L2 format %c%c%c%c %dx%d @ %ffps\n",
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800185 streamingFmt.fourcc & 0xFF,
186 (streamingFmt.fourcc >> 8) & 0xFF,
187 (streamingFmt.fourcc >> 16) & 0xFF,
188 (streamingFmt.fourcc >> 24) & 0xFF,
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800189 streamingFmt.width, streamingFmt.height,
190 mV4l2StreamingFps);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800191
192 size_t numDequeuedV4l2Buffers = 0;
193 {
194 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
195 numDequeuedV4l2Buffers = mNumDequeuedV4l2Buffers;
196 }
197 dprintf(fd, "V4L2 buffer queue size %zu, dequeued %zu\n",
198 v4L2BufferCount, numDequeuedV4l2Buffers);
199 }
200
201 dprintf(fd, "In-flight frames (not sorted):");
202 for (const auto& frameNumber : inflightFrames) {
203 dprintf(fd, "%d, ", frameNumber);
204 }
205 dprintf(fd, "\n");
206 mOutputThread->dump(fd);
207 dprintf(fd, "\n");
208
209 if (intfLocked) {
210 mInterfaceLock.unlock();
211 }
212
213 return;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700214}
215
216Return<void> ExternalCameraDeviceSession::constructDefaultRequestSettings(
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800217 V3_2::RequestTemplate type,
218 V3_2::ICameraDeviceSession::constructDefaultRequestSettings_cb _hidl_cb) {
219 V3_2::CameraMetadata outMetadata;
220 Status status = constructDefaultRequestSettingsRaw(
221 static_cast<RequestTemplate>(type), &outMetadata);
222 _hidl_cb(status, outMetadata);
223 return Void();
224}
225
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800226Status ExternalCameraDeviceSession::constructDefaultRequestSettingsRaw(RequestTemplate type,
227 V3_2::CameraMetadata *outMetadata) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700228 CameraMetadata emptyMd;
229 Status status = initStatus();
230 if (status != Status::OK) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800231 return status;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700232 }
233
234 switch (type) {
235 case RequestTemplate::PREVIEW:
236 case RequestTemplate::STILL_CAPTURE:
237 case RequestTemplate::VIDEO_RECORD:
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800238 case RequestTemplate::VIDEO_SNAPSHOT: {
239 *outMetadata = mDefaultRequests[type];
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700240 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800241 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700242 case RequestTemplate::MANUAL:
243 case RequestTemplate::ZERO_SHUTTER_LAG:
Eino-Ville Talvala0a2a9fc2018-02-05 16:27:15 -0800244 // Don't support MANUAL, ZSL templates
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800245 status = Status::ILLEGAL_ARGUMENT;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700246 break;
247 default:
248 ALOGE("%s: unknown request template type %d", __FUNCTION__, static_cast<int>(type));
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800249 status = Status::ILLEGAL_ARGUMENT;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700250 break;
251 }
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800252 return status;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700253}
254
255Return<void> ExternalCameraDeviceSession::configureStreams(
256 const V3_2::StreamConfiguration& streams,
257 ICameraDeviceSession::configureStreams_cb _hidl_cb) {
258 V3_2::HalStreamConfiguration outStreams;
259 V3_3::HalStreamConfiguration outStreams_v33;
260 Mutex::Autolock _il(mInterfaceLock);
261
262 Status status = configureStreams(streams, &outStreams_v33);
263 size_t size = outStreams_v33.streams.size();
264 outStreams.streams.resize(size);
265 for (size_t i = 0; i < size; i++) {
266 outStreams.streams[i] = outStreams_v33.streams[i].v3_2;
267 }
268 _hidl_cb(status, outStreams);
269 return Void();
270}
271
272Return<void> ExternalCameraDeviceSession::configureStreams_3_3(
273 const V3_2::StreamConfiguration& streams,
274 ICameraDeviceSession::configureStreams_3_3_cb _hidl_cb) {
275 V3_3::HalStreamConfiguration outStreams;
276 Mutex::Autolock _il(mInterfaceLock);
277
278 Status status = configureStreams(streams, &outStreams);
279 _hidl_cb(status, outStreams);
280 return Void();
281}
282
283Return<void> ExternalCameraDeviceSession::configureStreams_3_4(
284 const V3_4::StreamConfiguration& requestedConfiguration,
285 ICameraDeviceSession::configureStreams_3_4_cb _hidl_cb) {
286 V3_2::StreamConfiguration config_v32;
287 V3_3::HalStreamConfiguration outStreams_v33;
288 Mutex::Autolock _il(mInterfaceLock);
289
290 config_v32.operationMode = requestedConfiguration.operationMode;
291 config_v32.streams.resize(requestedConfiguration.streams.size());
292 for (size_t i = 0; i < config_v32.streams.size(); i++) {
293 config_v32.streams[i] = requestedConfiguration.streams[i].v3_2;
294 }
295
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700296 Status status = configureStreams(config_v32, &outStreams_v33);
297
298 V3_4::HalStreamConfiguration outStreams;
299 outStreams.streams.resize(outStreams_v33.streams.size());
300 for (size_t i = 0; i < outStreams.streams.size(); i++) {
301 outStreams.streams[i].v3_3 = outStreams_v33.streams[i];
302 }
303 _hidl_cb(status, outStreams);
304 return Void();
305}
306
307Return<void> ExternalCameraDeviceSession::getCaptureRequestMetadataQueue(
308 ICameraDeviceSession::getCaptureRequestMetadataQueue_cb _hidl_cb) {
309 Mutex::Autolock _il(mInterfaceLock);
310 _hidl_cb(*mRequestMetadataQueue->getDesc());
311 return Void();
312}
313
314Return<void> ExternalCameraDeviceSession::getCaptureResultMetadataQueue(
315 ICameraDeviceSession::getCaptureResultMetadataQueue_cb _hidl_cb) {
316 Mutex::Autolock _il(mInterfaceLock);
317 _hidl_cb(*mResultMetadataQueue->getDesc());
318 return Void();
319}
320
321Return<void> ExternalCameraDeviceSession::processCaptureRequest(
322 const hidl_vec<CaptureRequest>& requests,
323 const hidl_vec<BufferCache>& cachesToRemove,
324 ICameraDeviceSession::processCaptureRequest_cb _hidl_cb) {
325 Mutex::Autolock _il(mInterfaceLock);
326 updateBufferCaches(cachesToRemove);
327
328 uint32_t numRequestProcessed = 0;
329 Status s = Status::OK;
330 for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
331 s = processOneCaptureRequest(requests[i]);
332 if (s != Status::OK) {
333 break;
334 }
335 }
336
337 _hidl_cb(s, numRequestProcessed);
338 return Void();
339}
340
341Return<void> ExternalCameraDeviceSession::processCaptureRequest_3_4(
342 const hidl_vec<V3_4::CaptureRequest>& requests,
343 const hidl_vec<V3_2::BufferCache>& cachesToRemove,
344 ICameraDeviceSession::processCaptureRequest_3_4_cb _hidl_cb) {
345 Mutex::Autolock _il(mInterfaceLock);
346 updateBufferCaches(cachesToRemove);
347
348 uint32_t numRequestProcessed = 0;
349 Status s = Status::OK;
350 for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
351 s = processOneCaptureRequest(requests[i].v3_2);
352 if (s != Status::OK) {
353 break;
354 }
355 }
356
357 _hidl_cb(s, numRequestProcessed);
358 return Void();
359}
360
361Return<Status> ExternalCameraDeviceSession::flush() {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -0800362 ATRACE_CALL();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -0800363 Mutex::Autolock _il(mInterfaceLock);
364 Status status = initStatus();
365 if (status != Status::OK) {
366 return status;
367 }
368 mOutputThread->flush();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700369 return Status::OK;
370}
371
372Return<void> ExternalCameraDeviceSession::close() {
373 Mutex::Autolock _il(mInterfaceLock);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800374 bool closed = isClosed();
375 if (!closed) {
376 mOutputThread->flush();
377 mOutputThread->requestExit();
378 mOutputThread->join();
379
380 Mutex::Autolock _l(mLock);
381 // free all buffers
382 for(auto pair : mStreamMap) {
383 cleanupBuffersLocked(/*Stream ID*/pair.first);
384 }
385 v4l2StreamOffLocked();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700386 ALOGV("%s: closing V4L2 camera FD %d", __FUNCTION__, mV4l2Fd.get());
387 mV4l2Fd.reset();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700388 mClosed = true;
389 }
390 return Void();
391}
392
393Status ExternalCameraDeviceSession::importRequest(
394 const CaptureRequest& request,
395 hidl_vec<buffer_handle_t*>& allBufPtrs,
396 hidl_vec<int>& allFences) {
397 size_t numOutputBufs = request.outputBuffers.size();
398 size_t numBufs = numOutputBufs;
399 // Validate all I/O buffers
400 hidl_vec<buffer_handle_t> allBufs;
401 hidl_vec<uint64_t> allBufIds;
402 allBufs.resize(numBufs);
403 allBufIds.resize(numBufs);
404 allBufPtrs.resize(numBufs);
405 allFences.resize(numBufs);
406 std::vector<int32_t> streamIds(numBufs);
407
408 for (size_t i = 0; i < numOutputBufs; i++) {
409 allBufs[i] = request.outputBuffers[i].buffer.getNativeHandle();
410 allBufIds[i] = request.outputBuffers[i].bufferId;
411 allBufPtrs[i] = &allBufs[i];
412 streamIds[i] = request.outputBuffers[i].streamId;
413 }
414
415 for (size_t i = 0; i < numBufs; i++) {
416 buffer_handle_t buf = allBufs[i];
417 uint64_t bufId = allBufIds[i];
418 CirculatingBuffers& cbs = mCirculatingBuffers[streamIds[i]];
419 if (cbs.count(bufId) == 0) {
420 if (buf == nullptr) {
421 ALOGE("%s: bufferId %" PRIu64 " has null buffer handle!", __FUNCTION__, bufId);
422 return Status::ILLEGAL_ARGUMENT;
423 }
424 // Register a newly seen buffer
425 buffer_handle_t importedBuf = buf;
426 sHandleImporter.importBuffer(importedBuf);
427 if (importedBuf == nullptr) {
428 ALOGE("%s: output buffer %zu is invalid!", __FUNCTION__, i);
429 return Status::INTERNAL_ERROR;
430 } else {
431 cbs[bufId] = importedBuf;
432 }
433 }
434 allBufPtrs[i] = &cbs[bufId];
435 }
436
437 // All buffers are imported. Now validate output buffer acquire fences
438 for (size_t i = 0; i < numOutputBufs; i++) {
439 if (!sHandleImporter.importFence(
440 request.outputBuffers[i].acquireFence, allFences[i])) {
441 ALOGE("%s: output buffer %zu acquire fence is invalid", __FUNCTION__, i);
442 cleanupInflightFences(allFences, i);
443 return Status::INTERNAL_ERROR;
444 }
445 }
446 return Status::OK;
447}
448
449void ExternalCameraDeviceSession::cleanupInflightFences(
450 hidl_vec<int>& allFences, size_t numFences) {
451 for (size_t j = 0; j < numFences; j++) {
452 sHandleImporter.closeFence(allFences[j]);
453 }
454}
455
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800456int ExternalCameraDeviceSession::waitForV4L2BufferReturnLocked(std::unique_lock<std::mutex>& lk) {
457 std::chrono::seconds timeout = std::chrono::seconds(kBufferWaitTimeoutSec);
458 mLock.unlock();
459 auto st = mV4L2BufferReturned.wait_for(lk, timeout);
460 // Here we introduce a order where mV4l2BufferLock is acquired before mLock, while
461 // the normal lock acquisition order is reversed. This is fine because in most of
462 // cases we are protected by mInterfaceLock. The only thread that can cause deadlock
463 // is the OutputThread, where we do need to make sure we don't acquire mLock then
464 // mV4l2BufferLock
465 mLock.lock();
466 if (st == std::cv_status::timeout) {
467 ALOGE("%s: wait for V4L2 buffer return timeout!", __FUNCTION__);
468 return -1;
469 }
470 return 0;
471}
472
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700473Status ExternalCameraDeviceSession::processOneCaptureRequest(const CaptureRequest& request) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -0800474 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700475 Status status = initStatus();
476 if (status != Status::OK) {
477 return status;
478 }
479
480 if (request.inputBuffer.streamId != -1) {
481 ALOGE("%s: external camera does not support reprocessing!", __FUNCTION__);
482 return Status::ILLEGAL_ARGUMENT;
483 }
484
485 Mutex::Autolock _l(mLock);
486 if (!mV4l2Streaming) {
487 ALOGE("%s: cannot process request in streamOff state!", __FUNCTION__);
488 return Status::INTERNAL_ERROR;
489 }
490
491 const camera_metadata_t *rawSettings = nullptr;
492 bool converted = true;
493 CameraMetadata settingsFmq; // settings from FMQ
494 if (request.fmqSettingsSize > 0) {
495 // non-blocking read; client must write metadata before calling
496 // processOneCaptureRequest
497 settingsFmq.resize(request.fmqSettingsSize);
498 bool read = mRequestMetadataQueue->read(settingsFmq.data(), request.fmqSettingsSize);
499 if (read) {
500 converted = V3_2::implementation::convertFromHidl(settingsFmq, &rawSettings);
501 } else {
502 ALOGE("%s: capture request settings metadata couldn't be read from fmq!", __FUNCTION__);
503 converted = false;
504 }
505 } else {
506 converted = V3_2::implementation::convertFromHidl(request.settings, &rawSettings);
507 }
508
509 if (converted && rawSettings != nullptr) {
510 mLatestReqSetting = rawSettings;
511 }
512
513 if (!converted) {
514 ALOGE("%s: capture request settings metadata is corrupt!", __FUNCTION__);
515 return Status::ILLEGAL_ARGUMENT;
516 }
517
518 if (mFirstRequest && rawSettings == nullptr) {
519 ALOGE("%s: capture request settings must not be null for first request!",
520 __FUNCTION__);
521 return Status::ILLEGAL_ARGUMENT;
522 }
523
524 hidl_vec<buffer_handle_t*> allBufPtrs;
525 hidl_vec<int> allFences;
526 size_t numOutputBufs = request.outputBuffers.size();
527
528 if (numOutputBufs == 0) {
529 ALOGE("%s: capture request must have at least one output buffer!", __FUNCTION__);
530 return Status::ILLEGAL_ARGUMENT;
531 }
532
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800533 camera_metadata_entry fpsRange = mLatestReqSetting.find(ANDROID_CONTROL_AE_TARGET_FPS_RANGE);
534 if (fpsRange.count == 2) {
535 double requestFpsMax = fpsRange.data.i32[1];
536 double closestFps = 0.0;
537 double fpsError = 1000.0;
538 bool fpsSupported = false;
539 for (const auto& fr : mV4l2StreamingFmt.frameRates) {
540 double f = fr.getDouble();
541 if (std::fabs(requestFpsMax - f) < 1.0) {
542 fpsSupported = true;
543 break;
544 }
545 if (std::fabs(requestFpsMax - f) < fpsError) {
546 fpsError = std::fabs(requestFpsMax - f);
547 closestFps = f;
548 }
549 }
550 if (!fpsSupported) {
551 /* This can happen in a few scenarios:
552 * 1. The application is sending a FPS range not supported by the configured outputs.
553 * 2. The application is sending a valid FPS range for all cofigured outputs, but
554 * the selected V4L2 size can only run at slower speed. This should be very rare
555 * though: for this to happen a sensor needs to support at least 3 different aspect
556 * ratio outputs, and when (at least) two outputs are both not the main aspect ratio
557 * of the webcam, a third size that's larger might be picked and runs into this
558 * issue.
559 */
560 ALOGW("%s: cannot reach fps %d! Will do %f instead",
561 __FUNCTION__, fpsRange.data.i32[1], closestFps);
562 requestFpsMax = closestFps;
563 }
564
565 if (requestFpsMax != mV4l2StreamingFps) {
566 {
567 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
568 while (mNumDequeuedV4l2Buffers != 0) {
569 // Wait until pipeline is idle before reconfigure stream
570 int waitRet = waitForV4L2BufferReturnLocked(lk);
571 if (waitRet != 0) {
572 ALOGE("%s: wait for pipeline idle failed!", __FUNCTION__);
573 return Status::INTERNAL_ERROR;
574 }
575 }
576 }
577 configureV4l2StreamLocked(mV4l2StreamingFmt, requestFpsMax);
578 }
579 }
580
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700581 status = importRequest(request, allBufPtrs, allFences);
582 if (status != Status::OK) {
583 return status;
584 }
585
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800586 nsecs_t shutterTs = 0;
587 sp<V4L2Frame> frameIn = dequeueV4l2FrameLocked(&shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700588 if ( frameIn == nullptr) {
589 ALOGE("%s: V4L2 deque frame failed!", __FUNCTION__);
590 return Status::INTERNAL_ERROR;
591 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700592
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800593 std::shared_ptr<HalRequest> halReq = std::make_shared<HalRequest>();
594 halReq->frameNumber = request.frameNumber;
595 halReq->setting = mLatestReqSetting;
596 halReq->frameIn = frameIn;
597 halReq->shutterTs = shutterTs;
598 halReq->buffers.resize(numOutputBufs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700599 for (size_t i = 0; i < numOutputBufs; i++) {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800600 HalStreamBuffer& halBuf = halReq->buffers[i];
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700601 int streamId = halBuf.streamId = request.outputBuffers[i].streamId;
602 halBuf.bufferId = request.outputBuffers[i].bufferId;
603 const Stream& stream = mStreamMap[streamId];
604 halBuf.width = stream.width;
605 halBuf.height = stream.height;
606 halBuf.format = stream.format;
607 halBuf.usage = stream.usage;
608 halBuf.bufPtr = allBufPtrs[i];
609 halBuf.acquireFence = allFences[i];
610 halBuf.fenceTimeout = false;
611 }
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800612 mInflightFrames.insert(halReq->frameNumber);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700613 // Send request to OutputThread for the rest of processing
614 mOutputThread->submitRequest(halReq);
615 mFirstRequest = false;
616 return Status::OK;
617}
618
619void ExternalCameraDeviceSession::notifyShutter(uint32_t frameNumber, nsecs_t shutterTs) {
620 NotifyMsg msg;
621 msg.type = MsgType::SHUTTER;
622 msg.msg.shutter.frameNumber = frameNumber;
623 msg.msg.shutter.timestamp = shutterTs;
624 mCallback->notify({msg});
625}
626
627void ExternalCameraDeviceSession::notifyError(
628 uint32_t frameNumber, int32_t streamId, ErrorCode ec) {
629 NotifyMsg msg;
630 msg.type = MsgType::ERROR;
631 msg.msg.error.frameNumber = frameNumber;
632 msg.msg.error.errorStreamId = streamId;
633 msg.msg.error.errorCode = ec;
634 mCallback->notify({msg});
635}
636
637//TODO: refactor with processCaptureResult
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800638Status ExternalCameraDeviceSession::processCaptureRequestError(
639 const std::shared_ptr<HalRequest>& req) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -0800640 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700641 // Return V4L2 buffer to V4L2 buffer queue
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800642 enqueueV4l2Frame(req->frameIn);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700643
644 // NotifyShutter
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800645 notifyShutter(req->frameNumber, req->shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700646
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800647 notifyError(/*frameNum*/req->frameNumber, /*stream*/-1, ErrorCode::ERROR_REQUEST);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700648
649 // Fill output buffers
650 hidl_vec<CaptureResult> results;
651 results.resize(1);
652 CaptureResult& result = results[0];
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800653 result.frameNumber = req->frameNumber;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700654 result.partialResult = 1;
655 result.inputBuffer.streamId = -1;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800656 result.outputBuffers.resize(req->buffers.size());
657 for (size_t i = 0; i < req->buffers.size(); i++) {
658 result.outputBuffers[i].streamId = req->buffers[i].streamId;
659 result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700660 result.outputBuffers[i].status = BufferStatus::ERROR;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800661 if (req->buffers[i].acquireFence >= 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700662 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800663 handle->data[0] = req->buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800664 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700665 }
666 }
667
668 // update inflight records
669 {
670 Mutex::Autolock _l(mLock);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800671 mInflightFrames.erase(req->frameNumber);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700672 }
673
674 // Callback into framework
675 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
676 freeReleaseFences(results);
677 return Status::OK;
678}
679
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800680Status ExternalCameraDeviceSession::processCaptureResult(std::shared_ptr<HalRequest>& req) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -0800681 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700682 // Return V4L2 buffer to V4L2 buffer queue
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800683 enqueueV4l2Frame(req->frameIn);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700684
685 // NotifyShutter
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800686 notifyShutter(req->frameNumber, req->shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700687
688 // Fill output buffers
689 hidl_vec<CaptureResult> results;
690 results.resize(1);
691 CaptureResult& result = results[0];
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800692 result.frameNumber = req->frameNumber;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700693 result.partialResult = 1;
694 result.inputBuffer.streamId = -1;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800695 result.outputBuffers.resize(req->buffers.size());
696 for (size_t i = 0; i < req->buffers.size(); i++) {
697 result.outputBuffers[i].streamId = req->buffers[i].streamId;
698 result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
699 if (req->buffers[i].fenceTimeout) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700700 result.outputBuffers[i].status = BufferStatus::ERROR;
701 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800702 handle->data[0] = req->buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800703 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800704 notifyError(req->frameNumber, req->buffers[i].streamId, ErrorCode::ERROR_BUFFER);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700705 } else {
706 result.outputBuffers[i].status = BufferStatus::OK;
707 // TODO: refactor
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800708 if (req->buffers[i].acquireFence > 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700709 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800710 handle->data[0] = req->buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800711 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700712 }
713 }
714 }
715
716 // Fill capture result metadata
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800717 fillCaptureResult(req->setting, req->shutterTs);
718 const camera_metadata_t *rawResult = req->setting.getAndLock();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700719 V3_2::implementation::convertToHidl(rawResult, &result.result);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800720 req->setting.unlock(rawResult);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700721
722 // update inflight records
723 {
724 Mutex::Autolock _l(mLock);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800725 mInflightFrames.erase(req->frameNumber);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700726 }
727
728 // Callback into framework
729 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
730 freeReleaseFences(results);
731 return Status::OK;
732}
733
734void ExternalCameraDeviceSession::invokeProcessCaptureResultCallback(
735 hidl_vec<CaptureResult> &results, bool tryWriteFmq) {
736 if (mProcessCaptureResultLock.tryLock() != OK) {
737 const nsecs_t NS_TO_SECOND = 1000000000;
738 ALOGV("%s: previous call is not finished! waiting 1s...", __FUNCTION__);
739 if (mProcessCaptureResultLock.timedLock(/* 1s */NS_TO_SECOND) != OK) {
740 ALOGE("%s: cannot acquire lock in 1s, cannot proceed",
741 __FUNCTION__);
742 return;
743 }
744 }
745 if (tryWriteFmq && mResultMetadataQueue->availableToWrite() > 0) {
746 for (CaptureResult &result : results) {
747 if (result.result.size() > 0) {
748 if (mResultMetadataQueue->write(result.result.data(), result.result.size())) {
749 result.fmqResultSize = result.result.size();
750 result.result.resize(0);
751 } else {
752 ALOGW("%s: couldn't utilize fmq, fall back to hwbinder", __FUNCTION__);
753 result.fmqResultSize = 0;
754 }
755 } else {
756 result.fmqResultSize = 0;
757 }
758 }
759 }
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -0800760 auto status = mCallback->processCaptureResult(results);
761 if (!status.isOk()) {
762 ALOGE("%s: processCaptureResult ERROR : %s", __FUNCTION__,
763 status.description().c_str());
764 }
765
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700766 mProcessCaptureResultLock.unlock();
767}
768
769void ExternalCameraDeviceSession::freeReleaseFences(hidl_vec<CaptureResult>& results) {
770 for (auto& result : results) {
771 if (result.inputBuffer.releaseFence.getNativeHandle() != nullptr) {
772 native_handle_t* handle = const_cast<native_handle_t*>(
773 result.inputBuffer.releaseFence.getNativeHandle());
774 native_handle_close(handle);
775 native_handle_delete(handle);
776 }
777 for (auto& buf : result.outputBuffers) {
778 if (buf.releaseFence.getNativeHandle() != nullptr) {
779 native_handle_t* handle = const_cast<native_handle_t*>(
780 buf.releaseFence.getNativeHandle());
781 native_handle_close(handle);
782 native_handle_delete(handle);
783 }
784 }
785 }
786 return;
787}
788
789ExternalCameraDeviceSession::OutputThread::OutputThread(
790 wp<ExternalCameraDeviceSession> parent,
791 CroppingType ct) : mParent(parent), mCroppingType(ct) {}
792
793ExternalCameraDeviceSession::OutputThread::~OutputThread() {}
794
795uint32_t ExternalCameraDeviceSession::OutputThread::getFourCcFromLayout(
796 const YCbCrLayout& layout) {
797 intptr_t cb = reinterpret_cast<intptr_t>(layout.cb);
798 intptr_t cr = reinterpret_cast<intptr_t>(layout.cr);
799 if (std::abs(cb - cr) == 1 && layout.chromaStep == 2) {
800 // Interleaved format
801 if (layout.cb > layout.cr) {
802 return V4L2_PIX_FMT_NV21;
803 } else {
804 return V4L2_PIX_FMT_NV12;
805 }
806 } else if (layout.chromaStep == 1) {
807 // Planar format
808 if (layout.cb > layout.cr) {
809 return V4L2_PIX_FMT_YVU420; // YV12
810 } else {
811 return V4L2_PIX_FMT_YUV420; // YU12
812 }
813 } else {
814 return FLEX_YUV_GENERIC;
815 }
816}
817
818int ExternalCameraDeviceSession::OutputThread::getCropRect(
819 CroppingType ct, const Size& inSize, const Size& outSize, IMapper::Rect* out) {
820 if (out == nullptr) {
821 ALOGE("%s: out is null", __FUNCTION__);
822 return -1;
823 }
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800824
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700825 uint32_t inW = inSize.width;
826 uint32_t inH = inSize.height;
827 uint32_t outW = outSize.width;
828 uint32_t outH = outSize.height;
829
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800830 // Handle special case where aspect ratio is close to input but scaled
831 // dimension is slightly larger than input
832 float arIn = ASPECT_RATIO(inSize);
833 float arOut = ASPECT_RATIO(outSize);
834 if (isAspectRatioClose(arIn, arOut)) {
835 out->left = 0;
836 out->top = 0;
837 out->width = inW;
838 out->height = inH;
839 return 0;
840 }
841
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700842 if (ct == VERTICAL) {
843 uint64_t scaledOutH = static_cast<uint64_t>(outH) * inW / outW;
844 if (scaledOutH > inH) {
845 ALOGE("%s: Output size %dx%d cannot be vertically cropped from input size %dx%d",
846 __FUNCTION__, outW, outH, inW, inH);
847 return -1;
848 }
849 scaledOutH = scaledOutH & ~0x1; // make it multiple of 2
850
851 out->left = 0;
852 out->top = ((inH - scaledOutH) / 2) & ~0x1;
853 out->width = inW;
854 out->height = static_cast<int32_t>(scaledOutH);
855 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledH %d",
856 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutH));
857 } else {
858 uint64_t scaledOutW = static_cast<uint64_t>(outW) * inH / outH;
859 if (scaledOutW > inW) {
860 ALOGE("%s: Output size %dx%d cannot be horizontally cropped from input size %dx%d",
861 __FUNCTION__, outW, outH, inW, inH);
862 return -1;
863 }
864 scaledOutW = scaledOutW & ~0x1; // make it multiple of 2
865
866 out->left = ((inW - scaledOutW) / 2) & ~0x1;
867 out->top = 0;
868 out->width = static_cast<int32_t>(scaledOutW);
869 out->height = inH;
870 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledW %d",
871 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutW));
872 }
873
874 return 0;
875}
876
877int ExternalCameraDeviceSession::OutputThread::cropAndScaleLocked(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800878 sp<AllocatedFrame>& in, const Size& outSz, YCbCrLayout* out) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700879 Size inSz = {in->mWidth, in->mHeight};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800880
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700881 int ret;
882 if (inSz == outSz) {
883 ret = in->getLayout(out);
884 if (ret != 0) {
885 ALOGE("%s: failed to get input image layout", __FUNCTION__);
886 return ret;
887 }
888 return ret;
889 }
890
891 // Cropping to output aspect ratio
892 IMapper::Rect inputCrop;
893 ret = getCropRect(mCroppingType, inSz, outSz, &inputCrop);
894 if (ret != 0) {
895 ALOGE("%s: failed to compute crop rect for output size %dx%d",
896 __FUNCTION__, outSz.width, outSz.height);
897 return ret;
898 }
899
900 YCbCrLayout croppedLayout;
901 ret = in->getCroppedLayout(inputCrop, &croppedLayout);
902 if (ret != 0) {
903 ALOGE("%s: failed to crop input image %dx%d to output size %dx%d",
904 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
905 return ret;
906 }
907
908 if ((mCroppingType == VERTICAL && inSz.width == outSz.width) ||
909 (mCroppingType == HORIZONTAL && inSz.height == outSz.height)) {
910 // No scale is needed
911 *out = croppedLayout;
912 return 0;
913 }
914
915 auto it = mScaledYu12Frames.find(outSz);
916 sp<AllocatedFrame> scaledYu12Buf;
917 if (it != mScaledYu12Frames.end()) {
918 scaledYu12Buf = it->second;
919 } else {
920 it = mIntermediateBuffers.find(outSz);
921 if (it == mIntermediateBuffers.end()) {
922 ALOGE("%s: failed to find intermediate buffer size %dx%d",
923 __FUNCTION__, outSz.width, outSz.height);
924 return -1;
925 }
926 scaledYu12Buf = it->second;
927 }
928 // Scale
929 YCbCrLayout outLayout;
930 ret = scaledYu12Buf->getLayout(&outLayout);
931 if (ret != 0) {
932 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
933 return ret;
934 }
935
936 ret = libyuv::I420Scale(
937 static_cast<uint8_t*>(croppedLayout.y),
938 croppedLayout.yStride,
939 static_cast<uint8_t*>(croppedLayout.cb),
940 croppedLayout.cStride,
941 static_cast<uint8_t*>(croppedLayout.cr),
942 croppedLayout.cStride,
943 inputCrop.width,
944 inputCrop.height,
945 static_cast<uint8_t*>(outLayout.y),
946 outLayout.yStride,
947 static_cast<uint8_t*>(outLayout.cb),
948 outLayout.cStride,
949 static_cast<uint8_t*>(outLayout.cr),
950 outLayout.cStride,
951 outSz.width,
952 outSz.height,
953 // TODO: b/72261744 see if we can use better filter without losing too much perf
954 libyuv::FilterMode::kFilterNone);
955
956 if (ret != 0) {
957 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
958 __FUNCTION__, inputCrop.width, inputCrop.height,
959 outSz.width, outSz.height, ret);
960 return ret;
961 }
962
963 *out = outLayout;
964 mScaledYu12Frames.insert({outSz, scaledYu12Buf});
965 return 0;
966}
967
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800968
969int ExternalCameraDeviceSession::OutputThread::cropAndScaleThumbLocked(
970 sp<AllocatedFrame>& in, const Size &outSz, YCbCrLayout* out) {
971 Size inSz {in->mWidth, in->mHeight};
972
973 if ((outSz.width * outSz.height) >
974 (mYu12ThumbFrame->mWidth * mYu12ThumbFrame->mHeight)) {
975 ALOGE("%s: Requested thumbnail size too big (%d,%d) > (%d,%d)",
976 __FUNCTION__, outSz.width, outSz.height,
977 mYu12ThumbFrame->mWidth, mYu12ThumbFrame->mHeight);
978 return -1;
979 }
980
981 int ret;
982
983 /* This will crop-and-zoom the input YUV frame to the thumbnail size
984 * Based on the following logic:
985 * 1) Square pixels come in, square pixels come out, therefore single
986 * scale factor is computed to either make input bigger or smaller
987 * depending on if we are upscaling or downscaling
988 * 2) That single scale factor would either make height too tall or width
989 * too wide so we need to crop the input either horizontally or vertically
990 * but not both
991 */
992
993 /* Convert the input and output dimensions into floats for ease of math */
994 float fWin = static_cast<float>(inSz.width);
995 float fHin = static_cast<float>(inSz.height);
996 float fWout = static_cast<float>(outSz.width);
997 float fHout = static_cast<float>(outSz.height);
998
999 /* Compute the one scale factor from (1) above, it will be the smaller of
1000 * the two possibilities. */
1001 float scaleFactor = std::min( fHin / fHout, fWin / fWout );
1002
1003 /* Since we are crop-and-zooming (as opposed to letter/pillar boxing) we can
1004 * simply multiply the output by our scaleFactor to get the cropped input
1005 * size. Note that at least one of {fWcrop, fHcrop} is going to wind up
1006 * being {fWin, fHin} respectively because fHout or fWout cancels out the
1007 * scaleFactor calculation above.
1008 *
1009 * Specifically:
1010 * if ( fHin / fHout ) < ( fWin / fWout ) we crop the sides off
1011 * input, in which case
1012 * scaleFactor = fHin / fHout
1013 * fWcrop = fHin / fHout * fWout
1014 * fHcrop = fHin
1015 *
1016 * Note that fWcrop <= fWin ( because ( fHin / fHout ) * fWout < fWin, which
1017 * is just the inequality above with both sides multiplied by fWout
1018 *
1019 * on the other hand if ( fWin / fWout ) < ( fHin / fHout) we crop the top
1020 * and the bottom off of input, and
1021 * scaleFactor = fWin / fWout
1022 * fWcrop = fWin
1023 * fHCrop = fWin / fWout * fHout
1024 */
1025 float fWcrop = scaleFactor * fWout;
1026 float fHcrop = scaleFactor * fHout;
1027
1028 /* Convert to integer and truncate to an even number */
1029 Size cropSz = { 2*static_cast<uint32_t>(fWcrop/2.0f),
1030 2*static_cast<uint32_t>(fHcrop/2.0f) };
1031
1032 /* Convert to a centered rectange with even top/left */
1033 IMapper::Rect inputCrop {
1034 2*static_cast<int32_t>((inSz.width - cropSz.width)/4),
1035 2*static_cast<int32_t>((inSz.height - cropSz.height)/4),
1036 static_cast<int32_t>(cropSz.width),
1037 static_cast<int32_t>(cropSz.height) };
1038
1039 if ((inputCrop.top < 0) ||
1040 (inputCrop.top >= static_cast<int32_t>(inSz.height)) ||
1041 (inputCrop.left < 0) ||
1042 (inputCrop.left >= static_cast<int32_t>(inSz.width)) ||
1043 (inputCrop.width <= 0) ||
1044 (inputCrop.width + inputCrop.left > static_cast<int32_t>(inSz.width)) ||
1045 (inputCrop.height <= 0) ||
1046 (inputCrop.height + inputCrop.top > static_cast<int32_t>(inSz.height)))
1047 {
1048 ALOGE("%s: came up with really wrong crop rectangle",__FUNCTION__);
1049 ALOGE("%s: input layout %dx%d to for output size %dx%d",
1050 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1051 ALOGE("%s: computed input crop +%d,+%d %dx%d",
1052 __FUNCTION__, inputCrop.left, inputCrop.top,
1053 inputCrop.width, inputCrop.height);
1054 return -1;
1055 }
1056
1057 YCbCrLayout inputLayout;
1058 ret = in->getCroppedLayout(inputCrop, &inputLayout);
1059 if (ret != 0) {
1060 ALOGE("%s: failed to crop input layout %dx%d to for output size %dx%d",
1061 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1062 ALOGE("%s: computed input crop +%d,+%d %dx%d",
1063 __FUNCTION__, inputCrop.left, inputCrop.top,
1064 inputCrop.width, inputCrop.height);
1065 return ret;
1066 }
1067 ALOGV("%s: crop input layout %dx%d to for output size %dx%d",
1068 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1069 ALOGV("%s: computed input crop +%d,+%d %dx%d",
1070 __FUNCTION__, inputCrop.left, inputCrop.top,
1071 inputCrop.width, inputCrop.height);
1072
1073
1074 // Scale
1075 YCbCrLayout outFullLayout;
1076
1077 ret = mYu12ThumbFrame->getLayout(&outFullLayout);
1078 if (ret != 0) {
1079 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
1080 return ret;
1081 }
1082
1083
1084 ret = libyuv::I420Scale(
1085 static_cast<uint8_t*>(inputLayout.y),
1086 inputLayout.yStride,
1087 static_cast<uint8_t*>(inputLayout.cb),
1088 inputLayout.cStride,
1089 static_cast<uint8_t*>(inputLayout.cr),
1090 inputLayout.cStride,
1091 inputCrop.width,
1092 inputCrop.height,
1093 static_cast<uint8_t*>(outFullLayout.y),
1094 outFullLayout.yStride,
1095 static_cast<uint8_t*>(outFullLayout.cb),
1096 outFullLayout.cStride,
1097 static_cast<uint8_t*>(outFullLayout.cr),
1098 outFullLayout.cStride,
1099 outSz.width,
1100 outSz.height,
1101 libyuv::FilterMode::kFilterNone);
1102
1103 if (ret != 0) {
1104 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
1105 __FUNCTION__, inputCrop.width, inputCrop.height,
1106 outSz.width, outSz.height, ret);
1107 return ret;
1108 }
1109
1110 *out = outFullLayout;
1111 return 0;
1112}
1113
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001114int ExternalCameraDeviceSession::OutputThread::formatConvertLocked(
1115 const YCbCrLayout& in, const YCbCrLayout& out, Size sz, uint32_t format) {
1116 int ret = 0;
1117 switch (format) {
1118 case V4L2_PIX_FMT_NV21:
1119 ret = libyuv::I420ToNV21(
1120 static_cast<uint8_t*>(in.y),
1121 in.yStride,
1122 static_cast<uint8_t*>(in.cb),
1123 in.cStride,
1124 static_cast<uint8_t*>(in.cr),
1125 in.cStride,
1126 static_cast<uint8_t*>(out.y),
1127 out.yStride,
1128 static_cast<uint8_t*>(out.cr),
1129 out.cStride,
1130 sz.width,
1131 sz.height);
1132 if (ret != 0) {
1133 ALOGE("%s: convert to NV21 buffer failed! ret %d",
1134 __FUNCTION__, ret);
1135 return ret;
1136 }
1137 break;
1138 case V4L2_PIX_FMT_NV12:
1139 ret = libyuv::I420ToNV12(
1140 static_cast<uint8_t*>(in.y),
1141 in.yStride,
1142 static_cast<uint8_t*>(in.cb),
1143 in.cStride,
1144 static_cast<uint8_t*>(in.cr),
1145 in.cStride,
1146 static_cast<uint8_t*>(out.y),
1147 out.yStride,
1148 static_cast<uint8_t*>(out.cb),
1149 out.cStride,
1150 sz.width,
1151 sz.height);
1152 if (ret != 0) {
1153 ALOGE("%s: convert to NV12 buffer failed! ret %d",
1154 __FUNCTION__, ret);
1155 return ret;
1156 }
1157 break;
1158 case V4L2_PIX_FMT_YVU420: // YV12
1159 case V4L2_PIX_FMT_YUV420: // YU12
1160 // TODO: maybe we can speed up here by somehow save this copy?
1161 ret = libyuv::I420Copy(
1162 static_cast<uint8_t*>(in.y),
1163 in.yStride,
1164 static_cast<uint8_t*>(in.cb),
1165 in.cStride,
1166 static_cast<uint8_t*>(in.cr),
1167 in.cStride,
1168 static_cast<uint8_t*>(out.y),
1169 out.yStride,
1170 static_cast<uint8_t*>(out.cb),
1171 out.cStride,
1172 static_cast<uint8_t*>(out.cr),
1173 out.cStride,
1174 sz.width,
1175 sz.height);
1176 if (ret != 0) {
1177 ALOGE("%s: copy to YV12 or YU12 buffer failed! ret %d",
1178 __FUNCTION__, ret);
1179 return ret;
1180 }
1181 break;
1182 case FLEX_YUV_GENERIC:
1183 // TODO: b/72261744 write to arbitrary flexible YUV layout. Slow.
1184 ALOGE("%s: unsupported flexible yuv layout"
1185 " y %p cb %p cr %p y_str %d c_str %d c_step %d",
1186 __FUNCTION__, out.y, out.cb, out.cr,
1187 out.yStride, out.cStride, out.chromaStep);
1188 return -1;
1189 default:
1190 ALOGE("%s: unknown YUV format 0x%x!", __FUNCTION__, format);
1191 return -1;
1192 }
1193 return 0;
1194}
1195
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001196int ExternalCameraDeviceSession::OutputThread::encodeJpegYU12(
1197 const Size & inSz, const YCbCrLayout& inLayout,
1198 int jpegQuality, const void *app1Buffer, size_t app1Size,
1199 void *out, const size_t maxOutSize, size_t &actualCodeSize)
1200{
1201 /* libjpeg is a C library so we use C-style "inheritance" by
1202 * putting libjpeg's jpeg_destination_mgr first in our custom
1203 * struct. This allows us to cast jpeg_destination_mgr* to
1204 * CustomJpegDestMgr* when we get it passed to us in a callback */
1205 struct CustomJpegDestMgr {
1206 struct jpeg_destination_mgr mgr;
1207 JOCTET *mBuffer;
1208 size_t mBufferSize;
1209 size_t mEncodedSize;
1210 bool mSuccess;
1211 } dmgr;
1212
1213 jpeg_compress_struct cinfo = {};
1214 jpeg_error_mgr jerr;
1215
1216 /* Initialize error handling with standard callbacks, but
1217 * then override output_message (to print to ALOG) and
1218 * error_exit to set a flag and print a message instead
1219 * of killing the whole process */
1220 cinfo.err = jpeg_std_error(&jerr);
1221
1222 cinfo.err->output_message = [](j_common_ptr cinfo) {
1223 char buffer[JMSG_LENGTH_MAX];
1224
1225 /* Create the message */
1226 (*cinfo->err->format_message)(cinfo, buffer);
1227 ALOGE("libjpeg error: %s", buffer);
1228 };
1229 cinfo.err->error_exit = [](j_common_ptr cinfo) {
1230 (*cinfo->err->output_message)(cinfo);
1231 if(cinfo->client_data) {
1232 auto & dmgr =
1233 *reinterpret_cast<CustomJpegDestMgr*>(cinfo->client_data);
1234 dmgr.mSuccess = false;
1235 }
1236 };
1237 /* Now that we initialized some callbacks, let's create our compressor */
1238 jpeg_create_compress(&cinfo);
1239
1240 /* Initialize our destination manager */
1241 dmgr.mBuffer = static_cast<JOCTET*>(out);
1242 dmgr.mBufferSize = maxOutSize;
1243 dmgr.mEncodedSize = 0;
1244 dmgr.mSuccess = true;
1245 cinfo.client_data = static_cast<void*>(&dmgr);
1246
1247 /* These lambdas become C-style function pointers and as per C++11 spec
1248 * may not capture anything */
1249 dmgr.mgr.init_destination = [](j_compress_ptr cinfo) {
1250 auto & dmgr = reinterpret_cast<CustomJpegDestMgr&>(*cinfo->dest);
1251 dmgr.mgr.next_output_byte = dmgr.mBuffer;
1252 dmgr.mgr.free_in_buffer = dmgr.mBufferSize;
1253 ALOGV("%s:%d jpeg start: %p [%zu]",
1254 __FUNCTION__, __LINE__, dmgr.mBuffer, dmgr.mBufferSize);
1255 };
1256
1257 dmgr.mgr.empty_output_buffer = [](j_compress_ptr cinfo __unused) {
1258 ALOGV("%s:%d Out of buffer", __FUNCTION__, __LINE__);
1259 return 0;
1260 };
1261
1262 dmgr.mgr.term_destination = [](j_compress_ptr cinfo) {
1263 auto & dmgr = reinterpret_cast<CustomJpegDestMgr&>(*cinfo->dest);
1264 dmgr.mEncodedSize = dmgr.mBufferSize - dmgr.mgr.free_in_buffer;
1265 ALOGV("%s:%d Done with jpeg: %zu", __FUNCTION__, __LINE__, dmgr.mEncodedSize);
1266 };
1267 cinfo.dest = reinterpret_cast<struct jpeg_destination_mgr*>(&dmgr);
1268
1269 /* We are going to be using JPEG in raw data mode, so we are passing
1270 * straight subsampled planar YCbCr and it will not touch our pixel
1271 * data or do any scaling or anything */
1272 cinfo.image_width = inSz.width;
1273 cinfo.image_height = inSz.height;
1274 cinfo.input_components = 3;
1275 cinfo.in_color_space = JCS_YCbCr;
1276
1277 /* Initialize defaults and then override what we want */
1278 jpeg_set_defaults(&cinfo);
1279
1280 jpeg_set_quality(&cinfo, jpegQuality, 1);
1281 jpeg_set_colorspace(&cinfo, JCS_YCbCr);
1282 cinfo.raw_data_in = 1;
1283 cinfo.dct_method = JDCT_IFAST;
1284
1285 /* Configure sampling factors. The sampling factor is JPEG subsampling 420
1286 * because the source format is YUV420. Note that libjpeg sampling factors
1287 * are... a little weird. Sampling of Y=2,U=1,V=1 means there is 1 U and
1288 * 1 V value for each 2 Y values */
1289 cinfo.comp_info[0].h_samp_factor = 2;
1290 cinfo.comp_info[0].v_samp_factor = 2;
1291 cinfo.comp_info[1].h_samp_factor = 1;
1292 cinfo.comp_info[1].v_samp_factor = 1;
1293 cinfo.comp_info[2].h_samp_factor = 1;
1294 cinfo.comp_info[2].v_samp_factor = 1;
1295
1296 /* Let's not hardcode YUV420 in 6 places... 5 was enough */
1297 int maxVSampFactor = std::max( {
1298 cinfo.comp_info[0].v_samp_factor,
1299 cinfo.comp_info[1].v_samp_factor,
1300 cinfo.comp_info[2].v_samp_factor
1301 });
1302 int cVSubSampling = cinfo.comp_info[0].v_samp_factor /
1303 cinfo.comp_info[1].v_samp_factor;
1304
1305 /* Start the compressor */
1306 jpeg_start_compress(&cinfo, TRUE);
1307
1308 /* Compute our macroblock height, so we can pad our input to be vertically
1309 * macroblock aligned.
1310 * TODO: Does it need to be horizontally MCU aligned too? */
1311
1312 size_t mcuV = DCTSIZE*maxVSampFactor;
1313 size_t paddedHeight = mcuV * ((inSz.height + mcuV - 1) / mcuV);
1314
1315 /* libjpeg uses arrays of row pointers, which makes it really easy to pad
1316 * data vertically (unfortunately doesn't help horizontally) */
1317 std::vector<JSAMPROW> yLines (paddedHeight);
1318 std::vector<JSAMPROW> cbLines(paddedHeight/cVSubSampling);
1319 std::vector<JSAMPROW> crLines(paddedHeight/cVSubSampling);
1320
1321 uint8_t *py = static_cast<uint8_t*>(inLayout.y);
1322 uint8_t *pcr = static_cast<uint8_t*>(inLayout.cr);
1323 uint8_t *pcb = static_cast<uint8_t*>(inLayout.cb);
1324
1325 for(uint32_t i = 0; i < paddedHeight; i++)
1326 {
1327 /* Once we are in the padding territory we still point to the last line
1328 * effectively replicating it several times ~ CLAMP_TO_EDGE */
1329 int li = std::min(i, inSz.height - 1);
1330 yLines[i] = static_cast<JSAMPROW>(py + li * inLayout.yStride);
1331 if(i < paddedHeight / cVSubSampling)
1332 {
1333 crLines[i] = static_cast<JSAMPROW>(pcr + li * inLayout.cStride);
1334 cbLines[i] = static_cast<JSAMPROW>(pcb + li * inLayout.cStride);
1335 }
1336 }
1337
1338 /* If APP1 data was passed in, use it */
1339 if(app1Buffer && app1Size)
1340 {
1341 jpeg_write_marker(&cinfo, JPEG_APP0 + 1,
1342 static_cast<const JOCTET*>(app1Buffer), app1Size);
1343 }
1344
1345 /* While we still have padded height left to go, keep giving it one
1346 * macroblock at a time. */
1347 while (cinfo.next_scanline < cinfo.image_height) {
1348 const uint32_t batchSize = DCTSIZE * maxVSampFactor;
1349 const uint32_t nl = cinfo.next_scanline;
1350 JSAMPARRAY planes[3]{ &yLines[nl],
1351 &cbLines[nl/cVSubSampling],
1352 &crLines[nl/cVSubSampling] };
1353
1354 uint32_t done = jpeg_write_raw_data(&cinfo, planes, batchSize);
1355
1356 if (done != batchSize) {
1357 ALOGE("%s: compressed %u lines, expected %u (total %u/%u)",
1358 __FUNCTION__, done, batchSize, cinfo.next_scanline,
1359 cinfo.image_height);
1360 return -1;
1361 }
1362 }
1363
1364 /* This will flush everything */
1365 jpeg_finish_compress(&cinfo);
1366
1367 /* Grab the actual code size and set it */
1368 actualCodeSize = dmgr.mEncodedSize;
1369
1370 return 0;
1371}
1372
1373/*
1374 * TODO: There needs to be a mechanism to discover allocated buffer size
1375 * in the HAL.
1376 *
1377 * This is very fragile because it is duplicated computation from:
1378 * frameworks/av/services/camera/libcameraservice/device3/Camera3Device.cpp
1379 *
1380 */
1381
1382/* This assumes mSupportedFormats have all been declared as supporting
1383 * HAL_PIXEL_FORMAT_BLOB to the framework */
1384Size ExternalCameraDeviceSession::getMaxJpegResolution() const {
1385 Size ret { 0, 0 };
1386 for(auto & fmt : mSupportedFormats) {
1387 if(fmt.width * fmt.height > ret.width * ret.height) {
1388 ret = Size { fmt.width, fmt.height };
1389 }
1390 }
1391 return ret;
1392}
1393
1394Size ExternalCameraDeviceSession::getMaxThumbResolution() const {
1395 Size thumbSize { 0, 0 };
1396 camera_metadata_ro_entry entry =
1397 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
1398 for(uint32_t i = 0; i < entry.count; i += 2) {
1399 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
1400 static_cast<uint32_t>(entry.data.i32[i+1]) };
1401 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
1402 thumbSize = sz;
1403 }
1404 }
1405
1406 if (thumbSize.width * thumbSize.height == 0) {
1407 ALOGW("%s: non-zero thumbnail size not available", __FUNCTION__);
1408 }
1409
1410 return thumbSize;
1411}
1412
1413
1414ssize_t ExternalCameraDeviceSession::getJpegBufferSize(
1415 uint32_t width, uint32_t height) const {
1416 // Constant from camera3.h
1417 const ssize_t kMinJpegBufferSize = 256 * 1024 + sizeof(CameraBlob);
1418 // Get max jpeg size (area-wise).
1419 if (mMaxJpegResolution.width == 0) {
1420 ALOGE("%s: Do not have a single supported JPEG stream",
1421 __FUNCTION__);
1422 return BAD_VALUE;
1423 }
1424
1425 // Get max jpeg buffer size
1426 ssize_t maxJpegBufferSize = 0;
1427 camera_metadata_ro_entry jpegBufMaxSize =
1428 mCameraCharacteristics.find(ANDROID_JPEG_MAX_SIZE);
1429 if (jpegBufMaxSize.count == 0) {
1430 ALOGE("%s: Can't find maximum JPEG size in static metadata!",
1431 __FUNCTION__);
1432 return BAD_VALUE;
1433 }
1434 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
1435
1436 if (maxJpegBufferSize <= kMinJpegBufferSize) {
1437 ALOGE("%s: ANDROID_JPEG_MAX_SIZE (%zd) <= kMinJpegBufferSize (%zd)",
1438 __FUNCTION__, maxJpegBufferSize, kMinJpegBufferSize);
1439 return BAD_VALUE;
1440 }
1441
1442 // Calculate final jpeg buffer size for the given resolution.
1443 float scaleFactor = ((float) (width * height)) /
1444 (mMaxJpegResolution.width * mMaxJpegResolution.height);
1445 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
1446 kMinJpegBufferSize;
1447 if (jpegBufferSize > maxJpegBufferSize) {
1448 jpegBufferSize = maxJpegBufferSize;
1449 }
1450
1451 return jpegBufferSize;
1452}
1453
1454int ExternalCameraDeviceSession::OutputThread::createJpegLocked(
1455 HalStreamBuffer &halBuf,
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001456 const std::shared_ptr<HalRequest>& req)
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001457{
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001458 ATRACE_CALL();
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001459 int ret;
1460 auto lfail = [&](auto... args) {
1461 ALOGE(args...);
1462
1463 return 1;
1464 };
1465 auto parent = mParent.promote();
1466 if (parent == nullptr) {
1467 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1468 return 1;
1469 }
1470
1471 ALOGV("%s: HAL buffer sid: %d bid: %" PRIu64 " w: %u h: %u",
1472 __FUNCTION__, halBuf.streamId, static_cast<uint64_t>(halBuf.bufferId),
1473 halBuf.width, halBuf.height);
1474 ALOGV("%s: HAL buffer fmt: %x usage: %" PRIx64 " ptr: %p",
1475 __FUNCTION__, halBuf.format, static_cast<uint64_t>(halBuf.usage),
1476 halBuf.bufPtr);
1477 ALOGV("%s: YV12 buffer %d x %d",
1478 __FUNCTION__,
1479 mYu12Frame->mWidth, mYu12Frame->mHeight);
1480
1481 int jpegQuality, thumbQuality;
1482 Size thumbSize;
1483
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001484 if (req->setting.exists(ANDROID_JPEG_QUALITY)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001485 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001486 req->setting.find(ANDROID_JPEG_QUALITY);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001487 jpegQuality = entry.data.u8[0];
1488 } else {
1489 return lfail("%s: ANDROID_JPEG_QUALITY not set",__FUNCTION__);
1490 }
1491
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001492 if (req->setting.exists(ANDROID_JPEG_THUMBNAIL_QUALITY)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001493 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001494 req->setting.find(ANDROID_JPEG_THUMBNAIL_QUALITY);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001495 thumbQuality = entry.data.u8[0];
1496 } else {
1497 return lfail(
1498 "%s: ANDROID_JPEG_THUMBNAIL_QUALITY not set",
1499 __FUNCTION__);
1500 }
1501
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001502 if (req->setting.exists(ANDROID_JPEG_THUMBNAIL_SIZE)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001503 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001504 req->setting.find(ANDROID_JPEG_THUMBNAIL_SIZE);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001505 thumbSize = Size { static_cast<uint32_t>(entry.data.i32[0]),
1506 static_cast<uint32_t>(entry.data.i32[1])
1507 };
1508 } else {
1509 return lfail(
1510 "%s: ANDROID_JPEG_THUMBNAIL_SIZE not set", __FUNCTION__);
1511 }
1512
1513 /* Cropped and scaled YU12 buffer for main and thumbnail */
1514 YCbCrLayout yu12Main;
1515 Size jpegSize { halBuf.width, halBuf.height };
1516
1517 /* Compute temporary buffer sizes accounting for the following:
1518 * thumbnail can't exceed APP1 size of 64K
1519 * main image needs to hold APP1, headers, and at most a poorly
1520 * compressed image */
1521 const ssize_t maxThumbCodeSize = 64 * 1024;
1522 const ssize_t maxJpegCodeSize = parent->getJpegBufferSize(jpegSize.width,
1523 jpegSize.height);
1524
1525 /* Check that getJpegBufferSize did not return an error */
1526 if (maxJpegCodeSize < 0) {
1527 return lfail(
1528 "%s: getJpegBufferSize returned %zd",__FUNCTION__,maxJpegCodeSize);
1529 }
1530
1531
1532 /* Hold actual thumbnail and main image code sizes */
1533 size_t thumbCodeSize = 0, jpegCodeSize = 0;
1534 /* Temporary thumbnail code buffer */
1535 std::vector<uint8_t> thumbCode(maxThumbCodeSize);
1536
1537 YCbCrLayout yu12Thumb;
1538 ret = cropAndScaleThumbLocked(mYu12Frame, thumbSize, &yu12Thumb);
1539
1540 if (ret != 0) {
1541 return lfail(
1542 "%s: crop and scale thumbnail failed!", __FUNCTION__);
1543 }
1544
1545 /* Scale and crop main jpeg */
1546 ret = cropAndScaleLocked(mYu12Frame, jpegSize, &yu12Main);
1547
1548 if (ret != 0) {
1549 return lfail("%s: crop and scale main failed!", __FUNCTION__);
1550 }
1551
1552 /* Encode the thumbnail image */
1553 ret = encodeJpegYU12(thumbSize, yu12Thumb,
1554 thumbQuality, 0, 0,
1555 &thumbCode[0], maxThumbCodeSize, thumbCodeSize);
1556
1557 if (ret != 0) {
1558 return lfail("%s: encodeJpegYU12 failed with %d",__FUNCTION__, ret);
1559 }
1560
1561 /* Combine camera characteristics with request settings to form EXIF
1562 * metadata */
1563 common::V1_0::helper::CameraMetadata meta(parent->mCameraCharacteristics);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001564 meta.append(req->setting);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001565
1566 /* Generate EXIF object */
1567 std::unique_ptr<ExifUtils> utils(ExifUtils::create());
1568 /* Make sure it's initialized */
1569 utils->initialize();
1570
1571 utils->setFromMetadata(meta, jpegSize.width, jpegSize.height);
1572
1573 /* Check if we made a non-zero-sized thumbnail. Currently not possible
1574 * that we got this far and the code is size 0, but if this code moves
1575 * around it might become relevant again */
1576
1577 ret = utils->generateApp1(thumbCodeSize ? &thumbCode[0] : 0, thumbCodeSize);
1578
1579 if (!ret) {
1580 return lfail("%s: generating APP1 failed", __FUNCTION__);
1581 }
1582
1583 /* Get internal buffer */
1584 size_t exifDataSize = utils->getApp1Length();
1585 const uint8_t* exifData = utils->getApp1Buffer();
1586
1587 /* Lock the HAL jpeg code buffer */
1588 void *bufPtr = sHandleImporter.lock(
1589 *(halBuf.bufPtr), halBuf.usage, maxJpegCodeSize);
1590
1591 if (!bufPtr) {
1592 return lfail("%s: could not lock %zu bytes", __FUNCTION__, maxJpegCodeSize);
1593 }
1594
1595 /* Encode the main jpeg image */
1596 ret = encodeJpegYU12(jpegSize, yu12Main,
1597 jpegQuality, exifData, exifDataSize,
1598 bufPtr, maxJpegCodeSize, jpegCodeSize);
1599
1600 /* TODO: Not sure this belongs here, maybe better to pass jpegCodeSize out
1601 * and do this when returning buffer to parent */
1602 CameraBlob blob { CameraBlobId::JPEG, static_cast<uint32_t>(jpegCodeSize) };
1603 void *blobDst =
1604 reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(bufPtr) +
1605 maxJpegCodeSize -
1606 sizeof(CameraBlob));
1607 memcpy(blobDst, &blob, sizeof(CameraBlob));
1608
1609 /* Unlock the HAL jpeg code buffer */
1610 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
1611 if (relFence > 0) {
1612 halBuf.acquireFence = relFence;
1613 }
1614
1615 /* Check if our JPEG actually succeeded */
1616 if (ret != 0) {
1617 return lfail(
1618 "%s: encodeJpegYU12 failed with %d",__FUNCTION__, ret);
1619 }
1620
1621 ALOGV("%s: encoded JPEG (ret:%d) with Q:%d max size: %zu",
1622 __FUNCTION__, ret, jpegQuality, maxJpegCodeSize);
1623
1624 return 0;
1625}
1626
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001627bool ExternalCameraDeviceSession::OutputThread::threadLoop() {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001628 std::shared_ptr<HalRequest> req;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001629 auto parent = mParent.promote();
1630 if (parent == nullptr) {
1631 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1632 return false;
1633 }
1634
1635 // TODO: maybe we need to setup a sensor thread to dq/enq v4l frames
1636 // regularly to prevent v4l buffer queue filled with stale buffers
1637 // when app doesn't program a preveiw request
1638 waitForNextRequest(&req);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001639 if (req == nullptr) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001640 // No new request, wait again
1641 return true;
1642 }
1643
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001644 auto onDeviceError = [&](auto... args) {
1645 ALOGE(args...);
1646 parent->notifyError(
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001647 req->frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001648 signalRequestDone();
1649 return false;
1650 };
1651
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001652 if (req->frameIn->mFourcc != V4L2_PIX_FMT_MJPEG) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001653 return onDeviceError("%s: do not support V4L2 format %c%c%c%c", __FUNCTION__,
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001654 req->frameIn->mFourcc & 0xFF,
1655 (req->frameIn->mFourcc >> 8) & 0xFF,
1656 (req->frameIn->mFourcc >> 16) & 0xFF,
1657 (req->frameIn->mFourcc >> 24) & 0xFF);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001658 }
1659
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001660 std::unique_lock<std::mutex> lk(mBufferLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001661 // Convert input V4L2 frame to YU12 of the same size
1662 // TODO: see if we can save some computation by converting to YV12 here
1663 uint8_t* inData;
1664 size_t inDataSize;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001665 req->frameIn->map(&inData, &inDataSize);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001666 // TODO: in some special case maybe we can decode jpg directly to gralloc output?
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001667 ATRACE_BEGIN("MJPGtoI420");
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001668 int res = libyuv::MJPGToI420(
1669 inData, inDataSize,
1670 static_cast<uint8_t*>(mYu12FrameLayout.y),
1671 mYu12FrameLayout.yStride,
1672 static_cast<uint8_t*>(mYu12FrameLayout.cb),
1673 mYu12FrameLayout.cStride,
1674 static_cast<uint8_t*>(mYu12FrameLayout.cr),
1675 mYu12FrameLayout.cStride,
1676 mYu12Frame->mWidth, mYu12Frame->mHeight,
1677 mYu12Frame->mWidth, mYu12Frame->mHeight);
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001678 ATRACE_END();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001679
1680 if (res != 0) {
1681 // For some webcam, the first few V4L2 frames might be malformed...
1682 ALOGE("%s: Convert V4L2 frame to YU12 failed! res %d", __FUNCTION__, res);
1683 lk.unlock();
1684 Status st = parent->processCaptureRequestError(req);
1685 if (st != Status::OK) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001686 return onDeviceError("%s: failed to process capture request error!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001687 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001688 signalRequestDone();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001689 return true;
1690 }
1691
1692 ALOGV("%s processing new request", __FUNCTION__);
1693 const int kSyncWaitTimeoutMs = 500;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001694 for (auto& halBuf : req->buffers) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001695 if (halBuf.acquireFence != -1) {
1696 int ret = sync_wait(halBuf.acquireFence, kSyncWaitTimeoutMs);
1697 if (ret) {
1698 halBuf.fenceTimeout = true;
1699 } else {
1700 ::close(halBuf.acquireFence);
Yin-Chia Yeh1e089662018-02-02 15:57:58 -08001701 halBuf.acquireFence = -1;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001702 }
1703 }
1704
1705 if (halBuf.fenceTimeout) {
1706 continue;
1707 }
1708
1709 // Gralloc lockYCbCr the buffer
1710 switch (halBuf.format) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001711 case PixelFormat::BLOB: {
1712 int ret = createJpegLocked(halBuf, req);
1713
1714 if(ret != 0) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001715 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001716 return onDeviceError("%s: createJpegLocked failed with %d",
1717 __FUNCTION__, ret);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001718 }
1719 } break;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001720 case PixelFormat::YCBCR_420_888:
1721 case PixelFormat::YV12: {
1722 IMapper::Rect outRect {0, 0,
1723 static_cast<int32_t>(halBuf.width),
1724 static_cast<int32_t>(halBuf.height)};
1725 YCbCrLayout outLayout = sHandleImporter.lockYCbCr(
1726 *(halBuf.bufPtr), halBuf.usage, outRect);
1727 ALOGV("%s: outLayout y %p cb %p cr %p y_str %d c_str %d c_step %d",
1728 __FUNCTION__, outLayout.y, outLayout.cb, outLayout.cr,
1729 outLayout.yStride, outLayout.cStride, outLayout.chromaStep);
1730
1731 // Convert to output buffer size/format
1732 uint32_t outputFourcc = getFourCcFromLayout(outLayout);
1733 ALOGV("%s: converting to format %c%c%c%c", __FUNCTION__,
1734 outputFourcc & 0xFF,
1735 (outputFourcc >> 8) & 0xFF,
1736 (outputFourcc >> 16) & 0xFF,
1737 (outputFourcc >> 24) & 0xFF);
1738
1739 YCbCrLayout cropAndScaled;
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001740 ATRACE_BEGIN("cropAndScaleLocked");
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001741 int ret = cropAndScaleLocked(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001742 mYu12Frame,
1743 Size { halBuf.width, halBuf.height },
1744 &cropAndScaled);
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001745 ATRACE_END();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001746 if (ret != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001747 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001748 return onDeviceError("%s: crop and scale failed!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001749 }
1750
1751 Size sz {halBuf.width, halBuf.height};
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001752 ATRACE_BEGIN("formatConvertLocked");
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001753 ret = formatConvertLocked(cropAndScaled, outLayout, sz, outputFourcc);
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001754 ATRACE_END();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001755 if (ret != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001756 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001757 return onDeviceError("%s: format coversion failed!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001758 }
1759 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
1760 if (relFence > 0) {
1761 halBuf.acquireFence = relFence;
1762 }
1763 } break;
1764 default:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001765 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001766 return onDeviceError("%s: unknown output format %x", __FUNCTION__, halBuf.format);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001767 }
1768 } // for each buffer
1769 mScaledYu12Frames.clear();
1770
1771 // Don't hold the lock while calling back to parent
1772 lk.unlock();
1773 Status st = parent->processCaptureResult(req);
1774 if (st != Status::OK) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001775 return onDeviceError("%s: failed to process capture result!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001776 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001777 signalRequestDone();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001778 return true;
1779}
1780
1781Status ExternalCameraDeviceSession::OutputThread::allocateIntermediateBuffers(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001782 const Size& v4lSize, const Size& thumbSize,
1783 const hidl_vec<Stream>& streams) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001784 std::lock_guard<std::mutex> lk(mBufferLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001785 if (mScaledYu12Frames.size() != 0) {
1786 ALOGE("%s: intermediate buffer pool has %zu inflight buffers! (expect 0)",
1787 __FUNCTION__, mScaledYu12Frames.size());
1788 return Status::INTERNAL_ERROR;
1789 }
1790
1791 // Allocating intermediate YU12 frame
1792 if (mYu12Frame == nullptr || mYu12Frame->mWidth != v4lSize.width ||
1793 mYu12Frame->mHeight != v4lSize.height) {
1794 mYu12Frame.clear();
1795 mYu12Frame = new AllocatedFrame(v4lSize.width, v4lSize.height);
1796 int ret = mYu12Frame->allocate(&mYu12FrameLayout);
1797 if (ret != 0) {
1798 ALOGE("%s: allocating YU12 frame failed!", __FUNCTION__);
1799 return Status::INTERNAL_ERROR;
1800 }
1801 }
1802
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001803 // Allocating intermediate YU12 thumbnail frame
1804 if (mYu12ThumbFrame == nullptr ||
1805 mYu12ThumbFrame->mWidth != thumbSize.width ||
1806 mYu12ThumbFrame->mHeight != thumbSize.height) {
1807 mYu12ThumbFrame.clear();
1808 mYu12ThumbFrame = new AllocatedFrame(thumbSize.width, thumbSize.height);
1809 int ret = mYu12ThumbFrame->allocate(&mYu12ThumbFrameLayout);
1810 if (ret != 0) {
1811 ALOGE("%s: allocating YU12 thumb frame failed!", __FUNCTION__);
1812 return Status::INTERNAL_ERROR;
1813 }
1814 }
1815
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001816 // Allocating scaled buffers
1817 for (const auto& stream : streams) {
1818 Size sz = {stream.width, stream.height};
1819 if (sz == v4lSize) {
1820 continue; // Don't need an intermediate buffer same size as v4lBuffer
1821 }
1822 if (mIntermediateBuffers.count(sz) == 0) {
1823 // Create new intermediate buffer
1824 sp<AllocatedFrame> buf = new AllocatedFrame(stream.width, stream.height);
1825 int ret = buf->allocate();
1826 if (ret != 0) {
1827 ALOGE("%s: allocating intermediate YU12 frame %dx%d failed!",
1828 __FUNCTION__, stream.width, stream.height);
1829 return Status::INTERNAL_ERROR;
1830 }
1831 mIntermediateBuffers[sz] = buf;
1832 }
1833 }
1834
1835 // Remove unconfigured buffers
1836 auto it = mIntermediateBuffers.begin();
1837 while (it != mIntermediateBuffers.end()) {
1838 bool configured = false;
1839 auto sz = it->first;
1840 for (const auto& stream : streams) {
1841 if (stream.width == sz.width && stream.height == sz.height) {
1842 configured = true;
1843 break;
1844 }
1845 }
1846 if (configured) {
1847 it++;
1848 } else {
1849 it = mIntermediateBuffers.erase(it);
1850 }
1851 }
1852 return Status::OK;
1853}
1854
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001855Status ExternalCameraDeviceSession::OutputThread::submitRequest(
1856 const std::shared_ptr<HalRequest>& req) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001857 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001858 mRequestList.push_back(req);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001859 lk.unlock();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001860 mRequestCond.notify_one();
1861 return Status::OK;
1862}
1863
1864void ExternalCameraDeviceSession::OutputThread::flush() {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001865 ATRACE_CALL();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001866 auto parent = mParent.promote();
1867 if (parent == nullptr) {
1868 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1869 return;
1870 }
1871
1872 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001873 std::list<std::shared_ptr<HalRequest>> reqs = std::move(mRequestList);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001874 mRequestList.clear();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001875 if (mProcessingRequest) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001876 std::chrono::seconds timeout = std::chrono::seconds(kFlushWaitTimeoutSec);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001877 auto st = mRequestDoneCond.wait_for(lk, timeout);
1878 if (st == std::cv_status::timeout) {
1879 ALOGE("%s: wait for inflight request finish timeout!", __FUNCTION__);
1880 }
1881 }
1882
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001883 ALOGV("%s: flusing inflight requests", __FUNCTION__);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001884 lk.unlock();
1885 for (const auto& req : reqs) {
1886 parent->processCaptureRequestError(req);
1887 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001888}
1889
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001890void ExternalCameraDeviceSession::OutputThread::waitForNextRequest(
1891 std::shared_ptr<HalRequest>* out) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001892 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001893 if (out == nullptr) {
1894 ALOGE("%s: out is null", __FUNCTION__);
1895 return;
1896 }
1897
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001898 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001899 int waitTimes = 0;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001900 while (mRequestList.empty()) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001901 if (exitPending()) {
1902 return;
1903 }
1904 std::chrono::milliseconds timeout = std::chrono::milliseconds(kReqWaitTimeoutMs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001905 auto st = mRequestCond.wait_for(lk, timeout);
1906 if (st == std::cv_status::timeout) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001907 waitTimes++;
1908 if (waitTimes == kReqWaitTimesMax) {
1909 // no new request, return
1910 return;
1911 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001912 }
1913 }
1914 *out = mRequestList.front();
1915 mRequestList.pop_front();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001916 mProcessingRequest = true;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001917 mProcessingFrameNumer = (*out)->frameNumber;
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001918}
1919
1920void ExternalCameraDeviceSession::OutputThread::signalRequestDone() {
1921 std::unique_lock<std::mutex> lk(mRequestListLock);
1922 mProcessingRequest = false;
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001923 mProcessingFrameNumer = 0;
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001924 lk.unlock();
1925 mRequestDoneCond.notify_one();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001926}
1927
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001928void ExternalCameraDeviceSession::OutputThread::dump(int fd) {
1929 std::lock_guard<std::mutex> lk(mRequestListLock);
1930 if (mProcessingRequest) {
1931 dprintf(fd, "OutputThread processing frame %d\n", mProcessingFrameNumer);
1932 } else {
1933 dprintf(fd, "OutputThread not processing any frames\n");
1934 }
1935 dprintf(fd, "OutputThread request list contains frame: ");
1936 for (const auto& req : mRequestList) {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001937 dprintf(fd, "%d, ", req->frameNumber);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08001938 }
1939 dprintf(fd, "\n");
1940}
1941
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001942void ExternalCameraDeviceSession::cleanupBuffersLocked(int id) {
1943 for (auto& pair : mCirculatingBuffers.at(id)) {
1944 sHandleImporter.freeBuffer(pair.second);
1945 }
1946 mCirculatingBuffers[id].clear();
1947 mCirculatingBuffers.erase(id);
1948}
1949
1950void ExternalCameraDeviceSession::updateBufferCaches(const hidl_vec<BufferCache>& cachesToRemove) {
1951 Mutex::Autolock _l(mLock);
1952 for (auto& cache : cachesToRemove) {
1953 auto cbsIt = mCirculatingBuffers.find(cache.streamId);
1954 if (cbsIt == mCirculatingBuffers.end()) {
1955 // The stream could have been removed
1956 continue;
1957 }
1958 CirculatingBuffers& cbs = cbsIt->second;
1959 auto it = cbs.find(cache.bufferId);
1960 if (it != cbs.end()) {
1961 sHandleImporter.freeBuffer(it->second);
1962 cbs.erase(it);
1963 } else {
1964 ALOGE("%s: stream %d buffer %" PRIu64 " is not cached",
1965 __FUNCTION__, cache.streamId, cache.bufferId);
1966 }
1967 }
1968}
1969
1970bool ExternalCameraDeviceSession::isSupported(const Stream& stream) {
1971 int32_t ds = static_cast<int32_t>(stream.dataSpace);
1972 PixelFormat fmt = stream.format;
1973 uint32_t width = stream.width;
1974 uint32_t height = stream.height;
1975 // TODO: check usage flags
1976
1977 if (stream.streamType != StreamType::OUTPUT) {
1978 ALOGE("%s: does not support non-output stream type", __FUNCTION__);
1979 return false;
1980 }
1981
1982 if (stream.rotation != StreamRotation::ROTATION_0) {
1983 ALOGE("%s: does not support stream rotation", __FUNCTION__);
1984 return false;
1985 }
1986
1987 if (ds & Dataspace::DEPTH) {
1988 ALOGI("%s: does not support depth output", __FUNCTION__);
1989 return false;
1990 }
1991
1992 switch (fmt) {
1993 case PixelFormat::BLOB:
1994 if (ds != static_cast<int32_t>(Dataspace::V0_JFIF)) {
1995 ALOGI("%s: BLOB format does not support dataSpace %x", __FUNCTION__, ds);
1996 return false;
1997 }
1998 case PixelFormat::IMPLEMENTATION_DEFINED:
1999 case PixelFormat::YCBCR_420_888:
2000 case PixelFormat::YV12:
2001 // TODO: check what dataspace we can support here.
2002 // intentional no-ops.
2003 break;
2004 default:
2005 ALOGI("%s: does not support format %x", __FUNCTION__, fmt);
2006 return false;
2007 }
2008
2009 // Assume we can convert any V4L2 format to any of supported output format for now, i.e,
2010 // ignoring v4l2Fmt.fourcc for now. Might need more subtle check if we support more v4l format
2011 // in the futrue.
2012 for (const auto& v4l2Fmt : mSupportedFormats) {
2013 if (width == v4l2Fmt.width && height == v4l2Fmt.height) {
2014 return true;
2015 }
2016 }
2017 ALOGI("%s: resolution %dx%d is not supported", __FUNCTION__, width, height);
2018 return false;
2019}
2020
2021int ExternalCameraDeviceSession::v4l2StreamOffLocked() {
2022 if (!mV4l2Streaming) {
2023 return OK;
2024 }
2025
2026 {
2027 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2028 if (mNumDequeuedV4l2Buffers != 0) {
2029 ALOGE("%s: there are %zu inflight V4L buffers",
2030 __FUNCTION__, mNumDequeuedV4l2Buffers);
2031 return -1;
2032 }
2033 }
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002034 mV4L2BufferCount = 0;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002035
2036 // VIDIOC_STREAMOFF
2037 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2038 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMOFF, &capture_type)) < 0) {
2039 ALOGE("%s: STREAMOFF failed: %s", __FUNCTION__, strerror(errno));
2040 return -errno;
2041 }
2042
2043 // VIDIOC_REQBUFS: clear buffers
2044 v4l2_requestbuffers req_buffers{};
2045 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2046 req_buffers.memory = V4L2_MEMORY_MMAP;
2047 req_buffers.count = 0;
2048 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
2049 ALOGE("%s: REQBUFS failed: %s", __FUNCTION__, strerror(errno));
2050 return -errno;
2051 }
2052
2053 mV4l2Streaming = false;
2054 return OK;
2055}
2056
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002057int ExternalCameraDeviceSession::setV4l2FpsLocked(double fps) {
2058 // VIDIOC_G_PARM/VIDIOC_S_PARM: set fps
2059 v4l2_streamparm streamparm = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
2060 // The following line checks that the driver knows about framerate get/set.
2061 int ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_G_PARM, &streamparm));
2062 if (ret != 0) {
2063 if (errno == -EINVAL) {
2064 ALOGW("%s: device does not support VIDIOC_G_PARM", __FUNCTION__);
2065 }
2066 return -errno;
2067 }
2068 // Now check if the device is able to accept a capture framerate set.
2069 if (!(streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME)) {
2070 ALOGW("%s: device does not support V4L2_CAP_TIMEPERFRAME", __FUNCTION__);
2071 return -EINVAL;
2072 }
2073
2074 // fps is float, approximate by a fraction.
2075 const int kFrameRatePrecision = 10000;
2076 streamparm.parm.capture.timeperframe.numerator = kFrameRatePrecision;
2077 streamparm.parm.capture.timeperframe.denominator =
2078 (fps * kFrameRatePrecision);
2079
2080 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_PARM, &streamparm)) < 0) {
2081 ALOGE("%s: failed to set framerate to %f: %s", __FUNCTION__, fps, strerror(errno));
2082 return -1;
2083 }
2084
2085 double retFps = streamparm.parm.capture.timeperframe.denominator /
2086 static_cast<double>(streamparm.parm.capture.timeperframe.numerator);
2087 if (std::fabs(fps - retFps) > 1.0) {
2088 ALOGE("%s: expect fps %f, got %f instead", __FUNCTION__, fps, retFps);
2089 return -1;
2090 }
2091 mV4l2StreamingFps = fps;
2092 return 0;
2093}
2094
2095int ExternalCameraDeviceSession::configureV4l2StreamLocked(
2096 const SupportedV4L2Format& v4l2Fmt, double requestFps) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002097 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002098 int ret = v4l2StreamOffLocked();
2099 if (ret != OK) {
2100 ALOGE("%s: stop v4l2 streaming failed: ret %d", __FUNCTION__, ret);
2101 return ret;
2102 }
2103
2104 // VIDIOC_S_FMT w/h/fmt
2105 v4l2_format fmt;
2106 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2107 fmt.fmt.pix.width = v4l2Fmt.width;
2108 fmt.fmt.pix.height = v4l2Fmt.height;
2109 fmt.fmt.pix.pixelformat = v4l2Fmt.fourcc;
2110 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt));
2111 if (ret < 0) {
2112 ALOGE("%s: S_FMT ioctl failed: %s", __FUNCTION__, strerror(errno));
2113 return -errno;
2114 }
2115
2116 if (v4l2Fmt.width != fmt.fmt.pix.width || v4l2Fmt.height != fmt.fmt.pix.height ||
2117 v4l2Fmt.fourcc != fmt.fmt.pix.pixelformat) {
2118 ALOGE("%s: S_FMT expect %c%c%c%c %dx%d, got %c%c%c%c %dx%d instead!", __FUNCTION__,
2119 v4l2Fmt.fourcc & 0xFF,
2120 (v4l2Fmt.fourcc >> 8) & 0xFF,
2121 (v4l2Fmt.fourcc >> 16) & 0xFF,
2122 (v4l2Fmt.fourcc >> 24) & 0xFF,
2123 v4l2Fmt.width, v4l2Fmt.height,
2124 fmt.fmt.pix.pixelformat & 0xFF,
2125 (fmt.fmt.pix.pixelformat >> 8) & 0xFF,
2126 (fmt.fmt.pix.pixelformat >> 16) & 0xFF,
2127 (fmt.fmt.pix.pixelformat >> 24) & 0xFF,
2128 fmt.fmt.pix.width, fmt.fmt.pix.height);
2129 return -EINVAL;
2130 }
2131 uint32_t bufferSize = fmt.fmt.pix.sizeimage;
2132 ALOGI("%s: V4L2 buffer size is %d", __FUNCTION__, bufferSize);
2133
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002134 const double kDefaultFps = 30.0;
2135 double fps = 1000.0;
2136 if (requestFps != 0.0) {
2137 fps = requestFps;
2138 } else {
2139 double maxFps = -1.0;
2140 // Try to pick the slowest fps that is at least 30
2141 for (const auto& fr : v4l2Fmt.frameRates) {
2142 double f = fr.getDouble();
2143 if (maxFps < f) {
2144 maxFps = f;
2145 }
2146 if (f >= kDefaultFps && f < fps) {
2147 fps = f;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002148 }
2149 }
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002150 if (fps == 1000.0) {
2151 fps = maxFps;
2152 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002153 }
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002154
2155 int fpsRet = setV4l2FpsLocked(fps);
2156 if (fpsRet != 0 && fpsRet != -EINVAL) {
2157 ALOGE("%s: set fps failed: %s", __FUNCTION__, strerror(fpsRet));
2158 return fpsRet;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002159 }
2160
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -08002161 uint32_t v4lBufferCount = (fps >= kDefaultFps) ?
2162 mCfg.numVideoBuffers : mCfg.numStillBuffers;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002163 // VIDIOC_REQBUFS: create buffers
2164 v4l2_requestbuffers req_buffers{};
2165 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2166 req_buffers.memory = V4L2_MEMORY_MMAP;
2167 req_buffers.count = v4lBufferCount;
2168 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
2169 ALOGE("%s: VIDIOC_REQBUFS failed: %s", __FUNCTION__, strerror(errno));
2170 return -errno;
2171 }
2172
2173 // Driver can indeed return more buffer if it needs more to operate
2174 if (req_buffers.count < v4lBufferCount) {
2175 ALOGE("%s: VIDIOC_REQBUFS expected %d buffers, got %d instead",
2176 __FUNCTION__, v4lBufferCount, req_buffers.count);
2177 return NO_MEMORY;
2178 }
2179
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002180 // VIDIOC_QUERYBUF: get buffer offset in the V4L2 fd
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002181 // VIDIOC_QBUF: send buffer to driver
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002182 mV4L2BufferCount = req_buffers.count;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002183 for (uint32_t i = 0; i < req_buffers.count; i++) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002184 v4l2_buffer buffer = {
2185 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
2186 .index = i,
2187 .memory = V4L2_MEMORY_MMAP};
2188
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002189 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QUERYBUF, &buffer)) < 0) {
2190 ALOGE("%s: QUERYBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
2191 return -errno;
2192 }
2193
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002194 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2195 ALOGE("%s: QBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
2196 return -errno;
2197 }
2198 }
2199
2200 // VIDIOC_STREAMON: start streaming
2201 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2202 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type)) < 0) {
2203 ALOGE("%s: VIDIOC_STREAMON failed: %s", __FUNCTION__, strerror(errno));
2204 return -errno;
2205 }
2206
2207 // Swallow first few frames after streamOn to account for bad frames from some devices
2208 for (int i = 0; i < kBadFramesAfterStreamOn; i++) {
2209 v4l2_buffer buffer{};
2210 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2211 buffer.memory = V4L2_MEMORY_MMAP;
2212 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
2213 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
2214 return -errno;
2215 }
2216
2217 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2218 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, buffer.index, strerror(errno));
2219 return -errno;
2220 }
2221 }
2222
2223 mV4l2StreamingFmt = v4l2Fmt;
2224 mV4l2Streaming = true;
2225 return OK;
2226}
2227
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002228sp<V4L2Frame> ExternalCameraDeviceSession::dequeueV4l2FrameLocked(/*out*/nsecs_t* shutterTs) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002229 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002230 sp<V4L2Frame> ret = nullptr;
2231
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002232 if (shutterTs == nullptr) {
2233 ALOGE("%s: shutterTs must not be null!", __FUNCTION__);
2234 return ret;
2235 }
2236
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002237 {
2238 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002239 if (mNumDequeuedV4l2Buffers == mV4L2BufferCount) {
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002240 int waitRet = waitForV4L2BufferReturnLocked(lk);
2241 if (waitRet != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002242 return ret;
2243 }
2244 }
2245 }
2246
2247 v4l2_buffer buffer{};
2248 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2249 buffer.memory = V4L2_MEMORY_MMAP;
2250 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
2251 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
2252 return ret;
2253 }
2254
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002255 if (buffer.index >= mV4L2BufferCount) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002256 ALOGE("%s: Invalid buffer id: %d", __FUNCTION__, buffer.index);
2257 return ret;
2258 }
2259
2260 if (buffer.flags & V4L2_BUF_FLAG_ERROR) {
2261 ALOGE("%s: v4l2 buf error! buf flag 0x%x", __FUNCTION__, buffer.flags);
2262 // TODO: try to dequeue again
2263 }
2264
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002265 if (buffer.flags & V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC) {
2266 // Ideally we should also check for V4L2_BUF_FLAG_TSTAMP_SRC_SOE, but
2267 // even V4L2_BUF_FLAG_TSTAMP_SRC_EOF is better than capture a timestamp now
2268 *shutterTs = static_cast<nsecs_t>(buffer.timestamp.tv_sec)*1000000000LL +
2269 buffer.timestamp.tv_usec * 1000LL;
2270 } else {
2271 *shutterTs = systemTime(SYSTEM_TIME_MONOTONIC);
2272 }
2273
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002274 {
2275 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2276 mNumDequeuedV4l2Buffers++;
2277 }
2278 return new V4L2Frame(
2279 mV4l2StreamingFmt.width, mV4l2StreamingFmt.height, mV4l2StreamingFmt.fourcc,
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002280 buffer.index, mV4l2Fd.get(), buffer.bytesused, buffer.m.offset);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002281}
2282
2283void ExternalCameraDeviceSession::enqueueV4l2Frame(const sp<V4L2Frame>& frame) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002284 ATRACE_CALL();
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002285 {
2286 // Release mLock before acquiring mV4l2BufferLock to avoid potential
2287 // deadlock
2288 Mutex::Autolock _l(mLock);
2289 frame->unmap();
2290 v4l2_buffer buffer{};
2291 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2292 buffer.memory = V4L2_MEMORY_MMAP;
2293 buffer.index = frame->mBufferIndex;
2294 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2295 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__,
2296 frame->mBufferIndex, strerror(errno));
2297 return;
2298 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002299 }
2300
2301 {
2302 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2303 mNumDequeuedV4l2Buffers--;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002304 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002305 mV4L2BufferReturned.notify_one();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002306}
2307
2308Status ExternalCameraDeviceSession::configureStreams(
2309 const V3_2::StreamConfiguration& config, V3_3::HalStreamConfiguration* out) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002310 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002311 if (config.operationMode != StreamConfigurationMode::NORMAL_MODE) {
2312 ALOGE("%s: unsupported operation mode: %d", __FUNCTION__, config.operationMode);
2313 return Status::ILLEGAL_ARGUMENT;
2314 }
2315
2316 if (config.streams.size() == 0) {
2317 ALOGE("%s: cannot configure zero stream", __FUNCTION__);
2318 return Status::ILLEGAL_ARGUMENT;
2319 }
2320
2321 int numProcessedStream = 0;
2322 int numStallStream = 0;
2323 for (const auto& stream : config.streams) {
2324 // Check if the format/width/height combo is supported
2325 if (!isSupported(stream)) {
2326 return Status::ILLEGAL_ARGUMENT;
2327 }
2328 if (stream.format == PixelFormat::BLOB) {
2329 numStallStream++;
2330 } else {
2331 numProcessedStream++;
2332 }
2333 }
2334
2335 if (numProcessedStream > kMaxProcessedStream) {
2336 ALOGE("%s: too many processed streams (expect <= %d, got %d)", __FUNCTION__,
2337 kMaxProcessedStream, numProcessedStream);
2338 return Status::ILLEGAL_ARGUMENT;
2339 }
2340
2341 if (numStallStream > kMaxStallStream) {
2342 ALOGE("%s: too many stall streams (expect <= %d, got %d)", __FUNCTION__,
2343 kMaxStallStream, numStallStream);
2344 return Status::ILLEGAL_ARGUMENT;
2345 }
2346
2347 Status status = initStatus();
2348 if (status != Status::OK) {
2349 return status;
2350 }
2351
2352 Mutex::Autolock _l(mLock);
2353 if (!mInflightFrames.empty()) {
2354 ALOGE("%s: trying to configureStreams while there are still %zu inflight frames!",
2355 __FUNCTION__, mInflightFrames.size());
2356 return Status::INTERNAL_ERROR;
2357 }
2358
2359 // Add new streams
2360 for (const auto& stream : config.streams) {
2361 if (mStreamMap.count(stream.id) == 0) {
2362 mStreamMap[stream.id] = stream;
2363 mCirculatingBuffers.emplace(stream.id, CirculatingBuffers{});
2364 }
2365 }
2366
2367 // Cleanup removed streams
2368 for(auto it = mStreamMap.begin(); it != mStreamMap.end();) {
2369 int id = it->first;
2370 bool found = false;
2371 for (const auto& stream : config.streams) {
2372 if (id == stream.id) {
2373 found = true;
2374 break;
2375 }
2376 }
2377 if (!found) {
2378 // Unmap all buffers of deleted stream
2379 cleanupBuffersLocked(id);
2380 it = mStreamMap.erase(it);
2381 } else {
2382 ++it;
2383 }
2384 }
2385
2386 // Now select a V4L2 format to produce all output streams
2387 float desiredAr = (mCroppingType == VERTICAL) ? kMaxAspectRatio : kMinAspectRatio;
2388 uint32_t maxDim = 0;
2389 for (const auto& stream : config.streams) {
2390 float aspectRatio = ASPECT_RATIO(stream);
2391 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2392 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2393 desiredAr = aspectRatio;
2394 }
2395
2396 // The dimension that's not cropped
2397 uint32_t dim = (mCroppingType == VERTICAL) ? stream.width : stream.height;
2398 if (dim > maxDim) {
2399 maxDim = dim;
2400 }
2401 }
2402 // Find the smallest format that matches the desired aspect ratio and is wide/high enough
2403 SupportedV4L2Format v4l2Fmt {.width = 0, .height = 0};
2404 for (const auto& fmt : mSupportedFormats) {
2405 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2406 if (dim >= maxDim) {
2407 float aspectRatio = ASPECT_RATIO(fmt);
2408 if (isAspectRatioClose(aspectRatio, desiredAr)) {
2409 v4l2Fmt = fmt;
2410 // since mSupportedFormats is sorted by width then height, the first matching fmt
2411 // will be the smallest one with matching aspect ratio
2412 break;
2413 }
2414 }
2415 }
2416 if (v4l2Fmt.width == 0) {
2417 // Cannot find exact good aspect ratio candidate, try to find a close one
2418 for (const auto& fmt : mSupportedFormats) {
2419 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2420 if (dim >= maxDim) {
2421 float aspectRatio = ASPECT_RATIO(fmt);
2422 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2423 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2424 v4l2Fmt = fmt;
2425 break;
2426 }
2427 }
2428 }
2429 }
2430
2431 if (v4l2Fmt.width == 0) {
2432 ALOGE("%s: unable to find a resolution matching (%s at least %d, aspect ratio %f)"
2433 , __FUNCTION__, (mCroppingType == VERTICAL) ? "width" : "height",
2434 maxDim, desiredAr);
2435 return Status::ILLEGAL_ARGUMENT;
2436 }
2437
2438 if (configureV4l2StreamLocked(v4l2Fmt) != 0) {
2439 ALOGE("V4L configuration failed!, format:%c%c%c%c, w %d, h %d",
2440 v4l2Fmt.fourcc & 0xFF,
2441 (v4l2Fmt.fourcc >> 8) & 0xFF,
2442 (v4l2Fmt.fourcc >> 16) & 0xFF,
2443 (v4l2Fmt.fourcc >> 24) & 0xFF,
2444 v4l2Fmt.width, v4l2Fmt.height);
2445 return Status::INTERNAL_ERROR;
2446 }
2447
2448 Size v4lSize = {v4l2Fmt.width, v4l2Fmt.height};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08002449 Size thumbSize { 0, 0 };
2450 camera_metadata_ro_entry entry =
2451 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
2452 for(uint32_t i = 0; i < entry.count; i += 2) {
2453 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
2454 static_cast<uint32_t>(entry.data.i32[i+1]) };
2455 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
2456 thumbSize = sz;
2457 }
2458 }
2459
2460 if (thumbSize.width * thumbSize.height == 0) {
2461 ALOGE("%s: non-zero thumbnail size not available", __FUNCTION__);
2462 return Status::INTERNAL_ERROR;
2463 }
2464
2465 status = mOutputThread->allocateIntermediateBuffers(v4lSize,
2466 mMaxThumbResolution, config.streams);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002467 if (status != Status::OK) {
2468 ALOGE("%s: allocating intermediate buffers failed!", __FUNCTION__);
2469 return status;
2470 }
2471
2472 out->streams.resize(config.streams.size());
2473 for (size_t i = 0; i < config.streams.size(); i++) {
2474 out->streams[i].overrideDataSpace = config.streams[i].dataSpace;
2475 out->streams[i].v3_2.id = config.streams[i].id;
2476 // TODO: double check should we add those CAMERA flags
2477 mStreamMap[config.streams[i].id].usage =
2478 out->streams[i].v3_2.producerUsage = config.streams[i].usage |
2479 BufferUsage::CPU_WRITE_OFTEN |
2480 BufferUsage::CAMERA_OUTPUT;
2481 out->streams[i].v3_2.consumerUsage = 0;
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002482 out->streams[i].v3_2.maxBuffers = mV4L2BufferCount;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002483
2484 switch (config.streams[i].format) {
2485 case PixelFormat::BLOB:
2486 case PixelFormat::YCBCR_420_888:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002487 case PixelFormat::YV12: // Used by SurfaceTexture
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002488 // No override
2489 out->streams[i].v3_2.overrideFormat = config.streams[i].format;
2490 break;
2491 case PixelFormat::IMPLEMENTATION_DEFINED:
2492 // Override based on VIDEO or not
2493 out->streams[i].v3_2.overrideFormat =
2494 (config.streams[i].usage & BufferUsage::VIDEO_ENCODER) ?
2495 PixelFormat::YCBCR_420_888 : PixelFormat::YV12;
2496 // Save overridden formt in mStreamMap
2497 mStreamMap[config.streams[i].id].format = out->streams[i].v3_2.overrideFormat;
2498 break;
2499 default:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002500 ALOGE("%s: unsupported format 0x%x", __FUNCTION__, config.streams[i].format);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002501 return Status::ILLEGAL_ARGUMENT;
2502 }
2503 }
2504
2505 mFirstRequest = true;
2506 return Status::OK;
2507}
2508
2509bool ExternalCameraDeviceSession::isClosed() {
2510 Mutex::Autolock _l(mLock);
2511 return mClosed;
2512}
2513
2514#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
2515#define UPDATE(md, tag, data, size) \
2516do { \
2517 if ((md).update((tag), (data), (size))) { \
2518 ALOGE("Update " #tag " failed!"); \
2519 return BAD_VALUE; \
2520 } \
2521} while (0)
2522
2523status_t ExternalCameraDeviceSession::initDefaultRequests() {
2524 ::android::hardware::camera::common::V1_0::helper::CameraMetadata md;
2525
2526 const uint8_t aberrationMode = ANDROID_COLOR_CORRECTION_ABERRATION_MODE_OFF;
2527 UPDATE(md, ANDROID_COLOR_CORRECTION_ABERRATION_MODE, &aberrationMode, 1);
2528
2529 const int32_t exposureCompensation = 0;
2530 UPDATE(md, ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION, &exposureCompensation, 1);
2531
2532 const uint8_t videoStabilizationMode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
2533 UPDATE(md, ANDROID_CONTROL_VIDEO_STABILIZATION_MODE, &videoStabilizationMode, 1);
2534
2535 const uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO;
2536 UPDATE(md, ANDROID_CONTROL_AWB_MODE, &awbMode, 1);
2537
2538 const uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON;
2539 UPDATE(md, ANDROID_CONTROL_AE_MODE, &aeMode, 1);
2540
2541 const uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
2542 UPDATE(md, ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
2543
2544 const uint8_t afMode = ANDROID_CONTROL_AF_MODE_AUTO;
2545 UPDATE(md, ANDROID_CONTROL_AF_MODE, &afMode, 1);
2546
2547 const uint8_t afTrigger = ANDROID_CONTROL_AF_TRIGGER_IDLE;
2548 UPDATE(md, ANDROID_CONTROL_AF_TRIGGER, &afTrigger, 1);
2549
2550 const uint8_t sceneMode = ANDROID_CONTROL_SCENE_MODE_DISABLED;
2551 UPDATE(md, ANDROID_CONTROL_SCENE_MODE, &sceneMode, 1);
2552
2553 const uint8_t effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF;
2554 UPDATE(md, ANDROID_CONTROL_EFFECT_MODE, &effectMode, 1);
2555
2556 const uint8_t flashMode = ANDROID_FLASH_MODE_OFF;
2557 UPDATE(md, ANDROID_FLASH_MODE, &flashMode, 1);
2558
2559 const int32_t thumbnailSize[] = {240, 180};
2560 UPDATE(md, ANDROID_JPEG_THUMBNAIL_SIZE, thumbnailSize, 2);
2561
2562 const uint8_t jpegQuality = 90;
2563 UPDATE(md, ANDROID_JPEG_QUALITY, &jpegQuality, 1);
2564 UPDATE(md, ANDROID_JPEG_THUMBNAIL_QUALITY, &jpegQuality, 1);
2565
2566 const int32_t jpegOrientation = 0;
2567 UPDATE(md, ANDROID_JPEG_ORIENTATION, &jpegOrientation, 1);
2568
2569 const uint8_t oisMode = ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF;
2570 UPDATE(md, ANDROID_LENS_OPTICAL_STABILIZATION_MODE, &oisMode, 1);
2571
2572 const uint8_t nrMode = ANDROID_NOISE_REDUCTION_MODE_OFF;
2573 UPDATE(md, ANDROID_NOISE_REDUCTION_MODE, &nrMode, 1);
2574
2575 const uint8_t fdMode = ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
2576 UPDATE(md, ANDROID_STATISTICS_FACE_DETECT_MODE, &fdMode, 1);
2577
2578 const uint8_t hotpixelMode = ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF;
2579 UPDATE(md, ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE, &hotpixelMode, 1);
2580
2581 bool support30Fps = false;
2582 int32_t maxFps = std::numeric_limits<int32_t>::min();
2583 for (const auto& supportedFormat : mSupportedFormats) {
Yin-Chia Yeh134093a2018-02-12 14:05:48 -08002584 for (const auto& fr : supportedFormat.frameRates) {
2585 int32_t framerateInt = static_cast<int32_t>(fr.getDouble());
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002586 if (maxFps < framerateInt) {
2587 maxFps = framerateInt;
2588 }
2589 if (framerateInt == 30) {
2590 support30Fps = true;
2591 break;
2592 }
2593 }
2594 if (support30Fps) {
2595 break;
2596 }
2597 }
2598 int32_t defaultFramerate = support30Fps ? 30 : maxFps;
2599 int32_t defaultFpsRange[] = {defaultFramerate, defaultFramerate};
2600 UPDATE(md, ANDROID_CONTROL_AE_TARGET_FPS_RANGE, defaultFpsRange, ARRAY_SIZE(defaultFpsRange));
2601
2602 uint8_t antibandingMode = ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO;
2603 UPDATE(md, ANDROID_CONTROL_AE_ANTIBANDING_MODE, &antibandingMode, 1);
2604
2605 const uint8_t controlMode = ANDROID_CONTROL_MODE_AUTO;
2606 UPDATE(md, ANDROID_CONTROL_MODE, &controlMode, 1);
2607
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002608 auto requestTemplates = hidl_enum_iterator<RequestTemplate>();
2609 for (RequestTemplate type : requestTemplates) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002610 ::android::hardware::camera::common::V1_0::helper::CameraMetadata mdCopy = md;
2611 uint8_t intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2612 switch (type) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002613 case RequestTemplate::PREVIEW:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002614 intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2615 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002616 case RequestTemplate::STILL_CAPTURE:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002617 intent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE;
2618 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002619 case RequestTemplate::VIDEO_RECORD:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002620 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD;
2621 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002622 case RequestTemplate::VIDEO_SNAPSHOT:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002623 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT;
2624 break;
2625 default:
Yuriy Romanenko083de0c2018-01-26 16:05:54 -08002626 ALOGV("%s: unsupported RequestTemplate type %d", __FUNCTION__, type);
2627 continue;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002628 }
2629 UPDATE(mdCopy, ANDROID_CONTROL_CAPTURE_INTENT, &intent, 1);
2630
2631 camera_metadata_t* rawMd = mdCopy.release();
2632 CameraMetadata hidlMd;
2633 hidlMd.setToExternal(
2634 (uint8_t*) rawMd, get_camera_metadata_size(rawMd));
2635 mDefaultRequests[type] = hidlMd;
2636 free_camera_metadata(rawMd);
2637 }
2638
2639 return OK;
2640}
2641
2642status_t ExternalCameraDeviceSession::fillCaptureResult(
2643 common::V1_0::helper::CameraMetadata &md, nsecs_t timestamp) {
2644 // android.control
2645 // For USB camera, we don't know the AE state. Set the state to converged to
2646 // indicate the frame should be good to use. Then apps don't have to wait the
2647 // AE state.
2648 const uint8_t aeState = ANDROID_CONTROL_AE_STATE_CONVERGED;
2649 UPDATE(md, ANDROID_CONTROL_AE_STATE, &aeState, 1);
2650
2651 const uint8_t ae_lock = ANDROID_CONTROL_AE_LOCK_OFF;
2652 UPDATE(md, ANDROID_CONTROL_AE_LOCK, &ae_lock, 1);
2653
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002654 bool afTrigger = mAfTrigger;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002655 if (md.exists(ANDROID_CONTROL_AF_TRIGGER)) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002656 Mutex::Autolock _l(mLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002657 camera_metadata_entry entry = md.find(ANDROID_CONTROL_AF_TRIGGER);
2658 if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_START) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002659 mAfTrigger = afTrigger = true;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002660 } else if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_CANCEL) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002661 mAfTrigger = afTrigger = false;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002662 }
2663 }
2664
2665 // For USB camera, the USB camera handles everything and we don't have control
2666 // over AF. We only simply fake the AF metadata based on the request
2667 // received here.
2668 uint8_t afState;
2669 if (afTrigger) {
2670 afState = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
2671 } else {
2672 afState = ANDROID_CONTROL_AF_STATE_INACTIVE;
2673 }
2674 UPDATE(md, ANDROID_CONTROL_AF_STATE, &afState, 1);
2675
2676 // Set AWB state to converged to indicate the frame should be good to use.
2677 const uint8_t awbState = ANDROID_CONTROL_AWB_STATE_CONVERGED;
2678 UPDATE(md, ANDROID_CONTROL_AWB_STATE, &awbState, 1);
2679
2680 const uint8_t awbLock = ANDROID_CONTROL_AWB_LOCK_OFF;
2681 UPDATE(md, ANDROID_CONTROL_AWB_LOCK, &awbLock, 1);
2682
2683 camera_metadata_ro_entry active_array_size =
2684 mCameraCharacteristics.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
2685
2686 if (active_array_size.count == 0) {
2687 ALOGE("%s: cannot find active array size!", __FUNCTION__);
2688 return -EINVAL;
2689 }
2690
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002691 const uint8_t flashState = ANDROID_FLASH_STATE_UNAVAILABLE;
2692 UPDATE(md, ANDROID_FLASH_STATE, &flashState, 1);
2693
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002694 // android.scaler
2695 const int32_t crop_region[] = {
2696 active_array_size.data.i32[0], active_array_size.data.i32[1],
2697 active_array_size.data.i32[2], active_array_size.data.i32[3],
2698 };
2699 UPDATE(md, ANDROID_SCALER_CROP_REGION, crop_region, ARRAY_SIZE(crop_region));
2700
2701 // android.sensor
2702 UPDATE(md, ANDROID_SENSOR_TIMESTAMP, &timestamp, 1);
2703
2704 // android.statistics
2705 const uint8_t lensShadingMapMode = ANDROID_STATISTICS_LENS_SHADING_MAP_MODE_OFF;
2706 UPDATE(md, ANDROID_STATISTICS_LENS_SHADING_MAP_MODE, &lensShadingMapMode, 1);
2707
2708 const uint8_t sceneFlicker = ANDROID_STATISTICS_SCENE_FLICKER_NONE;
2709 UPDATE(md, ANDROID_STATISTICS_SCENE_FLICKER, &sceneFlicker, 1);
2710
2711 return OK;
2712}
2713
2714#undef ARRAY_SIZE
2715#undef UPDATE
2716
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002717} // namespace implementation
2718} // namespace V3_4
2719} // namespace device
2720} // namespace camera
2721} // namespace hardware
2722} // namespace android