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