blob: 74fd7f4cb1e7b60d0efa60797b5acda56508a02a [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 Yeh17982492018-02-05 17:41:01 -080058 const ExternalCameraConfig& cfg,
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -080059 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;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800519 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700520 }
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;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800557 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700558 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;
Yin-Chia Yeh1e089662018-02-02 15:57:58 -0800565 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700566 }
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 }
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -0800614 auto status = mCallback->processCaptureResult(results);
615 if (!status.isOk()) {
616 ALOGE("%s: processCaptureResult ERROR : %s", __FUNCTION__,
617 status.description().c_str());
618 }
619
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700620 mProcessCaptureResultLock.unlock();
621}
622
623void ExternalCameraDeviceSession::freeReleaseFences(hidl_vec<CaptureResult>& results) {
624 for (auto& result : results) {
625 if (result.inputBuffer.releaseFence.getNativeHandle() != nullptr) {
626 native_handle_t* handle = const_cast<native_handle_t*>(
627 result.inputBuffer.releaseFence.getNativeHandle());
628 native_handle_close(handle);
629 native_handle_delete(handle);
630 }
631 for (auto& buf : result.outputBuffers) {
632 if (buf.releaseFence.getNativeHandle() != nullptr) {
633 native_handle_t* handle = const_cast<native_handle_t*>(
634 buf.releaseFence.getNativeHandle());
635 native_handle_close(handle);
636 native_handle_delete(handle);
637 }
638 }
639 }
640 return;
641}
642
643ExternalCameraDeviceSession::OutputThread::OutputThread(
644 wp<ExternalCameraDeviceSession> parent,
645 CroppingType ct) : mParent(parent), mCroppingType(ct) {}
646
647ExternalCameraDeviceSession::OutputThread::~OutputThread() {}
648
649uint32_t ExternalCameraDeviceSession::OutputThread::getFourCcFromLayout(
650 const YCbCrLayout& layout) {
651 intptr_t cb = reinterpret_cast<intptr_t>(layout.cb);
652 intptr_t cr = reinterpret_cast<intptr_t>(layout.cr);
653 if (std::abs(cb - cr) == 1 && layout.chromaStep == 2) {
654 // Interleaved format
655 if (layout.cb > layout.cr) {
656 return V4L2_PIX_FMT_NV21;
657 } else {
658 return V4L2_PIX_FMT_NV12;
659 }
660 } else if (layout.chromaStep == 1) {
661 // Planar format
662 if (layout.cb > layout.cr) {
663 return V4L2_PIX_FMT_YVU420; // YV12
664 } else {
665 return V4L2_PIX_FMT_YUV420; // YU12
666 }
667 } else {
668 return FLEX_YUV_GENERIC;
669 }
670}
671
672int ExternalCameraDeviceSession::OutputThread::getCropRect(
673 CroppingType ct, const Size& inSize, const Size& outSize, IMapper::Rect* out) {
674 if (out == nullptr) {
675 ALOGE("%s: out is null", __FUNCTION__);
676 return -1;
677 }
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800678
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700679 uint32_t inW = inSize.width;
680 uint32_t inH = inSize.height;
681 uint32_t outW = outSize.width;
682 uint32_t outH = outSize.height;
683
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800684 // Handle special case where aspect ratio is close to input but scaled
685 // dimension is slightly larger than input
686 float arIn = ASPECT_RATIO(inSize);
687 float arOut = ASPECT_RATIO(outSize);
688 if (isAspectRatioClose(arIn, arOut)) {
689 out->left = 0;
690 out->top = 0;
691 out->width = inW;
692 out->height = inH;
693 return 0;
694 }
695
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700696 if (ct == VERTICAL) {
697 uint64_t scaledOutH = static_cast<uint64_t>(outH) * inW / outW;
698 if (scaledOutH > inH) {
699 ALOGE("%s: Output size %dx%d cannot be vertically cropped from input size %dx%d",
700 __FUNCTION__, outW, outH, inW, inH);
701 return -1;
702 }
703 scaledOutH = scaledOutH & ~0x1; // make it multiple of 2
704
705 out->left = 0;
706 out->top = ((inH - scaledOutH) / 2) & ~0x1;
707 out->width = inW;
708 out->height = static_cast<int32_t>(scaledOutH);
709 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledH %d",
710 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutH));
711 } else {
712 uint64_t scaledOutW = static_cast<uint64_t>(outW) * inH / outH;
713 if (scaledOutW > inW) {
714 ALOGE("%s: Output size %dx%d cannot be horizontally cropped from input size %dx%d",
715 __FUNCTION__, outW, outH, inW, inH);
716 return -1;
717 }
718 scaledOutW = scaledOutW & ~0x1; // make it multiple of 2
719
720 out->left = ((inW - scaledOutW) / 2) & ~0x1;
721 out->top = 0;
722 out->width = static_cast<int32_t>(scaledOutW);
723 out->height = inH;
724 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledW %d",
725 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutW));
726 }
727
728 return 0;
729}
730
731int ExternalCameraDeviceSession::OutputThread::cropAndScaleLocked(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800732 sp<AllocatedFrame>& in, const Size& outSz, YCbCrLayout* out) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700733 Size inSz = {in->mWidth, in->mHeight};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800734
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700735 int ret;
736 if (inSz == outSz) {
737 ret = in->getLayout(out);
738 if (ret != 0) {
739 ALOGE("%s: failed to get input image layout", __FUNCTION__);
740 return ret;
741 }
742 return ret;
743 }
744
745 // Cropping to output aspect ratio
746 IMapper::Rect inputCrop;
747 ret = getCropRect(mCroppingType, inSz, outSz, &inputCrop);
748 if (ret != 0) {
749 ALOGE("%s: failed to compute crop rect for output size %dx%d",
750 __FUNCTION__, outSz.width, outSz.height);
751 return ret;
752 }
753
754 YCbCrLayout croppedLayout;
755 ret = in->getCroppedLayout(inputCrop, &croppedLayout);
756 if (ret != 0) {
757 ALOGE("%s: failed to crop input image %dx%d to output size %dx%d",
758 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
759 return ret;
760 }
761
762 if ((mCroppingType == VERTICAL && inSz.width == outSz.width) ||
763 (mCroppingType == HORIZONTAL && inSz.height == outSz.height)) {
764 // No scale is needed
765 *out = croppedLayout;
766 return 0;
767 }
768
769 auto it = mScaledYu12Frames.find(outSz);
770 sp<AllocatedFrame> scaledYu12Buf;
771 if (it != mScaledYu12Frames.end()) {
772 scaledYu12Buf = it->second;
773 } else {
774 it = mIntermediateBuffers.find(outSz);
775 if (it == mIntermediateBuffers.end()) {
776 ALOGE("%s: failed to find intermediate buffer size %dx%d",
777 __FUNCTION__, outSz.width, outSz.height);
778 return -1;
779 }
780 scaledYu12Buf = it->second;
781 }
782 // Scale
783 YCbCrLayout outLayout;
784 ret = scaledYu12Buf->getLayout(&outLayout);
785 if (ret != 0) {
786 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
787 return ret;
788 }
789
790 ret = libyuv::I420Scale(
791 static_cast<uint8_t*>(croppedLayout.y),
792 croppedLayout.yStride,
793 static_cast<uint8_t*>(croppedLayout.cb),
794 croppedLayout.cStride,
795 static_cast<uint8_t*>(croppedLayout.cr),
796 croppedLayout.cStride,
797 inputCrop.width,
798 inputCrop.height,
799 static_cast<uint8_t*>(outLayout.y),
800 outLayout.yStride,
801 static_cast<uint8_t*>(outLayout.cb),
802 outLayout.cStride,
803 static_cast<uint8_t*>(outLayout.cr),
804 outLayout.cStride,
805 outSz.width,
806 outSz.height,
807 // TODO: b/72261744 see if we can use better filter without losing too much perf
808 libyuv::FilterMode::kFilterNone);
809
810 if (ret != 0) {
811 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
812 __FUNCTION__, inputCrop.width, inputCrop.height,
813 outSz.width, outSz.height, ret);
814 return ret;
815 }
816
817 *out = outLayout;
818 mScaledYu12Frames.insert({outSz, scaledYu12Buf});
819 return 0;
820}
821
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -0800822
823int ExternalCameraDeviceSession::OutputThread::cropAndScaleThumbLocked(
824 sp<AllocatedFrame>& in, const Size &outSz, YCbCrLayout* out) {
825 Size inSz {in->mWidth, in->mHeight};
826
827 if ((outSz.width * outSz.height) >
828 (mYu12ThumbFrame->mWidth * mYu12ThumbFrame->mHeight)) {
829 ALOGE("%s: Requested thumbnail size too big (%d,%d) > (%d,%d)",
830 __FUNCTION__, outSz.width, outSz.height,
831 mYu12ThumbFrame->mWidth, mYu12ThumbFrame->mHeight);
832 return -1;
833 }
834
835 int ret;
836
837 /* This will crop-and-zoom the input YUV frame to the thumbnail size
838 * Based on the following logic:
839 * 1) Square pixels come in, square pixels come out, therefore single
840 * scale factor is computed to either make input bigger or smaller
841 * depending on if we are upscaling or downscaling
842 * 2) That single scale factor would either make height too tall or width
843 * too wide so we need to crop the input either horizontally or vertically
844 * but not both
845 */
846
847 /* Convert the input and output dimensions into floats for ease of math */
848 float fWin = static_cast<float>(inSz.width);
849 float fHin = static_cast<float>(inSz.height);
850 float fWout = static_cast<float>(outSz.width);
851 float fHout = static_cast<float>(outSz.height);
852
853 /* Compute the one scale factor from (1) above, it will be the smaller of
854 * the two possibilities. */
855 float scaleFactor = std::min( fHin / fHout, fWin / fWout );
856
857 /* Since we are crop-and-zooming (as opposed to letter/pillar boxing) we can
858 * simply multiply the output by our scaleFactor to get the cropped input
859 * size. Note that at least one of {fWcrop, fHcrop} is going to wind up
860 * being {fWin, fHin} respectively because fHout or fWout cancels out the
861 * scaleFactor calculation above.
862 *
863 * Specifically:
864 * if ( fHin / fHout ) < ( fWin / fWout ) we crop the sides off
865 * input, in which case
866 * scaleFactor = fHin / fHout
867 * fWcrop = fHin / fHout * fWout
868 * fHcrop = fHin
869 *
870 * Note that fWcrop <= fWin ( because ( fHin / fHout ) * fWout < fWin, which
871 * is just the inequality above with both sides multiplied by fWout
872 *
873 * on the other hand if ( fWin / fWout ) < ( fHin / fHout) we crop the top
874 * and the bottom off of input, and
875 * scaleFactor = fWin / fWout
876 * fWcrop = fWin
877 * fHCrop = fWin / fWout * fHout
878 */
879 float fWcrop = scaleFactor * fWout;
880 float fHcrop = scaleFactor * fHout;
881
882 /* Convert to integer and truncate to an even number */
883 Size cropSz = { 2*static_cast<uint32_t>(fWcrop/2.0f),
884 2*static_cast<uint32_t>(fHcrop/2.0f) };
885
886 /* Convert to a centered rectange with even top/left */
887 IMapper::Rect inputCrop {
888 2*static_cast<int32_t>((inSz.width - cropSz.width)/4),
889 2*static_cast<int32_t>((inSz.height - cropSz.height)/4),
890 static_cast<int32_t>(cropSz.width),
891 static_cast<int32_t>(cropSz.height) };
892
893 if ((inputCrop.top < 0) ||
894 (inputCrop.top >= static_cast<int32_t>(inSz.height)) ||
895 (inputCrop.left < 0) ||
896 (inputCrop.left >= static_cast<int32_t>(inSz.width)) ||
897 (inputCrop.width <= 0) ||
898 (inputCrop.width + inputCrop.left > static_cast<int32_t>(inSz.width)) ||
899 (inputCrop.height <= 0) ||
900 (inputCrop.height + inputCrop.top > static_cast<int32_t>(inSz.height)))
901 {
902 ALOGE("%s: came up with really wrong crop rectangle",__FUNCTION__);
903 ALOGE("%s: input layout %dx%d to for output size %dx%d",
904 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
905 ALOGE("%s: computed input crop +%d,+%d %dx%d",
906 __FUNCTION__, inputCrop.left, inputCrop.top,
907 inputCrop.width, inputCrop.height);
908 return -1;
909 }
910
911 YCbCrLayout inputLayout;
912 ret = in->getCroppedLayout(inputCrop, &inputLayout);
913 if (ret != 0) {
914 ALOGE("%s: failed to crop input layout %dx%d to for output size %dx%d",
915 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
916 ALOGE("%s: computed input crop +%d,+%d %dx%d",
917 __FUNCTION__, inputCrop.left, inputCrop.top,
918 inputCrop.width, inputCrop.height);
919 return ret;
920 }
921 ALOGV("%s: crop input layout %dx%d to for output size %dx%d",
922 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
923 ALOGV("%s: computed input crop +%d,+%d %dx%d",
924 __FUNCTION__, inputCrop.left, inputCrop.top,
925 inputCrop.width, inputCrop.height);
926
927
928 // Scale
929 YCbCrLayout outFullLayout;
930
931 ret = mYu12ThumbFrame->getLayout(&outFullLayout);
932 if (ret != 0) {
933 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
934 return ret;
935 }
936
937
938 ret = libyuv::I420Scale(
939 static_cast<uint8_t*>(inputLayout.y),
940 inputLayout.yStride,
941 static_cast<uint8_t*>(inputLayout.cb),
942 inputLayout.cStride,
943 static_cast<uint8_t*>(inputLayout.cr),
944 inputLayout.cStride,
945 inputCrop.width,
946 inputCrop.height,
947 static_cast<uint8_t*>(outFullLayout.y),
948 outFullLayout.yStride,
949 static_cast<uint8_t*>(outFullLayout.cb),
950 outFullLayout.cStride,
951 static_cast<uint8_t*>(outFullLayout.cr),
952 outFullLayout.cStride,
953 outSz.width,
954 outSz.height,
955 libyuv::FilterMode::kFilterNone);
956
957 if (ret != 0) {
958 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
959 __FUNCTION__, inputCrop.width, inputCrop.height,
960 outSz.width, outSz.height, ret);
961 return ret;
962 }
963
964 *out = outFullLayout;
965 return 0;
966}
967
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700968int ExternalCameraDeviceSession::OutputThread::formatConvertLocked(
969 const YCbCrLayout& in, const YCbCrLayout& out, Size sz, uint32_t format) {
970 int ret = 0;
971 switch (format) {
972 case V4L2_PIX_FMT_NV21:
973 ret = libyuv::I420ToNV21(
974 static_cast<uint8_t*>(in.y),
975 in.yStride,
976 static_cast<uint8_t*>(in.cb),
977 in.cStride,
978 static_cast<uint8_t*>(in.cr),
979 in.cStride,
980 static_cast<uint8_t*>(out.y),
981 out.yStride,
982 static_cast<uint8_t*>(out.cr),
983 out.cStride,
984 sz.width,
985 sz.height);
986 if (ret != 0) {
987 ALOGE("%s: convert to NV21 buffer failed! ret %d",
988 __FUNCTION__, ret);
989 return ret;
990 }
991 break;
992 case V4L2_PIX_FMT_NV12:
993 ret = libyuv::I420ToNV12(
994 static_cast<uint8_t*>(in.y),
995 in.yStride,
996 static_cast<uint8_t*>(in.cb),
997 in.cStride,
998 static_cast<uint8_t*>(in.cr),
999 in.cStride,
1000 static_cast<uint8_t*>(out.y),
1001 out.yStride,
1002 static_cast<uint8_t*>(out.cb),
1003 out.cStride,
1004 sz.width,
1005 sz.height);
1006 if (ret != 0) {
1007 ALOGE("%s: convert to NV12 buffer failed! ret %d",
1008 __FUNCTION__, ret);
1009 return ret;
1010 }
1011 break;
1012 case V4L2_PIX_FMT_YVU420: // YV12
1013 case V4L2_PIX_FMT_YUV420: // YU12
1014 // TODO: maybe we can speed up here by somehow save this copy?
1015 ret = libyuv::I420Copy(
1016 static_cast<uint8_t*>(in.y),
1017 in.yStride,
1018 static_cast<uint8_t*>(in.cb),
1019 in.cStride,
1020 static_cast<uint8_t*>(in.cr),
1021 in.cStride,
1022 static_cast<uint8_t*>(out.y),
1023 out.yStride,
1024 static_cast<uint8_t*>(out.cb),
1025 out.cStride,
1026 static_cast<uint8_t*>(out.cr),
1027 out.cStride,
1028 sz.width,
1029 sz.height);
1030 if (ret != 0) {
1031 ALOGE("%s: copy to YV12 or YU12 buffer failed! ret %d",
1032 __FUNCTION__, ret);
1033 return ret;
1034 }
1035 break;
1036 case FLEX_YUV_GENERIC:
1037 // TODO: b/72261744 write to arbitrary flexible YUV layout. Slow.
1038 ALOGE("%s: unsupported flexible yuv layout"
1039 " y %p cb %p cr %p y_str %d c_str %d c_step %d",
1040 __FUNCTION__, out.y, out.cb, out.cr,
1041 out.yStride, out.cStride, out.chromaStep);
1042 return -1;
1043 default:
1044 ALOGE("%s: unknown YUV format 0x%x!", __FUNCTION__, format);
1045 return -1;
1046 }
1047 return 0;
1048}
1049
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001050int ExternalCameraDeviceSession::OutputThread::encodeJpegYU12(
1051 const Size & inSz, const YCbCrLayout& inLayout,
1052 int jpegQuality, const void *app1Buffer, size_t app1Size,
1053 void *out, const size_t maxOutSize, size_t &actualCodeSize)
1054{
1055 /* libjpeg is a C library so we use C-style "inheritance" by
1056 * putting libjpeg's jpeg_destination_mgr first in our custom
1057 * struct. This allows us to cast jpeg_destination_mgr* to
1058 * CustomJpegDestMgr* when we get it passed to us in a callback */
1059 struct CustomJpegDestMgr {
1060 struct jpeg_destination_mgr mgr;
1061 JOCTET *mBuffer;
1062 size_t mBufferSize;
1063 size_t mEncodedSize;
1064 bool mSuccess;
1065 } dmgr;
1066
1067 jpeg_compress_struct cinfo = {};
1068 jpeg_error_mgr jerr;
1069
1070 /* Initialize error handling with standard callbacks, but
1071 * then override output_message (to print to ALOG) and
1072 * error_exit to set a flag and print a message instead
1073 * of killing the whole process */
1074 cinfo.err = jpeg_std_error(&jerr);
1075
1076 cinfo.err->output_message = [](j_common_ptr cinfo) {
1077 char buffer[JMSG_LENGTH_MAX];
1078
1079 /* Create the message */
1080 (*cinfo->err->format_message)(cinfo, buffer);
1081 ALOGE("libjpeg error: %s", buffer);
1082 };
1083 cinfo.err->error_exit = [](j_common_ptr cinfo) {
1084 (*cinfo->err->output_message)(cinfo);
1085 if(cinfo->client_data) {
1086 auto & dmgr =
1087 *reinterpret_cast<CustomJpegDestMgr*>(cinfo->client_data);
1088 dmgr.mSuccess = false;
1089 }
1090 };
1091 /* Now that we initialized some callbacks, let's create our compressor */
1092 jpeg_create_compress(&cinfo);
1093
1094 /* Initialize our destination manager */
1095 dmgr.mBuffer = static_cast<JOCTET*>(out);
1096 dmgr.mBufferSize = maxOutSize;
1097 dmgr.mEncodedSize = 0;
1098 dmgr.mSuccess = true;
1099 cinfo.client_data = static_cast<void*>(&dmgr);
1100
1101 /* These lambdas become C-style function pointers and as per C++11 spec
1102 * may not capture anything */
1103 dmgr.mgr.init_destination = [](j_compress_ptr cinfo) {
1104 auto & dmgr = reinterpret_cast<CustomJpegDestMgr&>(*cinfo->dest);
1105 dmgr.mgr.next_output_byte = dmgr.mBuffer;
1106 dmgr.mgr.free_in_buffer = dmgr.mBufferSize;
1107 ALOGV("%s:%d jpeg start: %p [%zu]",
1108 __FUNCTION__, __LINE__, dmgr.mBuffer, dmgr.mBufferSize);
1109 };
1110
1111 dmgr.mgr.empty_output_buffer = [](j_compress_ptr cinfo __unused) {
1112 ALOGV("%s:%d Out of buffer", __FUNCTION__, __LINE__);
1113 return 0;
1114 };
1115
1116 dmgr.mgr.term_destination = [](j_compress_ptr cinfo) {
1117 auto & dmgr = reinterpret_cast<CustomJpegDestMgr&>(*cinfo->dest);
1118 dmgr.mEncodedSize = dmgr.mBufferSize - dmgr.mgr.free_in_buffer;
1119 ALOGV("%s:%d Done with jpeg: %zu", __FUNCTION__, __LINE__, dmgr.mEncodedSize);
1120 };
1121 cinfo.dest = reinterpret_cast<struct jpeg_destination_mgr*>(&dmgr);
1122
1123 /* We are going to be using JPEG in raw data mode, so we are passing
1124 * straight subsampled planar YCbCr and it will not touch our pixel
1125 * data or do any scaling or anything */
1126 cinfo.image_width = inSz.width;
1127 cinfo.image_height = inSz.height;
1128 cinfo.input_components = 3;
1129 cinfo.in_color_space = JCS_YCbCr;
1130
1131 /* Initialize defaults and then override what we want */
1132 jpeg_set_defaults(&cinfo);
1133
1134 jpeg_set_quality(&cinfo, jpegQuality, 1);
1135 jpeg_set_colorspace(&cinfo, JCS_YCbCr);
1136 cinfo.raw_data_in = 1;
1137 cinfo.dct_method = JDCT_IFAST;
1138
1139 /* Configure sampling factors. The sampling factor is JPEG subsampling 420
1140 * because the source format is YUV420. Note that libjpeg sampling factors
1141 * are... a little weird. Sampling of Y=2,U=1,V=1 means there is 1 U and
1142 * 1 V value for each 2 Y values */
1143 cinfo.comp_info[0].h_samp_factor = 2;
1144 cinfo.comp_info[0].v_samp_factor = 2;
1145 cinfo.comp_info[1].h_samp_factor = 1;
1146 cinfo.comp_info[1].v_samp_factor = 1;
1147 cinfo.comp_info[2].h_samp_factor = 1;
1148 cinfo.comp_info[2].v_samp_factor = 1;
1149
1150 /* Let's not hardcode YUV420 in 6 places... 5 was enough */
1151 int maxVSampFactor = std::max( {
1152 cinfo.comp_info[0].v_samp_factor,
1153 cinfo.comp_info[1].v_samp_factor,
1154 cinfo.comp_info[2].v_samp_factor
1155 });
1156 int cVSubSampling = cinfo.comp_info[0].v_samp_factor /
1157 cinfo.comp_info[1].v_samp_factor;
1158
1159 /* Start the compressor */
1160 jpeg_start_compress(&cinfo, TRUE);
1161
1162 /* Compute our macroblock height, so we can pad our input to be vertically
1163 * macroblock aligned.
1164 * TODO: Does it need to be horizontally MCU aligned too? */
1165
1166 size_t mcuV = DCTSIZE*maxVSampFactor;
1167 size_t paddedHeight = mcuV * ((inSz.height + mcuV - 1) / mcuV);
1168
1169 /* libjpeg uses arrays of row pointers, which makes it really easy to pad
1170 * data vertically (unfortunately doesn't help horizontally) */
1171 std::vector<JSAMPROW> yLines (paddedHeight);
1172 std::vector<JSAMPROW> cbLines(paddedHeight/cVSubSampling);
1173 std::vector<JSAMPROW> crLines(paddedHeight/cVSubSampling);
1174
1175 uint8_t *py = static_cast<uint8_t*>(inLayout.y);
1176 uint8_t *pcr = static_cast<uint8_t*>(inLayout.cr);
1177 uint8_t *pcb = static_cast<uint8_t*>(inLayout.cb);
1178
1179 for(uint32_t i = 0; i < paddedHeight; i++)
1180 {
1181 /* Once we are in the padding territory we still point to the last line
1182 * effectively replicating it several times ~ CLAMP_TO_EDGE */
1183 int li = std::min(i, inSz.height - 1);
1184 yLines[i] = static_cast<JSAMPROW>(py + li * inLayout.yStride);
1185 if(i < paddedHeight / cVSubSampling)
1186 {
1187 crLines[i] = static_cast<JSAMPROW>(pcr + li * inLayout.cStride);
1188 cbLines[i] = static_cast<JSAMPROW>(pcb + li * inLayout.cStride);
1189 }
1190 }
1191
1192 /* If APP1 data was passed in, use it */
1193 if(app1Buffer && app1Size)
1194 {
1195 jpeg_write_marker(&cinfo, JPEG_APP0 + 1,
1196 static_cast<const JOCTET*>(app1Buffer), app1Size);
1197 }
1198
1199 /* While we still have padded height left to go, keep giving it one
1200 * macroblock at a time. */
1201 while (cinfo.next_scanline < cinfo.image_height) {
1202 const uint32_t batchSize = DCTSIZE * maxVSampFactor;
1203 const uint32_t nl = cinfo.next_scanline;
1204 JSAMPARRAY planes[3]{ &yLines[nl],
1205 &cbLines[nl/cVSubSampling],
1206 &crLines[nl/cVSubSampling] };
1207
1208 uint32_t done = jpeg_write_raw_data(&cinfo, planes, batchSize);
1209
1210 if (done != batchSize) {
1211 ALOGE("%s: compressed %u lines, expected %u (total %u/%u)",
1212 __FUNCTION__, done, batchSize, cinfo.next_scanline,
1213 cinfo.image_height);
1214 return -1;
1215 }
1216 }
1217
1218 /* This will flush everything */
1219 jpeg_finish_compress(&cinfo);
1220
1221 /* Grab the actual code size and set it */
1222 actualCodeSize = dmgr.mEncodedSize;
1223
1224 return 0;
1225}
1226
1227/*
1228 * TODO: There needs to be a mechanism to discover allocated buffer size
1229 * in the HAL.
1230 *
1231 * This is very fragile because it is duplicated computation from:
1232 * frameworks/av/services/camera/libcameraservice/device3/Camera3Device.cpp
1233 *
1234 */
1235
1236/* This assumes mSupportedFormats have all been declared as supporting
1237 * HAL_PIXEL_FORMAT_BLOB to the framework */
1238Size ExternalCameraDeviceSession::getMaxJpegResolution() const {
1239 Size ret { 0, 0 };
1240 for(auto & fmt : mSupportedFormats) {
1241 if(fmt.width * fmt.height > ret.width * ret.height) {
1242 ret = Size { fmt.width, fmt.height };
1243 }
1244 }
1245 return ret;
1246}
1247
1248Size ExternalCameraDeviceSession::getMaxThumbResolution() const {
1249 Size thumbSize { 0, 0 };
1250 camera_metadata_ro_entry entry =
1251 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
1252 for(uint32_t i = 0; i < entry.count; i += 2) {
1253 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
1254 static_cast<uint32_t>(entry.data.i32[i+1]) };
1255 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
1256 thumbSize = sz;
1257 }
1258 }
1259
1260 if (thumbSize.width * thumbSize.height == 0) {
1261 ALOGW("%s: non-zero thumbnail size not available", __FUNCTION__);
1262 }
1263
1264 return thumbSize;
1265}
1266
1267
1268ssize_t ExternalCameraDeviceSession::getJpegBufferSize(
1269 uint32_t width, uint32_t height) const {
1270 // Constant from camera3.h
1271 const ssize_t kMinJpegBufferSize = 256 * 1024 + sizeof(CameraBlob);
1272 // Get max jpeg size (area-wise).
1273 if (mMaxJpegResolution.width == 0) {
1274 ALOGE("%s: Do not have a single supported JPEG stream",
1275 __FUNCTION__);
1276 return BAD_VALUE;
1277 }
1278
1279 // Get max jpeg buffer size
1280 ssize_t maxJpegBufferSize = 0;
1281 camera_metadata_ro_entry jpegBufMaxSize =
1282 mCameraCharacteristics.find(ANDROID_JPEG_MAX_SIZE);
1283 if (jpegBufMaxSize.count == 0) {
1284 ALOGE("%s: Can't find maximum JPEG size in static metadata!",
1285 __FUNCTION__);
1286 return BAD_VALUE;
1287 }
1288 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
1289
1290 if (maxJpegBufferSize <= kMinJpegBufferSize) {
1291 ALOGE("%s: ANDROID_JPEG_MAX_SIZE (%zd) <= kMinJpegBufferSize (%zd)",
1292 __FUNCTION__, maxJpegBufferSize, kMinJpegBufferSize);
1293 return BAD_VALUE;
1294 }
1295
1296 // Calculate final jpeg buffer size for the given resolution.
1297 float scaleFactor = ((float) (width * height)) /
1298 (mMaxJpegResolution.width * mMaxJpegResolution.height);
1299 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
1300 kMinJpegBufferSize;
1301 if (jpegBufferSize > maxJpegBufferSize) {
1302 jpegBufferSize = maxJpegBufferSize;
1303 }
1304
1305 return jpegBufferSize;
1306}
1307
1308int ExternalCameraDeviceSession::OutputThread::createJpegLocked(
1309 HalStreamBuffer &halBuf,
1310 HalRequest &req)
1311{
1312 int ret;
1313 auto lfail = [&](auto... args) {
1314 ALOGE(args...);
1315
1316 return 1;
1317 };
1318 auto parent = mParent.promote();
1319 if (parent == nullptr) {
1320 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1321 return 1;
1322 }
1323
1324 ALOGV("%s: HAL buffer sid: %d bid: %" PRIu64 " w: %u h: %u",
1325 __FUNCTION__, halBuf.streamId, static_cast<uint64_t>(halBuf.bufferId),
1326 halBuf.width, halBuf.height);
1327 ALOGV("%s: HAL buffer fmt: %x usage: %" PRIx64 " ptr: %p",
1328 __FUNCTION__, halBuf.format, static_cast<uint64_t>(halBuf.usage),
1329 halBuf.bufPtr);
1330 ALOGV("%s: YV12 buffer %d x %d",
1331 __FUNCTION__,
1332 mYu12Frame->mWidth, mYu12Frame->mHeight);
1333
1334 int jpegQuality, thumbQuality;
1335 Size thumbSize;
1336
1337 if (req.setting.exists(ANDROID_JPEG_QUALITY)) {
1338 camera_metadata_entry entry =
1339 req.setting.find(ANDROID_JPEG_QUALITY);
1340 jpegQuality = entry.data.u8[0];
1341 } else {
1342 return lfail("%s: ANDROID_JPEG_QUALITY not set",__FUNCTION__);
1343 }
1344
1345 if (req.setting.exists(ANDROID_JPEG_THUMBNAIL_QUALITY)) {
1346 camera_metadata_entry entry =
1347 req.setting.find(ANDROID_JPEG_THUMBNAIL_QUALITY);
1348 thumbQuality = entry.data.u8[0];
1349 } else {
1350 return lfail(
1351 "%s: ANDROID_JPEG_THUMBNAIL_QUALITY not set",
1352 __FUNCTION__);
1353 }
1354
1355 if (req.setting.exists(ANDROID_JPEG_THUMBNAIL_SIZE)) {
1356 camera_metadata_entry entry =
1357 req.setting.find(ANDROID_JPEG_THUMBNAIL_SIZE);
1358 thumbSize = Size { static_cast<uint32_t>(entry.data.i32[0]),
1359 static_cast<uint32_t>(entry.data.i32[1])
1360 };
1361 } else {
1362 return lfail(
1363 "%s: ANDROID_JPEG_THUMBNAIL_SIZE not set", __FUNCTION__);
1364 }
1365
1366 /* Cropped and scaled YU12 buffer for main and thumbnail */
1367 YCbCrLayout yu12Main;
1368 Size jpegSize { halBuf.width, halBuf.height };
1369
1370 /* Compute temporary buffer sizes accounting for the following:
1371 * thumbnail can't exceed APP1 size of 64K
1372 * main image needs to hold APP1, headers, and at most a poorly
1373 * compressed image */
1374 const ssize_t maxThumbCodeSize = 64 * 1024;
1375 const ssize_t maxJpegCodeSize = parent->getJpegBufferSize(jpegSize.width,
1376 jpegSize.height);
1377
1378 /* Check that getJpegBufferSize did not return an error */
1379 if (maxJpegCodeSize < 0) {
1380 return lfail(
1381 "%s: getJpegBufferSize returned %zd",__FUNCTION__,maxJpegCodeSize);
1382 }
1383
1384
1385 /* Hold actual thumbnail and main image code sizes */
1386 size_t thumbCodeSize = 0, jpegCodeSize = 0;
1387 /* Temporary thumbnail code buffer */
1388 std::vector<uint8_t> thumbCode(maxThumbCodeSize);
1389
1390 YCbCrLayout yu12Thumb;
1391 ret = cropAndScaleThumbLocked(mYu12Frame, thumbSize, &yu12Thumb);
1392
1393 if (ret != 0) {
1394 return lfail(
1395 "%s: crop and scale thumbnail failed!", __FUNCTION__);
1396 }
1397
1398 /* Scale and crop main jpeg */
1399 ret = cropAndScaleLocked(mYu12Frame, jpegSize, &yu12Main);
1400
1401 if (ret != 0) {
1402 return lfail("%s: crop and scale main failed!", __FUNCTION__);
1403 }
1404
1405 /* Encode the thumbnail image */
1406 ret = encodeJpegYU12(thumbSize, yu12Thumb,
1407 thumbQuality, 0, 0,
1408 &thumbCode[0], maxThumbCodeSize, thumbCodeSize);
1409
1410 if (ret != 0) {
1411 return lfail("%s: encodeJpegYU12 failed with %d",__FUNCTION__, ret);
1412 }
1413
1414 /* Combine camera characteristics with request settings to form EXIF
1415 * metadata */
1416 common::V1_0::helper::CameraMetadata meta(parent->mCameraCharacteristics);
1417 meta.append(req.setting);
1418
1419 /* Generate EXIF object */
1420 std::unique_ptr<ExifUtils> utils(ExifUtils::create());
1421 /* Make sure it's initialized */
1422 utils->initialize();
1423
1424 utils->setFromMetadata(meta, jpegSize.width, jpegSize.height);
1425
1426 /* Check if we made a non-zero-sized thumbnail. Currently not possible
1427 * that we got this far and the code is size 0, but if this code moves
1428 * around it might become relevant again */
1429
1430 ret = utils->generateApp1(thumbCodeSize ? &thumbCode[0] : 0, thumbCodeSize);
1431
1432 if (!ret) {
1433 return lfail("%s: generating APP1 failed", __FUNCTION__);
1434 }
1435
1436 /* Get internal buffer */
1437 size_t exifDataSize = utils->getApp1Length();
1438 const uint8_t* exifData = utils->getApp1Buffer();
1439
1440 /* Lock the HAL jpeg code buffer */
1441 void *bufPtr = sHandleImporter.lock(
1442 *(halBuf.bufPtr), halBuf.usage, maxJpegCodeSize);
1443
1444 if (!bufPtr) {
1445 return lfail("%s: could not lock %zu bytes", __FUNCTION__, maxJpegCodeSize);
1446 }
1447
1448 /* Encode the main jpeg image */
1449 ret = encodeJpegYU12(jpegSize, yu12Main,
1450 jpegQuality, exifData, exifDataSize,
1451 bufPtr, maxJpegCodeSize, jpegCodeSize);
1452
1453 /* TODO: Not sure this belongs here, maybe better to pass jpegCodeSize out
1454 * and do this when returning buffer to parent */
1455 CameraBlob blob { CameraBlobId::JPEG, static_cast<uint32_t>(jpegCodeSize) };
1456 void *blobDst =
1457 reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(bufPtr) +
1458 maxJpegCodeSize -
1459 sizeof(CameraBlob));
1460 memcpy(blobDst, &blob, sizeof(CameraBlob));
1461
1462 /* Unlock the HAL jpeg code buffer */
1463 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
1464 if (relFence > 0) {
1465 halBuf.acquireFence = relFence;
1466 }
1467
1468 /* Check if our JPEG actually succeeded */
1469 if (ret != 0) {
1470 return lfail(
1471 "%s: encodeJpegYU12 failed with %d",__FUNCTION__, ret);
1472 }
1473
1474 ALOGV("%s: encoded JPEG (ret:%d) with Q:%d max size: %zu",
1475 __FUNCTION__, ret, jpegQuality, maxJpegCodeSize);
1476
1477 return 0;
1478}
1479
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001480bool ExternalCameraDeviceSession::OutputThread::threadLoop() {
1481 HalRequest req;
1482 auto parent = mParent.promote();
1483 if (parent == nullptr) {
1484 ALOGE("%s: session has been disconnected!", __FUNCTION__);
1485 return false;
1486 }
1487
1488 // TODO: maybe we need to setup a sensor thread to dq/enq v4l frames
1489 // regularly to prevent v4l buffer queue filled with stale buffers
1490 // when app doesn't program a preveiw request
1491 waitForNextRequest(&req);
1492 if (req.frameIn == nullptr) {
1493 // No new request, wait again
1494 return true;
1495 }
1496
1497 if (req.frameIn->mFourcc != V4L2_PIX_FMT_MJPEG) {
1498 ALOGE("%s: do not support V4L2 format %c%c%c%c", __FUNCTION__,
1499 req.frameIn->mFourcc & 0xFF,
1500 (req.frameIn->mFourcc >> 8) & 0xFF,
1501 (req.frameIn->mFourcc >> 16) & 0xFF,
1502 (req.frameIn->mFourcc >> 24) & 0xFF);
1503 parent->notifyError(
1504 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1505 return false;
1506 }
1507
1508 std::unique_lock<std::mutex> lk(mLock);
1509
1510 // Convert input V4L2 frame to YU12 of the same size
1511 // TODO: see if we can save some computation by converting to YV12 here
1512 uint8_t* inData;
1513 size_t inDataSize;
1514 req.frameIn->map(&inData, &inDataSize);
1515 // TODO: profile
1516 // TODO: in some special case maybe we can decode jpg directly to gralloc output?
1517 int res = libyuv::MJPGToI420(
1518 inData, inDataSize,
1519 static_cast<uint8_t*>(mYu12FrameLayout.y),
1520 mYu12FrameLayout.yStride,
1521 static_cast<uint8_t*>(mYu12FrameLayout.cb),
1522 mYu12FrameLayout.cStride,
1523 static_cast<uint8_t*>(mYu12FrameLayout.cr),
1524 mYu12FrameLayout.cStride,
1525 mYu12Frame->mWidth, mYu12Frame->mHeight,
1526 mYu12Frame->mWidth, mYu12Frame->mHeight);
1527
1528 if (res != 0) {
1529 // For some webcam, the first few V4L2 frames might be malformed...
1530 ALOGE("%s: Convert V4L2 frame to YU12 failed! res %d", __FUNCTION__, res);
1531 lk.unlock();
1532 Status st = parent->processCaptureRequestError(req);
1533 if (st != Status::OK) {
1534 ALOGE("%s: failed to process capture request error!", __FUNCTION__);
1535 parent->notifyError(
1536 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1537 return false;
1538 }
1539 return true;
1540 }
1541
1542 ALOGV("%s processing new request", __FUNCTION__);
1543 const int kSyncWaitTimeoutMs = 500;
1544 for (auto& halBuf : req.buffers) {
1545 if (halBuf.acquireFence != -1) {
1546 int ret = sync_wait(halBuf.acquireFence, kSyncWaitTimeoutMs);
1547 if (ret) {
1548 halBuf.fenceTimeout = true;
1549 } else {
1550 ::close(halBuf.acquireFence);
Yin-Chia Yeh1e089662018-02-02 15:57:58 -08001551 halBuf.acquireFence = -1;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001552 }
1553 }
1554
1555 if (halBuf.fenceTimeout) {
1556 continue;
1557 }
1558
1559 // Gralloc lockYCbCr the buffer
1560 switch (halBuf.format) {
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001561 case PixelFormat::BLOB: {
1562 int ret = createJpegLocked(halBuf, req);
1563
1564 if(ret != 0) {
1565 ALOGE("%s: createJpegLocked failed with %d",
1566 __FUNCTION__, ret);
1567 lk.unlock();
1568 parent->notifyError(
1569 /*frameNum*/req.frameNumber,
1570 /*stream*/-1,
1571 ErrorCode::ERROR_DEVICE);
1572
1573 return false;
1574 }
1575 } break;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001576 case PixelFormat::YCBCR_420_888:
1577 case PixelFormat::YV12: {
1578 IMapper::Rect outRect {0, 0,
1579 static_cast<int32_t>(halBuf.width),
1580 static_cast<int32_t>(halBuf.height)};
1581 YCbCrLayout outLayout = sHandleImporter.lockYCbCr(
1582 *(halBuf.bufPtr), halBuf.usage, outRect);
1583 ALOGV("%s: outLayout y %p cb %p cr %p y_str %d c_str %d c_step %d",
1584 __FUNCTION__, outLayout.y, outLayout.cb, outLayout.cr,
1585 outLayout.yStride, outLayout.cStride, outLayout.chromaStep);
1586
1587 // Convert to output buffer size/format
1588 uint32_t outputFourcc = getFourCcFromLayout(outLayout);
1589 ALOGV("%s: converting to format %c%c%c%c", __FUNCTION__,
1590 outputFourcc & 0xFF,
1591 (outputFourcc >> 8) & 0xFF,
1592 (outputFourcc >> 16) & 0xFF,
1593 (outputFourcc >> 24) & 0xFF);
1594
1595 YCbCrLayout cropAndScaled;
1596 int ret = cropAndScaleLocked(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001597 mYu12Frame,
1598 Size { halBuf.width, halBuf.height },
1599 &cropAndScaled);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001600 if (ret != 0) {
1601 ALOGE("%s: crop and scale failed!", __FUNCTION__);
1602 lk.unlock();
1603 parent->notifyError(
1604 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1605 return false;
1606 }
1607
1608 Size sz {halBuf.width, halBuf.height};
1609 ret = formatConvertLocked(cropAndScaled, outLayout, sz, outputFourcc);
1610 if (ret != 0) {
1611 ALOGE("%s: format coversion failed!", __FUNCTION__);
1612 lk.unlock();
1613 parent->notifyError(
1614 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1615 return false;
1616 }
1617 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
1618 if (relFence > 0) {
1619 halBuf.acquireFence = relFence;
1620 }
1621 } break;
1622 default:
1623 ALOGE("%s: unknown output format %x", __FUNCTION__, halBuf.format);
1624 lk.unlock();
1625 parent->notifyError(
1626 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1627 return false;
1628 }
1629 } // for each buffer
1630 mScaledYu12Frames.clear();
1631
1632 // Don't hold the lock while calling back to parent
1633 lk.unlock();
1634 Status st = parent->processCaptureResult(req);
1635 if (st != Status::OK) {
1636 ALOGE("%s: failed to process capture result!", __FUNCTION__);
1637 parent->notifyError(
1638 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1639 return false;
1640 }
1641 return true;
1642}
1643
1644Status ExternalCameraDeviceSession::OutputThread::allocateIntermediateBuffers(
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001645 const Size& v4lSize, const Size& thumbSize,
1646 const hidl_vec<Stream>& streams) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001647 std::lock_guard<std::mutex> lk(mLock);
1648 if (mScaledYu12Frames.size() != 0) {
1649 ALOGE("%s: intermediate buffer pool has %zu inflight buffers! (expect 0)",
1650 __FUNCTION__, mScaledYu12Frames.size());
1651 return Status::INTERNAL_ERROR;
1652 }
1653
1654 // Allocating intermediate YU12 frame
1655 if (mYu12Frame == nullptr || mYu12Frame->mWidth != v4lSize.width ||
1656 mYu12Frame->mHeight != v4lSize.height) {
1657 mYu12Frame.clear();
1658 mYu12Frame = new AllocatedFrame(v4lSize.width, v4lSize.height);
1659 int ret = mYu12Frame->allocate(&mYu12FrameLayout);
1660 if (ret != 0) {
1661 ALOGE("%s: allocating YU12 frame failed!", __FUNCTION__);
1662 return Status::INTERNAL_ERROR;
1663 }
1664 }
1665
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08001666 // Allocating intermediate YU12 thumbnail frame
1667 if (mYu12ThumbFrame == nullptr ||
1668 mYu12ThumbFrame->mWidth != thumbSize.width ||
1669 mYu12ThumbFrame->mHeight != thumbSize.height) {
1670 mYu12ThumbFrame.clear();
1671 mYu12ThumbFrame = new AllocatedFrame(thumbSize.width, thumbSize.height);
1672 int ret = mYu12ThumbFrame->allocate(&mYu12ThumbFrameLayout);
1673 if (ret != 0) {
1674 ALOGE("%s: allocating YU12 thumb frame failed!", __FUNCTION__);
1675 return Status::INTERNAL_ERROR;
1676 }
1677 }
1678
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001679 // Allocating scaled buffers
1680 for (const auto& stream : streams) {
1681 Size sz = {stream.width, stream.height};
1682 if (sz == v4lSize) {
1683 continue; // Don't need an intermediate buffer same size as v4lBuffer
1684 }
1685 if (mIntermediateBuffers.count(sz) == 0) {
1686 // Create new intermediate buffer
1687 sp<AllocatedFrame> buf = new AllocatedFrame(stream.width, stream.height);
1688 int ret = buf->allocate();
1689 if (ret != 0) {
1690 ALOGE("%s: allocating intermediate YU12 frame %dx%d failed!",
1691 __FUNCTION__, stream.width, stream.height);
1692 return Status::INTERNAL_ERROR;
1693 }
1694 mIntermediateBuffers[sz] = buf;
1695 }
1696 }
1697
1698 // Remove unconfigured buffers
1699 auto it = mIntermediateBuffers.begin();
1700 while (it != mIntermediateBuffers.end()) {
1701 bool configured = false;
1702 auto sz = it->first;
1703 for (const auto& stream : streams) {
1704 if (stream.width == sz.width && stream.height == sz.height) {
1705 configured = true;
1706 break;
1707 }
1708 }
1709 if (configured) {
1710 it++;
1711 } else {
1712 it = mIntermediateBuffers.erase(it);
1713 }
1714 }
1715 return Status::OK;
1716}
1717
1718Status ExternalCameraDeviceSession::OutputThread::submitRequest(const HalRequest& req) {
1719 std::lock_guard<std::mutex> lk(mLock);
1720 // TODO: reduce object copy in this path
1721 mRequestList.push_back(req);
1722 mRequestCond.notify_one();
1723 return Status::OK;
1724}
1725
1726void ExternalCameraDeviceSession::OutputThread::flush() {
1727 std::lock_guard<std::mutex> lk(mLock);
1728 // TODO: send buffer/request errors back to framework
1729 mRequestList.clear();
1730}
1731
1732void ExternalCameraDeviceSession::OutputThread::waitForNextRequest(HalRequest* out) {
1733 if (out == nullptr) {
1734 ALOGE("%s: out is null", __FUNCTION__);
1735 return;
1736 }
1737
1738 std::unique_lock<std::mutex> lk(mLock);
1739 while (mRequestList.empty()) {
1740 std::chrono::seconds timeout = std::chrono::seconds(kReqWaitTimeoutSec);
1741 auto st = mRequestCond.wait_for(lk, timeout);
1742 if (st == std::cv_status::timeout) {
1743 // no new request, return
1744 return;
1745 }
1746 }
1747 *out = mRequestList.front();
1748 mRequestList.pop_front();
1749}
1750
1751void ExternalCameraDeviceSession::cleanupBuffersLocked(int id) {
1752 for (auto& pair : mCirculatingBuffers.at(id)) {
1753 sHandleImporter.freeBuffer(pair.second);
1754 }
1755 mCirculatingBuffers[id].clear();
1756 mCirculatingBuffers.erase(id);
1757}
1758
1759void ExternalCameraDeviceSession::updateBufferCaches(const hidl_vec<BufferCache>& cachesToRemove) {
1760 Mutex::Autolock _l(mLock);
1761 for (auto& cache : cachesToRemove) {
1762 auto cbsIt = mCirculatingBuffers.find(cache.streamId);
1763 if (cbsIt == mCirculatingBuffers.end()) {
1764 // The stream could have been removed
1765 continue;
1766 }
1767 CirculatingBuffers& cbs = cbsIt->second;
1768 auto it = cbs.find(cache.bufferId);
1769 if (it != cbs.end()) {
1770 sHandleImporter.freeBuffer(it->second);
1771 cbs.erase(it);
1772 } else {
1773 ALOGE("%s: stream %d buffer %" PRIu64 " is not cached",
1774 __FUNCTION__, cache.streamId, cache.bufferId);
1775 }
1776 }
1777}
1778
1779bool ExternalCameraDeviceSession::isSupported(const Stream& stream) {
1780 int32_t ds = static_cast<int32_t>(stream.dataSpace);
1781 PixelFormat fmt = stream.format;
1782 uint32_t width = stream.width;
1783 uint32_t height = stream.height;
1784 // TODO: check usage flags
1785
1786 if (stream.streamType != StreamType::OUTPUT) {
1787 ALOGE("%s: does not support non-output stream type", __FUNCTION__);
1788 return false;
1789 }
1790
1791 if (stream.rotation != StreamRotation::ROTATION_0) {
1792 ALOGE("%s: does not support stream rotation", __FUNCTION__);
1793 return false;
1794 }
1795
1796 if (ds & Dataspace::DEPTH) {
1797 ALOGI("%s: does not support depth output", __FUNCTION__);
1798 return false;
1799 }
1800
1801 switch (fmt) {
1802 case PixelFormat::BLOB:
1803 if (ds != static_cast<int32_t>(Dataspace::V0_JFIF)) {
1804 ALOGI("%s: BLOB format does not support dataSpace %x", __FUNCTION__, ds);
1805 return false;
1806 }
1807 case PixelFormat::IMPLEMENTATION_DEFINED:
1808 case PixelFormat::YCBCR_420_888:
1809 case PixelFormat::YV12:
1810 // TODO: check what dataspace we can support here.
1811 // intentional no-ops.
1812 break;
1813 default:
1814 ALOGI("%s: does not support format %x", __FUNCTION__, fmt);
1815 return false;
1816 }
1817
1818 // Assume we can convert any V4L2 format to any of supported output format for now, i.e,
1819 // ignoring v4l2Fmt.fourcc for now. Might need more subtle check if we support more v4l format
1820 // in the futrue.
1821 for (const auto& v4l2Fmt : mSupportedFormats) {
1822 if (width == v4l2Fmt.width && height == v4l2Fmt.height) {
1823 return true;
1824 }
1825 }
1826 ALOGI("%s: resolution %dx%d is not supported", __FUNCTION__, width, height);
1827 return false;
1828}
1829
1830int ExternalCameraDeviceSession::v4l2StreamOffLocked() {
1831 if (!mV4l2Streaming) {
1832 return OK;
1833 }
1834
1835 {
1836 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1837 if (mNumDequeuedV4l2Buffers != 0) {
1838 ALOGE("%s: there are %zu inflight V4L buffers",
1839 __FUNCTION__, mNumDequeuedV4l2Buffers);
1840 return -1;
1841 }
1842 }
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08001843 mV4L2BufferCount = 0;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001844
1845 // VIDIOC_STREAMOFF
1846 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1847 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMOFF, &capture_type)) < 0) {
1848 ALOGE("%s: STREAMOFF failed: %s", __FUNCTION__, strerror(errno));
1849 return -errno;
1850 }
1851
1852 // VIDIOC_REQBUFS: clear buffers
1853 v4l2_requestbuffers req_buffers{};
1854 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1855 req_buffers.memory = V4L2_MEMORY_MMAP;
1856 req_buffers.count = 0;
1857 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
1858 ALOGE("%s: REQBUFS failed: %s", __FUNCTION__, strerror(errno));
1859 return -errno;
1860 }
1861
1862 mV4l2Streaming = false;
1863 return OK;
1864}
1865
1866int ExternalCameraDeviceSession::configureV4l2StreamLocked(const SupportedV4L2Format& v4l2Fmt) {
1867 int ret = v4l2StreamOffLocked();
1868 if (ret != OK) {
1869 ALOGE("%s: stop v4l2 streaming failed: ret %d", __FUNCTION__, ret);
1870 return ret;
1871 }
1872
1873 // VIDIOC_S_FMT w/h/fmt
1874 v4l2_format fmt;
1875 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1876 fmt.fmt.pix.width = v4l2Fmt.width;
1877 fmt.fmt.pix.height = v4l2Fmt.height;
1878 fmt.fmt.pix.pixelformat = v4l2Fmt.fourcc;
1879 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt));
1880 if (ret < 0) {
1881 ALOGE("%s: S_FMT ioctl failed: %s", __FUNCTION__, strerror(errno));
1882 return -errno;
1883 }
1884
1885 if (v4l2Fmt.width != fmt.fmt.pix.width || v4l2Fmt.height != fmt.fmt.pix.height ||
1886 v4l2Fmt.fourcc != fmt.fmt.pix.pixelformat) {
1887 ALOGE("%s: S_FMT expect %c%c%c%c %dx%d, got %c%c%c%c %dx%d instead!", __FUNCTION__,
1888 v4l2Fmt.fourcc & 0xFF,
1889 (v4l2Fmt.fourcc >> 8) & 0xFF,
1890 (v4l2Fmt.fourcc >> 16) & 0xFF,
1891 (v4l2Fmt.fourcc >> 24) & 0xFF,
1892 v4l2Fmt.width, v4l2Fmt.height,
1893 fmt.fmt.pix.pixelformat & 0xFF,
1894 (fmt.fmt.pix.pixelformat >> 8) & 0xFF,
1895 (fmt.fmt.pix.pixelformat >> 16) & 0xFF,
1896 (fmt.fmt.pix.pixelformat >> 24) & 0xFF,
1897 fmt.fmt.pix.width, fmt.fmt.pix.height);
1898 return -EINVAL;
1899 }
1900 uint32_t bufferSize = fmt.fmt.pix.sizeimage;
1901 ALOGI("%s: V4L2 buffer size is %d", __FUNCTION__, bufferSize);
1902
1903 float maxFps = -1.f;
1904 float fps = 1000.f;
1905 const float kDefaultFps = 30.f;
1906 // Try to pick the slowest fps that is at least 30
1907 for (const auto& f : v4l2Fmt.frameRates) {
1908 if (maxFps < f) {
1909 maxFps = f;
1910 }
1911 if (f >= kDefaultFps && f < fps) {
1912 fps = f;
1913 }
1914 }
1915 if (fps == 1000.f) {
1916 fps = maxFps;
1917 }
1918
1919 // VIDIOC_G_PARM/VIDIOC_S_PARM: set fps
1920 v4l2_streamparm streamparm = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
1921 // The following line checks that the driver knows about framerate get/set.
1922 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_G_PARM, &streamparm)) >= 0) {
1923 // Now check if the device is able to accept a capture framerate set.
1924 if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
1925 // |frame_rate| is float, approximate by a fraction.
1926 const int kFrameRatePrecision = 10000;
1927 streamparm.parm.capture.timeperframe.numerator = kFrameRatePrecision;
1928 streamparm.parm.capture.timeperframe.denominator =
1929 (fps * kFrameRatePrecision);
1930
1931 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_PARM, &streamparm)) < 0) {
1932 ALOGE("%s: failed to set framerate to %f", __FUNCTION__, fps);
1933 return UNKNOWN_ERROR;
1934 }
1935 }
1936 }
1937 float retFps = streamparm.parm.capture.timeperframe.denominator /
1938 streamparm.parm.capture.timeperframe.numerator;
1939 if (std::fabs(fps - retFps) > std::numeric_limits<float>::epsilon()) {
1940 ALOGE("%s: expect fps %f, got %f instead", __FUNCTION__, fps, retFps);
1941 return BAD_VALUE;
1942 }
1943
Yin-Chia Yeh53f4cb12018-01-29 10:31:45 -08001944 uint32_t v4lBufferCount = (fps >= kDefaultFps) ?
1945 mCfg.numVideoBuffers : mCfg.numStillBuffers;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001946 // VIDIOC_REQBUFS: create buffers
1947 v4l2_requestbuffers req_buffers{};
1948 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1949 req_buffers.memory = V4L2_MEMORY_MMAP;
1950 req_buffers.count = v4lBufferCount;
1951 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
1952 ALOGE("%s: VIDIOC_REQBUFS failed: %s", __FUNCTION__, strerror(errno));
1953 return -errno;
1954 }
1955
1956 // Driver can indeed return more buffer if it needs more to operate
1957 if (req_buffers.count < v4lBufferCount) {
1958 ALOGE("%s: VIDIOC_REQBUFS expected %d buffers, got %d instead",
1959 __FUNCTION__, v4lBufferCount, req_buffers.count);
1960 return NO_MEMORY;
1961 }
1962
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08001963 // VIDIOC_QUERYBUF: get buffer offset in the V4L2 fd
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001964 // VIDIOC_QBUF: send buffer to driver
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08001965 mV4L2BufferCount = req_buffers.count;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001966 for (uint32_t i = 0; i < req_buffers.count; i++) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001967 v4l2_buffer buffer = {
1968 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
1969 .index = i,
1970 .memory = V4L2_MEMORY_MMAP};
1971
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08001972 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QUERYBUF, &buffer)) < 0) {
1973 ALOGE("%s: QUERYBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
1974 return -errno;
1975 }
1976
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001977 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1978 ALOGE("%s: QBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
1979 return -errno;
1980 }
1981 }
1982
1983 // VIDIOC_STREAMON: start streaming
1984 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1985 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type)) < 0) {
1986 ALOGE("%s: VIDIOC_STREAMON failed: %s", __FUNCTION__, strerror(errno));
1987 return -errno;
1988 }
1989
1990 // Swallow first few frames after streamOn to account for bad frames from some devices
1991 for (int i = 0; i < kBadFramesAfterStreamOn; i++) {
1992 v4l2_buffer buffer{};
1993 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1994 buffer.memory = V4L2_MEMORY_MMAP;
1995 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
1996 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
1997 return -errno;
1998 }
1999
2000 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2001 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, buffer.index, strerror(errno));
2002 return -errno;
2003 }
2004 }
2005
2006 mV4l2StreamingFmt = v4l2Fmt;
2007 mV4l2Streaming = true;
2008 return OK;
2009}
2010
2011sp<V4L2Frame> ExternalCameraDeviceSession::dequeueV4l2FrameLocked() {
2012 sp<V4L2Frame> ret = nullptr;
2013
2014 {
2015 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002016 if (mNumDequeuedV4l2Buffers == mV4L2BufferCount) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002017 std::chrono::seconds timeout = std::chrono::seconds(kBufferWaitTimeoutSec);
2018 mLock.unlock();
2019 auto st = mV4L2BufferReturned.wait_for(lk, timeout);
2020 mLock.lock();
2021 if (st == std::cv_status::timeout) {
2022 ALOGE("%s: wait for V4L2 buffer return timeout!", __FUNCTION__);
2023 return ret;
2024 }
2025 }
2026 }
2027
2028 v4l2_buffer buffer{};
2029 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2030 buffer.memory = V4L2_MEMORY_MMAP;
2031 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
2032 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
2033 return ret;
2034 }
2035
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002036 if (buffer.index >= mV4L2BufferCount) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002037 ALOGE("%s: Invalid buffer id: %d", __FUNCTION__, buffer.index);
2038 return ret;
2039 }
2040
2041 if (buffer.flags & V4L2_BUF_FLAG_ERROR) {
2042 ALOGE("%s: v4l2 buf error! buf flag 0x%x", __FUNCTION__, buffer.flags);
2043 // TODO: try to dequeue again
2044 }
2045
2046 {
2047 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2048 mNumDequeuedV4l2Buffers++;
2049 }
2050 return new V4L2Frame(
2051 mV4l2StreamingFmt.width, mV4l2StreamingFmt.height, mV4l2StreamingFmt.fourcc,
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002052 buffer.index, mV4l2Fd.get(), buffer.bytesused, buffer.m.offset);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002053}
2054
2055void ExternalCameraDeviceSession::enqueueV4l2Frame(const sp<V4L2Frame>& frame) {
2056 Mutex::Autolock _l(mLock);
2057 frame->unmap();
2058 v4l2_buffer buffer{};
2059 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2060 buffer.memory = V4L2_MEMORY_MMAP;
2061 buffer.index = frame->mBufferIndex;
2062 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
2063 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, frame->mBufferIndex, strerror(errno));
2064 return;
2065 }
2066
2067 {
2068 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
2069 mNumDequeuedV4l2Buffers--;
2070 mV4L2BufferReturned.notify_one();
2071 }
2072}
2073
2074Status ExternalCameraDeviceSession::configureStreams(
2075 const V3_2::StreamConfiguration& config, V3_3::HalStreamConfiguration* out) {
2076 if (config.operationMode != StreamConfigurationMode::NORMAL_MODE) {
2077 ALOGE("%s: unsupported operation mode: %d", __FUNCTION__, config.operationMode);
2078 return Status::ILLEGAL_ARGUMENT;
2079 }
2080
2081 if (config.streams.size() == 0) {
2082 ALOGE("%s: cannot configure zero stream", __FUNCTION__);
2083 return Status::ILLEGAL_ARGUMENT;
2084 }
2085
2086 int numProcessedStream = 0;
2087 int numStallStream = 0;
2088 for (const auto& stream : config.streams) {
2089 // Check if the format/width/height combo is supported
2090 if (!isSupported(stream)) {
2091 return Status::ILLEGAL_ARGUMENT;
2092 }
2093 if (stream.format == PixelFormat::BLOB) {
2094 numStallStream++;
2095 } else {
2096 numProcessedStream++;
2097 }
2098 }
2099
2100 if (numProcessedStream > kMaxProcessedStream) {
2101 ALOGE("%s: too many processed streams (expect <= %d, got %d)", __FUNCTION__,
2102 kMaxProcessedStream, numProcessedStream);
2103 return Status::ILLEGAL_ARGUMENT;
2104 }
2105
2106 if (numStallStream > kMaxStallStream) {
2107 ALOGE("%s: too many stall streams (expect <= %d, got %d)", __FUNCTION__,
2108 kMaxStallStream, numStallStream);
2109 return Status::ILLEGAL_ARGUMENT;
2110 }
2111
2112 Status status = initStatus();
2113 if (status != Status::OK) {
2114 return status;
2115 }
2116
2117 Mutex::Autolock _l(mLock);
2118 if (!mInflightFrames.empty()) {
2119 ALOGE("%s: trying to configureStreams while there are still %zu inflight frames!",
2120 __FUNCTION__, mInflightFrames.size());
2121 return Status::INTERNAL_ERROR;
2122 }
2123
2124 // Add new streams
2125 for (const auto& stream : config.streams) {
2126 if (mStreamMap.count(stream.id) == 0) {
2127 mStreamMap[stream.id] = stream;
2128 mCirculatingBuffers.emplace(stream.id, CirculatingBuffers{});
2129 }
2130 }
2131
2132 // Cleanup removed streams
2133 for(auto it = mStreamMap.begin(); it != mStreamMap.end();) {
2134 int id = it->first;
2135 bool found = false;
2136 for (const auto& stream : config.streams) {
2137 if (id == stream.id) {
2138 found = true;
2139 break;
2140 }
2141 }
2142 if (!found) {
2143 // Unmap all buffers of deleted stream
2144 cleanupBuffersLocked(id);
2145 it = mStreamMap.erase(it);
2146 } else {
2147 ++it;
2148 }
2149 }
2150
2151 // Now select a V4L2 format to produce all output streams
2152 float desiredAr = (mCroppingType == VERTICAL) ? kMaxAspectRatio : kMinAspectRatio;
2153 uint32_t maxDim = 0;
2154 for (const auto& stream : config.streams) {
2155 float aspectRatio = ASPECT_RATIO(stream);
2156 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2157 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2158 desiredAr = aspectRatio;
2159 }
2160
2161 // The dimension that's not cropped
2162 uint32_t dim = (mCroppingType == VERTICAL) ? stream.width : stream.height;
2163 if (dim > maxDim) {
2164 maxDim = dim;
2165 }
2166 }
2167 // Find the smallest format that matches the desired aspect ratio and is wide/high enough
2168 SupportedV4L2Format v4l2Fmt {.width = 0, .height = 0};
2169 for (const auto& fmt : mSupportedFormats) {
2170 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2171 if (dim >= maxDim) {
2172 float aspectRatio = ASPECT_RATIO(fmt);
2173 if (isAspectRatioClose(aspectRatio, desiredAr)) {
2174 v4l2Fmt = fmt;
2175 // since mSupportedFormats is sorted by width then height, the first matching fmt
2176 // will be the smallest one with matching aspect ratio
2177 break;
2178 }
2179 }
2180 }
2181 if (v4l2Fmt.width == 0) {
2182 // Cannot find exact good aspect ratio candidate, try to find a close one
2183 for (const auto& fmt : mSupportedFormats) {
2184 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
2185 if (dim >= maxDim) {
2186 float aspectRatio = ASPECT_RATIO(fmt);
2187 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
2188 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
2189 v4l2Fmt = fmt;
2190 break;
2191 }
2192 }
2193 }
2194 }
2195
2196 if (v4l2Fmt.width == 0) {
2197 ALOGE("%s: unable to find a resolution matching (%s at least %d, aspect ratio %f)"
2198 , __FUNCTION__, (mCroppingType == VERTICAL) ? "width" : "height",
2199 maxDim, desiredAr);
2200 return Status::ILLEGAL_ARGUMENT;
2201 }
2202
2203 if (configureV4l2StreamLocked(v4l2Fmt) != 0) {
2204 ALOGE("V4L configuration failed!, format:%c%c%c%c, w %d, h %d",
2205 v4l2Fmt.fourcc & 0xFF,
2206 (v4l2Fmt.fourcc >> 8) & 0xFF,
2207 (v4l2Fmt.fourcc >> 16) & 0xFF,
2208 (v4l2Fmt.fourcc >> 24) & 0xFF,
2209 v4l2Fmt.width, v4l2Fmt.height);
2210 return Status::INTERNAL_ERROR;
2211 }
2212
2213 Size v4lSize = {v4l2Fmt.width, v4l2Fmt.height};
Yuriy Romanenkoe932f1b2018-01-19 16:12:00 -08002214 Size thumbSize { 0, 0 };
2215 camera_metadata_ro_entry entry =
2216 mCameraCharacteristics.find(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES);
2217 for(uint32_t i = 0; i < entry.count; i += 2) {
2218 Size sz { static_cast<uint32_t>(entry.data.i32[i]),
2219 static_cast<uint32_t>(entry.data.i32[i+1]) };
2220 if(sz.width * sz.height > thumbSize.width * thumbSize.height) {
2221 thumbSize = sz;
2222 }
2223 }
2224
2225 if (thumbSize.width * thumbSize.height == 0) {
2226 ALOGE("%s: non-zero thumbnail size not available", __FUNCTION__);
2227 return Status::INTERNAL_ERROR;
2228 }
2229
2230 status = mOutputThread->allocateIntermediateBuffers(v4lSize,
2231 mMaxThumbResolution, config.streams);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002232 if (status != Status::OK) {
2233 ALOGE("%s: allocating intermediate buffers failed!", __FUNCTION__);
2234 return status;
2235 }
2236
2237 out->streams.resize(config.streams.size());
2238 for (size_t i = 0; i < config.streams.size(); i++) {
2239 out->streams[i].overrideDataSpace = config.streams[i].dataSpace;
2240 out->streams[i].v3_2.id = config.streams[i].id;
2241 // TODO: double check should we add those CAMERA flags
2242 mStreamMap[config.streams[i].id].usage =
2243 out->streams[i].v3_2.producerUsage = config.streams[i].usage |
2244 BufferUsage::CPU_WRITE_OFTEN |
2245 BufferUsage::CAMERA_OUTPUT;
2246 out->streams[i].v3_2.consumerUsage = 0;
Yuriy Romanenko9cdd6f92018-01-31 15:59:20 -08002247 out->streams[i].v3_2.maxBuffers = mV4L2BufferCount;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002248
2249 switch (config.streams[i].format) {
2250 case PixelFormat::BLOB:
2251 case PixelFormat::YCBCR_420_888:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002252 case PixelFormat::YV12: // Used by SurfaceTexture
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002253 // No override
2254 out->streams[i].v3_2.overrideFormat = config.streams[i].format;
2255 break;
2256 case PixelFormat::IMPLEMENTATION_DEFINED:
2257 // Override based on VIDEO or not
2258 out->streams[i].v3_2.overrideFormat =
2259 (config.streams[i].usage & BufferUsage::VIDEO_ENCODER) ?
2260 PixelFormat::YCBCR_420_888 : PixelFormat::YV12;
2261 // Save overridden formt in mStreamMap
2262 mStreamMap[config.streams[i].id].format = out->streams[i].v3_2.overrideFormat;
2263 break;
2264 default:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002265 ALOGE("%s: unsupported format 0x%x", __FUNCTION__, config.streams[i].format);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002266 return Status::ILLEGAL_ARGUMENT;
2267 }
2268 }
2269
2270 mFirstRequest = true;
2271 return Status::OK;
2272}
2273
2274bool ExternalCameraDeviceSession::isClosed() {
2275 Mutex::Autolock _l(mLock);
2276 return mClosed;
2277}
2278
2279#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
2280#define UPDATE(md, tag, data, size) \
2281do { \
2282 if ((md).update((tag), (data), (size))) { \
2283 ALOGE("Update " #tag " failed!"); \
2284 return BAD_VALUE; \
2285 } \
2286} while (0)
2287
2288status_t ExternalCameraDeviceSession::initDefaultRequests() {
2289 ::android::hardware::camera::common::V1_0::helper::CameraMetadata md;
2290
2291 const uint8_t aberrationMode = ANDROID_COLOR_CORRECTION_ABERRATION_MODE_OFF;
2292 UPDATE(md, ANDROID_COLOR_CORRECTION_ABERRATION_MODE, &aberrationMode, 1);
2293
2294 const int32_t exposureCompensation = 0;
2295 UPDATE(md, ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION, &exposureCompensation, 1);
2296
2297 const uint8_t videoStabilizationMode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
2298 UPDATE(md, ANDROID_CONTROL_VIDEO_STABILIZATION_MODE, &videoStabilizationMode, 1);
2299
2300 const uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO;
2301 UPDATE(md, ANDROID_CONTROL_AWB_MODE, &awbMode, 1);
2302
2303 const uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON;
2304 UPDATE(md, ANDROID_CONTROL_AE_MODE, &aeMode, 1);
2305
2306 const uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
2307 UPDATE(md, ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
2308
2309 const uint8_t afMode = ANDROID_CONTROL_AF_MODE_AUTO;
2310 UPDATE(md, ANDROID_CONTROL_AF_MODE, &afMode, 1);
2311
2312 const uint8_t afTrigger = ANDROID_CONTROL_AF_TRIGGER_IDLE;
2313 UPDATE(md, ANDROID_CONTROL_AF_TRIGGER, &afTrigger, 1);
2314
2315 const uint8_t sceneMode = ANDROID_CONTROL_SCENE_MODE_DISABLED;
2316 UPDATE(md, ANDROID_CONTROL_SCENE_MODE, &sceneMode, 1);
2317
2318 const uint8_t effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF;
2319 UPDATE(md, ANDROID_CONTROL_EFFECT_MODE, &effectMode, 1);
2320
2321 const uint8_t flashMode = ANDROID_FLASH_MODE_OFF;
2322 UPDATE(md, ANDROID_FLASH_MODE, &flashMode, 1);
2323
2324 const int32_t thumbnailSize[] = {240, 180};
2325 UPDATE(md, ANDROID_JPEG_THUMBNAIL_SIZE, thumbnailSize, 2);
2326
2327 const uint8_t jpegQuality = 90;
2328 UPDATE(md, ANDROID_JPEG_QUALITY, &jpegQuality, 1);
2329 UPDATE(md, ANDROID_JPEG_THUMBNAIL_QUALITY, &jpegQuality, 1);
2330
2331 const int32_t jpegOrientation = 0;
2332 UPDATE(md, ANDROID_JPEG_ORIENTATION, &jpegOrientation, 1);
2333
2334 const uint8_t oisMode = ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF;
2335 UPDATE(md, ANDROID_LENS_OPTICAL_STABILIZATION_MODE, &oisMode, 1);
2336
2337 const uint8_t nrMode = ANDROID_NOISE_REDUCTION_MODE_OFF;
2338 UPDATE(md, ANDROID_NOISE_REDUCTION_MODE, &nrMode, 1);
2339
2340 const uint8_t fdMode = ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
2341 UPDATE(md, ANDROID_STATISTICS_FACE_DETECT_MODE, &fdMode, 1);
2342
2343 const uint8_t hotpixelMode = ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF;
2344 UPDATE(md, ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE, &hotpixelMode, 1);
2345
2346 bool support30Fps = false;
2347 int32_t maxFps = std::numeric_limits<int32_t>::min();
2348 for (const auto& supportedFormat : mSupportedFormats) {
2349 for (const auto& frameRate : supportedFormat.frameRates) {
2350 int32_t framerateInt = static_cast<int32_t>(frameRate);
2351 if (maxFps < framerateInt) {
2352 maxFps = framerateInt;
2353 }
2354 if (framerateInt == 30) {
2355 support30Fps = true;
2356 break;
2357 }
2358 }
2359 if (support30Fps) {
2360 break;
2361 }
2362 }
2363 int32_t defaultFramerate = support30Fps ? 30 : maxFps;
2364 int32_t defaultFpsRange[] = {defaultFramerate, defaultFramerate};
2365 UPDATE(md, ANDROID_CONTROL_AE_TARGET_FPS_RANGE, defaultFpsRange, ARRAY_SIZE(defaultFpsRange));
2366
2367 uint8_t antibandingMode = ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO;
2368 UPDATE(md, ANDROID_CONTROL_AE_ANTIBANDING_MODE, &antibandingMode, 1);
2369
2370 const uint8_t controlMode = ANDROID_CONTROL_MODE_AUTO;
2371 UPDATE(md, ANDROID_CONTROL_MODE, &controlMode, 1);
2372
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002373 auto requestTemplates = hidl_enum_iterator<RequestTemplate>();
2374 for (RequestTemplate type : requestTemplates) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002375 ::android::hardware::camera::common::V1_0::helper::CameraMetadata mdCopy = md;
2376 uint8_t intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2377 switch (type) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002378 case RequestTemplate::PREVIEW:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002379 intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2380 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002381 case RequestTemplate::STILL_CAPTURE:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002382 intent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE;
2383 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002384 case RequestTemplate::VIDEO_RECORD:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002385 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD;
2386 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08002387 case RequestTemplate::VIDEO_SNAPSHOT:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002388 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT;
2389 break;
2390 default:
Yuriy Romanenko083de0c2018-01-26 16:05:54 -08002391 ALOGV("%s: unsupported RequestTemplate type %d", __FUNCTION__, type);
2392 continue;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002393 }
2394 UPDATE(mdCopy, ANDROID_CONTROL_CAPTURE_INTENT, &intent, 1);
2395
2396 camera_metadata_t* rawMd = mdCopy.release();
2397 CameraMetadata hidlMd;
2398 hidlMd.setToExternal(
2399 (uint8_t*) rawMd, get_camera_metadata_size(rawMd));
2400 mDefaultRequests[type] = hidlMd;
2401 free_camera_metadata(rawMd);
2402 }
2403
2404 return OK;
2405}
2406
2407status_t ExternalCameraDeviceSession::fillCaptureResult(
2408 common::V1_0::helper::CameraMetadata &md, nsecs_t timestamp) {
2409 // android.control
2410 // For USB camera, we don't know the AE state. Set the state to converged to
2411 // indicate the frame should be good to use. Then apps don't have to wait the
2412 // AE state.
2413 const uint8_t aeState = ANDROID_CONTROL_AE_STATE_CONVERGED;
2414 UPDATE(md, ANDROID_CONTROL_AE_STATE, &aeState, 1);
2415
2416 const uint8_t ae_lock = ANDROID_CONTROL_AE_LOCK_OFF;
2417 UPDATE(md, ANDROID_CONTROL_AE_LOCK, &ae_lock, 1);
2418
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002419 bool afTrigger = mAfTrigger;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002420 if (md.exists(ANDROID_CONTROL_AF_TRIGGER)) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002421 Mutex::Autolock _l(mLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002422 camera_metadata_entry entry = md.find(ANDROID_CONTROL_AF_TRIGGER);
2423 if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_START) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002424 mAfTrigger = afTrigger = true;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002425 } else if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_CANCEL) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002426 mAfTrigger = afTrigger = false;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002427 }
2428 }
2429
2430 // For USB camera, the USB camera handles everything and we don't have control
2431 // over AF. We only simply fake the AF metadata based on the request
2432 // received here.
2433 uint8_t afState;
2434 if (afTrigger) {
2435 afState = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
2436 } else {
2437 afState = ANDROID_CONTROL_AF_STATE_INACTIVE;
2438 }
2439 UPDATE(md, ANDROID_CONTROL_AF_STATE, &afState, 1);
2440
2441 // Set AWB state to converged to indicate the frame should be good to use.
2442 const uint8_t awbState = ANDROID_CONTROL_AWB_STATE_CONVERGED;
2443 UPDATE(md, ANDROID_CONTROL_AWB_STATE, &awbState, 1);
2444
2445 const uint8_t awbLock = ANDROID_CONTROL_AWB_LOCK_OFF;
2446 UPDATE(md, ANDROID_CONTROL_AWB_LOCK, &awbLock, 1);
2447
2448 camera_metadata_ro_entry active_array_size =
2449 mCameraCharacteristics.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
2450
2451 if (active_array_size.count == 0) {
2452 ALOGE("%s: cannot find active array size!", __FUNCTION__);
2453 return -EINVAL;
2454 }
2455
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08002456 const uint8_t flashState = ANDROID_FLASH_STATE_UNAVAILABLE;
2457 UPDATE(md, ANDROID_FLASH_STATE, &flashState, 1);
2458
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002459 // android.scaler
2460 const int32_t crop_region[] = {
2461 active_array_size.data.i32[0], active_array_size.data.i32[1],
2462 active_array_size.data.i32[2], active_array_size.data.i32[3],
2463 };
2464 UPDATE(md, ANDROID_SCALER_CROP_REGION, crop_region, ARRAY_SIZE(crop_region));
2465
2466 // android.sensor
2467 UPDATE(md, ANDROID_SENSOR_TIMESTAMP, &timestamp, 1);
2468
2469 // android.statistics
2470 const uint8_t lensShadingMapMode = ANDROID_STATISTICS_LENS_SHADING_MAP_MODE_OFF;
2471 UPDATE(md, ANDROID_STATISTICS_LENS_SHADING_MAP_MODE, &lensShadingMapMode, 1);
2472
2473 const uint8_t sceneFlicker = ANDROID_STATISTICS_SCENE_FLICKER_NONE;
2474 UPDATE(md, ANDROID_STATISTICS_SCENE_FLICKER, &sceneFlicker, 1);
2475
2476 return OK;
2477}
2478
2479#undef ARRAY_SIZE
2480#undef UPDATE
2481
Yin-Chia Yeh19030592017-10-19 17:30:11 -07002482} // namespace implementation
2483} // namespace V3_4
2484} // namespace device
2485} // namespace camera
2486} // namespace hardware
2487} // namespace android