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