1 /*
2 * Copyright (C) 2019 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 "VtsHalEvsTest"
18
19 #include "FrameHandler.h"
20 #include "FormatConvert.h"
21
22 #include <stdio.h>
23 #include <string.h>
24 #include <chrono>
25
26 #include <android/log.h>
27 #include <cutils/native_handle.h>
28 #include <ui/GraphicBuffer.h>
29
30 using namespace std::chrono_literals;
31
FrameHandler(android::sp<IEvsCamera> pCamera,CameraDesc cameraInfo,android::sp<IEvsDisplay> pDisplay,BufferControlFlag mode)32 FrameHandler::FrameHandler(android::sp <IEvsCamera> pCamera, CameraDesc cameraInfo,
33 android::sp <IEvsDisplay> pDisplay,
34 BufferControlFlag mode) :
35 mCamera(pCamera),
36 mCameraInfo(cameraInfo),
37 mDisplay(pDisplay),
38 mReturnMode(mode) {
39 // Nothing but member initialization here...
40 }
41
42
shutdown()43 void FrameHandler::shutdown()
44 {
45 // Make sure we're not still streaming
46 blockingStopStream();
47
48 // At this point, the receiver thread is no longer running, so we can safely drop
49 // our remote object references so they can be freed
50 mCamera = nullptr;
51 mDisplay = nullptr;
52 }
53
54
startStream()55 bool FrameHandler::startStream() {
56 // Tell the camera to start streaming
57 Return<EvsResult> result = mCamera->startVideoStream(this);
58 if (result != EvsResult::OK) {
59 return false;
60 }
61
62 // Mark ourselves as running
63 mLock.lock();
64 mRunning = true;
65 mLock.unlock();
66
67 return true;
68 }
69
70
asyncStopStream()71 void FrameHandler::asyncStopStream() {
72 // Tell the camera to stop streaming.
73 // This will result in a null frame being delivered when the stream actually stops.
74 mCamera->stopVideoStream();
75 }
76
77
blockingStopStream()78 void FrameHandler::blockingStopStream() {
79 // Tell the stream to stop
80 asyncStopStream();
81
82 // Wait until the stream has actually stopped
83 std::unique_lock<std::mutex> lock(mEventLock);
84 if (mRunning) {
85 mEventSignal.wait(lock, [this]() { return !mRunning; });
86 }
87 }
88
89
returnHeldBuffer()90 bool FrameHandler::returnHeldBuffer() {
91 std::lock_guard<std::mutex> lock(mLock);
92
93 // Return the oldest buffer we're holding
94 if (mHeldBuffers.empty()) {
95 // No buffers are currently held
96 return false;
97 }
98
99 hidl_vec<BufferDesc_1_1> buffers = mHeldBuffers.front();
100 mHeldBuffers.pop();
101 mCamera->doneWithFrame_1_1(buffers);
102
103 return true;
104 }
105
106
isRunning()107 bool FrameHandler::isRunning() {
108 std::lock_guard<std::mutex> lock(mLock);
109 return mRunning;
110 }
111
112
waitForFrameCount(unsigned frameCount)113 void FrameHandler::waitForFrameCount(unsigned frameCount) {
114 // Wait until we've seen at least the requested number of frames (could be more)
115 std::unique_lock<std::mutex> lock(mLock);
116 mFrameSignal.wait(lock, [this, frameCount](){
117 return mFramesReceived >= frameCount;
118 });
119 }
120
121
getFramesCounters(unsigned * received,unsigned * displayed)122 void FrameHandler::getFramesCounters(unsigned* received, unsigned* displayed) {
123 std::lock_guard<std::mutex> lock(mLock);
124
125 if (received) {
126 *received = mFramesReceived;
127 }
128 if (displayed) {
129 *displayed = mFramesDisplayed;
130 }
131 }
132
133
deliverFrame(const BufferDesc_1_0 & bufferArg)134 Return<void> FrameHandler::deliverFrame(const BufferDesc_1_0& bufferArg) {
135 ALOGW("A frame delivered via v1.0 method is rejected.");
136 mCamera->doneWithFrame(bufferArg);
137 return Void();
138 }
139
140
deliverFrame_1_1(const hidl_vec<BufferDesc_1_1> & buffers)141 Return<void> FrameHandler::deliverFrame_1_1(const hidl_vec<BufferDesc_1_1>& buffers) {
142 mLock.lock();
143 // For VTS tests, FrameHandler uses a single frame among delivered frames.
144 auto bufferIdx = mFramesDisplayed % buffers.size();
145 auto buffer = buffers[bufferIdx];
146 mLock.unlock();
147
148 const AHardwareBuffer_Desc* pDesc =
149 reinterpret_cast<const AHardwareBuffer_Desc *>(&buffer.buffer.description);
150 ALOGD("Received a frame from the camera (%p)",
151 buffer.buffer.nativeHandle.getNativeHandle());
152
153 // Store a dimension of a received frame.
154 mFrameWidth = pDesc->width;
155 mFrameHeight = pDesc->height;
156
157 // If we were given an opened display at construction time, then send the received
158 // image back down the camera.
159 bool displayed = false;
160 if (mDisplay.get()) {
161 // Get the output buffer we'll use to display the imagery
162 BufferDesc_1_0 tgtBuffer = {};
163 mDisplay->getTargetBuffer([&tgtBuffer](const BufferDesc_1_0& buff) {
164 tgtBuffer = buff;
165 }
166 );
167
168 if (tgtBuffer.memHandle == nullptr) {
169 printf("Didn't get target buffer - frame lost\n");
170 ALOGE("Didn't get requested output buffer -- skipping this frame.");
171 } else {
172 // Copy the contents of the of buffer.memHandle into tgtBuffer
173 copyBufferContents(tgtBuffer, buffer);
174
175 // Send the target buffer back for display
176 Return<EvsResult> result = mDisplay->returnTargetBufferForDisplay(tgtBuffer);
177 if (!result.isOk()) {
178 printf("HIDL error on display buffer (%s)- frame lost\n",
179 result.description().c_str());
180 ALOGE("Error making the remote function call. HIDL said %s",
181 result.description().c_str());
182 } else if (result != EvsResult::OK) {
183 printf("Display reported error - frame lost\n");
184 ALOGE("We encountered error %d when returning a buffer to the display!",
185 (EvsResult) result);
186 } else {
187 // Everything looks good!
188 // Keep track so tests or watch dogs can monitor progress
189 displayed = true;
190 }
191 }
192 }
193
194 mLock.lock();
195 // increases counters
196 ++mFramesReceived;
197 mFramesDisplayed += (int)displayed;
198 mLock.unlock();
199 mFrameSignal.notify_all();
200
201 switch (mReturnMode) {
202 case eAutoReturn:
203 // Send the camera buffer back now that the client has seen it
204 ALOGD("Calling doneWithFrame");
205 mCamera->doneWithFrame_1_1(buffers);
206 break;
207 case eNoAutoReturn:
208 // Hang onto the buffer handles for now -- the client will return it explicitly later
209 mHeldBuffers.push(buffers);
210 break;
211 }
212
213 ALOGD("Frame handling complete");
214
215 return Void();
216 }
217
218
notify(const EvsEventDesc & event)219 Return<void> FrameHandler::notify(const EvsEventDesc& event) {
220 // Local flag we use to keep track of when the stream is stopping
221 std::unique_lock<std::mutex> lock(mEventLock);
222 mLatestEventDesc.aType = event.aType;
223 mLatestEventDesc.payload[0] = event.payload[0];
224 mLatestEventDesc.payload[1] = event.payload[1];
225 if (mLatestEventDesc.aType == EvsEventType::STREAM_STOPPED) {
226 // Signal that the last frame has been received and the stream is stopped
227 mRunning = false;
228 } else if (mLatestEventDesc.aType == EvsEventType::PARAMETER_CHANGED) {
229 ALOGD("Camera parameter 0x%X is changed to 0x%X",
230 mLatestEventDesc.payload[0], mLatestEventDesc.payload[1]);
231 } else {
232 ALOGD("Received an event %s", eventToString(mLatestEventDesc.aType));
233 }
234 lock.unlock();
235 mEventSignal.notify_one();
236
237 return Void();
238 }
239
240
copyBufferContents(const BufferDesc_1_0 & tgtBuffer,const BufferDesc_1_1 & srcBuffer)241 bool FrameHandler::copyBufferContents(const BufferDesc_1_0& tgtBuffer,
242 const BufferDesc_1_1& srcBuffer) {
243 bool success = true;
244 const AHardwareBuffer_Desc* pSrcDesc =
245 reinterpret_cast<const AHardwareBuffer_Desc *>(&srcBuffer.buffer.description);
246
247 // Make sure we don't run off the end of either buffer
248 const unsigned width = std::min(tgtBuffer.width,
249 pSrcDesc->width);
250 const unsigned height = std::min(tgtBuffer.height,
251 pSrcDesc->height);
252
253 sp<android::GraphicBuffer> tgt = new android::GraphicBuffer(tgtBuffer.memHandle,
254 android::GraphicBuffer::CLONE_HANDLE,
255 tgtBuffer.width,
256 tgtBuffer.height,
257 tgtBuffer.format,
258 1,
259 tgtBuffer.usage,
260 tgtBuffer.stride);
261 sp<android::GraphicBuffer> src = new android::GraphicBuffer(srcBuffer.buffer.nativeHandle,
262 android::GraphicBuffer::CLONE_HANDLE,
263 pSrcDesc->width,
264 pSrcDesc->height,
265 pSrcDesc->format,
266 pSrcDesc->layers,
267 pSrcDesc->usage,
268 pSrcDesc->stride);
269
270 // Lock our source buffer for reading (current expectation are for this to be NV21 format)
271 uint8_t* srcPixels = nullptr;
272 src->lock(GRALLOC_USAGE_SW_READ_OFTEN, (void**)&srcPixels);
273
274 // Lock our target buffer for writing (should be either RGBA8888 or BGRA8888 format)
275 uint32_t* tgtPixels = nullptr;
276 tgt->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, (void**)&tgtPixels);
277
278 if (srcPixels && tgtPixels) {
279 using namespace ::android::hardware::automotive::evs::common;
280 if (tgtBuffer.format == HAL_PIXEL_FORMAT_RGBA_8888) {
281 if (pSrcDesc->format == HAL_PIXEL_FORMAT_YCRCB_420_SP) { // 420SP == NV21
282 Utils::copyNV21toRGB32(width, height,
283 srcPixels,
284 tgtPixels, tgtBuffer.stride);
285 } else if (pSrcDesc->format == HAL_PIXEL_FORMAT_YV12) { // YUV_420P == YV12
286 Utils::copyYV12toRGB32(width, height,
287 srcPixels,
288 tgtPixels, tgtBuffer.stride);
289 } else if (pSrcDesc->format == HAL_PIXEL_FORMAT_YCBCR_422_I) { // YUYV
290 Utils::copyYUYVtoRGB32(width, height,
291 srcPixels, pSrcDesc->stride,
292 tgtPixels, tgtBuffer.stride);
293 } else if (pSrcDesc->format == tgtBuffer.format) { // 32bit RGBA
294 Utils::copyMatchedInterleavedFormats(width, height,
295 srcPixels, pSrcDesc->stride,
296 tgtPixels, tgtBuffer.stride,
297 tgtBuffer.pixelSize);
298 } else {
299 ALOGE("Camera buffer format is not supported");
300 success = false;
301 }
302 } else if (tgtBuffer.format == HAL_PIXEL_FORMAT_BGRA_8888) {
303 if (pSrcDesc->format == HAL_PIXEL_FORMAT_YCRCB_420_SP) { // 420SP == NV21
304 Utils::copyNV21toBGR32(width, height,
305 srcPixels,
306 tgtPixels, tgtBuffer.stride);
307 } else if (pSrcDesc->format == HAL_PIXEL_FORMAT_YV12) { // YUV_420P == YV12
308 Utils::copyYV12toBGR32(width, height,
309 srcPixels,
310 tgtPixels, tgtBuffer.stride);
311 } else if (pSrcDesc->format == HAL_PIXEL_FORMAT_YCBCR_422_I) { // YUYV
312 Utils::copyYUYVtoBGR32(width, height,
313 srcPixels, pSrcDesc->stride,
314 tgtPixels, tgtBuffer.stride);
315 } else if (pSrcDesc->format == tgtBuffer.format) { // 32bit RGBA
316 Utils::copyMatchedInterleavedFormats(width, height,
317 srcPixels, pSrcDesc->stride,
318 tgtPixels, tgtBuffer.stride,
319 tgtBuffer.pixelSize);
320 } else {
321 ALOGE("Camera buffer format is not supported");
322 success = false;
323 }
324 } else {
325 // We always expect 32 bit RGB for the display output for now. Is there a need for 565?
326 ALOGE("Diplay buffer is always expected to be 32bit RGBA");
327 success = false;
328 }
329 } else {
330 ALOGE("Failed to lock buffer contents for contents transfer");
331 success = false;
332 }
333
334 if (srcPixels) {
335 src->unlock();
336 }
337 if (tgtPixels) {
338 tgt->unlock();
339 }
340
341 return success;
342 }
343
getFrameDimension(unsigned * width,unsigned * height)344 void FrameHandler::getFrameDimension(unsigned* width, unsigned* height) {
345 if (width) {
346 *width = mFrameWidth;
347 }
348
349 if (height) {
350 *height = mFrameHeight;
351 }
352 }
353
waitForEvent(const EvsEventDesc & aTargetEvent,EvsEventDesc & aReceivedEvent,bool ignorePayload)354 bool FrameHandler::waitForEvent(const EvsEventDesc& aTargetEvent,
355 EvsEventDesc& aReceivedEvent,
356 bool ignorePayload) {
357 // Wait until we get an expected parameter change event.
358 std::unique_lock<std::mutex> lock(mEventLock);
359 auto now = std::chrono::system_clock::now();
360 bool found = false;
361 while (!found) {
362 bool result = mEventSignal.wait_until(lock, now + 5s,
363 [this, aTargetEvent, ignorePayload, &aReceivedEvent, &found](){
364 found = (mLatestEventDesc.aType == aTargetEvent.aType) &&
365 (ignorePayload || (mLatestEventDesc.payload[0] == aTargetEvent.payload[0] &&
366 mLatestEventDesc.payload[1] == aTargetEvent.payload[1]));
367
368 aReceivedEvent.aType = mLatestEventDesc.aType;
369 aReceivedEvent.payload[0] = mLatestEventDesc.payload[0];
370 aReceivedEvent.payload[1] = mLatestEventDesc.payload[1];
371 return found;
372 }
373 );
374
375 if (!result) {
376 ALOGW("A timer is expired before a target event has happened.");
377 break;
378 }
379 }
380
381 return found;
382 }
383
eventToString(const EvsEventType aType)384 const char *FrameHandler::eventToString(const EvsEventType aType) {
385 switch (aType) {
386 case EvsEventType::STREAM_STARTED:
387 return "STREAM_STARTED";
388 case EvsEventType::STREAM_STOPPED:
389 return "STREAM_STOPPED";
390 case EvsEventType::FRAME_DROPPED:
391 return "FRAME_DROPPED";
392 case EvsEventType::TIMEOUT:
393 return "TIMEOUT";
394 case EvsEventType::PARAMETER_CHANGED:
395 return "PARAMETER_CHANGED";
396 case EvsEventType::MASTER_RELEASED:
397 return "MASTER_RELEASED";
398 default:
399 return "Unknown";
400 }
401 }
402
403