blob: a46bcac34195f846ece8152ce9e36174ecc87c83 [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 Yeh53f4cb12018-01-29 10:31:45 -080049} // Anonymous namespace
Yin-Chia Yeh19030592017-10-19 17:30:11 -070050
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080051// Static instances
52const int ExternalCameraDeviceSession::kMaxProcessedStream;
53const int ExternalCameraDeviceSession::kMaxStallStream;
Yin-Chia Yeh19030592017-10-19 17:30:11 -070054HandleImporter ExternalCameraDeviceSession::sHandleImporter;
55
Yin-Chia Yeh19030592017-10-19 17:30:11 -070056ExternalCameraDeviceSession::ExternalCameraDeviceSession(
57 const sp<ICameraDeviceCallback>& callback,
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080058 const ExternalCameraDeviceConfig& cfg,
59 const std::vector<SupportedV4L2Format>& sortedFormats,
60 const CroppingType& croppingType,
Yin-Chia Yeh19030592017-10-19 17:30:11 -070061 const common::V1_0::helper::CameraMetadata& chars,
62 unique_fd v4l2Fd) :
63 mCallback(callback),
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080064 mCfg(cfg),
Yin-Chia Yeh19030592017-10-19 17:30:11 -070065 mCameraCharacteristics(chars),
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080066 mSupportedFormats(sortedFormats),
67 mCroppingType(croppingType),
Yin-Chia Yeh19030592017-10-19 17:30:11 -070068 mV4l2Fd(std::move(v4l2Fd)),
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -080069 mOutputThread(new OutputThread(this, mCroppingType)),
70 mMaxThumbResolution(getMaxThumbResolution()),
71 mMaxJpegResolution(getMaxJpegResolution()) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -070072 mInitFail = initialize();
73}
74
Yin-Chia Yeh19030592017-10-19 17:30:11 -070075bool ExternalCameraDeviceSession::initialize() {
76 if (mV4l2Fd.get() < 0) {
77 ALOGE("%s: invalid v4l2 device fd %d!", __FUNCTION__, mV4l2Fd.get());
78 return true;
79 }
80
81 status_t status = initDefaultRequests();
82 if (status != OK) {
83 ALOGE("%s: init default requests failed!", __FUNCTION__);
84 return true;
85 }
86
87 mRequestMetadataQueue = std::make_unique<RequestMetadataQueue>(
88 kMetadataMsgQueueSize, false /* non blocking */);
89 if (!mRequestMetadataQueue->isValid()) {
90 ALOGE("%s: invalid request fmq", __FUNCTION__);
91 return true;
92 }
93 mResultMetadataQueue = std::make_shared<RequestMetadataQueue>(
94 kMetadataMsgQueueSize, false /* non blocking */);
95 if (!mResultMetadataQueue->isValid()) {
96 ALOGE("%s: invalid result fmq", __FUNCTION__);
97 return true;
98 }
99
100 // TODO: check is PRIORITY_DISPLAY enough?
101 mOutputThread->run("ExtCamOut", PRIORITY_DISPLAY);
102 return false;
103}
104
105Status ExternalCameraDeviceSession::initStatus() const {
106 Mutex::Autolock _l(mLock);
107 Status status = Status::OK;
108 if (mInitFail || mClosed) {
109 ALOGI("%s: sesssion initFailed %d closed %d", __FUNCTION__, mInitFail, mClosed);
110 status = Status::INTERNAL_ERROR;
111 }
112 return status;
113}
114
115ExternalCameraDeviceSession::~ExternalCameraDeviceSession() {
116 if (!isClosed()) {
117 ALOGE("ExternalCameraDeviceSession deleted before close!");
118 close();
119 }
120}
121
122void ExternalCameraDeviceSession::dumpState(const native_handle_t*) {
123 // TODO: b/72261676 dump more runtime information
124}
125
126Return<void> ExternalCameraDeviceSession::constructDefaultRequestSettings(
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800127 V3_2::RequestTemplate type,
128 V3_2::ICameraDeviceSession::constructDefaultRequestSettings_cb _hidl_cb) {
129 V3_2::CameraMetadata outMetadata;
130 Status status = constructDefaultRequestSettingsRaw(
131 static_cast<RequestTemplate>(type), &outMetadata);
132 _hidl_cb(status, outMetadata);
133 return Void();
134}
135
136Return<void> ExternalCameraDeviceSession::constructDefaultRequestSettings_3_4(
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700137 RequestTemplate type,
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800138 ICameraDeviceSession::constructDefaultRequestSettings_cb _hidl_cb) {
139 V3_2::CameraMetadata outMetadata;
140 Status status = constructDefaultRequestSettingsRaw(type, &outMetadata);
141 _hidl_cb(status, outMetadata);
142 return Void();
143}
144
145Status ExternalCameraDeviceSession::constructDefaultRequestSettingsRaw(RequestTemplate type,
146 V3_2::CameraMetadata *outMetadata) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700147 CameraMetadata emptyMd;
148 Status status = initStatus();
149 if (status != Status::OK) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800150 return status;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700151 }
152
153 switch (type) {
154 case RequestTemplate::PREVIEW:
155 case RequestTemplate::STILL_CAPTURE:
156 case RequestTemplate::VIDEO_RECORD:
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800157 case RequestTemplate::VIDEO_SNAPSHOT: {
158 *outMetadata = mDefaultRequests[type];
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700159 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800160 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700161 case RequestTemplate::MANUAL:
162 case RequestTemplate::ZERO_SHUTTER_LAG:
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800163 case RequestTemplate::MOTION_TRACKING_PREVIEW:
164 case RequestTemplate::MOTION_TRACKING_BEST:
165 // Don't support MANUAL, ZSL, MOTION_TRACKING_* templates
166 status = Status::ILLEGAL_ARGUMENT;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700167 break;
168 default:
169 ALOGE("%s: unknown request template type %d", __FUNCTION__, static_cast<int>(type));
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800170 status = Status::ILLEGAL_ARGUMENT;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700171 break;
172 }
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800173 return status;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700174}
175
176Return<void> ExternalCameraDeviceSession::configureStreams(
177 const V3_2::StreamConfiguration& streams,
178 ICameraDeviceSession::configureStreams_cb _hidl_cb) {
179 V3_2::HalStreamConfiguration outStreams;
180 V3_3::HalStreamConfiguration outStreams_v33;
181 Mutex::Autolock _il(mInterfaceLock);
182
183 Status status = configureStreams(streams, &outStreams_v33);
184 size_t size = outStreams_v33.streams.size();
185 outStreams.streams.resize(size);
186 for (size_t i = 0; i < size; i++) {
187 outStreams.streams[i] = outStreams_v33.streams[i].v3_2;
188 }
189 _hidl_cb(status, outStreams);
190 return Void();
191}
192
193Return<void> ExternalCameraDeviceSession::configureStreams_3_3(
194 const V3_2::StreamConfiguration& streams,
195 ICameraDeviceSession::configureStreams_3_3_cb _hidl_cb) {
196 V3_3::HalStreamConfiguration outStreams;
197 Mutex::Autolock _il(mInterfaceLock);
198
199 Status status = configureStreams(streams, &outStreams);
200 _hidl_cb(status, outStreams);
201 return Void();
202}
203
204Return<void> ExternalCameraDeviceSession::configureStreams_3_4(
205 const V3_4::StreamConfiguration& requestedConfiguration,
206 ICameraDeviceSession::configureStreams_3_4_cb _hidl_cb) {
207 V3_2::StreamConfiguration config_v32;
208 V3_3::HalStreamConfiguration outStreams_v33;
209 Mutex::Autolock _il(mInterfaceLock);
210
211 config_v32.operationMode = requestedConfiguration.operationMode;
212 config_v32.streams.resize(requestedConfiguration.streams.size());
213 for (size_t i = 0; i < config_v32.streams.size(); i++) {
214 config_v32.streams[i] = requestedConfiguration.streams[i].v3_2;
215 }
216
217 // Ignore requestedConfiguration.sessionParams. External camera does not support it
218 Status status = configureStreams(config_v32, &outStreams_v33);
219
220 V3_4::HalStreamConfiguration outStreams;
221 outStreams.streams.resize(outStreams_v33.streams.size());
222 for (size_t i = 0; i < outStreams.streams.size(); i++) {
223 outStreams.streams[i].v3_3 = outStreams_v33.streams[i];
224 }
225 _hidl_cb(status, outStreams);
226 return Void();
227}
228
229Return<void> ExternalCameraDeviceSession::getCaptureRequestMetadataQueue(
230 ICameraDeviceSession::getCaptureRequestMetadataQueue_cb _hidl_cb) {
231 Mutex::Autolock _il(mInterfaceLock);
232 _hidl_cb(*mRequestMetadataQueue->getDesc());
233 return Void();
234}
235
236Return<void> ExternalCameraDeviceSession::getCaptureResultMetadataQueue(
237 ICameraDeviceSession::getCaptureResultMetadataQueue_cb _hidl_cb) {
238 Mutex::Autolock _il(mInterfaceLock);
239 _hidl_cb(*mResultMetadataQueue->getDesc());
240 return Void();
241}
242
243Return<void> ExternalCameraDeviceSession::processCaptureRequest(
244 const hidl_vec<CaptureRequest>& requests,
245 const hidl_vec<BufferCache>& cachesToRemove,
246 ICameraDeviceSession::processCaptureRequest_cb _hidl_cb) {
247 Mutex::Autolock _il(mInterfaceLock);
248 updateBufferCaches(cachesToRemove);
249
250 uint32_t numRequestProcessed = 0;
251 Status s = Status::OK;
252 for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
253 s = processOneCaptureRequest(requests[i]);
254 if (s != Status::OK) {
255 break;
256 }
257 }
258
259 _hidl_cb(s, numRequestProcessed);
260 return Void();
261}
262
263Return<void> ExternalCameraDeviceSession::processCaptureRequest_3_4(
264 const hidl_vec<V3_4::CaptureRequest>& requests,
265 const hidl_vec<V3_2::BufferCache>& cachesToRemove,
266 ICameraDeviceSession::processCaptureRequest_3_4_cb _hidl_cb) {
267 Mutex::Autolock _il(mInterfaceLock);
268 updateBufferCaches(cachesToRemove);
269
270 uint32_t numRequestProcessed = 0;
271 Status s = Status::OK;
272 for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
273 s = processOneCaptureRequest(requests[i].v3_2);
274 if (s != Status::OK) {
275 break;
276 }
277 }
278
279 _hidl_cb(s, numRequestProcessed);
280 return Void();
281}
282
283Return<Status> ExternalCameraDeviceSession::flush() {
284 return Status::OK;
285}
286
287Return<void> ExternalCameraDeviceSession::close() {
288 Mutex::Autolock _il(mInterfaceLock);
289 Mutex::Autolock _l(mLock);
290 if (!mClosed) {
291 // TODO: b/72261676 Cleanup inflight buffers/V4L2 buffer queue
292 ALOGV("%s: closing V4L2 camera FD %d", __FUNCTION__, mV4l2Fd.get());
293 mV4l2Fd.reset();
294 mOutputThread->requestExit(); // TODO: join?
295
296 // free all imported buffers
297 for(auto& pair : mCirculatingBuffers) {
298 CirculatingBuffers& buffers = pair.second;
299 for (auto& p2 : buffers) {
300 sHandleImporter.freeBuffer(p2.second);
301 }
302 }
303
304 mClosed = true;
305 }
306 return Void();
307}
308
309Status ExternalCameraDeviceSession::importRequest(
310 const CaptureRequest& request,
311 hidl_vec<buffer_handle_t*>& allBufPtrs,
312 hidl_vec<int>& allFences) {
313 size_t numOutputBufs = request.outputBuffers.size();
314 size_t numBufs = numOutputBufs;
315 // Validate all I/O buffers
316 hidl_vec<buffer_handle_t> allBufs;
317 hidl_vec<uint64_t> allBufIds;
318 allBufs.resize(numBufs);
319 allBufIds.resize(numBufs);
320 allBufPtrs.resize(numBufs);
321 allFences.resize(numBufs);
322 std::vector<int32_t> streamIds(numBufs);
323
324 for (size_t i = 0; i < numOutputBufs; i++) {
325 allBufs[i] = request.outputBuffers[i].buffer.getNativeHandle();
326 allBufIds[i] = request.outputBuffers[i].bufferId;
327 allBufPtrs[i] = &allBufs[i];
328 streamIds[i] = request.outputBuffers[i].streamId;
329 }
330
331 for (size_t i = 0; i < numBufs; i++) {
332 buffer_handle_t buf = allBufs[i];
333 uint64_t bufId = allBufIds[i];
334 CirculatingBuffers& cbs = mCirculatingBuffers[streamIds[i]];
335 if (cbs.count(bufId) == 0) {
336 if (buf == nullptr) {
337 ALOGE("%s: bufferId %" PRIu64 " has null buffer handle!", __FUNCTION__, bufId);
338 return Status::ILLEGAL_ARGUMENT;
339 }
340 // Register a newly seen buffer
341 buffer_handle_t importedBuf = buf;
342 sHandleImporter.importBuffer(importedBuf);
343 if (importedBuf == nullptr) {
344 ALOGE("%s: output buffer %zu is invalid!", __FUNCTION__, i);
345 return Status::INTERNAL_ERROR;
346 } else {
347 cbs[bufId] = importedBuf;
348 }
349 }
350 allBufPtrs[i] = &cbs[bufId];
351 }
352
353 // All buffers are imported. Now validate output buffer acquire fences
354 for (size_t i = 0; i < numOutputBufs; i++) {
355 if (!sHandleImporter.importFence(
356 request.outputBuffers[i].acquireFence, allFences[i])) {
357 ALOGE("%s: output buffer %zu acquire fence is invalid", __FUNCTION__, i);
358 cleanupInflightFences(allFences, i);
359 return Status::INTERNAL_ERROR;
360 }
361 }
362 return Status::OK;
363}
364
365void ExternalCameraDeviceSession::cleanupInflightFences(
366 hidl_vec<int>& allFences, size_t numFences) {
367 for (size_t j = 0; j < numFences; j++) {
368 sHandleImporter.closeFence(allFences[j]);
369 }
370}
371
372Status ExternalCameraDeviceSession::processOneCaptureRequest(const CaptureRequest& request) {
373 Status status = initStatus();
374 if (status != Status::OK) {
375 return status;
376 }
377
378 if (request.inputBuffer.streamId != -1) {
379 ALOGE("%s: external camera does not support reprocessing!", __FUNCTION__);
380 return Status::ILLEGAL_ARGUMENT;
381 }
382
383 Mutex::Autolock _l(mLock);
384 if (!mV4l2Streaming) {
385 ALOGE("%s: cannot process request in streamOff state!", __FUNCTION__);
386 return Status::INTERNAL_ERROR;
387 }
388
389 const camera_metadata_t *rawSettings = nullptr;
390 bool converted = true;
391 CameraMetadata settingsFmq; // settings from FMQ
392 if (request.fmqSettingsSize > 0) {
393 // non-blocking read; client must write metadata before calling
394 // processOneCaptureRequest
395 settingsFmq.resize(request.fmqSettingsSize);
396 bool read = mRequestMetadataQueue->read(settingsFmq.data(), request.fmqSettingsSize);
397 if (read) {
398 converted = V3_2::implementation::convertFromHidl(settingsFmq, &rawSettings);
399 } else {
400 ALOGE("%s: capture request settings metadata couldn't be read from fmq!", __FUNCTION__);
401 converted = false;
402 }
403 } else {
404 converted = V3_2::implementation::convertFromHidl(request.settings, &rawSettings);
405 }
406
407 if (converted && rawSettings != nullptr) {
408 mLatestReqSetting = rawSettings;
409 }
410
411 if (!converted) {
412 ALOGE("%s: capture request settings metadata is corrupt!", __FUNCTION__);
413 return Status::ILLEGAL_ARGUMENT;
414 }
415
416 if (mFirstRequest && rawSettings == nullptr) {
417 ALOGE("%s: capture request settings must not be null for first request!",
418 __FUNCTION__);
419 return Status::ILLEGAL_ARGUMENT;
420 }
421
422 hidl_vec<buffer_handle_t*> allBufPtrs;
423 hidl_vec<int> allFences;
424 size_t numOutputBufs = request.outputBuffers.size();
425
426 if (numOutputBufs == 0) {
427 ALOGE("%s: capture request must have at least one output buffer!", __FUNCTION__);
428 return Status::ILLEGAL_ARGUMENT;
429 }
430
431 status = importRequest(request, allBufPtrs, allFences);
432 if (status != Status::OK) {
433 return status;
434 }
435
436 // TODO: program fps range per capture request here
437 // or limit the set of availableFpsRange
438
439 sp<V4L2Frame> frameIn = dequeueV4l2FrameLocked();
440 if ( frameIn == nullptr) {
441 ALOGE("%s: V4L2 deque frame failed!", __FUNCTION__);
442 return Status::INTERNAL_ERROR;
443 }
444 // TODO: This can probably be replaced by use v4lbuffer timestamp
445 // if the device supports it
446 nsecs_t shutterTs = systemTime(SYSTEM_TIME_MONOTONIC);
447
448
449 // TODO: reduce object copy in this path
450 HalRequest halReq = {
451 .frameNumber = request.frameNumber,
452 .setting = mLatestReqSetting,
453 .frameIn = frameIn,
454 .shutterTs = shutterTs};
455 halReq.buffers.resize(numOutputBufs);
456 for (size_t i = 0; i < numOutputBufs; i++) {
457 HalStreamBuffer& halBuf = halReq.buffers[i];
458 int streamId = halBuf.streamId = request.outputBuffers[i].streamId;
459 halBuf.bufferId = request.outputBuffers[i].bufferId;
460 const Stream& stream = mStreamMap[streamId];
461 halBuf.width = stream.width;
462 halBuf.height = stream.height;
463 halBuf.format = stream.format;
464 halBuf.usage = stream.usage;
465 halBuf.bufPtr = allBufPtrs[i];
466 halBuf.acquireFence = allFences[i];
467 halBuf.fenceTimeout = false;
468 }
469 mInflightFrames.insert(halReq.frameNumber);
470 // Send request to OutputThread for the rest of processing
471 mOutputThread->submitRequest(halReq);
472 mFirstRequest = false;
473 return Status::OK;
474}
475
476void ExternalCameraDeviceSession::notifyShutter(uint32_t frameNumber, nsecs_t shutterTs) {
477 NotifyMsg msg;
478 msg.type = MsgType::SHUTTER;
479 msg.msg.shutter.frameNumber = frameNumber;
480 msg.msg.shutter.timestamp = shutterTs;
481 mCallback->notify({msg});
482}
483
484void ExternalCameraDeviceSession::notifyError(
485 uint32_t frameNumber, int32_t streamId, ErrorCode ec) {
486 NotifyMsg msg;
487 msg.type = MsgType::ERROR;
488 msg.msg.error.frameNumber = frameNumber;
489 msg.msg.error.errorStreamId = streamId;
490 msg.msg.error.errorCode = ec;
491 mCallback->notify({msg});
492}
493
494//TODO: refactor with processCaptureResult
495Status ExternalCameraDeviceSession::processCaptureRequestError(HalRequest& req) {
496 // Return V4L2 buffer to V4L2 buffer queue
497 enqueueV4l2Frame(req.frameIn);
498
499 // NotifyShutter
500 notifyShutter(req.frameNumber, req.shutterTs);
501
502 notifyError(/*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_REQUEST);
503
504 // Fill output buffers
505 hidl_vec<CaptureResult> results;
506 results.resize(1);
507 CaptureResult& result = results[0];
508 result.frameNumber = req.frameNumber;
509 result.partialResult = 1;
510 result.inputBuffer.streamId = -1;
511 result.outputBuffers.resize(req.buffers.size());
512 for (size_t i = 0; i < req.buffers.size(); i++) {
513 result.outputBuffers[i].streamId = req.buffers[i].streamId;
514 result.outputBuffers[i].bufferId = req.buffers[i].bufferId;
515 result.outputBuffers[i].status = BufferStatus::ERROR;
516 if (req.buffers[i].acquireFence >= 0) {
517 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
518 handle->data[0] = req.buffers[i].acquireFence;
519 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/true);
520 }
521 }
522
523 // update inflight records
524 {
525 Mutex::Autolock _l(mLock);
526 mInflightFrames.erase(req.frameNumber);
527 }
528
529 // Callback into framework
530 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
531 freeReleaseFences(results);
532 return Status::OK;
533}
534
535Status ExternalCameraDeviceSession::processCaptureResult(HalRequest& req) {
536 // Return V4L2 buffer to V4L2 buffer queue
537 enqueueV4l2Frame(req.frameIn);
538
539 // NotifyShutter
540 notifyShutter(req.frameNumber, req.shutterTs);
541
542 // Fill output buffers
543 hidl_vec<CaptureResult> results;
544 results.resize(1);
545 CaptureResult& result = results[0];
546 result.frameNumber = req.frameNumber;
547 result.partialResult = 1;
548 result.inputBuffer.streamId = -1;
549 result.outputBuffers.resize(req.buffers.size());
550 for (size_t i = 0; i < req.buffers.size(); i++) {
551 result.outputBuffers[i].streamId = req.buffers[i].streamId;
552 result.outputBuffers[i].bufferId = req.buffers[i].bufferId;
553 if (req.buffers[i].fenceTimeout) {
554 result.outputBuffers[i].status = BufferStatus::ERROR;
555 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
556 handle->data[0] = req.buffers[i].acquireFence;
557 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/true);
558 notifyError(req.frameNumber, req.buffers[i].streamId, ErrorCode::ERROR_BUFFER);
559 } else {
560 result.outputBuffers[i].status = BufferStatus::OK;
561 // TODO: refactor
562 if (req.buffers[i].acquireFence > 0) {
563 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
564 handle->data[0] = req.buffers[i].acquireFence;
565 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/true);
566 }
567 }
568 }
569
570 // Fill capture result metadata
571 fillCaptureResult(req.setting, req.shutterTs);
572 const camera_metadata_t *rawResult = req.setting.getAndLock();
573 V3_2::implementation::convertToHidl(rawResult, &result.result);
574 req.setting.unlock(rawResult);
575
576 // update inflight records
577 {
578 Mutex::Autolock _l(mLock);
579 mInflightFrames.erase(req.frameNumber);
580 }
581
582 // Callback into framework
583 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
584 freeReleaseFences(results);
585 return Status::OK;
586}
587
588void ExternalCameraDeviceSession::invokeProcessCaptureResultCallback(
589 hidl_vec<CaptureResult> &results, bool tryWriteFmq) {
590 if (mProcessCaptureResultLock.tryLock() != OK) {
591 const nsecs_t NS_TO_SECOND = 1000000000;
592 ALOGV("%s: previous call is not finished! waiting 1s...", __FUNCTION__);
593 if (mProcessCaptureResultLock.timedLock(/* 1s */NS_TO_SECOND) != OK) {
594 ALOGE("%s: cannot acquire lock in 1s, cannot proceed",
595 __FUNCTION__);
596 return;
597 }
598 }
599 if (tryWriteFmq && mResultMetadataQueue->availableToWrite() > 0) {
600 for (CaptureResult &result : results) {
601 if (result.result.size() > 0) {
602 if (mResultMetadataQueue->write(result.result.data(), result.result.size())) {
603 result.fmqResultSize = result.result.size();
604 result.result.resize(0);
605 } else {
606 ALOGW("%s: couldn't utilize fmq, fall back to hwbinder", __FUNCTION__);
607 result.fmqResultSize = 0;
608 }
609 } else {
610 result.fmqResultSize = 0;
611 }
612 }
613 }
614 mCallback->processCaptureResult(results);
615 mProcessCaptureResultLock.unlock();
616}
617
618void ExternalCameraDeviceSession::freeReleaseFences(hidl_vec<CaptureResult>& results) {
619 for (auto& result : results) {
620 if (result.inputBuffer.releaseFence.getNativeHandle() != nullptr) {
621 native_handle_t* handle = const_cast<native_handle_t*>(
622 result.inputBuffer.releaseFence.getNativeHandle());
623 native_handle_close(handle);
624 native_handle_delete(handle);
625 }
626 for (auto& buf : result.outputBuffers) {
627 if (buf.releaseFence.getNativeHandle() != nullptr) {
628 native_handle_t* handle = const_cast<native_handle_t*>(
629 buf.releaseFence.getNativeHandle());
630 native_handle_close(handle);
631 native_handle_delete(handle);
632 }
633 }
634 }
635 return;
636}
637
638ExternalCameraDeviceSession::OutputThread::OutputThread(
639 wp<ExternalCameraDeviceSession> parent,
640 CroppingType ct) : mParent(parent), mCroppingType(ct) {}
641
642ExternalCameraDeviceSession::OutputThread::~OutputThread() {}
643
644uint32_t ExternalCameraDeviceSession::OutputThread::getFourCcFromLayout(
645 const YCbCrLayout& layout) {
646 intptr_t cb = reinterpret_cast<intptr_t>(layout.cb);
647 intptr_t cr = reinterpret_cast<intptr_t>(layout.cr);
648 if (std::abs(cb - cr) == 1 && layout.chromaStep == 2) {
649 // Interleaved format
650 if (layout.cb > layout.cr) {
651 return V4L2_PIX_FMT_NV21;
652 } else {
653 return V4L2_PIX_FMT_NV12;
654 }
655 } else if (layout.chromaStep == 1) {
656 // Planar format
657 if (layout.cb > layout.cr) {
658 return V4L2_PIX_FMT_YVU420; // YV12
659 } else {
660 return V4L2_PIX_FMT_YUV420; // YU12
661 }
662 } else {
663 return FLEX_YUV_GENERIC;
664 }
665}
666
667int ExternalCameraDeviceSession::OutputThread::getCropRect(
668 CroppingType ct, const Size& inSize, const Size& outSize, IMapper::Rect* out) {
669 if (out == nullptr) {
670 ALOGE("%s: out is null", __FUNCTION__);
671 return -1;
672 }
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800673
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700674 uint32_t inW = inSize.width;
675 uint32_t inH = inSize.height;
676 uint32_t outW = outSize.width;
677 uint32_t outH = outSize.height;
678
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800679 // Handle special case where aspect ratio is close to input but scaled
680 // dimension is slightly larger than input
681 float arIn = ASPECT_RATIO(inSize);
682 float arOut = ASPECT_RATIO(outSize);
683 if (isAspectRatioClose(arIn, arOut)) {
684 out->left = 0;
685 out->top = 0;
686 out->width = inW;
687 out->height = inH;
688 return 0;
689 }
690
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700691 if (ct == VERTICAL) {
692 uint64_t scaledOutH = static_cast<uint64_t>(outH) * inW / outW;
693 if (scaledOutH > inH) {
694 ALOGE("%s: Output size %dx%d cannot be vertically cropped from input size %dx%d",
695 __FUNCTION__, outW, outH, inW, inH);
696 return -1;
697 }
698 scaledOutH = scaledOutH & ~0x1; // make it multiple of 2
699
700 out->left = 0;
701 out->top = ((inH - scaledOutH) / 2) & ~0x1;
702 out->width = inW;
703 out->height = static_cast<int32_t>(scaledOutH);
704 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledH %d",
705 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutH));
706 } else {
707 uint64_t scaledOutW = static_cast<uint64_t>(outW) * inH / outH;
708 if (scaledOutW > inW) {
709 ALOGE("%s: Output size %dx%d cannot be horizontally cropped from input size %dx%d",
710 __FUNCTION__, outW, outH, inW, inH);
711 return -1;
712 }
713 scaledOutW = scaledOutW & ~0x1; // make it multiple of 2
714
715 out->left = ((inW - scaledOutW) / 2) & ~0x1;
716 out->top = 0;
717 out->width = static_cast<int32_t>(scaledOutW);
718 out->height = inH;
719 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledW %d",
720 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutW));
721 }
722
723 return 0;
724}
725
726int ExternalCameraDeviceSession::OutputThread::cropAndScaleLocked(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800727 sp<AllocatedFrame>& in, const Size& outSz, YCbCrLayout* out) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700728 Size inSz = {in->mWidth, in->mHeight};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800729
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700730 int ret;
731 if (inSz == outSz) {
732 ret = in->getLayout(out);
733 if (ret != 0) {
734 ALOGE("%s: failed to get input image layout", __FUNCTION__);
735 return ret;
736 }
737 return ret;
738 }
739
740 // Cropping to output aspect ratio
741 IMapper::Rect inputCrop;
742 ret = getCropRect(mCroppingType, inSz, outSz, &inputCrop);
743 if (ret != 0) {
744 ALOGE("%s: failed to compute crop rect for output size %dx%d",
745 __FUNCTION__, outSz.width, outSz.height);
746 return ret;
747 }
748
749 YCbCrLayout croppedLayout;
750 ret = in->getCroppedLayout(inputCrop, &croppedLayout);
751 if (ret != 0) {
752 ALOGE("%s: failed to crop input image %dx%d to output size %dx%d",
753 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
754 return ret;
755 }
756
757 if ((mCroppingType == VERTICAL && inSz.width == outSz.width) ||
758 (mCroppingType == HORIZONTAL && inSz.height == outSz.height)) {
759 // No scale is needed
760 *out = croppedLayout;
761 return 0;
762 }
763
764 auto it = mScaledYu12Frames.find(outSz);
765 sp<AllocatedFrame> scaledYu12Buf;
766 if (it != mScaledYu12Frames.end()) {
767 scaledYu12Buf = it->second;
768 } else {
769 it = mIntermediateBuffers.find(outSz);
770 if (it == mIntermediateBuffers.end()) {
771 ALOGE("%s: failed to find intermediate buffer size %dx%d",
772 __FUNCTION__, outSz.width, outSz.height);
773 return -1;
774 }
775 scaledYu12Buf = it->second;
776 }
777 // Scale
778 YCbCrLayout outLayout;
779 ret = scaledYu12Buf->getLayout(&outLayout);
780 if (ret != 0) {
781 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
782 return ret;
783 }
784
785 ret = libyuv::I420Scale(
786 static_cast<uint8_t*>(croppedLayout.y),
787 croppedLayout.yStride,
788 static_cast<uint8_t*>(croppedLayout.cb),
789 croppedLayout.cStride,
790 static_cast<uint8_t*>(croppedLayout.cr),
791 croppedLayout.cStride,
792 inputCrop.width,
793 inputCrop.height,
794 static_cast<uint8_t*>(outLayout.y),
795 outLayout.yStride,
796 static_cast<uint8_t*>(outLayout.cb),
797 outLayout.cStride,
798 static_cast<uint8_t*>(outLayout.cr),
799 outLayout.cStride,
800 outSz.width,
801 outSz.height,
802 // TODO: b/72261744 see if we can use better filter without losing too much perf
803 libyuv::FilterMode::kFilterNone);
804
805 if (ret != 0) {
806 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
807 __FUNCTION__, inputCrop.width, inputCrop.height,
808 outSz.width, outSz.height, ret);
809 return ret;
810 }
811
812 *out = outLayout;
813 mScaledYu12Frames.insert({outSz, scaledYu12Buf});
814 return 0;
815}
816
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800817
818int ExternalCameraDeviceSession::OutputThread::cropAndScaleThumbLocked(
819 sp<AllocatedFrame>& in, const Size &outSz, YCbCrLayout* out) {
820 Size inSz {in->mWidth, in->mHeight};
821
822 if ((outSz.width * outSz.height) >
823 (mYu12ThumbFrame->mWidth * mYu12ThumbFrame->mHeight)) {
824 ALOGE("%s: Requested thumbnail size too big (%d,%d) > (%d,%d)",
825 __FUNCTION__, outSz.width, outSz.height,
826 mYu12ThumbFrame->mWidth, mYu12ThumbFrame->mHeight);
827 return -1;
828 }
829
830 int ret;
831
832 /* This will crop-and-zoom the input YUV frame to the thumbnail size
833 * Based on the following logic:
834 * 1) Square pixels come in, square pixels come out, therefore single
835 * scale factor is computed to either make input bigger or smaller
836 * depending on if we are upscaling or downscaling
837 * 2) That single scale factor would either make height too tall or width
838 * too wide so we need to crop the input either horizontally or vertically
839 * but not both
840 */
841
842 /* Convert the input and output dimensions into floats for ease of math */
843 float fWin = static_cast<float>(inSz.width);
844 float fHin = static_cast<float>(inSz.height);
845 float fWout = static_cast<float>(outSz.width);
846 float fHout = static_cast<float>(outSz.height);
847
848 /* Compute the one scale factor from (1) above, it will be the smaller of
849 * the two possibilities. */
850 float scaleFactor = std::min( fHin / fHout, fWin / fWout );
851
852 /* Since we are crop-and-zooming (as opposed to letter/pillar boxing) we can
853 * simply multiply the output by our scaleFactor to get the cropped input
854 * size. Note that at least one of {fWcrop, fHcrop} is going to wind up
855 * being {fWin, fHin} respectively because fHout or fWout cancels out the
856 * scaleFactor calculation above.
857 *
858 * Specifically:
859 * if ( fHin / fHout ) < ( fWin / fWout ) we crop the sides off
860 * input, in which case
861 * scaleFactor = fHin / fHout
862 * fWcrop = fHin / fHout * fWout
863 * fHcrop = fHin
864 *
865 * Note that fWcrop <= fWin ( because ( fHin / fHout ) * fWout < fWin, which
866 * is just the inequality above with both sides multiplied by fWout
867 *
868 * on the other hand if ( fWin / fWout ) < ( fHin / fHout) we crop the top
869 * and the bottom off of input, and
870 * scaleFactor = fWin / fWout
871 * fWcrop = fWin
872 * fHCrop = fWin / fWout * fHout
873 */
874 float fWcrop = scaleFactor * fWout;
875 float fHcrop = scaleFactor * fHout;
876
877 /* Convert to integer and truncate to an even number */
878 Size cropSz = { 2*static_cast<uint32_t>(fWcrop/2.0f),
879 2*static_cast<uint32_t>(fHcrop/2.0f) };
880
881 /* Convert to a centered rectange with even top/left */
882 IMapper::Rect inputCrop {
883 2*static_cast<int32_t>((inSz.width - cropSz.width)/4),
884 2*static_cast<int32_t>((inSz.height - cropSz.height)/4),
885 static_cast<int32_t>(cropSz.width),
886 static_cast<int32_t>(cropSz.height) };
887
888 if ((inputCrop.top < 0) ||
889 (inputCrop.top >= static_cast<int32_t>(inSz.height)) ||
890 (inputCrop.left < 0) ||
891 (inputCrop.left >= static_cast<int32_t>(inSz.width)) ||
892 (inputCrop.width <= 0) ||
893 (inputCrop.width + inputCrop.left > static_cast<int32_t>(inSz.width)) ||
894 (inputCrop.height <= 0) ||
895 (inputCrop.height + inputCrop.top > static_cast<int32_t>(inSz.height)))
896 {
897 ALOGE("%s: came up with really wrong crop rectangle",__FUNCTION__);
898 ALOGE("%s: input layout %dx%d to for output size %dx%d",
899 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
900 ALOGE("%s: computed input crop +%d,+%d %dx%d",
901 __FUNCTION__, inputCrop.left, inputCrop.top,
902 inputCrop.width, inputCrop.height);
903 return -1;
904 }
905
906 YCbCrLayout inputLayout;
907 ret = in->getCroppedLayout(inputCrop, &inputLayout);
908 if (ret != 0) {
909 ALOGE("%s: failed to crop input layout %dx%d to for output size %dx%d",
910 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
911 ALOGE("%s: computed input crop +%d,+%d %dx%d",
912 __FUNCTION__, inputCrop.left, inputCrop.top,
913 inputCrop.width, inputCrop.height);
914 return ret;
915 }
916 ALOGV("%s: crop input layout %dx%d to for output size %dx%d",
917 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
918 ALOGV("%s: computed input crop +%d,+%d %dx%d",
919 __FUNCTION__, inputCrop.left, inputCrop.top,
920 inputCrop.width, inputCrop.height);
921
922
923 // Scale
924 YCbCrLayout outFullLayout;
925
926 ret = mYu12ThumbFrame->getLayout(&outFullLayout);
927 if (ret != 0) {
928 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
929 return ret;
930 }
931
932
933 ret = libyuv::I420Scale(
934 static_cast<uint8_t*>(inputLayout.y),
935 inputLayout.yStride,
936 static_cast<uint8_t*>(inputLayout.cb),
937 inputLayout.cStride,
938 static_cast<uint8_t*>(inputLayout.cr),
939 inputLayout.cStride,
940 inputCrop.width,
941 inputCrop.height,
942 static_cast<uint8_t*>(outFullLayout.y),
943 outFullLayout.yStride,
944 static_cast<uint8_t*>(outFullLayout.cb),
945 outFullLayout.cStride,
946 static_cast<uint8_t*>(outFullLayout.cr),
947 outFullLayout.cStride,
948 outSz.width,
949 outSz.height,
950 libyuv::FilterMode::kFilterNone);
951
952 if (ret != 0) {
953 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
954 __FUNCTION__, inputCrop.width, inputCrop.height,
955 outSz.width, outSz.height, ret);
956 return ret;
957 }
958
959 *out = outFullLayout;
960 return 0;
961}
962
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700963int ExternalCameraDeviceSession::OutputThread::formatConvertLocked(
964 const YCbCrLayout& in, const YCbCrLayout& out, Size sz, uint32_t format) {
965 int ret = 0;
966 switch (format) {
967 case V4L2_PIX_FMT_NV21:
968 ret = libyuv::I420ToNV21(
969 static_cast<uint8_t*>(in.y),
970 in.yStride,
971 static_cast<uint8_t*>(in.cb),
972 in.cStride,
973 static_cast<uint8_t*>(in.cr),
974 in.cStride,
975 static_cast<uint8_t*>(out.y),
976 out.yStride,
977 static_cast<uint8_t*>(out.cr),
978 out.cStride,
979 sz.width,
980 sz.height);
981 if (ret != 0) {
982 ALOGE("%s: convert to NV21 buffer failed! ret %d",
983 __FUNCTION__, ret);
984 return ret;
985 }
986 break;
987 case V4L2_PIX_FMT_NV12:
988 ret = libyuv::I420ToNV12(
989 static_cast<uint8_t*>(in.y),
990 in.yStride,
991 static_cast<uint8_t*>(in.cb),
992 in.cStride,
993 static_cast<uint8_t*>(in.cr),
994 in.cStride,
995 static_cast<uint8_t*>(out.y),
996 out.yStride,
997 static_cast<uint8_t*>(out.cb),
998 out.cStride,
999 sz.width,
1000 sz.height);
1001 if (ret != 0) {
1002 ALOGE("%s: convert to NV12 buffer failed! ret %d",
1003 __FUNCTION__, ret);
1004 return ret;
1005 }
1006 break;
1007 case V4L2_PIX_FMT_YVU420: // YV12
1008 case V4L2_PIX_FMT_YUV420: // YU12
1009 // TODO: maybe we can speed up here by somehow save this copy?
1010 ret = libyuv::I420Copy(
1011 static_cast<uint8_t*>(in.y),
1012 in.yStride,
1013 static_cast<uint8_t*>(in.cb),
1014 in.cStride,
1015 static_cast<uint8_t*>(in.cr),
1016 in.cStride,
1017 static_cast<uint8_t*>(out.y),
1018 out.yStride,
1019 static_cast<uint8_t*>(out.cb),
1020 out.cStride,
1021 static_cast<uint8_t*>(out.cr),
1022 out.cStride,
1023 sz.width,
1024 sz.height);
1025 if (ret != 0) {
1026 ALOGE("%s: copy to YV12 or YU12 buffer failed! ret %d",
1027 __FUNCTION__, ret);
1028 return ret;
1029 }
1030 break;
1031 case FLEX_YUV_GENERIC:
1032 // TODO: b/72261744 write to arbitrary flexible YUV layout. Slow.
1033 ALOGE("%s: unsupported flexible yuv layout"
1034 " y %p cb %p cr %p y_str %d c_str %d c_step %d",
1035 __FUNCTION__, out.y, out.cb, out.cr,
1036 out.yStride, out.cStride, out.chromaStep);
1037 return -1;
1038 default:
1039 ALOGE("%s: unknown YUV format 0x%x!", __FUNCTION__, format);
1040 return -1;
1041 }
1042 return 0;
1043}
1044
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001045int ExternalCameraDeviceSession::OutputThread::encodeJpegYU12(
1046 const Size & inSz, const YCbCrLayout& inLayout,
1047 int jpegQuality, const void *app1Buffer, size_t app1Size,
1048 void *out, const size_t maxOutSize, size_t &actualCodeSize)
1049{
1050 /* libjpeg is a C library so we use C-style "inheritance" by
1051 * putting libjpeg's jpeg_destination_mgr first in our custom
1052 * struct. This allows us to cast jpeg_destination_mgr* to
1053 * CustomJpegDestMgr* when we get it passed to us in a callback */
1054 struct CustomJpegDestMgr {
1055 struct jpeg_destination_mgr mgr;
1056 JOCTET *mBuffer;
1057 size_t mBufferSize;
1058 size_t mEncodedSize;
1059 bool mSuccess;
1060 } dmgr;
1061
1062 jpeg_compress_struct cinfo = {};
1063 jpeg_error_mgr jerr;
1064
1065 /* Initialize error handling with standard callbacks, but
1066 * then override output_message (to print to ALOG) and
1067 * error_exit to set a flag and print a message instead
1068 * of killing the whole process */
1069 cinfo.err = jpeg_std_error(&jerr);
1070
1071 cinfo.err->output_message = [](j_common_ptr cinfo) {
1072 char buffer[JMSG_LENGTH_MAX];
1073
1074 /* Create the message */
1075 (*cinfo->err->format_message)(cinfo, buffer);
1076 ALOGE("libjpeg error: %s", buffer);
1077 };
1078 cinfo.err->error_exit = [](j_common_ptr cinfo) {
1079 (*cinfo->err->output_message)(cinfo);
1080 if(cinfo->client_data) {
1081 auto & dmgr =
1082 *reinterpret_cast<CustomJpegDestMgr*>(cinfo->client_data);
1083 dmgr.mSuccess = false;
1084 }
1085 };
1086 /* Now that we initialized some callbacks, let's create our compressor */
1087 jpeg_create_compress(&cinfo);
1088
1089 /* Initialize our destination manager */
1090 dmgr.mBuffer = static_cast<JOCTET*>(out);
1091 dmgr.mBufferSize = maxOutSize;
1092 dmgr.mEncodedSize = 0;
1093 dmgr.mSuccess = true;
1094 cinfo.client_data = static_cast<void*>(&dmgr);
1095
1096 /* These lambdas become C-style function pointers and as per C++11 spec
1097 * may not capture anything */
1098 dmgr.mgr.init_destination = [](j_compress_ptr cinfo) {
1099 auto & dmgr = reinterpret_cast<CustomJpegDestMgr&>(*cinfo->dest);
1100 dmgr.mgr.next_output_byte = dmgr.mBuffer;
1101 dmgr.mgr.free_in_buffer = dmgr.mBufferSize;
1102 ALOGV("%s:%d jpeg start: %p [%zu]",
1103 __FUNCTION__, __LINE__, dmgr.mBuffer, dmgr.mBufferSize);
1104 };
1105
1106 dmgr.mgr.empty_output_buffer = [](j_compress_ptr cinfo __unused) {
1107 ALOGV("%s:%d Out of buffer", __FUNCTION__, __LINE__);
1108 return 0;
1109 };
1110
1111 dmgr.mgr.term_destination = [](j_compress_ptr cinfo) {
1112 auto & dmgr = reinterpret_cast<CustomJpegDestMgr&>(*cinfo->dest);
1113 dmgr.mEncodedSize = dmgr.mBufferSize - dmgr.mgr.free_in_buffer;
1114 ALOGV("%s:%d Done with jpeg: %zu", __FUNCTION__, __LINE__, dmgr.mEncodedSize);
1115 };
1116 cinfo.dest = reinterpret_cast<struct jpeg_destination_mgr*>(&dmgr);
1117
1118 /* We are going to be using JPEG in raw data mode, so we are passing
1119 * straight subsampled planar YCbCr and it will not touch our pixel
1120 * data or do any scaling or anything */
1121 cinfo.image_width = inSz.width;
1122 cinfo.image_height = inSz.height;
1123 cinfo.input_components = 3;
1124 cinfo.in_color_space = JCS_YCbCr;
1125
1126 /* Initialize defaults and then override what we want */
1127 jpeg_set_defaults(&cinfo);
1128
1129 jpeg_set_quality(&cinfo, jpegQuality, 1);
1130 jpeg_set_colorspace(&cinfo, JCS_YCbCr);
1131 cinfo.raw_data_in = 1;
1132 cinfo.dct_method = JDCT_IFAST;
1133
1134 /* Configure sampling factors. The sampling factor is JPEG subsampling 420
1135 * because the source format is YUV420. Note that libjpeg sampling factors
1136 * are... a little weird. Sampling of Y=2,U=1,V=1 means there is 1 U and
1137 * 1 V value for each 2 Y values */
1138 cinfo.comp_info[0].h_samp_factor = 2;
1139 cinfo.comp_info[0].v_samp_factor = 2;
1140 cinfo.comp_info[1].h_samp_factor = 1;
1141 cinfo.comp_info[1].v_samp_factor = 1;
1142 cinfo.comp_info[2].h_samp_factor = 1;
1143 cinfo.comp_info[2].v_samp_factor = 1;
1144
1145 /* Let's not hardcode YUV420 in 6 places... 5 was enough */
1146 int maxVSampFactor = std::max( {
1147 cinfo.comp_info[0].v_samp_factor,
1148 cinfo.comp_info[1].v_samp_factor,
1149 cinfo.comp_info[2].v_samp_factor
1150 });
1151 int cVSubSampling = cinfo.comp_info[0].v_samp_factor /
1152 cinfo.comp_info[1].v_samp_factor;
1153
1154 /* Start the compressor */
1155 jpeg_start_compress(&cinfo, TRUE);
1156
1157 /* Compute our macroblock height, so we can pad our input to be vertically
1158 * macroblock aligned.
1159 * TODO: Does it need to be horizontally MCU aligned too? */
1160
1161 size_t mcuV = DCTSIZE*maxVSampFactor;
1162 size_t paddedHeight = mcuV * ((inSz.height + mcuV - 1) / mcuV);
1163
1164 /* libjpeg uses arrays of row pointers, which makes it really easy to pad
1165 * data vertically (unfortunately doesn't help horizontally) */
1166 std::vector<JSAMPROW> yLines (paddedHeight);
1167 std::vector<JSAMPROW> cbLines(paddedHeight/cVSubSampling);
1168 std::vector<JSAMPROW> crLines(paddedHeight/cVSubSampling);
1169
1170 uint8_t *py = static_cast<uint8_t*>(inLayout.y);
1171 uint8_t *pcr = static_cast<uint8_t*>(inLayout.cr);
1172 uint8_t *pcb = static_cast<uint8_t*>(inLayout.cb);
1173
1174 for(uint32_t i = 0; i < paddedHeight; i++)
1175 {
1176 /* Once we are in the padding territory we still point to the last line
1177 * effectively replicating it several times ~ CLAMP_TO_EDGE */
1178 int li = std::min(i, inSz.height - 1);
1179 yLines[i] = static_cast<JSAMPROW>(py + li * inLayout.yStride);
1180 if(i < paddedHeight / cVSubSampling)
1181 {
1182 crLines[i] = static_cast<JSAMPROW>(pcr + li * inLayout.cStride);
1183 cbLines[i] = static_cast<JSAMPROW>(pcb + li * inLayout.cStride);
1184 }
1185 }
1186
1187 /* If APP1 data was passed in, use it */
1188 if(app1Buffer && app1Size)
1189 {
1190 jpeg_write_marker(&cinfo, JPEG_APP0 + 1,
1191 static_cast<const JOCTET*>(app1Buffer), app1Size);
1192 }
1193
1194 /* While we still have padded height left to go, keep giving it one
1195 * macroblock at a time. */
1196 while (cinfo.next_scanline < cinfo.image_height) {
1197 const uint32_t batchSize = DCTSIZE * maxVSampFactor;
1198 const uint32_t nl = cinfo.next_scanline;
1199 JSAMPARRAY planes[3]{ &yLines[nl],
1200 &cbLines[nl/cVSubSampling],
1201 &crLines[nl/cVSubSampling] };
1202
1203 uint32_t done = jpeg_write_raw_data(&cinfo, planes, batchSize);
1204
1205 if (done != batchSize) {
1206 ALOGE("%s: compressed %u lines, expected %u (total %u/%u)",
1207 __FUNCTION__, done, batchSize, cinfo.next_scanline,
1208 cinfo.image_height);
1209 return -1;
1210 }
1211 }
1212
1213 /* This will flush everything */
1214 jpeg_finish_compress(&cinfo);
1215
1216 /* Grab the actual code size and set it */
1217 actualCodeSize = dmgr.mEncodedSize;
1218
1219 return 0;
1220}
1221
1222/*
1223 * TODO: There needs to be a mechanism to discover allocated buffer size
1224 * in the HAL.
1225 *
1226 * This is very fragile because it is duplicated computation from:
1227 * frameworks/av/services/camera/libcameraservice/device3/Camera3Device.cpp
1228 *
1229 */
1230
1231/* This assumes mSupportedFormats have all been declared as supporting
1232 * HAL_PIXEL_FORMAT_BLOB to the framework */
1233Size ExternalCameraDeviceSession::getMaxJpegResolution() const {
1234 Size ret { 0, 0 };
1235 for(auto & fmt : mSupportedFormats) {
1236 if(fmt.width * fmt.height > ret.width * ret.height) {
1237 ret = Size { fmt.width, fmt.height };
1238 }
1239 }
1240 return ret;
1241}
1242
1243Size ExternalCameraDeviceSession::getMaxThumbResolution() const {
1244 Size thumbSize { 0, 0 };
1245 camera_metadata_ro_entry entry =
1246 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
1247 for(uint32_t i = 0; i < entry.count; i += 2) {
1248 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
1249 static_cast<uint32_t>(entry.data.i32[i+1]) };
1250 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
1251 thumbSize = sz;
1252 }
1253 }
1254
1255 if (thumbSize.width * thumbSize.height == 0) {
1256 ALOGW("%s: non-zero thumbnail size not available", __FUNCTION__);
1257 }
1258
1259 return thumbSize;
1260}
1261
1262
1263ssize_t ExternalCameraDeviceSession::getJpegBufferSize(
1264 uint32_t width, uint32_t height) const {
1265 // Constant from camera3.h
1266 const ssize_t kMinJpegBufferSize = 256 * 1024 + sizeof(CameraBlob);
1267 // Get max jpeg size (area-wise).
1268 if (mMaxJpegResolution.width == 0) {
1269 ALOGE("%s: Do not have a single supported JPEG stream",
1270 __FUNCTION__);
1271 return BAD_VALUE;
1272 }
1273
1274 // Get max jpeg buffer size
1275 ssize_t maxJpegBufferSize = 0;
1276 camera_metadata_ro_entry jpegBufMaxSize =
1277 mCameraCharacteristics.find(ANDROID_JPEG_MAX_SIZE);
1278 if (jpegBufMaxSize.count == 0) {
1279 ALOGE("%s: Can't find maximum JPEG size in static metadata!",
1280 __FUNCTION__);
1281 return BAD_VALUE;
1282 }
1283 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
1284
1285 if (maxJpegBufferSize <= kMinJpegBufferSize) {
1286 ALOGE("%s: ANDROID_JPEG_MAX_SIZE (%zd) <= kMinJpegBufferSize (%zd)",
1287 __FUNCTION__, maxJpegBufferSize, kMinJpegBufferSize);
1288 return BAD_VALUE;
1289 }
1290
1291 // Calculate final jpeg buffer size for the given resolution.
1292 float scaleFactor = ((float) (width * height)) /
1293 (mMaxJpegResolution.width * mMaxJpegResolution.height);
1294 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
1295 kMinJpegBufferSize;
1296 if (jpegBufferSize > maxJpegBufferSize) {
1297 jpegBufferSize = maxJpegBufferSize;
1298 }
1299
1300 return jpegBufferSize;
1301}
1302
1303int ExternalCameraDeviceSession::OutputThread::createJpegLocked(
1304 HalStreamBuffer &halBuf,
1305 HalRequest &req)
1306{
1307 int ret;
1308 auto lfail = [&](auto... args) {
1309 ALOGE(args...);
1310
1311 return 1;
1312 };
1313 auto parent = mParent.promote();
1314 if (parent == nullptr) {
1315 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1316 return 1;
1317 }
1318
1319 ALOGV("%s: HAL buffer sid: %d bid: %" PRIu64 " w: %u h: %u",
1320 __FUNCTION__, halBuf.streamId, static_cast<uint64_t>(halBuf.bufferId),
1321 halBuf.width, halBuf.height);
1322 ALOGV("%s: HAL buffer fmt: %x usage: %" PRIx64 " ptr: %p",
1323 __FUNCTION__, halBuf.format, static_cast<uint64_t>(halBuf.usage),
1324 halBuf.bufPtr);
1325 ALOGV("%s: YV12 buffer %d x %d",
1326 __FUNCTION__,
1327 mYu12Frame->mWidth, mYu12Frame->mHeight);
1328
1329 int jpegQuality, thumbQuality;
1330 Size thumbSize;
1331
1332 if (req.setting.exists(ANDROID_JPEG_QUALITY)) {
1333 camera_metadata_entry entry =
1334 req.setting.find(ANDROID_JPEG_QUALITY);
1335 jpegQuality = entry.data.u8[0];
1336 } else {
1337 return lfail("%s: ANDROID_JPEG_QUALITY not set",__FUNCTION__);
1338 }
1339
1340 if (req.setting.exists(ANDROID_JPEG_THUMBNAIL_QUALITY)) {
1341 camera_metadata_entry entry =
1342 req.setting.find(ANDROID_JPEG_THUMBNAIL_QUALITY);
1343 thumbQuality = entry.data.u8[0];
1344 } else {
1345 return lfail(
1346 "%s: ANDROID_JPEG_THUMBNAIL_QUALITY not set",
1347 __FUNCTION__);
1348 }
1349
1350 if (req.setting.exists(ANDROID_JPEG_THUMBNAIL_SIZE)) {
1351 camera_metadata_entry entry =
1352 req.setting.find(ANDROID_JPEG_THUMBNAIL_SIZE);
1353 thumbSize = Size { static_cast<uint32_t>(entry.data.i32[0]),
1354 static_cast<uint32_t>(entry.data.i32[1])
1355 };
1356 } else {
1357 return lfail(
1358 "%s: ANDROID_JPEG_THUMBNAIL_SIZE not set", __FUNCTION__);
1359 }
1360
1361 /* Cropped and scaled YU12 buffer for main and thumbnail */
1362 YCbCrLayout yu12Main;
1363 Size jpegSize { halBuf.width, halBuf.height };
1364
1365 /* Compute temporary buffer sizes accounting for the following:
1366 * thumbnail can't exceed APP1 size of 64K
1367 * main image needs to hold APP1, headers, and at most a poorly
1368 * compressed image */
1369 const ssize_t maxThumbCodeSize = 64 * 1024;
1370 const ssize_t maxJpegCodeSize = parent->getJpegBufferSize(jpegSize.width,
1371 jpegSize.height);
1372
1373 /* Check that getJpegBufferSize did not return an error */
1374 if (maxJpegCodeSize < 0) {
1375 return lfail(
1376 "%s: getJpegBufferSize returned %zd",__FUNCTION__,maxJpegCodeSize);
1377 }
1378
1379
1380 /* Hold actual thumbnail and main image code sizes */
1381 size_t thumbCodeSize = 0, jpegCodeSize = 0;
1382 /* Temporary thumbnail code buffer */
1383 std::vector<uint8_t> thumbCode(maxThumbCodeSize);
1384
1385 YCbCrLayout yu12Thumb;
1386 ret = cropAndScaleThumbLocked(mYu12Frame, thumbSize, &yu12Thumb);
1387
1388 if (ret != 0) {
1389 return lfail(
1390 "%s: crop and scale thumbnail failed!", __FUNCTION__);
1391 }
1392
1393 /* Scale and crop main jpeg */
1394 ret = cropAndScaleLocked(mYu12Frame, jpegSize, &yu12Main);
1395
1396 if (ret != 0) {
1397 return lfail("%s: crop and scale main failed!", __FUNCTION__);
1398 }
1399
1400 /* Encode the thumbnail image */
1401 ret = encodeJpegYU12(thumbSize, yu12Thumb,
1402 thumbQuality, 0, 0,
1403 &thumbCode[0], maxThumbCodeSize, thumbCodeSize);
1404
1405 if (ret != 0) {
1406 return lfail("%s: encodeJpegYU12 failed with %d",__FUNCTION__, ret);
1407 }
1408
1409 /* Combine camera characteristics with request settings to form EXIF
1410 * metadata */
1411 common::V1_0::helper::CameraMetadata meta(parent->mCameraCharacteristics);
1412 meta.append(req.setting);
1413
1414 /* Generate EXIF object */
1415 std::unique_ptr<ExifUtils> utils(ExifUtils::create());
1416 /* Make sure it's initialized */
1417 utils->initialize();
1418
1419 utils->setFromMetadata(meta, jpegSize.width, jpegSize.height);
1420
1421 /* Check if we made a non-zero-sized thumbnail. Currently not possible
1422 * that we got this far and the code is size 0, but if this code moves
1423 * around it might become relevant again */
1424
1425 ret = utils->generateApp1(thumbCodeSize ? &thumbCode[0] : 0, thumbCodeSize);
1426
1427 if (!ret) {
1428 return lfail("%s: generating APP1 failed", __FUNCTION__);
1429 }
1430
1431 /* Get internal buffer */
1432 size_t exifDataSize = utils->getApp1Length();
1433 const uint8_t* exifData = utils->getApp1Buffer();
1434
1435 /* Lock the HAL jpeg code buffer */
1436 void *bufPtr = sHandleImporter.lock(
1437 *(halBuf.bufPtr), halBuf.usage, maxJpegCodeSize);
1438
1439 if (!bufPtr) {
1440 return lfail("%s: could not lock %zu bytes", __FUNCTION__, maxJpegCodeSize);
1441 }
1442
1443 /* Encode the main jpeg image */
1444 ret = encodeJpegYU12(jpegSize, yu12Main,
1445 jpegQuality, exifData, exifDataSize,
1446 bufPtr, maxJpegCodeSize, jpegCodeSize);
1447
1448 /* TODO: Not sure this belongs here, maybe better to pass jpegCodeSize out
1449 * and do this when returning buffer to parent */
1450 CameraBlob blob { CameraBlobId::JPEG, static_cast<uint32_t>(jpegCodeSize) };
1451 void *blobDst =
1452 reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(bufPtr) +
1453 maxJpegCodeSize -
1454 sizeof(CameraBlob));
1455 memcpy(blobDst, &blob, sizeof(CameraBlob));
1456
1457 /* Unlock the HAL jpeg code buffer */
1458 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
1459 if (relFence > 0) {
1460 halBuf.acquireFence = relFence;
1461 }
1462
1463 /* Check if our JPEG actually succeeded */
1464 if (ret != 0) {
1465 return lfail(
1466 "%s: encodeJpegYU12 failed with %d",__FUNCTION__, ret);
1467 }
1468
1469 ALOGV("%s: encoded JPEG (ret:%d) with Q:%d max size: %zu",
1470 __FUNCTION__, ret, jpegQuality, maxJpegCodeSize);
1471
1472 return 0;
1473}
1474
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001475bool ExternalCameraDeviceSession::OutputThread::threadLoop() {
1476 HalRequest req;
1477 auto parent = mParent.promote();
1478 if (parent == nullptr) {
1479 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1480 return false;
1481 }
1482
1483 // TODO: maybe we need to setup a sensor thread to dq/enq v4l frames
1484 // regularly to prevent v4l buffer queue filled with stale buffers
1485 // when app doesn't program a preveiw request
1486 waitForNextRequest(&req);
1487 if (req.frameIn == nullptr) {
1488 // No new request, wait again
1489 return true;
1490 }
1491
1492 if (req.frameIn->mFourcc != V4L2_PIX_FMT_MJPEG) {
1493 ALOGE("%s: do not support V4L2 format %c%c%c%c", __FUNCTION__,
1494 req.frameIn->mFourcc & 0xFF,
1495 (req.frameIn->mFourcc >> 8) & 0xFF,
1496 (req.frameIn->mFourcc >> 16) & 0xFF,
1497 (req.frameIn->mFourcc >> 24) & 0xFF);
1498 parent->notifyError(
1499 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1500 return false;
1501 }
1502
1503 std::unique_lock<std::mutex> lk(mLock);
1504
1505 // Convert input V4L2 frame to YU12 of the same size
1506 // TODO: see if we can save some computation by converting to YV12 here
1507 uint8_t* inData;
1508 size_t inDataSize;
1509 req.frameIn->map(&inData, &inDataSize);
1510 // TODO: profile
1511 // TODO: in some special case maybe we can decode jpg directly to gralloc output?
1512 int res = libyuv::MJPGToI420(
1513 inData, inDataSize,
1514 static_cast<uint8_t*>(mYu12FrameLayout.y),
1515 mYu12FrameLayout.yStride,
1516 static_cast<uint8_t*>(mYu12FrameLayout.cb),
1517 mYu12FrameLayout.cStride,
1518 static_cast<uint8_t*>(mYu12FrameLayout.cr),
1519 mYu12FrameLayout.cStride,
1520 mYu12Frame->mWidth, mYu12Frame->mHeight,
1521 mYu12Frame->mWidth, mYu12Frame->mHeight);
1522
1523 if (res != 0) {
1524 // For some webcam, the first few V4L2 frames might be malformed...
1525 ALOGE("%s: Convert V4L2 frame to YU12 failed! res %d", __FUNCTION__, res);
1526 lk.unlock();
1527 Status st = parent->processCaptureRequestError(req);
1528 if (st != Status::OK) {
1529 ALOGE("%s: failed to process capture request error!", __FUNCTION__);
1530 parent->notifyError(
1531 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1532 return false;
1533 }
1534 return true;
1535 }
1536
1537 ALOGV("%s processing new request", __FUNCTION__);
1538 const int kSyncWaitTimeoutMs = 500;
1539 for (auto& halBuf : req.buffers) {
1540 if (halBuf.acquireFence != -1) {
1541 int ret = sync_wait(halBuf.acquireFence, kSyncWaitTimeoutMs);
1542 if (ret) {
1543 halBuf.fenceTimeout = true;
1544 } else {
1545 ::close(halBuf.acquireFence);
1546 }
1547 }
1548
1549 if (halBuf.fenceTimeout) {
1550 continue;
1551 }
1552
1553 // Gralloc lockYCbCr the buffer
1554 switch (halBuf.format) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001555 case PixelFormat::BLOB: {
1556 int ret = createJpegLocked(halBuf, req);
1557
1558 if(ret != 0) {
1559 ALOGE("%s: createJpegLocked failed with %d",
1560 __FUNCTION__, ret);
1561 lk.unlock();
1562 parent->notifyError(
1563 /*frameNum*/req.frameNumber,
1564 /*stream*/-1,
1565 ErrorCode::ERROR_DEVICE);
1566
1567 return false;
1568 }
1569 } break;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001570 case PixelFormat::YCBCR_420_888:
1571 case PixelFormat::YV12: {
1572 IMapper::Rect outRect {0, 0,
1573 static_cast<int32_t>(halBuf.width),
1574 static_cast<int32_t>(halBuf.height)};
1575 YCbCrLayout outLayout = sHandleImporter.lockYCbCr(
1576 *(halBuf.bufPtr), halBuf.usage, outRect);
1577 ALOGV("%s: outLayout y %p cb %p cr %p y_str %d c_str %d c_step %d",
1578 __FUNCTION__, outLayout.y, outLayout.cb, outLayout.cr,
1579 outLayout.yStride, outLayout.cStride, outLayout.chromaStep);
1580
1581 // Convert to output buffer size/format
1582 uint32_t outputFourcc = getFourCcFromLayout(outLayout);
1583 ALOGV("%s: converting to format %c%c%c%c", __FUNCTION__,
1584 outputFourcc & 0xFF,
1585 (outputFourcc >> 8) & 0xFF,
1586 (outputFourcc >> 16) & 0xFF,
1587 (outputFourcc >> 24) & 0xFF);
1588
1589 YCbCrLayout cropAndScaled;
1590 int ret = cropAndScaleLocked(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001591 mYu12Frame,
1592 Size { halBuf.width, halBuf.height },
1593 &cropAndScaled);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001594 if (ret != 0) {
1595 ALOGE("%s: crop and scale failed!", __FUNCTION__);
1596 lk.unlock();
1597 parent->notifyError(
1598 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1599 return false;
1600 }
1601
1602 Size sz {halBuf.width, halBuf.height};
1603 ret = formatConvertLocked(cropAndScaled, outLayout, sz, outputFourcc);
1604 if (ret != 0) {
1605 ALOGE("%s: format coversion failed!", __FUNCTION__);
1606 lk.unlock();
1607 parent->notifyError(
1608 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1609 return false;
1610 }
1611 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
1612 if (relFence > 0) {
1613 halBuf.acquireFence = relFence;
1614 }
1615 } break;
1616 default:
1617 ALOGE("%s: unknown output format %x", __FUNCTION__, halBuf.format);
1618 lk.unlock();
1619 parent->notifyError(
1620 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1621 return false;
1622 }
1623 } // for each buffer
1624 mScaledYu12Frames.clear();
1625
1626 // Don't hold the lock while calling back to parent
1627 lk.unlock();
1628 Status st = parent->processCaptureResult(req);
1629 if (st != Status::OK) {
1630 ALOGE("%s: failed to process capture result!", __FUNCTION__);
1631 parent->notifyError(
1632 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1633 return false;
1634 }
1635 return true;
1636}
1637
1638Status ExternalCameraDeviceSession::OutputThread::allocateIntermediateBuffers(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001639 const Size& v4lSize, const Size& thumbSize,
1640 const hidl_vec<Stream>& streams) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001641 std::lock_guard<std::mutex> lk(mLock);
1642 if (mScaledYu12Frames.size() != 0) {
1643 ALOGE("%s: intermediate buffer pool has %zu inflight buffers! (expect 0)",
1644 __FUNCTION__, mScaledYu12Frames.size());
1645 return Status::INTERNAL_ERROR;
1646 }
1647
1648 // Allocating intermediate YU12 frame
1649 if (mYu12Frame == nullptr || mYu12Frame->mWidth != v4lSize.width ||
1650 mYu12Frame->mHeight != v4lSize.height) {
1651 mYu12Frame.clear();
1652 mYu12Frame = new AllocatedFrame(v4lSize.width, v4lSize.height);
1653 int ret = mYu12Frame->allocate(&mYu12FrameLayout);
1654 if (ret != 0) {
1655 ALOGE("%s: allocating YU12 frame failed!", __FUNCTION__);
1656 return Status::INTERNAL_ERROR;
1657 }
1658 }
1659
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001660 // Allocating intermediate YU12 thumbnail frame
1661 if (mYu12ThumbFrame == nullptr ||
1662 mYu12ThumbFrame->mWidth != thumbSize.width ||
1663 mYu12ThumbFrame->mHeight != thumbSize.height) {
1664 mYu12ThumbFrame.clear();
1665 mYu12ThumbFrame = new AllocatedFrame(thumbSize.width, thumbSize.height);
1666 int ret = mYu12ThumbFrame->allocate(&mYu12ThumbFrameLayout);
1667 if (ret != 0) {
1668 ALOGE("%s: allocating YU12 thumb frame failed!", __FUNCTION__);
1669 return Status::INTERNAL_ERROR;
1670 }
1671 }
1672
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001673 // Allocating scaled buffers
1674 for (const auto& stream : streams) {
1675 Size sz = {stream.width, stream.height};
1676 if (sz == v4lSize) {
1677 continue; // Don't need an intermediate buffer same size as v4lBuffer
1678 }
1679 if (mIntermediateBuffers.count(sz) == 0) {
1680 // Create new intermediate buffer
1681 sp<AllocatedFrame> buf = new AllocatedFrame(stream.width, stream.height);
1682 int ret = buf->allocate();
1683 if (ret != 0) {
1684 ALOGE("%s: allocating intermediate YU12 frame %dx%d failed!",
1685 __FUNCTION__, stream.width, stream.height);
1686 return Status::INTERNAL_ERROR;
1687 }
1688 mIntermediateBuffers[sz] = buf;
1689 }
1690 }
1691
1692 // Remove unconfigured buffers
1693 auto it = mIntermediateBuffers.begin();
1694 while (it != mIntermediateBuffers.end()) {
1695 bool configured = false;
1696 auto sz = it->first;
1697 for (const auto& stream : streams) {
1698 if (stream.width == sz.width && stream.height == sz.height) {
1699 configured = true;
1700 break;
1701 }
1702 }
1703 if (configured) {
1704 it++;
1705 } else {
1706 it = mIntermediateBuffers.erase(it);
1707 }
1708 }
1709 return Status::OK;
1710}
1711
1712Status ExternalCameraDeviceSession::OutputThread::submitRequest(const HalRequest& req) {
1713 std::lock_guard<std::mutex> lk(mLock);
1714 // TODO: reduce object copy in this path
1715 mRequestList.push_back(req);
1716 mRequestCond.notify_one();
1717 return Status::OK;
1718}
1719
1720void ExternalCameraDeviceSession::OutputThread::flush() {
1721 std::lock_guard<std::mutex> lk(mLock);
1722 // TODO: send buffer/request errors back to framework
1723 mRequestList.clear();
1724}
1725
1726void ExternalCameraDeviceSession::OutputThread::waitForNextRequest(HalRequest* out) {
1727 if (out == nullptr) {
1728 ALOGE("%s: out is null", __FUNCTION__);
1729 return;
1730 }
1731
1732 std::unique_lock<std::mutex> lk(mLock);
1733 while (mRequestList.empty()) {
1734 std::chrono::seconds timeout = std::chrono::seconds(kReqWaitTimeoutSec);
1735 auto st = mRequestCond.wait_for(lk, timeout);
1736 if (st == std::cv_status::timeout) {
1737 // no new request, return
1738 return;
1739 }
1740 }
1741 *out = mRequestList.front();
1742 mRequestList.pop_front();
1743}
1744
1745void ExternalCameraDeviceSession::cleanupBuffersLocked(int id) {
1746 for (auto& pair : mCirculatingBuffers.at(id)) {
1747 sHandleImporter.freeBuffer(pair.second);
1748 }
1749 mCirculatingBuffers[id].clear();
1750 mCirculatingBuffers.erase(id);
1751}
1752
1753void ExternalCameraDeviceSession::updateBufferCaches(const hidl_vec<BufferCache>& cachesToRemove) {
1754 Mutex::Autolock _l(mLock);
1755 for (auto& cache : cachesToRemove) {
1756 auto cbsIt = mCirculatingBuffers.find(cache.streamId);
1757 if (cbsIt == mCirculatingBuffers.end()) {
1758 // The stream could have been removed
1759 continue;
1760 }
1761 CirculatingBuffers& cbs = cbsIt->second;
1762 auto it = cbs.find(cache.bufferId);
1763 if (it != cbs.end()) {
1764 sHandleImporter.freeBuffer(it->second);
1765 cbs.erase(it);
1766 } else {
1767 ALOGE("%s: stream %d buffer %" PRIu64 " is not cached",
1768 __FUNCTION__, cache.streamId, cache.bufferId);
1769 }
1770 }
1771}
1772
1773bool ExternalCameraDeviceSession::isSupported(const Stream& stream) {
1774 int32_t ds = static_cast<int32_t>(stream.dataSpace);
1775 PixelFormat fmt = stream.format;
1776 uint32_t width = stream.width;
1777 uint32_t height = stream.height;
1778 // TODO: check usage flags
1779
1780 if (stream.streamType != StreamType::OUTPUT) {
1781 ALOGE("%s: does not support non-output stream type", __FUNCTION__);
1782 return false;
1783 }
1784
1785 if (stream.rotation != StreamRotation::ROTATION_0) {
1786 ALOGE("%s: does not support stream rotation", __FUNCTION__);
1787 return false;
1788 }
1789
1790 if (ds & Dataspace::DEPTH) {
1791 ALOGI("%s: does not support depth output", __FUNCTION__);
1792 return false;
1793 }
1794
1795 switch (fmt) {
1796 case PixelFormat::BLOB:
1797 if (ds != static_cast<int32_t>(Dataspace::V0_JFIF)) {
1798 ALOGI("%s: BLOB format does not support dataSpace %x", __FUNCTION__, ds);
1799 return false;
1800 }
1801 case PixelFormat::IMPLEMENTATION_DEFINED:
1802 case PixelFormat::YCBCR_420_888:
1803 case PixelFormat::YV12:
1804 // TODO: check what dataspace we can support here.
1805 // intentional no-ops.
1806 break;
1807 default:
1808 ALOGI("%s: does not support format %x", __FUNCTION__, fmt);
1809 return false;
1810 }
1811
1812 // Assume we can convert any V4L2 format to any of supported output format for now, i.e,
1813 // ignoring v4l2Fmt.fourcc for now. Might need more subtle check if we support more v4l format
1814 // in the futrue.
1815 for (const auto& v4l2Fmt : mSupportedFormats) {
1816 if (width == v4l2Fmt.width && height == v4l2Fmt.height) {
1817 return true;
1818 }
1819 }
1820 ALOGI("%s: resolution %dx%d is not supported", __FUNCTION__, width, height);
1821 return false;
1822}
1823
1824int ExternalCameraDeviceSession::v4l2StreamOffLocked() {
1825 if (!mV4l2Streaming) {
1826 return OK;
1827 }
1828
1829 {
1830 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1831 if (mNumDequeuedV4l2Buffers != 0) {
1832 ALOGE("%s: there are %zu inflight V4L buffers",
1833 __FUNCTION__, mNumDequeuedV4l2Buffers);
1834 return -1;
1835 }
1836 }
1837 mV4l2Buffers.clear(); // VIDIOC_REQBUFS will fail if FDs are not clear first
1838
1839 // VIDIOC_STREAMOFF
1840 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1841 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMOFF, &capture_type)) < 0) {
1842 ALOGE("%s: STREAMOFF failed: %s", __FUNCTION__, strerror(errno));
1843 return -errno;
1844 }
1845
1846 // VIDIOC_REQBUFS: clear buffers
1847 v4l2_requestbuffers req_buffers{};
1848 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1849 req_buffers.memory = V4L2_MEMORY_MMAP;
1850 req_buffers.count = 0;
1851 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
1852 ALOGE("%s: REQBUFS failed: %s", __FUNCTION__, strerror(errno));
1853 return -errno;
1854 }
1855
1856 mV4l2Streaming = false;
1857 return OK;
1858}
1859
1860int ExternalCameraDeviceSession::configureV4l2StreamLocked(const SupportedV4L2Format& v4l2Fmt) {
1861 int ret = v4l2StreamOffLocked();
1862 if (ret != OK) {
1863 ALOGE("%s: stop v4l2 streaming failed: ret %d", __FUNCTION__, ret);
1864 return ret;
1865 }
1866
1867 // VIDIOC_S_FMT w/h/fmt
1868 v4l2_format fmt;
1869 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1870 fmt.fmt.pix.width = v4l2Fmt.width;
1871 fmt.fmt.pix.height = v4l2Fmt.height;
1872 fmt.fmt.pix.pixelformat = v4l2Fmt.fourcc;
1873 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt));
1874 if (ret < 0) {
1875 ALOGE("%s: S_FMT ioctl failed: %s", __FUNCTION__, strerror(errno));
1876 return -errno;
1877 }
1878
1879 if (v4l2Fmt.width != fmt.fmt.pix.width || v4l2Fmt.height != fmt.fmt.pix.height ||
1880 v4l2Fmt.fourcc != fmt.fmt.pix.pixelformat) {
1881 ALOGE("%s: S_FMT expect %c%c%c%c %dx%d, got %c%c%c%c %dx%d instead!", __FUNCTION__,
1882 v4l2Fmt.fourcc & 0xFF,
1883 (v4l2Fmt.fourcc >> 8) & 0xFF,
1884 (v4l2Fmt.fourcc >> 16) & 0xFF,
1885 (v4l2Fmt.fourcc >> 24) & 0xFF,
1886 v4l2Fmt.width, v4l2Fmt.height,
1887 fmt.fmt.pix.pixelformat & 0xFF,
1888 (fmt.fmt.pix.pixelformat >> 8) & 0xFF,
1889 (fmt.fmt.pix.pixelformat >> 16) & 0xFF,
1890 (fmt.fmt.pix.pixelformat >> 24) & 0xFF,
1891 fmt.fmt.pix.width, fmt.fmt.pix.height);
1892 return -EINVAL;
1893 }
1894 uint32_t bufferSize = fmt.fmt.pix.sizeimage;
1895 ALOGI("%s: V4L2 buffer size is %d", __FUNCTION__, bufferSize);
1896
1897 float maxFps = -1.f;
1898 float fps = 1000.f;
1899 const float kDefaultFps = 30.f;
1900 // Try to pick the slowest fps that is at least 30
1901 for (const auto& f : v4l2Fmt.frameRates) {
1902 if (maxFps < f) {
1903 maxFps = f;
1904 }
1905 if (f >= kDefaultFps && f < fps) {
1906 fps = f;
1907 }
1908 }
1909 if (fps == 1000.f) {
1910 fps = maxFps;
1911 }
1912
1913 // VIDIOC_G_PARM/VIDIOC_S_PARM: set fps
1914 v4l2_streamparm streamparm = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
1915 // The following line checks that the driver knows about framerate get/set.
1916 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_G_PARM, &streamparm)) >= 0) {
1917 // Now check if the device is able to accept a capture framerate set.
1918 if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
1919 // |frame_rate| is float, approximate by a fraction.
1920 const int kFrameRatePrecision = 10000;
1921 streamparm.parm.capture.timeperframe.numerator = kFrameRatePrecision;
1922 streamparm.parm.capture.timeperframe.denominator =
1923 (fps * kFrameRatePrecision);
1924
1925 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_PARM, &streamparm)) < 0) {
1926 ALOGE("%s: failed to set framerate to %f", __FUNCTION__, fps);
1927 return UNKNOWN_ERROR;
1928 }
1929 }
1930 }
1931 float retFps = streamparm.parm.capture.timeperframe.denominator /
1932 streamparm.parm.capture.timeperframe.numerator;
1933 if (std::fabs(fps - retFps) > std::numeric_limits<float>::epsilon()) {
1934 ALOGE("%s: expect fps %f, got %f instead", __FUNCTION__, fps, retFps);
1935 return BAD_VALUE;
1936 }
1937
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -08001938 uint32_t v4lBufferCount = (fps >= kDefaultFps) ?
1939 mCfg.numVideoBuffers : mCfg.numStillBuffers;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001940 // VIDIOC_REQBUFS: create buffers
1941 v4l2_requestbuffers req_buffers{};
1942 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1943 req_buffers.memory = V4L2_MEMORY_MMAP;
1944 req_buffers.count = v4lBufferCount;
1945 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
1946 ALOGE("%s: VIDIOC_REQBUFS failed: %s", __FUNCTION__, strerror(errno));
1947 return -errno;
1948 }
1949
1950 // Driver can indeed return more buffer if it needs more to operate
1951 if (req_buffers.count < v4lBufferCount) {
1952 ALOGE("%s: VIDIOC_REQBUFS expected %d buffers, got %d instead",
1953 __FUNCTION__, v4lBufferCount, req_buffers.count);
1954 return NO_MEMORY;
1955 }
1956
1957 // VIDIOC_EXPBUF: export buffers as FD
1958 // VIDIOC_QBUF: send buffer to driver
1959 mV4l2Buffers.resize(req_buffers.count);
1960 for (uint32_t i = 0; i < req_buffers.count; i++) {
1961 v4l2_exportbuffer expbuf {};
1962 expbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1963 expbuf.index = i;
1964 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_EXPBUF, &expbuf)) < 0) {
1965 ALOGE("%s: EXPBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
1966 return -errno;
1967 }
1968 mV4l2Buffers[i].reset(expbuf.fd);
1969
1970 v4l2_buffer buffer = {
1971 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
1972 .index = i,
1973 .memory = V4L2_MEMORY_MMAP};
1974
1975 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1976 ALOGE("%s: QBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
1977 return -errno;
1978 }
1979 }
1980
1981 // VIDIOC_STREAMON: start streaming
1982 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1983 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type)) < 0) {
1984 ALOGE("%s: VIDIOC_STREAMON failed: %s", __FUNCTION__, strerror(errno));
1985 return -errno;
1986 }
1987
1988 // Swallow first few frames after streamOn to account for bad frames from some devices
1989 for (int i = 0; i < kBadFramesAfterStreamOn; i++) {
1990 v4l2_buffer buffer{};
1991 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1992 buffer.memory = V4L2_MEMORY_MMAP;
1993 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
1994 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
1995 return -errno;
1996 }
1997
1998 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1999 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, buffer.index, strerror(errno));
2000 return -errno;
2001 }
2002 }
2003
2004 mV4l2StreamingFmt = v4l2Fmt;
2005 mV4l2Streaming = true;
2006 return OK;
2007}
2008
2009sp<V4L2Frame> ExternalCameraDeviceSession::dequeueV4l2FrameLocked() {
2010 sp<V4L2Frame> ret = nullptr;
2011
2012 {
2013 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
2014 if (mNumDequeuedV4l2Buffers == mV4l2Buffers.size()) {
2015 std::chrono::seconds timeout = std::chrono::seconds(kBufferWaitTimeoutSec);
2016 mLock.unlock();
2017 auto st = mV4L2BufferReturned.wait_for(lk, timeout);
2018 mLock.lock();
2019 if (st == std::cv_status::timeout) {
2020 ALOGE("%s: wait for V4L2 buffer return timeout!", __FUNCTION__);
2021 return ret;
2022 }
2023 }
2024 }
2025
2026 v4l2_buffer buffer{};
2027 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2028 buffer.memory = V4L2_MEMORY_MMAP;
2029 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
2030 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
2031 return ret;
2032 }
2033
2034 if (buffer.index >= mV4l2Buffers.size()) {
2035 ALOGE("%s: Invalid buffer id: %d", __FUNCTION__, buffer.index);
2036 return ret;
2037 }
2038
2039 if (buffer.flags & V4L2_BUF_FLAG_ERROR) {
2040 ALOGE("%s: v4l2 buf error! buf flag 0x%x", __FUNCTION__, buffer.flags);
2041 // TODO: try to dequeue again
2042 }
2043
2044 {
2045 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2046 mNumDequeuedV4l2Buffers++;
2047 }
2048 return new V4L2Frame(
2049 mV4l2StreamingFmt.width, mV4l2StreamingFmt.height, mV4l2StreamingFmt.fourcc,
2050 buffer.index, mV4l2Buffers[buffer.index].get(), buffer.bytesused);
2051}
2052
2053void ExternalCameraDeviceSession::enqueueV4l2Frame(const sp<V4L2Frame>& frame) {
2054 Mutex::Autolock _l(mLock);
2055 frame->unmap();
2056 v4l2_buffer buffer{};
2057 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2058 buffer.memory = V4L2_MEMORY_MMAP;
2059 buffer.index = frame->mBufferIndex;
2060 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2061 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, frame->mBufferIndex, strerror(errno));
2062 return;
2063 }
2064
2065 {
2066 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2067 mNumDequeuedV4l2Buffers--;
2068 mV4L2BufferReturned.notify_one();
2069 }
2070}
2071
2072Status ExternalCameraDeviceSession::configureStreams(
2073 const V3_2::StreamConfiguration& config, V3_3::HalStreamConfiguration* out) {
2074 if (config.operationMode != StreamConfigurationMode::NORMAL_MODE) {
2075 ALOGE("%s: unsupported operation mode: %d", __FUNCTION__, config.operationMode);
2076 return Status::ILLEGAL_ARGUMENT;
2077 }
2078
2079 if (config.streams.size() == 0) {
2080 ALOGE("%s: cannot configure zero stream", __FUNCTION__);
2081 return Status::ILLEGAL_ARGUMENT;
2082 }
2083
2084 int numProcessedStream = 0;
2085 int numStallStream = 0;
2086 for (const auto& stream : config.streams) {
2087 // Check if the format/width/height combo is supported
2088 if (!isSupported(stream)) {
2089 return Status::ILLEGAL_ARGUMENT;
2090 }
2091 if (stream.format == PixelFormat::BLOB) {
2092 numStallStream++;
2093 } else {
2094 numProcessedStream++;
2095 }
2096 }
2097
2098 if (numProcessedStream > kMaxProcessedStream) {
2099 ALOGE("%s: too many processed streams (expect <= %d, got %d)", __FUNCTION__,
2100 kMaxProcessedStream, numProcessedStream);
2101 return Status::ILLEGAL_ARGUMENT;
2102 }
2103
2104 if (numStallStream > kMaxStallStream) {
2105 ALOGE("%s: too many stall streams (expect <= %d, got %d)", __FUNCTION__,
2106 kMaxStallStream, numStallStream);
2107 return Status::ILLEGAL_ARGUMENT;
2108 }
2109
2110 Status status = initStatus();
2111 if (status != Status::OK) {
2112 return status;
2113 }
2114
2115 Mutex::Autolock _l(mLock);
2116 if (!mInflightFrames.empty()) {
2117 ALOGE("%s: trying to configureStreams while there are still %zu inflight frames!",
2118 __FUNCTION__, mInflightFrames.size());
2119 return Status::INTERNAL_ERROR;
2120 }
2121
2122 // Add new streams
2123 for (const auto& stream : config.streams) {
2124 if (mStreamMap.count(stream.id) == 0) {
2125 mStreamMap[stream.id] = stream;
2126 mCirculatingBuffers.emplace(stream.id, CirculatingBuffers{});
2127 }
2128 }
2129
2130 // Cleanup removed streams
2131 for(auto it = mStreamMap.begin(); it != mStreamMap.end();) {
2132 int id = it->first;
2133 bool found = false;
2134 for (const auto& stream : config.streams) {
2135 if (id == stream.id) {
2136 found = true;
2137 break;
2138 }
2139 }
2140 if (!found) {
2141 // Unmap all buffers of deleted stream
2142 cleanupBuffersLocked(id);
2143 it = mStreamMap.erase(it);
2144 } else {
2145 ++it;
2146 }
2147 }
2148
2149 // Now select a V4L2 format to produce all output streams
2150 float desiredAr = (mCroppingType == VERTICAL) ? kMaxAspectRatio : kMinAspectRatio;
2151 uint32_t maxDim = 0;
2152 for (const auto& stream : config.streams) {
2153 float aspectRatio = ASPECT_RATIO(stream);
2154 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2155 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2156 desiredAr = aspectRatio;
2157 }
2158
2159 // The dimension that's not cropped
2160 uint32_t dim = (mCroppingType == VERTICAL) ? stream.width : stream.height;
2161 if (dim > maxDim) {
2162 maxDim = dim;
2163 }
2164 }
2165 // Find the smallest format that matches the desired aspect ratio and is wide/high enough
2166 SupportedV4L2Format v4l2Fmt {.width = 0, .height = 0};
2167 for (const auto& fmt : mSupportedFormats) {
2168 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2169 if (dim >= maxDim) {
2170 float aspectRatio = ASPECT_RATIO(fmt);
2171 if (isAspectRatioClose(aspectRatio, desiredAr)) {
2172 v4l2Fmt = fmt;
2173 // since mSupportedFormats is sorted by width then height, the first matching fmt
2174 // will be the smallest one with matching aspect ratio
2175 break;
2176 }
2177 }
2178 }
2179 if (v4l2Fmt.width == 0) {
2180 // Cannot find exact good aspect ratio candidate, try to find a close one
2181 for (const auto& fmt : mSupportedFormats) {
2182 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2183 if (dim >= maxDim) {
2184 float aspectRatio = ASPECT_RATIO(fmt);
2185 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2186 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2187 v4l2Fmt = fmt;
2188 break;
2189 }
2190 }
2191 }
2192 }
2193
2194 if (v4l2Fmt.width == 0) {
2195 ALOGE("%s: unable to find a resolution matching (%s at least %d, aspect ratio %f)"
2196 , __FUNCTION__, (mCroppingType == VERTICAL) ? "width" : "height",
2197 maxDim, desiredAr);
2198 return Status::ILLEGAL_ARGUMENT;
2199 }
2200
2201 if (configureV4l2StreamLocked(v4l2Fmt) != 0) {
2202 ALOGE("V4L configuration failed!, format:%c%c%c%c, w %d, h %d",
2203 v4l2Fmt.fourcc & 0xFF,
2204 (v4l2Fmt.fourcc >> 8) & 0xFF,
2205 (v4l2Fmt.fourcc >> 16) & 0xFF,
2206 (v4l2Fmt.fourcc >> 24) & 0xFF,
2207 v4l2Fmt.width, v4l2Fmt.height);
2208 return Status::INTERNAL_ERROR;
2209 }
2210
2211 Size v4lSize = {v4l2Fmt.width, v4l2Fmt.height};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08002212 Size thumbSize { 0, 0 };
2213 camera_metadata_ro_entry entry =
2214 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
2215 for(uint32_t i = 0; i < entry.count; i += 2) {
2216 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
2217 static_cast<uint32_t>(entry.data.i32[i+1]) };
2218 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
2219 thumbSize = sz;
2220 }
2221 }
2222
2223 if (thumbSize.width * thumbSize.height == 0) {
2224 ALOGE("%s: non-zero thumbnail size not available", __FUNCTION__);
2225 return Status::INTERNAL_ERROR;
2226 }
2227
2228 status = mOutputThread->allocateIntermediateBuffers(v4lSize,
2229 mMaxThumbResolution, config.streams);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002230 if (status != Status::OK) {
2231 ALOGE("%s: allocating intermediate buffers failed!", __FUNCTION__);
2232 return status;
2233 }
2234
2235 out->streams.resize(config.streams.size());
2236 for (size_t i = 0; i < config.streams.size(); i++) {
2237 out->streams[i].overrideDataSpace = config.streams[i].dataSpace;
2238 out->streams[i].v3_2.id = config.streams[i].id;
2239 // TODO: double check should we add those CAMERA flags
2240 mStreamMap[config.streams[i].id].usage =
2241 out->streams[i].v3_2.producerUsage = config.streams[i].usage |
2242 BufferUsage::CPU_WRITE_OFTEN |
2243 BufferUsage::CAMERA_OUTPUT;
2244 out->streams[i].v3_2.consumerUsage = 0;
2245 out->streams[i].v3_2.maxBuffers = mV4l2Buffers.size();
2246
2247 switch (config.streams[i].format) {
2248 case PixelFormat::BLOB:
2249 case PixelFormat::YCBCR_420_888:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002250 case PixelFormat::YV12: // Used by SurfaceTexture
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002251 // No override
2252 out->streams[i].v3_2.overrideFormat = config.streams[i].format;
2253 break;
2254 case PixelFormat::IMPLEMENTATION_DEFINED:
2255 // Override based on VIDEO or not
2256 out->streams[i].v3_2.overrideFormat =
2257 (config.streams[i].usage & BufferUsage::VIDEO_ENCODER) ?
2258 PixelFormat::YCBCR_420_888 : PixelFormat::YV12;
2259 // Save overridden formt in mStreamMap
2260 mStreamMap[config.streams[i].id].format = out->streams[i].v3_2.overrideFormat;
2261 break;
2262 default:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002263 ALOGE("%s: unsupported format 0x%x", __FUNCTION__, config.streams[i].format);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002264 return Status::ILLEGAL_ARGUMENT;
2265 }
2266 }
2267
2268 mFirstRequest = true;
2269 return Status::OK;
2270}
2271
2272bool ExternalCameraDeviceSession::isClosed() {
2273 Mutex::Autolock _l(mLock);
2274 return mClosed;
2275}
2276
2277#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
2278#define UPDATE(md, tag, data, size) \
2279do { \
2280 if ((md).update((tag), (data), (size))) { \
2281 ALOGE("Update " #tag " failed!"); \
2282 return BAD_VALUE; \
2283 } \
2284} while (0)
2285
2286status_t ExternalCameraDeviceSession::initDefaultRequests() {
2287 ::android::hardware::camera::common::V1_0::helper::CameraMetadata md;
2288
2289 const uint8_t aberrationMode = ANDROID_COLOR_CORRECTION_ABERRATION_MODE_OFF;
2290 UPDATE(md, ANDROID_COLOR_CORRECTION_ABERRATION_MODE, &aberrationMode, 1);
2291
2292 const int32_t exposureCompensation = 0;
2293 UPDATE(md, ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION, &exposureCompensation, 1);
2294
2295 const uint8_t videoStabilizationMode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
2296 UPDATE(md, ANDROID_CONTROL_VIDEO_STABILIZATION_MODE, &videoStabilizationMode, 1);
2297
2298 const uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO;
2299 UPDATE(md, ANDROID_CONTROL_AWB_MODE, &awbMode, 1);
2300
2301 const uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON;
2302 UPDATE(md, ANDROID_CONTROL_AE_MODE, &aeMode, 1);
2303
2304 const uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
2305 UPDATE(md, ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
2306
2307 const uint8_t afMode = ANDROID_CONTROL_AF_MODE_AUTO;
2308 UPDATE(md, ANDROID_CONTROL_AF_MODE, &afMode, 1);
2309
2310 const uint8_t afTrigger = ANDROID_CONTROL_AF_TRIGGER_IDLE;
2311 UPDATE(md, ANDROID_CONTROL_AF_TRIGGER, &afTrigger, 1);
2312
2313 const uint8_t sceneMode = ANDROID_CONTROL_SCENE_MODE_DISABLED;
2314 UPDATE(md, ANDROID_CONTROL_SCENE_MODE, &sceneMode, 1);
2315
2316 const uint8_t effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF;
2317 UPDATE(md, ANDROID_CONTROL_EFFECT_MODE, &effectMode, 1);
2318
2319 const uint8_t flashMode = ANDROID_FLASH_MODE_OFF;
2320 UPDATE(md, ANDROID_FLASH_MODE, &flashMode, 1);
2321
2322 const int32_t thumbnailSize[] = {240, 180};
2323 UPDATE(md, ANDROID_JPEG_THUMBNAIL_SIZE, thumbnailSize, 2);
2324
2325 const uint8_t jpegQuality = 90;
2326 UPDATE(md, ANDROID_JPEG_QUALITY, &jpegQuality, 1);
2327 UPDATE(md, ANDROID_JPEG_THUMBNAIL_QUALITY, &jpegQuality, 1);
2328
2329 const int32_t jpegOrientation = 0;
2330 UPDATE(md, ANDROID_JPEG_ORIENTATION, &jpegOrientation, 1);
2331
2332 const uint8_t oisMode = ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF;
2333 UPDATE(md, ANDROID_LENS_OPTICAL_STABILIZATION_MODE, &oisMode, 1);
2334
2335 const uint8_t nrMode = ANDROID_NOISE_REDUCTION_MODE_OFF;
2336 UPDATE(md, ANDROID_NOISE_REDUCTION_MODE, &nrMode, 1);
2337
2338 const uint8_t fdMode = ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
2339 UPDATE(md, ANDROID_STATISTICS_FACE_DETECT_MODE, &fdMode, 1);
2340
2341 const uint8_t hotpixelMode = ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF;
2342 UPDATE(md, ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE, &hotpixelMode, 1);
2343
2344 bool support30Fps = false;
2345 int32_t maxFps = std::numeric_limits<int32_t>::min();
2346 for (const auto& supportedFormat : mSupportedFormats) {
2347 for (const auto& frameRate : supportedFormat.frameRates) {
2348 int32_t framerateInt = static_cast<int32_t>(frameRate);
2349 if (maxFps < framerateInt) {
2350 maxFps = framerateInt;
2351 }
2352 if (framerateInt == 30) {
2353 support30Fps = true;
2354 break;
2355 }
2356 }
2357 if (support30Fps) {
2358 break;
2359 }
2360 }
2361 int32_t defaultFramerate = support30Fps ? 30 : maxFps;
2362 int32_t defaultFpsRange[] = {defaultFramerate, defaultFramerate};
2363 UPDATE(md, ANDROID_CONTROL_AE_TARGET_FPS_RANGE, defaultFpsRange, ARRAY_SIZE(defaultFpsRange));
2364
2365 uint8_t antibandingMode = ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO;
2366 UPDATE(md, ANDROID_CONTROL_AE_ANTIBANDING_MODE, &antibandingMode, 1);
2367
2368 const uint8_t controlMode = ANDROID_CONTROL_MODE_AUTO;
2369 UPDATE(md, ANDROID_CONTROL_MODE, &controlMode, 1);
2370
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002371 auto requestTemplates = hidl_enum_iterator<RequestTemplate>();
2372 for (RequestTemplate type : requestTemplates) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002373 ::android::hardware::camera::common::V1_0::helper::CameraMetadata mdCopy = md;
2374 uint8_t intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2375 switch (type) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002376 case RequestTemplate::PREVIEW:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002377 intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2378 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002379 case RequestTemplate::STILL_CAPTURE:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002380 intent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE;
2381 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002382 case RequestTemplate::VIDEO_RECORD:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002383 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD;
2384 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002385 case RequestTemplate::VIDEO_SNAPSHOT:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002386 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT;
2387 break;
2388 default:
Yuriy Romanenko083de0c2018-01-26 16:05:54 -08002389 ALOGV("%s: unsupported RequestTemplate type %d", __FUNCTION__, type);
2390 continue;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002391 }
2392 UPDATE(mdCopy, ANDROID_CONTROL_CAPTURE_INTENT, &intent, 1);
2393
2394 camera_metadata_t* rawMd = mdCopy.release();
2395 CameraMetadata hidlMd;
2396 hidlMd.setToExternal(
2397 (uint8_t*) rawMd, get_camera_metadata_size(rawMd));
2398 mDefaultRequests[type] = hidlMd;
2399 free_camera_metadata(rawMd);
2400 }
2401
2402 return OK;
2403}
2404
2405status_t ExternalCameraDeviceSession::fillCaptureResult(
2406 common::V1_0::helper::CameraMetadata &md, nsecs_t timestamp) {
2407 // android.control
2408 // For USB camera, we don't know the AE state. Set the state to converged to
2409 // indicate the frame should be good to use. Then apps don't have to wait the
2410 // AE state.
2411 const uint8_t aeState = ANDROID_CONTROL_AE_STATE_CONVERGED;
2412 UPDATE(md, ANDROID_CONTROL_AE_STATE, &aeState, 1);
2413
2414 const uint8_t ae_lock = ANDROID_CONTROL_AE_LOCK_OFF;
2415 UPDATE(md, ANDROID_CONTROL_AE_LOCK, &ae_lock, 1);
2416
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002417 bool afTrigger = mAfTrigger;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002418 if (md.exists(ANDROID_CONTROL_AF_TRIGGER)) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002419 Mutex::Autolock _l(mLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002420 camera_metadata_entry entry = md.find(ANDROID_CONTROL_AF_TRIGGER);
2421 if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_START) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002422 mAfTrigger = afTrigger = true;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002423 } else if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_CANCEL) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002424 mAfTrigger = afTrigger = false;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002425 }
2426 }
2427
2428 // For USB camera, the USB camera handles everything and we don't have control
2429 // over AF. We only simply fake the AF metadata based on the request
2430 // received here.
2431 uint8_t afState;
2432 if (afTrigger) {
2433 afState = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
2434 } else {
2435 afState = ANDROID_CONTROL_AF_STATE_INACTIVE;
2436 }
2437 UPDATE(md, ANDROID_CONTROL_AF_STATE, &afState, 1);
2438
2439 // Set AWB state to converged to indicate the frame should be good to use.
2440 const uint8_t awbState = ANDROID_CONTROL_AWB_STATE_CONVERGED;
2441 UPDATE(md, ANDROID_CONTROL_AWB_STATE, &awbState, 1);
2442
2443 const uint8_t awbLock = ANDROID_CONTROL_AWB_LOCK_OFF;
2444 UPDATE(md, ANDROID_CONTROL_AWB_LOCK, &awbLock, 1);
2445
2446 camera_metadata_ro_entry active_array_size =
2447 mCameraCharacteristics.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
2448
2449 if (active_array_size.count == 0) {
2450 ALOGE("%s: cannot find active array size!", __FUNCTION__);
2451 return -EINVAL;
2452 }
2453
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002454 const uint8_t flashState = ANDROID_FLASH_STATE_UNAVAILABLE;
2455 UPDATE(md, ANDROID_FLASH_STATE, &flashState, 1);
2456
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002457 // android.scaler
2458 const int32_t crop_region[] = {
2459 active_array_size.data.i32[0], active_array_size.data.i32[1],
2460 active_array_size.data.i32[2], active_array_size.data.i32[3],
2461 };
2462 UPDATE(md, ANDROID_SCALER_CROP_REGION, crop_region, ARRAY_SIZE(crop_region));
2463
2464 // android.sensor
2465 UPDATE(md, ANDROID_SENSOR_TIMESTAMP, &timestamp, 1);
2466
2467 // android.statistics
2468 const uint8_t lensShadingMapMode = ANDROID_STATISTICS_LENS_SHADING_MAP_MODE_OFF;
2469 UPDATE(md, ANDROID_STATISTICS_LENS_SHADING_MAP_MODE, &lensShadingMapMode, 1);
2470
2471 const uint8_t sceneFlicker = ANDROID_STATISTICS_SCENE_FLICKER_NONE;
2472 UPDATE(md, ANDROID_STATISTICS_SCENE_FLICKER, &sceneFlicker, 1);
2473
2474 return OK;
2475}
2476
2477#undef ARRAY_SIZE
2478#undef UPDATE
2479
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002480} // namespace implementation
2481} // namespace V3_4
2482} // namespace device
2483} // namespace camera
2484} // namespace hardware
2485} // namespace android