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