blob: 0714ee2bed9da6df3ff6175a3575413252af6484 [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"
24#include "algorithm"
25#include <utils/Timers.h>
26#include <cmath>
27#include <linux/videodev2.h>
28#include <sync/sync.h>
29
30#define HAVE_JPEG // required for libyuv.h to export MJPEG decode APIs
31#include <libyuv.h>
32
33namespace android {
34namespace hardware {
35namespace camera {
36namespace device {
37namespace V3_4 {
38namespace implementation {
39
40// Size of request/result metadata fast message queue. Change to 0 to always use hwbinder buffer.
41static constexpr size_t kMetadataMsgQueueSize = 1 << 20 /* 1MB */;
42const int ExternalCameraDeviceSession::kMaxProcessedStream;
43const int ExternalCameraDeviceSession::kMaxStallStream;
44const Size kMaxVideoSize = {1920, 1088}; // Maybe this should be programmable
45const int kNumVideoBuffers = 4; // number of v4l2 buffers when streaming <= kMaxVideoSize
46const int kNumStillBuffers = 2; // number of v4l2 buffers when streaming > kMaxVideoSize
47const int kBadFramesAfterStreamOn = 1; // drop x frames after streamOn to get rid of some initial
48 // bad frames. TODO: develop a better bad frame detection
49 // method
50
51// Aspect ratio is defined as width/height here and ExternalCameraDevice
52// will guarantee all supported sizes has width >= height (so aspect ratio >= 1.0)
53#define ASPECT_RATIO(sz) (static_cast<float>((sz).width) / (sz).height)
54const float kMaxAspectRatio = std::numeric_limits<float>::max();
55const float kMinAspectRatio = 1.f;
56
57HandleImporter ExternalCameraDeviceSession::sHandleImporter;
58
59bool isAspectRatioClose(float ar1, float ar2) {
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -080060 const float kAspectRatioMatchThres = 0.025f; // This threshold is good enough to distinguish
Yin-Chia Yeh19030592017-10-19 17:30:11 -070061 // 4:3/16:9/20:9
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -080062 // 1.33 / 1.78 / 2
Yin-Chia Yeh19030592017-10-19 17:30:11 -070063 return (std::abs(ar1 - ar2) < kAspectRatioMatchThres);
64}
65
66ExternalCameraDeviceSession::ExternalCameraDeviceSession(
67 const sp<ICameraDeviceCallback>& callback,
68 const std::vector<SupportedV4L2Format>& supportedFormats,
69 const common::V1_0::helper::CameraMetadata& chars,
70 unique_fd v4l2Fd) :
71 mCallback(callback),
72 mCameraCharacteristics(chars),
73 mV4l2Fd(std::move(v4l2Fd)),
74 mSupportedFormats(sortFormats(supportedFormats)),
75 mCroppingType(initCroppingType(mSupportedFormats)),
76 mOutputThread(new OutputThread(this, mCroppingType)) {
77 mInitFail = initialize();
78}
79
80std::vector<SupportedV4L2Format> ExternalCameraDeviceSession::sortFormats(
81 const std::vector<SupportedV4L2Format>& inFmts) {
82 std::vector<SupportedV4L2Format> fmts = inFmts;
83 std::sort(fmts.begin(), fmts.end(),
84 [](const SupportedV4L2Format& a, const SupportedV4L2Format& b) -> bool {
85 if (a.width == b.width) {
86 return a.height < b.height;
87 }
88 return a.width < b.width;
89 });
90 return fmts;
91}
92
93CroppingType ExternalCameraDeviceSession::initCroppingType(
94 const std::vector<SupportedV4L2Format>& sortedFmts) {
95 const auto& maxSize = sortedFmts[sortedFmts.size() - 1];
96 float maxSizeAr = ASPECT_RATIO(maxSize);
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -080097 float minAr = kMaxAspectRatio;
98 float maxAr = kMinAspectRatio;
Yin-Chia Yeh19030592017-10-19 17:30:11 -070099 for (const auto& fmt : sortedFmts) {
100 float ar = ASPECT_RATIO(fmt);
101 if (ar < minAr) {
102 minAr = ar;
103 }
104 if (ar > maxAr) {
105 maxAr = ar;
106 }
107 }
108
109 CroppingType ct = VERTICAL;
110 if (isAspectRatioClose(maxSizeAr, maxAr)) {
111 // Ex: 16:9 sensor, cropping horizontally to get to 4:3
112 ct = HORIZONTAL;
113 } else if (isAspectRatioClose(maxSizeAr, minAr)) {
114 // Ex: 4:3 sensor, cropping vertically to get to 16:9
115 ct = VERTICAL;
116 } else {
117 ALOGI("%s: camera maxSizeAr %f is not close to minAr %f or maxAr %f",
118 __FUNCTION__, maxSizeAr, minAr, maxAr);
119 if ((maxSizeAr - minAr) < (maxAr - maxSizeAr)) {
120 ct = VERTICAL;
121 } else {
122 ct = HORIZONTAL;
123 }
124 }
125 ALOGI("%s: camera croppingType is %d", __FUNCTION__, ct);
126 return ct;
127}
128
129
130bool ExternalCameraDeviceSession::initialize() {
131 if (mV4l2Fd.get() < 0) {
132 ALOGE("%s: invalid v4l2 device fd %d!", __FUNCTION__, mV4l2Fd.get());
133 return true;
134 }
135
136 status_t status = initDefaultRequests();
137 if (status != OK) {
138 ALOGE("%s: init default requests failed!", __FUNCTION__);
139 return true;
140 }
141
142 mRequestMetadataQueue = std::make_unique<RequestMetadataQueue>(
143 kMetadataMsgQueueSize, false /* non blocking */);
144 if (!mRequestMetadataQueue->isValid()) {
145 ALOGE("%s: invalid request fmq", __FUNCTION__);
146 return true;
147 }
148 mResultMetadataQueue = std::make_shared<RequestMetadataQueue>(
149 kMetadataMsgQueueSize, false /* non blocking */);
150 if (!mResultMetadataQueue->isValid()) {
151 ALOGE("%s: invalid result fmq", __FUNCTION__);
152 return true;
153 }
154
155 // TODO: check is PRIORITY_DISPLAY enough?
156 mOutputThread->run("ExtCamOut", PRIORITY_DISPLAY);
157 return false;
158}
159
160Status ExternalCameraDeviceSession::initStatus() const {
161 Mutex::Autolock _l(mLock);
162 Status status = Status::OK;
163 if (mInitFail || mClosed) {
164 ALOGI("%s: sesssion initFailed %d closed %d", __FUNCTION__, mInitFail, mClosed);
165 status = Status::INTERNAL_ERROR;
166 }
167 return status;
168}
169
170ExternalCameraDeviceSession::~ExternalCameraDeviceSession() {
171 if (!isClosed()) {
172 ALOGE("ExternalCameraDeviceSession deleted before close!");
173 close();
174 }
175}
176
177void ExternalCameraDeviceSession::dumpState(const native_handle_t*) {
178 // TODO: b/72261676 dump more runtime information
179}
180
181Return<void> ExternalCameraDeviceSession::constructDefaultRequestSettings(
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800182 V3_2::RequestTemplate type,
183 V3_2::ICameraDeviceSession::constructDefaultRequestSettings_cb _hidl_cb) {
184 V3_2::CameraMetadata outMetadata;
185 Status status = constructDefaultRequestSettingsRaw(
186 static_cast<RequestTemplate>(type), &outMetadata);
187 _hidl_cb(status, outMetadata);
188 return Void();
189}
190
191Return<void> ExternalCameraDeviceSession::constructDefaultRequestSettings_3_4(
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700192 RequestTemplate type,
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800193 ICameraDeviceSession::constructDefaultRequestSettings_cb _hidl_cb) {
194 V3_2::CameraMetadata outMetadata;
195 Status status = constructDefaultRequestSettingsRaw(type, &outMetadata);
196 _hidl_cb(status, outMetadata);
197 return Void();
198}
199
200Status ExternalCameraDeviceSession::constructDefaultRequestSettingsRaw(RequestTemplate type,
201 V3_2::CameraMetadata *outMetadata) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700202 CameraMetadata emptyMd;
203 Status status = initStatus();
204 if (status != Status::OK) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800205 return status;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700206 }
207
208 switch (type) {
209 case RequestTemplate::PREVIEW:
210 case RequestTemplate::STILL_CAPTURE:
211 case RequestTemplate::VIDEO_RECORD:
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800212 case RequestTemplate::VIDEO_SNAPSHOT: {
213 *outMetadata = mDefaultRequests[type];
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700214 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800215 }
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700216 case RequestTemplate::MANUAL:
217 case RequestTemplate::ZERO_SHUTTER_LAG:
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800218 case RequestTemplate::MOTION_TRACKING_PREVIEW:
219 case RequestTemplate::MOTION_TRACKING_BEST:
220 // Don't support MANUAL, ZSL, MOTION_TRACKING_* templates
221 status = Status::ILLEGAL_ARGUMENT;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700222 break;
223 default:
224 ALOGE("%s: unknown request template type %d", __FUNCTION__, static_cast<int>(type));
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800225 status = Status::ILLEGAL_ARGUMENT;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700226 break;
227 }
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -0800228 return status;
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700229}
230
231Return<void> ExternalCameraDeviceSession::configureStreams(
232 const V3_2::StreamConfiguration& streams,
233 ICameraDeviceSession::configureStreams_cb _hidl_cb) {
234 V3_2::HalStreamConfiguration outStreams;
235 V3_3::HalStreamConfiguration outStreams_v33;
236 Mutex::Autolock _il(mInterfaceLock);
237
238 Status status = configureStreams(streams, &outStreams_v33);
239 size_t size = outStreams_v33.streams.size();
240 outStreams.streams.resize(size);
241 for (size_t i = 0; i < size; i++) {
242 outStreams.streams[i] = outStreams_v33.streams[i].v3_2;
243 }
244 _hidl_cb(status, outStreams);
245 return Void();
246}
247
248Return<void> ExternalCameraDeviceSession::configureStreams_3_3(
249 const V3_2::StreamConfiguration& streams,
250 ICameraDeviceSession::configureStreams_3_3_cb _hidl_cb) {
251 V3_3::HalStreamConfiguration outStreams;
252 Mutex::Autolock _il(mInterfaceLock);
253
254 Status status = configureStreams(streams, &outStreams);
255 _hidl_cb(status, outStreams);
256 return Void();
257}
258
259Return<void> ExternalCameraDeviceSession::configureStreams_3_4(
260 const V3_4::StreamConfiguration& requestedConfiguration,
261 ICameraDeviceSession::configureStreams_3_4_cb _hidl_cb) {
262 V3_2::StreamConfiguration config_v32;
263 V3_3::HalStreamConfiguration outStreams_v33;
264 Mutex::Autolock _il(mInterfaceLock);
265
266 config_v32.operationMode = requestedConfiguration.operationMode;
267 config_v32.streams.resize(requestedConfiguration.streams.size());
268 for (size_t i = 0; i < config_v32.streams.size(); i++) {
269 config_v32.streams[i] = requestedConfiguration.streams[i].v3_2;
270 }
271
272 // Ignore requestedConfiguration.sessionParams. External camera does not support it
273 Status status = configureStreams(config_v32, &outStreams_v33);
274
275 V3_4::HalStreamConfiguration outStreams;
276 outStreams.streams.resize(outStreams_v33.streams.size());
277 for (size_t i = 0; i < outStreams.streams.size(); i++) {
278 outStreams.streams[i].v3_3 = outStreams_v33.streams[i];
279 }
280 _hidl_cb(status, outStreams);
281 return Void();
282}
283
284Return<void> ExternalCameraDeviceSession::getCaptureRequestMetadataQueue(
285 ICameraDeviceSession::getCaptureRequestMetadataQueue_cb _hidl_cb) {
286 Mutex::Autolock _il(mInterfaceLock);
287 _hidl_cb(*mRequestMetadataQueue->getDesc());
288 return Void();
289}
290
291Return<void> ExternalCameraDeviceSession::getCaptureResultMetadataQueue(
292 ICameraDeviceSession::getCaptureResultMetadataQueue_cb _hidl_cb) {
293 Mutex::Autolock _il(mInterfaceLock);
294 _hidl_cb(*mResultMetadataQueue->getDesc());
295 return Void();
296}
297
298Return<void> ExternalCameraDeviceSession::processCaptureRequest(
299 const hidl_vec<CaptureRequest>& requests,
300 const hidl_vec<BufferCache>& cachesToRemove,
301 ICameraDeviceSession::processCaptureRequest_cb _hidl_cb) {
302 Mutex::Autolock _il(mInterfaceLock);
303 updateBufferCaches(cachesToRemove);
304
305 uint32_t numRequestProcessed = 0;
306 Status s = Status::OK;
307 for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
308 s = processOneCaptureRequest(requests[i]);
309 if (s != Status::OK) {
310 break;
311 }
312 }
313
314 _hidl_cb(s, numRequestProcessed);
315 return Void();
316}
317
318Return<void> ExternalCameraDeviceSession::processCaptureRequest_3_4(
319 const hidl_vec<V3_4::CaptureRequest>& requests,
320 const hidl_vec<V3_2::BufferCache>& cachesToRemove,
321 ICameraDeviceSession::processCaptureRequest_3_4_cb _hidl_cb) {
322 Mutex::Autolock _il(mInterfaceLock);
323 updateBufferCaches(cachesToRemove);
324
325 uint32_t numRequestProcessed = 0;
326 Status s = Status::OK;
327 for (size_t i = 0; i < requests.size(); i++, numRequestProcessed++) {
328 s = processOneCaptureRequest(requests[i].v3_2);
329 if (s != Status::OK) {
330 break;
331 }
332 }
333
334 _hidl_cb(s, numRequestProcessed);
335 return Void();
336}
337
338Return<Status> ExternalCameraDeviceSession::flush() {
339 return Status::OK;
340}
341
342Return<void> ExternalCameraDeviceSession::close() {
343 Mutex::Autolock _il(mInterfaceLock);
344 Mutex::Autolock _l(mLock);
345 if (!mClosed) {
346 // TODO: b/72261676 Cleanup inflight buffers/V4L2 buffer queue
347 ALOGV("%s: closing V4L2 camera FD %d", __FUNCTION__, mV4l2Fd.get());
348 mV4l2Fd.reset();
349 mOutputThread->requestExit(); // TODO: join?
350
351 // free all imported buffers
352 for(auto& pair : mCirculatingBuffers) {
353 CirculatingBuffers& buffers = pair.second;
354 for (auto& p2 : buffers) {
355 sHandleImporter.freeBuffer(p2.second);
356 }
357 }
358
359 mClosed = true;
360 }
361 return Void();
362}
363
364Status ExternalCameraDeviceSession::importRequest(
365 const CaptureRequest& request,
366 hidl_vec<buffer_handle_t*>& allBufPtrs,
367 hidl_vec<int>& allFences) {
368 size_t numOutputBufs = request.outputBuffers.size();
369 size_t numBufs = numOutputBufs;
370 // Validate all I/O buffers
371 hidl_vec<buffer_handle_t> allBufs;
372 hidl_vec<uint64_t> allBufIds;
373 allBufs.resize(numBufs);
374 allBufIds.resize(numBufs);
375 allBufPtrs.resize(numBufs);
376 allFences.resize(numBufs);
377 std::vector<int32_t> streamIds(numBufs);
378
379 for (size_t i = 0; i < numOutputBufs; i++) {
380 allBufs[i] = request.outputBuffers[i].buffer.getNativeHandle();
381 allBufIds[i] = request.outputBuffers[i].bufferId;
382 allBufPtrs[i] = &allBufs[i];
383 streamIds[i] = request.outputBuffers[i].streamId;
384 }
385
386 for (size_t i = 0; i < numBufs; i++) {
387 buffer_handle_t buf = allBufs[i];
388 uint64_t bufId = allBufIds[i];
389 CirculatingBuffers& cbs = mCirculatingBuffers[streamIds[i]];
390 if (cbs.count(bufId) == 0) {
391 if (buf == nullptr) {
392 ALOGE("%s: bufferId %" PRIu64 " has null buffer handle!", __FUNCTION__, bufId);
393 return Status::ILLEGAL_ARGUMENT;
394 }
395 // Register a newly seen buffer
396 buffer_handle_t importedBuf = buf;
397 sHandleImporter.importBuffer(importedBuf);
398 if (importedBuf == nullptr) {
399 ALOGE("%s: output buffer %zu is invalid!", __FUNCTION__, i);
400 return Status::INTERNAL_ERROR;
401 } else {
402 cbs[bufId] = importedBuf;
403 }
404 }
405 allBufPtrs[i] = &cbs[bufId];
406 }
407
408 // All buffers are imported. Now validate output buffer acquire fences
409 for (size_t i = 0; i < numOutputBufs; i++) {
410 if (!sHandleImporter.importFence(
411 request.outputBuffers[i].acquireFence, allFences[i])) {
412 ALOGE("%s: output buffer %zu acquire fence is invalid", __FUNCTION__, i);
413 cleanupInflightFences(allFences, i);
414 return Status::INTERNAL_ERROR;
415 }
416 }
417 return Status::OK;
418}
419
420void ExternalCameraDeviceSession::cleanupInflightFences(
421 hidl_vec<int>& allFences, size_t numFences) {
422 for (size_t j = 0; j < numFences; j++) {
423 sHandleImporter.closeFence(allFences[j]);
424 }
425}
426
427Status ExternalCameraDeviceSession::processOneCaptureRequest(const CaptureRequest& request) {
428 Status status = initStatus();
429 if (status != Status::OK) {
430 return status;
431 }
432
433 if (request.inputBuffer.streamId != -1) {
434 ALOGE("%s: external camera does not support reprocessing!", __FUNCTION__);
435 return Status::ILLEGAL_ARGUMENT;
436 }
437
438 Mutex::Autolock _l(mLock);
439 if (!mV4l2Streaming) {
440 ALOGE("%s: cannot process request in streamOff state!", __FUNCTION__);
441 return Status::INTERNAL_ERROR;
442 }
443
444 const camera_metadata_t *rawSettings = nullptr;
445 bool converted = true;
446 CameraMetadata settingsFmq; // settings from FMQ
447 if (request.fmqSettingsSize > 0) {
448 // non-blocking read; client must write metadata before calling
449 // processOneCaptureRequest
450 settingsFmq.resize(request.fmqSettingsSize);
451 bool read = mRequestMetadataQueue->read(settingsFmq.data(), request.fmqSettingsSize);
452 if (read) {
453 converted = V3_2::implementation::convertFromHidl(settingsFmq, &rawSettings);
454 } else {
455 ALOGE("%s: capture request settings metadata couldn't be read from fmq!", __FUNCTION__);
456 converted = false;
457 }
458 } else {
459 converted = V3_2::implementation::convertFromHidl(request.settings, &rawSettings);
460 }
461
462 if (converted && rawSettings != nullptr) {
463 mLatestReqSetting = rawSettings;
464 }
465
466 if (!converted) {
467 ALOGE("%s: capture request settings metadata is corrupt!", __FUNCTION__);
468 return Status::ILLEGAL_ARGUMENT;
469 }
470
471 if (mFirstRequest && rawSettings == nullptr) {
472 ALOGE("%s: capture request settings must not be null for first request!",
473 __FUNCTION__);
474 return Status::ILLEGAL_ARGUMENT;
475 }
476
477 hidl_vec<buffer_handle_t*> allBufPtrs;
478 hidl_vec<int> allFences;
479 size_t numOutputBufs = request.outputBuffers.size();
480
481 if (numOutputBufs == 0) {
482 ALOGE("%s: capture request must have at least one output buffer!", __FUNCTION__);
483 return Status::ILLEGAL_ARGUMENT;
484 }
485
486 status = importRequest(request, allBufPtrs, allFences);
487 if (status != Status::OK) {
488 return status;
489 }
490
491 // TODO: program fps range per capture request here
492 // or limit the set of availableFpsRange
493
494 sp<V4L2Frame> frameIn = dequeueV4l2FrameLocked();
495 if ( frameIn == nullptr) {
496 ALOGE("%s: V4L2 deque frame failed!", __FUNCTION__);
497 return Status::INTERNAL_ERROR;
498 }
499 // TODO: This can probably be replaced by use v4lbuffer timestamp
500 // if the device supports it
501 nsecs_t shutterTs = systemTime(SYSTEM_TIME_MONOTONIC);
502
503
504 // TODO: reduce object copy in this path
505 HalRequest halReq = {
506 .frameNumber = request.frameNumber,
507 .setting = mLatestReqSetting,
508 .frameIn = frameIn,
509 .shutterTs = shutterTs};
510 halReq.buffers.resize(numOutputBufs);
511 for (size_t i = 0; i < numOutputBufs; i++) {
512 HalStreamBuffer& halBuf = halReq.buffers[i];
513 int streamId = halBuf.streamId = request.outputBuffers[i].streamId;
514 halBuf.bufferId = request.outputBuffers[i].bufferId;
515 const Stream& stream = mStreamMap[streamId];
516 halBuf.width = stream.width;
517 halBuf.height = stream.height;
518 halBuf.format = stream.format;
519 halBuf.usage = stream.usage;
520 halBuf.bufPtr = allBufPtrs[i];
521 halBuf.acquireFence = allFences[i];
522 halBuf.fenceTimeout = false;
523 }
524 mInflightFrames.insert(halReq.frameNumber);
525 // Send request to OutputThread for the rest of processing
526 mOutputThread->submitRequest(halReq);
527 mFirstRequest = false;
528 return Status::OK;
529}
530
531void ExternalCameraDeviceSession::notifyShutter(uint32_t frameNumber, nsecs_t shutterTs) {
532 NotifyMsg msg;
533 msg.type = MsgType::SHUTTER;
534 msg.msg.shutter.frameNumber = frameNumber;
535 msg.msg.shutter.timestamp = shutterTs;
536 mCallback->notify({msg});
537}
538
539void ExternalCameraDeviceSession::notifyError(
540 uint32_t frameNumber, int32_t streamId, ErrorCode ec) {
541 NotifyMsg msg;
542 msg.type = MsgType::ERROR;
543 msg.msg.error.frameNumber = frameNumber;
544 msg.msg.error.errorStreamId = streamId;
545 msg.msg.error.errorCode = ec;
546 mCallback->notify({msg});
547}
548
549//TODO: refactor with processCaptureResult
550Status ExternalCameraDeviceSession::processCaptureRequestError(HalRequest& req) {
551 // Return V4L2 buffer to V4L2 buffer queue
552 enqueueV4l2Frame(req.frameIn);
553
554 // NotifyShutter
555 notifyShutter(req.frameNumber, req.shutterTs);
556
557 notifyError(/*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_REQUEST);
558
559 // Fill output buffers
560 hidl_vec<CaptureResult> results;
561 results.resize(1);
562 CaptureResult& result = results[0];
563 result.frameNumber = req.frameNumber;
564 result.partialResult = 1;
565 result.inputBuffer.streamId = -1;
566 result.outputBuffers.resize(req.buffers.size());
567 for (size_t i = 0; i < req.buffers.size(); i++) {
568 result.outputBuffers[i].streamId = req.buffers[i].streamId;
569 result.outputBuffers[i].bufferId = req.buffers[i].bufferId;
570 result.outputBuffers[i].status = BufferStatus::ERROR;
571 if (req.buffers[i].acquireFence >= 0) {
572 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
573 handle->data[0] = req.buffers[i].acquireFence;
574 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/true);
575 }
576 }
577
578 // update inflight records
579 {
580 Mutex::Autolock _l(mLock);
581 mInflightFrames.erase(req.frameNumber);
582 }
583
584 // Callback into framework
585 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
586 freeReleaseFences(results);
587 return Status::OK;
588}
589
590Status ExternalCameraDeviceSession::processCaptureResult(HalRequest& req) {
591 // Return V4L2 buffer to V4L2 buffer queue
592 enqueueV4l2Frame(req.frameIn);
593
594 // NotifyShutter
595 notifyShutter(req.frameNumber, req.shutterTs);
596
597 // Fill output buffers
598 hidl_vec<CaptureResult> results;
599 results.resize(1);
600 CaptureResult& result = results[0];
601 result.frameNumber = req.frameNumber;
602 result.partialResult = 1;
603 result.inputBuffer.streamId = -1;
604 result.outputBuffers.resize(req.buffers.size());
605 for (size_t i = 0; i < req.buffers.size(); i++) {
606 result.outputBuffers[i].streamId = req.buffers[i].streamId;
607 result.outputBuffers[i].bufferId = req.buffers[i].bufferId;
608 if (req.buffers[i].fenceTimeout) {
609 result.outputBuffers[i].status = BufferStatus::ERROR;
610 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
611 handle->data[0] = req.buffers[i].acquireFence;
612 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/true);
613 notifyError(req.frameNumber, req.buffers[i].streamId, ErrorCode::ERROR_BUFFER);
614 } else {
615 result.outputBuffers[i].status = BufferStatus::OK;
616 // TODO: refactor
617 if (req.buffers[i].acquireFence > 0) {
618 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
619 handle->data[0] = req.buffers[i].acquireFence;
620 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/true);
621 }
622 }
623 }
624
625 // Fill capture result metadata
626 fillCaptureResult(req.setting, req.shutterTs);
627 const camera_metadata_t *rawResult = req.setting.getAndLock();
628 V3_2::implementation::convertToHidl(rawResult, &result.result);
629 req.setting.unlock(rawResult);
630
631 // update inflight records
632 {
633 Mutex::Autolock _l(mLock);
634 mInflightFrames.erase(req.frameNumber);
635 }
636
637 // Callback into framework
638 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
639 freeReleaseFences(results);
640 return Status::OK;
641}
642
643void ExternalCameraDeviceSession::invokeProcessCaptureResultCallback(
644 hidl_vec<CaptureResult> &results, bool tryWriteFmq) {
645 if (mProcessCaptureResultLock.tryLock() != OK) {
646 const nsecs_t NS_TO_SECOND = 1000000000;
647 ALOGV("%s: previous call is not finished! waiting 1s...", __FUNCTION__);
648 if (mProcessCaptureResultLock.timedLock(/* 1s */NS_TO_SECOND) != OK) {
649 ALOGE("%s: cannot acquire lock in 1s, cannot proceed",
650 __FUNCTION__);
651 return;
652 }
653 }
654 if (tryWriteFmq && mResultMetadataQueue->availableToWrite() > 0) {
655 for (CaptureResult &result : results) {
656 if (result.result.size() > 0) {
657 if (mResultMetadataQueue->write(result.result.data(), result.result.size())) {
658 result.fmqResultSize = result.result.size();
659 result.result.resize(0);
660 } else {
661 ALOGW("%s: couldn't utilize fmq, fall back to hwbinder", __FUNCTION__);
662 result.fmqResultSize = 0;
663 }
664 } else {
665 result.fmqResultSize = 0;
666 }
667 }
668 }
669 mCallback->processCaptureResult(results);
670 mProcessCaptureResultLock.unlock();
671}
672
673void ExternalCameraDeviceSession::freeReleaseFences(hidl_vec<CaptureResult>& results) {
674 for (auto& result : results) {
675 if (result.inputBuffer.releaseFence.getNativeHandle() != nullptr) {
676 native_handle_t* handle = const_cast<native_handle_t*>(
677 result.inputBuffer.releaseFence.getNativeHandle());
678 native_handle_close(handle);
679 native_handle_delete(handle);
680 }
681 for (auto& buf : result.outputBuffers) {
682 if (buf.releaseFence.getNativeHandle() != nullptr) {
683 native_handle_t* handle = const_cast<native_handle_t*>(
684 buf.releaseFence.getNativeHandle());
685 native_handle_close(handle);
686 native_handle_delete(handle);
687 }
688 }
689 }
690 return;
691}
692
693ExternalCameraDeviceSession::OutputThread::OutputThread(
694 wp<ExternalCameraDeviceSession> parent,
695 CroppingType ct) : mParent(parent), mCroppingType(ct) {}
696
697ExternalCameraDeviceSession::OutputThread::~OutputThread() {}
698
699uint32_t ExternalCameraDeviceSession::OutputThread::getFourCcFromLayout(
700 const YCbCrLayout& layout) {
701 intptr_t cb = reinterpret_cast<intptr_t>(layout.cb);
702 intptr_t cr = reinterpret_cast<intptr_t>(layout.cr);
703 if (std::abs(cb - cr) == 1 && layout.chromaStep == 2) {
704 // Interleaved format
705 if (layout.cb > layout.cr) {
706 return V4L2_PIX_FMT_NV21;
707 } else {
708 return V4L2_PIX_FMT_NV12;
709 }
710 } else if (layout.chromaStep == 1) {
711 // Planar format
712 if (layout.cb > layout.cr) {
713 return V4L2_PIX_FMT_YVU420; // YV12
714 } else {
715 return V4L2_PIX_FMT_YUV420; // YU12
716 }
717 } else {
718 return FLEX_YUV_GENERIC;
719 }
720}
721
722int ExternalCameraDeviceSession::OutputThread::getCropRect(
723 CroppingType ct, const Size& inSize, const Size& outSize, IMapper::Rect* out) {
724 if (out == nullptr) {
725 ALOGE("%s: out is null", __FUNCTION__);
726 return -1;
727 }
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800728
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700729 uint32_t inW = inSize.width;
730 uint32_t inH = inSize.height;
731 uint32_t outW = outSize.width;
732 uint32_t outH = outSize.height;
733
Yin-Chia Yeh4acd76e2018-01-23 15:29:14 -0800734 // Handle special case where aspect ratio is close to input but scaled
735 // dimension is slightly larger than input
736 float arIn = ASPECT_RATIO(inSize);
737 float arOut = ASPECT_RATIO(outSize);
738 if (isAspectRatioClose(arIn, arOut)) {
739 out->left = 0;
740 out->top = 0;
741 out->width = inW;
742 out->height = inH;
743 return 0;
744 }
745
Yin-Chia Yeh19030592017-10-19 17:30:11 -0700746 if (ct == VERTICAL) {
747 uint64_t scaledOutH = static_cast<uint64_t>(outH) * inW / outW;
748 if (scaledOutH > inH) {
749 ALOGE("%s: Output size %dx%d cannot be vertically cropped from input size %dx%d",
750 __FUNCTION__, outW, outH, inW, inH);
751 return -1;
752 }
753 scaledOutH = scaledOutH & ~0x1; // make it multiple of 2
754
755 out->left = 0;
756 out->top = ((inH - scaledOutH) / 2) & ~0x1;
757 out->width = inW;
758 out->height = static_cast<int32_t>(scaledOutH);
759 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledH %d",
760 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutH));
761 } else {
762 uint64_t scaledOutW = static_cast<uint64_t>(outW) * inH / outH;
763 if (scaledOutW > inW) {
764 ALOGE("%s: Output size %dx%d cannot be horizontally cropped from input size %dx%d",
765 __FUNCTION__, outW, outH, inW, inH);
766 return -1;
767 }
768 scaledOutW = scaledOutW & ~0x1; // make it multiple of 2
769
770 out->left = ((inW - scaledOutW) / 2) & ~0x1;
771 out->top = 0;
772 out->width = static_cast<int32_t>(scaledOutW);
773 out->height = inH;
774 ALOGV("%s: crop %dx%d to %dx%d: top %d, scaledW %d",
775 __FUNCTION__, inW, inH, outW, outH, out->top, static_cast<int32_t>(scaledOutW));
776 }
777
778 return 0;
779}
780
781int ExternalCameraDeviceSession::OutputThread::cropAndScaleLocked(
782 sp<AllocatedFrame>& in, const HalStreamBuffer& halBuf, YCbCrLayout* out) {
783 Size inSz = {in->mWidth, in->mHeight};
784 Size outSz = {halBuf.width, halBuf.height};
785 int ret;
786 if (inSz == outSz) {
787 ret = in->getLayout(out);
788 if (ret != 0) {
789 ALOGE("%s: failed to get input image layout", __FUNCTION__);
790 return ret;
791 }
792 return ret;
793 }
794
795 // Cropping to output aspect ratio
796 IMapper::Rect inputCrop;
797 ret = getCropRect(mCroppingType, inSz, outSz, &inputCrop);
798 if (ret != 0) {
799 ALOGE("%s: failed to compute crop rect for output size %dx%d",
800 __FUNCTION__, outSz.width, outSz.height);
801 return ret;
802 }
803
804 YCbCrLayout croppedLayout;
805 ret = in->getCroppedLayout(inputCrop, &croppedLayout);
806 if (ret != 0) {
807 ALOGE("%s: failed to crop input image %dx%d to output size %dx%d",
808 __FUNCTION__, inSz.width, inSz.height, outSz.width, outSz.height);
809 return ret;
810 }
811
812 if ((mCroppingType == VERTICAL && inSz.width == outSz.width) ||
813 (mCroppingType == HORIZONTAL && inSz.height == outSz.height)) {
814 // No scale is needed
815 *out = croppedLayout;
816 return 0;
817 }
818
819 auto it = mScaledYu12Frames.find(outSz);
820 sp<AllocatedFrame> scaledYu12Buf;
821 if (it != mScaledYu12Frames.end()) {
822 scaledYu12Buf = it->second;
823 } else {
824 it = mIntermediateBuffers.find(outSz);
825 if (it == mIntermediateBuffers.end()) {
826 ALOGE("%s: failed to find intermediate buffer size %dx%d",
827 __FUNCTION__, outSz.width, outSz.height);
828 return -1;
829 }
830 scaledYu12Buf = it->second;
831 }
832 // Scale
833 YCbCrLayout outLayout;
834 ret = scaledYu12Buf->getLayout(&outLayout);
835 if (ret != 0) {
836 ALOGE("%s: failed to get output buffer layout", __FUNCTION__);
837 return ret;
838 }
839
840 ret = libyuv::I420Scale(
841 static_cast<uint8_t*>(croppedLayout.y),
842 croppedLayout.yStride,
843 static_cast<uint8_t*>(croppedLayout.cb),
844 croppedLayout.cStride,
845 static_cast<uint8_t*>(croppedLayout.cr),
846 croppedLayout.cStride,
847 inputCrop.width,
848 inputCrop.height,
849 static_cast<uint8_t*>(outLayout.y),
850 outLayout.yStride,
851 static_cast<uint8_t*>(outLayout.cb),
852 outLayout.cStride,
853 static_cast<uint8_t*>(outLayout.cr),
854 outLayout.cStride,
855 outSz.width,
856 outSz.height,
857 // TODO: b/72261744 see if we can use better filter without losing too much perf
858 libyuv::FilterMode::kFilterNone);
859
860 if (ret != 0) {
861 ALOGE("%s: failed to scale buffer from %dx%d to %dx%d. Ret %d",
862 __FUNCTION__, inputCrop.width, inputCrop.height,
863 outSz.width, outSz.height, ret);
864 return ret;
865 }
866
867 *out = outLayout;
868 mScaledYu12Frames.insert({outSz, scaledYu12Buf});
869 return 0;
870}
871
872int ExternalCameraDeviceSession::OutputThread::formatConvertLocked(
873 const YCbCrLayout& in, const YCbCrLayout& out, Size sz, uint32_t format) {
874 int ret = 0;
875 switch (format) {
876 case V4L2_PIX_FMT_NV21:
877 ret = libyuv::I420ToNV21(
878 static_cast<uint8_t*>(in.y),
879 in.yStride,
880 static_cast<uint8_t*>(in.cb),
881 in.cStride,
882 static_cast<uint8_t*>(in.cr),
883 in.cStride,
884 static_cast<uint8_t*>(out.y),
885 out.yStride,
886 static_cast<uint8_t*>(out.cr),
887 out.cStride,
888 sz.width,
889 sz.height);
890 if (ret != 0) {
891 ALOGE("%s: convert to NV21 buffer failed! ret %d",
892 __FUNCTION__, ret);
893 return ret;
894 }
895 break;
896 case V4L2_PIX_FMT_NV12:
897 ret = libyuv::I420ToNV12(
898 static_cast<uint8_t*>(in.y),
899 in.yStride,
900 static_cast<uint8_t*>(in.cb),
901 in.cStride,
902 static_cast<uint8_t*>(in.cr),
903 in.cStride,
904 static_cast<uint8_t*>(out.y),
905 out.yStride,
906 static_cast<uint8_t*>(out.cb),
907 out.cStride,
908 sz.width,
909 sz.height);
910 if (ret != 0) {
911 ALOGE("%s: convert to NV12 buffer failed! ret %d",
912 __FUNCTION__, ret);
913 return ret;
914 }
915 break;
916 case V4L2_PIX_FMT_YVU420: // YV12
917 case V4L2_PIX_FMT_YUV420: // YU12
918 // TODO: maybe we can speed up here by somehow save this copy?
919 ret = libyuv::I420Copy(
920 static_cast<uint8_t*>(in.y),
921 in.yStride,
922 static_cast<uint8_t*>(in.cb),
923 in.cStride,
924 static_cast<uint8_t*>(in.cr),
925 in.cStride,
926 static_cast<uint8_t*>(out.y),
927 out.yStride,
928 static_cast<uint8_t*>(out.cb),
929 out.cStride,
930 static_cast<uint8_t*>(out.cr),
931 out.cStride,
932 sz.width,
933 sz.height);
934 if (ret != 0) {
935 ALOGE("%s: copy to YV12 or YU12 buffer failed! ret %d",
936 __FUNCTION__, ret);
937 return ret;
938 }
939 break;
940 case FLEX_YUV_GENERIC:
941 // TODO: b/72261744 write to arbitrary flexible YUV layout. Slow.
942 ALOGE("%s: unsupported flexible yuv layout"
943 " y %p cb %p cr %p y_str %d c_str %d c_step %d",
944 __FUNCTION__, out.y, out.cb, out.cr,
945 out.yStride, out.cStride, out.chromaStep);
946 return -1;
947 default:
948 ALOGE("%s: unknown YUV format 0x%x!", __FUNCTION__, format);
949 return -1;
950 }
951 return 0;
952}
953
954bool ExternalCameraDeviceSession::OutputThread::threadLoop() {
955 HalRequest req;
956 auto parent = mParent.promote();
957 if (parent == nullptr) {
958 ALOGE("%s: session has been disconnected!", __FUNCTION__);
959 return false;
960 }
961
962 // TODO: maybe we need to setup a sensor thread to dq/enq v4l frames
963 // regularly to prevent v4l buffer queue filled with stale buffers
964 // when app doesn't program a preveiw request
965 waitForNextRequest(&req);
966 if (req.frameIn == nullptr) {
967 // No new request, wait again
968 return true;
969 }
970
971 if (req.frameIn->mFourcc != V4L2_PIX_FMT_MJPEG) {
972 ALOGE("%s: do not support V4L2 format %c%c%c%c", __FUNCTION__,
973 req.frameIn->mFourcc & 0xFF,
974 (req.frameIn->mFourcc >> 8) & 0xFF,
975 (req.frameIn->mFourcc >> 16) & 0xFF,
976 (req.frameIn->mFourcc >> 24) & 0xFF);
977 parent->notifyError(
978 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
979 return false;
980 }
981
982 std::unique_lock<std::mutex> lk(mLock);
983
984 // Convert input V4L2 frame to YU12 of the same size
985 // TODO: see if we can save some computation by converting to YV12 here
986 uint8_t* inData;
987 size_t inDataSize;
988 req.frameIn->map(&inData, &inDataSize);
989 // TODO: profile
990 // TODO: in some special case maybe we can decode jpg directly to gralloc output?
991 int res = libyuv::MJPGToI420(
992 inData, inDataSize,
993 static_cast<uint8_t*>(mYu12FrameLayout.y),
994 mYu12FrameLayout.yStride,
995 static_cast<uint8_t*>(mYu12FrameLayout.cb),
996 mYu12FrameLayout.cStride,
997 static_cast<uint8_t*>(mYu12FrameLayout.cr),
998 mYu12FrameLayout.cStride,
999 mYu12Frame->mWidth, mYu12Frame->mHeight,
1000 mYu12Frame->mWidth, mYu12Frame->mHeight);
1001
1002 if (res != 0) {
1003 // For some webcam, the first few V4L2 frames might be malformed...
1004 ALOGE("%s: Convert V4L2 frame to YU12 failed! res %d", __FUNCTION__, res);
1005 lk.unlock();
1006 Status st = parent->processCaptureRequestError(req);
1007 if (st != Status::OK) {
1008 ALOGE("%s: failed to process capture request error!", __FUNCTION__);
1009 parent->notifyError(
1010 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1011 return false;
1012 }
1013 return true;
1014 }
1015
1016 ALOGV("%s processing new request", __FUNCTION__);
1017 const int kSyncWaitTimeoutMs = 500;
1018 for (auto& halBuf : req.buffers) {
1019 if (halBuf.acquireFence != -1) {
1020 int ret = sync_wait(halBuf.acquireFence, kSyncWaitTimeoutMs);
1021 if (ret) {
1022 halBuf.fenceTimeout = true;
1023 } else {
1024 ::close(halBuf.acquireFence);
1025 }
1026 }
1027
1028 if (halBuf.fenceTimeout) {
1029 continue;
1030 }
1031
1032 // Gralloc lockYCbCr the buffer
1033 switch (halBuf.format) {
1034 case PixelFormat::BLOB:
1035 // TODO: b/72261675 implement JPEG output path
1036 break;
1037 case PixelFormat::YCBCR_420_888:
1038 case PixelFormat::YV12: {
1039 IMapper::Rect outRect {0, 0,
1040 static_cast<int32_t>(halBuf.width),
1041 static_cast<int32_t>(halBuf.height)};
1042 YCbCrLayout outLayout = sHandleImporter.lockYCbCr(
1043 *(halBuf.bufPtr), halBuf.usage, outRect);
1044 ALOGV("%s: outLayout y %p cb %p cr %p y_str %d c_str %d c_step %d",
1045 __FUNCTION__, outLayout.y, outLayout.cb, outLayout.cr,
1046 outLayout.yStride, outLayout.cStride, outLayout.chromaStep);
1047
1048 // Convert to output buffer size/format
1049 uint32_t outputFourcc = getFourCcFromLayout(outLayout);
1050 ALOGV("%s: converting to format %c%c%c%c", __FUNCTION__,
1051 outputFourcc & 0xFF,
1052 (outputFourcc >> 8) & 0xFF,
1053 (outputFourcc >> 16) & 0xFF,
1054 (outputFourcc >> 24) & 0xFF);
1055
1056 YCbCrLayout cropAndScaled;
1057 int ret = cropAndScaleLocked(
1058 mYu12Frame, halBuf, &cropAndScaled);
1059 if (ret != 0) {
1060 ALOGE("%s: crop and scale failed!", __FUNCTION__);
1061 lk.unlock();
1062 parent->notifyError(
1063 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1064 return false;
1065 }
1066
1067 Size sz {halBuf.width, halBuf.height};
1068 ret = formatConvertLocked(cropAndScaled, outLayout, sz, outputFourcc);
1069 if (ret != 0) {
1070 ALOGE("%s: format coversion failed!", __FUNCTION__);
1071 lk.unlock();
1072 parent->notifyError(
1073 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1074 return false;
1075 }
1076 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
1077 if (relFence > 0) {
1078 halBuf.acquireFence = relFence;
1079 }
1080 } break;
1081 default:
1082 ALOGE("%s: unknown output format %x", __FUNCTION__, halBuf.format);
1083 lk.unlock();
1084 parent->notifyError(
1085 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1086 return false;
1087 }
1088 } // for each buffer
1089 mScaledYu12Frames.clear();
1090
1091 // Don't hold the lock while calling back to parent
1092 lk.unlock();
1093 Status st = parent->processCaptureResult(req);
1094 if (st != Status::OK) {
1095 ALOGE("%s: failed to process capture result!", __FUNCTION__);
1096 parent->notifyError(
1097 /*frameNum*/req.frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
1098 return false;
1099 }
1100 return true;
1101}
1102
1103Status ExternalCameraDeviceSession::OutputThread::allocateIntermediateBuffers(
1104 const Size& v4lSize, const hidl_vec<Stream>& streams) {
1105 std::lock_guard<std::mutex> lk(mLock);
1106 if (mScaledYu12Frames.size() != 0) {
1107 ALOGE("%s: intermediate buffer pool has %zu inflight buffers! (expect 0)",
1108 __FUNCTION__, mScaledYu12Frames.size());
1109 return Status::INTERNAL_ERROR;
1110 }
1111
1112 // Allocating intermediate YU12 frame
1113 if (mYu12Frame == nullptr || mYu12Frame->mWidth != v4lSize.width ||
1114 mYu12Frame->mHeight != v4lSize.height) {
1115 mYu12Frame.clear();
1116 mYu12Frame = new AllocatedFrame(v4lSize.width, v4lSize.height);
1117 int ret = mYu12Frame->allocate(&mYu12FrameLayout);
1118 if (ret != 0) {
1119 ALOGE("%s: allocating YU12 frame failed!", __FUNCTION__);
1120 return Status::INTERNAL_ERROR;
1121 }
1122 }
1123
1124 // Allocating scaled buffers
1125 for (const auto& stream : streams) {
1126 Size sz = {stream.width, stream.height};
1127 if (sz == v4lSize) {
1128 continue; // Don't need an intermediate buffer same size as v4lBuffer
1129 }
1130 if (mIntermediateBuffers.count(sz) == 0) {
1131 // Create new intermediate buffer
1132 sp<AllocatedFrame> buf = new AllocatedFrame(stream.width, stream.height);
1133 int ret = buf->allocate();
1134 if (ret != 0) {
1135 ALOGE("%s: allocating intermediate YU12 frame %dx%d failed!",
1136 __FUNCTION__, stream.width, stream.height);
1137 return Status::INTERNAL_ERROR;
1138 }
1139 mIntermediateBuffers[sz] = buf;
1140 }
1141 }
1142
1143 // Remove unconfigured buffers
1144 auto it = mIntermediateBuffers.begin();
1145 while (it != mIntermediateBuffers.end()) {
1146 bool configured = false;
1147 auto sz = it->first;
1148 for (const auto& stream : streams) {
1149 if (stream.width == sz.width && stream.height == sz.height) {
1150 configured = true;
1151 break;
1152 }
1153 }
1154 if (configured) {
1155 it++;
1156 } else {
1157 it = mIntermediateBuffers.erase(it);
1158 }
1159 }
1160 return Status::OK;
1161}
1162
1163Status ExternalCameraDeviceSession::OutputThread::submitRequest(const HalRequest& req) {
1164 std::lock_guard<std::mutex> lk(mLock);
1165 // TODO: reduce object copy in this path
1166 mRequestList.push_back(req);
1167 mRequestCond.notify_one();
1168 return Status::OK;
1169}
1170
1171void ExternalCameraDeviceSession::OutputThread::flush() {
1172 std::lock_guard<std::mutex> lk(mLock);
1173 // TODO: send buffer/request errors back to framework
1174 mRequestList.clear();
1175}
1176
1177void ExternalCameraDeviceSession::OutputThread::waitForNextRequest(HalRequest* out) {
1178 if (out == nullptr) {
1179 ALOGE("%s: out is null", __FUNCTION__);
1180 return;
1181 }
1182
1183 std::unique_lock<std::mutex> lk(mLock);
1184 while (mRequestList.empty()) {
1185 std::chrono::seconds timeout = std::chrono::seconds(kReqWaitTimeoutSec);
1186 auto st = mRequestCond.wait_for(lk, timeout);
1187 if (st == std::cv_status::timeout) {
1188 // no new request, return
1189 return;
1190 }
1191 }
1192 *out = mRequestList.front();
1193 mRequestList.pop_front();
1194}
1195
1196void ExternalCameraDeviceSession::cleanupBuffersLocked(int id) {
1197 for (auto& pair : mCirculatingBuffers.at(id)) {
1198 sHandleImporter.freeBuffer(pair.second);
1199 }
1200 mCirculatingBuffers[id].clear();
1201 mCirculatingBuffers.erase(id);
1202}
1203
1204void ExternalCameraDeviceSession::updateBufferCaches(const hidl_vec<BufferCache>& cachesToRemove) {
1205 Mutex::Autolock _l(mLock);
1206 for (auto& cache : cachesToRemove) {
1207 auto cbsIt = mCirculatingBuffers.find(cache.streamId);
1208 if (cbsIt == mCirculatingBuffers.end()) {
1209 // The stream could have been removed
1210 continue;
1211 }
1212 CirculatingBuffers& cbs = cbsIt->second;
1213 auto it = cbs.find(cache.bufferId);
1214 if (it != cbs.end()) {
1215 sHandleImporter.freeBuffer(it->second);
1216 cbs.erase(it);
1217 } else {
1218 ALOGE("%s: stream %d buffer %" PRIu64 " is not cached",
1219 __FUNCTION__, cache.streamId, cache.bufferId);
1220 }
1221 }
1222}
1223
1224bool ExternalCameraDeviceSession::isSupported(const Stream& stream) {
1225 int32_t ds = static_cast<int32_t>(stream.dataSpace);
1226 PixelFormat fmt = stream.format;
1227 uint32_t width = stream.width;
1228 uint32_t height = stream.height;
1229 // TODO: check usage flags
1230
1231 if (stream.streamType != StreamType::OUTPUT) {
1232 ALOGE("%s: does not support non-output stream type", __FUNCTION__);
1233 return false;
1234 }
1235
1236 if (stream.rotation != StreamRotation::ROTATION_0) {
1237 ALOGE("%s: does not support stream rotation", __FUNCTION__);
1238 return false;
1239 }
1240
1241 if (ds & Dataspace::DEPTH) {
1242 ALOGI("%s: does not support depth output", __FUNCTION__);
1243 return false;
1244 }
1245
1246 switch (fmt) {
1247 case PixelFormat::BLOB:
1248 if (ds != static_cast<int32_t>(Dataspace::V0_JFIF)) {
1249 ALOGI("%s: BLOB format does not support dataSpace %x", __FUNCTION__, ds);
1250 return false;
1251 }
1252 case PixelFormat::IMPLEMENTATION_DEFINED:
1253 case PixelFormat::YCBCR_420_888:
1254 case PixelFormat::YV12:
1255 // TODO: check what dataspace we can support here.
1256 // intentional no-ops.
1257 break;
1258 default:
1259 ALOGI("%s: does not support format %x", __FUNCTION__, fmt);
1260 return false;
1261 }
1262
1263 // Assume we can convert any V4L2 format to any of supported output format for now, i.e,
1264 // ignoring v4l2Fmt.fourcc for now. Might need more subtle check if we support more v4l format
1265 // in the futrue.
1266 for (const auto& v4l2Fmt : mSupportedFormats) {
1267 if (width == v4l2Fmt.width && height == v4l2Fmt.height) {
1268 return true;
1269 }
1270 }
1271 ALOGI("%s: resolution %dx%d is not supported", __FUNCTION__, width, height);
1272 return false;
1273}
1274
1275int ExternalCameraDeviceSession::v4l2StreamOffLocked() {
1276 if (!mV4l2Streaming) {
1277 return OK;
1278 }
1279
1280 {
1281 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1282 if (mNumDequeuedV4l2Buffers != 0) {
1283 ALOGE("%s: there are %zu inflight V4L buffers",
1284 __FUNCTION__, mNumDequeuedV4l2Buffers);
1285 return -1;
1286 }
1287 }
1288 mV4l2Buffers.clear(); // VIDIOC_REQBUFS will fail if FDs are not clear first
1289
1290 // VIDIOC_STREAMOFF
1291 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1292 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMOFF, &capture_type)) < 0) {
1293 ALOGE("%s: STREAMOFF failed: %s", __FUNCTION__, strerror(errno));
1294 return -errno;
1295 }
1296
1297 // VIDIOC_REQBUFS: clear buffers
1298 v4l2_requestbuffers req_buffers{};
1299 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1300 req_buffers.memory = V4L2_MEMORY_MMAP;
1301 req_buffers.count = 0;
1302 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
1303 ALOGE("%s: REQBUFS failed: %s", __FUNCTION__, strerror(errno));
1304 return -errno;
1305 }
1306
1307 mV4l2Streaming = false;
1308 return OK;
1309}
1310
1311int ExternalCameraDeviceSession::configureV4l2StreamLocked(const SupportedV4L2Format& v4l2Fmt) {
1312 int ret = v4l2StreamOffLocked();
1313 if (ret != OK) {
1314 ALOGE("%s: stop v4l2 streaming failed: ret %d", __FUNCTION__, ret);
1315 return ret;
1316 }
1317
1318 // VIDIOC_S_FMT w/h/fmt
1319 v4l2_format fmt;
1320 fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1321 fmt.fmt.pix.width = v4l2Fmt.width;
1322 fmt.fmt.pix.height = v4l2Fmt.height;
1323 fmt.fmt.pix.pixelformat = v4l2Fmt.fourcc;
1324 ret = TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_FMT, &fmt));
1325 if (ret < 0) {
1326 ALOGE("%s: S_FMT ioctl failed: %s", __FUNCTION__, strerror(errno));
1327 return -errno;
1328 }
1329
1330 if (v4l2Fmt.width != fmt.fmt.pix.width || v4l2Fmt.height != fmt.fmt.pix.height ||
1331 v4l2Fmt.fourcc != fmt.fmt.pix.pixelformat) {
1332 ALOGE("%s: S_FMT expect %c%c%c%c %dx%d, got %c%c%c%c %dx%d instead!", __FUNCTION__,
1333 v4l2Fmt.fourcc & 0xFF,
1334 (v4l2Fmt.fourcc >> 8) & 0xFF,
1335 (v4l2Fmt.fourcc >> 16) & 0xFF,
1336 (v4l2Fmt.fourcc >> 24) & 0xFF,
1337 v4l2Fmt.width, v4l2Fmt.height,
1338 fmt.fmt.pix.pixelformat & 0xFF,
1339 (fmt.fmt.pix.pixelformat >> 8) & 0xFF,
1340 (fmt.fmt.pix.pixelformat >> 16) & 0xFF,
1341 (fmt.fmt.pix.pixelformat >> 24) & 0xFF,
1342 fmt.fmt.pix.width, fmt.fmt.pix.height);
1343 return -EINVAL;
1344 }
1345 uint32_t bufferSize = fmt.fmt.pix.sizeimage;
1346 ALOGI("%s: V4L2 buffer size is %d", __FUNCTION__, bufferSize);
1347
1348 float maxFps = -1.f;
1349 float fps = 1000.f;
1350 const float kDefaultFps = 30.f;
1351 // Try to pick the slowest fps that is at least 30
1352 for (const auto& f : v4l2Fmt.frameRates) {
1353 if (maxFps < f) {
1354 maxFps = f;
1355 }
1356 if (f >= kDefaultFps && f < fps) {
1357 fps = f;
1358 }
1359 }
1360 if (fps == 1000.f) {
1361 fps = maxFps;
1362 }
1363
1364 // VIDIOC_G_PARM/VIDIOC_S_PARM: set fps
1365 v4l2_streamparm streamparm = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
1366 // The following line checks that the driver knows about framerate get/set.
1367 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_G_PARM, &streamparm)) >= 0) {
1368 // Now check if the device is able to accept a capture framerate set.
1369 if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
1370 // |frame_rate| is float, approximate by a fraction.
1371 const int kFrameRatePrecision = 10000;
1372 streamparm.parm.capture.timeperframe.numerator = kFrameRatePrecision;
1373 streamparm.parm.capture.timeperframe.denominator =
1374 (fps * kFrameRatePrecision);
1375
1376 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_S_PARM, &streamparm)) < 0) {
1377 ALOGE("%s: failed to set framerate to %f", __FUNCTION__, fps);
1378 return UNKNOWN_ERROR;
1379 }
1380 }
1381 }
1382 float retFps = streamparm.parm.capture.timeperframe.denominator /
1383 streamparm.parm.capture.timeperframe.numerator;
1384 if (std::fabs(fps - retFps) > std::numeric_limits<float>::epsilon()) {
1385 ALOGE("%s: expect fps %f, got %f instead", __FUNCTION__, fps, retFps);
1386 return BAD_VALUE;
1387 }
1388
1389 uint32_t v4lBufferCount = (v4l2Fmt.width <= kMaxVideoSize.width &&
1390 v4l2Fmt.height <= kMaxVideoSize.height) ? kNumVideoBuffers : kNumStillBuffers;
1391 // VIDIOC_REQBUFS: create buffers
1392 v4l2_requestbuffers req_buffers{};
1393 req_buffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1394 req_buffers.memory = V4L2_MEMORY_MMAP;
1395 req_buffers.count = v4lBufferCount;
1396 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_REQBUFS, &req_buffers)) < 0) {
1397 ALOGE("%s: VIDIOC_REQBUFS failed: %s", __FUNCTION__, strerror(errno));
1398 return -errno;
1399 }
1400
1401 // Driver can indeed return more buffer if it needs more to operate
1402 if (req_buffers.count < v4lBufferCount) {
1403 ALOGE("%s: VIDIOC_REQBUFS expected %d buffers, got %d instead",
1404 __FUNCTION__, v4lBufferCount, req_buffers.count);
1405 return NO_MEMORY;
1406 }
1407
1408 // VIDIOC_EXPBUF: export buffers as FD
1409 // VIDIOC_QBUF: send buffer to driver
1410 mV4l2Buffers.resize(req_buffers.count);
1411 for (uint32_t i = 0; i < req_buffers.count; i++) {
1412 v4l2_exportbuffer expbuf {};
1413 expbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1414 expbuf.index = i;
1415 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_EXPBUF, &expbuf)) < 0) {
1416 ALOGE("%s: EXPBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
1417 return -errno;
1418 }
1419 mV4l2Buffers[i].reset(expbuf.fd);
1420
1421 v4l2_buffer buffer = {
1422 .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
1423 .index = i,
1424 .memory = V4L2_MEMORY_MMAP};
1425
1426 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1427 ALOGE("%s: QBUF %d failed: %s", __FUNCTION__, i, strerror(errno));
1428 return -errno;
1429 }
1430 }
1431
1432 // VIDIOC_STREAMON: start streaming
1433 v4l2_buf_type capture_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1434 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_STREAMON, &capture_type)) < 0) {
1435 ALOGE("%s: VIDIOC_STREAMON failed: %s", __FUNCTION__, strerror(errno));
1436 return -errno;
1437 }
1438
1439 // Swallow first few frames after streamOn to account for bad frames from some devices
1440 for (int i = 0; i < kBadFramesAfterStreamOn; i++) {
1441 v4l2_buffer buffer{};
1442 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1443 buffer.memory = V4L2_MEMORY_MMAP;
1444 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
1445 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
1446 return -errno;
1447 }
1448
1449 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1450 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, buffer.index, strerror(errno));
1451 return -errno;
1452 }
1453 }
1454
1455 mV4l2StreamingFmt = v4l2Fmt;
1456 mV4l2Streaming = true;
1457 return OK;
1458}
1459
1460sp<V4L2Frame> ExternalCameraDeviceSession::dequeueV4l2FrameLocked() {
1461 sp<V4L2Frame> ret = nullptr;
1462
1463 {
1464 std::unique_lock<std::mutex> lk(mV4l2BufferLock);
1465 if (mNumDequeuedV4l2Buffers == mV4l2Buffers.size()) {
1466 std::chrono::seconds timeout = std::chrono::seconds(kBufferWaitTimeoutSec);
1467 mLock.unlock();
1468 auto st = mV4L2BufferReturned.wait_for(lk, timeout);
1469 mLock.lock();
1470 if (st == std::cv_status::timeout) {
1471 ALOGE("%s: wait for V4L2 buffer return timeout!", __FUNCTION__);
1472 return ret;
1473 }
1474 }
1475 }
1476
1477 v4l2_buffer buffer{};
1478 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1479 buffer.memory = V4L2_MEMORY_MMAP;
1480 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_DQBUF, &buffer)) < 0) {
1481 ALOGE("%s: DQBUF fails: %s", __FUNCTION__, strerror(errno));
1482 return ret;
1483 }
1484
1485 if (buffer.index >= mV4l2Buffers.size()) {
1486 ALOGE("%s: Invalid buffer id: %d", __FUNCTION__, buffer.index);
1487 return ret;
1488 }
1489
1490 if (buffer.flags & V4L2_BUF_FLAG_ERROR) {
1491 ALOGE("%s: v4l2 buf error! buf flag 0x%x", __FUNCTION__, buffer.flags);
1492 // TODO: try to dequeue again
1493 }
1494
1495 {
1496 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1497 mNumDequeuedV4l2Buffers++;
1498 }
1499 return new V4L2Frame(
1500 mV4l2StreamingFmt.width, mV4l2StreamingFmt.height, mV4l2StreamingFmt.fourcc,
1501 buffer.index, mV4l2Buffers[buffer.index].get(), buffer.bytesused);
1502}
1503
1504void ExternalCameraDeviceSession::enqueueV4l2Frame(const sp<V4L2Frame>& frame) {
1505 Mutex::Autolock _l(mLock);
1506 frame->unmap();
1507 v4l2_buffer buffer{};
1508 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1509 buffer.memory = V4L2_MEMORY_MMAP;
1510 buffer.index = frame->mBufferIndex;
1511 if (TEMP_FAILURE_RETRY(ioctl(mV4l2Fd.get(), VIDIOC_QBUF, &buffer)) < 0) {
1512 ALOGE("%s: QBUF index %d fails: %s", __FUNCTION__, frame->mBufferIndex, strerror(errno));
1513 return;
1514 }
1515
1516 {
1517 std::lock_guard<std::mutex> lk(mV4l2BufferLock);
1518 mNumDequeuedV4l2Buffers--;
1519 mV4L2BufferReturned.notify_one();
1520 }
1521}
1522
1523Status ExternalCameraDeviceSession::configureStreams(
1524 const V3_2::StreamConfiguration& config, V3_3::HalStreamConfiguration* out) {
1525 if (config.operationMode != StreamConfigurationMode::NORMAL_MODE) {
1526 ALOGE("%s: unsupported operation mode: %d", __FUNCTION__, config.operationMode);
1527 return Status::ILLEGAL_ARGUMENT;
1528 }
1529
1530 if (config.streams.size() == 0) {
1531 ALOGE("%s: cannot configure zero stream", __FUNCTION__);
1532 return Status::ILLEGAL_ARGUMENT;
1533 }
1534
1535 int numProcessedStream = 0;
1536 int numStallStream = 0;
1537 for (const auto& stream : config.streams) {
1538 // Check if the format/width/height combo is supported
1539 if (!isSupported(stream)) {
1540 return Status::ILLEGAL_ARGUMENT;
1541 }
1542 if (stream.format == PixelFormat::BLOB) {
1543 numStallStream++;
1544 } else {
1545 numProcessedStream++;
1546 }
1547 }
1548
1549 if (numProcessedStream > kMaxProcessedStream) {
1550 ALOGE("%s: too many processed streams (expect <= %d, got %d)", __FUNCTION__,
1551 kMaxProcessedStream, numProcessedStream);
1552 return Status::ILLEGAL_ARGUMENT;
1553 }
1554
1555 if (numStallStream > kMaxStallStream) {
1556 ALOGE("%s: too many stall streams (expect <= %d, got %d)", __FUNCTION__,
1557 kMaxStallStream, numStallStream);
1558 return Status::ILLEGAL_ARGUMENT;
1559 }
1560
1561 Status status = initStatus();
1562 if (status != Status::OK) {
1563 return status;
1564 }
1565
1566 Mutex::Autolock _l(mLock);
1567 if (!mInflightFrames.empty()) {
1568 ALOGE("%s: trying to configureStreams while there are still %zu inflight frames!",
1569 __FUNCTION__, mInflightFrames.size());
1570 return Status::INTERNAL_ERROR;
1571 }
1572
1573 // Add new streams
1574 for (const auto& stream : config.streams) {
1575 if (mStreamMap.count(stream.id) == 0) {
1576 mStreamMap[stream.id] = stream;
1577 mCirculatingBuffers.emplace(stream.id, CirculatingBuffers{});
1578 }
1579 }
1580
1581 // Cleanup removed streams
1582 for(auto it = mStreamMap.begin(); it != mStreamMap.end();) {
1583 int id = it->first;
1584 bool found = false;
1585 for (const auto& stream : config.streams) {
1586 if (id == stream.id) {
1587 found = true;
1588 break;
1589 }
1590 }
1591 if (!found) {
1592 // Unmap all buffers of deleted stream
1593 cleanupBuffersLocked(id);
1594 it = mStreamMap.erase(it);
1595 } else {
1596 ++it;
1597 }
1598 }
1599
1600 // Now select a V4L2 format to produce all output streams
1601 float desiredAr = (mCroppingType == VERTICAL) ? kMaxAspectRatio : kMinAspectRatio;
1602 uint32_t maxDim = 0;
1603 for (const auto& stream : config.streams) {
1604 float aspectRatio = ASPECT_RATIO(stream);
1605 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
1606 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
1607 desiredAr = aspectRatio;
1608 }
1609
1610 // The dimension that's not cropped
1611 uint32_t dim = (mCroppingType == VERTICAL) ? stream.width : stream.height;
1612 if (dim > maxDim) {
1613 maxDim = dim;
1614 }
1615 }
1616 // Find the smallest format that matches the desired aspect ratio and is wide/high enough
1617 SupportedV4L2Format v4l2Fmt {.width = 0, .height = 0};
1618 for (const auto& fmt : mSupportedFormats) {
1619 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
1620 if (dim >= maxDim) {
1621 float aspectRatio = ASPECT_RATIO(fmt);
1622 if (isAspectRatioClose(aspectRatio, desiredAr)) {
1623 v4l2Fmt = fmt;
1624 // since mSupportedFormats is sorted by width then height, the first matching fmt
1625 // will be the smallest one with matching aspect ratio
1626 break;
1627 }
1628 }
1629 }
1630 if (v4l2Fmt.width == 0) {
1631 // Cannot find exact good aspect ratio candidate, try to find a close one
1632 for (const auto& fmt : mSupportedFormats) {
1633 uint32_t dim = (mCroppingType == VERTICAL) ? fmt.width : fmt.height;
1634 if (dim >= maxDim) {
1635 float aspectRatio = ASPECT_RATIO(fmt);
1636 if ((mCroppingType == VERTICAL && aspectRatio < desiredAr) ||
1637 (mCroppingType == HORIZONTAL && aspectRatio > desiredAr)) {
1638 v4l2Fmt = fmt;
1639 break;
1640 }
1641 }
1642 }
1643 }
1644
1645 if (v4l2Fmt.width == 0) {
1646 ALOGE("%s: unable to find a resolution matching (%s at least %d, aspect ratio %f)"
1647 , __FUNCTION__, (mCroppingType == VERTICAL) ? "width" : "height",
1648 maxDim, desiredAr);
1649 return Status::ILLEGAL_ARGUMENT;
1650 }
1651
1652 if (configureV4l2StreamLocked(v4l2Fmt) != 0) {
1653 ALOGE("V4L configuration failed!, format:%c%c%c%c, w %d, h %d",
1654 v4l2Fmt.fourcc & 0xFF,
1655 (v4l2Fmt.fourcc >> 8) & 0xFF,
1656 (v4l2Fmt.fourcc >> 16) & 0xFF,
1657 (v4l2Fmt.fourcc >> 24) & 0xFF,
1658 v4l2Fmt.width, v4l2Fmt.height);
1659 return Status::INTERNAL_ERROR;
1660 }
1661
1662 Size v4lSize = {v4l2Fmt.width, v4l2Fmt.height};
1663 status = mOutputThread->allocateIntermediateBuffers(v4lSize, config.streams);
1664 if (status != Status::OK) {
1665 ALOGE("%s: allocating intermediate buffers failed!", __FUNCTION__);
1666 return status;
1667 }
1668
1669 out->streams.resize(config.streams.size());
1670 for (size_t i = 0; i < config.streams.size(); i++) {
1671 out->streams[i].overrideDataSpace = config.streams[i].dataSpace;
1672 out->streams[i].v3_2.id = config.streams[i].id;
1673 // TODO: double check should we add those CAMERA flags
1674 mStreamMap[config.streams[i].id].usage =
1675 out->streams[i].v3_2.producerUsage = config.streams[i].usage |
1676 BufferUsage::CPU_WRITE_OFTEN |
1677 BufferUsage::CAMERA_OUTPUT;
1678 out->streams[i].v3_2.consumerUsage = 0;
1679 out->streams[i].v3_2.maxBuffers = mV4l2Buffers.size();
1680
1681 switch (config.streams[i].format) {
1682 case PixelFormat::BLOB:
1683 case PixelFormat::YCBCR_420_888:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08001684 case PixelFormat::YV12: // Used by SurfaceTexture
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001685 // No override
1686 out->streams[i].v3_2.overrideFormat = config.streams[i].format;
1687 break;
1688 case PixelFormat::IMPLEMENTATION_DEFINED:
1689 // Override based on VIDEO or not
1690 out->streams[i].v3_2.overrideFormat =
1691 (config.streams[i].usage & BufferUsage::VIDEO_ENCODER) ?
1692 PixelFormat::YCBCR_420_888 : PixelFormat::YV12;
1693 // Save overridden formt in mStreamMap
1694 mStreamMap[config.streams[i].id].format = out->streams[i].v3_2.overrideFormat;
1695 break;
1696 default:
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08001697 ALOGE("%s: unsupported format 0x%x", __FUNCTION__, config.streams[i].format);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001698 return Status::ILLEGAL_ARGUMENT;
1699 }
1700 }
1701
1702 mFirstRequest = true;
1703 return Status::OK;
1704}
1705
1706bool ExternalCameraDeviceSession::isClosed() {
1707 Mutex::Autolock _l(mLock);
1708 return mClosed;
1709}
1710
1711#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
1712#define UPDATE(md, tag, data, size) \
1713do { \
1714 if ((md).update((tag), (data), (size))) { \
1715 ALOGE("Update " #tag " failed!"); \
1716 return BAD_VALUE; \
1717 } \
1718} while (0)
1719
1720status_t ExternalCameraDeviceSession::initDefaultRequests() {
1721 ::android::hardware::camera::common::V1_0::helper::CameraMetadata md;
1722
1723 const uint8_t aberrationMode = ANDROID_COLOR_CORRECTION_ABERRATION_MODE_OFF;
1724 UPDATE(md, ANDROID_COLOR_CORRECTION_ABERRATION_MODE, &aberrationMode, 1);
1725
1726 const int32_t exposureCompensation = 0;
1727 UPDATE(md, ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION, &exposureCompensation, 1);
1728
1729 const uint8_t videoStabilizationMode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
1730 UPDATE(md, ANDROID_CONTROL_VIDEO_STABILIZATION_MODE, &videoStabilizationMode, 1);
1731
1732 const uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO;
1733 UPDATE(md, ANDROID_CONTROL_AWB_MODE, &awbMode, 1);
1734
1735 const uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON;
1736 UPDATE(md, ANDROID_CONTROL_AE_MODE, &aeMode, 1);
1737
1738 const uint8_t aePrecaptureTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
1739 UPDATE(md, ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &aePrecaptureTrigger, 1);
1740
1741 const uint8_t afMode = ANDROID_CONTROL_AF_MODE_AUTO;
1742 UPDATE(md, ANDROID_CONTROL_AF_MODE, &afMode, 1);
1743
1744 const uint8_t afTrigger = ANDROID_CONTROL_AF_TRIGGER_IDLE;
1745 UPDATE(md, ANDROID_CONTROL_AF_TRIGGER, &afTrigger, 1);
1746
1747 const uint8_t sceneMode = ANDROID_CONTROL_SCENE_MODE_DISABLED;
1748 UPDATE(md, ANDROID_CONTROL_SCENE_MODE, &sceneMode, 1);
1749
1750 const uint8_t effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF;
1751 UPDATE(md, ANDROID_CONTROL_EFFECT_MODE, &effectMode, 1);
1752
1753 const uint8_t flashMode = ANDROID_FLASH_MODE_OFF;
1754 UPDATE(md, ANDROID_FLASH_MODE, &flashMode, 1);
1755
1756 const int32_t thumbnailSize[] = {240, 180};
1757 UPDATE(md, ANDROID_JPEG_THUMBNAIL_SIZE, thumbnailSize, 2);
1758
1759 const uint8_t jpegQuality = 90;
1760 UPDATE(md, ANDROID_JPEG_QUALITY, &jpegQuality, 1);
1761 UPDATE(md, ANDROID_JPEG_THUMBNAIL_QUALITY, &jpegQuality, 1);
1762
1763 const int32_t jpegOrientation = 0;
1764 UPDATE(md, ANDROID_JPEG_ORIENTATION, &jpegOrientation, 1);
1765
1766 const uint8_t oisMode = ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF;
1767 UPDATE(md, ANDROID_LENS_OPTICAL_STABILIZATION_MODE, &oisMode, 1);
1768
1769 const uint8_t nrMode = ANDROID_NOISE_REDUCTION_MODE_OFF;
1770 UPDATE(md, ANDROID_NOISE_REDUCTION_MODE, &nrMode, 1);
1771
1772 const uint8_t fdMode = ANDROID_STATISTICS_FACE_DETECT_MODE_OFF;
1773 UPDATE(md, ANDROID_STATISTICS_FACE_DETECT_MODE, &fdMode, 1);
1774
1775 const uint8_t hotpixelMode = ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF;
1776 UPDATE(md, ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE, &hotpixelMode, 1);
1777
1778 bool support30Fps = false;
1779 int32_t maxFps = std::numeric_limits<int32_t>::min();
1780 for (const auto& supportedFormat : mSupportedFormats) {
1781 for (const auto& frameRate : supportedFormat.frameRates) {
1782 int32_t framerateInt = static_cast<int32_t>(frameRate);
1783 if (maxFps < framerateInt) {
1784 maxFps = framerateInt;
1785 }
1786 if (framerateInt == 30) {
1787 support30Fps = true;
1788 break;
1789 }
1790 }
1791 if (support30Fps) {
1792 break;
1793 }
1794 }
1795 int32_t defaultFramerate = support30Fps ? 30 : maxFps;
1796 int32_t defaultFpsRange[] = {defaultFramerate, defaultFramerate};
1797 UPDATE(md, ANDROID_CONTROL_AE_TARGET_FPS_RANGE, defaultFpsRange, ARRAY_SIZE(defaultFpsRange));
1798
1799 uint8_t antibandingMode = ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO;
1800 UPDATE(md, ANDROID_CONTROL_AE_ANTIBANDING_MODE, &antibandingMode, 1);
1801
1802 const uint8_t controlMode = ANDROID_CONTROL_MODE_AUTO;
1803 UPDATE(md, ANDROID_CONTROL_MODE, &controlMode, 1);
1804
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08001805 auto requestTemplates = hidl_enum_iterator<RequestTemplate>();
1806 for (RequestTemplate type : requestTemplates) {
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001807 ::android::hardware::camera::common::V1_0::helper::CameraMetadata mdCopy = md;
1808 uint8_t intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
1809 switch (type) {
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08001810 case RequestTemplate::PREVIEW:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001811 intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
1812 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08001813 case RequestTemplate::STILL_CAPTURE:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001814 intent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE;
1815 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08001816 case RequestTemplate::VIDEO_RECORD:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001817 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD;
1818 break;
Eino-Ville Talvala658d30d2018-01-18 12:55:07 -08001819 case RequestTemplate::VIDEO_SNAPSHOT:
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001820 intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT;
1821 break;
1822 default:
1823 ALOGE("%s: unknown template type %d", __FUNCTION__, type);
1824 return BAD_VALUE;
1825 }
1826 UPDATE(mdCopy, ANDROID_CONTROL_CAPTURE_INTENT, &intent, 1);
1827
1828 camera_metadata_t* rawMd = mdCopy.release();
1829 CameraMetadata hidlMd;
1830 hidlMd.setToExternal(
1831 (uint8_t*) rawMd, get_camera_metadata_size(rawMd));
1832 mDefaultRequests[type] = hidlMd;
1833 free_camera_metadata(rawMd);
1834 }
1835
1836 return OK;
1837}
1838
1839status_t ExternalCameraDeviceSession::fillCaptureResult(
1840 common::V1_0::helper::CameraMetadata &md, nsecs_t timestamp) {
1841 // android.control
1842 // For USB camera, we don't know the AE state. Set the state to converged to
1843 // indicate the frame should be good to use. Then apps don't have to wait the
1844 // AE state.
1845 const uint8_t aeState = ANDROID_CONTROL_AE_STATE_CONVERGED;
1846 UPDATE(md, ANDROID_CONTROL_AE_STATE, &aeState, 1);
1847
1848 const uint8_t ae_lock = ANDROID_CONTROL_AE_LOCK_OFF;
1849 UPDATE(md, ANDROID_CONTROL_AE_LOCK, &ae_lock, 1);
1850
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08001851 bool afTrigger = mAfTrigger;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001852 if (md.exists(ANDROID_CONTROL_AF_TRIGGER)) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08001853 Mutex::Autolock _l(mLock);
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001854 camera_metadata_entry entry = md.find(ANDROID_CONTROL_AF_TRIGGER);
1855 if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_START) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08001856 mAfTrigger = afTrigger = true;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001857 } else if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_CANCEL) {
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08001858 mAfTrigger = afTrigger = false;
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001859 }
1860 }
1861
1862 // For USB camera, the USB camera handles everything and we don't have control
1863 // over AF. We only simply fake the AF metadata based on the request
1864 // received here.
1865 uint8_t afState;
1866 if (afTrigger) {
1867 afState = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
1868 } else {
1869 afState = ANDROID_CONTROL_AF_STATE_INACTIVE;
1870 }
1871 UPDATE(md, ANDROID_CONTROL_AF_STATE, &afState, 1);
1872
1873 // Set AWB state to converged to indicate the frame should be good to use.
1874 const uint8_t awbState = ANDROID_CONTROL_AWB_STATE_CONVERGED;
1875 UPDATE(md, ANDROID_CONTROL_AWB_STATE, &awbState, 1);
1876
1877 const uint8_t awbLock = ANDROID_CONTROL_AWB_LOCK_OFF;
1878 UPDATE(md, ANDROID_CONTROL_AWB_LOCK, &awbLock, 1);
1879
1880 camera_metadata_ro_entry active_array_size =
1881 mCameraCharacteristics.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
1882
1883 if (active_array_size.count == 0) {
1884 ALOGE("%s: cannot find active array size!", __FUNCTION__);
1885 return -EINVAL;
1886 }
1887
Yin-Chia Yehfb1c1542018-01-24 15:46:36 -08001888 const uint8_t flashState = ANDROID_FLASH_STATE_UNAVAILABLE;
1889 UPDATE(md, ANDROID_FLASH_STATE, &flashState, 1);
1890
Yin-Chia Yeh19030592017-10-19 17:30:11 -07001891 // android.scaler
1892 const int32_t crop_region[] = {
1893 active_array_size.data.i32[0], active_array_size.data.i32[1],
1894 active_array_size.data.i32[2], active_array_size.data.i32[3],
1895 };
1896 UPDATE(md, ANDROID_SCALER_CROP_REGION, crop_region, ARRAY_SIZE(crop_region));
1897
1898 // android.sensor
1899 UPDATE(md, ANDROID_SENSOR_TIMESTAMP, &timestamp, 1);
1900
1901 // android.statistics
1902 const uint8_t lensShadingMapMode = ANDROID_STATISTICS_LENS_SHADING_MAP_MODE_OFF;
1903 UPDATE(md, ANDROID_STATISTICS_LENS_SHADING_MAP_MODE, &lensShadingMapMode, 1);
1904
1905 const uint8_t sceneFlicker = ANDROID_STATISTICS_SCENE_FLICKER_NONE;
1906 UPDATE(md, ANDROID_STATISTICS_SCENE_FLICKER, &sceneFlicker, 1);
1907
1908 return OK;
1909}
1910
1911#undef ARRAY_SIZE
1912#undef UPDATE
1913
1914V4L2Frame::V4L2Frame(
1915 uint32_t w, uint32_t h, uint32_t fourcc,
1916 int bufIdx, int fd, uint32_t dataSize) :
1917 mWidth(w), mHeight(h), mFourcc(fourcc),
1918 mBufferIndex(bufIdx), mFd(fd), mDataSize(dataSize) {}
1919
1920int V4L2Frame::map(uint8_t** data, size_t* dataSize) {
1921 if (data == nullptr || dataSize == nullptr) {
1922 ALOGI("%s: V4L2 buffer map bad argument: data %p, dataSize %p",
1923 __FUNCTION__, data, dataSize);
1924 return -EINVAL;
1925 }
1926
1927 Mutex::Autolock _l(mLock);
1928 if (!mMapped) {
1929 void* addr = mmap(NULL, mDataSize, PROT_READ, MAP_SHARED, mFd, 0);
1930 if (addr == MAP_FAILED) {
1931 ALOGE("%s: V4L2 buffer map failed: %s", __FUNCTION__, strerror(errno));
1932 return -EINVAL;
1933 }
1934 mData = static_cast<uint8_t*>(addr);
1935 mMapped = true;
1936 }
1937 *data = mData;
1938 *dataSize = mDataSize;
1939 ALOGV("%s: V4L map FD %d, data %p size %zu", __FUNCTION__, mFd, mData, mDataSize);
1940 return 0;
1941}
1942
1943int V4L2Frame::unmap() {
1944 Mutex::Autolock _l(mLock);
1945 if (mMapped) {
1946 ALOGV("%s: V4L unmap data %p size %zu", __FUNCTION__, mData, mDataSize);
1947 if (munmap(mData, mDataSize) != 0) {
1948 ALOGE("%s: V4L2 buffer unmap failed: %s", __FUNCTION__, strerror(errno));
1949 return -EINVAL;
1950 }
1951 mMapped = false;
1952 }
1953 return 0;
1954}
1955
1956V4L2Frame::~V4L2Frame() {
1957 unmap();
1958}
1959
1960AllocatedFrame::AllocatedFrame(
1961 uint32_t w, uint32_t h) :
1962 mWidth(w), mHeight(h), mFourcc(V4L2_PIX_FMT_YUV420) {};
1963
1964AllocatedFrame::~AllocatedFrame() {}
1965
1966int AllocatedFrame::allocate(YCbCrLayout* out) {
1967 if ((mWidth % 2) || (mHeight % 2)) {
1968 ALOGE("%s: bad dimension %dx%d (not multiple of 2)", __FUNCTION__, mWidth, mHeight);
1969 return -EINVAL;
1970 }
1971
1972 uint32_t dataSize = mWidth * mHeight * 3 / 2; // YUV420
1973 if (mData.size() != dataSize) {
1974 mData.resize(dataSize);
1975 }
1976
1977 if (out != nullptr) {
1978 out->y = mData.data();
1979 out->yStride = mWidth;
1980 uint8_t* cbStart = mData.data() + mWidth * mHeight;
1981 uint8_t* crStart = cbStart + mWidth * mHeight / 4;
1982 out->cb = cbStart;
1983 out->cr = crStart;
1984 out->cStride = mWidth / 2;
1985 out->chromaStep = 1;
1986 }
1987 return 0;
1988}
1989
1990int AllocatedFrame::getLayout(YCbCrLayout* out) {
1991 IMapper::Rect noCrop = {0, 0,
1992 static_cast<int32_t>(mWidth),
1993 static_cast<int32_t>(mHeight)};
1994 return getCroppedLayout(noCrop, out);
1995}
1996
1997int AllocatedFrame::getCroppedLayout(const IMapper::Rect& rect, YCbCrLayout* out) {
1998 if (out == nullptr) {
1999 ALOGE("%s: null out", __FUNCTION__);
2000 return -1;
2001 }
2002 if ((rect.left + rect.width) > static_cast<int>(mWidth) ||
2003 (rect.top + rect.height) > static_cast<int>(mHeight) ||
2004 (rect.left % 2) || (rect.top % 2) || (rect.width % 2) || (rect.height % 2)) {
2005 ALOGE("%s: bad rect left %d top %d w %d h %d", __FUNCTION__,
2006 rect.left, rect.top, rect.width, rect.height);
2007 return -1;
2008 }
2009
2010 out->y = mData.data() + mWidth * rect.top + rect.left;
2011 out->yStride = mWidth;
2012 uint8_t* cbStart = mData.data() + mWidth * mHeight;
2013 uint8_t* crStart = cbStart + mWidth * mHeight / 4;
2014 out->cb = cbStart + mWidth * rect.top / 4 + rect.left / 2;
2015 out->cr = crStart + mWidth * rect.top / 4 + rect.left / 2;
2016 out->cStride = mWidth / 2;
2017 out->chromaStep = 1;
2018 return 0;
2019}
2020
2021} // namespace implementation
2022} // namespace V3_4
2023} // namespace device
2024} // namespace camera
2025} // namespace hardware
2026} // namespace android