blob: b30a23fc009134e7b41d06c2170014eae07517db [file] [log] [blame]
Scott Randolphb342cb12017-04-25 17:38:29 -07001/*
2 * Copyright (C) 2016 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 "android.hardware.automotive.evs@1.0-display"
18
19#include "EvsV4lCamera.h"
20#include "EvsEnumerator.h"
21#include "bufferCopy.h"
22
23#include <ui/GraphicBufferAllocator.h>
24#include <ui/GraphicBufferMapper.h>
25
26
27namespace android {
28namespace hardware {
29namespace automotive {
30namespace evs {
31namespace V1_0 {
32namespace implementation {
33
34
35// Arbitrary limit on number of graphics buffers allowed to be allocated
36// Safeguards against unreasonable resource consumption and provides a testable limit
37static const unsigned MAX_BUFFERS_IN_FLIGHT = 100;
38
39
40EvsV4lCamera::EvsV4lCamera(const char *deviceName) :
41 mFramesAllowed(0),
42 mFramesInUse(0) {
43 ALOGD("EvsV4lCamera instantiated");
44
45 mDescription.cameraId = deviceName;
46
47 // Initialize the video device
48 if (!mVideo.open(deviceName)) {
49 ALOGE("Failed to open v4l device %s\n", deviceName);
50 }
51
52 // NOTE: Our current spec says only support NV21 -- can we stick to that with software
53 // conversion? Will this work with the hardware texture units?
54 // TODO: Settle on the one official format that works on all platforms
55 // TODO: Get NV21 working? It is scrambled somewhere along the way right now.
56// mFormat = HAL_PIXEL_FORMAT_YCRCB_420_SP; // 420SP == NV21
57// mFormat = HAL_PIXEL_FORMAT_RGBA_8888;
58 mFormat = HAL_PIXEL_FORMAT_YCBCR_422_I;
59
60 // How we expect to use the gralloc buffers we'll exchange with our client
61 mUsage = GRALLOC_USAGE_HW_TEXTURE |
62 GRALLOC_USAGE_SW_READ_RARELY |
63 GRALLOC_USAGE_SW_WRITE_OFTEN;
64}
65
66
67EvsV4lCamera::~EvsV4lCamera() {
68 ALOGD("EvsV4lCamera being destroyed");
69 shutdown();
70}
71
72
73//
74// This gets called if another caller "steals" ownership of the camera
75//
76void EvsV4lCamera::shutdown()
77{
78 ALOGD("EvsV4lCamera shutdown");
79
80 // Make sure our output stream is cleaned up
81 // (It really should be already)
82 stopVideoStream();
83
84 // Note: Since stopVideoStream is blocking, no other threads can now be running
85
86 // Close our video capture device
87 mVideo.close();
88
89 // Drop all the graphics buffers we've been using
90 if (mBuffers.size() > 0) {
91 GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
92 for (auto&& rec : mBuffers) {
93 if (rec.inUse) {
94 ALOGW("Error - releasing buffer despite remote ownership");
95 }
96 alloc.free(rec.handle);
97 rec.handle = nullptr;
98 }
99 mBuffers.clear();
100 }
101}
102
103
104// Methods from ::android::hardware::automotive::evs::V1_0::IEvsCamera follow.
105Return<void> EvsV4lCamera::getCameraInfo(getCameraInfo_cb _hidl_cb) {
106 ALOGD("getCameraInfo");
107
108 // Send back our self description
109 _hidl_cb(mDescription);
110 return Void();
111}
112
113
114Return<EvsResult> EvsV4lCamera::setMaxFramesInFlight(uint32_t bufferCount) {
115 ALOGD("setMaxFramesInFlight");
116 std::lock_guard<std::mutex> lock(mAccessLock);
117
118 // If we've been displaced by another owner of the camera, then we can't do anything else
119 if (!mVideo.isOpen()) {
120 ALOGW("ignoring setMaxFramesInFlight call when camera has been lost.");
121 return EvsResult::OWNERSHIP_LOST;
122 }
123
124 // We cannot function without at least one video buffer to send data
125 if (bufferCount < 1) {
126 ALOGE("Ignoring setMaxFramesInFlight with less than one buffer requested");
127 return EvsResult::INVALID_ARG;
128 }
129
130 // Update our internal state
131 if (setAvailableFrames_Locked(bufferCount)) {
132 return EvsResult::OK;
133 } else {
134 return EvsResult::BUFFER_NOT_AVAILABLE;
135 }
136}
137
138
139Return<EvsResult> EvsV4lCamera::startVideoStream(const ::android::sp<IEvsCameraStream>& stream) {
140 ALOGD("startVideoStream");
141 std::lock_guard<std::mutex> lock(mAccessLock);
142
143 // If we've been displaced by another owner of the camera, then we can't do anything else
144 if (!mVideo.isOpen()) {
145 ALOGW("ignoring startVideoStream call when camera has been lost.");
146 return EvsResult::OWNERSHIP_LOST;
147 }
148 if (mStream.get() != nullptr) {
149 ALOGE("ignoring startVideoStream call when a stream is already running.");
150 return EvsResult::STREAM_ALREADY_RUNNING;
151 }
152
153 // If the client never indicated otherwise, configure ourselves for a single streaming buffer
154 if (mFramesAllowed < 1) {
155 if (!setAvailableFrames_Locked(1)) {
156 ALOGE("Failed to start stream because we couldn't get a graphics buffer");
157 return EvsResult::BUFFER_NOT_AVAILABLE;
158 }
159 }
160
161 // Choose which image transfer function we need
162 // Map from V4L2 to Android graphic buffer format
163 const uint32_t videoSrcFormat = mVideo.getV4LFormat();
164 ALOGI("Configuring to accept %4.4s camera data and convert to NV21", (char*)&videoSrcFormat);
165
166 // TODO: Simplify this by supporting only ONE fixed output format
167 switch (mFormat) {
168 case HAL_PIXEL_FORMAT_YCRCB_420_SP:
169 switch (videoSrcFormat) {
170 case V4L2_PIX_FMT_NV21: mFillBufferFromVideo = fillNV21FromNV21; break;
171 // case V4L2_PIX_FMT_YV12: mFillBufferFromVideo = fillNV21FromYV12; break;
172 case V4L2_PIX_FMT_YUYV: mFillBufferFromVideo = fillNV21FromYUYV; break;
173 // case V4L2_PIX_FORMAT_NV16: mFillBufferFromVideo = fillNV21FromNV16; break;
174 default:
175 // TODO: Are there other V4L2 formats we must support?
176 ALOGE("Unhandled camera output format %c%c%c%c (0x%8X)\n",
177 ((char*)&videoSrcFormat)[0],
178 ((char*)&videoSrcFormat)[1],
179 ((char*)&videoSrcFormat)[2],
180 ((char*)&videoSrcFormat)[3],
181 videoSrcFormat);
182 }
183 break;
184 case HAL_PIXEL_FORMAT_RGBA_8888:
185 switch (videoSrcFormat) {
186 case V4L2_PIX_FMT_YUYV: mFillBufferFromVideo = fillRGBAFromYUYV; break;
187 default:
188 // TODO: Are there other V4L2 formats we must support?
189 ALOGE("Unhandled camera format %4.4s", (char*)&videoSrcFormat);
190 }
191 break;
192 case HAL_PIXEL_FORMAT_YCBCR_422_I:
193 switch (videoSrcFormat) {
194 case V4L2_PIX_FMT_YUYV: mFillBufferFromVideo = fillYUYVFromYUYV; break;
195 default:
196 // TODO: Are there other V4L2 formats we must support?
197 ALOGE("Unhandled camera format %4.4s", (char*)&videoSrcFormat);
198 }
199 break;
200 default:
201 // TODO: Why have we told ourselves to output something we don't understand!?
202 ALOGE("Unhandled output format %4.4s", (char*)&mFormat);
203 }
204
205
206 // Record the user's callback for use when we have a frame ready
207 mStream = stream;
208
209 // Set up the video stream with a callback to our member function forwardFrame()
210 if (!mVideo.startStream([this](VideoCapture*, imageBuffer* tgt, void* data) {
211 this->forwardFrame(tgt, data);
212 })
213 ) {
214 mStream = nullptr; // No need to hold onto this if we failed to start
215 ALOGE("underlying camera start stream failed");
216 return EvsResult::UNDERLYING_SERVICE_ERROR;
217 }
218
219 return EvsResult::OK;
220}
221
222
223Return<void> EvsV4lCamera::doneWithFrame(const BufferDesc& buffer) {
224 ALOGD("doneWithFrame");
225 std::lock_guard <std::mutex> lock(mAccessLock);
226
227 // If we've been displaced by another owner of the camera, then we can't do anything else
228 if (!mVideo.isOpen()) {
229 ALOGW("ignoring doneWithFrame call when camera has been lost.");
230 } else {
231 if (buffer.memHandle == nullptr) {
232 ALOGE("ignoring doneWithFrame called with null handle");
233 } else if (buffer.bufferId >= mBuffers.size()) {
234 ALOGE("ignoring doneWithFrame called with invalid bufferId %d (max is %zu)",
235 buffer.bufferId, mBuffers.size()-1);
236 } else if (!mBuffers[buffer.bufferId].inUse) {
237 ALOGE("ignoring doneWithFrame called on frame %d which is already free",
238 buffer.bufferId);
239 } else {
240 // Mark the frame as available
241 mBuffers[buffer.bufferId].inUse = false;
242 mFramesInUse--;
243
244 // If this frame's index is high in the array, try to move it down
245 // to improve locality after mFramesAllowed has been reduced.
246 if (buffer.bufferId >= mFramesAllowed) {
247 // Find an empty slot lower in the array (which should always exist in this case)
248 for (auto&& rec : mBuffers) {
249 if (rec.handle == nullptr) {
250 rec.handle = mBuffers[buffer.bufferId].handle;
251 mBuffers[buffer.bufferId].handle = nullptr;
252 break;
253 }
254 }
255 }
256 }
257 }
258
259 return Void();
260}
261
262
263Return<void> EvsV4lCamera::stopVideoStream() {
264 ALOGD("stopVideoStream");
265
266 // Tell the capture device to stop (and block until it does)
267 mVideo.stopStream();
268
269 if (mStream != nullptr) {
270 std::unique_lock <std::mutex> lock(mAccessLock);
271
272 // Send one last NULL frame to signal the actual end of stream
273 BufferDesc nullBuff = {};
274 auto result = mStream->deliverFrame(nullBuff);
275 if (!result.isOk()) {
276 ALOGE("Error delivering end of stream marker");
277 }
278
279 // Drop our reference to the client's stream receiver
280 mStream = nullptr;
281 }
282
283 return Void();
284}
285
286
287Return<int32_t> EvsV4lCamera::getExtendedInfo(uint32_t /*opaqueIdentifier*/) {
288 ALOGD("getExtendedInfo");
289 // Return zero by default as required by the spec
290 return 0;
291}
292
293
294Return<EvsResult> EvsV4lCamera::setExtendedInfo(uint32_t /*opaqueIdentifier*/,
295 int32_t /*opaqueValue*/) {
296 ALOGD("setExtendedInfo");
297 std::lock_guard<std::mutex> lock(mAccessLock);
298
299 // If we've been displaced by another owner of the camera, then we can't do anything else
300 if (!mVideo.isOpen()) {
301 ALOGW("ignoring setExtendedInfo call when camera has been lost.");
302 return EvsResult::OWNERSHIP_LOST;
303 }
304
305 // We don't store any device specific information in this implementation
306 return EvsResult::INVALID_ARG;
307}
308
309
310bool EvsV4lCamera::setAvailableFrames_Locked(unsigned bufferCount) {
311 if (bufferCount < 1) {
312 ALOGE("Ignoring request to set buffer count to zero");
313 return false;
314 }
315 if (bufferCount > MAX_BUFFERS_IN_FLIGHT) {
316 ALOGE("Rejecting buffer request in excess of internal limit");
317 return false;
318 }
319
320 // Is an increase required?
321 if (mFramesAllowed < bufferCount) {
322 // An increase is required
323 unsigned needed = bufferCount - mFramesAllowed;
324 ALOGI("Allocating %d buffers for camera frames", needed);
325
326 unsigned added = increaseAvailableFrames_Locked(needed);
327 if (added != needed) {
328 // If we didn't add all the frames we needed, then roll back to the previous state
329 ALOGE("Rolling back to previous frame queue size");
330 decreaseAvailableFrames_Locked(added);
331 return false;
332 }
333 } else if (mFramesAllowed > bufferCount) {
334 // A decrease is required
335 unsigned framesToRelease = mFramesAllowed - bufferCount;
336 ALOGI("Returning %d camera frame buffers", framesToRelease);
337
338 unsigned released = decreaseAvailableFrames_Locked(framesToRelease);
339 if (released != framesToRelease) {
340 // This shouldn't happen with a properly behaving client because the client
341 // should only make this call after returning sufficient outstanding buffers
342 // to allow a clean resize.
343 ALOGE("Buffer queue shrink failed -- too many buffers currently in use?");
344 }
345 }
346
347 return true;
348}
349
350
351unsigned EvsV4lCamera::increaseAvailableFrames_Locked(unsigned numToAdd) {
352 // Acquire the graphics buffer allocator
353 GraphicBufferAllocator &alloc(GraphicBufferAllocator::get());
354
355 unsigned added = 0;
356
357
358 while (added < numToAdd) {
359 unsigned pixelsPerLine;
360 buffer_handle_t memHandle = nullptr;
361 status_t result = alloc.allocate(mVideo.getWidth(), mVideo.getHeight(),
362 mFormat, 1,
363 mUsage,
364 &memHandle, &pixelsPerLine, 0, "EvsV4lCamera");
365 if (result != NO_ERROR) {
366 ALOGE("Error %d allocating %d x %d graphics buffer",
367 result,
368 mVideo.getWidth(),
369 mVideo.getHeight());
370 break;
371 }
372 if (!memHandle) {
373 ALOGE("We didn't get a buffer handle back from the allocator");
374 break;
375 }
376 if (mStride) {
377 if (mStride != pixelsPerLine) {
378 ALOGE("We did not expect to get buffers with different strides!");
379 }
380 } else {
381 // Gralloc defines stride in terms of pixels per line
382 mStride = pixelsPerLine;
383 }
384
385 // Find a place to store the new buffer
386 bool stored = false;
387 for (auto&& rec : mBuffers) {
388 if (rec.handle == nullptr) {
389 // Use this existing entry
390 rec.handle = memHandle;
391 rec.inUse = false;
392 stored = true;
393 break;
394 }
395 }
396 if (!stored) {
397 // Add a BufferRecord wrapping this handle to our set of available buffers
398 mBuffers.emplace_back(memHandle);
399 }
400
401 mFramesAllowed++;
402 added++;
403 }
404
405 return added;
406}
407
408
409unsigned EvsV4lCamera::decreaseAvailableFrames_Locked(unsigned numToRemove) {
410 // Acquire the graphics buffer allocator
411 GraphicBufferAllocator &alloc(GraphicBufferAllocator::get());
412
413 unsigned removed = 0;
414
415 for (auto&& rec : mBuffers) {
416 // Is this record not in use, but holding a buffer that we can free?
417 if ((rec.inUse == false) && (rec.handle != nullptr)) {
418 // Release buffer and update the record so we can recognize it as "empty"
419 alloc.free(rec.handle);
420 rec.handle = nullptr;
421
422 mFramesAllowed--;
423 removed++;
424
425 if (removed == numToRemove) {
426 break;
427 }
428 }
429 }
430
431 return removed;
432}
433
434
435// This is the async callback from the video camera that tells us a frame is ready
436void EvsV4lCamera::forwardFrame(imageBuffer* /*pV4lBuff*/, void* pData) {
437 bool readyForFrame = false;
438 size_t idx = 0;
439
440 // Lock scope for updating shared state
441 {
442 std::lock_guard<std::mutex> lock(mAccessLock);
443
444 // Are we allowed to issue another buffer?
445 if (mFramesInUse >= mFramesAllowed) {
446 // Can't do anything right now -- skip this frame
447 ALOGW("Skipped a frame because too many are in flight\n");
448 } else {
449 // Identify an available buffer to fill
450 for (idx = 0; idx < mBuffers.size(); idx++) {
451 if (!mBuffers[idx].inUse) {
452 if (mBuffers[idx].handle != nullptr) {
453 // Found an available record, so stop looking
454 break;
455 }
456 }
457 }
458 if (idx >= mBuffers.size()) {
459 // This shouldn't happen since we already checked mFramesInUse vs mFramesAllowed
460 ALOGE("Failed to find an available buffer slot\n");
461 } else {
462 // We're going to make the frame busy
463 mBuffers[idx].inUse = true;
464 mFramesInUse++;
465 readyForFrame = true;
466 }
467 }
468 }
469
470 if (!readyForFrame) {
471 // We need to return the vide buffer so it can capture a new frame
472 mVideo.markFrameConsumed();
473 } else {
474 // Assemble the buffer description we'll transmit below
475 BufferDesc buff = {};
476 buff.width = mVideo.getWidth();
477 buff.height = mVideo.getHeight();
478 buff.stride = mStride;
479 buff.format = mFormat;
480 buff.usage = mUsage;
481 buff.bufferId = idx;
482 buff.memHandle = mBuffers[idx].handle;
483
484 // Lock our output buffer for writing
485 void *targetPixels = nullptr;
486 GraphicBufferMapper &mapper = GraphicBufferMapper::get();
487 mapper.lock(buff.memHandle,
488 GRALLOC_USAGE_SW_WRITE_OFTEN | GRALLOC_USAGE_SW_READ_NEVER,
489 android::Rect(buff.width, buff.height),
490 (void **) &targetPixels);
491
492 // If we failed to lock the pixel buffer, we're about to crash, but log it first
493 if (!targetPixels) {
494 ALOGE("Camera failed to gain access to image buffer for writing");
495 }
496
497 // Transfer the video image into the output buffer, making any needed
498 // format conversion along the way
499 mFillBufferFromVideo(buff, (uint8_t*)targetPixels, pData, mVideo.getStride());
500
501 // Unlock the output buffer
502 mapper.unlock(buff.memHandle);
503
504
505 // Give the video frame back to the underlying device for reuse
506 // Note that we do this before making the client callback to give the underlying
507 // camera more time to capture the next frame.
508 mVideo.markFrameConsumed();
509
510 // Issue the (asynchronous) callback to the client -- can't be holding the lock
511 auto result = mStream->deliverFrame(buff);
512 if (result.isOk()) {
513 ALOGD("Delivered %p as id %d", buff.memHandle.getNativeHandle(), buff.bufferId);
514 } else {
515 // This can happen if the client dies and is likely unrecoverable.
516 // To avoid consuming resources generating failing calls, we stop sending
517 // frames. Note, however, that the stream remains in the "STREAMING" state
518 // until cleaned up on the main thread.
519 ALOGE("Frame delivery call failed in the transport layer.");
520
521 // Since we didn't actually deliver it, mark the frame as available
522 std::lock_guard<std::mutex> lock(mAccessLock);
523 mBuffers[idx].inUse = false;
524 mFramesInUse--;
525 }
526 }
527}
528
529} // namespace implementation
530} // namespace V1_0
531} // namespace evs
532} // namespace automotive
533} // namespace hardware
534} // namespace android