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