CanvasContext.cpp revision cdfeef6624613ca06fe8a7edfb92608afb0499ee
1/*
2 * Copyright (C) 2014 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 LOG_TAG "CanvasContext"
18
19#include "CanvasContext.h"
20
21#include <cutils/properties.h>
22#include <private/hwui/DrawGlInfo.h>
23#include <strings.h>
24
25#include "RenderThread.h"
26#include "../Caches.h"
27#include "../DeferredLayerUpdater.h"
28#include "../LayerRenderer.h"
29#include "../OpenGLRenderer.h"
30#include "../Stencil.h"
31
32#define PROPERTY_RENDER_DIRTY_REGIONS "debug.hwui.render_dirty_regions"
33#define GLES_VERSION 2
34#define USE_TEXTURE_ATLAS false
35
36// Android-specific addition that is used to show when frames began in systrace
37EGLAPI void EGLAPIENTRY eglBeginFrame(EGLDisplay dpy, EGLSurface surface);
38
39namespace android {
40namespace uirenderer {
41namespace renderthread {
42
43#define ERROR_CASE(x) case x: return #x;
44static const char* egl_error_str(EGLint error) {
45    switch (error) {
46        ERROR_CASE(EGL_SUCCESS)
47        ERROR_CASE(EGL_NOT_INITIALIZED)
48        ERROR_CASE(EGL_BAD_ACCESS)
49        ERROR_CASE(EGL_BAD_ALLOC)
50        ERROR_CASE(EGL_BAD_ATTRIBUTE)
51        ERROR_CASE(EGL_BAD_CONFIG)
52        ERROR_CASE(EGL_BAD_CONTEXT)
53        ERROR_CASE(EGL_BAD_CURRENT_SURFACE)
54        ERROR_CASE(EGL_BAD_DISPLAY)
55        ERROR_CASE(EGL_BAD_MATCH)
56        ERROR_CASE(EGL_BAD_NATIVE_PIXMAP)
57        ERROR_CASE(EGL_BAD_NATIVE_WINDOW)
58        ERROR_CASE(EGL_BAD_PARAMETER)
59        ERROR_CASE(EGL_BAD_SURFACE)
60        ERROR_CASE(EGL_CONTEXT_LOST)
61    default:
62        return "Unknown error";
63    }
64}
65static const char* egl_error_str() {
66    return egl_error_str(eglGetError());
67}
68
69static bool load_dirty_regions_property() {
70    char buf[PROPERTY_VALUE_MAX];
71    int len = property_get(PROPERTY_RENDER_DIRTY_REGIONS, buf, "true");
72    return !strncasecmp("true", buf, len);
73}
74
75// This class contains the shared global EGL objects, such as EGLDisplay
76// and EGLConfig, which are re-used by CanvasContext
77class GlobalContext {
78public:
79    static GlobalContext* get();
80
81    // Returns true on success, false on failure
82    void initialize();
83
84    bool hasContext();
85
86    void usePBufferSurface();
87    EGLSurface createSurface(EGLNativeWindowType window);
88    void destroySurface(EGLSurface surface);
89
90    void destroy();
91
92    bool isCurrent(EGLSurface surface) { return mCurrentSurface == surface; }
93    // Returns true if the current surface changed, false if it was already current
94    bool makeCurrent(EGLSurface surface);
95    void beginFrame(EGLSurface surface, EGLint* width, EGLint* height);
96    void swapBuffers(EGLSurface surface);
97
98    bool enableDirtyRegions(EGLSurface surface);
99
100    void setTextureAtlas(const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize);
101
102private:
103    GlobalContext();
104    // GlobalContext is never destroyed, method is purposely not implemented
105    ~GlobalContext();
106
107    void loadConfig();
108    void createContext();
109    void initAtlas();
110
111    static GlobalContext* sContext;
112
113    EGLDisplay mEglDisplay;
114    EGLConfig mEglConfig;
115    EGLContext mEglContext;
116    EGLSurface mPBufferSurface;
117
118    const bool mRequestDirtyRegions;
119    bool mCanSetDirtyRegions;
120
121    EGLSurface mCurrentSurface;
122
123    sp<GraphicBuffer> mAtlasBuffer;
124    int64_t* mAtlasMap;
125    size_t mAtlasMapSize;
126};
127
128GlobalContext* GlobalContext::sContext = 0;
129
130GlobalContext* GlobalContext::get() {
131    if (!sContext) {
132        sContext = new GlobalContext();
133    }
134    return sContext;
135}
136
137GlobalContext::GlobalContext()
138        : mEglDisplay(EGL_NO_DISPLAY)
139        , mEglConfig(0)
140        , mEglContext(EGL_NO_CONTEXT)
141        , mPBufferSurface(EGL_NO_SURFACE)
142        , mRequestDirtyRegions(load_dirty_regions_property())
143        , mCurrentSurface(EGL_NO_SURFACE)
144        , mAtlasMap(NULL)
145        , mAtlasMapSize(0) {
146    mCanSetDirtyRegions = mRequestDirtyRegions;
147    ALOGD("Render dirty regions requested: %s", mRequestDirtyRegions ? "true" : "false");
148}
149
150void GlobalContext::initialize() {
151    if (hasContext()) return;
152
153    mEglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
154    LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY,
155            "Failed to get EGL_DEFAULT_DISPLAY! err=%s", egl_error_str());
156
157    EGLint major, minor;
158    LOG_ALWAYS_FATAL_IF(eglInitialize(mEglDisplay, &major, &minor) == EGL_FALSE,
159            "Failed to initialize display %p! err=%s", mEglDisplay, egl_error_str());
160
161    ALOGI("Initialized EGL, version %d.%d", (int)major, (int)minor);
162
163    loadConfig();
164    createContext();
165    usePBufferSurface();
166    Caches::getInstance().init();
167    initAtlas();
168}
169
170bool GlobalContext::hasContext() {
171    return mEglDisplay != EGL_NO_DISPLAY;
172}
173
174void GlobalContext::loadConfig() {
175    EGLint swapBehavior = mCanSetDirtyRegions ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0;
176    EGLint attribs[] = {
177            EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
178            EGL_RED_SIZE, 8,
179            EGL_GREEN_SIZE, 8,
180            EGL_BLUE_SIZE, 8,
181            EGL_ALPHA_SIZE, 8,
182            EGL_DEPTH_SIZE, 0,
183            EGL_CONFIG_CAVEAT, EGL_NONE,
184            EGL_STENCIL_SIZE, Stencil::getStencilSize(),
185            EGL_SURFACE_TYPE, EGL_WINDOW_BIT | swapBehavior,
186            EGL_NONE
187    };
188
189    EGLint num_configs = 1;
190    if (!eglChooseConfig(mEglDisplay, attribs, &mEglConfig, num_configs, &num_configs)
191            || num_configs != 1) {
192        // Failed to get a valid config
193        if (mCanSetDirtyRegions) {
194            ALOGW("Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...");
195            // Try again without dirty regions enabled
196            mCanSetDirtyRegions = false;
197            loadConfig();
198        } else {
199            LOG_ALWAYS_FATAL("Failed to choose config, error = %s", egl_error_str());
200        }
201    }
202}
203
204void GlobalContext::createContext() {
205    EGLint attribs[] = { EGL_CONTEXT_CLIENT_VERSION, GLES_VERSION, EGL_NONE };
206    mEglContext = eglCreateContext(mEglDisplay, mEglConfig, EGL_NO_CONTEXT, attribs);
207    LOG_ALWAYS_FATAL_IF(mEglContext == EGL_NO_CONTEXT,
208        "Failed to create context, error = %s", egl_error_str());
209}
210
211void GlobalContext::setTextureAtlas(const sp<GraphicBuffer>& buffer,
212        int64_t* map, size_t mapSize) {
213
214    // Already initialized
215    if (mAtlasBuffer.get()) {
216        ALOGW("Multiple calls to setTextureAtlas!");
217        delete map;
218        return;
219    }
220
221    mAtlasBuffer = buffer;
222    mAtlasMap = map;
223    mAtlasMapSize = mapSize;
224
225    if (hasContext()) {
226        usePBufferSurface();
227        initAtlas();
228    }
229}
230
231void GlobalContext::initAtlas() {
232    if (USE_TEXTURE_ATLAS) {
233        Caches::getInstance().assetAtlas.init(mAtlasBuffer, mAtlasMap, mAtlasMapSize);
234    }
235}
236
237void GlobalContext::usePBufferSurface() {
238    LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY,
239            "usePBufferSurface() called on uninitialized GlobalContext!");
240
241    if (mPBufferSurface == EGL_NO_SURFACE) {
242        EGLint attribs[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE };
243        mPBufferSurface = eglCreatePbufferSurface(mEglDisplay, mEglConfig, attribs);
244    }
245    makeCurrent(mPBufferSurface);
246}
247
248EGLSurface GlobalContext::createSurface(EGLNativeWindowType window) {
249    initialize();
250    return eglCreateWindowSurface(mEglDisplay, mEglConfig, window, NULL);
251}
252
253void GlobalContext::destroySurface(EGLSurface surface) {
254    if (isCurrent(surface)) {
255        makeCurrent(EGL_NO_SURFACE);
256    }
257    if (!eglDestroySurface(mEglDisplay, surface)) {
258        ALOGW("Failed to destroy surface %p, error=%s", (void*)surface, egl_error_str());
259    }
260}
261
262void GlobalContext::destroy() {
263    if (mEglDisplay == EGL_NO_DISPLAY) return;
264
265    usePBufferSurface();
266    if (Caches::hasInstance()) {
267        Caches::getInstance().terminate();
268    }
269
270    eglDestroyContext(mEglDisplay, mEglContext);
271    eglDestroySurface(mEglDisplay, mPBufferSurface);
272    eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
273    eglTerminate(mEglDisplay);
274    eglReleaseThread();
275
276    mEglDisplay = EGL_NO_DISPLAY;
277    mEglContext = EGL_NO_CONTEXT;
278    mPBufferSurface = EGL_NO_SURFACE;
279    mCurrentSurface = EGL_NO_SURFACE;
280}
281
282bool GlobalContext::makeCurrent(EGLSurface surface) {
283    if (isCurrent(surface)) return false;
284
285    if (surface == EGL_NO_SURFACE) {
286        // If we are setting EGL_NO_SURFACE we don't care about any of the potential
287        // return errors, which would only happen if mEglDisplay had already been
288        // destroyed in which case the current context is already NO_CONTEXT
289        eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
290    } else if (!eglMakeCurrent(mEglDisplay, surface, surface, mEglContext)) {
291        LOG_ALWAYS_FATAL("Failed to make current on surface %p, error=%s",
292                (void*)surface, egl_error_str());
293    }
294    mCurrentSurface = surface;
295    return true;
296}
297
298void GlobalContext::beginFrame(EGLSurface surface, EGLint* width, EGLint* height) {
299    LOG_ALWAYS_FATAL_IF(surface == EGL_NO_SURFACE,
300            "Tried to beginFrame on EGL_NO_SURFACE!");
301    makeCurrent(surface);
302    if (width) {
303        eglQuerySurface(mEglDisplay, surface, EGL_WIDTH, width);
304    }
305    if (height) {
306        eglQuerySurface(mEglDisplay, surface, EGL_HEIGHT, height);
307    }
308    eglBeginFrame(mEglDisplay, surface);
309}
310
311void GlobalContext::swapBuffers(EGLSurface surface) {
312    eglSwapBuffers(mEglDisplay, surface);
313    EGLint err = eglGetError();
314    LOG_ALWAYS_FATAL_IF(err != EGL_SUCCESS,
315            "Encountered EGL error %d %s during rendering", err, egl_error_str(err));
316}
317
318bool GlobalContext::enableDirtyRegions(EGLSurface surface) {
319    if (!mRequestDirtyRegions) return false;
320
321    if (mCanSetDirtyRegions) {
322        if (!eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, EGL_BUFFER_PRESERVED)) {
323            ALOGW("Failed to set EGL_SWAP_BEHAVIOR on surface %p, error=%s",
324                    (void*) surface, egl_error_str());
325            return false;
326        }
327        return true;
328    }
329    // Perhaps it is already enabled?
330    EGLint value;
331    if (!eglQuerySurface(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, &value)) {
332        ALOGW("Failed to query EGL_SWAP_BEHAVIOR on surface %p, error=%p",
333                (void*) surface, egl_error_str());
334        return false;
335    }
336    return value == EGL_BUFFER_PRESERVED;
337}
338
339CanvasContext::CanvasContext(bool translucent, RenderNode* rootRenderNode)
340        : mRenderThread(RenderThread::getInstance())
341        , mEglSurface(EGL_NO_SURFACE)
342        , mDirtyRegionsEnabled(false)
343        , mOpaque(!translucent)
344        , mCanvas(0)
345        , mHaveNewSurface(false)
346        , mRootRenderNode(rootRenderNode) {
347    mGlobalContext = GlobalContext::get();
348}
349
350CanvasContext::~CanvasContext() {
351    destroyCanvasAndSurface();
352    mRenderThread.removeFrameCallback(this);
353}
354
355void CanvasContext::destroyCanvasAndSurface() {
356    if (mCanvas) {
357        delete mCanvas;
358        mCanvas = 0;
359    }
360    setSurface(NULL);
361}
362
363void CanvasContext::setSurface(EGLNativeWindowType window) {
364    if (mEglSurface != EGL_NO_SURFACE) {
365        mGlobalContext->destroySurface(mEglSurface);
366        mEglSurface = EGL_NO_SURFACE;
367    }
368
369    if (window) {
370        mEglSurface = mGlobalContext->createSurface(window);
371        LOG_ALWAYS_FATAL_IF(mEglSurface == EGL_NO_SURFACE,
372                "Failed to create EGLSurface for window %p, eglErr = %s",
373                (void*) window, egl_error_str());
374    }
375
376    if (mEglSurface != EGL_NO_SURFACE) {
377        mDirtyRegionsEnabled = mGlobalContext->enableDirtyRegions(mEglSurface);
378        mHaveNewSurface = true;
379        makeCurrent();
380    } else {
381        mRenderThread.removeFrameCallback(this);
382    }
383}
384
385void CanvasContext::swapBuffers() {
386    mGlobalContext->swapBuffers(mEglSurface);
387    mHaveNewSurface = false;
388}
389
390void CanvasContext::requireSurface() {
391    LOG_ALWAYS_FATAL_IF(mEglSurface == EGL_NO_SURFACE,
392            "requireSurface() called but no surface set!");
393    makeCurrent();
394}
395
396bool CanvasContext::initialize(EGLNativeWindowType window) {
397    if (mCanvas) return false;
398    setSurface(window);
399    mCanvas = new OpenGLRenderer();
400    mCanvas->initProperties();
401    return true;
402}
403
404void CanvasContext::updateSurface(EGLNativeWindowType window) {
405    setSurface(window);
406}
407
408void CanvasContext::pauseSurface(EGLNativeWindowType window) {
409    // TODO: For now we just need a fence, in the future suspend any animations
410    // and such to prevent from trying to render into this surface
411}
412
413void CanvasContext::setup(int width, int height) {
414    if (!mCanvas) return;
415    mCanvas->setViewport(width, height);
416}
417
418void CanvasContext::setOpaque(bool opaque) {
419    mOpaque = opaque;
420}
421
422void CanvasContext::makeCurrent() {
423    // TODO: Figure out why this workaround is needed, see b/13913604
424    // In the meantime this matches the behavior of GLRenderer, so it is not a regression
425    mHaveNewSurface |= mGlobalContext->makeCurrent(mEglSurface);
426}
427
428void CanvasContext::prepareDraw(const Vector<DeferredLayerUpdater*>* layerUpdaters,
429        TreeInfo& info) {
430    LOG_ALWAYS_FATAL_IF(!mCanvas, "Cannot prepareDraw without a canvas!");
431    makeCurrent();
432
433    processLayerUpdates(layerUpdaters, info);
434    if (info.out.hasAnimations) {
435        // TODO: Uh... crap?
436    }
437    prepareTree(info);
438}
439
440void CanvasContext::processLayerUpdates(const Vector<DeferredLayerUpdater*>* layerUpdaters,
441        TreeInfo& info) {
442    for (size_t i = 0; i < layerUpdaters->size(); i++) {
443        DeferredLayerUpdater* update = layerUpdaters->itemAt(i);
444        bool success = update->apply(info);
445        LOG_ALWAYS_FATAL_IF(!success, "Failed to update layer!");
446        if (update->backingLayer()->deferredUpdateScheduled) {
447            mCanvas->pushLayerUpdate(update->backingLayer());
448        }
449    }
450}
451
452void CanvasContext::prepareTree(TreeInfo& info) {
453    mRenderThread.removeFrameCallback(this);
454
455    info.frameTimeMs = mRenderThread.timeLord().frameTimeMs();
456    mRootRenderNode->prepareTree(info);
457
458    if (info.out.hasAnimations) {
459        if (info.out.hasFunctors) {
460            info.out.requiresUiRedraw = true;
461        } else if (!info.out.requiresUiRedraw) {
462            // If animationsNeedsRedraw is set don't bother posting for an RT anim
463            // as we will just end up fighting the UI thread.
464            mRenderThread.postFrameCallback(this);
465        }
466    }
467}
468
469void CanvasContext::draw(Rect* dirty) {
470    LOG_ALWAYS_FATAL_IF(!mCanvas || mEglSurface == EGL_NO_SURFACE,
471            "drawDisplayList called on a context with no canvas or surface!");
472
473    EGLint width, height;
474    mGlobalContext->beginFrame(mEglSurface, &width, &height);
475    if (width != mCanvas->getViewportWidth() || height != mCanvas->getViewportHeight()) {
476        mCanvas->setViewport(width, height);
477        dirty = NULL;
478    } else if (!mDirtyRegionsEnabled || mHaveNewSurface) {
479        dirty = NULL;
480    }
481
482    status_t status;
483    if (dirty && !dirty->isEmpty()) {
484        status = mCanvas->prepareDirty(dirty->left, dirty->top,
485                dirty->right, dirty->bottom, mOpaque);
486    } else {
487        status = mCanvas->prepare(mOpaque);
488    }
489
490    Rect outBounds;
491    status |= mCanvas->drawDisplayList(mRootRenderNode.get(), outBounds);
492
493    // TODO: Draw debug info
494    // TODO: Performance tracking
495
496    mCanvas->finish();
497
498    if (status & DrawGlInfo::kStatusDrew) {
499        swapBuffers();
500    }
501}
502
503// Called by choreographer to do an RT-driven animation
504void CanvasContext::doFrame() {
505    if (CC_UNLIKELY(!mCanvas || mEglSurface == EGL_NO_SURFACE)) {
506        return;
507    }
508
509    ATRACE_CALL();
510
511    TreeInfo info;
512    info.evaluateAnimations = true;
513    info.performStagingPush = false;
514    info.prepareTextures = false;
515
516    prepareTree(info);
517    draw(NULL);
518}
519
520void CanvasContext::invokeFunctor(Functor* functor) {
521    ATRACE_CALL();
522    DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext;
523    if (mGlobalContext->hasContext()) {
524        requireGlContext();
525        mode = DrawGlInfo::kModeProcess;
526    }
527    (*functor)(mode, NULL);
528
529    if (mCanvas) {
530        mCanvas->resume();
531    }
532}
533
534bool CanvasContext::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) {
535    requireGlContext();
536    TreeInfo info;
537    layer->apply(info);
538    return LayerRenderer::copyLayer(layer->backingLayer(), bitmap);
539}
540
541void CanvasContext::runWithGlContext(RenderTask* task) {
542    requireGlContext();
543    task->run();
544}
545
546Layer* CanvasContext::createRenderLayer(int width, int height) {
547    requireSurface();
548    return LayerRenderer::createRenderLayer(width, height);
549}
550
551Layer* CanvasContext::createTextureLayer() {
552    requireSurface();
553    return LayerRenderer::createTextureLayer();
554}
555
556void CanvasContext::requireGlContext() {
557    if (mEglSurface != EGL_NO_SURFACE) {
558        makeCurrent();
559    } else {
560        mGlobalContext->usePBufferSurface();
561    }
562}
563
564void CanvasContext::setTextureAtlas(const sp<GraphicBuffer>& buffer,
565        int64_t* map, size_t mapSize) {
566    GlobalContext::get()->setTextureAtlas(buffer, map, mapSize);
567}
568
569} /* namespace renderthread */
570} /* namespace uirenderer */
571} /* namespace android */
572