1 /*
2 * Copyright (C) 2020 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
17 #define LOG_TAG "ExtCamOfflnSsn@3.6"
18 #define ATRACE_TAG ATRACE_TAG_CAMERA
19 #include <android/log.h>
20
21 #include <linux/videodev2.h>
22 #include <sync/sync.h>
23
24 #define HAVE_JPEG // required for libyuv.h to export MJPEG decode APIs
25 #include <libyuv.h>
26
27 #include <utils/Trace.h>
28 #include "ExternalCameraOfflineSession.h"
29
30 namespace {
31
32 // Size of request/result metadata fast message queue. Change to 0 to always use hwbinder buffer.
33 static constexpr size_t kMetadataMsgQueueSize = 1 << 18 /* 256kB */;
34
35 } // anonymous namespace
36
37 namespace android {
38 namespace hardware {
39 namespace camera {
40 namespace device {
41 namespace V3_6 {
42 namespace implementation {
43
44 // static instance
45 HandleImporter ExternalCameraOfflineSession::sHandleImporter;
46
47 using V3_5::implementation::ExternalCameraDeviceSession;
48
ExternalCameraOfflineSession(const CroppingType & croppingType,const common::V1_0::helper::CameraMetadata & chars,const std::string & cameraId,const std::string & exifMake,const std::string & exifModel,const uint32_t blobBufferSize,const bool afTrigger,const hidl_vec<Stream> & offlineStreams,std::deque<std::shared_ptr<HalRequest>> & offlineReqs,const std::map<int,CirculatingBuffers> & circulatingBuffers)49 ExternalCameraOfflineSession::ExternalCameraOfflineSession(
50 const CroppingType& croppingType,
51 const common::V1_0::helper::CameraMetadata& chars,
52 const std::string& cameraId,
53 const std::string& exifMake,
54 const std::string& exifModel,
55 const uint32_t blobBufferSize,
56 const bool afTrigger,
57 const hidl_vec<Stream>& offlineStreams,
58 std::deque<std::shared_ptr<HalRequest>>& offlineReqs,
59 const std::map<int, CirculatingBuffers>& circulatingBuffers) :
60 mCroppingType(croppingType), mChars(chars), mCameraId(cameraId),
61 mExifMake(exifMake), mExifModel(exifModel), mBlobBufferSize(blobBufferSize),
62 mAfTrigger(afTrigger), mOfflineStreams(offlineStreams), mOfflineReqs(offlineReqs),
63 mCirculatingBuffers(circulatingBuffers) {}
64
~ExternalCameraOfflineSession()65 ExternalCameraOfflineSession::~ExternalCameraOfflineSession() {
66 close();
67 }
68
initialize()69 bool ExternalCameraOfflineSession::initialize() {
70 mResultMetadataQueue = std::make_shared<ResultMetadataQueue>(
71 kMetadataMsgQueueSize, false /* non blocking */);
72 if (!mResultMetadataQueue->isValid()) {
73 ALOGE("%s: invalid result fmq", __FUNCTION__);
74 return true;
75 }
76 return false;
77 }
78
initOutputThread()79 void ExternalCameraOfflineSession::initOutputThread() {
80 if (mOutputThread != nullptr) {
81 ALOGE("%s: OutputThread already exist!", __FUNCTION__);
82 return;
83 }
84
85 mBufferRequestThread = new ExternalCameraDeviceSession::BufferRequestThread(
86 this, mCallback);
87 mBufferRequestThread->run("ExtCamBufReq", PRIORITY_DISPLAY);
88
89 mOutputThread = new OutputThread(this, mCroppingType, mChars,
90 mBufferRequestThread, mOfflineReqs);
91
92 mOutputThread->setExifMakeModel(mExifMake, mExifModel);
93
94 Size inputSize = { mOfflineReqs[0]->frameIn->mWidth, mOfflineReqs[0]->frameIn->mHeight};
95 Size maxThumbSize = V3_4::implementation::getMaxThumbnailResolution(mChars);
96 mOutputThread->allocateIntermediateBuffers(
97 inputSize, maxThumbSize, mOfflineStreams, mBlobBufferSize);
98
99 mOutputThread->run("ExtCamOfflnOut", PRIORITY_DISPLAY);
100 }
101
threadLoop()102 bool ExternalCameraOfflineSession::OutputThread::threadLoop() {
103 auto parent = mParent.promote();
104 if (parent == nullptr) {
105 ALOGE("%s: session has been disconnected!", __FUNCTION__);
106 return false;
107 }
108
109 if (mOfflineReqs.empty()) {
110 ALOGI("%s: all offline requests are processed. Stopping.", __FUNCTION__);
111 return false;
112 }
113
114 std::shared_ptr<HalRequest> req = mOfflineReqs.front();
115 mOfflineReqs.pop_front();
116
117 auto onDeviceError = [&](auto... args) {
118 ALOGE(args...);
119 parent->notifyError(
120 req->frameNumber, /*stream*/-1, ErrorCode::ERROR_DEVICE);
121 signalRequestDone();
122 return false;
123 };
124
125 if (req->frameIn->mFourcc != V4L2_PIX_FMT_MJPEG && req->frameIn->mFourcc != V4L2_PIX_FMT_Z16) {
126 return onDeviceError("%s: do not support V4L2 format %c%c%c%c", __FUNCTION__,
127 req->frameIn->mFourcc & 0xFF,
128 (req->frameIn->mFourcc >> 8) & 0xFF,
129 (req->frameIn->mFourcc >> 16) & 0xFF,
130 (req->frameIn->mFourcc >> 24) & 0xFF);
131 }
132
133 int res = requestBufferStart(req->buffers);
134 if (res != 0) {
135 ALOGE("%s: send BufferRequest failed! res %d", __FUNCTION__, res);
136 return onDeviceError("%s: failed to send buffer request!", __FUNCTION__);
137 }
138
139 std::unique_lock<std::mutex> lk(mBufferLock);
140 // Convert input V4L2 frame to YU12 of the same size
141 // TODO: see if we can save some computation by converting to YV12 here
142 uint8_t* inData;
143 size_t inDataSize;
144 if (req->frameIn->getData(&inData, &inDataSize) != 0) {
145 lk.unlock();
146 return onDeviceError("%s: V4L2 buffer map failed", __FUNCTION__);
147 }
148
149 // TODO: in some special case maybe we can decode jpg directly to gralloc output?
150 if (req->frameIn->mFourcc == V4L2_PIX_FMT_MJPEG) {
151 ATRACE_BEGIN("MJPGtoI420");
152 int res = libyuv::MJPGToI420(
153 inData, inDataSize, static_cast<uint8_t*>(mYu12FrameLayout.y), mYu12FrameLayout.yStride,
154 static_cast<uint8_t*>(mYu12FrameLayout.cb), mYu12FrameLayout.cStride,
155 static_cast<uint8_t*>(mYu12FrameLayout.cr), mYu12FrameLayout.cStride,
156 mYu12Frame->mWidth, mYu12Frame->mHeight, mYu12Frame->mWidth, mYu12Frame->mHeight);
157 ATRACE_END();
158
159 if (res != 0) {
160 // For some webcam, the first few V4L2 frames might be malformed...
161 ALOGE("%s: Convert V4L2 frame to YU12 failed! res %d", __FUNCTION__, res);
162 lk.unlock();
163 Status st = parent->processCaptureRequestError(req);
164 if (st != Status::OK) {
165 return onDeviceError("%s: failed to process capture request error!", __FUNCTION__);
166 }
167 signalRequestDone();
168 return true;
169 }
170 }
171
172 ATRACE_BEGIN("Wait for BufferRequest done");
173 res = waitForBufferRequestDone(&req->buffers);
174 ATRACE_END();
175
176 if (res != 0) {
177 ALOGE("%s: wait for BufferRequest done failed! res %d", __FUNCTION__, res);
178 lk.unlock();
179 return onDeviceError("%s: failed to process buffer request error!", __FUNCTION__);
180 }
181
182 ALOGV("%s processing new request", __FUNCTION__);
183 const int kSyncWaitTimeoutMs = 500;
184 for (auto& halBuf : req->buffers) {
185 if (*(halBuf.bufPtr) == nullptr) {
186 ALOGW("%s: buffer for stream %d missing", __FUNCTION__, halBuf.streamId);
187 halBuf.fenceTimeout = true;
188 } else if (halBuf.acquireFence >= 0) {
189 int ret = sync_wait(halBuf.acquireFence, kSyncWaitTimeoutMs);
190 if (ret) {
191 halBuf.fenceTimeout = true;
192 } else {
193 ::close(halBuf.acquireFence);
194 halBuf.acquireFence = -1;
195 }
196 }
197
198 if (halBuf.fenceTimeout) {
199 continue;
200 }
201
202 // Gralloc lockYCbCr the buffer
203 switch (halBuf.format) {
204 case PixelFormat::BLOB: {
205 int ret = createJpegLocked(halBuf, req->setting);
206
207 if(ret != 0) {
208 lk.unlock();
209 return onDeviceError("%s: createJpegLocked failed with %d",
210 __FUNCTION__, ret);
211 }
212 } break;
213 case PixelFormat::Y16: {
214 void* outLayout = sHandleImporter.lock(*(halBuf.bufPtr), halBuf.usage, inDataSize);
215
216 std::memcpy(outLayout, inData, inDataSize);
217
218 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
219 if (relFence >= 0) {
220 halBuf.acquireFence = relFence;
221 }
222 } break;
223 case PixelFormat::YCBCR_420_888:
224 case PixelFormat::YV12: {
225 IMapper::Rect outRect {0, 0,
226 static_cast<int32_t>(halBuf.width),
227 static_cast<int32_t>(halBuf.height)};
228 YCbCrLayout outLayout = sHandleImporter.lockYCbCr(
229 *(halBuf.bufPtr), halBuf.usage, outRect);
230 ALOGV("%s: outLayout y %p cb %p cr %p y_str %d c_str %d c_step %d",
231 __FUNCTION__, outLayout.y, outLayout.cb, outLayout.cr,
232 outLayout.yStride, outLayout.cStride, outLayout.chromaStep);
233
234 // Convert to output buffer size/format
235 uint32_t outputFourcc = V3_4::implementation::getFourCcFromLayout(outLayout);
236 ALOGV("%s: converting to format %c%c%c%c", __FUNCTION__,
237 outputFourcc & 0xFF,
238 (outputFourcc >> 8) & 0xFF,
239 (outputFourcc >> 16) & 0xFF,
240 (outputFourcc >> 24) & 0xFF);
241
242 YCbCrLayout cropAndScaled;
243 ATRACE_BEGIN("cropAndScaleLocked");
244 int ret = cropAndScaleLocked(
245 mYu12Frame,
246 Size { halBuf.width, halBuf.height },
247 &cropAndScaled);
248 ATRACE_END();
249 if (ret != 0) {
250 lk.unlock();
251 return onDeviceError("%s: crop and scale failed!", __FUNCTION__);
252 }
253
254 Size sz {halBuf.width, halBuf.height};
255 ATRACE_BEGIN("formatConvert");
256 ret = V3_4::implementation::formatConvert(cropAndScaled, outLayout, sz, outputFourcc);
257 ATRACE_END();
258 if (ret != 0) {
259 lk.unlock();
260 return onDeviceError("%s: format coversion failed!", __FUNCTION__);
261 }
262 int relFence = sHandleImporter.unlock(*(halBuf.bufPtr));
263 if (relFence >= 0) {
264 halBuf.acquireFence = relFence;
265 }
266 } break;
267 default:
268 lk.unlock();
269 return onDeviceError("%s: unknown output format %x", __FUNCTION__, halBuf.format);
270 }
271 } // for each buffer
272 mScaledYu12Frames.clear();
273
274 // Don't hold the lock while calling back to parent
275 lk.unlock();
276 Status st = parent->processCaptureResult(req);
277 if (st != Status::OK) {
278 return onDeviceError("%s: failed to process capture result!", __FUNCTION__);
279 }
280 signalRequestDone();
281 return true;
282 }
283
importBuffer(int32_t streamId,uint64_t bufId,buffer_handle_t buf,buffer_handle_t ** outBufPtr,bool allowEmptyBuf)284 Status ExternalCameraOfflineSession::importBuffer(int32_t streamId,
285 uint64_t bufId, buffer_handle_t buf,
286 /*out*/buffer_handle_t** outBufPtr,
287 bool allowEmptyBuf) {
288 Mutex::Autolock _l(mCbsLock);
289 return V3_4::implementation::importBufferImpl(
290 mCirculatingBuffers, sHandleImporter, streamId,
291 bufId, buf, outBufPtr, allowEmptyBuf);
292 return Status::OK;
293 };
294
295 #define UPDATE(md, tag, data, size) \
296 do { \
297 if ((md).update((tag), (data), (size))) { \
298 ALOGE("Update " #tag " failed!"); \
299 return BAD_VALUE; \
300 } \
301 } while (0)
302
fillCaptureResult(common::V1_0::helper::CameraMetadata & md,nsecs_t timestamp)303 status_t ExternalCameraOfflineSession::fillCaptureResult(
304 common::V1_0::helper::CameraMetadata &md, nsecs_t timestamp) {
305 bool afTrigger = false;
306 {
307 std::lock_guard<std::mutex> lk(mAfTriggerLock);
308 afTrigger = mAfTrigger;
309 if (md.exists(ANDROID_CONTROL_AF_TRIGGER)) {
310 camera_metadata_entry entry = md.find(ANDROID_CONTROL_AF_TRIGGER);
311 if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_START) {
312 mAfTrigger = afTrigger = true;
313 } else if (entry.data.u8[0] == ANDROID_CONTROL_AF_TRIGGER_CANCEL) {
314 mAfTrigger = afTrigger = false;
315 }
316 }
317 }
318
319 // For USB camera, the USB camera handles everything and we don't have control
320 // over AF. We only simply fake the AF metadata based on the request
321 // received here.
322 uint8_t afState;
323 if (afTrigger) {
324 afState = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
325 } else {
326 afState = ANDROID_CONTROL_AF_STATE_INACTIVE;
327 }
328 UPDATE(md, ANDROID_CONTROL_AF_STATE, &afState, 1);
329
330 camera_metadata_ro_entry activeArraySize =
331 mChars.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
332
333 return V3_4::implementation::fillCaptureResultCommon(md, timestamp, activeArraySize);
334 }
335
336 #undef UPDATE
337
processCaptureResult(std::shared_ptr<HalRequest> & req)338 Status ExternalCameraOfflineSession::processCaptureResult(std::shared_ptr<HalRequest>& req) {
339 ATRACE_CALL();
340 // Fill output buffers
341 hidl_vec<CaptureResult> results;
342 results.resize(1);
343 CaptureResult& result = results[0];
344 result.frameNumber = req->frameNumber;
345 result.partialResult = 1;
346 result.inputBuffer.streamId = -1;
347 result.outputBuffers.resize(req->buffers.size());
348 for (size_t i = 0; i < req->buffers.size(); i++) {
349 result.outputBuffers[i].streamId = req->buffers[i].streamId;
350 result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
351 if (req->buffers[i].fenceTimeout) {
352 result.outputBuffers[i].status = BufferStatus::ERROR;
353 if (req->buffers[i].acquireFence >= 0) {
354 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
355 handle->data[0] = req->buffers[i].acquireFence;
356 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
357 }
358 notifyError(req->frameNumber, req->buffers[i].streamId, ErrorCode::ERROR_BUFFER);
359 } else {
360 result.outputBuffers[i].status = BufferStatus::OK;
361 // TODO: refactor
362 if (req->buffers[i].acquireFence >= 0) {
363 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
364 handle->data[0] = req->buffers[i].acquireFence;
365 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
366 }
367 }
368 }
369
370 // Fill capture result metadata
371 fillCaptureResult(req->setting, req->shutterTs);
372 const camera_metadata_t *rawResult = req->setting.getAndLock();
373 V3_2::implementation::convertToHidl(rawResult, &result.result);
374 req->setting.unlock(rawResult);
375
376 // Callback into framework
377 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
378 V3_4::implementation::freeReleaseFences(results);
379 return Status::OK;
380 };
381
invokeProcessCaptureResultCallback(hidl_vec<CaptureResult> & results,bool tryWriteFmq)382 void ExternalCameraOfflineSession::invokeProcessCaptureResultCallback(
383 hidl_vec<CaptureResult> &results, bool tryWriteFmq) {
384 if (mProcessCaptureResultLock.tryLock() != OK) {
385 const nsecs_t NS_TO_SECOND = 1000000000;
386 ALOGV("%s: previous call is not finished! waiting 1s...", __FUNCTION__);
387 if (mProcessCaptureResultLock.timedLock(/* 1s */NS_TO_SECOND) != OK) {
388 ALOGE("%s: cannot acquire lock in 1s, cannot proceed",
389 __FUNCTION__);
390 return;
391 }
392 }
393 if (tryWriteFmq && mResultMetadataQueue->availableToWrite() > 0) {
394 for (CaptureResult &result : results) {
395 if (result.result.size() > 0) {
396 if (mResultMetadataQueue->write(result.result.data(), result.result.size())) {
397 result.fmqResultSize = result.result.size();
398 result.result.resize(0);
399 } else {
400 ALOGW("%s: couldn't utilize fmq, fall back to hwbinder", __FUNCTION__);
401 result.fmqResultSize = 0;
402 }
403 } else {
404 result.fmqResultSize = 0;
405 }
406 }
407 }
408 auto status = mCallback->processCaptureResult(results);
409 if (!status.isOk()) {
410 ALOGE("%s: processCaptureResult ERROR : %s", __FUNCTION__,
411 status.description().c_str());
412 }
413
414 mProcessCaptureResultLock.unlock();
415 }
416
processCaptureRequestError(const std::shared_ptr<HalRequest> & req,std::vector<NotifyMsg> * outMsgs,std::vector<CaptureResult> * outResults)417 Status ExternalCameraOfflineSession::processCaptureRequestError(
418 const std::shared_ptr<HalRequest>& req,
419 /*out*/std::vector<NotifyMsg>* outMsgs,
420 /*out*/std::vector<CaptureResult>* outResults) {
421 ATRACE_CALL();
422
423 if (outMsgs == nullptr) {
424 notifyError(/*frameNum*/req->frameNumber, /*stream*/-1, ErrorCode::ERROR_REQUEST);
425 } else {
426 NotifyMsg shutter;
427 shutter.type = MsgType::SHUTTER;
428 shutter.msg.shutter.frameNumber = req->frameNumber;
429 shutter.msg.shutter.timestamp = req->shutterTs;
430
431 NotifyMsg error;
432 error.type = MsgType::ERROR;
433 error.msg.error.frameNumber = req->frameNumber;
434 error.msg.error.errorStreamId = -1;
435 error.msg.error.errorCode = ErrorCode::ERROR_REQUEST;
436 outMsgs->push_back(shutter);
437 outMsgs->push_back(error);
438 }
439
440 // Fill output buffers
441 hidl_vec<CaptureResult> results;
442 results.resize(1);
443 CaptureResult& result = results[0];
444 result.frameNumber = req->frameNumber;
445 result.partialResult = 1;
446 result.inputBuffer.streamId = -1;
447 result.outputBuffers.resize(req->buffers.size());
448 for (size_t i = 0; i < req->buffers.size(); i++) {
449 result.outputBuffers[i].streamId = req->buffers[i].streamId;
450 result.outputBuffers[i].bufferId = req->buffers[i].bufferId;
451 result.outputBuffers[i].status = BufferStatus::ERROR;
452 if (req->buffers[i].acquireFence >= 0) {
453 native_handle_t* handle = native_handle_create(/*numFds*/1, /*numInts*/0);
454 handle->data[0] = req->buffers[i].acquireFence;
455 result.outputBuffers[i].releaseFence.setTo(handle, /*shouldOwn*/false);
456 }
457 }
458
459 if (outResults == nullptr) {
460 // Callback into framework
461 invokeProcessCaptureResultCallback(results, /* tryWriteFmq */true);
462 V3_4::implementation::freeReleaseFences(results);
463 } else {
464 outResults->push_back(result);
465 }
466 return Status::OK;
467 };
468
getJpegBufferSize(uint32_t,uint32_t) const469 ssize_t ExternalCameraOfflineSession::getJpegBufferSize(
470 uint32_t /*width*/, uint32_t /*height*/) const {
471 // Empty implementation here as the jpeg buffer size is passed in by ctor
472 return 0;
473 };
474
notifyError(uint32_t frameNumber,int32_t streamId,ErrorCode ec)475 void ExternalCameraOfflineSession::notifyError(uint32_t frameNumber, int32_t streamId, ErrorCode ec) {
476 NotifyMsg msg;
477 msg.type = MsgType::ERROR;
478 msg.msg.error.frameNumber = frameNumber;
479 msg.msg.error.errorStreamId = streamId;
480 msg.msg.error.errorCode = ec;
481 mCallback->notify({msg});
482 };
483
setCallback(const sp<ICameraDeviceCallback> & cb)484 Return<void> ExternalCameraOfflineSession::setCallback(const sp<ICameraDeviceCallback>& cb) {
485 Mutex::Autolock _il(mInterfaceLock);
486 if (mCallback != nullptr && cb != nullptr) {
487 ALOGE("%s: callback must not be set twice!", __FUNCTION__);
488 return Void();
489 }
490 mCallback = cb;
491
492 initOutputThread();
493
494 if (mOutputThread == nullptr) {
495 ALOGE("%s: init OutputThread failed!", __FUNCTION__);
496 }
497 return Void();
498 }
499
getCaptureResultMetadataQueue(V3_3::ICameraDeviceSession::getCaptureResultMetadataQueue_cb _hidl_cb)500 Return<void> ExternalCameraOfflineSession::getCaptureResultMetadataQueue(
501 V3_3::ICameraDeviceSession::getCaptureResultMetadataQueue_cb _hidl_cb) {
502 Mutex::Autolock _il(mInterfaceLock);
503 _hidl_cb(*mResultMetadataQueue->getDesc());
504 return Void();
505 }
506
cleanupBuffersLocked(int id)507 void ExternalCameraOfflineSession::cleanupBuffersLocked(int id) {
508 for (auto& pair : mCirculatingBuffers.at(id)) {
509 sHandleImporter.freeBuffer(pair.second);
510 }
511 mCirculatingBuffers[id].clear();
512 mCirculatingBuffers.erase(id);
513 }
514
close()515 Return<void> ExternalCameraOfflineSession::close() {
516 Mutex::Autolock _il(mInterfaceLock);
517 {
518 Mutex::Autolock _l(mLock);
519 if (mClosed) {
520 ALOGW("%s: offline session already closed!", __FUNCTION__);
521 return Void();
522 }
523 }
524 if (mBufferRequestThread) {
525 mBufferRequestThread->requestExit();
526 mBufferRequestThread->join();
527 mBufferRequestThread.clear();
528 }
529 if (mOutputThread) {
530 mOutputThread->flush();
531 mOutputThread->requestExit();
532 mOutputThread->join();
533 mOutputThread.clear();
534 }
535
536 Mutex::Autolock _l(mLock);
537 // free all buffers
538 {
539 Mutex::Autolock _cbl(mCbsLock);
540 for(auto stream : mOfflineStreams) {
541 cleanupBuffersLocked(stream.id);
542 }
543 }
544 mCallback.clear();
545 mClosed = true;
546 return Void();
547 }
548
549 } // namespace implementation
550 } // namespace V3_6
551 } // namespace device
552 } // namespace camera
553 } // namespace hardware
554 } // namespace android
555