1 /*
2 * Copyright (C) 2018 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 GL_GLEXT_PROTOTYPES
18 #define EGL_EGLEXT_PROTOTYPES
19
20 #include <EGL/egl.h>
21 #include <EGL/eglext.h>
22 #include <GLES2/gl2.h>
23 #include <GLES2/gl2ext.h>
24 #include <cutils/compiler.h>
25 #include <gui/BufferItem.h>
26 #include <gui/BufferQueue.h>
27 #include <surfacetexture/EGLConsumer.h>
28 #include <surfacetexture/SurfaceTexture.h>
29 #include <inttypes.h>
30 #include <private/gui/SyncFeatures.h>
31 #include <utils/Log.h>
32 #include <utils/String8.h>
33 #include <utils/Trace.h>
34
35 #define PROT_CONTENT_EXT_STR "EGL_EXT_protected_content"
36 #define EGL_PROTECTED_CONTENT_EXT 0x32C0
37
38 namespace android {
39
40 // Macros for including the SurfaceTexture name in log messages
41 #define EGC_LOGV(x, ...) ALOGV("[%s] " x, st.mName.c_str(), ##__VA_ARGS__)
42 #define EGC_LOGD(x, ...) ALOGD("[%s] " x, st.mName.c_str(), ##__VA_ARGS__)
43 #define EGC_LOGW(x, ...) ALOGW("[%s] " x, st.mName.c_str(), ##__VA_ARGS__)
44 #define EGC_LOGE(x, ...) ALOGE("[%s] " x, st.mName.c_str(), ##__VA_ARGS__)
45
46 static const struct {
47 uint32_t width, height;
48 char const* bits;
49 } kDebugData = {15, 12,
50 "_______________"
51 "_______________"
52 "_____XX_XX_____"
53 "__X_X_____X_X__"
54 "__X_XXXXXXX_X__"
55 "__XXXXXXXXXXX__"
56 "___XX_XXX_XX___"
57 "____XXXXXXX____"
58 "_____X___X_____"
59 "____X_____X____"
60 "_______________"
61 "_______________"};
62
63 Mutex EGLConsumer::sStaticInitLock;
64 sp<GraphicBuffer> EGLConsumer::sReleasedTexImageBuffer;
65
hasEglProtectedContentImpl()66 static bool hasEglProtectedContentImpl() {
67 EGLDisplay dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
68 const char* exts = eglQueryString(dpy, EGL_EXTENSIONS);
69 size_t cropExtLen = strlen(PROT_CONTENT_EXT_STR);
70 size_t extsLen = strlen(exts);
71 bool equal = !strcmp(PROT_CONTENT_EXT_STR, exts);
72 bool atStart = !strncmp(PROT_CONTENT_EXT_STR " ", exts, cropExtLen + 1);
73 bool atEnd = (cropExtLen + 1) < extsLen &&
74 !strcmp(" " PROT_CONTENT_EXT_STR, exts + extsLen - (cropExtLen + 1));
75 bool inMiddle = strstr(exts, " " PROT_CONTENT_EXT_STR " ");
76 return equal || atStart || atEnd || inMiddle;
77 }
78
hasEglProtectedContent()79 static bool hasEglProtectedContent() {
80 // Only compute whether the extension is present once the first time this
81 // function is called.
82 static bool hasIt = hasEglProtectedContentImpl();
83 return hasIt;
84 }
85
EGLConsumer()86 EGLConsumer::EGLConsumer() : mEglDisplay(EGL_NO_DISPLAY), mEglContext(EGL_NO_CONTEXT) {}
87
updateTexImage(SurfaceTexture & st)88 status_t EGLConsumer::updateTexImage(SurfaceTexture& st) {
89 // Make sure the EGL state is the same as in previous calls.
90 status_t err = checkAndUpdateEglStateLocked(st);
91 if (err != NO_ERROR) {
92 return err;
93 }
94
95 BufferItem item;
96
97 // Acquire the next buffer.
98 // In asynchronous mode the list is guaranteed to be one buffer
99 // deep, while in synchronous mode we use the oldest buffer.
100 err = st.acquireBufferLocked(&item, 0);
101 if (err != NO_ERROR) {
102 if (err == BufferQueue::NO_BUFFER_AVAILABLE) {
103 // We always bind the texture even if we don't update its contents.
104 EGC_LOGV("updateTexImage: no buffers were available");
105 glBindTexture(st.mTexTarget, st.mTexName);
106 err = NO_ERROR;
107 } else {
108 EGC_LOGE("updateTexImage: acquire failed: %s (%d)", strerror(-err), err);
109 }
110 return err;
111 }
112
113 // Release the previous buffer.
114 err = updateAndReleaseLocked(item, nullptr, st);
115 if (err != NO_ERROR) {
116 // We always bind the texture.
117 glBindTexture(st.mTexTarget, st.mTexName);
118 return err;
119 }
120
121 // Bind the new buffer to the GL texture, and wait until it's ready.
122 return bindTextureImageLocked(st);
123 }
124
releaseTexImage(SurfaceTexture & st)125 status_t EGLConsumer::releaseTexImage(SurfaceTexture& st) {
126 // Make sure the EGL state is the same as in previous calls.
127 status_t err = NO_ERROR;
128
129 // if we're detached, no need to validate EGL's state -- we won't use it.
130 if (st.mOpMode == SurfaceTexture::OpMode::attachedToGL) {
131 err = checkAndUpdateEglStateLocked(st, true);
132 if (err != NO_ERROR) {
133 return err;
134 }
135 }
136
137 // Update the EGLConsumer state.
138 int buf = st.mCurrentTexture;
139 if (buf != BufferQueue::INVALID_BUFFER_SLOT) {
140 EGC_LOGV("releaseTexImage: (slot=%d, mOpMode=%d)", buf, (int)st.mOpMode);
141
142 // if we're detached, we just use the fence that was created in
143 // detachFromContext() so... basically, nothing more to do here.
144 if (st.mOpMode == SurfaceTexture::OpMode::attachedToGL) {
145 // Do whatever sync ops we need to do before releasing the slot.
146 err = syncForReleaseLocked(mEglDisplay, st);
147 if (err != NO_ERROR) {
148 EGC_LOGE("syncForReleaseLocked failed (slot=%d), err=%d", buf, err);
149 return err;
150 }
151 }
152
153 err = st.releaseBufferLocked(buf, st.mSlots[buf].mGraphicBuffer);
154 if (err < NO_ERROR) {
155 EGC_LOGE("releaseTexImage: failed to release buffer: %s (%d)", strerror(-err), err);
156 return err;
157 }
158
159 if (mReleasedTexImage == nullptr) {
160 mReleasedTexImage = new EglImage(getDebugTexImageBuffer());
161 }
162
163 st.mCurrentTexture = BufferQueue::INVALID_BUFFER_SLOT;
164 mCurrentTextureImage = mReleasedTexImage;
165 st.mCurrentCrop.makeInvalid();
166 st.mCurrentTransform = 0;
167 st.mCurrentTimestamp = 0;
168 st.mCurrentDataSpace = HAL_DATASPACE_UNKNOWN;
169 st.mCurrentFence = Fence::NO_FENCE;
170 st.mCurrentFenceTime = FenceTime::NO_FENCE;
171
172 // detached, don't touch the texture (and we may not even have an
173 // EGLDisplay here.
174 if (st.mOpMode == SurfaceTexture::OpMode::attachedToGL) {
175 // This binds a dummy buffer (mReleasedTexImage).
176 status_t result = bindTextureImageLocked(st);
177 if (result != NO_ERROR) {
178 return result;
179 }
180 }
181 }
182
183 return NO_ERROR;
184 }
185
getDebugTexImageBuffer()186 sp<GraphicBuffer> EGLConsumer::getDebugTexImageBuffer() {
187 Mutex::Autolock _l(sStaticInitLock);
188 if (CC_UNLIKELY(sReleasedTexImageBuffer == nullptr)) {
189 // The first time, create the debug texture in case the application
190 // continues to use it.
191 sp<GraphicBuffer> buffer =
192 new GraphicBuffer(kDebugData.width, kDebugData.height, PIXEL_FORMAT_RGBA_8888,
193 DEFAULT_USAGE_FLAGS | GraphicBuffer::USAGE_SW_WRITE_RARELY,
194 "[EGLConsumer debug texture]");
195 uint32_t* bits;
196 buffer->lock(GraphicBuffer::USAGE_SW_WRITE_RARELY, reinterpret_cast<void**>(&bits));
197 uint32_t stride = buffer->getStride();
198 uint32_t height = buffer->getHeight();
199 memset(bits, 0, stride * height * 4);
200 for (uint32_t y = 0; y < kDebugData.height; y++) {
201 for (uint32_t x = 0; x < kDebugData.width; x++) {
202 bits[x] = (kDebugData.bits[y + kDebugData.width + x] == 'X') ? 0xFF000000
203 : 0xFFFFFFFF;
204 }
205 bits += stride;
206 }
207 buffer->unlock();
208 sReleasedTexImageBuffer = buffer;
209 }
210 return sReleasedTexImageBuffer;
211 }
212
onAcquireBufferLocked(BufferItem * item,SurfaceTexture & st)213 void EGLConsumer::onAcquireBufferLocked(BufferItem* item, SurfaceTexture& st) {
214 // If item->mGraphicBuffer is not null, this buffer has not been acquired
215 // before, so any prior EglImage created is using a stale buffer. This
216 // replaces any old EglImage with a new one (using the new buffer).
217 int slot = item->mSlot;
218 if (item->mGraphicBuffer != nullptr || mEglSlots[slot].mEglImage.get() == nullptr) {
219 mEglSlots[slot].mEglImage = new EglImage(st.mSlots[slot].mGraphicBuffer);
220 }
221 }
222
onReleaseBufferLocked(int buf)223 void EGLConsumer::onReleaseBufferLocked(int buf) {
224 mEglSlots[buf].mEglFence = EGL_NO_SYNC_KHR;
225 }
226
updateAndReleaseLocked(const BufferItem & item,PendingRelease * pendingRelease,SurfaceTexture & st)227 status_t EGLConsumer::updateAndReleaseLocked(const BufferItem& item, PendingRelease* pendingRelease,
228 SurfaceTexture& st) {
229 status_t err = NO_ERROR;
230
231 int slot = item.mSlot;
232
233 if (st.mOpMode != SurfaceTexture::OpMode::attachedToGL) {
234 EGC_LOGE("updateAndRelease: EGLConsumer is not attached to an OpenGL "
235 "ES context");
236 st.releaseBufferLocked(slot, st.mSlots[slot].mGraphicBuffer);
237 return INVALID_OPERATION;
238 }
239
240 // Confirm state.
241 err = checkAndUpdateEglStateLocked(st);
242 if (err != NO_ERROR) {
243 st.releaseBufferLocked(slot, st.mSlots[slot].mGraphicBuffer);
244 return err;
245 }
246
247 // Ensure we have a valid EglImageKHR for the slot, creating an EglImage
248 // if nessessary, for the gralloc buffer currently in the slot in
249 // ConsumerBase.
250 // We may have to do this even when item.mGraphicBuffer == NULL (which
251 // means the buffer was previously acquired).
252 err = mEglSlots[slot].mEglImage->createIfNeeded(mEglDisplay);
253 if (err != NO_ERROR) {
254 EGC_LOGW("updateAndRelease: unable to createImage on display=%p slot=%d", mEglDisplay,
255 slot);
256 st.releaseBufferLocked(slot, st.mSlots[slot].mGraphicBuffer);
257 return UNKNOWN_ERROR;
258 }
259
260 // Do whatever sync ops we need to do before releasing the old slot.
261 if (slot != st.mCurrentTexture) {
262 err = syncForReleaseLocked(mEglDisplay, st);
263 if (err != NO_ERROR) {
264 // Release the buffer we just acquired. It's not safe to
265 // release the old buffer, so instead we just drop the new frame.
266 // As we are still under lock since acquireBuffer, it is safe to
267 // release by slot.
268 st.releaseBufferLocked(slot, st.mSlots[slot].mGraphicBuffer);
269 return err;
270 }
271 }
272
273 EGC_LOGV("updateAndRelease: (slot=%d buf=%p) -> (slot=%d buf=%p)", st.mCurrentTexture,
274 mCurrentTextureImage != nullptr ? mCurrentTextureImage->graphicBufferHandle()
275 : nullptr,
276 slot, st.mSlots[slot].mGraphicBuffer->handle);
277
278 // Hang onto the pointer so that it isn't freed in the call to
279 // releaseBufferLocked() if we're in shared buffer mode and both buffers are
280 // the same.
281 sp<EglImage> nextTextureImage = mEglSlots[slot].mEglImage;
282
283 // release old buffer
284 if (st.mCurrentTexture != BufferQueue::INVALID_BUFFER_SLOT) {
285 if (pendingRelease == nullptr) {
286 status_t status =
287 st.releaseBufferLocked(st.mCurrentTexture,
288 mCurrentTextureImage->graphicBuffer(), mEglDisplay,
289 mEglSlots[st.mCurrentTexture].mEglFence);
290 if (status < NO_ERROR) {
291 EGC_LOGE("updateAndRelease: failed to release buffer: %s (%d)", strerror(-status),
292 status);
293 err = status;
294 // keep going, with error raised [?]
295 }
296 } else {
297 pendingRelease->currentTexture = st.mCurrentTexture;
298 pendingRelease->graphicBuffer = mCurrentTextureImage->graphicBuffer();
299 pendingRelease->display = mEglDisplay;
300 pendingRelease->fence = mEglSlots[st.mCurrentTexture].mEglFence;
301 pendingRelease->isPending = true;
302 }
303 }
304
305 // Update the EGLConsumer state.
306 st.mCurrentTexture = slot;
307 mCurrentTextureImage = nextTextureImage;
308 st.mCurrentCrop = item.mCrop;
309 st.mCurrentTransform = item.mTransform;
310 st.mCurrentScalingMode = item.mScalingMode;
311 st.mCurrentTimestamp = item.mTimestamp;
312 st.mCurrentDataSpace = item.mDataSpace;
313 st.mCurrentFence = item.mFence;
314 st.mCurrentFenceTime = item.mFenceTime;
315 st.mCurrentFrameNumber = item.mFrameNumber;
316
317 st.computeCurrentTransformMatrixLocked();
318
319 return err;
320 }
321
bindTextureImageLocked(SurfaceTexture & st)322 status_t EGLConsumer::bindTextureImageLocked(SurfaceTexture& st) {
323 if (mEglDisplay == EGL_NO_DISPLAY) {
324 ALOGE("bindTextureImage: invalid display");
325 return INVALID_OPERATION;
326 }
327
328 GLenum error;
329 while ((error = glGetError()) != GL_NO_ERROR) {
330 EGC_LOGW("bindTextureImage: clearing GL error: %#04x", error);
331 }
332
333 glBindTexture(st.mTexTarget, st.mTexName);
334 if (st.mCurrentTexture == BufferQueue::INVALID_BUFFER_SLOT && mCurrentTextureImage == nullptr) {
335 EGC_LOGE("bindTextureImage: no currently-bound texture");
336 return NO_INIT;
337 }
338
339 status_t err = mCurrentTextureImage->createIfNeeded(mEglDisplay);
340 if (err != NO_ERROR) {
341 EGC_LOGW("bindTextureImage: can't create image on display=%p slot=%d", mEglDisplay,
342 st.mCurrentTexture);
343 return UNKNOWN_ERROR;
344 }
345 mCurrentTextureImage->bindToTextureTarget(st.mTexTarget);
346
347 // In the rare case that the display is terminated and then initialized
348 // again, we can't detect that the display changed (it didn't), but the
349 // image is invalid. In this case, repeat the exact same steps while
350 // forcing the creation of a new image.
351 if ((error = glGetError()) != GL_NO_ERROR) {
352 glBindTexture(st.mTexTarget, st.mTexName);
353 status_t result = mCurrentTextureImage->createIfNeeded(mEglDisplay, true);
354 if (result != NO_ERROR) {
355 EGC_LOGW("bindTextureImage: can't create image on display=%p slot=%d", mEglDisplay,
356 st.mCurrentTexture);
357 return UNKNOWN_ERROR;
358 }
359 mCurrentTextureImage->bindToTextureTarget(st.mTexTarget);
360 if ((error = glGetError()) != GL_NO_ERROR) {
361 EGC_LOGE("bindTextureImage: error binding external image: %#04x", error);
362 return UNKNOWN_ERROR;
363 }
364 }
365
366 // Wait for the new buffer to be ready.
367 return doGLFenceWaitLocked(st);
368 }
369
checkAndUpdateEglStateLocked(SurfaceTexture & st,bool contextCheck)370 status_t EGLConsumer::checkAndUpdateEglStateLocked(SurfaceTexture& st, bool contextCheck) {
371 EGLDisplay dpy = eglGetCurrentDisplay();
372 EGLContext ctx = eglGetCurrentContext();
373
374 if (!contextCheck) {
375 // if this is the first time we're called, mEglDisplay/mEglContext have
376 // never been set, so don't error out (below).
377 if (mEglDisplay == EGL_NO_DISPLAY) {
378 mEglDisplay = dpy;
379 }
380 if (mEglContext == EGL_NO_CONTEXT) {
381 mEglContext = ctx;
382 }
383 }
384
385 if (mEglDisplay != dpy || dpy == EGL_NO_DISPLAY) {
386 EGC_LOGE("checkAndUpdateEglState: invalid current EGLDisplay");
387 return INVALID_OPERATION;
388 }
389
390 if (mEglContext != ctx || ctx == EGL_NO_CONTEXT) {
391 EGC_LOGE("checkAndUpdateEglState: invalid current EGLContext");
392 return INVALID_OPERATION;
393 }
394
395 mEglDisplay = dpy;
396 mEglContext = ctx;
397 return NO_ERROR;
398 }
399
detachFromContext(SurfaceTexture & st)400 status_t EGLConsumer::detachFromContext(SurfaceTexture& st) {
401 EGLDisplay dpy = eglGetCurrentDisplay();
402 EGLContext ctx = eglGetCurrentContext();
403
404 if (mEglDisplay != dpy && mEglDisplay != EGL_NO_DISPLAY) {
405 EGC_LOGE("detachFromContext: invalid current EGLDisplay");
406 return INVALID_OPERATION;
407 }
408
409 if (mEglContext != ctx && mEglContext != EGL_NO_CONTEXT) {
410 EGC_LOGE("detachFromContext: invalid current EGLContext");
411 return INVALID_OPERATION;
412 }
413
414 if (dpy != EGL_NO_DISPLAY && ctx != EGL_NO_CONTEXT) {
415 status_t err = syncForReleaseLocked(dpy, st);
416 if (err != OK) {
417 return err;
418 }
419
420 glDeleteTextures(1, &st.mTexName);
421 }
422
423 mEglDisplay = EGL_NO_DISPLAY;
424 mEglContext = EGL_NO_CONTEXT;
425
426 return OK;
427 }
428
attachToContext(uint32_t tex,SurfaceTexture & st)429 status_t EGLConsumer::attachToContext(uint32_t tex, SurfaceTexture& st) {
430 // Initialize mCurrentTextureImage if there is a current buffer from past
431 // attached state.
432 int slot = st.mCurrentTexture;
433 if (slot != BufferItem::INVALID_BUFFER_SLOT) {
434 if (!mEglSlots[slot].mEglImage.get()) {
435 mEglSlots[slot].mEglImage = new EglImage(st.mSlots[slot].mGraphicBuffer);
436 }
437 mCurrentTextureImage = mEglSlots[slot].mEglImage;
438 }
439
440 EGLDisplay dpy = eglGetCurrentDisplay();
441 EGLContext ctx = eglGetCurrentContext();
442
443 if (dpy == EGL_NO_DISPLAY) {
444 EGC_LOGE("attachToContext: invalid current EGLDisplay");
445 return INVALID_OPERATION;
446 }
447
448 if (ctx == EGL_NO_CONTEXT) {
449 EGC_LOGE("attachToContext: invalid current EGLContext");
450 return INVALID_OPERATION;
451 }
452
453 // We need to bind the texture regardless of whether there's a current
454 // buffer.
455 glBindTexture(st.mTexTarget, GLuint(tex));
456
457 mEglDisplay = dpy;
458 mEglContext = ctx;
459 st.mTexName = tex;
460 st.mOpMode = SurfaceTexture::OpMode::attachedToGL;
461
462 if (mCurrentTextureImage != nullptr) {
463 // This may wait for a buffer a second time. This is likely required if
464 // this is a different context, since otherwise the wait could be skipped
465 // by bouncing through another context. For the same context the extra
466 // wait is redundant.
467 status_t err = bindTextureImageLocked(st);
468 if (err != NO_ERROR) {
469 return err;
470 }
471 }
472
473 return OK;
474 }
475
syncForReleaseLocked(EGLDisplay dpy,SurfaceTexture & st)476 status_t EGLConsumer::syncForReleaseLocked(EGLDisplay dpy, SurfaceTexture& st) {
477 EGC_LOGV("syncForReleaseLocked");
478
479 if (st.mCurrentTexture != BufferQueue::INVALID_BUFFER_SLOT) {
480 if (SyncFeatures::getInstance().useNativeFenceSync()) {
481 EGLSyncKHR sync = eglCreateSyncKHR(dpy, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
482 if (sync == EGL_NO_SYNC_KHR) {
483 EGC_LOGE("syncForReleaseLocked: error creating EGL fence: %#x", eglGetError());
484 return UNKNOWN_ERROR;
485 }
486 glFlush();
487 int fenceFd = eglDupNativeFenceFDANDROID(dpy, sync);
488 eglDestroySyncKHR(dpy, sync);
489 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
490 EGC_LOGE("syncForReleaseLocked: error dup'ing native fence "
491 "fd: %#x",
492 eglGetError());
493 return UNKNOWN_ERROR;
494 }
495 sp<Fence> fence(new Fence(fenceFd));
496 status_t err = st.addReleaseFenceLocked(st.mCurrentTexture,
497 mCurrentTextureImage->graphicBuffer(), fence);
498 if (err != OK) {
499 EGC_LOGE("syncForReleaseLocked: error adding release fence: "
500 "%s (%d)",
501 strerror(-err), err);
502 return err;
503 }
504 } else if (st.mUseFenceSync && SyncFeatures::getInstance().useFenceSync()) {
505 EGLSyncKHR fence = mEglSlots[st.mCurrentTexture].mEglFence;
506 if (fence != EGL_NO_SYNC_KHR) {
507 // There is already a fence for the current slot. We need to
508 // wait on that before replacing it with another fence to
509 // ensure that all outstanding buffer accesses have completed
510 // before the producer accesses it.
511 EGLint result = eglClientWaitSyncKHR(dpy, fence, 0, 1000000000);
512 if (result == EGL_FALSE) {
513 EGC_LOGE("syncForReleaseLocked: error waiting for previous "
514 "fence: %#x",
515 eglGetError());
516 return UNKNOWN_ERROR;
517 } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
518 EGC_LOGE("syncForReleaseLocked: timeout waiting for previous "
519 "fence");
520 return TIMED_OUT;
521 }
522 eglDestroySyncKHR(dpy, fence);
523 }
524
525 // Create a fence for the outstanding accesses in the current
526 // OpenGL ES context.
527 fence = eglCreateSyncKHR(dpy, EGL_SYNC_FENCE_KHR, nullptr);
528 if (fence == EGL_NO_SYNC_KHR) {
529 EGC_LOGE("syncForReleaseLocked: error creating fence: %#x", eglGetError());
530 return UNKNOWN_ERROR;
531 }
532 glFlush();
533 mEglSlots[st.mCurrentTexture].mEglFence = fence;
534 }
535 }
536
537 return OK;
538 }
539
doGLFenceWaitLocked(SurfaceTexture & st) const540 status_t EGLConsumer::doGLFenceWaitLocked(SurfaceTexture& st) const {
541 EGLDisplay dpy = eglGetCurrentDisplay();
542 EGLContext ctx = eglGetCurrentContext();
543
544 if (mEglDisplay != dpy || mEglDisplay == EGL_NO_DISPLAY) {
545 EGC_LOGE("doGLFenceWait: invalid current EGLDisplay");
546 return INVALID_OPERATION;
547 }
548
549 if (mEglContext != ctx || mEglContext == EGL_NO_CONTEXT) {
550 EGC_LOGE("doGLFenceWait: invalid current EGLContext");
551 return INVALID_OPERATION;
552 }
553
554 if (st.mCurrentFence->isValid()) {
555 if (SyncFeatures::getInstance().useWaitSync() &&
556 SyncFeatures::getInstance().useNativeFenceSync()) {
557 // Create an EGLSyncKHR from the current fence.
558 int fenceFd = st.mCurrentFence->dup();
559 if (fenceFd == -1) {
560 EGC_LOGE("doGLFenceWait: error dup'ing fence fd: %d", errno);
561 return -errno;
562 }
563 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd, EGL_NONE};
564 EGLSyncKHR sync = eglCreateSyncKHR(dpy, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
565 if (sync == EGL_NO_SYNC_KHR) {
566 close(fenceFd);
567 EGC_LOGE("doGLFenceWait: error creating EGL fence: %#x", eglGetError());
568 return UNKNOWN_ERROR;
569 }
570
571 // XXX: The spec draft is inconsistent as to whether this should
572 // return an EGLint or void. Ignore the return value for now, as
573 // it's not strictly needed.
574 eglWaitSyncKHR(dpy, sync, 0);
575 EGLint eglErr = eglGetError();
576 eglDestroySyncKHR(dpy, sync);
577 if (eglErr != EGL_SUCCESS) {
578 EGC_LOGE("doGLFenceWait: error waiting for EGL fence: %#x", eglErr);
579 return UNKNOWN_ERROR;
580 }
581 } else {
582 status_t err = st.mCurrentFence->waitForever("EGLConsumer::doGLFenceWaitLocked");
583 if (err != NO_ERROR) {
584 EGC_LOGE("doGLFenceWait: error waiting for fence: %d", err);
585 return err;
586 }
587 }
588 }
589
590 return NO_ERROR;
591 }
592
onFreeBufferLocked(int slotIndex)593 void EGLConsumer::onFreeBufferLocked(int slotIndex) {
594 if (mEglSlots[slotIndex].mEglImage != nullptr &&
595 mEglSlots[slotIndex].mEglImage == mCurrentTextureImage) {
596 mCurrentTextureImage.clear();
597 }
598 mEglSlots[slotIndex].mEglImage.clear();
599 }
600
onAbandonLocked()601 void EGLConsumer::onAbandonLocked() {
602 mCurrentTextureImage.clear();
603 }
604
EglImage(sp<GraphicBuffer> graphicBuffer)605 EGLConsumer::EglImage::EglImage(sp<GraphicBuffer> graphicBuffer)
606 : mGraphicBuffer(graphicBuffer), mEglImage(EGL_NO_IMAGE_KHR), mEglDisplay(EGL_NO_DISPLAY) {}
607
~EglImage()608 EGLConsumer::EglImage::~EglImage() {
609 if (mEglImage != EGL_NO_IMAGE_KHR) {
610 if (!eglDestroyImageKHR(mEglDisplay, mEglImage)) {
611 ALOGE("~EglImage: eglDestroyImageKHR failed");
612 }
613 eglTerminate(mEglDisplay);
614 }
615 }
616
createIfNeeded(EGLDisplay eglDisplay,bool forceCreation)617 status_t EGLConsumer::EglImage::createIfNeeded(EGLDisplay eglDisplay, bool forceCreation) {
618 // If there's an image and it's no longer valid, destroy it.
619 bool haveImage = mEglImage != EGL_NO_IMAGE_KHR;
620 bool displayInvalid = mEglDisplay != eglDisplay;
621 if (haveImage && (displayInvalid || forceCreation)) {
622 if (!eglDestroyImageKHR(mEglDisplay, mEglImage)) {
623 ALOGE("createIfNeeded: eglDestroyImageKHR failed");
624 }
625 eglTerminate(mEglDisplay);
626 mEglImage = EGL_NO_IMAGE_KHR;
627 mEglDisplay = EGL_NO_DISPLAY;
628 }
629
630 // If there's no image, create one.
631 if (mEglImage == EGL_NO_IMAGE_KHR) {
632 mEglDisplay = eglDisplay;
633 mEglImage = createImage(mEglDisplay, mGraphicBuffer);
634 }
635
636 // Fail if we can't create a valid image.
637 if (mEglImage == EGL_NO_IMAGE_KHR) {
638 mEglDisplay = EGL_NO_DISPLAY;
639 const sp<GraphicBuffer>& buffer = mGraphicBuffer;
640 ALOGE("Failed to create image. size=%ux%u st=%u usage=%#" PRIx64 " fmt=%d",
641 buffer->getWidth(), buffer->getHeight(), buffer->getStride(), buffer->getUsage(),
642 buffer->getPixelFormat());
643 return UNKNOWN_ERROR;
644 }
645
646 return OK;
647 }
648
bindToTextureTarget(uint32_t texTarget)649 void EGLConsumer::EglImage::bindToTextureTarget(uint32_t texTarget) {
650 glEGLImageTargetTexture2DOES(texTarget, static_cast<GLeglImageOES>(mEglImage));
651 }
652
createImage(EGLDisplay dpy,const sp<GraphicBuffer> & graphicBuffer)653 EGLImageKHR EGLConsumer::EglImage::createImage(EGLDisplay dpy,
654 const sp<GraphicBuffer>& graphicBuffer) {
655 EGLClientBuffer cbuf = static_cast<EGLClientBuffer>(graphicBuffer->getNativeBuffer());
656 const bool createProtectedImage =
657 (graphicBuffer->getUsage() & GRALLOC_USAGE_PROTECTED) && hasEglProtectedContent();
658 EGLint attrs[] = {
659 EGL_IMAGE_PRESERVED_KHR,
660 EGL_TRUE,
661 createProtectedImage ? EGL_PROTECTED_CONTENT_EXT : EGL_NONE,
662 createProtectedImage ? EGL_TRUE : EGL_NONE,
663 EGL_NONE,
664 };
665 eglInitialize(dpy, nullptr, nullptr);
666 EGLImageKHR image =
667 eglCreateImageKHR(dpy, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID, cbuf, attrs);
668 if (image == EGL_NO_IMAGE_KHR) {
669 EGLint error = eglGetError();
670 ALOGE("error creating EGLImage: %#x", error);
671 eglTerminate(dpy);
672 }
673 return image;
674 }
675
676 } // namespace android
677