• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 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 
19 #include "bufferCopy.h"
20 
21 #include <aidl/android/hardware/graphics/common/HardwareBufferDescription.h>
22 #include <aidlcommonsupport/NativeHandle.h>
23 #include <android-base/logging.h>
24 #include <android-base/unique_fd.h>
25 #include <android/hardware_buffer.h>
26 #include <ui/GraphicBufferAllocator.h>
27 #include <ui/GraphicBufferMapper.h>
28 #include <utils/SystemClock.h>
29 
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 
33 namespace {
34 
35 using ::aidl::android::hardware::graphics::common::BufferUsage;
36 using ::aidl::android::hardware::graphics::common::HardwareBufferDescription;
37 using ::android::base::Error;
38 using ::android::base::Result;
39 using ::ndk::ScopedAStatus;
40 
41 // Default camera output image resolution
42 constexpr std::array<int32_t, 2> kDefaultResolution = {640, 480};
43 
44 // Arbitrary limit on number of graphics buffers allowed to be allocated
45 // Safeguards against unreasonable resource consumption and provides a testable limit
46 constexpr unsigned kMaxBuffersInFlight = 100;
47 
48 }  // namespace
49 
50 namespace aidl::android::hardware::automotive::evs::implementation {
51 
EvsV4lCamera(const char * deviceName,std::unique_ptr<ConfigManager::CameraInfo> & camInfo)52 EvsV4lCamera::EvsV4lCamera(const char* deviceName,
53                            std::unique_ptr<ConfigManager::CameraInfo>& camInfo) :
54       mFramesAllowed(0), mFramesInUse(0), mCameraInfo(camInfo) {
55     LOG(DEBUG) << "EvsV4lCamera instantiated";
56 
57     mDescription.id = deviceName;
58     if (camInfo) {
59         uint8_t* ptr = reinterpret_cast<uint8_t*>(camInfo->characteristics);
60         const size_t len = get_camera_metadata_size(camInfo->characteristics);
61         mDescription.metadata.insert(mDescription.metadata.end(), ptr, ptr + len);
62     }
63 
64     // Default output buffer format.
65     mFormat = HAL_PIXEL_FORMAT_RGBA_8888;
66 
67     // How we expect to use the gralloc buffers we'll exchange with our client
68     mUsage = GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_SW_READ_RARELY | GRALLOC_USAGE_SW_WRITE_OFTEN;
69 }
70 
~EvsV4lCamera()71 EvsV4lCamera::~EvsV4lCamera() {
72     LOG(DEBUG) << "EvsV4lCamera being destroyed";
73     shutdown();
74 }
75 
76 // This gets called if another caller "steals" ownership of the camera
shutdown()77 void EvsV4lCamera::shutdown() {
78     LOG(DEBUG) << "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         ::android::GraphicBufferAllocator& alloc(::android::GraphicBufferAllocator::get());
92         for (auto&& rec : mBuffers) {
93             if (rec.inUse) {
94                 LOG(WARNING) << "Releasing buffer despite remote ownership";
95             }
96             alloc.free(rec.handle);
97             rec.handle = nullptr;
98         }
99         mBuffers.clear();
100     }
101 }
102 
103 // Methods from ::aidl::android::hardware::automotive::evs::IEvsCamera follow.
getCameraInfo(CameraDesc * _aidl_return)104 ScopedAStatus EvsV4lCamera::getCameraInfo(CameraDesc* _aidl_return) {
105     LOG(DEBUG) << __FUNCTION__;
106 
107     // Send back our self description
108     *_aidl_return = mDescription;
109     return ScopedAStatus::ok();
110 }
111 
setMaxFramesInFlight(int32_t bufferCount)112 ScopedAStatus EvsV4lCamera::setMaxFramesInFlight(int32_t bufferCount) {
113     LOG(DEBUG) << __FUNCTION__;
114     std::lock_guard<std::mutex> lock(mAccessLock);
115 
116     // If we've been displaced by another owner of the camera, then we can't do anything else
117     if (!mVideo.isOpen()) {
118         LOG(WARNING) << "Ignoring setMaxFramesInFlight call when camera has been lost.";
119         return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::OWNERSHIP_LOST));
120     }
121 
122     // We cannot function without at least one video buffer to send data
123     if (bufferCount < 1) {
124         LOG(ERROR) << "Ignoring setMaxFramesInFlight with less than one buffer requested";
125         return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::INVALID_ARG));
126     }
127 
128     // Update our internal state
129     if (setAvailableFrames_Locked(bufferCount)) {
130         return ScopedAStatus::ok();
131     } else {
132         return ScopedAStatus::fromServiceSpecificError(
133                 static_cast<int>(EvsResult::BUFFER_NOT_AVAILABLE));
134     }
135 }
136 
startVideoStream(const std::shared_ptr<IEvsCameraStream> & client)137 ScopedAStatus EvsV4lCamera::startVideoStream(const std::shared_ptr<IEvsCameraStream>& client) {
138     LOG(DEBUG) << __FUNCTION__;
139     std::lock_guard<std::mutex> lock(mAccessLock);
140 
141     // If we've been displaced by another owner of the camera, then we can't do anything else
142     if (!mVideo.isOpen()) {
143         LOG(WARNING) << "Ignoring startVideoStream call when camera has been lost.";
144         return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::OWNERSHIP_LOST));
145     }
146 
147     if (mStream) {
148         LOG(ERROR) << "Ignoring startVideoStream call when a stream is already running.";
149         return ScopedAStatus::fromServiceSpecificError(
150                 static_cast<int>(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             LOG(ERROR) << "Failed to start stream because we couldn't get a graphics buffer";
157             return ScopedAStatus::fromServiceSpecificError(
158                     static_cast<int>(EvsResult::BUFFER_NOT_AVAILABLE));
159         }
160     }
161 
162     // Choose which image transfer function we need
163     // Map from V4L2 to Android graphic buffer format
164     const auto videoSrcFormat = mVideo.getV4LFormat();
165     LOG(INFO) << "Configuring to accept " << std::string((char*)&videoSrcFormat)
166               << " camera data and convert to " << std::hex << mFormat;
167 
168     switch (mFormat) {
169         case HAL_PIXEL_FORMAT_YCRCB_420_SP:
170             switch (videoSrcFormat) {
171                 case V4L2_PIX_FMT_NV21:
172                     mFillBufferFromVideo = fillNV21FromNV21;
173                     break;
174                 case V4L2_PIX_FMT_YUYV:
175                     mFillBufferFromVideo = fillNV21FromYUYV;
176                     break;
177                 default:
178                     LOG(ERROR) << "Unhandled camera output format: " << ((char*)&videoSrcFormat)[0]
179                                << ((char*)&videoSrcFormat)[1] << ((char*)&videoSrcFormat)[2]
180                                << ((char*)&videoSrcFormat)[3] << std::hex << videoSrcFormat;
181             }
182             break;
183         case HAL_PIXEL_FORMAT_RGBA_8888:
184             switch (videoSrcFormat) {
185                 case V4L2_PIX_FMT_YUYV:
186                     mFillBufferFromVideo = fillRGBAFromYUYV;
187                     break;
188                 default:
189                     LOG(ERROR) << "Unhandled camera source format " << (char*)&videoSrcFormat;
190             }
191             break;
192         case HAL_PIXEL_FORMAT_YCBCR_422_I:
193             switch (videoSrcFormat) {
194                 case V4L2_PIX_FMT_YUYV:
195                     mFillBufferFromVideo = fillYUYVFromYUYV;
196                     break;
197                 case V4L2_PIX_FMT_UYVY:
198                     mFillBufferFromVideo = fillYUYVFromUYVY;
199                     break;
200                 default:
201                     LOG(ERROR) << "Unhandled camera source format " << (char*)&videoSrcFormat;
202             }
203             break;
204         default:
205             LOG(ERROR) << "Unhandled camera format " << (char*)&mFormat;
206     }
207 
208     // Record the user's callback for use when we have a frame ready
209     mStream = client;
210 
211     // Set up the video stream with a callback to our member function forwardFrame()
212     if (!mVideo.startStream([this](VideoCapture*, imageBuffer* tgt, void* data) {
213             this->forwardFrame(tgt, data);
214         })) {
215         // No need to hold onto this if we failed to start
216         mStream = nullptr;
217         LOG(ERROR) << "Underlying camera start stream failed";
218         return ScopedAStatus::fromServiceSpecificError(
219                 static_cast<int>(EvsResult::UNDERLYING_SERVICE_ERROR));
220     }
221 
222     return ScopedAStatus::ok();
223 }
224 
stopVideoStream()225 ScopedAStatus EvsV4lCamera::stopVideoStream() {
226     LOG(DEBUG) << __FUNCTION__;
227 
228     // Tell the capture device to stop (and block until it does)
229     mVideo.stopStream();
230     if (mStream) {
231         std::unique_lock<std::mutex> lock(mAccessLock);
232 
233         EvsEventDesc event;
234         event.aType = EvsEventType::STREAM_STOPPED;
235         auto result = mStream->notify(event);
236         if (!result.isOk()) {
237             LOG(WARNING) << "Error delivering end of stream event";
238         }
239 
240         // Drop our reference to the client's stream receiver
241         mStream = nullptr;
242     }
243 
244     return ScopedAStatus::ok();
245 }
246 
getPhysicalCameraInfo(const std::string & id,CameraDesc * _aidl_return)247 ScopedAStatus EvsV4lCamera::getPhysicalCameraInfo([[maybe_unused]] const std::string& id,
248                                                   CameraDesc* _aidl_return) {
249     LOG(DEBUG) << __FUNCTION__;
250 
251     // This method works exactly same as getCameraInfo_1_1() in EVS HW module.
252     *_aidl_return = mDescription;
253     return ScopedAStatus::ok();
254 }
255 
doneWithFrame(const std::vector<BufferDesc> & buffers)256 ScopedAStatus EvsV4lCamera::doneWithFrame(const std::vector<BufferDesc>& buffers) {
257     LOG(DEBUG) << __FUNCTION__;
258 
259     for (const auto& buffer : buffers) {
260         doneWithFrame_impl(buffer);
261     }
262 
263     return ScopedAStatus::ok();
264 }
265 
pauseVideoStream()266 ScopedAStatus EvsV4lCamera::pauseVideoStream() {
267     return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::NOT_SUPPORTED));
268 }
269 
resumeVideoStream()270 ScopedAStatus EvsV4lCamera::resumeVideoStream() {
271     return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::NOT_SUPPORTED));
272 }
273 
setPrimaryClient()274 ScopedAStatus EvsV4lCamera::setPrimaryClient() {
275     /* Because EVS HW module reference implementation expects a single client at
276      * a time, this returns a success code always.
277      */
278     return ScopedAStatus::ok();
279 }
280 
forcePrimaryClient(const std::shared_ptr<IEvsDisplay> &)281 ScopedAStatus EvsV4lCamera::forcePrimaryClient(const std::shared_ptr<IEvsDisplay>&) {
282     /* Because EVS HW module reference implementation expects a single client at
283      * a time, this returns a success code always.
284      */
285     return ScopedAStatus::ok();
286 }
287 
unsetPrimaryClient()288 ScopedAStatus EvsV4lCamera::unsetPrimaryClient() {
289     /* Because EVS HW module reference implementation expects a single client at
290      * a time, there is no chance that this is called by the secondary client and
291      * therefore returns a success code always.
292      */
293     return ScopedAStatus::ok();
294 }
295 
getParameterList(std::vector<CameraParam> * _aidl_return)296 ScopedAStatus EvsV4lCamera::getParameterList(std::vector<CameraParam>* _aidl_return) {
297     if (mCameraInfo) {
298         _aidl_return->resize(mCameraInfo->controls.size());
299         auto idx = 0;
300         for (auto& [name, range] : mCameraInfo->controls) {
301             (*_aidl_return)[idx++] = name;
302         }
303     }
304 
305     return ScopedAStatus::ok();
306 }
307 
getIntParameterRange(CameraParam id,ParameterRange * _aidl_return)308 ScopedAStatus EvsV4lCamera::getIntParameterRange(CameraParam id, ParameterRange* _aidl_return) {
309     if (!mCameraInfo) {
310         return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::NOT_SUPPORTED));
311     }
312 
313     auto it = mCameraInfo->controls.find(id);
314     if (it == mCameraInfo->controls.end()) {
315         return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::NOT_SUPPORTED));
316     }
317 
318     _aidl_return->min = std::get<0>(it->second);
319     _aidl_return->max = std::get<1>(it->second);
320     _aidl_return->step = std::get<2>(it->second);
321 
322     return ScopedAStatus::ok();
323 }
324 
setIntParameter(CameraParam id,int32_t value,std::vector<int32_t> * effectiveValue)325 ScopedAStatus EvsV4lCamera::setIntParameter(CameraParam id, int32_t value,
326                                             std::vector<int32_t>* effectiveValue) {
327     uint32_t v4l2cid = V4L2_CID_BASE;
328     if (!convertToV4l2CID(id, v4l2cid)) {
329         return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::INVALID_ARG));
330     } else {
331         v4l2_control control = {v4l2cid, value};
332         if (mVideo.setParameter(control) < 0 || mVideo.getParameter(control) < 0) {
333             return ScopedAStatus::fromServiceSpecificError(
334                     static_cast<int>(EvsResult::UNDERLYING_SERVICE_ERROR));
335         }
336 
337         (*effectiveValue)[0] = control.value;
338     }
339 
340     return ScopedAStatus::ok();
341 }
342 
getIntParameter(CameraParam id,std::vector<int32_t> * value)343 ScopedAStatus EvsV4lCamera::getIntParameter(CameraParam id, std::vector<int32_t>* value) {
344     uint32_t v4l2cid = V4L2_CID_BASE;
345     if (!convertToV4l2CID(id, v4l2cid)) {
346         return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::INVALID_ARG));
347     } else {
348         v4l2_control control = {v4l2cid, 0};
349         if (mVideo.getParameter(control) < 0) {
350             return ScopedAStatus::fromServiceSpecificError(
351                     static_cast<int>(EvsResult::INVALID_ARG));
352         }
353 
354         // Report a result
355         (*value)[0] = control.value;
356     }
357 
358     return ScopedAStatus::ok();
359 }
360 
setExtendedInfo(int32_t opaqueIdentifier,const std::vector<uint8_t> & opaqueValue)361 ScopedAStatus EvsV4lCamera::setExtendedInfo(int32_t opaqueIdentifier,
362                                             const std::vector<uint8_t>& opaqueValue) {
363     mExtInfo.insert_or_assign(opaqueIdentifier, opaqueValue);
364     return ScopedAStatus::ok();
365 }
366 
getExtendedInfo(int32_t opaqueIdentifier,std::vector<uint8_t> * opaqueValue)367 ScopedAStatus EvsV4lCamera::getExtendedInfo(int32_t opaqueIdentifier,
368                                             std::vector<uint8_t>* opaqueValue) {
369     const auto it = mExtInfo.find(opaqueIdentifier);
370     if (it == mExtInfo.end()) {
371         return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::INVALID_ARG));
372     } else {
373         *opaqueValue = mExtInfo[opaqueIdentifier];
374     }
375 
376     return ScopedAStatus::ok();
377 }
378 
importExternalBuffers(const std::vector<BufferDesc> & buffers,int32_t * _aidl_return)379 ScopedAStatus EvsV4lCamera::importExternalBuffers(const std::vector<BufferDesc>& buffers,
380                                                   int32_t* _aidl_return) {
381     LOG(DEBUG) << __FUNCTION__;
382 
383     // If we've been displaced by another owner of the camera, then we can't do anything else
384     if (!mVideo.isOpen()) {
385         LOG(WARNING) << "Ignoring a request add external buffers " << "when camera has been lost.";
386         *_aidl_return = 0;
387         return ScopedAStatus::fromServiceSpecificError(static_cast<int>(EvsResult::OWNERSHIP_LOST));
388     }
389 
390     size_t numBuffersToAdd = buffers.size();
391     if (numBuffersToAdd < 1) {
392         LOG(DEBUG) << "No buffers to add.";
393         *_aidl_return = 0;
394         return ScopedAStatus::ok();
395     }
396 
397     {
398         std::lock_guard<std::mutex> lock(mAccessLock);
399         if (numBuffersToAdd > (kMaxBuffersInFlight - mFramesAllowed)) {
400             numBuffersToAdd -= (kMaxBuffersInFlight - mFramesAllowed);
401             LOG(WARNING) << "Exceed the limit on number of buffers.  " << numBuffersToAdd
402                          << " buffers will be added only.";
403         }
404 
405         ::android::GraphicBufferMapper& mapper = ::android::GraphicBufferMapper::get();
406         const auto before = mFramesAllowed;
407         for (size_t i = 0; i < numBuffersToAdd; ++i) {
408             // TODO: reject if external buffer is configured differently.
409             auto& b = buffers[i];
410             const HardwareBufferDescription& description = b.buffer.description;
411 
412             // Import a buffer to add
413             buffer_handle_t memHandle = nullptr;
414             const auto result =
415                     mapper.importBuffer(::android::dupFromAidl(b.buffer.handle), description.width,
416                                         description.height, 1,
417                                         static_cast<::android::PixelFormat>(description.format),
418                                         static_cast<uint64_t>(description.usage),
419                                         description.stride, &memHandle);
420             if (result != ::android::NO_ERROR || memHandle == nullptr) {
421                 LOG(WARNING) << "Failed to import a buffer " << b.bufferId;
422                 continue;
423             }
424 
425             auto stored = false;
426             for (auto&& rec : mBuffers) {
427                 if (rec.handle == nullptr) {
428                     // Use this existing entry
429                     rec.handle = memHandle;
430                     rec.inUse = false;
431 
432                     stored = true;
433                     break;
434                 }
435             }
436 
437             if (!stored) {
438                 // Add a BufferRecord wrapping this handle to our set of available buffers
439                 mBuffers.push_back(std::move(BufferRecord(memHandle)));
440             }
441 
442             ++mFramesAllowed;
443         }
444 
445         *_aidl_return = mFramesAllowed - before;
446         return ScopedAStatus::ok();
447     }
448 }
449 
doneWithFrame_impl(const BufferDesc & bufferDesc)450 EvsResult EvsV4lCamera::doneWithFrame_impl(const BufferDesc& bufferDesc) {
451     if (!mVideo.isOpen()) {
452         LOG(WARNING) << "Ignoring doneWithFrame call when camera has been lost.";
453         return EvsResult::OK;
454     }
455 
456     if (static_cast<uint32_t>(bufferDesc.bufferId) >= mBuffers.size()) {
457         LOG(WARNING) << "Ignoring doneWithFrame called with invalid id " << bufferDesc.bufferId
458                      << " (max is " << mBuffers.size() - 1 << ")";
459         return EvsResult::OK;
460     }
461 
462     // Mark this buffer as available
463     {
464         std::lock_guard<std::mutex> lock(mAccessLock);
465         mBuffers[bufferDesc.bufferId].inUse = false;
466         --mFramesInUse;
467 
468         // If this frame's index is high in the array, try to move it down
469         // to improve locality after mFramesAllowed has been reduced.
470         if (static_cast<uint32_t>(bufferDesc.bufferId) >= mFramesAllowed) {
471             // Find an empty slot lower in the array (which should always exist in this case)
472             bool found = false;
473             for (auto&& rec : mBuffers) {
474                 if (!rec.handle) {
475                     rec.handle = mBuffers[bufferDesc.bufferId].handle;
476                     mBuffers[bufferDesc.bufferId].handle = nullptr;
477                     found = true;
478                     break;
479                 }
480             }
481 
482             if (!found) {
483                 LOG(WARNING) << "No empty slot!";
484             }
485         }
486     }
487 
488     return EvsResult::OK;
489 }
490 
doneWithFrame_impl(uint32_t bufferId,buffer_handle_t handle)491 EvsResult EvsV4lCamera::doneWithFrame_impl(uint32_t bufferId, buffer_handle_t handle) {
492     std::lock_guard<std::mutex> lock(mAccessLock);
493 
494     // If we've been displaced by another owner of the camera, then we can't do anything else
495     if (!mVideo.isOpen()) {
496         LOG(WARNING) << "Ignoring doneWithFrame call when camera has been lost.";
497         return EvsResult::OK;
498     }
499 
500     if (handle == nullptr) {
501         LOG(ERROR) << "Ignoring doneWithFrame called with null handle";
502     } else if (bufferId >= mBuffers.size()) {
503         LOG(ERROR) << "Ignoring doneWithFrame called with invalid bufferId " << bufferId
504                    << " (max is " << mBuffers.size() - 1 << ")";
505     } else if (!mBuffers[bufferId].inUse) {
506         LOG(ERROR) << "Ignoring doneWithFrame called on frame " << bufferId
507                    << " which is already free";
508     } else {
509         // Mark the frame as available
510         mBuffers[bufferId].inUse = false;
511         --mFramesInUse;
512 
513         // If this frame's index is high in the array, try to move it down
514         // to improve locality after mFramesAllowed has been reduced.
515         if (bufferId >= mFramesAllowed) {
516             // Find an empty slot lower in the array (which should always exist in this case)
517             bool found = false;
518             for (auto&& rec : mBuffers) {
519                 if (!rec.handle) {
520                     rec.handle = mBuffers[bufferId].handle;
521                     mBuffers[bufferId].handle = nullptr;
522                     found = true;
523                     break;
524                 }
525             }
526 
527             if (!found) {
528                 LOG(WARNING) << "No empty slot!";
529             }
530         }
531     }
532 
533     return EvsResult::OK;
534 }
535 
setAvailableFrames_Locked(unsigned bufferCount)536 bool EvsV4lCamera::setAvailableFrames_Locked(unsigned bufferCount) {
537     if (bufferCount < 1) {
538         LOG(ERROR) << "Ignoring request to set buffer count to zero";
539         return false;
540     }
541     if (bufferCount > kMaxBuffersInFlight) {
542         LOG(ERROR) << "Rejecting buffer request in excess of internal limit";
543         return false;
544     }
545 
546     // Is an increase required?
547     if (mFramesAllowed < bufferCount) {
548         // An increase is required
549         auto needed = bufferCount - mFramesAllowed;
550         LOG(INFO) << "Allocating " << needed << " buffers for camera frames";
551 
552         auto added = increaseAvailableFrames_Locked(needed);
553         if (added != needed) {
554             // If we didn't add all the frames we needed, then roll back to the previous state
555             LOG(ERROR) << "Rolling back to previous frame queue size";
556             decreaseAvailableFrames_Locked(added);
557             return false;
558         }
559     } else if (mFramesAllowed > bufferCount) {
560         // A decrease is required
561         auto framesToRelease = mFramesAllowed - bufferCount;
562         LOG(INFO) << "Returning " << framesToRelease << " camera frame buffers";
563 
564         auto released = decreaseAvailableFrames_Locked(framesToRelease);
565         if (released != framesToRelease) {
566             // This shouldn't happen with a properly behaving client because the client
567             // should only make this call after returning sufficient outstanding buffers
568             // to allow a clean resize.
569             LOG(ERROR) << "Buffer queue shrink failed -- too many buffers currently in use?";
570         }
571     }
572 
573     return true;
574 }
575 
increaseAvailableFrames_Locked(unsigned numToAdd)576 unsigned EvsV4lCamera::increaseAvailableFrames_Locked(unsigned numToAdd) {
577     // Acquire the graphics buffer allocator
578     ::android::GraphicBufferAllocator& alloc(::android::GraphicBufferAllocator::get());
579 
580     unsigned added = 0;
581     while (added < numToAdd) {
582         unsigned pixelsPerLine = 0;
583         buffer_handle_t memHandle = nullptr;
584         auto result = alloc.allocate(mVideo.getWidth(), mVideo.getHeight(), mFormat, 1, mUsage,
585                                      &memHandle, &pixelsPerLine, 0, "EvsV4lCamera");
586         if (result != ::android::NO_ERROR) {
587             LOG(ERROR) << "Error " << result << " allocating " << mVideo.getWidth() << " x "
588                        << mVideo.getHeight() << " graphics buffer";
589             break;
590         }
591         if (memHandle == nullptr) {
592             LOG(ERROR) << "We didn't get a buffer handle back from the allocator";
593             break;
594         }
595         if (mStride > 0) {
596             if (mStride != pixelsPerLine) {
597                 LOG(ERROR) << "We did not expect to get buffers with different strides!";
598             }
599         } else {
600             // Gralloc defines stride in terms of pixels per line
601             mStride = pixelsPerLine;
602         }
603 
604         // Find a place to store the new buffer
605         auto stored = false;
606         for (auto&& rec : mBuffers) {
607             if (rec.handle == nullptr) {
608                 // Use this existing entry
609                 rec.handle = memHandle;
610                 rec.inUse = false;
611                 stored = true;
612                 break;
613             }
614         }
615         if (!stored) {
616             // Add a BufferRecord wrapping this handle to our set of available buffers
617             mBuffers.push_back(std::move(BufferRecord(memHandle)));
618         }
619 
620         ++mFramesAllowed;
621         ++added;
622     }
623 
624     return added;
625 }
626 
decreaseAvailableFrames_Locked(unsigned numToRemove)627 unsigned EvsV4lCamera::decreaseAvailableFrames_Locked(unsigned numToRemove) {
628     // Acquire the graphics buffer allocator
629     ::android::GraphicBufferAllocator& alloc(::android::GraphicBufferAllocator::get());
630 
631     unsigned removed = 0;
632     for (auto&& rec : mBuffers) {
633         // Is this record not in use, but holding a buffer that we can free?
634         if ((rec.inUse == false) && (rec.handle != nullptr)) {
635             // Release buffer and update the record so we can recognize it as "empty"
636             alloc.free(rec.handle);
637             rec.handle = nullptr;
638 
639             --mFramesAllowed;
640             ++removed;
641 
642             if (removed == numToRemove) {
643                 break;
644             }
645         }
646     }
647 
648     return removed;
649 }
650 
651 // This is the async callback from the video camera that tells us a frame is ready
forwardFrame(imageBuffer * pV4lBuff,void * pData)652 void EvsV4lCamera::forwardFrame(imageBuffer* pV4lBuff, void* pData) {
653     LOG(DEBUG) << __FUNCTION__;
654     bool readyForFrame = false;
655     unsigned idx = 0;
656 
657     // Lock scope for updating shared state
658     {
659         std::lock_guard<std::mutex> lock(mAccessLock);
660 
661         // Are we allowed to issue another buffer?
662         if (mFramesInUse >= mFramesAllowed) {
663             // Can't do anything right now -- skip this frame
664             LOG(WARNING) << "Skipped a frame because too many are in flight";
665         } else {
666             // Identify an available buffer to fill
667             for (idx = 0; idx < mBuffers.size(); idx++) {
668                 if (!mBuffers[idx].inUse) {
669                     if (mBuffers[idx].handle != nullptr) {
670                         // Found an available record, so stop looking
671                         break;
672                     }
673                 }
674             }
675             if (idx >= mBuffers.size()) {
676                 // This shouldn't happen since we already checked mFramesInUse vs mFramesAllowed
677                 LOG(ERROR) << "Failed to find an available buffer slot";
678             } else {
679                 // We're going to make the frame busy
680                 mBuffers[idx].inUse = true;
681                 mFramesInUse++;
682                 readyForFrame = true;
683             }
684         }
685     }
686 
687     if (mDumpFrame) {
688         // Construct a target filename with the device identifier
689         std::string filename = std::string(mDescription.id);
690         std::replace(filename.begin(), filename.end(), '/', '_');
691         filename = mDumpPath + filename + "_" + std::to_string(mFrameCounter) + ".bin";
692 
693         ::android::base::unique_fd fd(
694                 open(filename.data(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP));
695         LOG(ERROR) << filename << ", " << fd;
696         if (fd == -1) {
697             PLOG(ERROR) << "Failed to open a file, " << filename;
698         } else {
699             auto width = mVideo.getWidth();
700             auto height = mVideo.getHeight();
701             auto len = write(fd.get(), &width, sizeof(width));
702             len += write(fd.get(), &height, sizeof(height));
703             len += write(fd.get(), &mStride, sizeof(mStride));
704             len += write(fd.get(), &mFormat, sizeof(mFormat));
705             len += write(fd.get(), pData, pV4lBuff->length);
706             LOG(INFO) << len << " bytes are written to " << filename;
707         }
708     }
709 
710     if (!readyForFrame) {
711         // We need to return the video buffer so it can capture a new frame
712         mVideo.markFrameConsumed(pV4lBuff->index);
713     } else {
714         using AidlPixelFormat = ::aidl::android::hardware::graphics::common::PixelFormat;
715 
716         // Assemble the buffer description we'll transmit below
717         buffer_handle_t memHandle = mBuffers[idx].handle;
718         BufferDesc bufferDesc = {
719                 .buffer =
720                         {
721                                 .description =
722                                         {
723                                                 .width = static_cast<int32_t>(mVideo.getWidth()),
724                                                 .height = static_cast<int32_t>(mVideo.getHeight()),
725                                                 .layers = 1,
726                                                 .format = static_cast<AidlPixelFormat>(mFormat),
727                                                 .usage = static_cast<BufferUsage>(mUsage),
728                                                 .stride = static_cast<int32_t>(mStride),
729                                         },
730                                 .handle = ::android::dupToAidl(memHandle),
731                         },
732                 .bufferId = static_cast<int32_t>(idx),
733                 .deviceId = mDescription.id,
734                 .timestamp = static_cast<int64_t>(::android::elapsedRealtimeNano() * 1e+3),
735         };
736 
737         // Lock our output buffer for writing
738         // TODO(b/145459970): Sometimes, physical camera device maps a buffer
739         // into the address that is about to be unmapped by another device; this
740         // causes SEGV_MAPPER.
741         void* targetPixels = nullptr;
742         ::android::GraphicBufferMapper& mapper = ::android::GraphicBufferMapper::get();
743         auto result =
744                 mapper.lock(memHandle, GRALLOC_USAGE_SW_WRITE_OFTEN | GRALLOC_USAGE_SW_READ_NEVER,
745                             ::android::Rect(bufferDesc.buffer.description.width,
746                                             bufferDesc.buffer.description.height),
747                             (void**)&targetPixels);
748 
749         // If we failed to lock the pixel buffer, we're about to crash, but log it first
750         if (!targetPixels) {
751             // TODO(b/145457727): When EvsHidlTest::CameraToDisplayRoundTrip
752             // test case was repeatedly executed, EVS occasionally fails to map
753             // a buffer.
754             LOG(ERROR) << "Camera failed to gain access to image buffer for writing - "
755                        << " status: " << ::android::statusToString(result);
756         }
757 
758         // Transfer the video image into the output buffer, making any needed
759         // format conversion along the way
760         mFillBufferFromVideo(bufferDesc, (uint8_t*)targetPixels, pData, mVideo.getStride());
761 
762         // Unlock the output buffer
763         mapper.unlock(memHandle);
764 
765         // Give the video frame back to the underlying device for reuse
766         // Note that we do this before making the client callback to give the
767         // underlying camera more time to capture the next frame
768         mVideo.markFrameConsumed(pV4lBuff->index);
769 
770         // Issue the (asynchronous) callback to the client -- can't be holding
771         // the lock
772         auto flag = false;
773         if (mStream) {
774             std::vector<BufferDesc> frames;
775             frames.push_back(std::move(bufferDesc));
776             flag = mStream->deliverFrame(frames).isOk();
777         }
778 
779         if (flag) {
780             LOG(DEBUG) << "Delivered " << memHandle << " as id " << bufferDesc.bufferId;
781         } else {
782             // This can happen if the client dies and is likely unrecoverable.
783             // To avoid consuming resources generating failing calls, we stop sending
784             // frames.  Note, however, that the stream remains in the "STREAMING" state
785             // until cleaned up on the main thread.
786             LOG(ERROR) << "Frame delivery call failed in the transport layer.";
787 
788             // Since we didn't actually deliver it, mark the frame as available
789             std::lock_guard<std::mutex> lock(mAccessLock);
790             mBuffers[idx].inUse = false;
791             --mFramesInUse;
792         }
793     }
794 
795     // Increse a frame counter
796     ++mFrameCounter;
797 }
798 
convertToV4l2CID(CameraParam id,uint32_t & v4l2cid)799 bool EvsV4lCamera::convertToV4l2CID(CameraParam id, uint32_t& v4l2cid) {
800     switch (id) {
801         case CameraParam::BRIGHTNESS:
802             v4l2cid = V4L2_CID_BRIGHTNESS;
803             break;
804         case CameraParam::CONTRAST:
805             v4l2cid = V4L2_CID_CONTRAST;
806             break;
807         case CameraParam::AUTO_WHITE_BALANCE:
808             v4l2cid = V4L2_CID_AUTO_WHITE_BALANCE;
809             break;
810         case CameraParam::WHITE_BALANCE_TEMPERATURE:
811             v4l2cid = V4L2_CID_WHITE_BALANCE_TEMPERATURE;
812             break;
813         case CameraParam::SHARPNESS:
814             v4l2cid = V4L2_CID_SHARPNESS;
815             break;
816         case CameraParam::AUTO_EXPOSURE:
817             v4l2cid = V4L2_CID_EXPOSURE_AUTO;
818             break;
819         case CameraParam::ABSOLUTE_EXPOSURE:
820             v4l2cid = V4L2_CID_EXPOSURE_ABSOLUTE;
821             break;
822         case CameraParam::AUTO_FOCUS:
823             v4l2cid = V4L2_CID_FOCUS_AUTO;
824             break;
825         case CameraParam::ABSOLUTE_FOCUS:
826             v4l2cid = V4L2_CID_FOCUS_ABSOLUTE;
827             break;
828         case CameraParam::ABSOLUTE_ZOOM:
829             v4l2cid = V4L2_CID_ZOOM_ABSOLUTE;
830             break;
831         default:
832             LOG(ERROR) << "Camera parameter " << static_cast<unsigned>(id) << " is unknown.";
833             return false;
834     }
835 
836     return mCameraControls.find(v4l2cid) != mCameraControls.end();
837 }
838 
Create(const char * deviceName)839 std::shared_ptr<EvsV4lCamera> EvsV4lCamera::Create(const char* deviceName) {
840     std::unique_ptr<ConfigManager::CameraInfo> nullCamInfo = nullptr;
841     return Create(deviceName, nullCamInfo);
842 }
843 
Create(const char * deviceName,std::unique_ptr<ConfigManager::CameraInfo> & camInfo,const Stream * requestedStreamCfg)844 std::shared_ptr<EvsV4lCamera> EvsV4lCamera::Create(
845         const char* deviceName, std::unique_ptr<ConfigManager::CameraInfo>& camInfo,
846         const Stream* requestedStreamCfg) {
847     LOG(INFO) << "Create " << deviceName;
848     std::shared_ptr<EvsV4lCamera> evsCamera =
849             ndk::SharedRefBase::make<EvsV4lCamera>(deviceName, camInfo);
850     if (!evsCamera) {
851         return nullptr;
852     }
853 
854     // Initialize the video device
855     bool success = false;
856     if (camInfo != nullptr && requestedStreamCfg != nullptr) {
857         LOG(INFO) << "Requested stream configuration:";
858         LOG(INFO) << "  width = " << requestedStreamCfg->width;
859         LOG(INFO) << "  height = " << requestedStreamCfg->height;
860         LOG(INFO) << "  format = " << static_cast<int>(requestedStreamCfg->format);
861         // Validate a given stream configuration.  If there is no exact match,
862         // this will try to find the best match based on:
863         // 1) same output format
864         // 2) the largest resolution that is smaller that a given configuration.
865         int32_t streamId = -1, area = INT_MIN;
866         for (auto& [id, cfg] : camInfo->streamConfigurations) {
867             if (cfg.format == requestedStreamCfg->format) {
868                 if (cfg.width == requestedStreamCfg->width &&
869                     cfg.height == requestedStreamCfg->height) {
870                     // Find exact match.
871                     streamId = id;
872                     break;
873                 } else if (cfg.width < requestedStreamCfg->width &&
874                            cfg.height < requestedStreamCfg->height &&
875                            cfg.width * cfg.height > area) {
876                     streamId = id;
877                     area = cfg.width * cfg.height;
878                 }
879             }
880         }
881 
882         if (streamId >= 0) {
883             LOG(INFO) << "Selected video stream configuration:";
884             LOG(INFO) << "  width = " << camInfo->streamConfigurations[streamId].width;
885             LOG(INFO) << "  height = " << camInfo->streamConfigurations[streamId].height;
886             LOG(INFO) << "  format = "
887                       << static_cast<int>(camInfo->streamConfigurations[streamId].format);
888             success = evsCamera->mVideo.open(deviceName,
889                                              camInfo->streamConfigurations[streamId].width,
890                                              camInfo->streamConfigurations[streamId].height);
891             // Safe to statically cast
892             // ::aidl::android::hardware::graphics::common::PixelFormat type to
893             // android_pixel_format_t
894             evsCamera->mFormat =
895                     static_cast<uint32_t>(camInfo->streamConfigurations[streamId].format);
896         }
897     }
898 
899     if (!success) {
900         // Create a camera object with the default resolution and format
901         // , HAL_PIXEL_FORMAT_RGBA_8888.
902         LOG(INFO) << "Open a video with default parameters";
903         success = evsCamera->mVideo.open(deviceName, kDefaultResolution[0], kDefaultResolution[1]);
904         if (!success) {
905             LOG(ERROR) << "Failed to open a video stream";
906             return nullptr;
907         }
908     }
909 
910     // List available camera parameters
911     evsCamera->mCameraControls = evsCamera->mVideo.enumerateCameraControls();
912 
913     // Please note that the buffer usage flag does not come from a given stream
914     // configuration.
915     evsCamera->mUsage =
916             GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_SW_READ_RARELY | GRALLOC_USAGE_SW_WRITE_OFTEN;
917 
918     return evsCamera;
919 }
920 
startDumpFrames(const std::string & path)921 Result<void> EvsV4lCamera::startDumpFrames(const std::string& path) {
922     struct stat info;
923     if (stat(path.data(), &info) != 0) {
924         return Error(::android::BAD_VALUE) << "Cannot access " << path;
925     } else if (!(info.st_mode & S_IFDIR)) {
926         return Error(::android::BAD_VALUE) << path << " is not a directory";
927     }
928 
929     mDumpPath = path;
930     mDumpFrame = true;
931 
932     return {};
933 }
934 
stopDumpFrames()935 Result<void> EvsV4lCamera::stopDumpFrames() {
936     if (!mDumpFrame) {
937         return Error(::android::INVALID_OPERATION) << "Device is not dumping frames";
938     }
939 
940     mDumpFrame = false;
941     return {};
942 }
943 
944 }  // namespace aidl::android::hardware::automotive::evs::implementation
945