egl.cpp revision 7be3e5d2d8101a8f5e12bbdf650431a734f88eba
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 <string.h>
19#include <errno.h>
20#include <dlfcn.h>
21
22#include <sys/ioctl.h>
23
24#if HAVE_ANDROID_OS
25#include <linux/android_pmem.h>
26#endif
27
28#include <EGL/egl.h>
29#include <EGL/eglext.h>
30#include <GLES/gl.h>
31#include <GLES/glext.h>
32
33#include <cutils/log.h>
34#include <cutils/atomic.h>
35#include <cutils/properties.h>
36#include <cutils/memory.h>
37
38#include <utils/RefBase.h>
39#include <utils/threads.h>
40#include <utils/KeyedVector.h>
41
42#include "hooks.h"
43#include "egl_impl.h"
44
45
46#define MAKE_CONFIG(_impl, _index)  ((EGLConfig)(((_impl)<<24) | (_index)))
47#define setError(_e, _r) setErrorEtc(__FUNCTION__, __LINE__, _e, _r)
48
49// ----------------------------------------------------------------------------
50namespace android {
51// ----------------------------------------------------------------------------
52
53#define VERSION_MAJOR 1
54#define VERSION_MINOR 4
55static char const * const gVendorString     = "Android";
56static char const * const gVersionString    = "1.31 Android META-EGL";
57static char const * const gClientApiString  = "OpenGL ES";
58static char const * const gExtensionString  =
59        "EGL_KHR_image "
60        "KHR_image_base "
61        "KHR_image_pixmap "
62        "EGL_ANDROID_image_native_buffer "
63        ;
64
65// ----------------------------------------------------------------------------
66
67template <int MAGIC>
68struct egl_object_t
69{
70    egl_object_t() : magic(MAGIC) { }
71    ~egl_object_t() { magic = 0; }
72    bool isValid() const { return magic == MAGIC; }
73private:
74    uint32_t    magic;
75};
76
77struct egl_display_t : public egl_object_t<'_dpy'>
78{
79    EGLDisplay  dpys[IMPL_NUM_DRIVERS_IMPLEMENTATIONS];
80    EGLConfig*  configs[IMPL_NUM_DRIVERS_IMPLEMENTATIONS];
81    EGLint      numConfigs[IMPL_NUM_DRIVERS_IMPLEMENTATIONS];
82    EGLint      numTotalConfigs;
83    char const* extensionsString;
84    volatile int32_t refs;
85    struct strings_t {
86        char const * vendor;
87        char const * version;
88        char const * clientApi;
89        char const * extensions;
90    };
91    strings_t   queryString[IMPL_NUM_DRIVERS_IMPLEMENTATIONS];
92};
93
94struct egl_surface_t : public egl_object_t<'_srf'>
95{
96    egl_surface_t(EGLDisplay dpy, EGLSurface surface,
97            int impl, egl_connection_t const* cnx)
98    : dpy(dpy), surface(surface), impl(impl), cnx(cnx)
99    {
100        // NOTE: window must be incRef'ed and connected already
101    }
102    ~egl_surface_t() {
103    }
104    EGLDisplay                  dpy;
105    EGLSurface                  surface;
106    int                         impl;
107    egl_connection_t const*     cnx;
108};
109
110struct egl_context_t : public egl_object_t<'_ctx'>
111{
112    egl_context_t(EGLDisplay dpy, EGLContext context,
113            int impl, egl_connection_t const* cnx)
114    : dpy(dpy), context(context), read(0), draw(0), impl(impl), cnx(cnx)
115    {
116    }
117    EGLDisplay                  dpy;
118    EGLContext                  context;
119    EGLSurface                  read;
120    EGLSurface                  draw;
121    int                         impl;
122    egl_connection_t const*     cnx;
123};
124
125struct egl_image_t : public egl_object_t<'_img'>
126{
127    egl_image_t(EGLDisplay dpy, EGLContext context)
128        : dpy(dpy), context(context)
129    {
130        memset(images, 0, sizeof(images));
131    }
132    EGLDisplay dpy;
133    EGLConfig context;
134    EGLImageKHR images[IMPL_NUM_DRIVERS_IMPLEMENTATIONS];
135};
136
137struct tls_t
138{
139    tls_t() : error(EGL_SUCCESS), ctx(0) { }
140    EGLint      error;
141    EGLContext  ctx;
142};
143
144static void gl_unimplemented() {
145    LOGE("called unimplemented OpenGL ES API");
146}
147
148// ----------------------------------------------------------------------------
149// GL / EGL hooks
150// ----------------------------------------------------------------------------
151
152#undef GL_ENTRY
153#undef EGL_ENTRY
154#define GL_ENTRY(_r, _api, ...) #_api,
155#define EGL_ENTRY(_r, _api, ...) #_api,
156
157static char const * const gl_names[] = {
158    #include "gl_entries.in"
159    #include "glext_entries.in"
160    NULL
161};
162
163static char const * const egl_names[] = {
164    #include "egl_entries.in"
165    NULL
166};
167
168#undef GL_ENTRY
169#undef EGL_ENTRY
170
171// ----------------------------------------------------------------------------
172
173egl_connection_t gEGLImpl[IMPL_NUM_DRIVERS_IMPLEMENTATIONS];
174static egl_display_t gDisplay[NUM_DISPLAYS];
175static pthread_mutex_t gThreadLocalStorageKeyMutex = PTHREAD_MUTEX_INITIALIZER;
176static pthread_key_t gEGLThreadLocalStorageKey = -1;
177
178// ----------------------------------------------------------------------------
179
180gl_hooks_t gHooks[IMPL_NUM_IMPLEMENTATIONS];
181pthread_key_t gGLWrapperKey = -1;
182
183// ----------------------------------------------------------------------------
184
185static __attribute__((noinline))
186const char *egl_strerror(EGLint err)
187{
188    switch (err){
189        case EGL_SUCCESS:               return "EGL_SUCCESS";
190        case EGL_NOT_INITIALIZED:       return "EGL_NOT_INITIALIZED";
191        case EGL_BAD_ACCESS:            return "EGL_BAD_ACCESS";
192        case EGL_BAD_ALLOC:             return "EGL_BAD_ALLOC";
193        case EGL_BAD_ATTRIBUTE:         return "EGL_BAD_ATTRIBUTE";
194        case EGL_BAD_CONFIG:            return "EGL_BAD_CONFIG";
195        case EGL_BAD_CONTEXT:           return "EGL_BAD_CONTEXT";
196        case EGL_BAD_CURRENT_SURFACE:   return "EGL_BAD_CURRENT_SURFACE";
197        case EGL_BAD_DISPLAY:           return "EGL_BAD_DISPLAY";
198        case EGL_BAD_MATCH:             return "EGL_BAD_MATCH";
199        case EGL_BAD_NATIVE_PIXMAP:     return "EGL_BAD_NATIVE_PIXMAP";
200        case EGL_BAD_NATIVE_WINDOW:     return "EGL_BAD_NATIVE_WINDOW";
201        case EGL_BAD_PARAMETER:         return "EGL_BAD_PARAMETER";
202        case EGL_BAD_SURFACE:           return "EGL_BAD_SURFACE";
203        case EGL_CONTEXT_LOST:          return "EGL_CONTEXT_LOST";
204        default: return "UNKNOWN";
205    }
206}
207
208static __attribute__((noinline))
209void clearTLS() {
210    if (gEGLThreadLocalStorageKey != -1) {
211        tls_t* tls = (tls_t*)pthread_getspecific(gEGLThreadLocalStorageKey);
212        if (tls) {
213            delete tls;
214            pthread_setspecific(gEGLThreadLocalStorageKey, 0);
215        }
216    }
217}
218
219static tls_t* getTLS()
220{
221    tls_t* tls = (tls_t*)pthread_getspecific(gEGLThreadLocalStorageKey);
222    if (tls == 0) {
223        tls = new tls_t;
224        pthread_setspecific(gEGLThreadLocalStorageKey, tls);
225    }
226    return tls;
227}
228
229template<typename T>
230static __attribute__((noinline))
231T setErrorEtc(const char* caller, int line, EGLint error, T returnValue) {
232    if (gEGLThreadLocalStorageKey == -1) {
233        pthread_mutex_lock(&gThreadLocalStorageKeyMutex);
234        if (gEGLThreadLocalStorageKey == -1)
235            pthread_key_create(&gEGLThreadLocalStorageKey, NULL);
236        pthread_mutex_unlock(&gThreadLocalStorageKeyMutex);
237    }
238    tls_t* tls = getTLS();
239    if (tls->error != error) {
240        LOGE("%s:%d error %x (%s)", caller, line, error, egl_strerror(error));
241        tls->error = error;
242    }
243    return returnValue;
244}
245
246static __attribute__((noinline))
247GLint getError() {
248    if (gEGLThreadLocalStorageKey == -1)
249        return EGL_SUCCESS;
250    tls_t* tls = (tls_t*)pthread_getspecific(gEGLThreadLocalStorageKey);
251    if (!tls) return EGL_SUCCESS;
252    GLint error = tls->error;
253    tls->error = EGL_SUCCESS;
254    return error;
255}
256
257static __attribute__((noinline))
258void setContext(EGLContext ctx) {
259    if (gEGLThreadLocalStorageKey == -1) {
260        pthread_mutex_lock(&gThreadLocalStorageKeyMutex);
261        if (gEGLThreadLocalStorageKey == -1)
262            pthread_key_create(&gEGLThreadLocalStorageKey, NULL);
263        pthread_mutex_unlock(&gThreadLocalStorageKeyMutex);
264    }
265    tls_t* tls = getTLS();
266    tls->ctx = ctx;
267}
268
269static __attribute__((noinline))
270EGLContext getContext() {
271    if (gEGLThreadLocalStorageKey == -1)
272        return EGL_NO_CONTEXT;
273    tls_t* tls = (tls_t*)pthread_getspecific(gEGLThreadLocalStorageKey);
274    if (!tls) return EGL_NO_CONTEXT;
275    return tls->ctx;
276}
277
278/*****************************************************************************/
279
280static __attribute__((noinline))
281void *load_driver(const char* driver, gl_hooks_t* hooks)
282{
283    //LOGD("%s", driver);
284    char scrap[256];
285    void* dso = dlopen(driver, RTLD_NOW | RTLD_LOCAL);
286    LOGE_IF(!dso,
287            "couldn't load <%s> library (%s)",
288            driver, dlerror());
289
290    if (dso) {
291        // first find the symbol for eglGetProcAddress
292
293        typedef __eglMustCastToProperFunctionPointerType (*getProcAddressType)(
294                const char*);
295
296        getProcAddressType getProcAddress =
297            (getProcAddressType)dlsym(dso, "eglGetProcAddress");
298
299        LOGE_IF(!getProcAddress,
300                "can't find eglGetProcAddress() in %s", driver);
301
302        __eglMustCastToProperFunctionPointerType* curr;
303        char const * const * api;
304
305        gl_hooks_t::egl_t* egl = &hooks->egl;
306        curr = (__eglMustCastToProperFunctionPointerType*)egl;
307        api = egl_names;
308        while (*api) {
309            char const * name = *api;
310            __eglMustCastToProperFunctionPointerType f =
311                (__eglMustCastToProperFunctionPointerType)dlsym(dso, name);
312            if (f == NULL) {
313                // couldn't find the entry-point, use eglGetProcAddress()
314                f = getProcAddress(name);
315                if (f == NULL) {
316                    f = (__eglMustCastToProperFunctionPointerType)0;
317                }
318            }
319            *curr++ = f;
320            api++;
321        }
322        gl_hooks_t::gl_t* gl = &hooks->gl;
323        curr = (__eglMustCastToProperFunctionPointerType*)gl;
324        api = gl_names;
325        while (*api) {
326            char const * name = *api;
327            __eglMustCastToProperFunctionPointerType f =
328                (__eglMustCastToProperFunctionPointerType)dlsym(dso, name);
329            if (f == NULL) {
330                // couldn't find the entry-point, use eglGetProcAddress()
331                f = getProcAddress(name);
332            }
333            if (f == NULL) {
334                // Try without the OES postfix
335                ssize_t index = ssize_t(strlen(name)) - 3;
336                if ((index>0 && (index<255)) && (!strcmp(name+index, "OES"))) {
337                    strncpy(scrap, name, index);
338                    scrap[index] = 0;
339                    f = (__eglMustCastToProperFunctionPointerType)dlsym(dso, scrap);
340                    //LOGD_IF(f, "found <%s> instead", scrap);
341                }
342            }
343            if (f == NULL) {
344                // Try with the OES postfix
345                ssize_t index = ssize_t(strlen(name)) - 3;
346                if ((index>0 && (index<252)) && (strcmp(name+index, "OES"))) {
347                    strncpy(scrap, name, index);
348                    scrap[index] = 0;
349                    strcat(scrap, "OES");
350                    f = (__eglMustCastToProperFunctionPointerType)dlsym(dso, scrap);
351                    //LOGD_IF(f, "found <%s> instead", scrap);
352                }
353            }
354            if (f == NULL) {
355                //LOGD("%s", name);
356                f = (__eglMustCastToProperFunctionPointerType)gl_unimplemented;
357            }
358            *curr++ = f;
359            api++;
360        }
361    }
362    return dso;
363}
364
365template<typename T>
366static __attribute__((noinline))
367int binarySearch(
368        T const sortedArray[], int first, int last, T key)
369{
370    while (first <= last) {
371        int mid = (first + last) / 2;
372        if (key > sortedArray[mid]) {
373            first = mid + 1;
374        } else if (key < sortedArray[mid]) {
375            last = mid - 1;
376        } else {
377            return mid;
378        }
379    }
380    return -1;
381}
382
383static EGLint configToUniqueId(egl_display_t const* dp, int i, int index)
384{
385    // NOTE: this mapping works only if we have no more than two EGLimpl
386    return (i>0 ? dp->numConfigs[0] : 0) + index;
387}
388
389static void uniqueIdToConfig(egl_display_t const* dp, EGLint configId,
390        int& i, int& index)
391{
392    // NOTE: this mapping works only if we have no more than two EGLimpl
393    size_t numConfigs = dp->numConfigs[0];
394    i = configId / numConfigs;
395    index = configId % numConfigs;
396}
397
398static int cmp_configs(const void* a, const void *b)
399{
400    EGLConfig c0 = *(EGLConfig const *)a;
401    EGLConfig c1 = *(EGLConfig const *)b;
402    return c0<c1 ? -1 : (c0>c1 ? 1 : 0);
403}
404
405struct extention_map_t {
406    const char* name;
407    __eglMustCastToProperFunctionPointerType address;
408};
409
410static const extention_map_t gExtentionMap[] = {
411    { "eglLockSurfaceKHR",
412            (__eglMustCastToProperFunctionPointerType)&eglLockSurfaceKHR },
413    { "eglUnlockSurfaceKHR",
414            (__eglMustCastToProperFunctionPointerType)&eglUnlockSurfaceKHR },
415    { "eglCreateImageKHR",
416            (__eglMustCastToProperFunctionPointerType)&eglCreateImageKHR },
417    { "eglDestroyImageKHR",
418            (__eglMustCastToProperFunctionPointerType)&eglDestroyImageKHR },
419};
420
421static extention_map_t gGLExtentionMap[MAX_NUMBER_OF_GL_EXTENSIONS];
422
423static void(*findProcAddress(const char* name,
424        const extention_map_t* map, size_t n))()
425{
426    for (uint32_t i=0 ; i<n ; i++) {
427        if (!strcmp(name, map[i].name)) {
428            return map[i].address;
429        }
430    }
431    return NULL;
432}
433
434// ----------------------------------------------------------------------------
435
436/*
437 * To "loose" the GPU, use something like
438 *    gEGLImpl[IMPL_HARDWARE].hooks = &gHooks[IMPL_CONTEXT_LOST];
439 *
440 */
441
442static int gl_context_lost() {
443    setGlThreadSpecific(&gHooks[IMPL_CONTEXT_LOST]);
444    return 0;
445}
446static int egl_context_lost() {
447    setGlThreadSpecific(&gHooks[IMPL_CONTEXT_LOST]);
448    return EGL_FALSE;
449}
450static EGLBoolean egl_context_lost_swap_buffers(void*, void*) {
451    usleep(100000); // don't use all the CPU
452    setGlThreadSpecific(&gHooks[IMPL_CONTEXT_LOST]);
453    return EGL_FALSE;
454}
455static GLint egl_context_lost_get_error() {
456    return EGL_CONTEXT_LOST;
457}
458static int ext_context_lost() {
459    return 0;
460}
461
462static void gl_no_context() {
463    LOGE("call to OpenGL ES API with no current context");
464}
465static void early_egl_init(void)
466{
467#if !USE_FAST_TLS_KEY
468    pthread_key_create(&gGLWrapperKey, NULL);
469#endif
470    uint32_t addr = (uint32_t)((void*)gl_no_context);
471    android_memset32(
472            (uint32_t*)(void*)&gHooks[IMPL_NO_CONTEXT],
473            addr,
474            sizeof(gHooks[IMPL_NO_CONTEXT]));
475    setGlThreadSpecific(&gHooks[IMPL_NO_CONTEXT]);
476}
477
478static pthread_once_t once_control = PTHREAD_ONCE_INIT;
479static int sEarlyInitState = pthread_once(&once_control, &early_egl_init);
480
481
482static inline
483egl_display_t* get_display(EGLDisplay dpy)
484{
485    uintptr_t index = uintptr_t(dpy)-1U;
486    return (index >= NUM_DISPLAYS) ? NULL : &gDisplay[index];
487}
488
489template<typename NATIVE, typename EGL>
490static inline NATIVE* egl_to_native_cast(EGL arg) {
491    return reinterpret_cast<NATIVE*>(arg);
492}
493
494static inline
495egl_surface_t* get_surface(EGLSurface surface) {
496    return egl_to_native_cast<egl_surface_t>(surface);
497}
498
499static inline
500egl_context_t* get_context(EGLContext context) {
501    return egl_to_native_cast<egl_context_t>(context);
502}
503
504static inline
505egl_image_t* get_image(EGLImageKHR image) {
506    return egl_to_native_cast<egl_image_t>(image);
507}
508
509static egl_connection_t* validate_display_config(
510        EGLDisplay dpy, EGLConfig config,
511        egl_display_t const*& dp, int& impl, int& index)
512{
513    dp = get_display(dpy);
514    if (!dp) return setError(EGL_BAD_DISPLAY, (egl_connection_t*)NULL);
515
516    impl = uintptr_t(config)>>24;
517    if (uint32_t(impl) >= IMPL_NUM_DRIVERS_IMPLEMENTATIONS) {
518        return setError(EGL_BAD_CONFIG, (egl_connection_t*)NULL);
519    }
520    index = uintptr_t(config) & 0xFFFFFF;
521    if (index >= dp->numConfigs[impl]) {
522        return setError(EGL_BAD_CONFIG, (egl_connection_t*)NULL);
523    }
524    egl_connection_t* const cnx = &gEGLImpl[impl];
525    if (cnx->dso == 0) {
526        return setError(EGL_BAD_CONFIG, (egl_connection_t*)NULL);
527    }
528    return cnx;
529}
530
531static EGLBoolean validate_display_context(EGLDisplay dpy, EGLContext ctx)
532{
533    if ((uintptr_t(dpy)-1U) >= NUM_DISPLAYS)
534        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
535    if (!get_display(dpy)->isValid())
536        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
537    if (!ctx) // TODO: make sure context is a valid object
538        return setError(EGL_BAD_CONTEXT, EGL_FALSE);
539    if (!get_context(ctx)->isValid())
540        return setError(EGL_BAD_CONTEXT, EGL_FALSE);
541    return EGL_TRUE;
542}
543
544static EGLBoolean validate_display_surface(EGLDisplay dpy, EGLSurface surface)
545{
546    if ((uintptr_t(dpy)-1U) >= NUM_DISPLAYS)
547        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
548    if (!get_display(dpy)->isValid())
549        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
550    if (!surface) // TODO: make sure surface is a valid object
551        return setError(EGL_BAD_SURFACE, EGL_FALSE);
552    if (!get_surface(surface)->isValid())
553        return setError(EGL_BAD_SURFACE, EGL_FALSE);
554    return EGL_TRUE;
555}
556
557
558EGLImageKHR egl_get_image_for_current_context(EGLImageKHR image)
559{
560    EGLContext context = getContext();
561    if (context == EGL_NO_CONTEXT || image == EGL_NO_IMAGE_KHR)
562        return EGL_NO_IMAGE_KHR;
563
564    egl_context_t const * const c = get_context(context);
565    if (!c->isValid())
566        return EGL_NO_IMAGE_KHR;
567
568    egl_image_t const * const i = get_image(image);
569    if (!i->isValid())
570        return EGL_NO_IMAGE_KHR;
571
572    return i->images[c->impl];
573}
574
575
576EGLDisplay egl_init_displays(NativeDisplayType display)
577{
578    if (sEarlyInitState) {
579        return EGL_NO_DISPLAY;
580    }
581
582    uint32_t index = uint32_t(display);
583    if (index >= NUM_DISPLAYS) {
584        return EGL_NO_DISPLAY;
585    }
586
587    EGLDisplay dpy = EGLDisplay(uintptr_t(display) + 1LU);
588    egl_display_t* d = &gDisplay[index];
589
590    // dynamically load all our EGL implementations for that display
591    // and call into the real eglGetGisplay()
592    egl_connection_t* cnx = &gEGLImpl[IMPL_SOFTWARE];
593    if (cnx->dso == 0) {
594        cnx->hooks = &gHooks[IMPL_SOFTWARE];
595        cnx->dso = load_driver("libagl.so", cnx->hooks);
596    }
597    if (cnx->dso && d->dpys[IMPL_SOFTWARE]==EGL_NO_DISPLAY) {
598        d->dpys[IMPL_SOFTWARE] = cnx->hooks->egl.eglGetDisplay(display);
599        LOGE_IF(d->dpys[IMPL_SOFTWARE]==EGL_NO_DISPLAY,
600                "No EGLDisplay for software EGL!");
601    }
602
603    cnx = &gEGLImpl[IMPL_HARDWARE];
604    if (cnx->dso == 0 && cnx->unavailable == 0) {
605        char value[PROPERTY_VALUE_MAX];
606        property_get("debug.egl.hw", value, "1");
607        if (atoi(value) != 0) {
608            cnx->hooks = &gHooks[IMPL_HARDWARE];
609            cnx->dso = load_driver("libhgl2.so", cnx->hooks);
610        } else {
611            LOGD("3D hardware acceleration is disabled");
612        }
613    }
614    if (cnx->dso && d->dpys[IMPL_HARDWARE]==EGL_NO_DISPLAY) {
615        android_memset32(
616                (uint32_t*)(void*)&gHooks[IMPL_CONTEXT_LOST].gl,
617                (uint32_t)((void*)gl_context_lost),
618                sizeof(gHooks[IMPL_CONTEXT_LOST].gl));
619        android_memset32(
620                (uint32_t*)(void*)&gHooks[IMPL_CONTEXT_LOST].egl,
621                (uint32_t)((void*)egl_context_lost),
622                sizeof(gHooks[IMPL_CONTEXT_LOST].egl));
623        android_memset32(
624                (uint32_t*)(void*)&gHooks[IMPL_CONTEXT_LOST].ext,
625                (uint32_t)((void*)ext_context_lost),
626                sizeof(gHooks[IMPL_CONTEXT_LOST].ext));
627
628        gHooks[IMPL_CONTEXT_LOST].egl.eglSwapBuffers =
629                egl_context_lost_swap_buffers;
630
631        gHooks[IMPL_CONTEXT_LOST].egl.eglGetError =
632                egl_context_lost_get_error;
633
634        gHooks[IMPL_CONTEXT_LOST].egl.eglTerminate =
635                gHooks[IMPL_HARDWARE].egl.eglTerminate;
636
637        d->dpys[IMPL_HARDWARE] = cnx->hooks->egl.eglGetDisplay(display);
638        if (d->dpys[IMPL_HARDWARE] == EGL_NO_DISPLAY) {
639            LOGE("h/w accelerated eglGetDisplay() failed (%s)",
640                    egl_strerror(cnx->hooks->egl.eglGetError()));
641            dlclose((void*)cnx->dso);
642            cnx->dso = 0;
643            // in case of failure, we want to make sure we don't try again
644            // as it's expensive.
645            cnx->unavailable = 1;
646        }
647    }
648
649    return dpy;
650}
651
652
653// ----------------------------------------------------------------------------
654}; // namespace android
655// ----------------------------------------------------------------------------
656
657using namespace android;
658
659EGLDisplay eglGetDisplay(NativeDisplayType display)
660{
661    return egl_init_displays(display);
662}
663
664// ----------------------------------------------------------------------------
665// Initialization
666// ----------------------------------------------------------------------------
667
668EGLBoolean eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor)
669{
670    egl_display_t * const dp = get_display(dpy);
671    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
672
673    if (android_atomic_inc(&dp->refs) > 0) {
674        if (major != NULL) *major = VERSION_MAJOR;
675        if (minor != NULL) *minor = VERSION_MINOR;
676        return EGL_TRUE;
677    }
678
679    setGlThreadSpecific(&gHooks[IMPL_NO_CONTEXT]);
680
681    // initialize each EGL and
682    // build our own extension string first, based on the extension we know
683    // and the extension supported by our client implementation
684    dp->extensionsString = strdup(gExtensionString);
685    for (int i=0 ; i<IMPL_NUM_DRIVERS_IMPLEMENTATIONS ; i++) {
686        egl_connection_t* const cnx = &gEGLImpl[i];
687        cnx->major = -1;
688        cnx->minor = -1;
689        if (!cnx->dso)
690            continue;
691
692        if (cnx->hooks->egl.eglInitialize(
693                dp->dpys[i], &cnx->major, &cnx->minor)) {
694
695            //LOGD("initialized %d dpy=%p, ver=%d.%d, cnx=%p",
696            //        i, dp->dpys[i], cnx->major, cnx->minor, cnx);
697
698            // get the query-strings for this display for each implementation
699            dp->queryString[i].vendor =
700                cnx->hooks->egl.eglQueryString(dp->dpys[i], EGL_VENDOR);
701            dp->queryString[i].version =
702                cnx->hooks->egl.eglQueryString(dp->dpys[i], EGL_VERSION);
703            dp->queryString[i].extensions = strdup(
704                    cnx->hooks->egl.eglQueryString(dp->dpys[i], EGL_EXTENSIONS));
705            dp->queryString[i].clientApi =
706                cnx->hooks->egl.eglQueryString(dp->dpys[i], EGL_CLIENT_APIS);
707
708        } else {
709            LOGD("%d: eglInitialize() failed (%s)",
710                    i, egl_strerror(cnx->hooks->egl.eglGetError()));
711        }
712    }
713
714    EGLBoolean res = EGL_FALSE;
715    for (int i=0 ; i<IMPL_NUM_DRIVERS_IMPLEMENTATIONS ; i++) {
716        egl_connection_t* const cnx = &gEGLImpl[i];
717        if (cnx->dso && cnx->major>=0 && cnx->minor>=0) {
718            EGLint n;
719            if (cnx->hooks->egl.eglGetConfigs(dp->dpys[i], 0, 0, &n)) {
720                dp->configs[i] = (EGLConfig*)malloc(sizeof(EGLConfig)*n);
721                if (dp->configs[i]) {
722                    if (cnx->hooks->egl.eglGetConfigs(
723                            dp->dpys[i], dp->configs[i], n, &dp->numConfigs[i]))
724                    {
725                        // sort the configurations so we can do binary searches
726                        qsort(  dp->configs[i],
727                                dp->numConfigs[i],
728                                sizeof(EGLConfig), cmp_configs);
729
730                        dp->numTotalConfigs += n;
731                        res = EGL_TRUE;
732                    }
733                }
734            }
735        }
736    }
737
738    if (res == EGL_TRUE) {
739        if (major != NULL) *major = VERSION_MAJOR;
740        if (minor != NULL) *minor = VERSION_MINOR;
741        return EGL_TRUE;
742    }
743    return setError(EGL_NOT_INITIALIZED, EGL_FALSE);
744}
745
746EGLBoolean eglTerminate(EGLDisplay dpy)
747{
748    egl_display_t* const dp = get_display(dpy);
749    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
750    if (android_atomic_dec(&dp->refs) != 1)
751        return EGL_TRUE;
752
753    EGLBoolean res = EGL_FALSE;
754    for (int i=0 ; i<IMPL_NUM_DRIVERS_IMPLEMENTATIONS ; i++) {
755        egl_connection_t* const cnx = &gEGLImpl[i];
756        if (cnx->dso) {
757            cnx->hooks->egl.eglTerminate(dp->dpys[i]);
758
759            /* REVISIT: it's unclear what to do if eglTerminate() fails,
760             * on one end we shouldn't care, on the other end if it fails
761             * it might not be safe to call dlclose() (there could be some
762             * threads around). */
763
764            free(dp->configs[i]);
765            free((void*)dp->queryString[i].extensions);
766            dp->numConfigs[i] = 0;
767            dp->dpys[i] = EGL_NO_DISPLAY;
768            dlclose((void*)cnx->dso);
769            cnx->dso = 0;
770            res = EGL_TRUE;
771        }
772    }
773    free((void*)dp->extensionsString);
774    dp->extensionsString = 0;
775    dp->numTotalConfigs = 0;
776    clearTLS();
777    return res;
778}
779
780// ----------------------------------------------------------------------------
781// configuration
782// ----------------------------------------------------------------------------
783
784EGLBoolean eglGetConfigs(   EGLDisplay dpy,
785                            EGLConfig *configs,
786                            EGLint config_size, EGLint *num_config)
787{
788    egl_display_t const * const dp = get_display(dpy);
789    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
790
791    GLint numConfigs = dp->numTotalConfigs;
792    if (!configs) {
793        *num_config = numConfigs;
794        return EGL_TRUE;
795    }
796    GLint n = 0;
797    for (int j=0 ; j<IMPL_NUM_DRIVERS_IMPLEMENTATIONS ; j++) {
798        for (int i=0 ; i<dp->numConfigs[j] && config_size ; i++) {
799            *configs++ = MAKE_CONFIG(j, i);
800            config_size--;
801            n++;
802        }
803    }
804
805    *num_config = n;
806    return EGL_TRUE;
807}
808
809EGLBoolean eglChooseConfig( EGLDisplay dpy, const EGLint *attrib_list,
810                            EGLConfig *configs, EGLint config_size,
811                            EGLint *num_config)
812{
813    egl_display_t const * const dp = get_display(dpy);
814    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
815
816    if (num_config==0) {
817        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
818    }
819
820    EGLint n;
821    EGLBoolean res = EGL_FALSE;
822    *num_config = 0;
823
824
825    // It is unfortunate, but we need to remap the EGL_CONFIG_IDs,
826    // to do  this, we have to go through the attrib_list array once
827    // to figure out both its size and if it contains an EGL_CONFIG_ID
828    // key. If so, the full array is copied and patched.
829    // NOTE: we assume that there can be only one occurrence
830    // of EGL_CONFIG_ID.
831
832    EGLint patch_index = -1;
833    GLint attr;
834    size_t size = 0;
835    while ((attr=attrib_list[size])) {
836        if (attr == EGL_CONFIG_ID)
837            patch_index = size;
838        size += 2;
839    }
840    if (patch_index >= 0) {
841        size += 2; // we need copy the sentinel as well
842        EGLint* new_list = (EGLint*)malloc(size*sizeof(EGLint));
843        if (new_list == 0)
844            return setError(EGL_BAD_ALLOC, EGL_FALSE);
845        memcpy(new_list, attrib_list, size*sizeof(EGLint));
846
847        // patch the requested EGL_CONFIG_ID
848        int i, index;
849        EGLint& configId(new_list[patch_index+1]);
850        uniqueIdToConfig(dp, configId, i, index);
851
852        egl_connection_t* const cnx = &gEGLImpl[i];
853        if (cnx->dso) {
854            cnx->hooks->egl.eglGetConfigAttrib(
855                    dp->dpys[i], dp->configs[i][index],
856                    EGL_CONFIG_ID, &configId);
857
858            // and switch to the new list
859            attrib_list = const_cast<const EGLint *>(new_list);
860
861            // At this point, the only configuration that can match is
862            // dp->configs[i][index], however, we don't know if it would be
863            // rejected because of the other attributes, so we do have to call
864            // cnx->hooks->egl.eglChooseConfig() -- but we don't have to loop
865            // through all the EGLimpl[].
866            // We also know we can only get a single config back, and we know
867            // which one.
868
869            res = cnx->hooks->egl.eglChooseConfig(
870                    dp->dpys[i], attrib_list, configs, config_size, &n);
871            if (res && n>0) {
872                // n has to be 0 or 1, by construction, and we already know
873                // which config it will return (since there can be only one).
874                if (configs) {
875                    configs[0] = MAKE_CONFIG(i, index);
876                }
877                *num_config = 1;
878            }
879        }
880
881        free(const_cast<EGLint *>(attrib_list));
882        return res;
883    }
884
885    for (int i=0 ; i<IMPL_NUM_DRIVERS_IMPLEMENTATIONS ; i++) {
886        egl_connection_t* const cnx = &gEGLImpl[i];
887        if (cnx->dso) {
888            if (cnx->hooks->egl.eglChooseConfig(
889                    dp->dpys[i], attrib_list, configs, config_size, &n)) {
890                if (configs) {
891                    // now we need to convert these client EGLConfig to our
892                    // internal EGLConfig format. This is done in O(n log n).
893                    for (int j=0 ; j<n ; j++) {
894                        int index = binarySearch<EGLConfig>(
895                                dp->configs[i], 0, dp->numConfigs[i]-1, configs[j]);
896                        if (index >= 0) {
897                            if (configs) {
898                                configs[j] = MAKE_CONFIG(i, index);
899                            }
900                        } else {
901                            return setError(EGL_BAD_CONFIG, EGL_FALSE);
902                        }
903                    }
904                    configs += n;
905                    config_size -= n;
906                }
907                *num_config += n;
908                res = EGL_TRUE;
909            }
910        }
911    }
912    return res;
913}
914
915EGLBoolean eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config,
916        EGLint attribute, EGLint *value)
917{
918    egl_display_t const* dp = 0;
919    int i=0, index=0;
920    egl_connection_t* cnx = validate_display_config(dpy, config, dp, i, index);
921    if (!cnx) return EGL_FALSE;
922
923    if (attribute == EGL_CONFIG_ID) {
924        // EGL_CONFIG_IDs must be unique, just use the order of the selected
925        // EGLConfig.
926        *value = configToUniqueId(dp, i, index);
927        return EGL_TRUE;
928    }
929    return cnx->hooks->egl.eglGetConfigAttrib(
930            dp->dpys[i], dp->configs[i][index], attribute, value);
931}
932
933// ----------------------------------------------------------------------------
934// surfaces
935// ----------------------------------------------------------------------------
936
937EGLSurface eglCreateWindowSurface(  EGLDisplay dpy, EGLConfig config,
938                                    NativeWindowType window,
939                                    const EGLint *attrib_list)
940{
941    egl_display_t const* dp = 0;
942    int i=0, index=0;
943    egl_connection_t* cnx = validate_display_config(dpy, config, dp, i, index);
944    if (cnx) {
945        EGLSurface surface = cnx->hooks->egl.eglCreateWindowSurface(
946                dp->dpys[i], dp->configs[i][index], window, attrib_list);
947        if (surface != EGL_NO_SURFACE) {
948            egl_surface_t* s = new egl_surface_t(dpy, surface, i, cnx);
949            return s;
950        }
951    }
952    return EGL_NO_SURFACE;
953}
954
955EGLSurface eglCreatePixmapSurface(  EGLDisplay dpy, EGLConfig config,
956                                    NativePixmapType pixmap,
957                                    const EGLint *attrib_list)
958{
959    egl_display_t const* dp = 0;
960    int i=0, index=0;
961    egl_connection_t* cnx = validate_display_config(dpy, config, dp, i, index);
962    if (cnx) {
963        EGLSurface surface = cnx->hooks->egl.eglCreatePixmapSurface(
964                dp->dpys[i], dp->configs[i][index], pixmap, attrib_list);
965        if (surface != EGL_NO_SURFACE) {
966            egl_surface_t* s = new egl_surface_t(dpy, surface, i, cnx);
967            return s;
968        }
969    }
970    return EGL_NO_SURFACE;
971}
972
973EGLSurface eglCreatePbufferSurface( EGLDisplay dpy, EGLConfig config,
974                                    const EGLint *attrib_list)
975{
976    egl_display_t const* dp = 0;
977    int i=0, index=0;
978    egl_connection_t* cnx = validate_display_config(dpy, config, dp, i, index);
979    if (cnx) {
980        EGLSurface surface = cnx->hooks->egl.eglCreatePbufferSurface(
981                dp->dpys[i], dp->configs[i][index], attrib_list);
982        if (surface != EGL_NO_SURFACE) {
983            egl_surface_t* s = new egl_surface_t(dpy, surface, i, cnx);
984            return s;
985        }
986    }
987    return EGL_NO_SURFACE;
988}
989
990EGLBoolean eglDestroySurface(EGLDisplay dpy, EGLSurface surface)
991{
992    if (!validate_display_surface(dpy, surface))
993        return EGL_FALSE;
994    egl_display_t const * const dp = get_display(dpy);
995    egl_surface_t const * const s = get_surface(surface);
996
997    EGLBoolean result = s->cnx->hooks->egl.eglDestroySurface(
998            dp->dpys[s->impl], s->surface);
999
1000    delete s;
1001    return result;
1002}
1003
1004EGLBoolean eglQuerySurface( EGLDisplay dpy, EGLSurface surface,
1005                            EGLint attribute, EGLint *value)
1006{
1007    if (!validate_display_surface(dpy, surface))
1008        return EGL_FALSE;
1009    egl_display_t const * const dp = get_display(dpy);
1010    egl_surface_t const * const s = get_surface(surface);
1011
1012    return s->cnx->hooks->egl.eglQuerySurface(
1013            dp->dpys[s->impl], s->surface, attribute, value);
1014}
1015
1016// ----------------------------------------------------------------------------
1017// contextes
1018// ----------------------------------------------------------------------------
1019
1020EGLContext eglCreateContext(EGLDisplay dpy, EGLConfig config,
1021                            EGLContext share_list, const EGLint *attrib_list)
1022{
1023    egl_display_t const* dp = 0;
1024    int i=0, index=0;
1025    egl_connection_t* cnx = validate_display_config(dpy, config, dp, i, index);
1026    if (cnx) {
1027        EGLContext context = cnx->hooks->egl.eglCreateContext(
1028                dp->dpys[i], dp->configs[i][index], share_list, attrib_list);
1029        if (context != EGL_NO_CONTEXT) {
1030            egl_context_t* c = new egl_context_t(dpy, context, i, cnx);
1031            return c;
1032        }
1033    }
1034    return EGL_NO_CONTEXT;
1035}
1036
1037EGLBoolean eglDestroyContext(EGLDisplay dpy, EGLContext ctx)
1038{
1039    if (!validate_display_context(dpy, ctx))
1040        return EGL_FALSE;
1041    egl_display_t const * const dp = get_display(dpy);
1042    egl_context_t * const c = get_context(ctx);
1043    EGLBoolean result = c->cnx->hooks->egl.eglDestroyContext(
1044            dp->dpys[c->impl], c->context);
1045    delete c;
1046    return result;
1047}
1048
1049EGLBoolean eglMakeCurrent(  EGLDisplay dpy, EGLSurface draw,
1050                            EGLSurface read, EGLContext ctx)
1051{
1052    egl_display_t const * const dp = get_display(dpy);
1053    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1054
1055    if (read == EGL_NO_SURFACE && draw  == EGL_NO_SURFACE &&
1056            ctx == EGL_NO_CONTEXT)
1057    {
1058        EGLBoolean result = EGL_TRUE;
1059        ctx = getContext();
1060        if (ctx) {
1061            egl_context_t * const c = get_context(ctx);
1062            result = c->cnx->hooks->egl.eglMakeCurrent(dp->dpys[c->impl], 0, 0, 0);
1063            if (result == EGL_TRUE) {
1064                setGlThreadSpecific(&gHooks[IMPL_NO_CONTEXT]);
1065                setContext(EGL_NO_CONTEXT);
1066            }
1067        }
1068        return result;
1069    }
1070
1071    if (!validate_display_context(dpy, ctx))
1072        return EGL_FALSE;
1073
1074    egl_context_t * const c = get_context(ctx);
1075    if (draw != EGL_NO_SURFACE) {
1076        egl_surface_t const * d = get_surface(draw);
1077        if (!d) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1078        if (d->impl != c->impl)
1079            return setError(EGL_BAD_MATCH, EGL_FALSE);
1080        draw = d->surface;
1081    }
1082    if (read != EGL_NO_SURFACE) {
1083        egl_surface_t const * r = get_surface(read);
1084        if (!r) return setError(EGL_BAD_SURFACE, EGL_FALSE);
1085        if (r->impl != c->impl)
1086            return setError(EGL_BAD_MATCH, EGL_FALSE);
1087        read = r->surface;
1088    }
1089    EGLBoolean result = c->cnx->hooks->egl.eglMakeCurrent(
1090            dp->dpys[c->impl], draw, read, c->context);
1091
1092    if (result == EGL_TRUE) {
1093        setGlThreadSpecific(c->cnx->hooks);
1094        setContext(ctx);
1095        c->read = read;
1096        c->draw = draw;
1097    }
1098    return result;
1099}
1100
1101
1102EGLBoolean eglQueryContext( EGLDisplay dpy, EGLContext ctx,
1103                            EGLint attribute, EGLint *value)
1104{
1105    if (!validate_display_context(dpy, ctx))
1106        return EGL_FALSE;
1107
1108    egl_display_t const * const dp = get_display(dpy);
1109    egl_context_t * const c = get_context(ctx);
1110
1111    return c->cnx->hooks->egl.eglQueryContext(
1112            dp->dpys[c->impl], c->context, attribute, value);
1113}
1114
1115EGLContext eglGetCurrentContext(void)
1116{
1117    EGLContext ctx = getContext();
1118    return ctx;
1119}
1120
1121EGLSurface eglGetCurrentSurface(EGLint readdraw)
1122{
1123    EGLContext ctx = getContext();
1124    if (ctx) {
1125        egl_context_t const * const c = get_context(ctx);
1126        if (!c) return setError(EGL_BAD_CONTEXT, EGL_NO_SURFACE);
1127        switch (readdraw) {
1128            case EGL_READ: return c->read;
1129            case EGL_DRAW: return c->draw;
1130            default: return setError(EGL_BAD_PARAMETER, EGL_NO_SURFACE);
1131        }
1132    }
1133    return EGL_NO_SURFACE;
1134}
1135
1136EGLDisplay eglGetCurrentDisplay(void)
1137{
1138    EGLContext ctx = getContext();
1139    if (ctx) {
1140        egl_context_t const * const c = get_context(ctx);
1141        if (!c) return setError(EGL_BAD_CONTEXT, EGL_NO_SURFACE);
1142        return c->dpy;
1143    }
1144    return EGL_NO_DISPLAY;
1145}
1146
1147EGLBoolean eglWaitGL(void)
1148{
1149    EGLBoolean res = EGL_TRUE;
1150    EGLContext ctx = getContext();
1151    if (ctx) {
1152        egl_context_t const * const c = get_context(ctx);
1153        if (!c) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1154        if (uint32_t(c->impl)>=2)
1155            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1156        egl_connection_t* const cnx = &gEGLImpl[c->impl];
1157        if (!cnx->dso)
1158            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1159        res = cnx->hooks->egl.eglWaitGL();
1160    }
1161    return res;
1162}
1163
1164EGLBoolean eglWaitNative(EGLint engine)
1165{
1166    EGLBoolean res = EGL_TRUE;
1167    EGLContext ctx = getContext();
1168    if (ctx) {
1169        egl_context_t const * const c = get_context(ctx);
1170        if (!c) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1171        if (uint32_t(c->impl)>=2)
1172            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1173        egl_connection_t* const cnx = &gEGLImpl[c->impl];
1174        if (!cnx->dso)
1175            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1176        res = cnx->hooks->egl.eglWaitNative(engine);
1177    }
1178    return res;
1179}
1180
1181EGLint eglGetError(void)
1182{
1183    EGLint result = EGL_SUCCESS;
1184    for (int i=0 ; i<IMPL_NUM_DRIVERS_IMPLEMENTATIONS ; i++) {
1185        EGLint err = EGL_SUCCESS;
1186        egl_connection_t* const cnx = &gEGLImpl[i];
1187        if (cnx->dso)
1188            err = cnx->hooks->egl.eglGetError();
1189        if (err!=EGL_SUCCESS && result==EGL_SUCCESS)
1190            result = err;
1191    }
1192    if (result == EGL_SUCCESS)
1193        result = getError();
1194    return result;
1195}
1196
1197__eglMustCastToProperFunctionPointerType eglGetProcAddress(const char *procname)
1198{
1199    // eglGetProcAddress() could be the very first function called
1200    // in which case we must make sure we've initialized ourselves, this
1201    // happens the first time egl_get_display() is called.
1202
1203    if (egl_init_displays(EGL_DEFAULT_DISPLAY) == EGL_NO_DISPLAY)
1204        return NULL;
1205
1206    __eglMustCastToProperFunctionPointerType addr;
1207    addr = findProcAddress(procname, gExtentionMap, NELEM(gExtentionMap));
1208    if (addr) return addr;
1209
1210    return NULL; // TODO: finish implementation below
1211
1212    addr = findProcAddress(procname, gGLExtentionMap, NELEM(gGLExtentionMap));
1213    if (addr) return addr;
1214
1215    addr = 0;
1216    int slot = -1;
1217    for (int i=0 ; i<IMPL_NUM_DRIVERS_IMPLEMENTATIONS ; i++) {
1218        egl_connection_t* const cnx = &gEGLImpl[i];
1219        if (cnx->dso) {
1220            if (cnx->hooks->egl.eglGetProcAddress) {
1221                addr = cnx->hooks->egl.eglGetProcAddress(procname);
1222                if (addr) {
1223                    if (slot == -1) {
1224                        slot = 0; // XXX: find free slot
1225                        if (slot == -1) {
1226                            addr = 0;
1227                            break;
1228                        }
1229                    }
1230                    cnx->hooks->ext.extensions[slot] = addr;
1231                }
1232            }
1233        }
1234    }
1235
1236    if (slot >= 0) {
1237        addr = 0; // XXX: address of stub 'slot'
1238        gGLExtentionMap[slot].name = strdup(procname);
1239        gGLExtentionMap[slot].address = addr;
1240    }
1241
1242    return addr;
1243
1244
1245    /*
1246     *  TODO: For OpenGL ES extensions, we must generate a stub
1247     *  that looks like
1248     *      mov     r12, #0xFFFF0FFF
1249     *      ldr     r12, [r12, #-15]
1250     *      ldr     r12, [r12, #TLS_SLOT_OPENGL_API*4]
1251     *      mov     r12, [r12, #api_offset]
1252     *      ldrne   pc, r12
1253     *      mov     pc, #unsupported_extension
1254     *
1255     *  and write the address of the extension in *all*
1256     *  gl_hooks_t::gl_ext_t at offset "api_offset" from gl_hooks_t
1257     *
1258     */
1259}
1260
1261EGLBoolean eglSwapBuffers(EGLDisplay dpy, EGLSurface draw)
1262{
1263    if (!validate_display_surface(dpy, draw))
1264        return EGL_FALSE;
1265    egl_display_t const * const dp = get_display(dpy);
1266    egl_surface_t const * const s = get_surface(draw);
1267    return s->cnx->hooks->egl.eglSwapBuffers(dp->dpys[s->impl], s->surface);
1268}
1269
1270EGLBoolean eglCopyBuffers(  EGLDisplay dpy, EGLSurface surface,
1271                            NativePixmapType target)
1272{
1273    if (!validate_display_surface(dpy, surface))
1274        return EGL_FALSE;
1275    egl_display_t const * const dp = get_display(dpy);
1276    egl_surface_t const * const s = get_surface(surface);
1277    return s->cnx->hooks->egl.eglCopyBuffers(
1278            dp->dpys[s->impl], s->surface, target);
1279}
1280
1281const char* eglQueryString(EGLDisplay dpy, EGLint name)
1282{
1283    egl_display_t const * const dp = get_display(dpy);
1284    switch (name) {
1285        case EGL_VENDOR:
1286            return gVendorString;
1287        case EGL_VERSION:
1288            return gVersionString;
1289        case EGL_EXTENSIONS:
1290            return gExtensionString;
1291        case EGL_CLIENT_APIS:
1292            return gClientApiString;
1293    }
1294    return setError(EGL_BAD_PARAMETER, (const char *)0);
1295}
1296
1297
1298// ----------------------------------------------------------------------------
1299// EGL 1.1
1300// ----------------------------------------------------------------------------
1301
1302EGLBoolean eglSurfaceAttrib(
1303        EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value)
1304{
1305    if (!validate_display_surface(dpy, surface))
1306        return EGL_FALSE;
1307    egl_display_t const * const dp = get_display(dpy);
1308    egl_surface_t const * const s = get_surface(surface);
1309    if (s->cnx->hooks->egl.eglSurfaceAttrib) {
1310        return s->cnx->hooks->egl.eglSurfaceAttrib(
1311                dp->dpys[s->impl], s->surface, attribute, value);
1312    }
1313    return setError(EGL_BAD_SURFACE, EGL_FALSE);
1314}
1315
1316EGLBoolean eglBindTexImage(
1317        EGLDisplay dpy, EGLSurface surface, EGLint buffer)
1318{
1319    if (!validate_display_surface(dpy, surface))
1320        return EGL_FALSE;
1321    egl_display_t const * const dp = get_display(dpy);
1322    egl_surface_t const * const s = get_surface(surface);
1323    if (s->cnx->hooks->egl.eglBindTexImage) {
1324        return s->cnx->hooks->egl.eglBindTexImage(
1325                dp->dpys[s->impl], s->surface, buffer);
1326    }
1327    return setError(EGL_BAD_SURFACE, EGL_FALSE);
1328}
1329
1330EGLBoolean eglReleaseTexImage(
1331        EGLDisplay dpy, EGLSurface surface, EGLint buffer)
1332{
1333    if (!validate_display_surface(dpy, surface))
1334        return EGL_FALSE;
1335    egl_display_t const * const dp = get_display(dpy);
1336    egl_surface_t const * const s = get_surface(surface);
1337    if (s->cnx->hooks->egl.eglReleaseTexImage) {
1338        return s->cnx->hooks->egl.eglReleaseTexImage(
1339                dp->dpys[s->impl], s->surface, buffer);
1340    }
1341    return setError(EGL_BAD_SURFACE, EGL_FALSE);
1342}
1343
1344EGLBoolean eglSwapInterval(EGLDisplay dpy, EGLint interval)
1345{
1346    egl_display_t * const dp = get_display(dpy);
1347    if (!dp) return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1348
1349    EGLBoolean res = EGL_TRUE;
1350    for (int i=0 ; i<IMPL_NUM_DRIVERS_IMPLEMENTATIONS ; i++) {
1351        egl_connection_t* const cnx = &gEGLImpl[i];
1352        if (cnx->dso) {
1353            if (cnx->hooks->egl.eglSwapInterval) {
1354                if (cnx->hooks->egl.eglSwapInterval(dp->dpys[i], interval) == EGL_FALSE) {
1355                    res = EGL_FALSE;
1356                }
1357            }
1358        }
1359    }
1360    return res;
1361}
1362
1363
1364// ----------------------------------------------------------------------------
1365// EGL 1.2
1366// ----------------------------------------------------------------------------
1367
1368EGLBoolean eglWaitClient(void)
1369{
1370    EGLBoolean res = EGL_TRUE;
1371    EGLContext ctx = getContext();
1372    if (ctx) {
1373        egl_context_t const * const c = get_context(ctx);
1374        if (!c) return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1375        if (uint32_t(c->impl)>=2)
1376            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1377        egl_connection_t* const cnx = &gEGLImpl[c->impl];
1378        if (!cnx->dso)
1379            return setError(EGL_BAD_CONTEXT, EGL_FALSE);
1380        if (cnx->hooks->egl.eglWaitClient) {
1381            res = cnx->hooks->egl.eglWaitClient();
1382        } else {
1383            res = cnx->hooks->egl.eglWaitGL();
1384        }
1385    }
1386    return res;
1387}
1388
1389EGLBoolean eglBindAPI(EGLenum api)
1390{
1391    // bind this API on all EGLs
1392    EGLBoolean res = EGL_TRUE;
1393    for (int i=0 ; i<IMPL_NUM_DRIVERS_IMPLEMENTATIONS ; i++) {
1394        egl_connection_t* const cnx = &gEGLImpl[i];
1395        if (cnx->dso) {
1396            if (cnx->hooks->egl.eglBindAPI) {
1397                if (cnx->hooks->egl.eglBindAPI(api) == EGL_FALSE) {
1398                    res = EGL_FALSE;
1399                }
1400            }
1401        }
1402    }
1403    return res;
1404}
1405
1406EGLenum eglQueryAPI(void)
1407{
1408    for (int i=0 ; i<IMPL_NUM_DRIVERS_IMPLEMENTATIONS ; i++) {
1409        egl_connection_t* const cnx = &gEGLImpl[i];
1410        if (cnx->dso) {
1411            if (cnx->hooks->egl.eglQueryAPI) {
1412                // the first one we find is okay, because they all
1413                // should be the same
1414                return cnx->hooks->egl.eglQueryAPI();
1415            }
1416        }
1417    }
1418    // or, it can only be OpenGL ES
1419    return EGL_OPENGL_ES_API;
1420}
1421
1422EGLBoolean eglReleaseThread(void)
1423{
1424    for (int i=0 ; i<IMPL_NUM_DRIVERS_IMPLEMENTATIONS ; i++) {
1425        egl_connection_t* const cnx = &gEGLImpl[i];
1426        if (cnx->dso) {
1427            if (cnx->hooks->egl.eglReleaseThread) {
1428                cnx->hooks->egl.eglReleaseThread();
1429            }
1430        }
1431    }
1432    clearTLS();
1433    return EGL_TRUE;
1434}
1435
1436EGLSurface eglCreatePbufferFromClientBuffer(
1437          EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer,
1438          EGLConfig config, const EGLint *attrib_list)
1439{
1440    egl_display_t const* dp = 0;
1441    int i=0, index=0;
1442    egl_connection_t* cnx = validate_display_config(dpy, config, dp, i, index);
1443    if (!cnx) return EGL_FALSE;
1444    if (cnx->hooks->egl.eglCreatePbufferFromClientBuffer) {
1445        return cnx->hooks->egl.eglCreatePbufferFromClientBuffer(
1446                dp->dpys[i], buftype, buffer, dp->configs[i][index], attrib_list);
1447    }
1448    return setError(EGL_BAD_CONFIG, EGL_NO_SURFACE);
1449}
1450
1451// ----------------------------------------------------------------------------
1452// EGL_EGLEXT_VERSION 3
1453// ----------------------------------------------------------------------------
1454
1455EGLBoolean eglLockSurfaceKHR(EGLDisplay dpy, EGLSurface surface,
1456        const EGLint *attrib_list)
1457{
1458    EGLBoolean result = EGL_FALSE;
1459    if (!validate_display_surface(dpy, surface))
1460        return result;
1461
1462    egl_display_t const * const dp = get_display(dpy);
1463    egl_surface_t const * const s = get_surface(surface);
1464
1465    if (s->cnx->hooks->egl.eglLockSurfaceKHR) {
1466        result = s->cnx->hooks->egl.eglLockSurfaceKHR(
1467                dp->dpys[s->impl], s->surface, attrib_list);
1468    }
1469    return result;
1470}
1471
1472EGLBoolean eglUnlockSurfaceKHR(EGLDisplay dpy, EGLSurface surface)
1473{
1474    EGLBoolean result = EGL_FALSE;
1475    if (!validate_display_surface(dpy, surface))
1476        return result;
1477
1478    egl_display_t const * const dp = get_display(dpy);
1479    egl_surface_t const * const s = get_surface(surface);
1480
1481    if (s->cnx->hooks->egl.eglUnlockSurfaceKHR) {
1482        result = s->cnx->hooks->egl.eglUnlockSurfaceKHR(
1483                dp->dpys[s->impl], s->surface);
1484    }
1485    return result;
1486}
1487
1488EGLImageKHR eglCreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target,
1489        EGLClientBuffer buffer, const EGLint *attrib_list)
1490{
1491    if (ctx != EGL_NO_CONTEXT) {
1492        if (!validate_display_context(dpy, ctx))
1493            return EGL_NO_IMAGE_KHR;
1494        egl_display_t const * const dp = get_display(dpy);
1495        egl_context_t * const c = get_context(ctx);
1496        // since we have an EGLContext, we know which implementation to use
1497        EGLImageKHR image = c->cnx->hooks->egl.eglCreateImageKHR(
1498                dp->dpys[c->impl], c->context, target, buffer, attrib_list);
1499        if (image == EGL_NO_IMAGE_KHR)
1500            return image;
1501
1502        egl_image_t* result = new egl_image_t(dpy, ctx);
1503        result->images[c->impl] = image;
1504        return (EGLImageKHR)result;
1505    } else {
1506        // EGL_NO_CONTEXT is a valid parameter
1507        egl_display_t const * const dp = get_display(dpy);
1508        if (dp == 0) {
1509            return setError(EGL_BAD_DISPLAY, EGL_NO_IMAGE_KHR);
1510        }
1511        // since we don't have a way to know which implementation to call,
1512        // we're calling all of them
1513
1514        EGLImageKHR implImages[IMPL_NUM_DRIVERS_IMPLEMENTATIONS];
1515        bool success = false;
1516        for (int i=0 ; i<IMPL_NUM_DRIVERS_IMPLEMENTATIONS ; i++) {
1517            egl_connection_t* const cnx = &gEGLImpl[i];
1518            implImages[i] = EGL_NO_IMAGE_KHR;
1519            if (cnx->dso) {
1520                if (cnx->hooks->egl.eglCreateImageKHR) {
1521                    implImages[i] = cnx->hooks->egl.eglCreateImageKHR(
1522                            dp->dpys[i], ctx, target, buffer, attrib_list);
1523                    if (implImages[i] != EGL_NO_IMAGE_KHR) {
1524                        success = true;
1525                    }
1526                }
1527            }
1528        }
1529        if (!success)
1530            return EGL_NO_IMAGE_KHR;
1531
1532        egl_image_t* result = new egl_image_t(dpy, ctx);
1533        memcpy(result->images, implImages, sizeof(implImages));
1534        return (EGLImageKHR)result;
1535    }
1536}
1537
1538EGLBoolean eglDestroyImageKHR(EGLDisplay dpy, EGLImageKHR img)
1539{
1540     egl_display_t const * const dp = get_display(dpy);
1541     if (dp == 0) {
1542         return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1543     }
1544
1545     egl_image_t* image = get_image(img);
1546     if (!image->isValid()) {
1547         return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1548     }
1549
1550     bool success = false;
1551     for (int i=0 ; i<IMPL_NUM_DRIVERS_IMPLEMENTATIONS ; i++) {
1552         egl_connection_t* const cnx = &gEGLImpl[i];
1553         if (image->images[i] != EGL_NO_IMAGE_KHR) {
1554             if (cnx->dso) {
1555                 if (cnx->hooks->egl.eglCreateImageKHR) {
1556                     if (cnx->hooks->egl.eglDestroyImageKHR(
1557                             dp->dpys[i], image->images[i])) {
1558                         success = true;
1559                     }
1560                 }
1561             }
1562         }
1563     }
1564     if (!success)
1565         return EGL_FALSE;
1566
1567     delete image;
1568
1569     return EGL_FALSE;
1570}
1571