blob: 01d9a0e304a373e35a134fbf8054d11920d18b56 [file] [log] [blame]
Scott Randolph6c085582017-03-30 14:24:14 -07001/*
2 * Copyright (C) 2017 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
21#include <stdio.h>
22#include <string.h>
23
24#include <android/log.h>
25#include <cutils/native_handle.h>
26#include <ui/GraphicBufferMapper.h>
27#include <ui/GraphicBuffer.h>
28
29#include <algorithm> // std::min
30
31
32// For the moment, we're assuming that the underlying EVS driver we're working with
33// is providing 4 byte RGBx data. This is fine for loopback testing, although
34// real hardware is expected to provide YUV data -- most likly formatted as YV12
35static const unsigned kBytesPerPixel = 4; // assuming 4 byte RGBx pixels
36
37
38FrameHandler::FrameHandler(android::sp <IEvsCamera> pCamera, CameraDesc cameraInfo,
39 android::sp <IEvsDisplay> pDisplay,
40 BufferControlFlag mode) :
41 mCamera(pCamera),
42 mCameraInfo(cameraInfo),
43 mDisplay(pDisplay),
44 mReturnMode(mode) {
45 // Nothing but member initialization here...
46}
47
48
49void FrameHandler::shutdown()
50{
51 // Make sure we're not still streaming
52 blockingStopStream();
53
54 // At this point, the receiver thread is no longer running, so we can safely drop
55 // our remote object references so they can be freed
56 mCamera = nullptr;
57 mDisplay = nullptr;
58}
59
60
61bool FrameHandler::startStream() {
62 // Mark ourselves as running
63 mLock.lock();
64 mRunning = true;
65 mLock.unlock();
66
67 // Tell the camera to start streaming
68 Return<EvsResult> result = mCamera->startVideoStream(this);
69 return (result == EvsResult::OK);
70}
71
72
73void FrameHandler::asyncStopStream() {
74 // Tell the camera to stop streaming.
75 // This will result in a null frame being delivered when the stream actually stops.
76 mCamera->stopVideoStream();
77}
78
79
80void FrameHandler::blockingStopStream() {
81 // Tell the stream to stop
82 asyncStopStream();
83
84 // Wait until the stream has actually stopped
85 std::unique_lock<std::mutex> lock(mLock);
86 mSignal.wait(lock, [this](){ return !mRunning; });
87}
88
89
90bool FrameHandler::returnHeldBuffer() {
91 std::unique_lock<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 BufferDesc buffer = mHeldBuffers.front();
100 mHeldBuffers.pop();
101 mCamera->doneWithFrame(buffer);
102
103 return true;
104}
105
106
107bool FrameHandler::isRunning() {
108 std::unique_lock<std::mutex> lock(mLock);
109 return mRunning;
110}
111
112
113void 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 mSignal.wait(lock, [this, frameCount](){ return mFramesReceived >= frameCount; });
117}
118
119
120void FrameHandler::getFramesCounters(unsigned* received, unsigned* displayed) {
121 std::unique_lock<std::mutex> lock(mLock);
122
123 if (received) {
124 *received = mFramesReceived;
125 }
126 if (displayed) {
127 *displayed = mFramesDisplayed;
128 }
129}
130
131
132Return<void> FrameHandler::deliverFrame(const BufferDesc& bufferArg) {
133 ALOGD("Received a frame from the camera (%p)", bufferArg.memHandle.getNativeHandle());
134
135 // Local flag we use to keep track of when the stream is stopping
136 bool timeToStop = false;
137
138 // TODO: Why do we get a gralloc crash if we don't clone the buffer here?
139 BufferDesc buffer(bufferArg);
140 ALOGD("Clone the received frame as %p", buffer.memHandle.getNativeHandle());
141
142 if (buffer.memHandle.getNativeHandle() == nullptr) {
143 // Signal that the last frame has been received and the stream is stopped
144 timeToStop = true;
145 } else {
146 // If we were given an opened display at construction time, then send the received
147 // image back down the camera.
148 if (mDisplay.get()) {
149 // Get the output buffer we'll use to display the imagery
150 BufferDesc tgtBuffer = {};
151 mDisplay->getTargetBuffer([&tgtBuffer](const BufferDesc& buff) {
152 tgtBuffer = buff;
153 }
154 );
155
156 if (tgtBuffer.memHandle == nullptr) {
157 printf("Didn't get target buffer - frame lost\n");
158 ALOGE("Didn't get requested output buffer -- skipping this frame.");
159 } else {
160 // In order for the handles passed through HIDL and stored in the BufferDesc to
161 // be lockable, we must register them with GraphicBufferMapper
162 registerBufferHelper(tgtBuffer);
163 registerBufferHelper(buffer);
164
165 // Copy the contents of the of buffer.memHandle into tgtBuffer
166 copyBufferContents(tgtBuffer, buffer);
167
168 // Send the target buffer back for display
169 Return <EvsResult> result = mDisplay->returnTargetBufferForDisplay(tgtBuffer);
170 if (!result.isOk()) {
171 printf("HIDL error on display buffer (%s)- frame lost\n",
172 result.description().c_str());
173 ALOGE("Error making the remote function call. HIDL said %s",
174 result.description().c_str());
175 } else if (result != EvsResult::OK) {
176 printf("Display reported error - frame lost\n");
177 ALOGE("We encountered error %d when returning a buffer to the display!",
178 (EvsResult) result);
179 } else {
180 // Everything looks good!
181 // Keep track so tests or watch dogs can monitor progress
182 mLock.lock();
183 mFramesDisplayed++;
184 mLock.unlock();
185 }
186
187 // Now tell GraphicBufferMapper we won't be using these handles anymore
188 unregisterBufferHelper(tgtBuffer);
189 unregisterBufferHelper(buffer);
190 }
191 }
192
193
194 switch (mReturnMode) {
195 case eAutoReturn:
196 // Send the camera buffer back now that we're done with it
197 ALOGD("Calling doneWithFrame");
198 // TODO: Why is it that we get a HIDL crash if we pass back the cloned buffer?
199 mCamera->doneWithFrame(bufferArg);
200 break;
201 case eNoAutoReturn:
202 // Hang onto the buffer handle for now -- we'll return it explicitly later
203 mHeldBuffers.push(bufferArg);
204 }
205
206
207 ALOGD("Frame handling complete");
208 }
209
210
211 // Update our received frame count and notify anybody who cares that things have changed
212 mLock.lock();
213 if (timeToStop) {
214 mRunning = false;
215 } else {
216 mFramesReceived++;
217 }
218 mLock.unlock();
219 mSignal.notify_all();
220
221
222 return Void();
223}
224
225
226bool FrameHandler::copyBufferContents(const BufferDesc& tgtBuffer,
227 const BufferDesc& srcBuffer) {
228 bool success = true;
229
230 // Make sure we don't run off the end of either buffer
231 const unsigned width = std::min(tgtBuffer.width,
232 srcBuffer.width);
233 const unsigned height = std::min(tgtBuffer.height,
234 srcBuffer.height);
235
236 android::GraphicBufferMapper &mapper = android::GraphicBufferMapper::get();
237
238
239 // Lock our source buffer for reading
240 unsigned char* srcPixels = nullptr;
241 mapper.registerBuffer(srcBuffer.memHandle);
242 mapper.lock(srcBuffer.memHandle,
243 GRALLOC_USAGE_SW_READ_OFTEN,
244 android::Rect(width, height),
245 (void **) &srcPixels);
246
247 // Lock our target buffer for writing
248 unsigned char* tgtPixels = nullptr;
249 mapper.registerBuffer(tgtBuffer.memHandle);
250 mapper.lock(tgtBuffer.memHandle,
251 GRALLOC_USAGE_SW_WRITE_OFTEN,
252 android::Rect(width, height),
253 (void **) &tgtPixels);
254
255 if (srcPixels && tgtPixels) {
256 for (unsigned row = 0; row < height; row++) {
257 // Copy the entire row of pixel data
258 memcpy(tgtPixels, srcPixels, width * kBytesPerPixel);
259
260 // Advance to the next row (keeping in mind that stride here is in units of pixels)
261 tgtPixels += tgtBuffer.stride * kBytesPerPixel;
262 srcPixels += srcBuffer.stride * kBytesPerPixel;
263 }
264 } else {
265 ALOGE("Failed to copy buffer contents");
266 success = false;
267 }
268
269 if (srcPixels) {
270 mapper.unlock(srcBuffer.memHandle);
271 }
272 if (tgtPixels) {
273 mapper.unlock(tgtBuffer.memHandle);
274 }
275 mapper.unregisterBuffer(srcBuffer.memHandle);
276 mapper.unregisterBuffer(tgtBuffer.memHandle);
277
278 return success;
279}
280
281
282void FrameHandler::registerBufferHelper(const BufferDesc& buffer)
283{
284 // In order for the handles passed through HIDL and stored in the BufferDesc to
285 // be lockable, we must register them with GraphicBufferMapper.
286 // If the device upon which we're running supports gralloc1, we could just call
287 // registerBuffer directly with the handle. But that call is broken for gralloc0 devices
288 // (which we care about, at least for now). As a result, we have to synthesize a GraphicBuffer
289 // object around the buffer handle in order to make a call to the overloaded alternate
290 // version of the registerBuffer call that does happen to work on gralloc0 devices.
291#if REGISTER_BUFFER_ALWAYS_WORKS
292 android::GraphicBufferMapper::get().registerBuffer(buffer.memHandle);
293#else
294 android::sp<android::GraphicBuffer> pGfxBuff = new android::GraphicBuffer(
295 buffer.width, buffer.height, buffer.format,
296 1, /* we always use exactly one layer */
297 buffer.usage, buffer.stride,
298 const_cast<native_handle_t*>(buffer.memHandle.getNativeHandle()),
299 false /* GraphicBuffer should not try to free the handle */
300 );
301
302 android::GraphicBufferMapper::get().registerBuffer(pGfxBuff.get());
303#endif
304}
305
306
307void FrameHandler::unregisterBufferHelper(const BufferDesc& buffer)
308{
309 // Now tell GraphicBufferMapper we won't be using these handles anymore
310 android::GraphicBufferMapper::get().unregisterBuffer(buffer.memHandle);
311}