egl_display.cpp revision c2e41222bf02a6579763974f82d65875cfa43481
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#define __STDC_LIMIT_MACROS 1
18
19#include <string.h>
20
21#include "../egl_impl.h"
22
23#include "egl_cache.h"
24#include "egl_display.h"
25#include "egl_object.h"
26#include "egl_tls.h"
27#include "Loader.h"
28#include <cutils/properties.h>
29
30// ----------------------------------------------------------------------------
31namespace android {
32// ----------------------------------------------------------------------------
33
34static char const * const sVendorString     = "Android";
35static char const * const sVersionString    = "1.4 Android META-EGL";
36static char const * const sClientApiString  = "OpenGL_ES";
37
38extern char const * const gBuiltinExtensionString;
39extern char const * const gExtensionString;
40
41extern void initEglTraceLevel();
42extern void initEglDebugLevel();
43extern void setGLHooksThreadSpecific(gl_hooks_t const *value);
44
45// ----------------------------------------------------------------------------
46
47static bool findExtension(const char* exts, const char* name, size_t nameLen) {
48    if (exts) {
49        const char* match = strstr(exts, name);
50        if (match && (match[nameLen] == '\0' || match[nameLen] == ' ')) {
51            return true;
52        }
53    }
54    return false;
55}
56
57egl_display_t egl_display_t::sDisplay[NUM_DISPLAYS];
58
59egl_display_t::egl_display_t() :
60    magic('_dpy'), finishOnSwap(false), traceGpuCompletion(false), refs(0) {
61}
62
63egl_display_t::~egl_display_t() {
64    magic = 0;
65    egl_cache_t::get()->terminate();
66}
67
68egl_display_t* egl_display_t::get(EGLDisplay dpy) {
69    uintptr_t index = uintptr_t(dpy)-1U;
70    return (index >= NUM_DISPLAYS) ? NULL : &sDisplay[index];
71}
72
73void egl_display_t::addObject(egl_object_t* object) {
74    Mutex::Autolock _l(lock);
75    objects.add(object);
76}
77
78void egl_display_t::removeObject(egl_object_t* object) {
79    Mutex::Autolock _l(lock);
80    objects.remove(object);
81}
82
83bool egl_display_t::getObject(egl_object_t* object) const {
84    Mutex::Autolock _l(lock);
85    if (objects.indexOf(object) >= 0) {
86        if (object->getDisplay() == this) {
87            object->incRef();
88            return true;
89        }
90    }
91    return false;
92}
93
94EGLDisplay egl_display_t::getFromNativeDisplay(EGLNativeDisplayType disp) {
95    if (uintptr_t(disp) >= NUM_DISPLAYS)
96        return NULL;
97
98    return sDisplay[uintptr_t(disp)].getDisplay(disp);
99}
100
101EGLDisplay egl_display_t::getDisplay(EGLNativeDisplayType display) {
102
103    Mutex::Autolock _l(lock);
104
105    // get our driver loader
106    Loader& loader(Loader::getInstance());
107
108    egl_connection_t* const cnx = &gEGLImpl;
109    if (cnx->dso && disp.dpy == EGL_NO_DISPLAY) {
110        EGLDisplay dpy = cnx->egl.eglGetDisplay(display);
111        disp.dpy = dpy;
112        if (dpy == EGL_NO_DISPLAY) {
113            loader.close(cnx->dso);
114            cnx->dso = NULL;
115        }
116    }
117
118    return EGLDisplay(uintptr_t(display) + 1U);
119}
120
121EGLBoolean egl_display_t::initialize(EGLint *major, EGLint *minor) {
122
123    Mutex::Autolock _l(lock);
124
125    if (refs > 0) {
126        if (major != NULL)
127            *major = VERSION_MAJOR;
128        if (minor != NULL)
129            *minor = VERSION_MINOR;
130        refs++;
131        return EGL_TRUE;
132    }
133
134#if EGL_TRACE
135
136    // Called both at early_init time and at this time. (Early_init is pre-zygote, so
137    // the information from that call may be stale.)
138    initEglTraceLevel();
139    initEglDebugLevel();
140
141#endif
142
143    setGLHooksThreadSpecific(&gHooksNoContext);
144
145    // initialize each EGL and
146    // build our own extension string first, based on the extension we know
147    // and the extension supported by our client implementation
148
149    egl_connection_t* const cnx = &gEGLImpl;
150    cnx->major = -1;
151    cnx->minor = -1;
152    if (cnx->dso) {
153
154#if defined(ADRENO130)
155#warning "Adreno-130 eglInitialize() workaround"
156        /*
157         * The ADRENO 130 driver returns a different EGLDisplay each time
158         * eglGetDisplay() is called, but also makes the EGLDisplay invalid
159         * after eglTerminate() has been called, so that eglInitialize()
160         * cannot be called again. Therefore, we need to make sure to call
161         * eglGetDisplay() before calling eglInitialize();
162         */
163        if (i == IMPL_HARDWARE) {
164            disp[i].dpy = cnx->egl.eglGetDisplay(EGL_DEFAULT_DISPLAY);
165        }
166#endif
167
168        EGLDisplay idpy = disp.dpy;
169        if (cnx->egl.eglInitialize(idpy, &cnx->major, &cnx->minor)) {
170            //ALOGD("initialized dpy=%p, ver=%d.%d, cnx=%p",
171            //        idpy, cnx->major, cnx->minor, cnx);
172
173            // display is now initialized
174            disp.state = egl_display_t::INITIALIZED;
175
176            // get the query-strings for this display for each implementation
177            disp.queryString.vendor = cnx->egl.eglQueryString(idpy,
178                    EGL_VENDOR);
179            disp.queryString.version = cnx->egl.eglQueryString(idpy,
180                    EGL_VERSION);
181            disp.queryString.extensions = cnx->egl.eglQueryString(idpy,
182                    EGL_EXTENSIONS);
183            disp.queryString.clientApi = cnx->egl.eglQueryString(idpy,
184                    EGL_CLIENT_APIS);
185
186        } else {
187            ALOGW("eglInitialize(%p) failed (%s)", idpy,
188                    egl_tls_t::egl_strerror(cnx->egl.eglGetError()));
189        }
190    }
191
192    // the query strings are per-display
193    mVendorString.setTo(sVendorString);
194    mVersionString.setTo(sVersionString);
195    mClientApiString.setTo(sClientApiString);
196
197    mExtensionString.setTo(gBuiltinExtensionString);
198    char const* start = gExtensionString;
199    char const* end;
200    do {
201        // find the space separating this extension for the next one
202        end = strchr(start, ' ');
203        if (end) {
204            // length of the extension string
205            const size_t len = end - start;
206            if (len) {
207                // NOTE: we could avoid the copy if we had strnstr.
208                const String8 ext(start, len);
209                if (findExtension(disp.queryString.extensions, ext.string(),
210                        len)) {
211                    mExtensionString.append(start, len+1);
212                }
213            }
214            // process the next extension string, and skip the space.
215            start = end + 1;
216        }
217    } while (end);
218
219    egl_cache_t::get()->initialize(this);
220
221    char value[PROPERTY_VALUE_MAX];
222    property_get("debug.egl.finish", value, "0");
223    if (atoi(value)) {
224        finishOnSwap = true;
225    }
226
227    property_get("debug.egl.traceGpuCompletion", value, "0");
228    if (atoi(value)) {
229        traceGpuCompletion = true;
230    }
231
232    refs++;
233    if (major != NULL)
234        *major = VERSION_MAJOR;
235    if (minor != NULL)
236        *minor = VERSION_MINOR;
237
238    mHibernation.setDisplayValid(true);
239
240    return EGL_TRUE;
241}
242
243EGLBoolean egl_display_t::terminate() {
244
245    Mutex::Autolock _l(lock);
246
247    if (refs == 0) {
248        /*
249         * From the EGL spec (3.2):
250         * "Termination of a display that has already been terminated,
251         *  (...), is allowed, but the only effect of such a call is
252         *  to return EGL_TRUE (...)
253         */
254        return EGL_TRUE;
255    }
256
257    // this is specific to Android, display termination is ref-counted.
258    if (refs > 1) {
259        refs--;
260        return EGL_TRUE;
261    }
262
263    EGLBoolean res = EGL_FALSE;
264    egl_connection_t* const cnx = &gEGLImpl;
265    if (cnx->dso && disp.state == egl_display_t::INITIALIZED) {
266        if (cnx->egl.eglTerminate(disp.dpy) == EGL_FALSE) {
267            ALOGW("eglTerminate(%p) failed (%s)", disp.dpy,
268                    egl_tls_t::egl_strerror(cnx->egl.eglGetError()));
269        }
270        // REVISIT: it's unclear what to do if eglTerminate() fails
271        disp.state = egl_display_t::TERMINATED;
272        res = EGL_TRUE;
273    }
274
275    mHibernation.setDisplayValid(false);
276
277    // Reset the extension string since it will be regenerated if we get
278    // reinitialized.
279    mExtensionString.setTo("");
280
281    // Mark all objects remaining in the list as terminated, unless
282    // there are no reference to them, it which case, we're free to
283    // delete them.
284    size_t count = objects.size();
285    ALOGW_IF(count, "eglTerminate() called w/ %d objects remaining", count);
286    for (size_t i=0 ; i<count ; i++) {
287        egl_object_t* o = objects.itemAt(i);
288        o->destroy();
289    }
290
291    // this marks all object handles are "terminated"
292    objects.clear();
293
294    refs--;
295    return res;
296}
297
298void egl_display_t::loseCurrent(egl_context_t * cur_c)
299{
300    if (cur_c) {
301        egl_display_t* display = cur_c->getDisplay();
302        if (display) {
303            display->loseCurrentImpl(cur_c);
304        }
305    }
306}
307
308void egl_display_t::loseCurrentImpl(egl_context_t * cur_c)
309{
310    // by construction, these are either 0 or valid (possibly terminated)
311    // it should be impossible for these to be invalid
312    ContextRef _cur_c(cur_c);
313    SurfaceRef _cur_r(cur_c ? get_surface(cur_c->read) : NULL);
314    SurfaceRef _cur_d(cur_c ? get_surface(cur_c->draw) : NULL);
315
316    { // scope for the lock
317        Mutex::Autolock _l(lock);
318        cur_c->onLooseCurrent();
319
320    }
321
322    // This cannot be called with the lock held because it might end-up
323    // calling back into EGL (in particular when a surface is destroyed
324    // it calls ANativeWindow::disconnect
325    _cur_c.release();
326    _cur_r.release();
327    _cur_d.release();
328}
329
330EGLBoolean egl_display_t::makeCurrent(egl_context_t* c, egl_context_t* cur_c,
331        EGLSurface draw, EGLSurface read, EGLContext ctx,
332        EGLSurface impl_draw, EGLSurface impl_read, EGLContext impl_ctx)
333{
334    EGLBoolean result;
335
336    // by construction, these are either 0 or valid (possibly terminated)
337    // it should be impossible for these to be invalid
338    ContextRef _cur_c(cur_c);
339    SurfaceRef _cur_r(cur_c ? get_surface(cur_c->read) : NULL);
340    SurfaceRef _cur_d(cur_c ? get_surface(cur_c->draw) : NULL);
341
342    { // scope for the lock
343        Mutex::Autolock _l(lock);
344        if (c) {
345            result = c->cnx->egl.eglMakeCurrent(
346                    disp.dpy, impl_draw, impl_read, impl_ctx);
347            if (result == EGL_TRUE) {
348                c->onMakeCurrent(draw, read);
349                if (!cur_c) {
350                    mHibernation.incWakeCount(HibernationMachine::STRONG);
351                }
352            }
353        } else {
354            result = cur_c->cnx->egl.eglMakeCurrent(
355                    disp.dpy, impl_draw, impl_read, impl_ctx);
356            if (result == EGL_TRUE) {
357                cur_c->onLooseCurrent();
358                mHibernation.decWakeCount(HibernationMachine::STRONG);
359            }
360        }
361    }
362
363    if (result == EGL_TRUE) {
364        // This cannot be called with the lock held because it might end-up
365        // calling back into EGL (in particular when a surface is destroyed
366        // it calls ANativeWindow::disconnect
367        _cur_c.release();
368        _cur_r.release();
369        _cur_d.release();
370    }
371
372    return result;
373}
374
375bool egl_display_t::haveExtension(const char* name, size_t nameLen) const {
376    if (!nameLen) {
377        nameLen = strlen(name);
378    }
379    return findExtension(mExtensionString.string(), name, nameLen);
380}
381
382// ----------------------------------------------------------------------------
383
384bool egl_display_t::HibernationMachine::incWakeCount(WakeRefStrength strength) {
385    Mutex::Autolock _l(mLock);
386    ALOGE_IF(mWakeCount < 0 || mWakeCount == INT32_MAX,
387             "Invalid WakeCount (%d) on enter\n", mWakeCount);
388
389    mWakeCount++;
390    if (strength == STRONG)
391        mAttemptHibernation = false;
392
393    if (CC_UNLIKELY(mHibernating)) {
394        ALOGV("Awakening\n");
395        egl_connection_t* const cnx = &gEGLImpl;
396
397        // These conditions should be guaranteed before entering hibernation;
398        // we don't want to get into a state where we can't wake up.
399        ALOGD_IF(!mDpyValid || !cnx->egl.eglAwakenProcessIMG,
400                 "Invalid hibernation state, unable to awaken\n");
401
402        if (!cnx->egl.eglAwakenProcessIMG()) {
403            ALOGE("Failed to awaken EGL implementation\n");
404            return false;
405        }
406        mHibernating = false;
407    }
408    return true;
409}
410
411void egl_display_t::HibernationMachine::decWakeCount(WakeRefStrength strength) {
412    Mutex::Autolock _l(mLock);
413    ALOGE_IF(mWakeCount <= 0, "Invalid WakeCount (%d) on leave\n", mWakeCount);
414
415    mWakeCount--;
416    if (strength == STRONG)
417        mAttemptHibernation = true;
418
419    if (mWakeCount == 0 && CC_UNLIKELY(mAttemptHibernation)) {
420        egl_connection_t* const cnx = &gEGLImpl;
421        mAttemptHibernation = false;
422        if (mAllowHibernation && mDpyValid &&
423                cnx->egl.eglHibernateProcessIMG &&
424                cnx->egl.eglAwakenProcessIMG) {
425            ALOGV("Hibernating\n");
426            if (!cnx->egl.eglHibernateProcessIMG()) {
427                ALOGE("Failed to hibernate EGL implementation\n");
428                return;
429            }
430            mHibernating = true;
431        }
432    }
433}
434
435void egl_display_t::HibernationMachine::setDisplayValid(bool valid) {
436    Mutex::Autolock _l(mLock);
437    mDpyValid = valid;
438}
439
440// ----------------------------------------------------------------------------
441}; // namespace android
442// ----------------------------------------------------------------------------
443