blob: dc5579ac6781c17f922e4ce1b62428ce8faabf23 [file] [log] [blame]
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#define LOG_TAG "ExtCamDevSsn@3.4"
17//#define LOG_NDEBUG 0
Yin-Chia Yehe99cf202018-02-28 11:30:38 -080018#define ATRACE_TAG ATRACE_TAG_CAMERA
Yin-Chia Yeh19030592017-10-19 17:30:11 -070019#include <log/log.h>
20
21#include <inttypes.h>
22#include "ExternalCameraDeviceSession.h"
23
24#include "android-base/macros.h"
Yin-Chia Yeh19030592017-10-19 17:30:11 -070025#include <utils/Timers.h>
Yin-Chia Yehe99cf202018-02-28 11:30:38 -080026#include <utils/Trace.h>
Yin-Chia Yeh19030592017-10-19 17:30:11 -070027#include <linux/videodev2.h>
28#include <sync/sync.h>
29
30#define HAVE_JPEG // required for libyuv.h to export MJPEG decode APIs
31#include <libyuv.h>
32
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -080033#include <jpeglib.h>
34
35
Yin-Chia Yeh19030592017-10-19 17:30:11 -070036namespace android {
37namespace hardware {
38namespace camera {
39namespace device {
40namespace V3_4 {
41namespace implementation {
42
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080043namespace {
Yin-Chia Yeh19030592017-10-19 17:30:11 -070044// Size of request/result metadata fast message queue. Change to 0 to always use hwbinder buffer.
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080045static constexpr size_t kMetadataMsgQueueSize = 1 << 18 /* 256kB */;
46
Yin-Chia Yeh19030592017-10-19 17:30:11 -070047const int kBadFramesAfterStreamOn = 1; // drop x frames after streamOn to get rid of some initial
48 // bad frames. TODO: develop a better bad frame detection
49 // method
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -080050constexpr int MAX_RETRY = 15; // Allow retry some ioctl failures a few times to account for some
51 // webcam showing temporarily ioctl failures.
Yin-Chia Yeh2d61bfd2018-03-14 13:50:23 -070052constexpr int IOCTL_RETRY_SLEEP_US = 33000; // 33ms * MAX_RETRY = 0.5 seconds
Yin-Chia Yeh19030592017-10-19 17:30:11 -070053
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -080054// Constants for tryLock during dumpstate
55static constexpr int kDumpLockRetries = 50;
56static constexpr int kDumpLockSleep = 60000;
57
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -080058bool tryLock(Mutex& mutex)
59{
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -080060 bool locked = false;
61 for (int i = 0; i < kDumpLockRetries; ++i) {
62 if (mutex.tryLock() == NO_ERROR) {
63 locked = true;
64 break;
65 }
66 usleep(kDumpLockSleep);
67 }
68 return locked;
69}
70
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -080071bool tryLock(std::mutex& mutex)
72{
73 bool locked = false;
74 for (int i = 0; i < kDumpLockRetries; ++i) {
75 if (mutex.try_lock()) {
76 locked = true;
77 break;
78 }
79 usleep(kDumpLockSleep);
80 }
81 return locked;
82}
83
Yin-Chia Yehee238402018-11-04 16:30:11 -080084buffer_handle_t sEmptyBuffer = nullptr;
85
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080086} // Anonymous namespace
Yin-Chia Yeh19030592017-10-19 17:30:11 -070087
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080088// Static instances
89const int ExternalCameraDeviceSession::kMaxProcessedStream;
90const int ExternalCameraDeviceSession::kMaxStallStream;
Yin-Chia Yeh19030592017-10-19 17:30:11 -070091HandleImporter ExternalCameraDeviceSession::sHandleImporter;
92
Yin-Chia Yeh19030592017-10-19 17:30:11 -070093ExternalCameraDeviceSession::ExternalCameraDeviceSession(
94 const sp<ICameraDeviceCallback>& callback,
Yin-Chia Yeh17982492018-02-05 17:41:01 -080095 const ExternalCameraConfig& cfg,
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080096 const std::vector<SupportedV4L2Format>& sortedFormats,
97 const CroppingType& croppingType,
Yin-Chia Yeh19030592017-10-19 17:30:11 -070098 const common::V1_0::helper::CameraMetadata& chars,
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -080099 const std::string& cameraId,
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700100 unique_fd v4l2Fd) :
101 mCallback(callback),
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -0800102 mCfg(cfg),
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700103 mCameraCharacteristics(chars),
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -0800104 mSupportedFormats(sortedFormats),
105 mCroppingType(croppingType),
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800106 mCameraId(cameraId),
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700107 mV4l2Fd(std::move(v4l2Fd)),
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800108 mMaxThumbResolution(getMaxThumbResolution()),
Yin-Chia Yehee238402018-11-04 16:30:11 -0800109 mMaxJpegResolution(getMaxJpegResolution()) {}
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700110
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700111bool ExternalCameraDeviceSession::initialize() {
112 if (mV4l2Fd.get() < 0) {
113 ALOGE("%s: invalid v4l2 device fd %d!", __FUNCTION__, mV4l2Fd.get());
114 return true;
115 }
116
Yin-Chia Yeh2d61bfd2018-03-14 13:50:23 -0700117 struct v4l2_capability capability;
118 int ret = ioctl(mV4l2Fd.get(), VIDIOC_QUERYCAP, &capability);
119 std::string make, model;
120 if (ret < 0) {
121 ALOGW("%s v4l2 QUERYCAP failed", __FUNCTION__);
122 make = "Generic UVC webcam";
123 model = "Generic UVC webcam";
124 } else {
125 // capability.card is UTF-8 encoded
126 char card[32];
127 int j = 0;
128 for (int i = 0; i < 32; i++) {
129 if (capability.card[i] < 128) {
130 card[j++] = capability.card[i];
131 }
132 if (capability.card[i] == '\0') {
133 break;
134 }
135 }
136 if (j == 0 || card[j - 1] != '\0') {
137 make = "Generic UVC webcam";
138 model = "Generic UVC webcam";
139 } else {
140 make = card;
141 model = card;
142 }
143 }
Yin-Chia Yehee238402018-11-04 16:30:11 -0800144
145 initOutputThread();
146 if (mOutputThread == nullptr) {
147 ALOGE("%s: init OutputThread failed!", __FUNCTION__);
148 return true;
149 }
Yin-Chia Yeh2d61bfd2018-03-14 13:50:23 -0700150 mOutputThread->setExifMakeModel(make, model);
151
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700152 status_t status = initDefaultRequests();
153 if (status != OK) {
154 ALOGE("%s: init default requests failed!", __FUNCTION__);
155 return true;
156 }
157
158 mRequestMetadataQueue = std::make_unique<RequestMetadataQueue>(
159 kMetadataMsgQueueSize, false /* non blocking */);
160 if (!mRequestMetadataQueue->isValid()) {
161 ALOGE("%s: invalid request fmq", __FUNCTION__);
162 return true;
163 }
164 mResultMetadataQueue = std::make_shared<RequestMetadataQueue>(
165 kMetadataMsgQueueSize, false /* non blocking */);
166 if (!mResultMetadataQueue->isValid()) {
167 ALOGE("%s: invalid result fmq", __FUNCTION__);
168 return true;
169 }
170
171 // TODO: check is PRIORITY_DISPLAY enough?
172 mOutputThread->run("ExtCamOut", PRIORITY_DISPLAY);
173 return false;
174}
175
Yin-Chia Yehee238402018-11-04 16:30:11 -0800176bool ExternalCameraDeviceSession::isInitFailed() {
177 Mutex::Autolock _l(mLock);
178 if (!mInitialized) {
179 mInitFail = initialize();
180 mInitialized = true;
181 }
182 return mInitFail;
183}
184
185void ExternalCameraDeviceSession::initOutputThread() {
186 mOutputThread = new OutputThread(this, mCroppingType);
187}
188
189void ExternalCameraDeviceSession::closeOutputThread() {
190 closeOutputThreadImpl();
191}
192
193void ExternalCameraDeviceSession::closeOutputThreadImpl() {
194 if (mOutputThread) {
195 mOutputThread->flush();
196 mOutputThread->requestExit();
197 mOutputThread->join();
198 mOutputThread.clear();
199 }
200}
201
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700202Status ExternalCameraDeviceSession::initStatus() const {
203 Mutex::Autolock _l(mLock);
204 Status status = Status::OK;
205 if (mInitFail || mClosed) {
206 ALOGI("%s: sesssion initFailed %d closed %d", __FUNCTION__, mInitFail, mClosed);
207 status = Status::INTERNAL_ERROR;
208 }
209 return status;
210}
211
212ExternalCameraDeviceSession::~ExternalCameraDeviceSession() {
213 if (!isClosed()) {
214 ALOGE("ExternalCameraDeviceSession deleted before close!");
Yin-Chia Yehee238402018-11-04 16:30:11 -0800215 close(/*callerIsDtor*/true);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700216 }
217}
218
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800219
220void ExternalCameraDeviceSession::dumpState(const native_handle_t* handle) {
221 if (handle->numFds != 1 || handle->numInts != 0) {
222 ALOGE("%s: handle must contain 1 FD and 0 integers! Got %d FDs and %d ints",
223 __FUNCTION__, handle->numFds, handle->numInts);
224 return;
225 }
226 int fd = handle->data[0];
227
228 bool intfLocked = tryLock(mInterfaceLock);
229 if (!intfLocked) {
230 dprintf(fd, "!! ExternalCameraDeviceSession interface may be deadlocked !!\n");
231 }
232
233 if (isClosed()) {
234 dprintf(fd, "External camera %s is closed\n", mCameraId.c_str());
235 return;
236 }
237
238 bool streaming = false;
239 size_t v4L2BufferCount = 0;
240 SupportedV4L2Format streamingFmt;
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800241 {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800242 bool sessionLocked = tryLock(mLock);
243 if (!sessionLocked) {
244 dprintf(fd, "!! ExternalCameraDeviceSession mLock may be deadlocked !!\n");
245 }
246 streaming = mV4l2Streaming;
247 streamingFmt = mV4l2StreamingFmt;
248 v4L2BufferCount = mV4L2BufferCount;
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -0800249
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800250 if (sessionLocked) {
251 mLock.unlock();
252 }
253 }
254
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -0800255 std::unordered_set<uint32_t> inflightFrames;
256 {
257 bool iffLocked = tryLock(mInflightFramesLock);
258 if (!iffLocked) {
259 dprintf(fd,
260 "!! ExternalCameraDeviceSession mInflightFramesLock may be deadlocked !!\n");
261 }
262 inflightFrames = mInflightFrames;
263 if (iffLocked) {
264 mInflightFramesLock.unlock();
265 }
266 }
267
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800268 dprintf(fd, "External camera %s V4L2 FD %d, cropping type %s, %s\n",
269 mCameraId.c_str(), mV4l2Fd.get(),
270 (mCroppingType == VERTICAL) ? "vertical" : "horizontal",
271 streaming ? "streaming" : "not streaming");
272 if (streaming) {
273 // TODO: dump fps later
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800274 dprintf(fd, "Current V4L2 format %c%c%c%c %dx%d @ %ffps\n",
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800275 streamingFmt.fourcc & 0xFF,
276 (streamingFmt.fourcc >> 8) & 0xFF,
277 (streamingFmt.fourcc >> 16) & 0xFF,
278 (streamingFmt.fourcc >> 24) & 0xFF,
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800279 streamingFmt.width, streamingFmt.height,
280 mV4l2StreamingFps);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800281
282 size_t numDequeuedV4l2Buffers = 0;
283 {
284 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
285 numDequeuedV4l2Buffers = mNumDequeuedV4l2Buffers;
286 }
287 dprintf(fd, "V4L2 buffer queue size %zu, dequeued %zu\n",
288 v4L2BufferCount, numDequeuedV4l2Buffers);
289 }
290
291 dprintf(fd, "In-flight frames (not sorted):");
292 for (const auto& frameNumber : inflightFrames) {
293 dprintf(fd, "%d, ", frameNumber);
294 }
295 dprintf(fd, "\n");
296 mOutputThread->dump(fd);
297 dprintf(fd, "\n");
298
299 if (intfLocked) {
300 mInterfaceLock.unlock();
301 }
302
303 return;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700304}
305
306Return<void> ExternalCameraDeviceSession::constructDefaultRequestSettings(
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800307 V3_2::RequestTemplate type,
308 V3_2::ICameraDeviceSession::constructDefaultRequestSettings_cb _hidl_cb) {
309 V3_2::CameraMetadata outMetadata;
310 Status status = constructDefaultRequestSettingsRaw(
311 static_cast<RequestTemplate>(type), &outMetadata);
312 _hidl_cb(status, outMetadata);
313 return Void();
314}
315
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800316Status ExternalCameraDeviceSession::constructDefaultRequestSettingsRaw(RequestTemplate type,
317 V3_2::CameraMetadata *outMetadata) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700318 CameraMetadata emptyMd;
319 Status status = initStatus();
320 if (status != Status::OK) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800321 return status;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700322 }
323
324 switch (type) {
325 case RequestTemplate::PREVIEW:
326 case RequestTemplate::STILL_CAPTURE:
327 case RequestTemplate::VIDEO_RECORD:
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800328 case RequestTemplate::VIDEO_SNAPSHOT: {
329 *outMetadata = mDefaultRequests[type];
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700330 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800331 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700332 case RequestTemplate::MANUAL:
333 case RequestTemplate::ZERO_SHUTTER_LAG:
Eino-Ville Talvala0a2a9fc2018-02-05 16:27:15 -0800334 // Don't support MANUAL, ZSL templates
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800335 status = Status::ILLEGAL_ARGUMENT;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700336 break;
337 default:
338 ALOGE("%s: unknown request template type %d", __FUNCTION__, static_cast<int>(type));
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800339 status = Status::ILLEGAL_ARGUMENT;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700340 break;
341 }
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800342 return status;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700343}
344
345Return<void> ExternalCameraDeviceSession::configureStreams(
346 const V3_2::StreamConfiguration& streams,
347 ICameraDeviceSession::configureStreams_cb _hidl_cb) {
348 V3_2::HalStreamConfiguration outStreams;
349 V3_3::HalStreamConfiguration outStreams_v33;
350 Mutex::Autolock _il(mInterfaceLock);
351
352 Status status = configureStreams(streams, &outStreams_v33);
353 size_t size = outStreams_v33.streams.size();
354 outStreams.streams.resize(size);
355 for (size_t i = 0; i < size; i++) {
356 outStreams.streams[i] = outStreams_v33.streams[i].v3_2;
357 }
358 _hidl_cb(status, outStreams);
359 return Void();
360}
361
362Return<void> ExternalCameraDeviceSession::configureStreams_3_3(
363 const V3_2::StreamConfiguration& streams,
364 ICameraDeviceSession::configureStreams_3_3_cb _hidl_cb) {
365 V3_3::HalStreamConfiguration outStreams;
366 Mutex::Autolock _il(mInterfaceLock);
367
368 Status status = configureStreams(streams, &outStreams);
369 _hidl_cb(status, outStreams);
370 return Void();
371}
372
373Return<void> ExternalCameraDeviceSession::configureStreams_3_4(
374 const V3_4::StreamConfiguration& requestedConfiguration,
375 ICameraDeviceSession::configureStreams_3_4_cb _hidl_cb) {
376 V3_2::StreamConfiguration config_v32;
377 V3_3::HalStreamConfiguration outStreams_v33;
Yin-Chia Yeh4c641182018-08-06 15:01:20 -0700378 V3_4::HalStreamConfiguration outStreams;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700379 Mutex::Autolock _il(mInterfaceLock);
380
381 config_v32.operationMode = requestedConfiguration.operationMode;
382 config_v32.streams.resize(requestedConfiguration.streams.size());
Yin-Chia Yeh4c641182018-08-06 15:01:20 -0700383 uint32_t blobBufferSize = 0;
384 int numStallStream = 0;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700385 for (size_t i = 0; i < config_v32.streams.size(); i++) {
386 config_v32.streams[i] = requestedConfiguration.streams[i].v3_2;
Yin-Chia Yeh4c641182018-08-06 15:01:20 -0700387 if (config_v32.streams[i].format == PixelFormat::BLOB) {
388 blobBufferSize = requestedConfiguration.streams[i].bufferSize;
389 numStallStream++;
390 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700391 }
392
Yin-Chia Yeh4c641182018-08-06 15:01:20 -0700393 // Fail early if there are multiple BLOB streams
394 if (numStallStream > kMaxStallStream) {
395 ALOGE("%s: too many stall streams (expect <= %d, got %d)", __FUNCTION__,
396 kMaxStallStream, numStallStream);
397 _hidl_cb(Status::ILLEGAL_ARGUMENT, outStreams);
398 return Void();
399 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700400
Yin-Chia Yeh4c641182018-08-06 15:01:20 -0700401 Status status = configureStreams(config_v32, &outStreams_v33, blobBufferSize);
402
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700403 outStreams.streams.resize(outStreams_v33.streams.size());
404 for (size_t i = 0; i < outStreams.streams.size(); i++) {
405 outStreams.streams[i].v3_3 = outStreams_v33.streams[i];
406 }
407 _hidl_cb(status, outStreams);
408 return Void();
409}
410
411Return<void> ExternalCameraDeviceSession::getCaptureRequestMetadataQueue(
412 ICameraDeviceSession::getCaptureRequestMetadataQueue_cb _hidl_cb) {
413 Mutex::Autolock _il(mInterfaceLock);
414 _hidl_cb(*mRequestMetadataQueue->getDesc());
415 return Void();
416}
417
418Return<void> ExternalCameraDeviceSession::getCaptureResultMetadataQueue(
419 ICameraDeviceSession::getCaptureResultMetadataQueue_cb _hidl_cb) {
420 Mutex::Autolock _il(mInterfaceLock);
421 _hidl_cb(*mResultMetadataQueue->getDesc());
422 return Void();
423}
424
425Return<void> ExternalCameraDeviceSession::processCaptureRequest(
426 const hidl_vec<CaptureRequest>& requests,
427 const hidl_vec<BufferCache>& cachesToRemove,
428 ICameraDeviceSession::processCaptureRequest_cb _hidl_cb) {
429 Mutex::Autolock _il(mInterfaceLock);
430 updateBufferCaches(cachesToRemove);
431
432 uint32_t numRequestProcessed = 0;
433 Status s = Status::OK;
434 for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
435 s = processOneCaptureRequest(requests[i]);
436 if (s != Status::OK) {
437 break;
438 }
439 }
440
441 _hidl_cb(s, numRequestProcessed);
442 return Void();
443}
444
445Return<void> ExternalCameraDeviceSession::processCaptureRequest_3_4(
446 const hidl_vec<V3_4::CaptureRequest>& requests,
447 const hidl_vec<V3_2::BufferCache>& cachesToRemove,
448 ICameraDeviceSession::processCaptureRequest_3_4_cb _hidl_cb) {
449 Mutex::Autolock _il(mInterfaceLock);
450 updateBufferCaches(cachesToRemove);
451
452 uint32_t numRequestProcessed = 0;
453 Status s = Status::OK;
454 for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
455 s = processOneCaptureRequest(requests[i].v3_2);
456 if (s != Status::OK) {
457 break;
458 }
459 }
460
461 _hidl_cb(s, numRequestProcessed);
462 return Void();
463}
464
465Return<Status> ExternalCameraDeviceSession::flush() {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -0800466 ATRACE_CALL();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -0800467 Mutex::Autolock _il(mInterfaceLock);
468 Status status = initStatus();
469 if (status != Status::OK) {
470 return status;
471 }
472 mOutputThread->flush();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700473 return Status::OK;
474}
475
Yin-Chia Yehee238402018-11-04 16:30:11 -0800476Return<void> ExternalCameraDeviceSession::close(bool callerIsDtor) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700477 Mutex::Autolock _il(mInterfaceLock);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800478 bool closed = isClosed();
479 if (!closed) {
Yin-Chia Yehee238402018-11-04 16:30:11 -0800480 if (callerIsDtor) {
481 closeOutputThreadImpl();
482 } else {
483 closeOutputThread();
484 }
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800485
486 Mutex::Autolock _l(mLock);
487 // free all buffers
Yin-Chia Yehee238402018-11-04 16:30:11 -0800488 {
489 Mutex::Autolock _l(mCbsLock);
490 for(auto pair : mStreamMap) {
491 cleanupBuffersLocked(/*Stream ID*/pair.first);
492 }
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800493 }
494 v4l2StreamOffLocked();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700495 ALOGV("%s: closing V4L2 camera FD %d", __FUNCTION__, mV4l2Fd.get());
496 mV4l2Fd.reset();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700497 mClosed = true;
498 }
499 return Void();
500}
501
Yin-Chia Yehee238402018-11-04 16:30:11 -0800502Status ExternalCameraDeviceSession::importRequestLocked(
503 const CaptureRequest& request,
504 hidl_vec<buffer_handle_t*>& allBufPtrs,
505 hidl_vec<int>& allFences) {
506 return importRequestLockedImpl(request, allBufPtrs, allFences);
507}
508
509Status ExternalCameraDeviceSession::importBuffer(int32_t streamId,
510 uint64_t bufId, buffer_handle_t buf,
511 /*out*/buffer_handle_t** outBufPtr,
512 bool allowEmptyBuf) {
513 Mutex::Autolock _l(mCbsLock);
514 return importBufferLocked(streamId, bufId, buf, outBufPtr, allowEmptyBuf);
515}
516
517Status ExternalCameraDeviceSession::importBufferLocked(int32_t streamId,
518 uint64_t bufId, buffer_handle_t buf,
519 /*out*/buffer_handle_t** outBufPtr,
520 bool allowEmptyBuf) {
521
522 if (buf == nullptr && bufId == BUFFER_ID_NO_BUFFER) {
523 if (allowEmptyBuf) {
524 *outBufPtr = &sEmptyBuffer;
525 return Status::OK;
526 } else {
527 ALOGE("%s: bufferId %" PRIu64 " has null buffer handle!", __FUNCTION__, bufId);
528 return Status::ILLEGAL_ARGUMENT;
529 }
530 }
531
532 CirculatingBuffers& cbs = mCirculatingBuffers[streamId];
533 if (cbs.count(bufId) == 0) {
534 if (buf == nullptr) {
535 ALOGE("%s: bufferId %" PRIu64 " has null buffer handle!", __FUNCTION__, bufId);
536 return Status::ILLEGAL_ARGUMENT;
537 }
538 // Register a newly seen buffer
539 buffer_handle_t importedBuf = buf;
540 sHandleImporter.importBuffer(importedBuf);
541 if (importedBuf == nullptr) {
542 ALOGE("%s: output buffer for stream %d is invalid!", __FUNCTION__, streamId);
543 return Status::INTERNAL_ERROR;
544 } else {
545 cbs[bufId] = importedBuf;
546 }
547 }
548 *outBufPtr = &cbs[bufId];
549 return Status::OK;
550}
551
552Status ExternalCameraDeviceSession::importRequestLockedImpl(
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700553 const CaptureRequest& request,
554 hidl_vec<buffer_handle_t*>& allBufPtrs,
Yin-Chia Yehee238402018-11-04 16:30:11 -0800555 hidl_vec<int>& allFences,
556 bool allowEmptyBuf) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700557 size_t numOutputBufs = request.outputBuffers.size();
558 size_t numBufs = numOutputBufs;
559 // Validate all I/O buffers
560 hidl_vec<buffer_handle_t> allBufs;
561 hidl_vec<uint64_t> allBufIds;
562 allBufs.resize(numBufs);
563 allBufIds.resize(numBufs);
564 allBufPtrs.resize(numBufs);
565 allFences.resize(numBufs);
566 std::vector<int32_t> streamIds(numBufs);
567
568 for (size_t i = 0; i < numOutputBufs; i++) {
569 allBufs[i] = request.outputBuffers[i].buffer.getNativeHandle();
570 allBufIds[i] = request.outputBuffers[i].bufferId;
571 allBufPtrs[i] = &allBufs[i];
572 streamIds[i] = request.outputBuffers[i].streamId;
573 }
574
Yin-Chia Yehee238402018-11-04 16:30:11 -0800575 {
576 Mutex::Autolock _l(mCbsLock);
577 for (size_t i = 0; i < numBufs; i++) {
578 Status st = importBufferLocked(
579 streamIds[i], allBufIds[i], allBufs[i], &allBufPtrs[i],
580 allowEmptyBuf);
581 if (st != Status::OK) {
582 // Detailed error logs printed in importBuffer
583 return st;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700584 }
585 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700586 }
587
588 // All buffers are imported. Now validate output buffer acquire fences
589 for (size_t i = 0; i < numOutputBufs; i++) {
590 if (!sHandleImporter.importFence(
591 request.outputBuffers[i].acquireFence, allFences[i])) {
592 ALOGE("%s: output buffer %zu acquire fence is invalid", __FUNCTION__, i);
593 cleanupInflightFences(allFences, i);
594 return Status::INTERNAL_ERROR;
595 }
596 }
597 return Status::OK;
598}
599
600void ExternalCameraDeviceSession::cleanupInflightFences(
601 hidl_vec<int>& allFences, size_t numFences) {
602 for (size_t j = 0; j < numFences; j++) {
603 sHandleImporter.closeFence(allFences[j]);
604 }
605}
606
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800607int ExternalCameraDeviceSession::waitForV4L2BufferReturnLocked(std::unique_lock<std::mutex>& lk) {
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -0800608 ATRACE_CALL();
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800609 std::chrono::seconds timeout = std::chrono::seconds(kBufferWaitTimeoutSec);
610 mLock.unlock();
611 auto st = mV4L2BufferReturned.wait_for(lk, timeout);
612 // Here we introduce a order where mV4l2BufferLock is acquired before mLock, while
613 // the normal lock acquisition order is reversed. This is fine because in most of
614 // cases we are protected by mInterfaceLock. The only thread that can cause deadlock
615 // is the OutputThread, where we do need to make sure we don't acquire mLock then
616 // mV4l2BufferLock
617 mLock.lock();
618 if (st == std::cv_status::timeout) {
619 ALOGE("%s: wait for V4L2 buffer return timeout!", __FUNCTION__);
620 return -1;
621 }
622 return 0;
623}
624
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700625Status ExternalCameraDeviceSession::processOneCaptureRequest(const CaptureRequest& request) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -0800626 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700627 Status status = initStatus();
628 if (status != Status::OK) {
629 return status;
630 }
631
632 if (request.inputBuffer.streamId != -1) {
633 ALOGE("%s: external camera does not support reprocessing!", __FUNCTION__);
634 return Status::ILLEGAL_ARGUMENT;
635 }
636
637 Mutex::Autolock _l(mLock);
638 if (!mV4l2Streaming) {
639 ALOGE("%s: cannot process request in streamOff state!", __FUNCTION__);
640 return Status::INTERNAL_ERROR;
641 }
642
643 const camera_metadata_t *rawSettings = nullptr;
644 bool converted = true;
645 CameraMetadata settingsFmq; // settings from FMQ
646 if (request.fmqSettingsSize > 0) {
647 // non-blocking read; client must write metadata before calling
648 // processOneCaptureRequest
649 settingsFmq.resize(request.fmqSettingsSize);
650 bool read = mRequestMetadataQueue->read(settingsFmq.data(), request.fmqSettingsSize);
651 if (read) {
652 converted = V3_2::implementation::convertFromHidl(settingsFmq, &rawSettings);
653 } else {
654 ALOGE("%s: capture request settings metadata couldn't be read from fmq!", __FUNCTION__);
655 converted = false;
656 }
657 } else {
658 converted = V3_2::implementation::convertFromHidl(request.settings, &rawSettings);
659 }
660
661 if (converted && rawSettings != nullptr) {
662 mLatestReqSetting = rawSettings;
663 }
664
665 if (!converted) {
666 ALOGE("%s: capture request settings metadata is corrupt!", __FUNCTION__);
667 return Status::ILLEGAL_ARGUMENT;
668 }
669
670 if (mFirstRequest && rawSettings == nullptr) {
671 ALOGE("%s: capture request settings must not be null for first request!",
672 __FUNCTION__);
673 return Status::ILLEGAL_ARGUMENT;
674 }
675
676 hidl_vec<buffer_handle_t*> allBufPtrs;
677 hidl_vec<int> allFences;
678 size_t numOutputBufs = request.outputBuffers.size();
679
680 if (numOutputBufs == 0) {
681 ALOGE("%s: capture request must have at least one output buffer!", __FUNCTION__);
682 return Status::ILLEGAL_ARGUMENT;
683 }
684
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -0800685 camera_metadata_entry fpsRange = mLatestReqSetting.find(ANDROID_CONTROL_AE_TARGET_FPS_RANGE);
686 if (fpsRange.count == 2) {
687 double requestFpsMax = fpsRange.data.i32[1];
688 double closestFps = 0.0;
689 double fpsError = 1000.0;
690 bool fpsSupported = false;
691 for (const auto& fr : mV4l2StreamingFmt.frameRates) {
692 double f = fr.getDouble();
693 if (std::fabs(requestFpsMax - f) < 1.0) {
694 fpsSupported = true;
695 break;
696 }
697 if (std::fabs(requestFpsMax - f) < fpsError) {
698 fpsError = std::fabs(requestFpsMax - f);
699 closestFps = f;
700 }
701 }
702 if (!fpsSupported) {
703 /* This can happen in a few scenarios:
704 * 1. The application is sending a FPS range not supported by the configured outputs.
705 * 2. The application is sending a valid FPS range for all cofigured outputs, but
706 * the selected V4L2 size can only run at slower speed. This should be very rare
707 * though: for this to happen a sensor needs to support at least 3 different aspect
708 * ratio outputs, and when (at least) two outputs are both not the main aspect ratio
709 * of the webcam, a third size that's larger might be picked and runs into this
710 * issue.
711 */
712 ALOGW("%s: cannot reach fps %d! Will do %f instead",
713 __FUNCTION__, fpsRange.data.i32[1], closestFps);
714 requestFpsMax = closestFps;
715 }
716
717 if (requestFpsMax != mV4l2StreamingFps) {
718 {
719 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
720 while (mNumDequeuedV4l2Buffers != 0) {
721 // Wait until pipeline is idle before reconfigure stream
722 int waitRet = waitForV4L2BufferReturnLocked(lk);
723 if (waitRet != 0) {
724 ALOGE("%s: wait for pipeline idle failed!", __FUNCTION__);
725 return Status::INTERNAL_ERROR;
726 }
727 }
728 }
729 configureV4l2StreamLocked(mV4l2StreamingFmt, requestFpsMax);
730 }
731 }
732
Yin-Chia Yehee238402018-11-04 16:30:11 -0800733 status = importRequestLocked(request, allBufPtrs, allFences);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700734 if (status != Status::OK) {
735 return status;
736 }
737
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -0800738 nsecs_t shutterTs = 0;
739 sp<V4L2Frame> frameIn = dequeueV4l2FrameLocked(&shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700740 if ( frameIn == nullptr) {
741 ALOGE("%s: V4L2 deque frame failed!", __FUNCTION__);
742 return Status::INTERNAL_ERROR;
743 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700744
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800745 std::shared_ptr<HalRequest> halReq = std::make_shared<HalRequest>();
746 halReq->frameNumber = request.frameNumber;
747 halReq->setting = mLatestReqSetting;
748 halReq->frameIn = frameIn;
749 halReq->shutterTs = shutterTs;
750 halReq->buffers.resize(numOutputBufs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700751 for (size_t i = 0; i < numOutputBufs; i++) {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800752 HalStreamBuffer& halBuf = halReq->buffers[i];
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700753 int streamId = halBuf.streamId = request.outputBuffers[i].streamId;
754 halBuf.bufferId = request.outputBuffers[i].bufferId;
755 const Stream& stream = mStreamMap[streamId];
756 halBuf.width = stream.width;
757 halBuf.height = stream.height;
758 halBuf.format = stream.format;
759 halBuf.usage = stream.usage;
760 halBuf.bufPtr = allBufPtrs[i];
761 halBuf.acquireFence = allFences[i];
762 halBuf.fenceTimeout = false;
763 }
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -0800764 {
765 std::lock_guard<std::mutex> lk(mInflightFramesLock);
766 mInflightFrames.insert(halReq->frameNumber);
767 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700768 // Send request to OutputThread for the rest of processing
769 mOutputThread->submitRequest(halReq);
770 mFirstRequest = false;
771 return Status::OK;
772}
773
774void ExternalCameraDeviceSession::notifyShutter(uint32_t frameNumber, nsecs_t shutterTs) {
775 NotifyMsg msg;
776 msg.type = MsgType::SHUTTER;
777 msg.msg.shutter.frameNumber = frameNumber;
778 msg.msg.shutter.timestamp = shutterTs;
779 mCallback->notify({msg});
780}
781
782void ExternalCameraDeviceSession::notifyError(
783 uint32_t frameNumber, int32_t streamId, ErrorCode ec) {
784 NotifyMsg msg;
785 msg.type = MsgType::ERROR;
786 msg.msg.error.frameNumber = frameNumber;
787 msg.msg.error.errorStreamId = streamId;
788 msg.msg.error.errorCode = ec;
789 mCallback->notify({msg});
790}
791
792//TODO: refactor with processCaptureResult
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800793Status ExternalCameraDeviceSession::processCaptureRequestError(
794 const std::shared_ptr<HalRequest>& req) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -0800795 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700796 // Return V4L2 buffer to V4L2 buffer queue
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800797 enqueueV4l2Frame(req->frameIn);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700798
799 // NotifyShutter
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800800 notifyShutter(req->frameNumber, req->shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700801
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800802 notifyError(/*frameNum*/req->frameNumber, /*stream*/-1, ErrorCode::ERROR_REQUEST);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700803
804 // Fill output buffers
805 hidl_vec<CaptureResult> results;
806 results.resize(1);
807 CaptureResult& result = results[0];
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800808 result.frameNumber = req->frameNumber;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700809 result.partialResult = 1;
810 result.inputBuffer.streamId = -1;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800811 result.outputBuffers.resize(req->buffers.size());
812 for (size_t i = 0; i < req->buffers.size(); i++) {
813 result.outputBuffers[i].streamId = req->buffers[i].streamId;
814 result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700815 result.outputBuffers[i].status = BufferStatus::ERROR;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800816 if (req->buffers[i].acquireFence >= 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700817 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800818 handle->data[0] = req->buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800819 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700820 }
821 }
822
823 // update inflight records
824 {
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -0800825 std::lock_guard<std::mutex> lk(mInflightFramesLock);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800826 mInflightFrames.erase(req->frameNumber);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700827 }
828
829 // Callback into framework
830 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
831 freeReleaseFences(results);
832 return Status::OK;
833}
834
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800835Status ExternalCameraDeviceSession::processCaptureResult(std::shared_ptr<HalRequest>& req) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -0800836 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700837 // Return V4L2 buffer to V4L2 buffer queue
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800838 enqueueV4l2Frame(req->frameIn);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700839
840 // NotifyShutter
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800841 notifyShutter(req->frameNumber, req->shutterTs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700842
843 // Fill output buffers
844 hidl_vec<CaptureResult> results;
845 results.resize(1);
846 CaptureResult& result = results[0];
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800847 result.frameNumber = req->frameNumber;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700848 result.partialResult = 1;
849 result.inputBuffer.streamId = -1;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800850 result.outputBuffers.resize(req->buffers.size());
851 for (size_t i = 0; i < req->buffers.size(); i++) {
852 result.outputBuffers[i].streamId = req->buffers[i].streamId;
853 result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
854 if (req->buffers[i].fenceTimeout) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700855 result.outputBuffers[i].status = BufferStatus::ERROR;
Yin-Chia Yeh965d9dd2019-03-14 14:21:01 -0700856 if (req->buffers[i].acquireFence >= 0) {
Yin-Chia Yehee238402018-11-04 16:30:11 -0800857 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
858 handle->data[0] = req->buffers[i].acquireFence;
859 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
860 }
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800861 notifyError(req->frameNumber, req->buffers[i].streamId, ErrorCode::ERROR_BUFFER);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700862 } else {
863 result.outputBuffers[i].status = BufferStatus::OK;
864 // TODO: refactor
Yin-Chia Yeh965d9dd2019-03-14 14:21:01 -0700865 if (req->buffers[i].acquireFence >= 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700866 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800867 handle->data[0] = req->buffers[i].acquireFence;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800868 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700869 }
870 }
871 }
872
873 // Fill capture result metadata
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800874 fillCaptureResult(req->setting, req->shutterTs);
875 const camera_metadata_t *rawResult = req->setting.getAndLock();
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700876 V3_2::implementation::convertToHidl(rawResult, &result.result);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800877 req->setting.unlock(rawResult);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700878
879 // update inflight records
880 {
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -0800881 std::lock_guard<std::mutex> lk(mInflightFramesLock);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -0800882 mInflightFrames.erase(req->frameNumber);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700883 }
884
885 // Callback into framework
886 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
887 freeReleaseFences(results);
888 return Status::OK;
889}
890
891void ExternalCameraDeviceSession::invokeProcessCaptureResultCallback(
892 hidl_vec<CaptureResult> &results, bool tryWriteFmq) {
893 if (mProcessCaptureResultLock.tryLock() != OK) {
894 const nsecs_t NS_TO_SECOND = 1000000000;
895 ALOGV("%s: previous call is not finished! waiting 1s...", __FUNCTION__);
896 if (mProcessCaptureResultLock.timedLock(/* 1s */NS_TO_SECOND) != OK) {
897 ALOGE("%s: cannot acquire lock in 1s, cannot proceed",
898 __FUNCTION__);
899 return;
900 }
901 }
902 if (tryWriteFmq && mResultMetadataQueue->availableToWrite() > 0) {
903 for (CaptureResult &result : results) {
904 if (result.result.size() > 0) {
905 if (mResultMetadataQueue->write(result.result.data(), result.result.size())) {
906 result.fmqResultSize = result.result.size();
907 result.result.resize(0);
908 } else {
909 ALOGW("%s: couldn't utilize fmq, fall back to hwbinder", __FUNCTION__);
910 result.fmqResultSize = 0;
911 }
912 } else {
913 result.fmqResultSize = 0;
914 }
915 }
916 }
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -0800917 auto status = mCallback->processCaptureResult(results);
918 if (!status.isOk()) {
919 ALOGE("%s: processCaptureResult ERROR : %s", __FUNCTION__,
920 status.description().c_str());
921 }
922
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700923 mProcessCaptureResultLock.unlock();
924}
925
926void ExternalCameraDeviceSession::freeReleaseFences(hidl_vec<CaptureResult>& results) {
927 for (auto& result : results) {
928 if (result.inputBuffer.releaseFence.getNativeHandle() != nullptr) {
929 native_handle_t* handle = const_cast<native_handle_t*>(
930 result.inputBuffer.releaseFence.getNativeHandle());
931 native_handle_close(handle);
932 native_handle_delete(handle);
933 }
934 for (auto& buf : result.outputBuffers) {
935 if (buf.releaseFence.getNativeHandle() != nullptr) {
936 native_handle_t* handle = const_cast<native_handle_t*>(
937 buf.releaseFence.getNativeHandle());
938 native_handle_close(handle);
939 native_handle_delete(handle);
940 }
941 }
942 }
943 return;
944}
945
946ExternalCameraDeviceSession::OutputThread::OutputThread(
947 wp<ExternalCameraDeviceSession> parent,
948 CroppingType ct) : mParent(parent), mCroppingType(ct) {}
949
950ExternalCameraDeviceSession::OutputThread::~OutputThread() {}
951
Yin-Chia Yeh2d61bfd2018-03-14 13:50:23 -0700952void ExternalCameraDeviceSession::OutputThread::setExifMakeModel(
953 const std::string& make, const std::string& model) {
954 mExifMake = make;
955 mExifModel = model;
956}
957
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700958uint32_t ExternalCameraDeviceSession::OutputThread::getFourCcFromLayout(
959 const YCbCrLayout& layout) {
960 intptr_t cb = reinterpret_cast<intptr_t>(layout.cb);
961 intptr_t cr = reinterpret_cast<intptr_t>(layout.cr);
962 if (std::abs(cb - cr) == 1 && layout.chromaStep == 2) {
963 // Interleaved format
964 if (layout.cb > layout.cr) {
965 return V4L2_PIX_FMT_NV21;
966 } else {
967 return V4L2_PIX_FMT_NV12;
968 }
969 } else if (layout.chromaStep == 1) {
970 // Planar format
971 if (layout.cb > layout.cr) {
972 return V4L2_PIX_FMT_YVU420; // YV12
973 } else {
974 return V4L2_PIX_FMT_YUV420; // YU12
975 }
976 } else {
977 return FLEX_YUV_GENERIC;
978 }
979}
980
981int ExternalCameraDeviceSession::OutputThread::getCropRect(
982 CroppingType ct, const Size& inSize, const Size& outSize, IMapper::Rect* out) {
983 if (out == nullptr) {
984 ALOGE("%s: out is null", __FUNCTION__);
985 return -1;
986 }
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800987
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700988 uint32_t inW = inSize.width;
989 uint32_t inH = inSize.height;
990 uint32_t outW = outSize.width;
991 uint32_t outH = outSize.height;
992
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800993 // Handle special case where aspect ratio is close to input but scaled
994 // dimension is slightly larger than input
995 float arIn = ASPECT_RATIO(inSize);
996 float arOut = ASPECT_RATIO(outSize);
997 if (isAspectRatioClose(arIn, arOut)) {
998 out->left = 0;
999 out->top = 0;
1000 out->width = inW;
1001 out->height = inH;
1002 return 0;
1003 }
1004
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001005 if (ct == VERTICAL) {
1006 uint64_t scaledOutH = static_cast<uint64_t>(outH) * inW / outW;
1007 if (scaledOutH > inH) {
1008 ALOGE("%s: Output size %dx%d cannot be vertically cropped from input size %dx%d",
1009 __FUNCTION__, outW, outH, inW, inH);
1010 return -1;
1011 }
1012 scaledOutH = scaledOutH & ~0x1; // make it multiple of 2
1013
1014 out->left = 0;
1015 out->top = ((inH - scaledOutH) / 2) & ~0x1;
1016 out->width = inW;
1017 out->height = static_cast<int32_t>(scaledOutH);
1018 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledH %d",
1019 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutH));
1020 } else {
1021 uint64_t scaledOutW = static_cast<uint64_t>(outW) * inH / outH;
1022 if (scaledOutW > inW) {
1023 ALOGE("%s: Output size %dx%d cannot be horizontally cropped from input size %dx%d",
1024 __FUNCTION__, outW, outH, inW, inH);
1025 return -1;
1026 }
1027 scaledOutW = scaledOutW & ~0x1; // make it multiple of 2
1028
1029 out->left = ((inW - scaledOutW) / 2) & ~0x1;
1030 out->top = 0;
1031 out->width = static_cast<int32_t>(scaledOutW);
1032 out->height = inH;
1033 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledW %d",
1034 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutW));
1035 }
1036
1037 return 0;
1038}
1039
1040int ExternalCameraDeviceSession::OutputThread::cropAndScaleLocked(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001041 sp<AllocatedFrame>& in, const Size& outSz, YCbCrLayout* out) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001042 Size inSz = {in->mWidth, in->mHeight};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001043
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001044 int ret;
1045 if (inSz == outSz) {
1046 ret = in->getLayout(out);
1047 if (ret != 0) {
1048 ALOGE("%s: failed to get input image layout", __FUNCTION__);
1049 return ret;
1050 }
1051 return ret;
1052 }
1053
1054 // Cropping to output aspect ratio
1055 IMapper::Rect inputCrop;
1056 ret = getCropRect(mCroppingType, inSz, outSz, &inputCrop);
1057 if (ret != 0) {
1058 ALOGE("%s: failed to compute crop rect for output size %dx%d",
1059 __FUNCTION__, outSz.width, outSz.height);
1060 return ret;
1061 }
1062
1063 YCbCrLayout croppedLayout;
1064 ret = in->getCroppedLayout(inputCrop, &croppedLayout);
1065 if (ret != 0) {
1066 ALOGE("%s: failed to crop input image %dx%d to output size %dx%d",
1067 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1068 return ret;
1069 }
1070
1071 if ((mCroppingType == VERTICAL && inSz.width == outSz.width) ||
1072 (mCroppingType == HORIZONTAL && inSz.height == outSz.height)) {
1073 // No scale is needed
1074 *out = croppedLayout;
1075 return 0;
1076 }
1077
1078 auto it = mScaledYu12Frames.find(outSz);
1079 sp<AllocatedFrame> scaledYu12Buf;
1080 if (it != mScaledYu12Frames.end()) {
1081 scaledYu12Buf = it->second;
1082 } else {
1083 it = mIntermediateBuffers.find(outSz);
1084 if (it == mIntermediateBuffers.end()) {
1085 ALOGE("%s: failed to find intermediate buffer size %dx%d",
1086 __FUNCTION__, outSz.width, outSz.height);
1087 return -1;
1088 }
1089 scaledYu12Buf = it->second;
1090 }
1091 // Scale
1092 YCbCrLayout outLayout;
1093 ret = scaledYu12Buf->getLayout(&outLayout);
1094 if (ret != 0) {
1095 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
1096 return ret;
1097 }
1098
1099 ret = libyuv::I420Scale(
1100 static_cast<uint8_t*>(croppedLayout.y),
1101 croppedLayout.yStride,
1102 static_cast<uint8_t*>(croppedLayout.cb),
1103 croppedLayout.cStride,
1104 static_cast<uint8_t*>(croppedLayout.cr),
1105 croppedLayout.cStride,
1106 inputCrop.width,
1107 inputCrop.height,
1108 static_cast<uint8_t*>(outLayout.y),
1109 outLayout.yStride,
1110 static_cast<uint8_t*>(outLayout.cb),
1111 outLayout.cStride,
1112 static_cast<uint8_t*>(outLayout.cr),
1113 outLayout.cStride,
1114 outSz.width,
1115 outSz.height,
1116 // TODO: b/72261744 see if we can use better filter without losing too much perf
1117 libyuv::FilterMode::kFilterNone);
1118
1119 if (ret != 0) {
1120 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
1121 __FUNCTION__, inputCrop.width, inputCrop.height,
1122 outSz.width, outSz.height, ret);
1123 return ret;
1124 }
1125
1126 *out = outLayout;
1127 mScaledYu12Frames.insert({outSz, scaledYu12Buf});
1128 return 0;
1129}
1130
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001131
1132int ExternalCameraDeviceSession::OutputThread::cropAndScaleThumbLocked(
1133 sp<AllocatedFrame>& in, const Size &outSz, YCbCrLayout* out) {
1134 Size inSz {in->mWidth, in->mHeight};
1135
1136 if ((outSz.width * outSz.height) >
1137 (mYu12ThumbFrame->mWidth * mYu12ThumbFrame->mHeight)) {
1138 ALOGE("%s: Requested thumbnail size too big (%d,%d) > (%d,%d)",
1139 __FUNCTION__, outSz.width, outSz.height,
1140 mYu12ThumbFrame->mWidth, mYu12ThumbFrame->mHeight);
1141 return -1;
1142 }
1143
1144 int ret;
1145
1146 /* This will crop-and-zoom the input YUV frame to the thumbnail size
1147 * Based on the following logic:
1148 * 1) Square pixels come in, square pixels come out, therefore single
1149 * scale factor is computed to either make input bigger or smaller
1150 * depending on if we are upscaling or downscaling
1151 * 2) That single scale factor would either make height too tall or width
1152 * too wide so we need to crop the input either horizontally or vertically
1153 * but not both
1154 */
1155
1156 /* Convert the input and output dimensions into floats for ease of math */
1157 float fWin = static_cast<float>(inSz.width);
1158 float fHin = static_cast<float>(inSz.height);
1159 float fWout = static_cast<float>(outSz.width);
1160 float fHout = static_cast<float>(outSz.height);
1161
1162 /* Compute the one scale factor from (1) above, it will be the smaller of
1163 * the two possibilities. */
1164 float scaleFactor = std::min( fHin / fHout, fWin / fWout );
1165
1166 /* Since we are crop-and-zooming (as opposed to letter/pillar boxing) we can
1167 * simply multiply the output by our scaleFactor to get the cropped input
1168 * size. Note that at least one of {fWcrop, fHcrop} is going to wind up
1169 * being {fWin, fHin} respectively because fHout or fWout cancels out the
1170 * scaleFactor calculation above.
1171 *
1172 * Specifically:
1173 * if ( fHin / fHout ) < ( fWin / fWout ) we crop the sides off
1174 * input, in which case
1175 * scaleFactor = fHin / fHout
1176 * fWcrop = fHin / fHout * fWout
1177 * fHcrop = fHin
1178 *
1179 * Note that fWcrop <= fWin ( because ( fHin / fHout ) * fWout < fWin, which
1180 * is just the inequality above with both sides multiplied by fWout
1181 *
1182 * on the other hand if ( fWin / fWout ) < ( fHin / fHout) we crop the top
1183 * and the bottom off of input, and
1184 * scaleFactor = fWin / fWout
1185 * fWcrop = fWin
1186 * fHCrop = fWin / fWout * fHout
1187 */
1188 float fWcrop = scaleFactor * fWout;
1189 float fHcrop = scaleFactor * fHout;
1190
1191 /* Convert to integer and truncate to an even number */
1192 Size cropSz = { 2*static_cast<uint32_t>(fWcrop/2.0f),
1193 2*static_cast<uint32_t>(fHcrop/2.0f) };
1194
1195 /* Convert to a centered rectange with even top/left */
1196 IMapper::Rect inputCrop {
1197 2*static_cast<int32_t>((inSz.width - cropSz.width)/4),
1198 2*static_cast<int32_t>((inSz.height - cropSz.height)/4),
1199 static_cast<int32_t>(cropSz.width),
1200 static_cast<int32_t>(cropSz.height) };
1201
1202 if ((inputCrop.top < 0) ||
1203 (inputCrop.top >= static_cast<int32_t>(inSz.height)) ||
1204 (inputCrop.left < 0) ||
1205 (inputCrop.left >= static_cast<int32_t>(inSz.width)) ||
1206 (inputCrop.width <= 0) ||
1207 (inputCrop.width + inputCrop.left > static_cast<int32_t>(inSz.width)) ||
1208 (inputCrop.height <= 0) ||
1209 (inputCrop.height + inputCrop.top > static_cast<int32_t>(inSz.height)))
1210 {
1211 ALOGE("%s: came up with really wrong crop rectangle",__FUNCTION__);
1212 ALOGE("%s: input layout %dx%d to for output size %dx%d",
1213 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1214 ALOGE("%s: computed input crop +%d,+%d %dx%d",
1215 __FUNCTION__, inputCrop.left, inputCrop.top,
1216 inputCrop.width, inputCrop.height);
1217 return -1;
1218 }
1219
1220 YCbCrLayout inputLayout;
1221 ret = in->getCroppedLayout(inputCrop, &inputLayout);
1222 if (ret != 0) {
1223 ALOGE("%s: failed to crop input layout %dx%d to for output size %dx%d",
1224 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1225 ALOGE("%s: computed input crop +%d,+%d %dx%d",
1226 __FUNCTION__, inputCrop.left, inputCrop.top,
1227 inputCrop.width, inputCrop.height);
1228 return ret;
1229 }
1230 ALOGV("%s: crop input layout %dx%d to for output size %dx%d",
1231 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
1232 ALOGV("%s: computed input crop +%d,+%d %dx%d",
1233 __FUNCTION__, inputCrop.left, inputCrop.top,
1234 inputCrop.width, inputCrop.height);
1235
1236
1237 // Scale
1238 YCbCrLayout outFullLayout;
1239
1240 ret = mYu12ThumbFrame->getLayout(&outFullLayout);
1241 if (ret != 0) {
1242 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
1243 return ret;
1244 }
1245
1246
1247 ret = libyuv::I420Scale(
1248 static_cast<uint8_t*>(inputLayout.y),
1249 inputLayout.yStride,
1250 static_cast<uint8_t*>(inputLayout.cb),
1251 inputLayout.cStride,
1252 static_cast<uint8_t*>(inputLayout.cr),
1253 inputLayout.cStride,
1254 inputCrop.width,
1255 inputCrop.height,
1256 static_cast<uint8_t*>(outFullLayout.y),
1257 outFullLayout.yStride,
1258 static_cast<uint8_t*>(outFullLayout.cb),
1259 outFullLayout.cStride,
1260 static_cast<uint8_t*>(outFullLayout.cr),
1261 outFullLayout.cStride,
1262 outSz.width,
1263 outSz.height,
1264 libyuv::FilterMode::kFilterNone);
1265
1266 if (ret != 0) {
1267 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
1268 __FUNCTION__, inputCrop.width, inputCrop.height,
1269 outSz.width, outSz.height, ret);
1270 return ret;
1271 }
1272
1273 *out = outFullLayout;
1274 return 0;
1275}
1276
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001277int ExternalCameraDeviceSession::OutputThread::formatConvertLocked(
1278 const YCbCrLayout& in, const YCbCrLayout& out, Size sz, uint32_t format) {
1279 int ret = 0;
1280 switch (format) {
1281 case V4L2_PIX_FMT_NV21:
1282 ret = libyuv::I420ToNV21(
1283 static_cast<uint8_t*>(in.y),
1284 in.yStride,
1285 static_cast<uint8_t*>(in.cb),
1286 in.cStride,
1287 static_cast<uint8_t*>(in.cr),
1288 in.cStride,
1289 static_cast<uint8_t*>(out.y),
1290 out.yStride,
1291 static_cast<uint8_t*>(out.cr),
1292 out.cStride,
1293 sz.width,
1294 sz.height);
1295 if (ret != 0) {
1296 ALOGE("%s: convert to NV21 buffer failed! ret %d",
1297 __FUNCTION__, ret);
1298 return ret;
1299 }
1300 break;
1301 case V4L2_PIX_FMT_NV12:
1302 ret = libyuv::I420ToNV12(
1303 static_cast<uint8_t*>(in.y),
1304 in.yStride,
1305 static_cast<uint8_t*>(in.cb),
1306 in.cStride,
1307 static_cast<uint8_t*>(in.cr),
1308 in.cStride,
1309 static_cast<uint8_t*>(out.y),
1310 out.yStride,
1311 static_cast<uint8_t*>(out.cb),
1312 out.cStride,
1313 sz.width,
1314 sz.height);
1315 if (ret != 0) {
1316 ALOGE("%s: convert to NV12 buffer failed! ret %d",
1317 __FUNCTION__, ret);
1318 return ret;
1319 }
1320 break;
1321 case V4L2_PIX_FMT_YVU420: // YV12
1322 case V4L2_PIX_FMT_YUV420: // YU12
1323 // TODO: maybe we can speed up here by somehow save this copy?
1324 ret = libyuv::I420Copy(
1325 static_cast<uint8_t*>(in.y),
1326 in.yStride,
1327 static_cast<uint8_t*>(in.cb),
1328 in.cStride,
1329 static_cast<uint8_t*>(in.cr),
1330 in.cStride,
1331 static_cast<uint8_t*>(out.y),
1332 out.yStride,
1333 static_cast<uint8_t*>(out.cb),
1334 out.cStride,
1335 static_cast<uint8_t*>(out.cr),
1336 out.cStride,
1337 sz.width,
1338 sz.height);
1339 if (ret != 0) {
1340 ALOGE("%s: copy to YV12 or YU12 buffer failed! ret %d",
1341 __FUNCTION__, ret);
1342 return ret;
1343 }
1344 break;
1345 case FLEX_YUV_GENERIC:
1346 // TODO: b/72261744 write to arbitrary flexible YUV layout. Slow.
1347 ALOGE("%s: unsupported flexible yuv layout"
1348 " y %p cb %p cr %p y_str %d c_str %d c_step %d",
1349 __FUNCTION__, out.y, out.cb, out.cr,
1350 out.yStride, out.cStride, out.chromaStep);
1351 return -1;
1352 default:
1353 ALOGE("%s: unknown YUV format 0x%x!", __FUNCTION__, format);
1354 return -1;
1355 }
1356 return 0;
1357}
1358
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001359int ExternalCameraDeviceSession::OutputThread::encodeJpegYU12(
1360 const Size & inSz, const YCbCrLayout& inLayout,
1361 int jpegQuality, const void *app1Buffer, size_t app1Size,
1362 void *out, const size_t maxOutSize, size_t &actualCodeSize)
1363{
1364 /* libjpeg is a C library so we use C-style "inheritance" by
1365 * putting libjpeg's jpeg_destination_mgr first in our custom
1366 * struct. This allows us to cast jpeg_destination_mgr* to
1367 * CustomJpegDestMgr* when we get it passed to us in a callback */
1368 struct CustomJpegDestMgr {
1369 struct jpeg_destination_mgr mgr;
1370 JOCTET *mBuffer;
1371 size_t mBufferSize;
1372 size_t mEncodedSize;
1373 bool mSuccess;
1374 } dmgr;
1375
1376 jpeg_compress_struct cinfo = {};
1377 jpeg_error_mgr jerr;
1378
1379 /* Initialize error handling with standard callbacks, but
1380 * then override output_message (to print to ALOG) and
1381 * error_exit to set a flag and print a message instead
1382 * of killing the whole process */
1383 cinfo.err = jpeg_std_error(&jerr);
1384
1385 cinfo.err->output_message = [](j_common_ptr cinfo) {
1386 char buffer[JMSG_LENGTH_MAX];
1387
1388 /* Create the message */
1389 (*cinfo->err->format_message)(cinfo, buffer);
1390 ALOGE("libjpeg error: %s", buffer);
1391 };
1392 cinfo.err->error_exit = [](j_common_ptr cinfo) {
1393 (*cinfo->err->output_message)(cinfo);
1394 if(cinfo->client_data) {
1395 auto & dmgr =
1396 *reinterpret_cast<CustomJpegDestMgr*>(cinfo->client_data);
1397 dmgr.mSuccess = false;
1398 }
1399 };
1400 /* Now that we initialized some callbacks, let's create our compressor */
1401 jpeg_create_compress(&cinfo);
1402
1403 /* Initialize our destination manager */
1404 dmgr.mBuffer = static_cast<JOCTET*>(out);
1405 dmgr.mBufferSize = maxOutSize;
1406 dmgr.mEncodedSize = 0;
1407 dmgr.mSuccess = true;
1408 cinfo.client_data = static_cast<void*>(&dmgr);
1409
1410 /* These lambdas become C-style function pointers and as per C++11 spec
1411 * may not capture anything */
1412 dmgr.mgr.init_destination = [](j_compress_ptr cinfo) {
1413 auto & dmgr = reinterpret_cast<CustomJpegDestMgr&>(*cinfo->dest);
1414 dmgr.mgr.next_output_byte = dmgr.mBuffer;
1415 dmgr.mgr.free_in_buffer = dmgr.mBufferSize;
1416 ALOGV("%s:%d jpeg start: %p [%zu]",
1417 __FUNCTION__, __LINE__, dmgr.mBuffer, dmgr.mBufferSize);
1418 };
1419
1420 dmgr.mgr.empty_output_buffer = [](j_compress_ptr cinfo __unused) {
1421 ALOGV("%s:%d Out of buffer", __FUNCTION__, __LINE__);
1422 return 0;
1423 };
1424
1425 dmgr.mgr.term_destination = [](j_compress_ptr cinfo) {
1426 auto & dmgr = reinterpret_cast<CustomJpegDestMgr&>(*cinfo->dest);
1427 dmgr.mEncodedSize = dmgr.mBufferSize - dmgr.mgr.free_in_buffer;
1428 ALOGV("%s:%d Done with jpeg: %zu", __FUNCTION__, __LINE__, dmgr.mEncodedSize);
1429 };
1430 cinfo.dest = reinterpret_cast<struct jpeg_destination_mgr*>(&dmgr);
1431
1432 /* We are going to be using JPEG in raw data mode, so we are passing
1433 * straight subsampled planar YCbCr and it will not touch our pixel
1434 * data or do any scaling or anything */
1435 cinfo.image_width = inSz.width;
1436 cinfo.image_height = inSz.height;
1437 cinfo.input_components = 3;
1438 cinfo.in_color_space = JCS_YCbCr;
1439
1440 /* Initialize defaults and then override what we want */
1441 jpeg_set_defaults(&cinfo);
1442
1443 jpeg_set_quality(&cinfo, jpegQuality, 1);
1444 jpeg_set_colorspace(&cinfo, JCS_YCbCr);
1445 cinfo.raw_data_in = 1;
1446 cinfo.dct_method = JDCT_IFAST;
1447
1448 /* Configure sampling factors. The sampling factor is JPEG subsampling 420
1449 * because the source format is YUV420. Note that libjpeg sampling factors
1450 * are... a little weird. Sampling of Y=2,U=1,V=1 means there is 1 U and
1451 * 1 V value for each 2 Y values */
1452 cinfo.comp_info[0].h_samp_factor = 2;
1453 cinfo.comp_info[0].v_samp_factor = 2;
1454 cinfo.comp_info[1].h_samp_factor = 1;
1455 cinfo.comp_info[1].v_samp_factor = 1;
1456 cinfo.comp_info[2].h_samp_factor = 1;
1457 cinfo.comp_info[2].v_samp_factor = 1;
1458
1459 /* Let's not hardcode YUV420 in 6 places... 5 was enough */
1460 int maxVSampFactor = std::max( {
1461 cinfo.comp_info[0].v_samp_factor,
1462 cinfo.comp_info[1].v_samp_factor,
1463 cinfo.comp_info[2].v_samp_factor
1464 });
1465 int cVSubSampling = cinfo.comp_info[0].v_samp_factor /
1466 cinfo.comp_info[1].v_samp_factor;
1467
1468 /* Start the compressor */
1469 jpeg_start_compress(&cinfo, TRUE);
1470
1471 /* Compute our macroblock height, so we can pad our input to be vertically
1472 * macroblock aligned.
1473 * TODO: Does it need to be horizontally MCU aligned too? */
1474
1475 size_t mcuV = DCTSIZE*maxVSampFactor;
1476 size_t paddedHeight = mcuV * ((inSz.height + mcuV - 1) / mcuV);
1477
1478 /* libjpeg uses arrays of row pointers, which makes it really easy to pad
1479 * data vertically (unfortunately doesn't help horizontally) */
1480 std::vector<JSAMPROW> yLines (paddedHeight);
1481 std::vector<JSAMPROW> cbLines(paddedHeight/cVSubSampling);
1482 std::vector<JSAMPROW> crLines(paddedHeight/cVSubSampling);
1483
1484 uint8_t *py = static_cast<uint8_t*>(inLayout.y);
1485 uint8_t *pcr = static_cast<uint8_t*>(inLayout.cr);
1486 uint8_t *pcb = static_cast<uint8_t*>(inLayout.cb);
1487
1488 for(uint32_t i = 0; i < paddedHeight; i++)
1489 {
1490 /* Once we are in the padding territory we still point to the last line
1491 * effectively replicating it several times ~ CLAMP_TO_EDGE */
1492 int li = std::min(i, inSz.height - 1);
1493 yLines[i] = static_cast<JSAMPROW>(py + li * inLayout.yStride);
1494 if(i < paddedHeight / cVSubSampling)
1495 {
1496 crLines[i] = static_cast<JSAMPROW>(pcr + li * inLayout.cStride);
1497 cbLines[i] = static_cast<JSAMPROW>(pcb + li * inLayout.cStride);
1498 }
1499 }
1500
1501 /* If APP1 data was passed in, use it */
1502 if(app1Buffer && app1Size)
1503 {
1504 jpeg_write_marker(&cinfo, JPEG_APP0 + 1,
1505 static_cast<const JOCTET*>(app1Buffer), app1Size);
1506 }
1507
1508 /* While we still have padded height left to go, keep giving it one
1509 * macroblock at a time. */
1510 while (cinfo.next_scanline < cinfo.image_height) {
1511 const uint32_t batchSize = DCTSIZE * maxVSampFactor;
1512 const uint32_t nl = cinfo.next_scanline;
1513 JSAMPARRAY planes[3]{ &yLines[nl],
1514 &cbLines[nl/cVSubSampling],
1515 &crLines[nl/cVSubSampling] };
1516
1517 uint32_t done = jpeg_write_raw_data(&cinfo, planes, batchSize);
1518
1519 if (done != batchSize) {
1520 ALOGE("%s: compressed %u lines, expected %u (total %u/%u)",
1521 __FUNCTION__, done, batchSize, cinfo.next_scanline,
1522 cinfo.image_height);
1523 return -1;
1524 }
1525 }
1526
1527 /* This will flush everything */
1528 jpeg_finish_compress(&cinfo);
1529
1530 /* Grab the actual code size and set it */
1531 actualCodeSize = dmgr.mEncodedSize;
1532
1533 return 0;
1534}
1535
1536/*
1537 * TODO: There needs to be a mechanism to discover allocated buffer size
1538 * in the HAL.
1539 *
1540 * This is very fragile because it is duplicated computation from:
1541 * frameworks/av/services/camera/libcameraservice/device3/Camera3Device.cpp
1542 *
1543 */
1544
1545/* This assumes mSupportedFormats have all been declared as supporting
1546 * HAL_PIXEL_FORMAT_BLOB to the framework */
1547Size ExternalCameraDeviceSession::getMaxJpegResolution() const {
1548 Size ret { 0, 0 };
1549 for(auto & fmt : mSupportedFormats) {
1550 if(fmt.width * fmt.height > ret.width * ret.height) {
1551 ret = Size { fmt.width, fmt.height };
1552 }
1553 }
1554 return ret;
1555}
1556
1557Size ExternalCameraDeviceSession::getMaxThumbResolution() const {
1558 Size thumbSize { 0, 0 };
1559 camera_metadata_ro_entry entry =
1560 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
1561 for(uint32_t i = 0; i < entry.count; i += 2) {
1562 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
1563 static_cast<uint32_t>(entry.data.i32[i+1]) };
1564 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
1565 thumbSize = sz;
1566 }
1567 }
1568
1569 if (thumbSize.width * thumbSize.height == 0) {
1570 ALOGW("%s: non-zero thumbnail size not available", __FUNCTION__);
1571 }
1572
1573 return thumbSize;
1574}
1575
1576
1577ssize_t ExternalCameraDeviceSession::getJpegBufferSize(
1578 uint32_t width, uint32_t height) const {
1579 // Constant from camera3.h
1580 const ssize_t kMinJpegBufferSize = 256 * 1024 + sizeof(CameraBlob);
1581 // Get max jpeg size (area-wise).
1582 if (mMaxJpegResolution.width == 0) {
1583 ALOGE("%s: Do not have a single supported JPEG stream",
1584 __FUNCTION__);
1585 return BAD_VALUE;
1586 }
1587
1588 // Get max jpeg buffer size
1589 ssize_t maxJpegBufferSize = 0;
1590 camera_metadata_ro_entry jpegBufMaxSize =
1591 mCameraCharacteristics.find(ANDROID_JPEG_MAX_SIZE);
1592 if (jpegBufMaxSize.count == 0) {
1593 ALOGE("%s: Can't find maximum JPEG size in static metadata!",
1594 __FUNCTION__);
1595 return BAD_VALUE;
1596 }
1597 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
1598
1599 if (maxJpegBufferSize <= kMinJpegBufferSize) {
1600 ALOGE("%s: ANDROID_JPEG_MAX_SIZE (%zd) <= kMinJpegBufferSize (%zd)",
1601 __FUNCTION__, maxJpegBufferSize, kMinJpegBufferSize);
1602 return BAD_VALUE;
1603 }
1604
1605 // Calculate final jpeg buffer size for the given resolution.
1606 float scaleFactor = ((float) (width * height)) /
1607 (mMaxJpegResolution.width * mMaxJpegResolution.height);
1608 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
1609 kMinJpegBufferSize;
1610 if (jpegBufferSize > maxJpegBufferSize) {
1611 jpegBufferSize = maxJpegBufferSize;
1612 }
1613
1614 return jpegBufferSize;
1615}
1616
1617int ExternalCameraDeviceSession::OutputThread::createJpegLocked(
1618 HalStreamBuffer &halBuf,
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001619 const std::shared_ptr<HalRequest>& req)
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001620{
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001621 ATRACE_CALL();
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001622 int ret;
1623 auto lfail = [&](auto... args) {
1624 ALOGE(args...);
1625
1626 return 1;
1627 };
1628 auto parent = mParent.promote();
1629 if (parent == nullptr) {
1630 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1631 return 1;
1632 }
1633
1634 ALOGV("%s: HAL buffer sid: %d bid: %" PRIu64 " w: %u h: %u",
1635 __FUNCTION__, halBuf.streamId, static_cast<uint64_t>(halBuf.bufferId),
1636 halBuf.width, halBuf.height);
1637 ALOGV("%s: HAL buffer fmt: %x usage: %" PRIx64 " ptr: %p",
1638 __FUNCTION__, halBuf.format, static_cast<uint64_t>(halBuf.usage),
1639 halBuf.bufPtr);
1640 ALOGV("%s: YV12 buffer %d x %d",
1641 __FUNCTION__,
1642 mYu12Frame->mWidth, mYu12Frame->mHeight);
1643
1644 int jpegQuality, thumbQuality;
1645 Size thumbSize;
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001646 bool outputThumbnail = true;
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001647
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001648 if (req->setting.exists(ANDROID_JPEG_QUALITY)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001649 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001650 req->setting.find(ANDROID_JPEG_QUALITY);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001651 jpegQuality = entry.data.u8[0];
1652 } else {
1653 return lfail("%s: ANDROID_JPEG_QUALITY not set",__FUNCTION__);
1654 }
1655
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001656 if (req->setting.exists(ANDROID_JPEG_THUMBNAIL_QUALITY)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001657 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001658 req->setting.find(ANDROID_JPEG_THUMBNAIL_QUALITY);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001659 thumbQuality = entry.data.u8[0];
1660 } else {
1661 return lfail(
1662 "%s: ANDROID_JPEG_THUMBNAIL_QUALITY not set",
1663 __FUNCTION__);
1664 }
1665
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001666 if (req->setting.exists(ANDROID_JPEG_THUMBNAIL_SIZE)) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001667 camera_metadata_entry entry =
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001668 req->setting.find(ANDROID_JPEG_THUMBNAIL_SIZE);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001669 thumbSize = Size { static_cast<uint32_t>(entry.data.i32[0]),
1670 static_cast<uint32_t>(entry.data.i32[1])
1671 };
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001672 if (thumbSize.width == 0 && thumbSize.height == 0) {
1673 outputThumbnail = false;
1674 }
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001675 } else {
1676 return lfail(
1677 "%s: ANDROID_JPEG_THUMBNAIL_SIZE not set", __FUNCTION__);
1678 }
1679
1680 /* Cropped and scaled YU12 buffer for main and thumbnail */
1681 YCbCrLayout yu12Main;
1682 Size jpegSize { halBuf.width, halBuf.height };
1683
1684 /* Compute temporary buffer sizes accounting for the following:
1685 * thumbnail can't exceed APP1 size of 64K
1686 * main image needs to hold APP1, headers, and at most a poorly
1687 * compressed image */
1688 const ssize_t maxThumbCodeSize = 64 * 1024;
Yin-Chia Yeh4c641182018-08-06 15:01:20 -07001689 const ssize_t maxJpegCodeSize = mBlobBufferSize == 0 ?
1690 parent->getJpegBufferSize(jpegSize.width, jpegSize.height) :
1691 mBlobBufferSize;
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001692
1693 /* Check that getJpegBufferSize did not return an error */
1694 if (maxJpegCodeSize < 0) {
1695 return lfail(
1696 "%s: getJpegBufferSize returned %zd",__FUNCTION__,maxJpegCodeSize);
1697 }
1698
1699
1700 /* Hold actual thumbnail and main image code sizes */
1701 size_t thumbCodeSize = 0, jpegCodeSize = 0;
1702 /* Temporary thumbnail code buffer */
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001703 std::vector<uint8_t> thumbCode(outputThumbnail ? maxThumbCodeSize : 0);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001704
1705 YCbCrLayout yu12Thumb;
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001706 if (outputThumbnail) {
1707 ret = cropAndScaleThumbLocked(mYu12Frame, thumbSize, &yu12Thumb);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001708
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001709 if (ret != 0) {
1710 return lfail(
1711 "%s: crop and scale thumbnail failed!", __FUNCTION__);
1712 }
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001713 }
1714
1715 /* Scale and crop main jpeg */
1716 ret = cropAndScaleLocked(mYu12Frame, jpegSize, &yu12Main);
1717
1718 if (ret != 0) {
1719 return lfail("%s: crop and scale main failed!", __FUNCTION__);
1720 }
1721
1722 /* Encode the thumbnail image */
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001723 if (outputThumbnail) {
1724 ret = encodeJpegYU12(thumbSize, yu12Thumb,
1725 thumbQuality, 0, 0,
1726 &thumbCode[0], maxThumbCodeSize, thumbCodeSize);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001727
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001728 if (ret != 0) {
1729 return lfail("%s: thumbnail encodeJpegYU12 failed with %d",__FUNCTION__, ret);
1730 }
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001731 }
1732
1733 /* Combine camera characteristics with request settings to form EXIF
1734 * metadata */
1735 common::V1_0::helper::CameraMetadata meta(parent->mCameraCharacteristics);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001736 meta.append(req->setting);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001737
1738 /* Generate EXIF object */
1739 std::unique_ptr<ExifUtils> utils(ExifUtils::create());
1740 /* Make sure it's initialized */
1741 utils->initialize();
1742
1743 utils->setFromMetadata(meta, jpegSize.width, jpegSize.height);
Yin-Chia Yeh2d61bfd2018-03-14 13:50:23 -07001744 utils->setMake(mExifMake);
1745 utils->setModel(mExifModel);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001746
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08001747 ret = utils->generateApp1(outputThumbnail ? &thumbCode[0] : 0, thumbCodeSize);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001748
1749 if (!ret) {
1750 return lfail("%s: generating APP1 failed", __FUNCTION__);
1751 }
1752
1753 /* Get internal buffer */
1754 size_t exifDataSize = utils->getApp1Length();
1755 const uint8_t* exifData = utils->getApp1Buffer();
1756
1757 /* Lock the HAL jpeg code buffer */
1758 void *bufPtr = sHandleImporter.lock(
1759 *(halBuf.bufPtr), halBuf.usage, maxJpegCodeSize);
1760
1761 if (!bufPtr) {
1762 return lfail("%s: could not lock %zu bytes", __FUNCTION__, maxJpegCodeSize);
1763 }
1764
1765 /* Encode the main jpeg image */
1766 ret = encodeJpegYU12(jpegSize, yu12Main,
1767 jpegQuality, exifData, exifDataSize,
1768 bufPtr, maxJpegCodeSize, jpegCodeSize);
1769
1770 /* TODO: Not sure this belongs here, maybe better to pass jpegCodeSize out
1771 * and do this when returning buffer to parent */
1772 CameraBlob blob { CameraBlobId::JPEG, static_cast<uint32_t>(jpegCodeSize) };
1773 void *blobDst =
1774 reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(bufPtr) +
1775 maxJpegCodeSize -
1776 sizeof(CameraBlob));
1777 memcpy(blobDst, &blob, sizeof(CameraBlob));
1778
1779 /* Unlock the HAL jpeg code buffer */
1780 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
Yin-Chia Yeh965d9dd2019-03-14 14:21:01 -07001781 if (relFence >= 0) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001782 halBuf.acquireFence = relFence;
1783 }
1784
1785 /* Check if our JPEG actually succeeded */
1786 if (ret != 0) {
1787 return lfail(
1788 "%s: encodeJpegYU12 failed with %d",__FUNCTION__, ret);
1789 }
1790
1791 ALOGV("%s: encoded JPEG (ret:%d) with Q:%d max size: %zu",
1792 __FUNCTION__, ret, jpegQuality, maxJpegCodeSize);
1793
1794 return 0;
1795}
1796
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001797bool ExternalCameraDeviceSession::OutputThread::threadLoop() {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001798 std::shared_ptr<HalRequest> req;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001799 auto parent = mParent.promote();
1800 if (parent == nullptr) {
1801 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1802 return false;
1803 }
1804
1805 // TODO: maybe we need to setup a sensor thread to dq/enq v4l frames
1806 // regularly to prevent v4l buffer queue filled with stale buffers
1807 // when app doesn't program a preveiw request
1808 waitForNextRequest(&req);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001809 if (req == nullptr) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001810 // No new request, wait again
1811 return true;
1812 }
1813
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001814 auto onDeviceError = [&](auto... args) {
1815 ALOGE(args...);
1816 parent->notifyError(
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001817 req->frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001818 signalRequestDone();
1819 return false;
1820 };
1821
Emil Jahshaneed00402018-12-11 15:15:17 +02001822 if (req->frameIn->mFourcc != V4L2_PIX_FMT_MJPEG && req->frameIn->mFourcc != V4L2_PIX_FMT_Z16) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001823 return onDeviceError("%s: do not support V4L2 format %c%c%c%c", __FUNCTION__,
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001824 req->frameIn->mFourcc & 0xFF,
1825 (req->frameIn->mFourcc >> 8) & 0xFF,
1826 (req->frameIn->mFourcc >> 16) & 0xFF,
1827 (req->frameIn->mFourcc >> 24) & 0xFF);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001828 }
1829
Yin-Chia Yehee238402018-11-04 16:30:11 -08001830 int res = requestBufferStart(req->buffers);
1831 if (res != 0) {
1832 ALOGE("%s: send BufferRequest failed! res %d", __FUNCTION__, res);
1833 return onDeviceError("%s: failed to send buffer request!", __FUNCTION__);
1834 }
1835
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001836 std::unique_lock<std::mutex> lk(mBufferLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001837 // Convert input V4L2 frame to YU12 of the same size
1838 // TODO: see if we can save some computation by converting to YV12 here
1839 uint8_t* inData;
1840 size_t inDataSize;
chenhg06ced052018-10-10 17:07:21 -07001841 if (req->frameIn->map(&inData, &inDataSize) != 0) {
1842 lk.unlock();
1843 return onDeviceError("%s: V4L2 buffer map failed", __FUNCTION__);
1844 }
1845
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001846 // TODO: in some special case maybe we can decode jpg directly to gralloc output?
Emil Jahshaneed00402018-12-11 15:15:17 +02001847 if (req->frameIn->mFourcc == V4L2_PIX_FMT_MJPEG) {
1848 ATRACE_BEGIN("MJPGtoI420");
1849 int res = libyuv::MJPGToI420(
1850 inData, inDataSize, static_cast<uint8_t*>(mYu12FrameLayout.y), mYu12FrameLayout.yStride,
1851 static_cast<uint8_t*>(mYu12FrameLayout.cb), mYu12FrameLayout.cStride,
1852 static_cast<uint8_t*>(mYu12FrameLayout.cr), mYu12FrameLayout.cStride,
1853 mYu12Frame->mWidth, mYu12Frame->mHeight, mYu12Frame->mWidth, mYu12Frame->mHeight);
1854 ATRACE_END();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001855
Emil Jahshaneed00402018-12-11 15:15:17 +02001856 if (res != 0) {
1857 // For some webcam, the first few V4L2 frames might be malformed...
1858 ALOGE("%s: Convert V4L2 frame to YU12 failed! res %d", __FUNCTION__, res);
1859 lk.unlock();
1860 Status st = parent->processCaptureRequestError(req);
1861 if (st != Status::OK) {
1862 return onDeviceError("%s: failed to process capture request error!", __FUNCTION__);
1863 }
1864 signalRequestDone();
1865 return true;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001866 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001867 }
1868
Yin-Chia Yehee238402018-11-04 16:30:11 -08001869 ATRACE_BEGIN("Wait for BufferRequest done");
1870 res = waitForBufferRequestDone(&req->buffers);
1871 ATRACE_END();
1872
1873 if (res != 0) {
1874 ALOGE("%s: wait for BufferRequest done failed! res %d", __FUNCTION__, res);
1875 lk.unlock();
1876 return onDeviceError("%s: failed to process buffer request error!", __FUNCTION__);
1877 }
1878
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001879 ALOGV("%s processing new request", __FUNCTION__);
1880 const int kSyncWaitTimeoutMs = 500;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08001881 for (auto& halBuf : req->buffers) {
Yin-Chia Yehee238402018-11-04 16:30:11 -08001882 if (*(halBuf.bufPtr) == nullptr) {
1883 ALOGW("%s: buffer for stream %d missing", __FUNCTION__, halBuf.streamId);
1884 halBuf.fenceTimeout = true;
Yin-Chia Yeh965d9dd2019-03-14 14:21:01 -07001885 } else if (halBuf.acquireFence >= 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001886 int ret = sync_wait(halBuf.acquireFence, kSyncWaitTimeoutMs);
1887 if (ret) {
1888 halBuf.fenceTimeout = true;
1889 } else {
1890 ::close(halBuf.acquireFence);
Yin-Chia Yeh1e089662018-02-02 15:57:58 -08001891 halBuf.acquireFence = -1;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001892 }
1893 }
1894
1895 if (halBuf.fenceTimeout) {
1896 continue;
1897 }
1898
1899 // Gralloc lockYCbCr the buffer
1900 switch (halBuf.format) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001901 case PixelFormat::BLOB: {
1902 int ret = createJpegLocked(halBuf, req);
1903
1904 if(ret != 0) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001905 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001906 return onDeviceError("%s: createJpegLocked failed with %d",
1907 __FUNCTION__, ret);
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001908 }
1909 } break;
Emil Jahshaneed00402018-12-11 15:15:17 +02001910 case PixelFormat::Y16: {
1911 void* outLayout = sHandleImporter.lock(*(halBuf.bufPtr), halBuf.usage, inDataSize);
1912
1913 std::memcpy(outLayout, inData, inDataSize);
1914
1915 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
1916 if (relFence >= 0) {
1917 halBuf.acquireFence = relFence;
1918 }
1919 } break;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001920 case PixelFormat::YCBCR_420_888:
1921 case PixelFormat::YV12: {
1922 IMapper::Rect outRect {0, 0,
1923 static_cast<int32_t>(halBuf.width),
1924 static_cast<int32_t>(halBuf.height)};
1925 YCbCrLayout outLayout = sHandleImporter.lockYCbCr(
1926 *(halBuf.bufPtr), halBuf.usage, outRect);
1927 ALOGV("%s: outLayout y %p cb %p cr %p y_str %d c_str %d c_step %d",
1928 __FUNCTION__, outLayout.y, outLayout.cb, outLayout.cr,
1929 outLayout.yStride, outLayout.cStride, outLayout.chromaStep);
1930
1931 // Convert to output buffer size/format
1932 uint32_t outputFourcc = getFourCcFromLayout(outLayout);
1933 ALOGV("%s: converting to format %c%c%c%c", __FUNCTION__,
1934 outputFourcc & 0xFF,
1935 (outputFourcc >> 8) & 0xFF,
1936 (outputFourcc >> 16) & 0xFF,
1937 (outputFourcc >> 24) & 0xFF);
1938
1939 YCbCrLayout cropAndScaled;
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001940 ATRACE_BEGIN("cropAndScaleLocked");
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001941 int ret = cropAndScaleLocked(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001942 mYu12Frame,
1943 Size { halBuf.width, halBuf.height },
1944 &cropAndScaled);
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001945 ATRACE_END();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001946 if (ret != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001947 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001948 return onDeviceError("%s: crop and scale failed!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001949 }
1950
1951 Size sz {halBuf.width, halBuf.height};
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001952 ATRACE_BEGIN("formatConvertLocked");
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001953 ret = formatConvertLocked(cropAndScaled, outLayout, sz, outputFourcc);
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08001954 ATRACE_END();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001955 if (ret != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001956 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001957 return onDeviceError("%s: format coversion failed!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001958 }
1959 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
Yin-Chia Yeh965d9dd2019-03-14 14:21:01 -07001960 if (relFence >= 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001961 halBuf.acquireFence = relFence;
1962 }
1963 } break;
1964 default:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001965 lk.unlock();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001966 return onDeviceError("%s: unknown output format %x", __FUNCTION__, halBuf.format);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001967 }
1968 } // for each buffer
1969 mScaledYu12Frames.clear();
1970
1971 // Don't hold the lock while calling back to parent
1972 lk.unlock();
1973 Status st = parent->processCaptureResult(req);
1974 if (st != Status::OK) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001975 return onDeviceError("%s: failed to process capture result!", __FUNCTION__);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001976 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001977 signalRequestDone();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001978 return true;
1979}
1980
1981Status ExternalCameraDeviceSession::OutputThread::allocateIntermediateBuffers(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001982 const Size& v4lSize, const Size& thumbSize,
Yin-Chia Yeh4c641182018-08-06 15:01:20 -07001983 const hidl_vec<Stream>& streams,
1984 uint32_t blobBufferSize) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08001985 std::lock_guard<std::mutex> lk(mBufferLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001986 if (mScaledYu12Frames.size() != 0) {
1987 ALOGE("%s: intermediate buffer pool has %zu inflight buffers! (expect 0)",
1988 __FUNCTION__, mScaledYu12Frames.size());
1989 return Status::INTERNAL_ERROR;
1990 }
1991
1992 // Allocating intermediate YU12 frame
1993 if (mYu12Frame == nullptr || mYu12Frame->mWidth != v4lSize.width ||
1994 mYu12Frame->mHeight != v4lSize.height) {
1995 mYu12Frame.clear();
1996 mYu12Frame = new AllocatedFrame(v4lSize.width, v4lSize.height);
1997 int ret = mYu12Frame->allocate(&mYu12FrameLayout);
1998 if (ret != 0) {
1999 ALOGE("%s: allocating YU12 frame failed!", __FUNCTION__);
2000 return Status::INTERNAL_ERROR;
2001 }
2002 }
2003
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08002004 // Allocating intermediate YU12 thumbnail frame
2005 if (mYu12ThumbFrame == nullptr ||
2006 mYu12ThumbFrame->mWidth != thumbSize.width ||
2007 mYu12ThumbFrame->mHeight != thumbSize.height) {
2008 mYu12ThumbFrame.clear();
2009 mYu12ThumbFrame = new AllocatedFrame(thumbSize.width, thumbSize.height);
2010 int ret = mYu12ThumbFrame->allocate(&mYu12ThumbFrameLayout);
2011 if (ret != 0) {
2012 ALOGE("%s: allocating YU12 thumb frame failed!", __FUNCTION__);
2013 return Status::INTERNAL_ERROR;
2014 }
2015 }
2016
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002017 // Allocating scaled buffers
2018 for (const auto& stream : streams) {
2019 Size sz = {stream.width, stream.height};
2020 if (sz == v4lSize) {
2021 continue; // Don't need an intermediate buffer same size as v4lBuffer
2022 }
2023 if (mIntermediateBuffers.count(sz) == 0) {
2024 // Create new intermediate buffer
2025 sp<AllocatedFrame> buf = new AllocatedFrame(stream.width, stream.height);
2026 int ret = buf->allocate();
2027 if (ret != 0) {
2028 ALOGE("%s: allocating intermediate YU12 frame %dx%d failed!",
2029 __FUNCTION__, stream.width, stream.height);
2030 return Status::INTERNAL_ERROR;
2031 }
2032 mIntermediateBuffers[sz] = buf;
2033 }
2034 }
2035
2036 // Remove unconfigured buffers
2037 auto it = mIntermediateBuffers.begin();
2038 while (it != mIntermediateBuffers.end()) {
2039 bool configured = false;
2040 auto sz = it->first;
2041 for (const auto& stream : streams) {
2042 if (stream.width == sz.width && stream.height == sz.height) {
2043 configured = true;
2044 break;
2045 }
2046 }
2047 if (configured) {
2048 it++;
2049 } else {
2050 it = mIntermediateBuffers.erase(it);
2051 }
2052 }
Yin-Chia Yeh4c641182018-08-06 15:01:20 -07002053
2054 mBlobBufferSize = blobBufferSize;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002055 return Status::OK;
2056}
2057
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08002058Status ExternalCameraDeviceSession::OutputThread::submitRequest(
2059 const std::shared_ptr<HalRequest>& req) {
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002060 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002061 mRequestList.push_back(req);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002062 lk.unlock();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002063 mRequestCond.notify_one();
2064 return Status::OK;
2065}
2066
2067void ExternalCameraDeviceSession::OutputThread::flush() {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002068 ATRACE_CALL();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002069 auto parent = mParent.promote();
2070 if (parent == nullptr) {
2071 ALOGE("%s: session has been disconnected!", __FUNCTION__);
2072 return;
2073 }
2074
2075 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08002076 std::list<std::shared_ptr<HalRequest>> reqs = std::move(mRequestList);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002077 mRequestList.clear();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002078 if (mProcessingRequest) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002079 std::chrono::seconds timeout = std::chrono::seconds(kFlushWaitTimeoutSec);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002080 auto st = mRequestDoneCond.wait_for(lk, timeout);
2081 if (st == std::cv_status::timeout) {
2082 ALOGE("%s: wait for inflight request finish timeout!", __FUNCTION__);
2083 }
2084 }
2085
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002086 ALOGV("%s: flusing inflight requests", __FUNCTION__);
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002087 lk.unlock();
2088 for (const auto& req : reqs) {
2089 parent->processCaptureRequestError(req);
2090 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002091}
2092
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08002093void ExternalCameraDeviceSession::OutputThread::waitForNextRequest(
2094 std::shared_ptr<HalRequest>* out) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002095 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002096 if (out == nullptr) {
2097 ALOGE("%s: out is null", __FUNCTION__);
2098 return;
2099 }
2100
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002101 std::unique_lock<std::mutex> lk(mRequestListLock);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002102 int waitTimes = 0;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002103 while (mRequestList.empty()) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002104 if (exitPending()) {
2105 return;
2106 }
2107 std::chrono::milliseconds timeout = std::chrono::milliseconds(kReqWaitTimeoutMs);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002108 auto st = mRequestCond.wait_for(lk, timeout);
2109 if (st == std::cv_status::timeout) {
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002110 waitTimes++;
2111 if (waitTimes == kReqWaitTimesMax) {
2112 // no new request, return
2113 return;
2114 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002115 }
2116 }
2117 *out = mRequestList.front();
2118 mRequestList.pop_front();
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002119 mProcessingRequest = true;
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08002120 mProcessingFrameNumer = (*out)->frameNumber;
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002121}
2122
2123void ExternalCameraDeviceSession::OutputThread::signalRequestDone() {
2124 std::unique_lock<std::mutex> lk(mRequestListLock);
2125 mProcessingRequest = false;
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002126 mProcessingFrameNumer = 0;
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002127 lk.unlock();
2128 mRequestDoneCond.notify_one();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002129}
2130
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002131void ExternalCameraDeviceSession::OutputThread::dump(int fd) {
2132 std::lock_guard<std::mutex> lk(mRequestListLock);
2133 if (mProcessingRequest) {
2134 dprintf(fd, "OutputThread processing frame %d\n", mProcessingFrameNumer);
2135 } else {
2136 dprintf(fd, "OutputThread not processing any frames\n");
2137 }
2138 dprintf(fd, "OutputThread request list contains frame: ");
2139 for (const auto& req : mRequestList) {
Yin-Chia Yehe086fb72018-02-16 14:54:04 -08002140 dprintf(fd, "%d, ", req->frameNumber);
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002141 }
2142 dprintf(fd, "\n");
2143}
2144
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002145void ExternalCameraDeviceSession::cleanupBuffersLocked(int id) {
2146 for (auto& pair : mCirculatingBuffers.at(id)) {
2147 sHandleImporter.freeBuffer(pair.second);
2148 }
2149 mCirculatingBuffers[id].clear();
2150 mCirculatingBuffers.erase(id);
2151}
2152
2153void ExternalCameraDeviceSession::updateBufferCaches(const hidl_vec<BufferCache>& cachesToRemove) {
Yin-Chia Yehee238402018-11-04 16:30:11 -08002154 Mutex::Autolock _l(mCbsLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002155 for (auto& cache : cachesToRemove) {
2156 auto cbsIt = mCirculatingBuffers.find(cache.streamId);
2157 if (cbsIt == mCirculatingBuffers.end()) {
2158 // The stream could have been removed
2159 continue;
2160 }
2161 CirculatingBuffers& cbs = cbsIt->second;
2162 auto it = cbs.find(cache.bufferId);
2163 if (it != cbs.end()) {
2164 sHandleImporter.freeBuffer(it->second);
2165 cbs.erase(it);
2166 } else {
2167 ALOGE("%s: stream %d buffer %" PRIu64 " is not cached",
2168 __FUNCTION__, cache.streamId, cache.bufferId);
2169 }
2170 }
2171}
2172
Emilian Peev40a8c6e2018-10-29 09:35:21 +00002173bool ExternalCameraDeviceSession::isSupported(const Stream& stream,
Emil Jahshaneed00402018-12-11 15:15:17 +02002174 const std::vector<SupportedV4L2Format>& supportedFormats,
2175 const ExternalCameraConfig& devCfg) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002176 int32_t ds = static_cast<int32_t>(stream.dataSpace);
2177 PixelFormat fmt = stream.format;
2178 uint32_t width = stream.width;
2179 uint32_t height = stream.height;
2180 // TODO: check usage flags
2181
2182 if (stream.streamType != StreamType::OUTPUT) {
2183 ALOGE("%s: does not support non-output stream type", __FUNCTION__);
2184 return false;
2185 }
2186
2187 if (stream.rotation != StreamRotation::ROTATION_0) {
2188 ALOGE("%s: does not support stream rotation", __FUNCTION__);
2189 return false;
2190 }
2191
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002192 switch (fmt) {
2193 case PixelFormat::BLOB:
2194 if (ds != static_cast<int32_t>(Dataspace::V0_JFIF)) {
2195 ALOGI("%s: BLOB format does not support dataSpace %x", __FUNCTION__, ds);
2196 return false;
2197 }
Chih-Hung Hsieh5daaea72018-10-16 14:22:12 -07002198 break;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002199 case PixelFormat::IMPLEMENTATION_DEFINED:
2200 case PixelFormat::YCBCR_420_888:
2201 case PixelFormat::YV12:
2202 // TODO: check what dataspace we can support here.
2203 // intentional no-ops.
2204 break;
Emil Jahshaneed00402018-12-11 15:15:17 +02002205 case PixelFormat::Y16:
2206 if (!devCfg.depthEnabled) {
2207 ALOGI("%s: Depth is not Enabled", __FUNCTION__);
2208 return false;
2209 }
2210 if (!(ds & Dataspace::DEPTH)) {
2211 ALOGI("%s: Y16 supports only dataSpace DEPTH", __FUNCTION__);
2212 return false;
2213 }
2214 break;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002215 default:
2216 ALOGI("%s: does not support format %x", __FUNCTION__, fmt);
2217 return false;
2218 }
2219
2220 // Assume we can convert any V4L2 format to any of supported output format for now, i.e,
2221 // ignoring v4l2Fmt.fourcc for now. Might need more subtle check if we support more v4l format
2222 // in the futrue.
Emilian Peev40a8c6e2018-10-29 09:35:21 +00002223 for (const auto& v4l2Fmt : supportedFormats) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002224 if (width == v4l2Fmt.width && height == v4l2Fmt.height) {
2225 return true;
2226 }
2227 }
2228 ALOGI("%s: resolution %dx%d is not supported", __FUNCTION__, width, height);
2229 return false;
2230}
2231
2232int ExternalCameraDeviceSession::v4l2StreamOffLocked() {
2233 if (!mV4l2Streaming) {
2234 return OK;
2235 }
2236
2237 {
2238 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2239 if (mNumDequeuedV4l2Buffers != 0) {
2240 ALOGE("%s: there are %zu inflight V4L buffers",
2241 __FUNCTION__, mNumDequeuedV4l2Buffers);
2242 return -1;
2243 }
2244 }
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002245 mV4L2BufferCount = 0;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002246
2247 // VIDIOC_STREAMOFF
2248 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2249 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMOFF, &capture_type)) < 0) {
2250 ALOGE("%s: STREAMOFF failed: %s", __FUNCTION__, strerror(errno));
2251 return -errno;
2252 }
2253
2254 // VIDIOC_REQBUFS: clear buffers
2255 v4l2_requestbuffers req_buffers{};
2256 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2257 req_buffers.memory = V4L2_MEMORY_MMAP;
2258 req_buffers.count = 0;
2259 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
2260 ALOGE("%s: REQBUFS failed: %s", __FUNCTION__, strerror(errno));
2261 return -errno;
2262 }
2263
2264 mV4l2Streaming = false;
2265 return OK;
2266}
2267
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002268int ExternalCameraDeviceSession::setV4l2FpsLocked(double fps) {
2269 // VIDIOC_G_PARM/VIDIOC_S_PARM: set fps
2270 v4l2_streamparm streamparm = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
2271 // The following line checks that the driver knows about framerate get/set.
2272 int ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_G_PARM, &streamparm));
2273 if (ret != 0) {
2274 if (errno == -EINVAL) {
2275 ALOGW("%s: device does not support VIDIOC_G_PARM", __FUNCTION__);
2276 }
2277 return -errno;
2278 }
2279 // Now check if the device is able to accept a capture framerate set.
2280 if (!(streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME)) {
2281 ALOGW("%s: device does not support V4L2_CAP_TIMEPERFRAME", __FUNCTION__);
2282 return -EINVAL;
2283 }
2284
2285 // fps is float, approximate by a fraction.
2286 const int kFrameRatePrecision = 10000;
2287 streamparm.parm.capture.timeperframe.numerator = kFrameRatePrecision;
2288 streamparm.parm.capture.timeperframe.denominator =
2289 (fps * kFrameRatePrecision);
2290
2291 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_PARM, &streamparm)) < 0) {
2292 ALOGE("%s: failed to set framerate to %f: %s", __FUNCTION__, fps, strerror(errno));
2293 return -1;
2294 }
2295
2296 double retFps = streamparm.parm.capture.timeperframe.denominator /
2297 static_cast<double>(streamparm.parm.capture.timeperframe.numerator);
2298 if (std::fabs(fps - retFps) > 1.0) {
2299 ALOGE("%s: expect fps %f, got %f instead", __FUNCTION__, fps, retFps);
2300 return -1;
2301 }
2302 mV4l2StreamingFps = fps;
2303 return 0;
2304}
2305
2306int ExternalCameraDeviceSession::configureV4l2StreamLocked(
2307 const SupportedV4L2Format& v4l2Fmt, double requestFps) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002308 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002309 int ret = v4l2StreamOffLocked();
2310 if (ret != OK) {
2311 ALOGE("%s: stop v4l2 streaming failed: ret %d", __FUNCTION__, ret);
2312 return ret;
2313 }
2314
2315 // VIDIOC_S_FMT w/h/fmt
2316 v4l2_format fmt;
2317 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2318 fmt.fmt.pix.width = v4l2Fmt.width;
2319 fmt.fmt.pix.height = v4l2Fmt.height;
2320 fmt.fmt.pix.pixelformat = v4l2Fmt.fourcc;
2321 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt));
2322 if (ret < 0) {
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08002323 int numAttempt = 0;
2324 while (ret < 0) {
2325 ALOGW("%s: VIDIOC_S_FMT failed, wait 33ms and try again", __FUNCTION__);
Yin-Chia Yeh2d61bfd2018-03-14 13:50:23 -07002326 usleep(IOCTL_RETRY_SLEEP_US); // sleep and try again
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08002327 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt));
2328 if (numAttempt == MAX_RETRY) {
2329 break;
2330 }
2331 numAttempt++;
2332 }
2333 if (ret < 0) {
2334 ALOGE("%s: S_FMT ioctl failed: %s", __FUNCTION__, strerror(errno));
2335 return -errno;
2336 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002337 }
2338
2339 if (v4l2Fmt.width != fmt.fmt.pix.width || v4l2Fmt.height != fmt.fmt.pix.height ||
2340 v4l2Fmt.fourcc != fmt.fmt.pix.pixelformat) {
2341 ALOGE("%s: S_FMT expect %c%c%c%c %dx%d, got %c%c%c%c %dx%d instead!", __FUNCTION__,
2342 v4l2Fmt.fourcc & 0xFF,
2343 (v4l2Fmt.fourcc >> 8) & 0xFF,
2344 (v4l2Fmt.fourcc >> 16) & 0xFF,
2345 (v4l2Fmt.fourcc >> 24) & 0xFF,
2346 v4l2Fmt.width, v4l2Fmt.height,
2347 fmt.fmt.pix.pixelformat & 0xFF,
2348 (fmt.fmt.pix.pixelformat >> 8) & 0xFF,
2349 (fmt.fmt.pix.pixelformat >> 16) & 0xFF,
2350 (fmt.fmt.pix.pixelformat >> 24) & 0xFF,
2351 fmt.fmt.pix.width, fmt.fmt.pix.height);
2352 return -EINVAL;
2353 }
2354 uint32_t bufferSize = fmt.fmt.pix.sizeimage;
2355 ALOGI("%s: V4L2 buffer size is %d", __FUNCTION__, bufferSize);
Emilian Peevbc0e1652018-04-03 13:28:46 +01002356 uint32_t expectedMaxBufferSize = kMaxBytesPerPixel * fmt.fmt.pix.width * fmt.fmt.pix.height;
2357 if ((bufferSize == 0) || (bufferSize > expectedMaxBufferSize)) {
2358 ALOGE("%s: V4L2 buffer size: %u looks invalid. Expected maximum size: %u", __FUNCTION__,
2359 bufferSize, expectedMaxBufferSize);
2360 return -EINVAL;
2361 }
2362 mMaxV4L2BufferSize = bufferSize;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002363
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002364 const double kDefaultFps = 30.0;
2365 double fps = 1000.0;
2366 if (requestFps != 0.0) {
2367 fps = requestFps;
2368 } else {
2369 double maxFps = -1.0;
2370 // Try to pick the slowest fps that is at least 30
2371 for (const auto& fr : v4l2Fmt.frameRates) {
2372 double f = fr.getDouble();
2373 if (maxFps < f) {
2374 maxFps = f;
2375 }
2376 if (f >= kDefaultFps && f < fps) {
2377 fps = f;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002378 }
2379 }
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002380 if (fps == 1000.0) {
2381 fps = maxFps;
2382 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002383 }
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002384
2385 int fpsRet = setV4l2FpsLocked(fps);
2386 if (fpsRet != 0 && fpsRet != -EINVAL) {
2387 ALOGE("%s: set fps failed: %s", __FUNCTION__, strerror(fpsRet));
2388 return fpsRet;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002389 }
2390
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -08002391 uint32_t v4lBufferCount = (fps >= kDefaultFps) ?
2392 mCfg.numVideoBuffers : mCfg.numStillBuffers;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002393 // VIDIOC_REQBUFS: create buffers
2394 v4l2_requestbuffers req_buffers{};
2395 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2396 req_buffers.memory = V4L2_MEMORY_MMAP;
2397 req_buffers.count = v4lBufferCount;
2398 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
2399 ALOGE("%s: VIDIOC_REQBUFS failed: %s", __FUNCTION__, strerror(errno));
2400 return -errno;
2401 }
2402
2403 // Driver can indeed return more buffer if it needs more to operate
2404 if (req_buffers.count < v4lBufferCount) {
2405 ALOGE("%s: VIDIOC_REQBUFS expected %d buffers, got %d instead",
2406 __FUNCTION__, v4lBufferCount, req_buffers.count);
2407 return NO_MEMORY;
2408 }
2409
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002410 // VIDIOC_QUERYBUF: get buffer offset in the V4L2 fd
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002411 // VIDIOC_QBUF: send buffer to driver
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002412 mV4L2BufferCount = req_buffers.count;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002413 for (uint32_t i = 0; i < req_buffers.count; i++) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002414 v4l2_buffer buffer = {
2415 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
2416 .index = i,
2417 .memory = V4L2_MEMORY_MMAP};
2418
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002419 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QUERYBUF, &buffer)) < 0) {
2420 ALOGE("%s: QUERYBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
2421 return -errno;
2422 }
2423
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002424 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2425 ALOGE("%s: QBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
2426 return -errno;
2427 }
2428 }
2429
2430 // VIDIOC_STREAMON: start streaming
2431 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08002432 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type));
2433 if (ret < 0) {
2434 int numAttempt = 0;
2435 while (ret < 0) {
2436 ALOGW("%s: VIDIOC_STREAMON failed, wait 33ms and try again", __FUNCTION__);
2437 usleep(IOCTL_RETRY_SLEEP_US); // sleep 100 ms and try again
2438 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type));
2439 if (numAttempt == MAX_RETRY) {
2440 break;
2441 }
2442 numAttempt++;
2443 }
2444 if (ret < 0) {
2445 ALOGE("%s: VIDIOC_STREAMON ioctl failed: %s", __FUNCTION__, strerror(errno));
2446 return -errno;
2447 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002448 }
2449
2450 // Swallow first few frames after streamOn to account for bad frames from some devices
2451 for (int i = 0; i < kBadFramesAfterStreamOn; i++) {
2452 v4l2_buffer buffer{};
2453 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2454 buffer.memory = V4L2_MEMORY_MMAP;
2455 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
2456 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
2457 return -errno;
2458 }
2459
2460 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2461 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, buffer.index, strerror(errno));
2462 return -errno;
2463 }
2464 }
2465
Yin-Chia Yeh8b699aa2018-02-28 15:58:54 -08002466 ALOGI("%s: start V4L2 streaming %dx%d@%ffps",
2467 __FUNCTION__, v4l2Fmt.width, v4l2Fmt.height, fps);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002468 mV4l2StreamingFmt = v4l2Fmt;
2469 mV4l2Streaming = true;
2470 return OK;
2471}
2472
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002473sp<V4L2Frame> ExternalCameraDeviceSession::dequeueV4l2FrameLocked(/*out*/nsecs_t* shutterTs) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002474 ATRACE_CALL();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002475 sp<V4L2Frame> ret = nullptr;
2476
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002477 if (shutterTs == nullptr) {
2478 ALOGE("%s: shutterTs must not be null!", __FUNCTION__);
2479 return ret;
2480 }
2481
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002482 {
2483 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002484 if (mNumDequeuedV4l2Buffers == mV4L2BufferCount) {
Yin-Chia Yeh3aa9ae92018-02-23 17:21:51 -08002485 int waitRet = waitForV4L2BufferReturnLocked(lk);
2486 if (waitRet != 0) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002487 return ret;
2488 }
2489 }
2490 }
2491
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -08002492 ATRACE_BEGIN("VIDIOC_DQBUF");
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002493 v4l2_buffer buffer{};
2494 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2495 buffer.memory = V4L2_MEMORY_MMAP;
2496 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
2497 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
2498 return ret;
2499 }
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -08002500 ATRACE_END();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002501
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002502 if (buffer.index >= mV4L2BufferCount) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002503 ALOGE("%s: Invalid buffer id: %d", __FUNCTION__, buffer.index);
2504 return ret;
2505 }
2506
2507 if (buffer.flags & V4L2_BUF_FLAG_ERROR) {
2508 ALOGE("%s: v4l2 buf error! buf flag 0x%x", __FUNCTION__, buffer.flags);
2509 // TODO: try to dequeue again
2510 }
2511
Emilian Peevbc0e1652018-04-03 13:28:46 +01002512 if (buffer.bytesused > mMaxV4L2BufferSize) {
2513 ALOGE("%s: v4l2 buffer bytes used: %u maximum %u", __FUNCTION__, buffer.bytesused,
2514 mMaxV4L2BufferSize);
2515 return ret;
2516 }
2517
Yin-Chia Yeh4a3393c2018-02-14 12:47:16 -08002518 if (buffer.flags & V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC) {
2519 // Ideally we should also check for V4L2_BUF_FLAG_TSTAMP_SRC_SOE, but
2520 // even V4L2_BUF_FLAG_TSTAMP_SRC_EOF is better than capture a timestamp now
2521 *shutterTs = static_cast<nsecs_t>(buffer.timestamp.tv_sec)*1000000000LL +
2522 buffer.timestamp.tv_usec * 1000LL;
2523 } else {
2524 *shutterTs = systemTime(SYSTEM_TIME_MONOTONIC);
2525 }
2526
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002527 {
2528 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2529 mNumDequeuedV4l2Buffers++;
2530 }
2531 return new V4L2Frame(
2532 mV4l2StreamingFmt.width, mV4l2StreamingFmt.height, mV4l2StreamingFmt.fourcc,
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002533 buffer.index, mV4l2Fd.get(), buffer.bytesused, buffer.m.offset);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002534}
2535
2536void ExternalCameraDeviceSession::enqueueV4l2Frame(const sp<V4L2Frame>& frame) {
Yin-Chia Yehe99cf202018-02-28 11:30:38 -08002537 ATRACE_CALL();
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -08002538 frame->unmap();
2539 ATRACE_BEGIN("VIDIOC_QBUF");
2540 v4l2_buffer buffer{};
2541 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2542 buffer.memory = V4L2_MEMORY_MMAP;
2543 buffer.index = frame->mBufferIndex;
2544 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2545 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__,
2546 frame->mBufferIndex, strerror(errno));
2547 return;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002548 }
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -08002549 ATRACE_END();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002550
2551 {
2552 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2553 mNumDequeuedV4l2Buffers--;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002554 }
Yin-Chia Yeh190e5602018-02-13 17:43:13 -08002555 mV4L2BufferReturned.notify_one();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002556}
2557
Emilian Peev40a8c6e2018-10-29 09:35:21 +00002558Status ExternalCameraDeviceSession::isStreamCombinationSupported(
Yin-Chia Yeh4c641182018-08-06 15:01:20 -07002559 const V3_2::StreamConfiguration& config,
Emil Jahshaneed00402018-12-11 15:15:17 +02002560 const std::vector<SupportedV4L2Format>& supportedFormats,
2561 const ExternalCameraConfig& devCfg) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002562 if (config.operationMode != StreamConfigurationMode::NORMAL_MODE) {
2563 ALOGE("%s: unsupported operation mode: %d", __FUNCTION__, config.operationMode);
2564 return Status::ILLEGAL_ARGUMENT;
2565 }
2566
2567 if (config.streams.size() == 0) {
2568 ALOGE("%s: cannot configure zero stream", __FUNCTION__);
2569 return Status::ILLEGAL_ARGUMENT;
2570 }
2571
2572 int numProcessedStream = 0;
2573 int numStallStream = 0;
2574 for (const auto& stream : config.streams) {
2575 // Check if the format/width/height combo is supported
Emil Jahshaneed00402018-12-11 15:15:17 +02002576 if (!isSupported(stream, supportedFormats, devCfg)) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002577 return Status::ILLEGAL_ARGUMENT;
2578 }
2579 if (stream.format == PixelFormat::BLOB) {
2580 numStallStream++;
2581 } else {
2582 numProcessedStream++;
2583 }
2584 }
2585
2586 if (numProcessedStream > kMaxProcessedStream) {
2587 ALOGE("%s: too many processed streams (expect <= %d, got %d)", __FUNCTION__,
2588 kMaxProcessedStream, numProcessedStream);
2589 return Status::ILLEGAL_ARGUMENT;
2590 }
2591
2592 if (numStallStream > kMaxStallStream) {
2593 ALOGE("%s: too many stall streams (expect <= %d, got %d)", __FUNCTION__,
2594 kMaxStallStream, numStallStream);
2595 return Status::ILLEGAL_ARGUMENT;
2596 }
2597
Emilian Peev40a8c6e2018-10-29 09:35:21 +00002598 return Status::OK;
2599}
2600
2601Status ExternalCameraDeviceSession::configureStreams(
2602 const V3_2::StreamConfiguration& config,
2603 V3_3::HalStreamConfiguration* out,
2604 uint32_t blobBufferSize) {
2605 ATRACE_CALL();
2606
Emil Jahshaneed00402018-12-11 15:15:17 +02002607 Status status = isStreamCombinationSupported(config, mSupportedFormats, mCfg);
Emilian Peev40a8c6e2018-10-29 09:35:21 +00002608 if (status != Status::OK) {
2609 return status;
2610 }
2611
2612 status = initStatus();
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002613 if (status != Status::OK) {
2614 return status;
2615 }
2616
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -08002617
2618 {
2619 std::lock_guard<std::mutex> lk(mInflightFramesLock);
2620 if (!mInflightFrames.empty()) {
2621 ALOGE("%s: trying to configureStreams while there are still %zu inflight frames!",
2622 __FUNCTION__, mInflightFrames.size());
2623 return Status::INTERNAL_ERROR;
2624 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002625 }
2626
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -08002627 Mutex::Autolock _l(mLock);
Yin-Chia Yehee238402018-11-04 16:30:11 -08002628 {
2629 Mutex::Autolock _l(mCbsLock);
2630 // Add new streams
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002631 for (const auto& stream : config.streams) {
Yin-Chia Yehee238402018-11-04 16:30:11 -08002632 if (mStreamMap.count(stream.id) == 0) {
2633 mStreamMap[stream.id] = stream;
2634 mCirculatingBuffers.emplace(stream.id, CirculatingBuffers{});
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002635 }
2636 }
Yin-Chia Yehee238402018-11-04 16:30:11 -08002637
2638 // Cleanup removed streams
2639 for(auto it = mStreamMap.begin(); it != mStreamMap.end();) {
2640 int id = it->first;
2641 bool found = false;
2642 for (const auto& stream : config.streams) {
2643 if (id == stream.id) {
2644 found = true;
2645 break;
2646 }
2647 }
2648 if (!found) {
2649 // Unmap all buffers of deleted stream
2650 cleanupBuffersLocked(id);
2651 it = mStreamMap.erase(it);
2652 } else {
2653 ++it;
2654 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002655 }
2656 }
2657
2658 // Now select a V4L2 format to produce all output streams
2659 float desiredAr = (mCroppingType == VERTICAL) ? kMaxAspectRatio : kMinAspectRatio;
2660 uint32_t maxDim = 0;
2661 for (const auto& stream : config.streams) {
2662 float aspectRatio = ASPECT_RATIO(stream);
Yin-Chia Yehc15a1ca2018-03-02 14:16:52 -08002663 ALOGI("%s: request stream %dx%d", __FUNCTION__, stream.width, stream.height);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002664 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2665 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2666 desiredAr = aspectRatio;
2667 }
2668
2669 // The dimension that's not cropped
2670 uint32_t dim = (mCroppingType == VERTICAL) ? stream.width : stream.height;
2671 if (dim > maxDim) {
2672 maxDim = dim;
2673 }
2674 }
2675 // Find the smallest format that matches the desired aspect ratio and is wide/high enough
2676 SupportedV4L2Format v4l2Fmt {.width = 0, .height = 0};
2677 for (const auto& fmt : mSupportedFormats) {
2678 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2679 if (dim >= maxDim) {
2680 float aspectRatio = ASPECT_RATIO(fmt);
2681 if (isAspectRatioClose(aspectRatio, desiredAr)) {
2682 v4l2Fmt = fmt;
2683 // since mSupportedFormats is sorted by width then height, the first matching fmt
2684 // will be the smallest one with matching aspect ratio
2685 break;
2686 }
2687 }
2688 }
2689 if (v4l2Fmt.width == 0) {
2690 // Cannot find exact good aspect ratio candidate, try to find a close one
2691 for (const auto& fmt : mSupportedFormats) {
2692 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2693 if (dim >= maxDim) {
2694 float aspectRatio = ASPECT_RATIO(fmt);
2695 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2696 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2697 v4l2Fmt = fmt;
2698 break;
2699 }
2700 }
2701 }
2702 }
2703
2704 if (v4l2Fmt.width == 0) {
2705 ALOGE("%s: unable to find a resolution matching (%s at least %d, aspect ratio %f)"
2706 , __FUNCTION__, (mCroppingType == VERTICAL) ? "width" : "height",
2707 maxDim, desiredAr);
2708 return Status::ILLEGAL_ARGUMENT;
2709 }
2710
2711 if (configureV4l2StreamLocked(v4l2Fmt) != 0) {
2712 ALOGE("V4L configuration failed!, format:%c%c%c%c, w %d, h %d",
2713 v4l2Fmt.fourcc & 0xFF,
2714 (v4l2Fmt.fourcc >> 8) & 0xFF,
2715 (v4l2Fmt.fourcc >> 16) & 0xFF,
2716 (v4l2Fmt.fourcc >> 24) & 0xFF,
2717 v4l2Fmt.width, v4l2Fmt.height);
2718 return Status::INTERNAL_ERROR;
2719 }
2720
2721 Size v4lSize = {v4l2Fmt.width, v4l2Fmt.height};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08002722 Size thumbSize { 0, 0 };
2723 camera_metadata_ro_entry entry =
2724 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
2725 for(uint32_t i = 0; i < entry.count; i += 2) {
2726 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
2727 static_cast<uint32_t>(entry.data.i32[i+1]) };
2728 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
2729 thumbSize = sz;
2730 }
2731 }
2732
2733 if (thumbSize.width * thumbSize.height == 0) {
2734 ALOGE("%s: non-zero thumbnail size not available", __FUNCTION__);
2735 return Status::INTERNAL_ERROR;
2736 }
2737
2738 status = mOutputThread->allocateIntermediateBuffers(v4lSize,
Yin-Chia Yeh4c641182018-08-06 15:01:20 -07002739 mMaxThumbResolution, config.streams, blobBufferSize);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002740 if (status != Status::OK) {
2741 ALOGE("%s: allocating intermediate buffers failed!", __FUNCTION__);
2742 return status;
2743 }
2744
2745 out->streams.resize(config.streams.size());
2746 for (size_t i = 0; i < config.streams.size(); i++) {
2747 out->streams[i].overrideDataSpace = config.streams[i].dataSpace;
2748 out->streams[i].v3_2.id = config.streams[i].id;
2749 // TODO: double check should we add those CAMERA flags
2750 mStreamMap[config.streams[i].id].usage =
2751 out->streams[i].v3_2.producerUsage = config.streams[i].usage |
2752 BufferUsage::CPU_WRITE_OFTEN |
2753 BufferUsage::CAMERA_OUTPUT;
2754 out->streams[i].v3_2.consumerUsage = 0;
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002755 out->streams[i].v3_2.maxBuffers = mV4L2BufferCount;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002756
2757 switch (config.streams[i].format) {
2758 case PixelFormat::BLOB:
2759 case PixelFormat::YCBCR_420_888:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002760 case PixelFormat::YV12: // Used by SurfaceTexture
Emil Jahshaneed00402018-12-11 15:15:17 +02002761 case PixelFormat::Y16:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002762 // No override
2763 out->streams[i].v3_2.overrideFormat = config.streams[i].format;
2764 break;
2765 case PixelFormat::IMPLEMENTATION_DEFINED:
2766 // Override based on VIDEO or not
2767 out->streams[i].v3_2.overrideFormat =
2768 (config.streams[i].usage & BufferUsage::VIDEO_ENCODER) ?
2769 PixelFormat::YCBCR_420_888 : PixelFormat::YV12;
2770 // Save overridden formt in mStreamMap
2771 mStreamMap[config.streams[i].id].format = out->streams[i].v3_2.overrideFormat;
2772 break;
2773 default:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002774 ALOGE("%s: unsupported format 0x%x", __FUNCTION__, config.streams[i].format);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002775 return Status::ILLEGAL_ARGUMENT;
2776 }
2777 }
2778
2779 mFirstRequest = true;
2780 return Status::OK;
2781}
2782
2783bool ExternalCameraDeviceSession::isClosed() {
2784 Mutex::Autolock _l(mLock);
2785 return mClosed;
2786}
2787
2788#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
2789#define UPDATE(md, tag, data, size) \
2790do { \
2791 if ((md).update((tag), (data), (size))) { \
2792 ALOGE("Update " #tag " failed!"); \
2793 return BAD_VALUE; \
2794 } \
2795} while (0)
2796
2797status_t ExternalCameraDeviceSession::initDefaultRequests() {
2798 ::android::hardware::camera::common::V1_0::helper::CameraMetadata md;
2799
2800 const uint8_t aberrationMode = ANDROID_COLOR_CORRECTION_ABERRATION_MODE_OFF;
2801 UPDATE(md, ANDROID_COLOR_CORRECTION_ABERRATION_MODE, &aberrationMode, 1);
2802
2803 const int32_t exposureCompensation = 0;
2804 UPDATE(md, ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION, &exposureCompensation, 1);
2805
2806 const uint8_t videoStabilizationMode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
2807 UPDATE(md, ANDROID_CONTROL_VIDEO_STABILIZATION_MODE, &videoStabilizationMode, 1);
2808
2809 const uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO;
2810 UPDATE(md, ANDROID_CONTROL_AWB_MODE, &awbMode, 1);
2811
2812 const uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON;
2813 UPDATE(md, ANDROID_CONTROL_AE_MODE, &aeMode, 1);
2814
2815 const uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
2816 UPDATE(md, ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
2817
2818 const uint8_t afMode = ANDROID_CONTROL_AF_MODE_AUTO;
2819 UPDATE(md, ANDROID_CONTROL_AF_MODE, &afMode, 1);
2820
2821 const uint8_t afTrigger = ANDROID_CONTROL_AF_TRIGGER_IDLE;
2822 UPDATE(md, ANDROID_CONTROL_AF_TRIGGER, &afTrigger, 1);
2823
2824 const uint8_t sceneMode = ANDROID_CONTROL_SCENE_MODE_DISABLED;
2825 UPDATE(md, ANDROID_CONTROL_SCENE_MODE, &sceneMode, 1);
2826
2827 const uint8_t effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF;
2828 UPDATE(md, ANDROID_CONTROL_EFFECT_MODE, &effectMode, 1);
2829
2830 const uint8_t flashMode = ANDROID_FLASH_MODE_OFF;
2831 UPDATE(md, ANDROID_FLASH_MODE, &flashMode, 1);
2832
2833 const int32_t thumbnailSize[] = {240, 180};
2834 UPDATE(md, ANDROID_JPEG_THUMBNAIL_SIZE, thumbnailSize, 2);
2835
2836 const uint8_t jpegQuality = 90;
2837 UPDATE(md, ANDROID_JPEG_QUALITY, &jpegQuality, 1);
2838 UPDATE(md, ANDROID_JPEG_THUMBNAIL_QUALITY, &jpegQuality, 1);
2839
2840 const int32_t jpegOrientation = 0;
2841 UPDATE(md, ANDROID_JPEG_ORIENTATION, &jpegOrientation, 1);
2842
2843 const uint8_t oisMode = ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF;
2844 UPDATE(md, ANDROID_LENS_OPTICAL_STABILIZATION_MODE, &oisMode, 1);
2845
2846 const uint8_t nrMode = ANDROID_NOISE_REDUCTION_MODE_OFF;
2847 UPDATE(md, ANDROID_NOISE_REDUCTION_MODE, &nrMode, 1);
2848
Yin-Chia Yehc15a1ca2018-03-02 14:16:52 -08002849 const int32_t testPatternModes = ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
2850 UPDATE(md, ANDROID_SENSOR_TEST_PATTERN_MODE, &testPatternModes, 1);
2851
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002852 const uint8_t fdMode = ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
2853 UPDATE(md, ANDROID_STATISTICS_FACE_DETECT_MODE, &fdMode, 1);
2854
2855 const uint8_t hotpixelMode = ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF;
2856 UPDATE(md, ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE, &hotpixelMode, 1);
2857
2858 bool support30Fps = false;
2859 int32_t maxFps = std::numeric_limits<int32_t>::min();
2860 for (const auto& supportedFormat : mSupportedFormats) {
Yin-Chia Yeh134093a2018-02-12 14:05:48 -08002861 for (const auto& fr : supportedFormat.frameRates) {
2862 int32_t framerateInt = static_cast<int32_t>(fr.getDouble());
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002863 if (maxFps < framerateInt) {
2864 maxFps = framerateInt;
2865 }
2866 if (framerateInt == 30) {
2867 support30Fps = true;
2868 break;
2869 }
2870 }
2871 if (support30Fps) {
2872 break;
2873 }
2874 }
2875 int32_t defaultFramerate = support30Fps ? 30 : maxFps;
Yin-Chia Yehc15a1ca2018-03-02 14:16:52 -08002876 int32_t defaultFpsRange[] = {defaultFramerate / 2, defaultFramerate};
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002877 UPDATE(md, ANDROID_CONTROL_AE_TARGET_FPS_RANGE, defaultFpsRange, ARRAY_SIZE(defaultFpsRange));
2878
2879 uint8_t antibandingMode = ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO;
2880 UPDATE(md, ANDROID_CONTROL_AE_ANTIBANDING_MODE, &antibandingMode, 1);
2881
2882 const uint8_t controlMode = ANDROID_CONTROL_MODE_AUTO;
2883 UPDATE(md, ANDROID_CONTROL_MODE, &controlMode, 1);
2884
Steven Morelandc90461c2018-05-01 16:54:09 -07002885 auto requestTemplates = hidl_enum_range<RequestTemplate>();
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002886 for (RequestTemplate type : requestTemplates) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002887 ::android::hardware::camera::common::V1_0::helper::CameraMetadata mdCopy = md;
2888 uint8_t intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2889 switch (type) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002890 case RequestTemplate::PREVIEW:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002891 intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2892 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002893 case RequestTemplate::STILL_CAPTURE:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002894 intent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE;
2895 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002896 case RequestTemplate::VIDEO_RECORD:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002897 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD;
2898 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002899 case RequestTemplate::VIDEO_SNAPSHOT:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002900 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT;
2901 break;
2902 default:
Yuriy Romanenko083de0c2018-01-26 16:05:54 -08002903 ALOGV("%s: unsupported RequestTemplate type %d", __FUNCTION__, type);
2904 continue;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002905 }
2906 UPDATE(mdCopy, ANDROID_CONTROL_CAPTURE_INTENT, &intent, 1);
2907
2908 camera_metadata_t* rawMd = mdCopy.release();
2909 CameraMetadata hidlMd;
2910 hidlMd.setToExternal(
2911 (uint8_t*) rawMd, get_camera_metadata_size(rawMd));
2912 mDefaultRequests[type] = hidlMd;
2913 free_camera_metadata(rawMd);
2914 }
2915
2916 return OK;
2917}
2918
2919status_t ExternalCameraDeviceSession::fillCaptureResult(
2920 common::V1_0::helper::CameraMetadata &md, nsecs_t timestamp) {
2921 // android.control
2922 // For USB camera, we don't know the AE state. Set the state to converged to
2923 // indicate the frame should be good to use. Then apps don't have to wait the
2924 // AE state.
2925 const uint8_t aeState = ANDROID_CONTROL_AE_STATE_CONVERGED;
2926 UPDATE(md, ANDROID_CONTROL_AE_STATE, &aeState, 1);
2927
2928 const uint8_t ae_lock = ANDROID_CONTROL_AE_LOCK_OFF;
2929 UPDATE(md, ANDROID_CONTROL_AE_LOCK, &ae_lock, 1);
2930
Yin-Chia Yeh94f52a32018-03-07 14:46:51 -08002931 bool afTrigger = false;
2932 {
2933 std::lock_guard<std::mutex> lk(mAfTriggerLock);
2934 afTrigger = mAfTrigger;
2935 if (md.exists(ANDROID_CONTROL_AF_TRIGGER)) {
2936 camera_metadata_entry entry = md.find(ANDROID_CONTROL_AF_TRIGGER);
2937 if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_START) {
2938 mAfTrigger = afTrigger = true;
2939 } else if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_CANCEL) {
2940 mAfTrigger = afTrigger = false;
2941 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002942 }
2943 }
2944
2945 // For USB camera, the USB camera handles everything and we don't have control
2946 // over AF. We only simply fake the AF metadata based on the request
2947 // received here.
2948 uint8_t afState;
2949 if (afTrigger) {
2950 afState = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
2951 } else {
2952 afState = ANDROID_CONTROL_AF_STATE_INACTIVE;
2953 }
2954 UPDATE(md, ANDROID_CONTROL_AF_STATE, &afState, 1);
2955
2956 // Set AWB state to converged to indicate the frame should be good to use.
2957 const uint8_t awbState = ANDROID_CONTROL_AWB_STATE_CONVERGED;
2958 UPDATE(md, ANDROID_CONTROL_AWB_STATE, &awbState, 1);
2959
2960 const uint8_t awbLock = ANDROID_CONTROL_AWB_LOCK_OFF;
2961 UPDATE(md, ANDROID_CONTROL_AWB_LOCK, &awbLock, 1);
2962
2963 camera_metadata_ro_entry active_array_size =
2964 mCameraCharacteristics.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
2965
2966 if (active_array_size.count == 0) {
2967 ALOGE("%s: cannot find active array size!", __FUNCTION__);
2968 return -EINVAL;
2969 }
2970
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002971 const uint8_t flashState = ANDROID_FLASH_STATE_UNAVAILABLE;
2972 UPDATE(md, ANDROID_FLASH_STATE, &flashState, 1);
2973
Yin-Chia Yehc15a1ca2018-03-02 14:16:52 -08002974 // This means pipeline latency of X frame intervals. The maximum number is 4.
2975 const uint8_t requestPipelineMaxDepth = 4;
2976 UPDATE(md, ANDROID_REQUEST_PIPELINE_DEPTH, &requestPipelineMaxDepth, 1);
2977
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002978 // android.scaler
2979 const int32_t crop_region[] = {
2980 active_array_size.data.i32[0], active_array_size.data.i32[1],
2981 active_array_size.data.i32[2], active_array_size.data.i32[3],
2982 };
2983 UPDATE(md, ANDROID_SCALER_CROP_REGION, crop_region, ARRAY_SIZE(crop_region));
2984
2985 // android.sensor
2986 UPDATE(md, ANDROID_SENSOR_TIMESTAMP, &timestamp, 1);
2987
2988 // android.statistics
2989 const uint8_t lensShadingMapMode = ANDROID_STATISTICS_LENS_SHADING_MAP_MODE_OFF;
2990 UPDATE(md, ANDROID_STATISTICS_LENS_SHADING_MAP_MODE, &lensShadingMapMode, 1);
2991
2992 const uint8_t sceneFlicker = ANDROID_STATISTICS_SCENE_FLICKER_NONE;
2993 UPDATE(md, ANDROID_STATISTICS_SCENE_FLICKER, &sceneFlicker, 1);
2994
2995 return OK;
2996}
2997
2998#undef ARRAY_SIZE
2999#undef UPDATE
3000
Yin-Chia Yeh19030592017-10-19 17:30:11 -07003001} // namespace implementation
3002} // namespace V3_4
3003} // namespace device
3004} // namespace camera
3005} // namespace hardware
3006} // namespace android