DisplayDevice.cpp revision 1d12d8a8e61163b35cf42c51c558a67138014e82
1/*
2 * Copyright (C) 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 <stdlib.h>
18#include <stdio.h>
19#include <string.h>
20#include <math.h>
21
22#include <cutils/properties.h>
23
24#include <utils/RefBase.h>
25#include <utils/Log.h>
26
27#include <ui/DisplayInfo.h>
28#include <ui/PixelFormat.h>
29
30#include <gui/SurfaceTextureClient.h>
31
32#include <GLES/gl.h>
33#include <EGL/egl.h>
34#include <EGL/eglext.h>
35
36#include <hardware/gralloc.h>
37
38#include "DisplayHardware/FramebufferSurface.h"
39#include "DisplayHardware/HWComposer.h"
40
41#include "clz.h"
42#include "DisplayDevice.h"
43#include "GLExtensions.h"
44#include "SurfaceFlinger.h"
45#include "LayerBase.h"
46
47// ----------------------------------------------------------------------------
48using namespace android;
49// ----------------------------------------------------------------------------
50
51static __attribute__((noinline))
52void checkGLErrors()
53{
54    do {
55        // there could be more than one error flag
56        GLenum error = glGetError();
57        if (error == GL_NO_ERROR)
58            break;
59        ALOGE("GL error 0x%04x", int(error));
60    } while(true);
61}
62
63// ----------------------------------------------------------------------------
64
65/*
66 * Initialize the display to the specified values.
67 *
68 */
69
70DisplayDevice::DisplayDevice(
71        const sp<SurfaceFlinger>& flinger,
72        DisplayType type, const wp<IBinder>& displayToken,
73        const sp<ANativeWindow>& nativeWindow,
74        const sp<FramebufferSurface>& framebufferSurface,
75        EGLConfig config)
76    : mFlinger(flinger),
77      mType(type), mHwcDisplayId(-1),
78      mNativeWindow(nativeWindow),
79      mFramebufferSurface(framebufferSurface),
80      mDisplay(EGL_NO_DISPLAY),
81      mSurface(EGL_NO_SURFACE),
82      mContext(EGL_NO_CONTEXT),
83      mDisplayWidth(), mDisplayHeight(), mFormat(),
84      mFlags(),
85      mPageFlipCount(),
86      mSecureLayerVisible(false),
87      mScreenAcquired(false),
88      mLayerStack(0),
89      mOrientation()
90{
91    init(config);
92}
93
94DisplayDevice::~DisplayDevice() {
95    if (mSurface != EGL_NO_SURFACE) {
96        eglDestroySurface(mDisplay, mSurface);
97        mSurface = EGL_NO_SURFACE;
98    }
99}
100
101bool DisplayDevice::isValid() const {
102    return mFlinger != NULL;
103}
104
105int DisplayDevice::getWidth() const {
106    return mDisplayWidth;
107}
108
109int DisplayDevice::getHeight() const {
110    return mDisplayHeight;
111}
112
113PixelFormat DisplayDevice::getFormat() const {
114    return mFormat;
115}
116
117EGLSurface DisplayDevice::getEGLSurface() const {
118    return mSurface;
119}
120
121void DisplayDevice::init(EGLConfig config)
122{
123    ANativeWindow* const window = mNativeWindow.get();
124
125    int format;
126    window->query(window, NATIVE_WINDOW_FORMAT, &format);
127
128    /*
129     * Create our display's surface
130     */
131
132    EGLSurface surface;
133    EGLint w, h;
134    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
135    surface = eglCreateWindowSurface(display, config, window, NULL);
136    eglQuerySurface(display, surface, EGL_WIDTH,  &mDisplayWidth);
137    eglQuerySurface(display, surface, EGL_HEIGHT, &mDisplayHeight);
138
139    mDisplay = display;
140    mSurface = surface;
141    mFormat  = format;
142    mPageFlipCount = 0;
143    mViewport.makeInvalid();
144    mFrame.makeInvalid();
145
146    // external displays are always considered enabled
147    mScreenAcquired = (mType >= DisplayDevice::NUM_DISPLAY_TYPES);
148
149    // get an h/w composer ID
150    mHwcDisplayId = mFlinger->allocateHwcDisplayId(mType);
151
152    // Name the display.  The name will be replaced shortly if the display
153    // was created with createDisplay().
154    switch (mType) {
155        case DISPLAY_PRIMARY:
156            mDisplayName = "Built-in Screen";
157            break;
158        case DISPLAY_EXTERNAL:
159            mDisplayName = "HDMI Screen";
160            break;
161        default:
162            mDisplayName = "Virtual Screen";    // e.g. Overlay #n
163            break;
164    }
165
166    // initialize the display orientation transform.
167    setProjection(DisplayState::eOrientationDefault, mViewport, mFrame);
168}
169
170uint32_t DisplayDevice::getPageFlipCount() const {
171    return mPageFlipCount;
172}
173
174status_t DisplayDevice::compositionComplete() const {
175    if (mFramebufferSurface == NULL) {
176        return NO_ERROR;
177    }
178    return mFramebufferSurface->compositionComplete();
179}
180
181void DisplayDevice::flip(const Region& dirty) const
182{
183    checkGLErrors();
184
185    EGLDisplay dpy = mDisplay;
186    EGLSurface surface = mSurface;
187
188#ifdef EGL_ANDROID_swap_rectangle
189    if (mFlags & SWAP_RECTANGLE) {
190        const Region newDirty(dirty.intersect(bounds()));
191        const Rect b(newDirty.getBounds());
192        eglSetSwapRectangleANDROID(dpy, surface,
193                b.left, b.top, b.width(), b.height());
194    }
195#endif
196
197    mPageFlipCount++;
198}
199
200void DisplayDevice::swapBuffers(HWComposer& hwc) const {
201    if (hwc.initCheck() != NO_ERROR) {
202        // no HWC, we call eglSwapBuffers()
203        eglSwapBuffers(mDisplay, mSurface);
204    } else {
205        // We have a valid HWC, but not all displays can use it, in particular
206        // the virtual displays are on their own.
207        // TODO: HWC 1.2 will allow virtual displays
208        if (mType >= DisplayDevice::DISPLAY_VIRTUAL) {
209            // always call eglSwapBuffers() for virtual displays
210            eglSwapBuffers(mDisplay, mSurface);
211        } else if (hwc.supportsFramebufferTarget()) {
212            // as of hwc 1.1 we always call eglSwapBuffers if we have some
213            // GLES layers
214            if (hwc.hasGlesComposition(mType)) {
215                eglSwapBuffers(mDisplay, mSurface);
216            }
217        } else {
218            // HWC doesn't have the framebuffer target, we don't call
219            // eglSwapBuffers(), since this is handled by HWComposer::commit().
220        }
221    }
222}
223
224void DisplayDevice::onSwapBuffersCompleted(HWComposer& hwc) const {
225    if (hwc.initCheck() == NO_ERROR) {
226        if (hwc.supportsFramebufferTarget()) {
227            int fd = hwc.getAndResetReleaseFenceFd(mType);
228            mFramebufferSurface->setReleaseFenceFd(fd);
229        }
230    }
231}
232
233uint32_t DisplayDevice::getFlags() const
234{
235    return mFlags;
236}
237
238EGLBoolean DisplayDevice::makeCurrent(EGLDisplay dpy,
239        const sp<const DisplayDevice>& hw, EGLContext ctx) {
240    EGLBoolean result = EGL_TRUE;
241    EGLSurface sur = eglGetCurrentSurface(EGL_DRAW);
242    if (sur != hw->mSurface) {
243        result = eglMakeCurrent(dpy, hw->mSurface, hw->mSurface, ctx);
244        if (result == EGL_TRUE) {
245            GLsizei w = hw->mDisplayWidth;
246            GLsizei h = hw->mDisplayHeight;
247            glViewport(0, 0, w, h);
248            glMatrixMode(GL_PROJECTION);
249            glLoadIdentity();
250            // put the origin in the left-bottom corner
251            glOrthof(0, w, 0, h, 0, 1); // l=0, r=w ; b=0, t=h
252        }
253    }
254    return result;
255}
256
257// ----------------------------------------------------------------------------
258
259void DisplayDevice::setVisibleLayersSortedByZ(const Vector< sp<LayerBase> >& layers) {
260    mVisibleLayersSortedByZ = layers;
261    mSecureLayerVisible = false;
262    size_t count = layers.size();
263    for (size_t i=0 ; i<count ; i++) {
264        if (layers[i]->isSecure()) {
265            mSecureLayerVisible = true;
266        }
267    }
268}
269
270const Vector< sp<LayerBase> >& DisplayDevice::getVisibleLayersSortedByZ() const {
271    return mVisibleLayersSortedByZ;
272}
273
274bool DisplayDevice::getSecureLayerVisible() const {
275    return mSecureLayerVisible;
276}
277
278Region DisplayDevice::getDirtyRegion(bool repaintEverything) const {
279    Region dirty;
280    if (repaintEverything) {
281        dirty.set(getBounds());
282    } else {
283        const Transform& planeTransform(mGlobalTransform);
284        dirty = planeTransform.transform(this->dirtyRegion);
285        dirty.andSelf(getBounds());
286    }
287    return dirty;
288}
289
290// ----------------------------------------------------------------------------
291
292bool DisplayDevice::canDraw() const {
293    return mScreenAcquired;
294}
295
296void DisplayDevice::releaseScreen() const {
297    mScreenAcquired = false;
298}
299
300void DisplayDevice::acquireScreen() const {
301    mScreenAcquired = true;
302}
303
304bool DisplayDevice::isScreenAcquired() const {
305    return mScreenAcquired;
306}
307
308// ----------------------------------------------------------------------------
309
310void DisplayDevice::setLayerStack(uint32_t stack) {
311    mLayerStack = stack;
312    dirtyRegion.set(bounds());
313}
314
315// ----------------------------------------------------------------------------
316
317status_t DisplayDevice::orientationToTransfrom(
318        int orientation, int w, int h, Transform* tr)
319{
320    uint32_t flags = 0;
321    switch (orientation) {
322    case DisplayState::eOrientationDefault:
323        flags = Transform::ROT_0;
324        break;
325    case DisplayState::eOrientation90:
326        flags = Transform::ROT_90;
327        break;
328    case DisplayState::eOrientation180:
329        flags = Transform::ROT_180;
330        break;
331    case DisplayState::eOrientation270:
332        flags = Transform::ROT_270;
333        break;
334    default:
335        return BAD_VALUE;
336    }
337    tr->set(flags, w, h);
338    return NO_ERROR;
339}
340
341void DisplayDevice::setProjection(int orientation,
342        const Rect& viewport, const Rect& frame) {
343    mOrientation = orientation;
344    mViewport = viewport;
345    mFrame = frame;
346    updateGeometryTransform();
347}
348
349void DisplayDevice::updateGeometryTransform() {
350    int w = mDisplayWidth;
351    int h = mDisplayHeight;
352    Transform TL, TP, R, S;
353    if (DisplayDevice::orientationToTransfrom(
354            mOrientation, w, h, &R) == NO_ERROR) {
355        dirtyRegion.set(bounds());
356
357        Rect viewport(mViewport);
358        Rect frame(mFrame);
359
360        if (!frame.isValid()) {
361            // the destination frame can be invalid if it has never been set,
362            // in that case we assume the whole display frame.
363            frame = Rect(w, h);
364        }
365
366        if (viewport.isEmpty()) {
367            // viewport can be invalid if it has never been set, in that case
368            // we assume the whole display size.
369            // it's also invalid to have an empty viewport, so we handle that
370            // case in the same way.
371            viewport = Rect(w, h);
372            if (R.getOrientation() & Transform::ROT_90) {
373                // viewport is always specified in the logical orientation
374                // of the display (ie: post-rotation).
375                swap(viewport.right, viewport.bottom);
376            }
377        }
378
379        float src_width  = viewport.width();
380        float src_height = viewport.height();
381        float dst_width  = frame.width();
382        float dst_height = frame.height();
383        if (src_width != dst_width || src_height != dst_height) {
384            float sx = dst_width  / src_width;
385            float sy = dst_height / src_height;
386            S.set(sx, 0, 0, sy);
387        }
388
389        float src_x = viewport.left;
390        float src_y = viewport.top;
391        float dst_x = frame.left;
392        float dst_y = frame.top;
393        TL.set(-src_x, -src_y);
394        TP.set(dst_x, dst_y);
395
396        // The viewport and frame are both in the logical orientation.
397        // Apply the logical translation, scale to physical size, apply the
398        // physical translation and finally rotate to the physical orientation.
399        mGlobalTransform = R * TP * S * TL;
400    }
401}
402
403void DisplayDevice::dump(String8& result, char* buffer, size_t SIZE) const {
404    const Transform& tr(mGlobalTransform);
405    snprintf(buffer, SIZE,
406        "+ DisplayDevice: %s\n"
407        "   type=%x, layerStack=%u, (%4dx%4d), ANativeWindow=%p, orient=%2d (type=%08x), "
408        "flips=%u, secure=%d, acquired=%d, numLayers=%u\n"
409        "   v:[%d,%d,%d,%d], f:[%d,%d,%d,%d], "
410        "transform:[[%0.3f,%0.3f,%0.3f][%0.3f,%0.3f,%0.3f][%0.3f,%0.3f,%0.3f]]\n",
411        mType, mDisplayName.string(),
412        mLayerStack, mDisplayWidth, mDisplayHeight, mNativeWindow.get(),
413        mOrientation, tr.getType(), getPageFlipCount(),
414        mSecureLayerVisible, mScreenAcquired, mVisibleLayersSortedByZ.size(),
415        mViewport.left, mViewport.top, mViewport.right, mViewport.bottom,
416        mFrame.left, mFrame.top, mFrame.right, mFrame.bottom,
417        tr[0][0], tr[1][0], tr[2][0],
418        tr[0][1], tr[1][1], tr[2][1],
419        tr[0][2], tr[1][2], tr[2][2]);
420
421    result.append(buffer);
422
423    String8 fbtargetDump;
424    if (mFramebufferSurface != NULL) {
425        mFramebufferSurface->dump(fbtargetDump);
426        result.append(fbtargetDump);
427    }
428}
429