egl.cpp revision ca41e362662a50383679b18d9832f6120dc721d9
1/*
2 ** Copyright 2007, 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 <ctype.h>
18#include <stdlib.h>
19#include <string.h>
20#include <errno.h>
21#include <dlfcn.h>
22
23#include <sys/ioctl.h>
24
25#if HAVE_ANDROID_OS
26#include <linux/android_pmem.h>
27#endif
28
29#include <EGL/egl.h>
30#include <EGL/eglext.h>
31#include <GLES/gl.h>
32#include <GLES/glext.h>
33
34#include <cutils/log.h>
35#include <cutils/atomic.h>
36#include <cutils/properties.h>
37#include <cutils/memory.h>
38
39#include <utils/SortedVector.h>
40#include <utils/KeyedVector.h>
41#include <utils/String8.h>
42
43#include <ui/egl/android_natives.h>
44
45#include "hooks.h"
46#include "egl_impl.h"
47#include "Loader.h"
48
49#define setError(_e, _r) setErrorEtc(__FUNCTION__, __LINE__, _e, _r)
50
51// ----------------------------------------------------------------------------
52namespace android {
53// ----------------------------------------------------------------------------
54
55#define VERSION_MAJOR 1
56#define VERSION_MINOR 4
57static char const * const gVendorString     = "Android";
58static char const * const gVersionString    = "1.4 Android META-EGL";
59static char const * const gClientApiString  = "OpenGL ES";
60static char const * const gExtensionString  =
61        "EGL_KHR_image "
62        "EGL_KHR_image_base "
63        "EGL_KHR_image_pixmap "
64        "EGL_KHR_gl_texture_2D_image "
65        "EGL_KHR_gl_texture_cubemap_image "
66        "EGL_KHR_gl_renderbuffer_image "
67        "EGL_KHR_fence_sync "
68        "EGL_ANDROID_image_native_buffer "
69        "EGL_ANDROID_swap_rectangle "
70        ;
71
72// ----------------------------------------------------------------------------
73
74class egl_object_t {
75    static SortedVector<egl_object_t*> sObjects;
76    static Mutex sLock;
77
78            volatile int32_t  terminated;
79    mutable volatile int32_t  count;
80
81public:
82    egl_object_t() : terminated(0), count(1) {
83        Mutex::Autolock _l(sLock);
84        sObjects.add(this);
85    }
86
87    inline bool isAlive() const { return !terminated; }
88
89private:
90    bool get() {
91        Mutex::Autolock _l(sLock);
92        if (egl_object_t::sObjects.indexOf(this) >= 0) {
93            android_atomic_inc(&count);
94            return true;
95        }
96        return false;
97    }
98
99    bool put() {
100        Mutex::Autolock _l(sLock);
101        if (android_atomic_dec(&count) == 1) {
102            sObjects.remove(this);
103            return true;
104        }
105        return false;
106    }
107
108public:
109    template <typename N, typename T>
110    struct LocalRef {
111        N* ref;
112        LocalRef(T o) : ref(0) {
113            N* native = reinterpret_cast<N*>(o);
114            if (o && native->get()) {
115                ref = native;
116            }
117        }
118        ~LocalRef() {
119            if (ref && ref->put()) {
120                delete ref;
121            }
122        }
123        inline N* get() {
124            return ref;
125        }
126        void acquire() const {
127            if (ref) {
128                android_atomic_inc(&ref->count);
129            }
130        }
131        void release() const {
132            if (ref) {
133                int32_t c = android_atomic_dec(&ref->count);
134                // ref->count cannot be 1 prior atomic_dec because we have
135                // a reference, and if we have one, it means there was
136                // already one before us.
137                LOGE_IF(c==1, "refcount is now 0 in release()");
138            }
139        }
140        void terminate() {
141            if (ref) {
142                ref->terminated = 1;
143                release();
144            }
145        }
146    };
147};
148
149SortedVector<egl_object_t*> egl_object_t::sObjects;
150Mutex egl_object_t::sLock;
151
152
153struct egl_config_t {
154    egl_config_t() {}
155    egl_config_t(int impl, EGLConfig config)
156        : impl(impl), config(config), configId(0), implConfigId(0) { }
157    int         impl;           // the implementation this config is for
158    EGLConfig   config;         // the implementation's EGLConfig
159    EGLint      configId;       // our CONFIG_ID
160    EGLint      implConfigId;   // the implementation's CONFIG_ID
161    inline bool operator < (const egl_config_t& rhs) const {
162        if (impl < rhs.impl) return true;
163        if (impl > rhs.impl) return false;
164        return config < rhs.config;
165    }
166};
167
168struct egl_display_t {
169    enum { NOT_INITIALIZED, INITIALIZED, TERMINATED };
170
171    struct strings_t {
172        char const * vendor;
173        char const * version;
174        char const * clientApi;
175        char const * extensions;
176    };
177
178    struct DisplayImpl {
179        DisplayImpl() : dpy(EGL_NO_DISPLAY), config(0),
180                        state(NOT_INITIALIZED), numConfigs(0) { }
181        EGLDisplay  dpy;
182        EGLConfig*  config;
183        EGLint      state;
184        EGLint      numConfigs;
185        strings_t   queryString;
186    };
187
188    uint32_t        magic;
189    DisplayImpl     disp[IMPL_NUM_IMPLEMENTATIONS];
190    EGLint          numTotalConfigs;
191    egl_config_t*   configs;
192    uint32_t        refs;
193    Mutex           lock;
194
195    egl_display_t() : magic('_dpy'), numTotalConfigs(0), configs(0) { }
196    ~egl_display_t() { magic = 0; }
197    inline bool isValid() const { return magic == '_dpy'; }
198    inline bool isAlive() const { return isValid(); }
199};
200
201struct egl_surface_t : public egl_object_t
202{
203    typedef egl_object_t::LocalRef<egl_surface_t, EGLSurface> Ref;
204
205    egl_surface_t(EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win,
206            EGLSurface surface, int impl, egl_connection_t const* cnx)
207    : dpy(dpy), surface(surface), config(config), win(win), impl(impl), cnx(cnx) {
208    }
209    ~egl_surface_t() {
210    }
211    EGLDisplay                  dpy;
212    EGLSurface                  surface;
213    EGLConfig                   config;
214    sp<ANativeWindow>           win;
215    int                         impl;
216    egl_connection_t const*     cnx;
217};
218
219struct egl_context_t : public egl_object_t
220{
221    typedef egl_object_t::LocalRef<egl_context_t, EGLContext> Ref;
222
223    egl_context_t(EGLDisplay dpy, EGLContext context, EGLConfig config,
224            int impl, egl_connection_t const* cnx, int version)
225    : dpy(dpy), context(context), config(config), read(0), draw(0), impl(impl),
226      cnx(cnx), version(version)
227    {
228    }
229    EGLDisplay                  dpy;
230    EGLContext                  context;
231    EGLConfig                   config;
232    EGLSurface                  read;
233    EGLSurface                  draw;
234    int                         impl;
235    egl_connection_t const*     cnx;
236    int                         version;
237};
238
239struct egl_image_t : public egl_object_t
240{
241    typedef egl_object_t::LocalRef<egl_image_t, EGLImageKHR> Ref;
242
243    egl_image_t(EGLDisplay dpy, EGLContext context)
244        : dpy(dpy), context(context)
245    {
246        memset(images, 0, sizeof(images));
247    }
248    EGLDisplay dpy;
249    EGLContext context;
250    EGLImageKHR images[IMPL_NUM_IMPLEMENTATIONS];
251};
252
253struct egl_sync_t : public egl_object_t
254{
255    typedef egl_object_t::LocalRef<egl_sync_t, EGLSyncKHR> Ref;
256
257    egl_sync_t(EGLDisplay dpy, EGLContext context, EGLSyncKHR sync)
258        : dpy(dpy), context(context), sync(sync)
259    {
260    }
261    EGLDisplay dpy;
262    EGLContext context;
263    EGLSyncKHR sync;
264};
265
266typedef egl_surface_t::Ref  SurfaceRef;
267typedef egl_context_t::Ref  ContextRef;
268typedef egl_image_t::Ref    ImageRef;
269typedef egl_sync_t::Ref     SyncRef;
270
271struct tls_t
272{
273    tls_t() : error(EGL_SUCCESS), ctx(0), logCallWithNoContext(EGL_TRUE) { }
274    EGLint      error;
275    EGLContext  ctx;
276    EGLBoolean  logCallWithNoContext;
277};
278
279
280// ----------------------------------------------------------------------------
281
282static egl_connection_t gEGLImpl[IMPL_NUM_IMPLEMENTATIONS];
283static egl_display_t gDisplay[NUM_DISPLAYS];
284static pthread_mutex_t gThreadLocalStorageKeyMutex = PTHREAD_MUTEX_INITIALIZER;
285static pthread_key_t gEGLThreadLocalStorageKey = -1;
286
287// ----------------------------------------------------------------------------
288
289EGLAPI gl_hooks_t gHooks[2][IMPL_NUM_IMPLEMENTATIONS];
290EGLAPI gl_hooks_t gHooksNoContext;
291EGLAPI pthread_key_t gGLWrapperKey = -1;
292
293#if EGL_TRACE
294
295EGLAPI pthread_key_t gGLTraceKey = -1;
296
297// ----------------------------------------------------------------------------
298
299static int gEGLTraceLevel;
300static int gEGLApplicationTraceLevel;
301extern EGLAPI gl_hooks_t gHooksTrace;
302
303static inline void setGlTraceThreadSpecific(gl_hooks_t const *value) {
304    pthread_setspecific(gGLTraceKey, value);
305}
306
307gl_hooks_t const* getGLTraceThreadSpecific() {
308    return static_cast<gl_hooks_t*>(pthread_getspecific(gGLTraceKey));
309}
310
311static void initEglTraceLevel() {
312    char value[PROPERTY_VALUE_MAX];
313    property_get("debug.egl.trace", value, "0");
314    int propertyLevel = atoi(value);
315    int applicationLevel = gEGLApplicationTraceLevel;
316    gEGLTraceLevel = propertyLevel > applicationLevel ? propertyLevel : applicationLevel;
317}
318
319static void setGLHooksThreadSpecific(gl_hooks_t const *value) {
320    if (gEGLTraceLevel > 0) {
321        setGlTraceThreadSpecific(value);
322        setGlThreadSpecific(&gHooksTrace);
323    } else {
324        setGlThreadSpecific(value);
325    }
326}
327
328/*
329 * Global entry point to allow applications to modify their own trace level.
330 * The effective trace level is the max of this level and the value of debug.egl.trace.
331 */
332extern "C"
333void setGLTraceLevel(int level) {
334    gEGLApplicationTraceLevel = level;
335}
336
337#else
338
339static inline void setGLHooksThreadSpecific(gl_hooks_t const *value) {
340    setGlThreadSpecific(value);
341}
342
343#endif
344
345// ----------------------------------------------------------------------------
346
347static __attribute__((noinline))
348const char *egl_strerror(EGLint err)
349{
350    switch (err){
351        case EGL_SUCCESS:               return "EGL_SUCCESS";
352        case EGL_NOT_INITIALIZED:       return "EGL_NOT_INITIALIZED";
353        case EGL_BAD_ACCESS:            return "EGL_BAD_ACCESS";
354        case EGL_BAD_ALLOC:             return "EGL_BAD_ALLOC";
355        case EGL_BAD_ATTRIBUTE:         return "EGL_BAD_ATTRIBUTE";
356        case EGL_BAD_CONFIG:            return "EGL_BAD_CONFIG";
357        case EGL_BAD_CONTEXT:           return "EGL_BAD_CONTEXT";
358        case EGL_BAD_CURRENT_SURFACE:   return "EGL_BAD_CURRENT_SURFACE";
359        case EGL_BAD_DISPLAY:           return "EGL_BAD_DISPLAY";
360        case EGL_BAD_MATCH:             return "EGL_BAD_MATCH";
361        case EGL_BAD_NATIVE_PIXMAP:     return "EGL_BAD_NATIVE_PIXMAP";
362        case EGL_BAD_NATIVE_WINDOW:     return "EGL_BAD_NATIVE_WINDOW";
363        case EGL_BAD_PARAMETER:         return "EGL_BAD_PARAMETER";
364        case EGL_BAD_SURFACE:           return "EGL_BAD_SURFACE";
365        case EGL_CONTEXT_LOST:          return "EGL_CONTEXT_LOST";
366        default: return "UNKNOWN";
367    }
368}
369
370static __attribute__((noinline))
371void clearTLS() {
372    if (gEGLThreadLocalStorageKey != -1) {
373        tls_t* tls = (tls_t*)pthread_getspecific(gEGLThreadLocalStorageKey);
374        if (tls) {
375            delete tls;
376            pthread_setspecific(gEGLThreadLocalStorageKey, 0);
377        }
378    }
379}
380
381static tls_t* getTLS()
382{
383    tls_t* tls = (tls_t*)pthread_getspecific(gEGLThreadLocalStorageKey);
384    if (tls == 0) {
385        tls = new tls_t;
386        pthread_setspecific(gEGLThreadLocalStorageKey, tls);
387    }
388    return tls;
389}
390
391template<typename T>
392static __attribute__((noinline))
393T setErrorEtc(const char* caller, int line, EGLint error, T returnValue) {
394    if (gEGLThreadLocalStorageKey == -1) {
395        pthread_mutex_lock(&gThreadLocalStorageKeyMutex);
396        if (gEGLThreadLocalStorageKey == -1)
397            pthread_key_create(&gEGLThreadLocalStorageKey, NULL);
398        pthread_mutex_unlock(&gThreadLocalStorageKeyMutex);
399    }
400    tls_t* tls = getTLS();
401    if (tls->error != error) {
402        LOGE("%s:%d error %x (%s)", caller, line, error, egl_strerror(error));
403        tls->error = error;
404    }
405    return returnValue;
406}
407
408static __attribute__((noinline))
409GLint getError() {
410    if (gEGLThreadLocalStorageKey == -1)
411        return EGL_SUCCESS;
412    tls_t* tls = (tls_t*)pthread_getspecific(gEGLThreadLocalStorageKey);
413    if (!tls) return EGL_SUCCESS;
414    GLint error = tls->error;
415    tls->error = EGL_SUCCESS;
416    return error;
417}
418
419static __attribute__((noinline))
420void setContext(EGLContext ctx) {
421    if (gEGLThreadLocalStorageKey == -1) {
422        pthread_mutex_lock(&gThreadLocalStorageKeyMutex);
423        if (gEGLThreadLocalStorageKey == -1)
424            pthread_key_create(&gEGLThreadLocalStorageKey, NULL);
425        pthread_mutex_unlock(&gThreadLocalStorageKeyMutex);
426    }
427    tls_t* tls = getTLS();
428    tls->ctx = ctx;
429}
430
431static __attribute__((noinline))
432EGLContext getContext() {
433    if (gEGLThreadLocalStorageKey == -1)
434        return EGL_NO_CONTEXT;
435    tls_t* tls = (tls_t*)pthread_getspecific(gEGLThreadLocalStorageKey);
436    if (!tls) return EGL_NO_CONTEXT;
437    return tls->ctx;
438}
439
440/*****************************************************************************/
441
442template<typename T>
443static __attribute__((noinline))
444int binarySearch(
445        T const sortedArray[], int first, int last, T key)
446{
447    while (first <= last) {
448        int mid = (first + last) / 2;
449        if (sortedArray[mid] < key) {
450            first = mid + 1;
451        } else if (key < sortedArray[mid]) {
452            last = mid - 1;
453        } else {
454            return mid;
455        }
456    }
457    return -1;
458}
459
460static int cmp_configs(const void* a, const void *b)
461{
462    const egl_config_t& c0 = *(egl_config_t const *)a;
463    const egl_config_t& c1 = *(egl_config_t const *)b;
464    return c0<c1 ? -1 : (c1<c0 ? 1 : 0);
465}
466
467struct extention_map_t {
468    const char* name;
469    __eglMustCastToProperFunctionPointerType address;
470};
471
472static const extention_map_t gExtentionMap[] = {
473    { "eglLockSurfaceKHR",
474            (__eglMustCastToProperFunctionPointerType)&eglLockSurfaceKHR },
475    { "eglUnlockSurfaceKHR",
476            (__eglMustCastToProperFunctionPointerType)&eglUnlockSurfaceKHR },
477    { "eglCreateImageKHR",
478            (__eglMustCastToProperFunctionPointerType)&eglCreateImageKHR },
479    { "eglDestroyImageKHR",
480            (__eglMustCastToProperFunctionPointerType)&eglDestroyImageKHR },
481    { "eglSetSwapRectangleANDROID",
482            (__eglMustCastToProperFunctionPointerType)&eglSetSwapRectangleANDROID },
483};
484
485extern const __eglMustCastToProperFunctionPointerType gExtensionForwarders[MAX_NUMBER_OF_GL_EXTENSIONS];
486
487// accesses protected by gInitDriverMutex
488static DefaultKeyedVector<String8, __eglMustCastToProperFunctionPointerType> gGLExtentionMap;
489static int gGLExtentionSlot = 0;
490
491static void(*findProcAddress(const char* name,
492        const extention_map_t* map, size_t n))()
493{
494    for (uint32_t i=0 ; i<n ; i++) {
495        if (!strcmp(name, map[i].name)) {
496            return map[i].address;
497        }
498    }
499    return NULL;
500}
501
502// ----------------------------------------------------------------------------
503
504static int gl_no_context() {
505    tls_t* tls = getTLS();
506    if (tls->logCallWithNoContext == EGL_TRUE) {
507        tls->logCallWithNoContext = EGL_FALSE;
508        LOGE("call to OpenGL ES API with no current context "
509             "(logged once per thread)");
510    }
511    return 0;
512}
513
514static void early_egl_init(void)
515{
516#if !USE_FAST_TLS_KEY
517    pthread_key_create(&gGLWrapperKey, NULL);
518#endif
519#if EGL_TRACE
520    pthread_key_create(&gGLTraceKey, NULL);
521    initEglTraceLevel();
522#endif
523    uint32_t addr = (uint32_t)((void*)gl_no_context);
524    android_memset32(
525            (uint32_t*)(void*)&gHooksNoContext,
526            addr,
527            sizeof(gHooksNoContext));
528
529    setGLHooksThreadSpecific(&gHooksNoContext);
530}
531
532static pthread_once_t once_control = PTHREAD_ONCE_INIT;
533static int sEarlyInitState = pthread_once(&once_control, &early_egl_init);
534
535
536static inline
537egl_display_t* get_display(EGLDisplay dpy)
538{
539    uintptr_t index = uintptr_t(dpy)-1U;
540    return (index >= NUM_DISPLAYS) ? NULL : &gDisplay[index];
541}
542
543template<typename NATIVE, typename EGL>
544static inline NATIVE* egl_to_native_cast(EGL arg) {
545    return reinterpret_cast<NATIVE*>(arg);
546}
547
548static inline
549egl_surface_t* get_surface(EGLSurface surface) {
550    return egl_to_native_cast<egl_surface_t>(surface);
551}
552
553static inline
554egl_context_t* get_context(EGLContext context) {
555    return egl_to_native_cast<egl_context_t>(context);
556}
557
558static inline
559egl_image_t* get_image(EGLImageKHR image) {
560    return egl_to_native_cast<egl_image_t>(image);
561}
562
563static inline
564egl_sync_t* get_sync(EGLSyncKHR sync) {
565    return egl_to_native_cast<egl_sync_t>(sync);
566}
567
568static egl_connection_t* validate_display_config(
569        EGLDisplay dpy, EGLConfig config,
570        egl_display_t const*& dp)
571{
572    dp = get_display(dpy);
573    if (!dp) return setError(EGL_BAD_DISPLAY, (egl_connection_t*)NULL);
574
575    if (intptr_t(config) >= dp->numTotalConfigs) {
576        return setError(EGL_BAD_CONFIG, (egl_connection_t*)NULL);
577    }
578    egl_connection_t* const cnx = &gEGLImpl[dp->configs[intptr_t(config)].impl];
579    if (cnx->dso == 0) {
580        return setError(EGL_BAD_CONFIG, (egl_connection_t*)NULL);
581    }
582    return cnx;
583}
584
585static EGLBoolean validate_display_context(EGLDisplay dpy, EGLContext ctx)
586{
587    if ((uintptr_t(dpy)-1U) >= NUM_DISPLAYS)
588        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
589    if (!get_display(dpy)->isAlive())
590        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
591    if (!get_context(ctx)->isAlive())
592        return setError(EGL_BAD_CONTEXT, EGL_FALSE);
593    return EGL_TRUE;
594}
595
596static EGLBoolean validate_display_surface(EGLDisplay dpy, EGLSurface surface)
597{
598    if ((uintptr_t(dpy)-1U) >= NUM_DISPLAYS)
599        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
600    if (!get_display(dpy)->isAlive())
601        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
602    if (!get_surface(surface)->isAlive())
603        return setError(EGL_BAD_SURFACE, EGL_FALSE);
604    return EGL_TRUE;
605}
606
607EGLImageKHR egl_get_image_for_current_context(EGLImageKHR image)
608{
609    ImageRef _i(image);
610    if (!_i.get()) return EGL_NO_IMAGE_KHR;
611
612    EGLContext context = getContext();
613    if (context == EGL_NO_CONTEXT || image == EGL_NO_IMAGE_KHR)
614        return EGL_NO_IMAGE_KHR;
615
616    egl_context_t const * const c = get_context(context);
617    if (!c->isAlive())
618        return EGL_NO_IMAGE_KHR;
619
620    egl_image_t const * const i = get_image(image);
621    return i->images[c->impl];
622}
623
624// ----------------------------------------------------------------------------
625
626// this mutex protects:
627//    d->disp[]
628//    egl_init_drivers_locked()
629//
630static pthread_mutex_t gInitDriverMutex = PTHREAD_MUTEX_INITIALIZER;
631
632EGLBoolean egl_init_drivers_locked()
633{
634    if (sEarlyInitState) {
635        // initialized by static ctor. should be set here.
636        return EGL_FALSE;
637    }
638
639    // get our driver loader
640    Loader& loader(Loader::getInstance());
641
642    // dynamically load all our EGL implementations for all displays
643    // and retrieve the corresponding EGLDisplay
644    // if that fails, don't use this driver.
645    // TODO: currently we only deal with EGL_DEFAULT_DISPLAY
646    egl_connection_t* cnx;
647    egl_display_t* d = &gDisplay[0];
648
649    cnx = &gEGLImpl[IMPL_SOFTWARE];
650    if (cnx->dso == 0) {
651        cnx->hooks[GLESv1_INDEX] = &gHooks[GLESv1_INDEX][IMPL_SOFTWARE];
652        cnx->hooks[GLESv2_INDEX] = &gHooks[GLESv2_INDEX][IMPL_SOFTWARE];
653        cnx->dso = loader.open(EGL_DEFAULT_DISPLAY, 0, cnx);
654        if (cnx->dso) {
655            EGLDisplay dpy = cnx->egl.eglGetDisplay(EGL_DEFAULT_DISPLAY);
656            LOGE_IF(dpy==EGL_NO_DISPLAY, "No EGLDisplay for software EGL!");
657            d->disp[IMPL_SOFTWARE].dpy = dpy;
658            if (dpy == EGL_NO_DISPLAY) {
659                loader.close(cnx->dso);
660                cnx->dso = NULL;
661            }
662        }
663    }
664
665    cnx = &gEGLImpl[IMPL_HARDWARE];
666    if (cnx->dso == 0) {
667        char value[PROPERTY_VALUE_MAX];
668        property_get("debug.egl.hw", value, "1");
669        if (atoi(value) != 0) {
670            cnx->hooks[GLESv1_INDEX] = &gHooks[GLESv1_INDEX][IMPL_HARDWARE];
671            cnx->hooks[GLESv2_INDEX] = &gHooks[GLESv2_INDEX][IMPL_HARDWARE];
672            cnx->dso = loader.open(EGL_DEFAULT_DISPLAY, 1, cnx);
673            if (cnx->dso) {
674                EGLDisplay dpy = cnx->egl.eglGetDisplay(EGL_DEFAULT_DISPLAY);
675                LOGE_IF(dpy==EGL_NO_DISPLAY, "No EGLDisplay for hardware EGL!");
676                d->disp[IMPL_HARDWARE].dpy = dpy;
677                if (dpy == EGL_NO_DISPLAY) {
678                    loader.close(cnx->dso);
679                    cnx->dso = NULL;
680                }
681            }
682        } else {
683            LOGD("3D hardware acceleration is disabled");
684        }
685    }
686
687    if (!gEGLImpl[IMPL_SOFTWARE].dso && !gEGLImpl[IMPL_HARDWARE].dso) {
688        return EGL_FALSE;
689    }
690
691    return EGL_TRUE;
692}
693
694EGLBoolean egl_init_drivers()
695{
696    EGLBoolean res;
697    pthread_mutex_lock(&gInitDriverMutex);
698    res = egl_init_drivers_locked();
699    pthread_mutex_unlock(&gInitDriverMutex);
700    return res;
701}
702
703// ----------------------------------------------------------------------------
704}; // namespace android
705// ----------------------------------------------------------------------------
706
707using namespace android;
708
709EGLDisplay eglGetDisplay(NativeDisplayType display)
710{
711    uint32_t index = uint32_t(display);
712    if (index >= NUM_DISPLAYS) {
713        return setError(EGL_BAD_PARAMETER, EGL_NO_DISPLAY);
714    }
715
716    if (egl_init_drivers() == EGL_FALSE) {
717        return setError(EGL_BAD_PARAMETER, EGL_NO_DISPLAY);
718    }
719
720    EGLDisplay dpy = EGLDisplay(uintptr_t(display) + 1LU);
721    return dpy;
722}
723
724// ----------------------------------------------------------------------------
725// Initialization
726// ----------------------------------------------------------------------------
727
728EGLBoolean eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor)
729{
730    egl_display_t * const dp = get_display(dpy);
731    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
732
733    Mutex::Autolock _l(dp->lock);
734
735    if (dp->refs > 0) {
736        if (major != NULL) *major = VERSION_MAJOR;
737        if (minor != NULL) *minor = VERSION_MINOR;
738        dp->refs++;
739        return EGL_TRUE;
740    }
741
742#if EGL_TRACE
743
744    // Called both at early_init time and at this time. (Early_init is pre-zygote, so
745    // the information from that call may be stale.)
746    initEglTraceLevel();
747
748#endif
749
750    setGLHooksThreadSpecific(&gHooksNoContext);
751
752    // initialize each EGL and
753    // build our own extension string first, based on the extension we know
754    // and the extension supported by our client implementation
755    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
756        egl_connection_t* const cnx = &gEGLImpl[i];
757        cnx->major = -1;
758        cnx->minor = -1;
759        if (!cnx->dso)
760            continue;
761
762#if defined(ADRENO130)
763#warning "Adreno-130 eglInitialize() workaround"
764        /*
765         * The ADRENO 130 driver returns a different EGLDisplay each time
766         * eglGetDisplay() is called, but also makes the EGLDisplay invalid
767         * after eglTerminate() has been called, so that eglInitialize()
768         * cannot be called again. Therefore, we need to make sure to call
769         * eglGetDisplay() before calling eglInitialize();
770         */
771        if (i == IMPL_HARDWARE) {
772            dp->disp[i].dpy =
773                cnx->egl.eglGetDisplay(EGL_DEFAULT_DISPLAY);
774        }
775#endif
776
777
778        EGLDisplay idpy = dp->disp[i].dpy;
779        if (cnx->egl.eglInitialize(idpy, &cnx->major, &cnx->minor)) {
780            //LOGD("initialized %d dpy=%p, ver=%d.%d, cnx=%p",
781            //        i, idpy, cnx->major, cnx->minor, cnx);
782
783            // display is now initialized
784            dp->disp[i].state = egl_display_t::INITIALIZED;
785
786            // get the query-strings for this display for each implementation
787            dp->disp[i].queryString.vendor =
788                cnx->egl.eglQueryString(idpy, EGL_VENDOR);
789            dp->disp[i].queryString.version =
790                cnx->egl.eglQueryString(idpy, EGL_VERSION);
791            dp->disp[i].queryString.extensions =
792                    cnx->egl.eglQueryString(idpy, EGL_EXTENSIONS);
793            dp->disp[i].queryString.clientApi =
794                cnx->egl.eglQueryString(idpy, EGL_CLIENT_APIS);
795
796        } else {
797            LOGW("%d: eglInitialize(%p) failed (%s)", i, idpy,
798                    egl_strerror(cnx->egl.eglGetError()));
799        }
800    }
801
802    EGLBoolean res = EGL_FALSE;
803    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
804        egl_connection_t* const cnx = &gEGLImpl[i];
805        if (cnx->dso && cnx->major>=0 && cnx->minor>=0) {
806            EGLint n;
807            if (cnx->egl.eglGetConfigs(dp->disp[i].dpy, 0, 0, &n)) {
808                dp->disp[i].config = (EGLConfig*)malloc(sizeof(EGLConfig)*n);
809                if (dp->disp[i].config) {
810                    if (cnx->egl.eglGetConfigs(
811                            dp->disp[i].dpy, dp->disp[i].config, n,
812                            &dp->disp[i].numConfigs))
813                    {
814                        dp->numTotalConfigs += n;
815                        res = EGL_TRUE;
816                    }
817                }
818            }
819        }
820    }
821
822    if (res == EGL_TRUE) {
823        dp->configs = new egl_config_t[ dp->numTotalConfigs ];
824        for (int i=0, k=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
825            egl_connection_t* const cnx = &gEGLImpl[i];
826            if (cnx->dso && cnx->major>=0 && cnx->minor>=0) {
827                for (int j=0 ; j<dp->disp[i].numConfigs ; j++) {
828                    dp->configs[k].impl = i;
829                    dp->configs[k].config = dp->disp[i].config[j];
830                    dp->configs[k].configId = k + 1; // CONFIG_ID start at 1
831                    // store the implementation's CONFIG_ID
832                    cnx->egl.eglGetConfigAttrib(
833                            dp->disp[i].dpy,
834                            dp->disp[i].config[j],
835                            EGL_CONFIG_ID,
836                            &dp->configs[k].implConfigId);
837                    k++;
838                }
839            }
840        }
841
842        // sort our configurations so we can do binary-searches
843        qsort(  dp->configs,
844                dp->numTotalConfigs,
845                sizeof(egl_config_t), cmp_configs);
846
847        dp->refs++;
848        if (major != NULL) *major = VERSION_MAJOR;
849        if (minor != NULL) *minor = VERSION_MINOR;
850        return EGL_TRUE;
851    }
852    return setError(EGL_NOT_INITIALIZED, EGL_FALSE);
853}
854
855EGLBoolean eglTerminate(EGLDisplay dpy)
856{
857    // NOTE: don't unload the drivers b/c some APIs can be called
858    // after eglTerminate() has been called. eglTerminate() only
859    // terminates an EGLDisplay, not a EGL itself.
860
861    egl_display_t* const dp = get_display(dpy);
862    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
863
864    Mutex::Autolock _l(dp->lock);
865
866    if (dp->refs == 0) {
867        return setError(EGL_NOT_INITIALIZED, EGL_FALSE);
868    }
869
870    // this is specific to Android, display termination is ref-counted.
871    if (dp->refs > 1) {
872        dp->refs--;
873        return EGL_TRUE;
874    }
875
876    EGLBoolean res = EGL_FALSE;
877    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
878        egl_connection_t* const cnx = &gEGLImpl[i];
879        if (cnx->dso && dp->disp[i].state == egl_display_t::INITIALIZED) {
880            if (cnx->egl.eglTerminate(dp->disp[i].dpy) == EGL_FALSE) {
881                LOGW("%d: eglTerminate(%p) failed (%s)", i, dp->disp[i].dpy,
882                        egl_strerror(cnx->egl.eglGetError()));
883            }
884            // REVISIT: it's unclear what to do if eglTerminate() fails
885            free(dp->disp[i].config);
886
887            dp->disp[i].numConfigs = 0;
888            dp->disp[i].config = 0;
889            dp->disp[i].state = egl_display_t::TERMINATED;
890
891            res = EGL_TRUE;
892        }
893    }
894
895    // TODO: all egl_object_t should be marked for termination
896
897    dp->refs--;
898    dp->numTotalConfigs = 0;
899    delete [] dp->configs;
900
901    return res;
902}
903
904// ----------------------------------------------------------------------------
905// configuration
906// ----------------------------------------------------------------------------
907
908EGLBoolean eglGetConfigs(   EGLDisplay dpy,
909                            EGLConfig *configs,
910                            EGLint config_size, EGLint *num_config)
911{
912    egl_display_t const * const dp = get_display(dpy);
913    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
914
915    GLint numConfigs = dp->numTotalConfigs;
916    if (!configs) {
917        *num_config = numConfigs;
918        return EGL_TRUE;
919    }
920
921    GLint n = 0;
922    for (intptr_t i=0 ; i<dp->numTotalConfigs && config_size ; i++) {
923        *configs++ = EGLConfig(i);
924        config_size--;
925        n++;
926    }
927
928    *num_config = n;
929    return EGL_TRUE;
930}
931
932EGLBoolean eglChooseConfig( EGLDisplay dpy, const EGLint *attrib_list,
933                            EGLConfig *configs, EGLint config_size,
934                            EGLint *num_config)
935{
936    egl_display_t const * const dp = get_display(dpy);
937    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
938
939    if (num_config==0) {
940        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
941    }
942
943    EGLint n;
944    EGLBoolean res = EGL_FALSE;
945    *num_config = 0;
946
947
948    // It is unfortunate, but we need to remap the EGL_CONFIG_IDs,
949    // to do this, we have to go through the attrib_list array once
950    // to figure out both its size and if it contains an EGL_CONFIG_ID
951    // key. If so, the full array is copied and patched.
952    // NOTE: we assume that there can be only one occurrence
953    // of EGL_CONFIG_ID.
954
955    EGLint patch_index = -1;
956    GLint attr;
957    size_t size = 0;
958    if (attrib_list) {
959        while ((attr=attrib_list[size]) != EGL_NONE) {
960            if (attr == EGL_CONFIG_ID)
961                patch_index = size;
962            size += 2;
963        }
964    }
965    if (patch_index >= 0) {
966        size += 2; // we need copy the sentinel as well
967        EGLint* new_list = (EGLint*)malloc(size*sizeof(EGLint));
968        if (new_list == 0)
969            return setError(EGL_BAD_ALLOC, EGL_FALSE);
970        memcpy(new_list, attrib_list, size*sizeof(EGLint));
971
972        // patch the requested EGL_CONFIG_ID
973        bool found = false;
974        EGLConfig ourConfig(0);
975        EGLint& configId(new_list[patch_index+1]);
976        for (intptr_t i=0 ; i<dp->numTotalConfigs ; i++) {
977            if (dp->configs[i].configId == configId) {
978                ourConfig = EGLConfig(i);
979                configId = dp->configs[i].implConfigId;
980                found = true;
981                break;
982            }
983        }
984
985        egl_connection_t* const cnx = &gEGLImpl[dp->configs[intptr_t(ourConfig)].impl];
986        if (found && cnx->dso) {
987            // and switch to the new list
988            attrib_list = const_cast<const EGLint *>(new_list);
989
990            // At this point, the only configuration that can match is
991            // dp->configs[i][index], however, we don't know if it would be
992            // rejected because of the other attributes, so we do have to call
993            // cnx->egl.eglChooseConfig() -- but we don't have to loop
994            // through all the EGLimpl[].
995            // We also know we can only get a single config back, and we know
996            // which one.
997
998            res = cnx->egl.eglChooseConfig(
999                    dp->disp[ dp->configs[intptr_t(ourConfig)].impl ].dpy,
1000                    attrib_list, configs, config_size, &n);
1001            if (res && n>0) {
1002                // n has to be 0 or 1, by construction, and we already know
1003                // which config it will return (since there can be only one).
1004                if (configs) {
1005                    configs[0] = ourConfig;
1006                }
1007                *num_config = 1;
1008            }
1009        }
1010
1011        free(const_cast<EGLint *>(attrib_list));
1012        return res;
1013    }
1014
1015
1016    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
1017        egl_connection_t* const cnx = &gEGLImpl[i];
1018        if (cnx->dso) {
1019            if (cnx->egl.eglChooseConfig(
1020                    dp->disp[i].dpy, attrib_list, configs, config_size, &n)) {
1021                if (configs) {
1022                    // now we need to convert these client EGLConfig to our
1023                    // internal EGLConfig format.
1024                    // This is done in O(n Log(n)) time.
1025                    for (int j=0 ; j<n ; j++) {
1026                        egl_config_t key(i, configs[j]);
1027                        intptr_t index = binarySearch<egl_config_t>(
1028                                dp->configs, 0, dp->numTotalConfigs, key);
1029                        if (index >= 0) {
1030                            configs[j] = EGLConfig(index);
1031                        } else {
1032                            return setError(EGL_BAD_CONFIG, EGL_FALSE);
1033                        }
1034                    }
1035                    configs += n;
1036                    config_size -= n;
1037                }
1038                *num_config += n;
1039                res = EGL_TRUE;
1040            }
1041        }
1042    }
1043    return res;
1044}
1045
1046EGLBoolean eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config,
1047        EGLint attribute, EGLint *value)
1048{
1049    egl_display_t const* dp = 0;
1050    egl_connection_t* cnx = validate_display_config(dpy, config, dp);
1051    if (!cnx) return EGL_FALSE;
1052
1053    if (attribute == EGL_CONFIG_ID) {
1054        *value = dp->configs[intptr_t(config)].configId;
1055        return EGL_TRUE;
1056    }
1057    return cnx->egl.eglGetConfigAttrib(
1058            dp->disp[ dp->configs[intptr_t(config)].impl ].dpy,
1059            dp->configs[intptr_t(config)].config, attribute, value);
1060}
1061
1062// ----------------------------------------------------------------------------
1063// surfaces
1064// ----------------------------------------------------------------------------
1065
1066EGLSurface eglCreateWindowSurface(  EGLDisplay dpy, EGLConfig config,
1067                                    NativeWindowType window,
1068                                    const EGLint *attrib_list)
1069{
1070    egl_display_t const* dp = 0;
1071    egl_connection_t* cnx = validate_display_config(dpy, config, dp);
1072    if (cnx) {
1073        EGLDisplay iDpy = dp->disp[ dp->configs[intptr_t(config)].impl ].dpy;
1074        EGLConfig iConfig = dp->configs[intptr_t(config)].config;
1075        EGLint format;
1076
1077        // set the native window's buffers format to match this config
1078        if (cnx->egl.eglGetConfigAttrib(iDpy,
1079                iConfig, EGL_NATIVE_VISUAL_ID, &format)) {
1080            if (format != 0) {
1081                native_window_set_buffers_geometry(window, 0, 0, format);
1082            }
1083        }
1084
1085        EGLSurface surface = cnx->egl.eglCreateWindowSurface(
1086                iDpy, iConfig, window, attrib_list);
1087        if (surface != EGL_NO_SURFACE) {
1088            egl_surface_t* s = new egl_surface_t(dpy, config, window, surface,
1089                    dp->configs[intptr_t(config)].impl, cnx);
1090            return s;
1091        }
1092    }
1093    return EGL_NO_SURFACE;
1094}
1095
1096EGLSurface eglCreatePixmapSurface(  EGLDisplay dpy, EGLConfig config,
1097                                    NativePixmapType pixmap,
1098                                    const EGLint *attrib_list)
1099{
1100    egl_display_t const* dp = 0;
1101    egl_connection_t* cnx = validate_display_config(dpy, config, dp);
1102    if (cnx) {
1103        EGLSurface surface = cnx->egl.eglCreatePixmapSurface(
1104                dp->disp[ dp->configs[intptr_t(config)].impl ].dpy,
1105                dp->configs[intptr_t(config)].config, pixmap, attrib_list);
1106        if (surface != EGL_NO_SURFACE) {
1107            egl_surface_t* s = new egl_surface_t(dpy, config, NULL, surface,
1108                    dp->configs[intptr_t(config)].impl, cnx);
1109            return s;
1110        }
1111    }
1112    return EGL_NO_SURFACE;
1113}
1114
1115EGLSurface eglCreatePbufferSurface( EGLDisplay dpy, EGLConfig config,
1116                                    const EGLint *attrib_list)
1117{
1118    egl_display_t const* dp = 0;
1119    egl_connection_t* cnx = validate_display_config(dpy, config, dp);
1120    if (cnx) {
1121        EGLSurface surface = cnx->egl.eglCreatePbufferSurface(
1122                dp->disp[ dp->configs[intptr_t(config)].impl ].dpy,
1123                dp->configs[intptr_t(config)].config, attrib_list);
1124        if (surface != EGL_NO_SURFACE) {
1125            egl_surface_t* s = new egl_surface_t(dpy, config, NULL, surface,
1126                    dp->configs[intptr_t(config)].impl, cnx);
1127            return s;
1128        }
1129    }
1130    return EGL_NO_SURFACE;
1131}
1132
1133EGLBoolean eglDestroySurface(EGLDisplay dpy, EGLSurface surface)
1134{
1135    SurfaceRef _s(surface);
1136    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1137
1138    if (!validate_display_surface(dpy, surface))
1139        return EGL_FALSE;
1140    egl_display_t const * const dp = get_display(dpy);
1141
1142    egl_surface_t * const s = get_surface(surface);
1143    EGLBoolean result = s->cnx->egl.eglDestroySurface(
1144            dp->disp[s->impl].dpy, s->surface);
1145    if (result == EGL_TRUE) {
1146        if (s->win != NULL) {
1147            native_window_set_buffers_geometry(s->win.get(), 0, 0, 0);
1148        }
1149        _s.terminate();
1150    }
1151    return result;
1152}
1153
1154EGLBoolean eglQuerySurface( EGLDisplay dpy, EGLSurface surface,
1155                            EGLint attribute, EGLint *value)
1156{
1157    SurfaceRef _s(surface);
1158    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1159
1160    if (!validate_display_surface(dpy, surface))
1161        return EGL_FALSE;
1162    egl_display_t const * const dp = get_display(dpy);
1163    egl_surface_t const * const s = get_surface(surface);
1164
1165    EGLBoolean result(EGL_TRUE);
1166    if (attribute == EGL_CONFIG_ID) {
1167        // We need to remap EGL_CONFIG_IDs
1168        *value = dp->configs[intptr_t(s->config)].configId;
1169    } else {
1170        result = s->cnx->egl.eglQuerySurface(
1171                dp->disp[s->impl].dpy, s->surface, attribute, value);
1172    }
1173
1174    return result;
1175}
1176
1177// ----------------------------------------------------------------------------
1178// Contexts
1179// ----------------------------------------------------------------------------
1180
1181EGLContext eglCreateContext(EGLDisplay dpy, EGLConfig config,
1182                            EGLContext share_list, const EGLint *attrib_list)
1183{
1184    egl_display_t const* dp = 0;
1185    egl_connection_t* cnx = validate_display_config(dpy, config, dp);
1186    if (cnx) {
1187        if (share_list != EGL_NO_CONTEXT) {
1188            egl_context_t* const c = get_context(share_list);
1189            share_list = c->context;
1190        }
1191        EGLContext context = cnx->egl.eglCreateContext(
1192                dp->disp[ dp->configs[intptr_t(config)].impl ].dpy,
1193                dp->configs[intptr_t(config)].config,
1194                share_list, attrib_list);
1195        if (context != EGL_NO_CONTEXT) {
1196            // figure out if it's a GLESv1 or GLESv2
1197            int version = 0;
1198            if (attrib_list) {
1199                while (*attrib_list != EGL_NONE) {
1200                    GLint attr = *attrib_list++;
1201                    GLint value = *attrib_list++;
1202                    if (attr == EGL_CONTEXT_CLIENT_VERSION) {
1203                        if (value == 1) {
1204                            version = GLESv1_INDEX;
1205                        } else if (value == 2) {
1206                            version = GLESv2_INDEX;
1207                        }
1208                    }
1209                };
1210            }
1211            egl_context_t* c = new egl_context_t(dpy, context, config,
1212                    dp->configs[intptr_t(config)].impl, cnx, version);
1213            return c;
1214        }
1215    }
1216    return EGL_NO_CONTEXT;
1217}
1218
1219EGLBoolean eglDestroyContext(EGLDisplay dpy, EGLContext ctx)
1220{
1221    ContextRef _c(ctx);
1222    if (!_c.get()) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1223
1224    if (!validate_display_context(dpy, ctx))
1225        return EGL_FALSE;
1226    egl_display_t const * const dp = get_display(dpy);
1227    egl_context_t * const c = get_context(ctx);
1228    EGLBoolean result = c->cnx->egl.eglDestroyContext(
1229            dp->disp[c->impl].dpy, c->context);
1230    if (result == EGL_TRUE) {
1231        _c.terminate();
1232    }
1233    return result;
1234}
1235
1236static void loseCurrent(egl_context_t * cur_c)
1237{
1238    if (cur_c) {
1239        egl_surface_t * cur_r = get_surface(cur_c->read);
1240        egl_surface_t * cur_d = get_surface(cur_c->draw);
1241
1242        // by construction, these are either 0 or valid (possibly terminated)
1243        // it should be impossible for these to be invalid
1244        ContextRef _cur_c(cur_c);
1245        SurfaceRef _cur_r(cur_r);
1246        SurfaceRef _cur_d(cur_d);
1247
1248        cur_c->read = NULL;
1249        cur_c->draw = NULL;
1250
1251        _cur_c.release();
1252        _cur_r.release();
1253        _cur_d.release();
1254    }
1255}
1256
1257EGLBoolean eglMakeCurrent(  EGLDisplay dpy, EGLSurface draw,
1258                            EGLSurface read, EGLContext ctx)
1259{
1260    // get a reference to the object passed in
1261    ContextRef _c(ctx);
1262    SurfaceRef _d(draw);
1263    SurfaceRef _r(read);
1264
1265    // validate the display and the context (if not EGL_NO_CONTEXT)
1266    egl_display_t const * const dp = get_display(dpy);
1267    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1268    if ((ctx != EGL_NO_CONTEXT) && (!validate_display_context(dpy, ctx))) {
1269        // EGL_NO_CONTEXT is valid
1270        return EGL_FALSE;
1271    }
1272
1273    // these are the underlying implementation's object
1274    EGLContext impl_ctx  = EGL_NO_CONTEXT;
1275    EGLSurface impl_draw = EGL_NO_SURFACE;
1276    EGLSurface impl_read = EGL_NO_SURFACE;
1277
1278    // these are our objects structs passed in
1279    egl_context_t       * c = NULL;
1280    egl_surface_t const * d = NULL;
1281    egl_surface_t const * r = NULL;
1282
1283    // these are the current objects structs
1284    egl_context_t * cur_c = get_context(getContext());
1285
1286    if (ctx != EGL_NO_CONTEXT) {
1287        c = get_context(ctx);
1288        impl_ctx = c->context;
1289    } else {
1290        // no context given, use the implementation of the current context
1291        if (cur_c == NULL) {
1292            // no current context
1293            if (draw != EGL_NO_SURFACE || read != EGL_NO_SURFACE) {
1294                // calling eglMakeCurrent( ..., !=0, !=0, EGL_NO_CONTEXT);
1295                return setError(EGL_BAD_MATCH, EGL_FALSE);
1296            }
1297            // not an error, there is just no current context.
1298            return EGL_TRUE;
1299        }
1300    }
1301
1302    // retrieve the underlying implementation's draw EGLSurface
1303    if (draw != EGL_NO_SURFACE) {
1304        d = get_surface(draw);
1305        // make sure the EGLContext and EGLSurface passed in are for
1306        // the same driver
1307        if (c && d->impl != c->impl)
1308            return setError(EGL_BAD_MATCH, EGL_FALSE);
1309        impl_draw = d->surface;
1310    }
1311
1312    // retrieve the underlying implementation's read EGLSurface
1313    if (read != EGL_NO_SURFACE) {
1314        r = get_surface(read);
1315        // make sure the EGLContext and EGLSurface passed in are for
1316        // the same driver
1317        if (c && r->impl != c->impl)
1318            return setError(EGL_BAD_MATCH, EGL_FALSE);
1319        impl_read = r->surface;
1320    }
1321
1322    EGLBoolean result;
1323
1324    if (c) {
1325        result = c->cnx->egl.eglMakeCurrent(
1326                dp->disp[c->impl].dpy, impl_draw, impl_read, impl_ctx);
1327    } else {
1328        result = cur_c->cnx->egl.eglMakeCurrent(
1329                dp->disp[cur_c->impl].dpy, impl_draw, impl_read, impl_ctx);
1330    }
1331
1332    if (result == EGL_TRUE) {
1333
1334        loseCurrent(cur_c);
1335
1336        if (ctx != EGL_NO_CONTEXT) {
1337            setGLHooksThreadSpecific(c->cnx->hooks[c->version]);
1338            setContext(ctx);
1339            _c.acquire();
1340            _r.acquire();
1341            _d.acquire();
1342            c->read = read;
1343            c->draw = draw;
1344        } else {
1345            setGLHooksThreadSpecific(&gHooksNoContext);
1346            setContext(EGL_NO_CONTEXT);
1347        }
1348    }
1349    return result;
1350}
1351
1352
1353EGLBoolean eglQueryContext( EGLDisplay dpy, EGLContext ctx,
1354                            EGLint attribute, EGLint *value)
1355{
1356    ContextRef _c(ctx);
1357    if (!_c.get()) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1358
1359    if (!validate_display_context(dpy, ctx))
1360        return EGL_FALSE;
1361
1362    egl_display_t const * const dp = get_display(dpy);
1363    egl_context_t * const c = get_context(ctx);
1364
1365    EGLBoolean result(EGL_TRUE);
1366    if (attribute == EGL_CONFIG_ID) {
1367        *value = dp->configs[intptr_t(c->config)].configId;
1368    } else {
1369        // We need to remap EGL_CONFIG_IDs
1370        result = c->cnx->egl.eglQueryContext(
1371                dp->disp[c->impl].dpy, c->context, attribute, value);
1372    }
1373
1374    return result;
1375}
1376
1377EGLContext eglGetCurrentContext(void)
1378{
1379    // could be called before eglInitialize(), but we wouldn't have a context
1380    // then, and this function would correctly return EGL_NO_CONTEXT.
1381
1382    EGLContext ctx = getContext();
1383    return ctx;
1384}
1385
1386EGLSurface eglGetCurrentSurface(EGLint readdraw)
1387{
1388    // could be called before eglInitialize(), but we wouldn't have a context
1389    // then, and this function would correctly return EGL_NO_SURFACE.
1390
1391    EGLContext ctx = getContext();
1392    if (ctx) {
1393        egl_context_t const * const c = get_context(ctx);
1394        if (!c) return setError(EGL_BAD_CONTEXT, EGL_NO_SURFACE);
1395        switch (readdraw) {
1396            case EGL_READ: return c->read;
1397            case EGL_DRAW: return c->draw;
1398            default: return setError(EGL_BAD_PARAMETER, EGL_NO_SURFACE);
1399        }
1400    }
1401    return EGL_NO_SURFACE;
1402}
1403
1404EGLDisplay eglGetCurrentDisplay(void)
1405{
1406    // could be called before eglInitialize(), but we wouldn't have a context
1407    // then, and this function would correctly return EGL_NO_DISPLAY.
1408
1409    EGLContext ctx = getContext();
1410    if (ctx) {
1411        egl_context_t const * const c = get_context(ctx);
1412        if (!c) return setError(EGL_BAD_CONTEXT, EGL_NO_SURFACE);
1413        return c->dpy;
1414    }
1415    return EGL_NO_DISPLAY;
1416}
1417
1418EGLBoolean eglWaitGL(void)
1419{
1420    // could be called before eglInitialize(), but we wouldn't have a context
1421    // then, and this function would return GL_TRUE, which isn't wrong.
1422
1423    EGLBoolean res = EGL_TRUE;
1424    EGLContext ctx = getContext();
1425    if (ctx) {
1426        egl_context_t const * const c = get_context(ctx);
1427        if (!c) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1428        if (uint32_t(c->impl)>=2)
1429            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1430        egl_connection_t* const cnx = &gEGLImpl[c->impl];
1431        if (!cnx->dso)
1432            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1433        res = cnx->egl.eglWaitGL();
1434    }
1435    return res;
1436}
1437
1438EGLBoolean eglWaitNative(EGLint engine)
1439{
1440    // could be called before eglInitialize(), but we wouldn't have a context
1441    // then, and this function would return GL_TRUE, which isn't wrong.
1442
1443    EGLBoolean res = EGL_TRUE;
1444    EGLContext ctx = getContext();
1445    if (ctx) {
1446        egl_context_t const * const c = get_context(ctx);
1447        if (!c) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1448        if (uint32_t(c->impl)>=2)
1449            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1450        egl_connection_t* const cnx = &gEGLImpl[c->impl];
1451        if (!cnx->dso)
1452            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1453        res = cnx->egl.eglWaitNative(engine);
1454    }
1455    return res;
1456}
1457
1458EGLint eglGetError(void)
1459{
1460    EGLint result = EGL_SUCCESS;
1461    EGLint err;
1462    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
1463        err = EGL_SUCCESS;
1464        egl_connection_t* const cnx = &gEGLImpl[i];
1465        if (cnx->dso)
1466            err = cnx->egl.eglGetError();
1467        if (err!=EGL_SUCCESS && result==EGL_SUCCESS)
1468            result = err;
1469    }
1470    err = getError();
1471    if (result == EGL_SUCCESS)
1472        result = err;
1473    return result;
1474}
1475
1476__eglMustCastToProperFunctionPointerType eglGetProcAddress(const char *procname)
1477{
1478    // eglGetProcAddress() could be the very first function called
1479    // in which case we must make sure we've initialized ourselves, this
1480    // happens the first time egl_get_display() is called.
1481
1482    if (egl_init_drivers() == EGL_FALSE) {
1483        setError(EGL_BAD_PARAMETER, NULL);
1484        return  NULL;
1485    }
1486
1487    __eglMustCastToProperFunctionPointerType addr;
1488    addr = findProcAddress(procname, gExtentionMap, NELEM(gExtentionMap));
1489    if (addr) return addr;
1490
1491    // this protects accesses to gGLExtentionMap and gGLExtentionSlot
1492    pthread_mutex_lock(&gInitDriverMutex);
1493
1494        /*
1495         * Since eglGetProcAddress() is not associated to anything, it needs
1496         * to return a function pointer that "works" regardless of what
1497         * the current context is.
1498         *
1499         * For this reason, we return a "forwarder", a small stub that takes
1500         * care of calling the function associated with the context
1501         * currently bound.
1502         *
1503         * We first look for extensions we've already resolved, if we're seeing
1504         * this extension for the first time, we go through all our
1505         * implementations and call eglGetProcAddress() and record the
1506         * result in the appropriate implementation hooks and return the
1507         * address of the forwarder corresponding to that hook set.
1508         *
1509         */
1510
1511        const String8 name(procname);
1512        addr = gGLExtentionMap.valueFor(name);
1513        const int slot = gGLExtentionSlot;
1514
1515        LOGE_IF(slot >= MAX_NUMBER_OF_GL_EXTENSIONS,
1516                "no more slots for eglGetProcAddress(\"%s\")",
1517                procname);
1518
1519        if (!addr && (slot < MAX_NUMBER_OF_GL_EXTENSIONS)) {
1520            bool found = false;
1521            for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
1522                egl_connection_t* const cnx = &gEGLImpl[i];
1523                if (cnx->dso && cnx->egl.eglGetProcAddress) {
1524                    found = true;
1525                    // Extensions are independent of the bound context
1526                    cnx->hooks[GLESv1_INDEX]->ext.extensions[slot] =
1527                    cnx->hooks[GLESv2_INDEX]->ext.extensions[slot] =
1528#if EGL_TRACE
1529                    gHooksTrace.ext.extensions[slot] =
1530#endif
1531                            cnx->egl.eglGetProcAddress(procname);
1532                }
1533            }
1534            if (found) {
1535                addr = gExtensionForwarders[slot];
1536                gGLExtentionMap.add(name, addr);
1537                gGLExtentionSlot++;
1538            }
1539        }
1540
1541    pthread_mutex_unlock(&gInitDriverMutex);
1542    return addr;
1543}
1544
1545EGLBoolean eglSwapBuffers(EGLDisplay dpy, EGLSurface draw)
1546{
1547    SurfaceRef _s(draw);
1548    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1549
1550    if (!validate_display_surface(dpy, draw))
1551        return EGL_FALSE;
1552    egl_display_t const * const dp = get_display(dpy);
1553    egl_surface_t const * const s = get_surface(draw);
1554    return s->cnx->egl.eglSwapBuffers(dp->disp[s->impl].dpy, s->surface);
1555}
1556
1557EGLBoolean eglCopyBuffers(  EGLDisplay dpy, EGLSurface surface,
1558                            NativePixmapType target)
1559{
1560    SurfaceRef _s(surface);
1561    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1562
1563    if (!validate_display_surface(dpy, surface))
1564        return EGL_FALSE;
1565    egl_display_t const * const dp = get_display(dpy);
1566    egl_surface_t const * const s = get_surface(surface);
1567    return s->cnx->egl.eglCopyBuffers(
1568            dp->disp[s->impl].dpy, s->surface, target);
1569}
1570
1571const char* eglQueryString(EGLDisplay dpy, EGLint name)
1572{
1573    egl_display_t const * const dp = get_display(dpy);
1574    switch (name) {
1575        case EGL_VENDOR:
1576            return gVendorString;
1577        case EGL_VERSION:
1578            return gVersionString;
1579        case EGL_EXTENSIONS:
1580            return gExtensionString;
1581        case EGL_CLIENT_APIS:
1582            return gClientApiString;
1583    }
1584    return setError(EGL_BAD_PARAMETER, (const char *)0);
1585}
1586
1587
1588// ----------------------------------------------------------------------------
1589// EGL 1.1
1590// ----------------------------------------------------------------------------
1591
1592EGLBoolean eglSurfaceAttrib(
1593        EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value)
1594{
1595    SurfaceRef _s(surface);
1596    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1597
1598    if (!validate_display_surface(dpy, surface))
1599        return EGL_FALSE;
1600    egl_display_t const * const dp = get_display(dpy);
1601    egl_surface_t const * const s = get_surface(surface);
1602    if (s->cnx->egl.eglSurfaceAttrib) {
1603        return s->cnx->egl.eglSurfaceAttrib(
1604                dp->disp[s->impl].dpy, s->surface, attribute, value);
1605    }
1606    return setError(EGL_BAD_SURFACE, EGL_FALSE);
1607}
1608
1609EGLBoolean eglBindTexImage(
1610        EGLDisplay dpy, EGLSurface surface, EGLint buffer)
1611{
1612    SurfaceRef _s(surface);
1613    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1614
1615    if (!validate_display_surface(dpy, surface))
1616        return EGL_FALSE;
1617    egl_display_t const * const dp = get_display(dpy);
1618    egl_surface_t const * const s = get_surface(surface);
1619    if (s->cnx->egl.eglBindTexImage) {
1620        return s->cnx->egl.eglBindTexImage(
1621                dp->disp[s->impl].dpy, s->surface, buffer);
1622    }
1623    return setError(EGL_BAD_SURFACE, EGL_FALSE);
1624}
1625
1626EGLBoolean eglReleaseTexImage(
1627        EGLDisplay dpy, EGLSurface surface, EGLint buffer)
1628{
1629    SurfaceRef _s(surface);
1630    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1631
1632    if (!validate_display_surface(dpy, surface))
1633        return EGL_FALSE;
1634    egl_display_t const * const dp = get_display(dpy);
1635    egl_surface_t const * const s = get_surface(surface);
1636    if (s->cnx->egl.eglReleaseTexImage) {
1637        return s->cnx->egl.eglReleaseTexImage(
1638                dp->disp[s->impl].dpy, s->surface, buffer);
1639    }
1640    return setError(EGL_BAD_SURFACE, EGL_FALSE);
1641}
1642
1643EGLBoolean eglSwapInterval(EGLDisplay dpy, EGLint interval)
1644{
1645    egl_display_t * const dp = get_display(dpy);
1646    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1647
1648    EGLBoolean res = EGL_TRUE;
1649    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
1650        egl_connection_t* const cnx = &gEGLImpl[i];
1651        if (cnx->dso) {
1652            if (cnx->egl.eglSwapInterval) {
1653                if (cnx->egl.eglSwapInterval(
1654                        dp->disp[i].dpy, interval) == EGL_FALSE) {
1655                    res = EGL_FALSE;
1656                }
1657            }
1658        }
1659    }
1660    return res;
1661}
1662
1663
1664// ----------------------------------------------------------------------------
1665// EGL 1.2
1666// ----------------------------------------------------------------------------
1667
1668EGLBoolean eglWaitClient(void)
1669{
1670    // could be called before eglInitialize(), but we wouldn't have a context
1671    // then, and this function would return GL_TRUE, which isn't wrong.
1672    EGLBoolean res = EGL_TRUE;
1673    EGLContext ctx = getContext();
1674    if (ctx) {
1675        egl_context_t const * const c = get_context(ctx);
1676        if (!c) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1677        if (uint32_t(c->impl)>=2)
1678            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1679        egl_connection_t* const cnx = &gEGLImpl[c->impl];
1680        if (!cnx->dso)
1681            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1682        if (cnx->egl.eglWaitClient) {
1683            res = cnx->egl.eglWaitClient();
1684        } else {
1685            res = cnx->egl.eglWaitGL();
1686        }
1687    }
1688    return res;
1689}
1690
1691EGLBoolean eglBindAPI(EGLenum api)
1692{
1693    if (egl_init_drivers() == EGL_FALSE) {
1694        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1695    }
1696
1697    // bind this API on all EGLs
1698    EGLBoolean res = EGL_TRUE;
1699    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
1700        egl_connection_t* const cnx = &gEGLImpl[i];
1701        if (cnx->dso) {
1702            if (cnx->egl.eglBindAPI) {
1703                if (cnx->egl.eglBindAPI(api) == EGL_FALSE) {
1704                    res = EGL_FALSE;
1705                }
1706            }
1707        }
1708    }
1709    return res;
1710}
1711
1712EGLenum eglQueryAPI(void)
1713{
1714    if (egl_init_drivers() == EGL_FALSE) {
1715        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1716    }
1717
1718    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
1719        egl_connection_t* const cnx = &gEGLImpl[i];
1720        if (cnx->dso) {
1721            if (cnx->egl.eglQueryAPI) {
1722                // the first one we find is okay, because they all
1723                // should be the same
1724                return cnx->egl.eglQueryAPI();
1725            }
1726        }
1727    }
1728    // or, it can only be OpenGL ES
1729    return EGL_OPENGL_ES_API;
1730}
1731
1732EGLBoolean eglReleaseThread(void)
1733{
1734    // If there is context bound to the thread, release it
1735    loseCurrent(get_context(getContext()));
1736
1737    for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
1738        egl_connection_t* const cnx = &gEGLImpl[i];
1739        if (cnx->dso) {
1740            if (cnx->egl.eglReleaseThread) {
1741                cnx->egl.eglReleaseThread();
1742            }
1743        }
1744    }
1745    clearTLS();
1746    return EGL_TRUE;
1747}
1748
1749EGLSurface eglCreatePbufferFromClientBuffer(
1750          EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer,
1751          EGLConfig config, const EGLint *attrib_list)
1752{
1753    egl_display_t const* dp = 0;
1754    egl_connection_t* cnx = validate_display_config(dpy, config, dp);
1755    if (!cnx) return EGL_FALSE;
1756    if (cnx->egl.eglCreatePbufferFromClientBuffer) {
1757        return cnx->egl.eglCreatePbufferFromClientBuffer(
1758                dp->disp[ dp->configs[intptr_t(config)].impl ].dpy,
1759                buftype, buffer,
1760                dp->configs[intptr_t(config)].config, attrib_list);
1761    }
1762    return setError(EGL_BAD_CONFIG, EGL_NO_SURFACE);
1763}
1764
1765// ----------------------------------------------------------------------------
1766// EGL_EGLEXT_VERSION 3
1767// ----------------------------------------------------------------------------
1768
1769EGLBoolean eglLockSurfaceKHR(EGLDisplay dpy, EGLSurface surface,
1770        const EGLint *attrib_list)
1771{
1772    SurfaceRef _s(surface);
1773    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1774
1775    if (!validate_display_surface(dpy, surface))
1776        return EGL_FALSE;
1777
1778    egl_display_t const * const dp = get_display(dpy);
1779    egl_surface_t const * const s = get_surface(surface);
1780
1781    if (s->cnx->egl.eglLockSurfaceKHR) {
1782        return s->cnx->egl.eglLockSurfaceKHR(
1783                dp->disp[s->impl].dpy, s->surface, attrib_list);
1784    }
1785    return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1786}
1787
1788EGLBoolean eglUnlockSurfaceKHR(EGLDisplay dpy, EGLSurface surface)
1789{
1790    SurfaceRef _s(surface);
1791    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1792
1793    if (!validate_display_surface(dpy, surface))
1794        return EGL_FALSE;
1795
1796    egl_display_t const * const dp = get_display(dpy);
1797    egl_surface_t const * const s = get_surface(surface);
1798
1799    if (s->cnx->egl.eglUnlockSurfaceKHR) {
1800        return s->cnx->egl.eglUnlockSurfaceKHR(
1801                dp->disp[s->impl].dpy, s->surface);
1802    }
1803    return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1804}
1805
1806EGLImageKHR eglCreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target,
1807        EGLClientBuffer buffer, const EGLint *attrib_list)
1808{
1809    if (ctx != EGL_NO_CONTEXT) {
1810        ContextRef _c(ctx);
1811        if (!_c.get()) return setError(EGL_BAD_CONTEXT, EGL_NO_IMAGE_KHR);
1812        if (!validate_display_context(dpy, ctx))
1813            return EGL_NO_IMAGE_KHR;
1814        egl_display_t const * const dp = get_display(dpy);
1815        egl_context_t * const c = get_context(ctx);
1816        // since we have an EGLContext, we know which implementation to use
1817        EGLImageKHR image = c->cnx->egl.eglCreateImageKHR(
1818                dp->disp[c->impl].dpy, c->context, target, buffer, attrib_list);
1819        if (image == EGL_NO_IMAGE_KHR)
1820            return image;
1821
1822        egl_image_t* result = new egl_image_t(dpy, ctx);
1823        result->images[c->impl] = image;
1824        return (EGLImageKHR)result;
1825    } else {
1826        // EGL_NO_CONTEXT is a valid parameter
1827        egl_display_t const * const dp = get_display(dpy);
1828        if (dp == 0) {
1829            return setError(EGL_BAD_DISPLAY, EGL_NO_IMAGE_KHR);
1830        }
1831
1832        /* Since we don't have a way to know which implementation to call,
1833         * we're calling all of them. If at least one of the implementation
1834         * succeeded, this is a success.
1835         */
1836
1837        EGLint currentError = eglGetError();
1838
1839        EGLImageKHR implImages[IMPL_NUM_IMPLEMENTATIONS];
1840        bool success = false;
1841        for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
1842            egl_connection_t* const cnx = &gEGLImpl[i];
1843            implImages[i] = EGL_NO_IMAGE_KHR;
1844            if (cnx->dso) {
1845                if (cnx->egl.eglCreateImageKHR) {
1846                    implImages[i] = cnx->egl.eglCreateImageKHR(
1847                            dp->disp[i].dpy, ctx, target, buffer, attrib_list);
1848                    if (implImages[i] != EGL_NO_IMAGE_KHR) {
1849                        success = true;
1850                    }
1851                }
1852            }
1853        }
1854
1855        if (!success) {
1856            // failure, if there was an error when we entered this function,
1857            // the error flag must not be updated.
1858            // Otherwise, the error is whatever happened in the implementation
1859            // that faulted.
1860            if (currentError != EGL_SUCCESS) {
1861                setError(currentError, EGL_NO_IMAGE_KHR);
1862            }
1863            return EGL_NO_IMAGE_KHR;
1864        } else {
1865            // In case of success, we need to clear all error flags
1866            // (especially those caused by the implementation that didn't
1867            // succeed). TODO: we could avoid this if we knew this was
1868            // a "full" success (all implementation succeeded).
1869            eglGetError();
1870        }
1871
1872        egl_image_t* result = new egl_image_t(dpy, ctx);
1873        memcpy(result->images, implImages, sizeof(implImages));
1874        return (EGLImageKHR)result;
1875    }
1876}
1877
1878EGLBoolean eglDestroyImageKHR(EGLDisplay dpy, EGLImageKHR img)
1879{
1880    egl_display_t const * const dp = get_display(dpy);
1881     if (dp == 0) {
1882         return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1883     }
1884
1885     ImageRef _i(img);
1886     if (!_i.get()) return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1887
1888     egl_image_t* image = get_image(img);
1889     bool success = false;
1890     for (int i=0 ; i<IMPL_NUM_IMPLEMENTATIONS ; i++) {
1891         egl_connection_t* const cnx = &gEGLImpl[i];
1892         if (image->images[i] != EGL_NO_IMAGE_KHR) {
1893             if (cnx->dso) {
1894                 if (cnx->egl.eglDestroyImageKHR) {
1895                     if (cnx->egl.eglDestroyImageKHR(
1896                             dp->disp[i].dpy, image->images[i])) {
1897                         success = true;
1898                     }
1899                 }
1900             }
1901         }
1902     }
1903     if (!success)
1904         return EGL_FALSE;
1905
1906     _i.terminate();
1907
1908     return EGL_TRUE;
1909}
1910
1911// ----------------------------------------------------------------------------
1912// EGL_EGLEXT_VERSION 5
1913// ----------------------------------------------------------------------------
1914
1915
1916EGLSyncKHR eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint *attrib_list)
1917{
1918    EGLContext ctx = eglGetCurrentContext();
1919    ContextRef _c(ctx);
1920    if (!_c.get()) return setError(EGL_BAD_CONTEXT, EGL_NO_SYNC_KHR);
1921    if (!validate_display_context(dpy, ctx))
1922        return EGL_NO_SYNC_KHR;
1923    egl_display_t const * const dp = get_display(dpy);
1924    egl_context_t * const c = get_context(ctx);
1925    EGLSyncKHR result = EGL_NO_SYNC_KHR;
1926    if (c->cnx->egl.eglCreateSyncKHR) {
1927        EGLSyncKHR sync = c->cnx->egl.eglCreateSyncKHR(
1928                dp->disp[c->impl].dpy, type, attrib_list);
1929        if (sync == EGL_NO_SYNC_KHR)
1930            return sync;
1931        result = (egl_sync_t*)new egl_sync_t(dpy, ctx, sync);
1932    }
1933    return (EGLSyncKHR)result;
1934}
1935
1936EGLBoolean eglDestroySyncKHR(EGLDisplay dpy, EGLSyncKHR sync)
1937{
1938    egl_display_t const * const dp = get_display(dpy);
1939    if (dp == 0) {
1940        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1941    }
1942
1943    SyncRef _s(sync);
1944    if (!_s.get()) return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1945    egl_sync_t* syncObject = get_sync(sync);
1946
1947    EGLContext ctx = syncObject->context;
1948    ContextRef _c(ctx);
1949    if (!_c.get()) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1950    if (!validate_display_context(dpy, ctx))
1951        return EGL_FALSE;
1952
1953    egl_context_t * const c = get_context(ctx);
1954
1955    if (c->cnx->egl.eglDestroySyncKHR) {
1956        return c->cnx->egl.eglDestroySyncKHR(
1957                dp->disp[c->impl].dpy, syncObject->sync);
1958    }
1959
1960    return EGL_FALSE;
1961}
1962
1963EGLint eglClientWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout)
1964{
1965    egl_display_t const * const dp = get_display(dpy);
1966    if (dp == 0) {
1967        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1968    }
1969
1970    SyncRef _s(sync);
1971    if (!_s.get()) return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1972    egl_sync_t* syncObject = get_sync(sync);
1973
1974    EGLContext ctx = syncObject->context;
1975    ContextRef _c(ctx);
1976    if (!_c.get()) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1977    if (!validate_display_context(dpy, ctx))
1978        return EGL_FALSE;
1979
1980    egl_context_t * const c = get_context(ctx);
1981
1982    if (c->cnx->egl.eglClientWaitSyncKHR) {
1983        return c->cnx->egl.eglClientWaitSyncKHR(
1984                dp->disp[c->impl].dpy, syncObject->sync, flags, timeout);
1985    }
1986
1987    return EGL_FALSE;
1988}
1989
1990EGLBoolean eglGetSyncAttribKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint *value)
1991{
1992    egl_display_t const * const dp = get_display(dpy);
1993    if (dp == 0) {
1994        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1995    }
1996
1997    SyncRef _s(sync);
1998    if (!_s.get()) return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1999    egl_sync_t* syncObject = get_sync(sync);
2000
2001    EGLContext ctx = syncObject->context;
2002    ContextRef _c(ctx);
2003    if (!_c.get()) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
2004    if (!validate_display_context(dpy, ctx))
2005        return EGL_FALSE;
2006
2007    egl_context_t * const c = get_context(ctx);
2008
2009    if (c->cnx->egl.eglGetSyncAttribKHR) {
2010        return c->cnx->egl.eglGetSyncAttribKHR(
2011                dp->disp[c->impl].dpy, syncObject->sync, attribute, value);
2012    }
2013
2014    return EGL_FALSE;
2015}
2016
2017// ----------------------------------------------------------------------------
2018// ANDROID extensions
2019// ----------------------------------------------------------------------------
2020
2021EGLBoolean eglSetSwapRectangleANDROID(EGLDisplay dpy, EGLSurface draw,
2022        EGLint left, EGLint top, EGLint width, EGLint height)
2023{
2024    SurfaceRef _s(draw);
2025    if (!_s.get()) return setError(EGL_BAD_SURFACE, EGL_FALSE);
2026
2027    if (!validate_display_surface(dpy, draw))
2028        return EGL_FALSE;
2029    egl_display_t const * const dp = get_display(dpy);
2030    egl_surface_t const * const s = get_surface(draw);
2031    if (s->cnx->egl.eglSetSwapRectangleANDROID) {
2032        return s->cnx->egl.eglSetSwapRectangleANDROID(
2033                dp->disp[s->impl].dpy, s->surface, left, top, width, height);
2034    }
2035    return setError(EGL_BAD_DISPLAY, NULL);
2036}
2037