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 #include "EvsDisplay.h"
18
19 #include <ui/GraphicBufferAllocator.h>
20 #include <ui/GraphicBufferMapper.h>
21
22 using ::android::frameworks::automotive::display::V1_0::HwDisplayConfig;
23 using ::android::frameworks::automotive::display::V1_0::HwDisplayState;
24 using ::android::frameworks::automotive::display::V1_0::IAutomotiveDisplayProxyService;
25 using ::android::hardware::automotive::evs::V1_0::DisplayDesc;
26 using ::android::hardware::automotive::evs::V1_0::DisplayState;
27 using ::android::hardware::automotive::evs::V1_0::EvsResult;
28
29 namespace {
30
31 // Arbitrary magic number for self-recognition
32 constexpr uint32_t kDefaultDisplayBufferId = 0x3870;
33
34 } // namespace
35
36 namespace android::hardware::automotive::evs::V1_1::implementation {
37
EvsDisplay()38 EvsDisplay::EvsDisplay() {
39 EvsDisplay(nullptr, 0);
40 }
41
EvsDisplay(sp<IAutomotiveDisplayProxyService> pDisplayProxy,uint64_t displayId)42 EvsDisplay::EvsDisplay(sp<IAutomotiveDisplayProxyService> pDisplayProxy, uint64_t displayId)
43 : mDisplayProxy(pDisplayProxy),
44 mDisplayId(displayId),
45 mGlWrapper(std::make_unique<GlWrapper>()) {
46 ALOGD("EvsDisplay instantiated");
47
48 // Set up our self description
49 // NOTE: These are arbitrary values chosen for testing
50 mInfo.displayId = "Mock Display";
51 mInfo.vendorFlags = 3870;
52
53 // Assemble the buffer description we'll use for our render target
54 mBuffer.width = 640;
55 mBuffer.height = 360;
56 mBuffer.format = HAL_PIXEL_FORMAT_RGBA_8888;
57 mBuffer.usage = GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_COMPOSER;
58 mBuffer.bufferId = kDefaultDisplayBufferId;
59 mBuffer.pixelSize = 4;
60 }
61
~EvsDisplay()62 EvsDisplay::~EvsDisplay() {
63 ALOGD("EvsDisplay being destroyed");
64 forceShutdown();
65 }
66
67 /**
68 * This gets called if another caller "steals" ownership of the display
69 */
forceShutdown()70 void EvsDisplay::forceShutdown() {
71 ALOGD("EvsDisplay forceShutdown");
72 std::lock_guard<std::mutex> lock(mAccessLock);
73
74 // If the buffer isn't being held by a remote client, release it now as an
75 // optimization to release the resources more quickly than the destructor might
76 // get called.
77 if (mBuffer.memHandle) {
78 // Report if we're going away while a buffer is outstanding
79 if (mFrameBusy) {
80 ALOGE("EvsDisplay going down while client is holding a buffer");
81 }
82
83 // Drop the graphics buffer we've been using
84 GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
85 alloc.free(mBuffer.memHandle);
86 mBuffer.memHandle = nullptr;
87
88 if (mGlWrapper) {
89 mGlWrapper->hideWindow(mDisplayProxy, mDisplayId);
90 mGlWrapper->shutdown();
91 }
92 }
93
94 // Put this object into an unrecoverable error state since somebody else
95 // is going to own the display now.
96 mRequestedState = DisplayState::DEAD;
97 }
98
99 /**
100 * Returns basic information about the EVS display provided by the system.
101 * See the description of the DisplayDesc structure for details.
102 */
getDisplayInfo(getDisplayInfo_cb _hidl_cb)103 Return<void> EvsDisplay::getDisplayInfo(getDisplayInfo_cb _hidl_cb) {
104 ALOGD("getDisplayInfo");
105
106 // Send back our self description
107 _hidl_cb(mInfo);
108 return {};
109 }
110
111 /**
112 * Clients may set the display state to express their desired state.
113 * The HAL implementation must gracefully accept a request for any state
114 * while in any other state, although the response may be to ignore the request.
115 * The display is defined to start in the NOT_VISIBLE state upon initialization.
116 * The client is then expected to request the VISIBLE_ON_NEXT_FRAME state, and
117 * then begin providing video. When the display is no longer required, the client
118 * is expected to request the NOT_VISIBLE state after passing the last video frame.
119 */
setDisplayState(DisplayState state)120 Return<EvsResult> EvsDisplay::setDisplayState(DisplayState state) {
121 ALOGD("setDisplayState");
122 std::lock_guard<std::mutex> lock(mAccessLock);
123
124 if (mRequestedState == DisplayState::DEAD) {
125 // This object no longer owns the display -- it's been superceeded!
126 return EvsResult::OWNERSHIP_LOST;
127 }
128
129 // Ensure we recognize the requested state so we don't go off the rails
130 if (state >= DisplayState::NUM_STATES) {
131 return EvsResult::INVALID_ARG;
132 }
133
134 if (!mGlWrapper) {
135 switch (state) {
136 case DisplayState::NOT_VISIBLE:
137 mGlWrapper->hideWindow(mDisplayProxy, mDisplayId);
138 break;
139 case DisplayState::VISIBLE:
140 mGlWrapper->showWindow(mDisplayProxy, mDisplayId);
141 break;
142 default:
143 break;
144 }
145 }
146
147 // Record the requested state
148 mRequestedState = state;
149
150 return EvsResult::OK;
151 }
152
153 /**
154 * The HAL implementation should report the actual current state, which might
155 * transiently differ from the most recently requested state. Note, however, that
156 * the logic responsible for changing display states should generally live above
157 * the device layer, making it undesirable for the HAL implementation to
158 * spontaneously change display states.
159 */
getDisplayState()160 Return<DisplayState> EvsDisplay::getDisplayState() {
161 ALOGD("getDisplayState");
162 std::lock_guard<std::mutex> lock(mAccessLock);
163
164 return mRequestedState;
165 }
166
167 /**
168 * This call returns a handle to a frame buffer associated with the display.
169 * This buffer may be locked and written to by software and/or GL. This buffer
170 * must be returned via a call to returnTargetBufferForDisplay() even if the
171 * display is no longer visible.
172 */
173 // TODO: We need to know if/when our client dies so we can get the buffer back! (blocked b/31632518)
getTargetBuffer(getTargetBuffer_cb _hidl_cb)174 Return<void> EvsDisplay::getTargetBuffer(getTargetBuffer_cb _hidl_cb) {
175 ALOGD("getTargetBuffer");
176 std::lock_guard<std::mutex> lock(mAccessLock);
177
178 if (mRequestedState == DisplayState::DEAD) {
179 ALOGE("Rejecting buffer request from object that lost ownership of the display.");
180 _hidl_cb({});
181 return {};
182 }
183
184 // If we don't already have a buffer, allocate one now
185 if (!mBuffer.memHandle) {
186 // Initialize our display window
187 // NOTE: This will cause the display to become "VISIBLE" before a frame is actually
188 // returned, which is contrary to the spec and will likely result in a black frame being
189 // (briefly) shown.
190 if (mGlWrapper->initialize(mDisplayProxy, mDisplayId)) {
191 // Assemble the buffer description we'll use for our render target
192 mBuffer.width = mGlWrapper->getWidth();
193 mBuffer.height = mGlWrapper->getHeight();
194 mBuffer.format = HAL_PIXEL_FORMAT_RGBA_8888;
195 mBuffer.usage = GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_COMPOSER;
196 mBuffer.bufferId = kDefaultDisplayBufferId;
197 mBuffer.pixelSize = 4;
198 } else {
199 // If we failed to initialize a EGL, then we're not going to display
200 // any.
201 mGlWrapper = nullptr;
202 }
203
204 // Allocate the buffer that will hold our displayable image
205 buffer_handle_t handle = nullptr;
206 GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
207 status_t result = alloc.allocate(mBuffer.width, mBuffer.height, mBuffer.format, 1,
208 mBuffer.usage, &handle, &mBuffer.stride, 0, "EvsDisplay");
209 if (result != NO_ERROR || !handle) {
210 ALOGE("Error %d allocating %d x %d graphics buffer", result, mBuffer.width,
211 mBuffer.height);
212 if (mGlWrapper) {
213 mGlWrapper->shutdown();
214 }
215 _hidl_cb({});
216 return {};
217 }
218
219 mBuffer.memHandle = handle;
220 mFrameBusy = false;
221 ALOGD("Allocated new buffer %p with stride %u", mBuffer.memHandle.getNativeHandle(),
222 mBuffer.stride);
223 }
224
225 // Do we have a frame available?
226 if (mFrameBusy) {
227 // This means either we have a 2nd client trying to compete for buffers
228 // (an unsupported mode of operation) or else the client hasn't returned
229 // a previously issued buffer yet (they're behaving badly).
230 // NOTE: We have to make the callback even if we have nothing to provide
231 ALOGE("getTargetBuffer called while no buffers available.");
232 _hidl_cb({});
233 return {};
234 } else {
235 // Mark our buffer as busy
236 mFrameBusy = true;
237
238 // Send the buffer to the client
239 ALOGD("Providing display buffer handle %p as id %d", mBuffer.memHandle.getNativeHandle(),
240 mBuffer.bufferId);
241 _hidl_cb(mBuffer);
242 return {};
243 }
244 }
245
246 /**
247 * This call tells the display that the buffer is ready for display.
248 * The buffer is no longer valid for use by the client after this call.
249 */
returnTargetBufferForDisplayImpl(const uint32_t bufferId,const buffer_handle_t memHandle)250 Return<EvsResult> EvsDisplay::returnTargetBufferForDisplayImpl(const uint32_t bufferId,
251 const buffer_handle_t memHandle) {
252 ALOGD("returnTargetBufferForDisplay %p", memHandle);
253 std::lock_guard<std::mutex> lock(mAccessLock);
254
255 // Nobody should call us with a null handle
256 if (!memHandle) {
257 ALOGE("returnTargetBufferForDisplay called without a valid buffer handle.\n");
258 return EvsResult::INVALID_ARG;
259 }
260 if (bufferId != mBuffer.bufferId) {
261 ALOGE("Got an unrecognized frame returned.\n");
262 return EvsResult::INVALID_ARG;
263 }
264 if (!mFrameBusy) {
265 ALOGE("A frame was returned with no outstanding frames.\n");
266 return EvsResult::BUFFER_NOT_AVAILABLE;
267 }
268
269 mFrameBusy = false;
270
271 // If we've been displaced by another owner of the display, then we can't do anything else
272 if (mRequestedState == DisplayState::DEAD) {
273 return EvsResult::OWNERSHIP_LOST;
274 }
275
276 // If we were waiting for a new frame, this is it!
277 if (mRequestedState == DisplayState::VISIBLE_ON_NEXT_FRAME) {
278 mRequestedState = DisplayState::VISIBLE;
279 if (mGlWrapper) {
280 mGlWrapper->showWindow(mDisplayProxy, mDisplayId);
281 }
282 }
283
284 // Validate we're in an expected state
285 if (mRequestedState != DisplayState::VISIBLE) {
286 // We shouldn't get frames back when we're not visible.
287 ALOGE("Got an unexpected frame returned while not visible - ignoring.\n");
288 } else if (mGlWrapper) {
289 // This is where the buffer would be made visible.
290 if (!mGlWrapper->updateImageTexture(mBuffer)) {
291 return EvsResult::UNDERLYING_SERVICE_ERROR;
292 }
293
294 // Put the image on the screen
295 mGlWrapper->renderImageToScreen();
296 } else {
297 // TODO: Move below validation logic to somewhere else
298 #if 0
299 // For now we simply validate it has the data we expect in it by reading it back
300 // Lock our display buffer for reading
301 uint32_t* pixels = nullptr;
302 GraphicBufferMapper& mapper = GraphicBufferMapper::get();
303 mapper.lock(mBuffer.memHandle, GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_NEVER,
304 android::Rect(mBuffer.width, mBuffer.height), (void**)&pixels);
305
306 // If we failed to lock the pixel buffer, we're about to crash, but log it first
307 if (!pixels) {
308 ALOGE("Display failed to gain access to image buffer for reading");
309 }
310
311 // Check the test pixels
312 bool frameLooksGood = true;
313 for (unsigned row = 0; row < mBuffer.height; row++) {
314 for (unsigned col = 0; col < mBuffer.width; col++) {
315 // Index into the row to check the pixel at this column.
316 // We expect 0xFF in the LSB channel, a vertical gradient in the
317 // second channel, a horitzontal gradient in the third channel, and
318 // 0xFF in the MSB.
319 // The exception is the very first 32 bits which is used for the
320 // time varying frame signature to avoid getting fooled by a static image.
321 uint32_t expectedPixel = 0xFF0000FF | // MSB and LSB
322 ((row & 0xFF) << 8) | // vertical gradient
323 ((col & 0xFF) << 16); // horizontal gradient
324 if ((row | col) == 0) {
325 // we'll check the "uniqueness" of the frame signature below
326 continue;
327 }
328 // Walk across this row (we'll step rows below)
329 uint32_t receivedPixel = pixels[col];
330 if (receivedPixel != expectedPixel) {
331 ALOGE("Pixel check mismatch in frame buffer");
332 frameLooksGood = false;
333 break;
334 }
335 }
336
337 if (!frameLooksGood) {
338 break;
339 }
340
341 // Point to the next row (NOTE: gralloc reports stride in units of pixels)
342 pixels = pixels + mBuffer.stride;
343 }
344
345 // Ensure we don't see the same buffer twice without it being rewritten
346 static uint32_t prevSignature = ~0;
347 uint32_t signature = pixels[0] & 0xFF;
348 if (prevSignature == signature) {
349 frameLooksGood = false;
350 ALOGE("Duplicate, likely stale frame buffer detected");
351 }
352
353 // Release our output buffer
354 mapper.unlock(mBuffer.memHandle);
355
356 if (!frameLooksGood) {
357 return EvsResult::UNDERLYING_SERVICE_ERROR;
358 }
359 #endif
360 }
361
362 return EvsResult::OK;
363 }
364
returnTargetBufferForDisplay(const V1_0::BufferDesc & buffer)365 Return<EvsResult> EvsDisplay::returnTargetBufferForDisplay(const V1_0::BufferDesc& buffer) {
366 return returnTargetBufferForDisplayImpl(buffer.bufferId, buffer.memHandle);
367 }
368
getDisplayInfo_1_1(getDisplayInfo_1_1_cb _info_cb)369 Return<void> EvsDisplay::getDisplayInfo_1_1(getDisplayInfo_1_1_cb _info_cb) {
370 if (mDisplayProxy != nullptr) {
371 return mDisplayProxy->getDisplayInfo(mDisplayId, _info_cb);
372 } else {
373 HwDisplayConfig nullConfig;
374 HwDisplayState nullState;
375 _info_cb(nullConfig, nullState);
376 return {};
377 }
378 }
379
380 } // namespace android::hardware::automotive::evs::V1_1::implementation
381