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