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