HWComposer.cpp revision babba1868773eba5edf8a8e335b8e109a32292e0
1/*
2 * Copyright (C) 2010 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 ATRACE_TAG ATRACE_TAG_GRAPHICS
18
19// Uncomment this to remove support for HWC_DEVICE_API_VERSION_0_3 and older
20#define HWC_REMOVE_DEPRECATED_VERSIONS 1
21
22#include <stdint.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <sys/types.h>
27
28#include <utils/Errors.h>
29#include <utils/String8.h>
30#include <utils/Thread.h>
31#include <utils/Trace.h>
32#include <utils/Vector.h>
33
34#include <ui/GraphicBuffer.h>
35
36#include <hardware/hardware.h>
37#include <hardware/hwcomposer.h>
38
39#include <cutils/log.h>
40#include <cutils/properties.h>
41
42#include "Layer.h"           // needed only for debugging
43#include "LayerBase.h"
44#include "HWComposer.h"
45#include "SurfaceFlinger.h"
46
47namespace android {
48
49#define MIN_HWC_HEADER_VERSION 0
50
51static uint32_t hwcApiVersion(const hwc_composer_device_1_t* hwc) {
52    uint32_t hwcVersion = hwc->common.version;
53    if (MIN_HWC_HEADER_VERSION == 0 &&
54            (hwcVersion & HARDWARE_API_VERSION_2_MAJ_MIN_MASK) == 0) {
55        // legacy version encoding
56        hwcVersion <<= 16;
57    }
58    return hwcVersion & HARDWARE_API_VERSION_2_MAJ_MIN_MASK;
59}
60
61static uint32_t hwcHeaderVersion(const hwc_composer_device_1_t* hwc) {
62    uint32_t hwcVersion = hwc->common.version;
63    if (MIN_HWC_HEADER_VERSION == 0 &&
64            (hwcVersion & HARDWARE_API_VERSION_2_MAJ_MIN_MASK) == 0) {
65        // legacy version encoding
66        hwcVersion <<= 16;
67    }
68    return hwcVersion & HARDWARE_API_VERSION_2_HEADER_MASK;
69}
70
71static bool hwcHasApiVersion(const hwc_composer_device_1_t* hwc,
72        uint32_t version) {
73    return hwcApiVersion(hwc) >= (version & HARDWARE_API_VERSION_2_MAJ_MIN_MASK);
74}
75
76// ---------------------------------------------------------------------------
77
78struct HWComposer::cb_context {
79    struct callbacks : public hwc_procs_t {
80        // these are here to facilitate the transition when adding
81        // new callbacks (an implementation can check for NULL before
82        // calling a new callback).
83        void (*zero[4])(void);
84    };
85    callbacks procs;
86    HWComposer* hwc;
87};
88
89// ---------------------------------------------------------------------------
90
91HWComposer::HWComposer(
92        const sp<SurfaceFlinger>& flinger,
93        EventHandler& handler)
94    : mFlinger(flinger),
95      mFbDev(0), mHwc(0), mNumDisplays(1),
96      mCBContext(new cb_context),
97      mEventHandler(handler),
98      mVSyncCount(0), mDebugForceFakeVSync(false)
99{
100    for (size_t i =0 ; i<MAX_DISPLAYS ; i++) {
101        mLists[i] = 0;
102    }
103
104    char value[PROPERTY_VALUE_MAX];
105    property_get("debug.sf.no_hw_vsync", value, "0");
106    mDebugForceFakeVSync = atoi(value);
107
108    bool needVSyncThread = true;
109
110    // Note: some devices may insist that the FB HAL be opened before HWC.
111    loadFbHalModule();
112    loadHwcModule();
113
114    // If we have no HWC, or a pre-1.1 HWC, an FB dev is mandatory.
115    if ((!mHwc || !hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1))
116            && !mFbDev) {
117        ALOGE("ERROR: failed to open framebuffer, aborting");
118        abort();
119    }
120
121    if (mHwc) {
122        ALOGI("Using %s version %u.%u", HWC_HARDWARE_COMPOSER,
123              (hwcApiVersion(mHwc) >> 24) & 0xff,
124              (hwcApiVersion(mHwc) >> 16) & 0xff);
125        if (mHwc->registerProcs) {
126            mCBContext->hwc = this;
127            mCBContext->procs.invalidate = &hook_invalidate;
128            mCBContext->procs.vsync = &hook_vsync;
129            if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1))
130                mCBContext->procs.hotplug = &hook_hotplug;
131            else
132                mCBContext->procs.hotplug = NULL;
133            memset(mCBContext->procs.zero, 0, sizeof(mCBContext->procs.zero));
134            mHwc->registerProcs(mHwc, &mCBContext->procs);
135        }
136
137        // don't need a vsync thread if we have a hardware composer
138        needVSyncThread = false;
139        // always turn vsync off when we start
140        mHwc->eventControl(mHwc, HWC_DISPLAY_PRIMARY, HWC_EVENT_VSYNC, 0);
141
142        // these IDs are always reserved
143        for (size_t i=0 ; i<HWC_NUM_DISPLAY_TYPES ; i++) {
144            mAllocatedDisplayIDs.markBit(i);
145        }
146
147        // the number of displays we actually have depends on the
148        // hw composer version
149        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_2)) {
150            // 1.2 adds support for virtual displays
151            mNumDisplays = MAX_DISPLAYS;
152        } else if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
153            // 1.1 adds support for multiple displays
154            mNumDisplays = HWC_NUM_DISPLAY_TYPES;
155        } else {
156            mNumDisplays = 1;
157        }
158    }
159
160    if (mFbDev) {
161        ALOG_ASSERT(!(mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)),
162                "should only have fbdev if no hwc or hwc is 1.0");
163
164        DisplayData& disp(mDisplayData[HWC_DISPLAY_PRIMARY]);
165        disp.xres = mFbDev->width;
166        disp.yres = mFbDev->height;
167        disp.format = mFbDev->format;
168        disp.xdpi = mFbDev->xdpi;
169        disp.ydpi = mFbDev->ydpi;
170        if (disp.refresh == 0) {
171            disp.refresh = nsecs_t(1e9 / mFbDev->fps);
172            ALOGW("getting VSYNC period from fb HAL: %lld", disp.refresh);
173        }
174        if (disp.refresh == 0) {
175            disp.refresh = nsecs_t(1e9 / 60.0);
176            ALOGW("getting VSYNC period from thin air: %lld",
177                    mDisplayData[HWC_DISPLAY_PRIMARY].refresh);
178        }
179    } else if (mHwc) {
180        queryDisplayProperties(HWC_DISPLAY_PRIMARY);
181    }
182
183    if (needVSyncThread) {
184        // we don't have VSYNC support, we need to fake it
185        mVSyncThread = new VSyncThread(*this);
186    }
187}
188
189HWComposer::~HWComposer() {
190    if (mHwc) {
191        mHwc->eventControl(mHwc, 0, EVENT_VSYNC, 0);
192    }
193    if (mVSyncThread != NULL) {
194        mVSyncThread->requestExitAndWait();
195    }
196    if (mHwc) {
197        hwc_close_1(mHwc);
198    }
199    if (mFbDev) {
200        framebuffer_close(mFbDev);
201    }
202    delete mCBContext;
203}
204
205// Load and prepare the hardware composer module.  Sets mHwc.
206void HWComposer::loadHwcModule()
207{
208    hw_module_t const* module;
209
210    if (hw_get_module(HWC_HARDWARE_MODULE_ID, &module) != 0) {
211        ALOGE("%s module not found", HWC_HARDWARE_MODULE_ID);
212        return;
213    }
214
215    int err = hwc_open_1(module, &mHwc);
216    if (err) {
217        ALOGE("%s device failed to initialize (%s)",
218              HWC_HARDWARE_COMPOSER, strerror(-err));
219        return;
220    }
221
222    if (!hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_0) ||
223            hwcHeaderVersion(mHwc) < MIN_HWC_HEADER_VERSION ||
224            hwcHeaderVersion(mHwc) > HWC_HEADER_VERSION) {
225        ALOGE("%s device version %#x unsupported, will not be used",
226              HWC_HARDWARE_COMPOSER, mHwc->common.version);
227        hwc_close_1(mHwc);
228        mHwc = NULL;
229        return;
230    }
231}
232
233// Load and prepare the FB HAL, which uses the gralloc module.  Sets mFbDev.
234void HWComposer::loadFbHalModule()
235{
236    hw_module_t const* module;
237
238    if (hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module) != 0) {
239        ALOGE("%s module not found", GRALLOC_HARDWARE_MODULE_ID);
240        return;
241    }
242
243    int err = framebuffer_open(module, &mFbDev);
244    if (err) {
245        ALOGE("framebuffer_open failed (%s)", strerror(-err));
246        return;
247    }
248}
249
250status_t HWComposer::initCheck() const {
251    return mHwc ? NO_ERROR : NO_INIT;
252}
253
254void HWComposer::hook_invalidate(const struct hwc_procs* procs) {
255    cb_context* ctx = reinterpret_cast<cb_context*>(
256            const_cast<hwc_procs_t*>(procs));
257    ctx->hwc->invalidate();
258}
259
260void HWComposer::hook_vsync(const struct hwc_procs* procs, int disp,
261        int64_t timestamp) {
262    cb_context* ctx = reinterpret_cast<cb_context*>(
263            const_cast<hwc_procs_t*>(procs));
264    ctx->hwc->vsync(disp, timestamp);
265}
266
267void HWComposer::hook_hotplug(const struct hwc_procs* procs, int disp,
268        int connected) {
269    cb_context* ctx = reinterpret_cast<cb_context*>(
270            const_cast<hwc_procs_t*>(procs));
271    ctx->hwc->hotplug(disp, connected);
272}
273
274void HWComposer::invalidate() {
275    mFlinger->repaintEverything();
276}
277
278void HWComposer::vsync(int disp, int64_t timestamp) {
279    ATRACE_INT("VSYNC", ++mVSyncCount&1);
280    mEventHandler.onVSyncReceived(disp, timestamp);
281    Mutex::Autolock _l(mLock);
282    mLastHwVSync = timestamp;
283}
284
285void HWComposer::hotplug(int disp, int connected) {
286    if (disp == HWC_DISPLAY_PRIMARY || disp >= HWC_NUM_DISPLAY_TYPES) {
287        ALOGE("hotplug event received for invalid display: disp=%d connected=%d",
288                disp, connected);
289        return;
290    }
291
292    if (connected)
293        queryDisplayProperties(disp);
294
295    // TODO: tell someone else about this
296}
297
298static const uint32_t DISPLAY_ATTRIBUTES[] = {
299    HWC_DISPLAY_VSYNC_PERIOD,
300    HWC_DISPLAY_RESOLUTION_X,
301    HWC_DISPLAY_RESOLUTION_Y,
302    HWC_DISPLAY_DPI_X,
303    HWC_DISPLAY_DPI_Y,
304    HWC_DISPLAY_NO_ATTRIBUTE,
305};
306#define NUM_DISPLAY_ATTRIBUTES (sizeof(DISPLAY_ATTRIBUTES) / sizeof(DISPLAY_ATTRIBUTES)[0])
307
308// http://developer.android.com/reference/android/util/DisplayMetrics.html
309#define ANDROID_DENSITY_TV    213
310#define ANDROID_DENSITY_XHIGH 320
311
312void HWComposer::queryDisplayProperties(int disp) {
313    ALOG_ASSERT(mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1));
314
315    // use zero as default value for unspecified attributes
316    int32_t values[NUM_DISPLAY_ATTRIBUTES - 1];
317    memset(values, 0, sizeof(values));
318
319    uint32_t config;
320    size_t numConfigs = 1;
321    status_t err = mHwc->getDisplayConfigs(mHwc, disp, &config, &numConfigs);
322    if (err == NO_ERROR) {
323        mHwc->getDisplayAttributes(mHwc, disp, config, DISPLAY_ATTRIBUTES,
324                values);
325    }
326
327    int32_t w = 0, h = 0;
328    for (size_t i = 0; i < NUM_DISPLAY_ATTRIBUTES - 1; i++) {
329        switch (DISPLAY_ATTRIBUTES[i]) {
330        case HWC_DISPLAY_VSYNC_PERIOD:
331            mDisplayData[disp].refresh = nsecs_t(values[i]);
332            break;
333        case HWC_DISPLAY_RESOLUTION_X:
334            mDisplayData[disp].xres = values[i];
335            break;
336        case HWC_DISPLAY_RESOLUTION_Y:
337            mDisplayData[disp].yres = values[i];
338            break;
339        case HWC_DISPLAY_DPI_X:
340            mDisplayData[disp].xdpi = values[i] / 1000.0f;
341            break;
342        case HWC_DISPLAY_DPI_Y:
343            mDisplayData[disp].ydpi = values[i] / 1000.0f;
344            break;
345        default:
346            ALOG_ASSERT(false, "unknown display attribute %#x",
347                    DISPLAY_ATTRIBUTES[i]);
348            break;
349        }
350    }
351
352    if (mDisplayData[disp].xdpi == 0.0f || mDisplayData[disp].ydpi == 0.0f) {
353        // is there anything smarter we can do?
354        if (h >= 1080) {
355            mDisplayData[disp].xdpi = ANDROID_DENSITY_XHIGH;
356            mDisplayData[disp].ydpi = ANDROID_DENSITY_XHIGH;
357        } else {
358            mDisplayData[disp].xdpi = ANDROID_DENSITY_TV;
359            mDisplayData[disp].ydpi = ANDROID_DENSITY_TV;
360        }
361    }
362}
363
364int32_t HWComposer::allocateDisplayId() {
365    if (mAllocatedDisplayIDs.count() >= mNumDisplays) {
366        return NO_MEMORY;
367    }
368    int32_t id = mAllocatedDisplayIDs.firstUnmarkedBit();
369    mAllocatedDisplayIDs.markBit(id);
370    return id;
371}
372
373status_t HWComposer::freeDisplayId(int32_t id) {
374    if (id < HWC_NUM_DISPLAY_TYPES) {
375        // cannot free the reserved IDs
376        return BAD_VALUE;
377    }
378    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
379        return BAD_INDEX;
380    }
381    mAllocatedDisplayIDs.clearBit(id);
382    return NO_ERROR;
383}
384
385nsecs_t HWComposer::getRefreshPeriod(int disp) const {
386    return mDisplayData[disp].refresh;
387}
388
389nsecs_t HWComposer::getRefreshTimestamp(int disp) const {
390    // this returns the last refresh timestamp.
391    // if the last one is not available, we estimate it based on
392    // the refresh period and whatever closest timestamp we have.
393    Mutex::Autolock _l(mLock);
394    nsecs_t now = systemTime(CLOCK_MONOTONIC);
395    return now - ((now - mLastHwVSync) %  mDisplayData[disp].refresh);
396}
397
398uint32_t HWComposer::getResolutionX(int disp) const {
399    return mDisplayData[disp].xres;
400}
401
402uint32_t HWComposer::getResolutionY(int disp) const {
403    return mDisplayData[disp].yres;
404}
405
406uint32_t HWComposer::getFormat(int disp) const {
407    return mDisplayData[disp].format;
408}
409
410float HWComposer::getDpiX(int disp) const {
411    return mDisplayData[disp].xdpi;
412}
413
414float HWComposer::getDpiY(int disp) const {
415    return mDisplayData[disp].ydpi;
416}
417
418void HWComposer::eventControl(int event, int enabled) {
419    status_t err = NO_ERROR;
420    if (mHwc) {
421        if (!mDebugForceFakeVSync) {
422            err = mHwc->eventControl(mHwc, 0, event, enabled);
423            // error here should not happen -- not sure what we should
424            // do if it does.
425            ALOGE_IF(err, "eventControl(%d, %d) failed %s",
426                    event, enabled, strerror(-err));
427        }
428    }
429
430    if (err == NO_ERROR && mVSyncThread != NULL) {
431        mVSyncThread->setEnabled(enabled);
432    }
433}
434
435status_t HWComposer::createWorkList(int32_t id, size_t numLayers) {
436    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
437        return BAD_INDEX;
438    }
439
440    if (mHwc) {
441        DisplayData& disp(mDisplayData[id]);
442        if (disp.capacity < numLayers || disp.list == NULL) {
443            const size_t size = sizeof(hwc_display_contents_1_t)
444                    + numLayers * sizeof(hwc_layer_1_t);
445            free(disp.list);
446            disp.list = (hwc_display_contents_1_t*)malloc(size);
447            disp.capacity = numLayers;
448        }
449        disp.list->flags = HWC_GEOMETRY_CHANGED;
450        disp.list->numHwLayers = numLayers;
451        disp.list->flipFenceFd = -1;
452    }
453    return NO_ERROR;
454}
455
456status_t HWComposer::prepare() {
457    for (size_t i=0 ; i<mNumDisplays ; i++) {
458        mLists[i] = mDisplayData[i].list;
459        if (mLists[i]) {
460            mLists[i]->dpy = EGL_NO_DISPLAY;
461            mLists[i]->sur = EGL_NO_SURFACE;
462        }
463    }
464    int err = mHwc->prepare(mHwc, mNumDisplays, mLists);
465    if (err == NO_ERROR) {
466        // here we're just making sure that "skip" layers are set
467        // to HWC_FRAMEBUFFER and we're also counting how many layers
468        // we have of each type.
469        for (size_t i=0 ; i<mNumDisplays ; i++) {
470            DisplayData& disp(mDisplayData[i]);
471            disp.hasFbComp = false;
472            disp.hasOvComp = false;
473            if (disp.list) {
474                for (size_t i=0 ; i<disp.list->numHwLayers ; i++) {
475                    hwc_layer_1_t& l = disp.list->hwLayers[i];
476                    if (l.flags & HWC_SKIP_LAYER) {
477                        l.compositionType = HWC_FRAMEBUFFER;
478                    }
479                    if (l.compositionType == HWC_FRAMEBUFFER) {
480                        disp.hasFbComp = true;
481                    }
482                    if (l.compositionType == HWC_OVERLAY) {
483                        disp.hasOvComp = true;
484                    }
485                }
486            }
487        }
488    }
489    return (status_t)err;
490}
491
492bool HWComposer::hasHwcComposition(int32_t id) const {
493    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
494        return false;
495    return mDisplayData[id].hasOvComp;
496}
497
498bool HWComposer::hasGlesComposition(int32_t id) const {
499    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
500        return false;
501    return mDisplayData[id].hasFbComp;
502}
503
504status_t HWComposer::commit() {
505    int err = NO_ERROR;
506    if (mHwc) {
507        if (!hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
508            // On version 1.0, the OpenGL ES target surface is communicated
509            // by the (dpy, sur) fields and we are guaranteed to have only
510            // a single display.
511            mLists[0]->dpy = eglGetCurrentDisplay();
512            mLists[0]->sur = eglGetCurrentSurface(EGL_DRAW);
513        }
514
515        err = mHwc->set(mHwc, mNumDisplays, mLists);
516
517        for (size_t i=0 ; i<mNumDisplays ; i++) {
518            DisplayData& disp(mDisplayData[i]);
519            if (disp.list) {
520                if (disp.list->flipFenceFd != -1) {
521                    close(disp.list->flipFenceFd);
522                    disp.list->flipFenceFd = -1;
523                }
524                disp.list->flags &= ~HWC_GEOMETRY_CHANGED;
525            }
526        }
527    }
528    return (status_t)err;
529}
530
531status_t HWComposer::release() const {
532    if (mHwc) {
533        mHwc->eventControl(mHwc, 0, HWC_EVENT_VSYNC, 0);
534        return (status_t)mHwc->blank(mHwc, 0, 1);
535    }
536    return NO_ERROR;
537}
538
539status_t HWComposer::acquire() const {
540    if (mHwc) {
541        return (status_t)mHwc->blank(mHwc, 0, 0);
542    }
543    return NO_ERROR;
544}
545
546size_t HWComposer::getNumLayers(int32_t id) const {
547    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
548        return 0;
549    }
550    return (mHwc && mDisplayData[id].list) ?
551            mDisplayData[id].list->numHwLayers : 0;
552}
553
554int HWComposer::fbPost(buffer_handle_t buffer)
555{
556    return mFbDev->post(mFbDev, buffer);
557}
558
559int HWComposer::fbCompositionComplete()
560{
561    if (mFbDev->compositionComplete) {
562        return mFbDev->compositionComplete(mFbDev);
563    } else {
564        return INVALID_OPERATION;
565    }
566}
567
568void HWComposer::fbDump(String8& result) {
569    if (mFbDev->common.version >= 1 && mFbDev->dump) {
570        const size_t SIZE = 4096;
571        char buffer[SIZE];
572        mFbDev->dump(mFbDev, buffer, SIZE);
573        result.append(buffer);
574    }
575}
576
577
578/*
579 * Helper template to implement a concrete HWCLayer
580 * This holds the pointer to the concrete hwc layer type
581 * and implements the "iterable" side of HWCLayer.
582 */
583template<typename CONCRETE, typename HWCTYPE>
584class Iterable : public HWComposer::HWCLayer {
585protected:
586    HWCTYPE* const mLayerList;
587    HWCTYPE* mCurrentLayer;
588    Iterable(HWCTYPE* layer) : mLayerList(layer), mCurrentLayer(layer) { }
589    inline HWCTYPE const * getLayer() const { return mCurrentLayer; }
590    inline HWCTYPE* getLayer() { return mCurrentLayer; }
591    virtual ~Iterable() { }
592private:
593    // returns a copy of ourselves
594    virtual HWComposer::HWCLayer* dup() {
595        return new CONCRETE( static_cast<const CONCRETE&>(*this) );
596    }
597    virtual status_t setLayer(size_t index) {
598        mCurrentLayer = &mLayerList[index];
599        return NO_ERROR;
600    }
601};
602
603/*
604 * Concrete implementation of HWCLayer for HWC_DEVICE_API_VERSION_1_0.
605 * This implements the HWCLayer side of HWCIterableLayer.
606 */
607class HWCLayerVersion1 : public Iterable<HWCLayerVersion1, hwc_layer_1_t> {
608public:
609    HWCLayerVersion1(hwc_layer_1_t* layer)
610        : Iterable<HWCLayerVersion1, hwc_layer_1_t>(layer) { }
611
612    virtual int32_t getCompositionType() const {
613        return getLayer()->compositionType;
614    }
615    virtual uint32_t getHints() const {
616        return getLayer()->hints;
617    }
618    virtual int getAndResetReleaseFenceFd() {
619        int fd = getLayer()->releaseFenceFd;
620        getLayer()->releaseFenceFd = -1;
621        return fd;
622    }
623    virtual void setAcquireFenceFd(int fenceFd) {
624        getLayer()->acquireFenceFd = fenceFd;
625    }
626
627    virtual void setDefaultState() {
628        getLayer()->compositionType = HWC_FRAMEBUFFER;
629        getLayer()->hints = 0;
630        getLayer()->flags = HWC_SKIP_LAYER;
631        getLayer()->handle = 0;
632        getLayer()->transform = 0;
633        getLayer()->blending = HWC_BLENDING_NONE;
634        getLayer()->visibleRegionScreen.numRects = 0;
635        getLayer()->visibleRegionScreen.rects = NULL;
636        getLayer()->acquireFenceFd = -1;
637        getLayer()->releaseFenceFd = -1;
638    }
639    virtual void setSkip(bool skip) {
640        if (skip) {
641            getLayer()->flags |= HWC_SKIP_LAYER;
642        } else {
643            getLayer()->flags &= ~HWC_SKIP_LAYER;
644        }
645    }
646    virtual void setBlending(uint32_t blending) {
647        getLayer()->blending = blending;
648    }
649    virtual void setTransform(uint32_t transform) {
650        getLayer()->transform = transform;
651    }
652    virtual void setFrame(const Rect& frame) {
653        reinterpret_cast<Rect&>(getLayer()->displayFrame) = frame;
654    }
655    virtual void setCrop(const Rect& crop) {
656        reinterpret_cast<Rect&>(getLayer()->sourceCrop) = crop;
657    }
658    virtual void setVisibleRegionScreen(const Region& reg) {
659        // Region::getSharedBuffer creates a reference to the underlying
660        // SharedBuffer of this Region, this reference is freed
661        // in onDisplayed()
662        hwc_region_t& visibleRegion = getLayer()->visibleRegionScreen;
663        SharedBuffer const* sb = reg.getSharedBuffer(&visibleRegion.numRects);
664        visibleRegion.rects = reinterpret_cast<hwc_rect_t const *>(sb->data());
665    }
666    virtual void setBuffer(const sp<GraphicBuffer>& buffer) {
667        if (buffer == 0 || buffer->handle == 0) {
668            getLayer()->compositionType = HWC_FRAMEBUFFER;
669            getLayer()->flags |= HWC_SKIP_LAYER;
670            getLayer()->handle = 0;
671        } else {
672            getLayer()->handle = buffer->handle;
673        }
674    }
675    virtual void onDisplayed() {
676        hwc_region_t& visibleRegion = getLayer()->visibleRegionScreen;
677        SharedBuffer const* sb = SharedBuffer::bufferFromData(visibleRegion.rects);
678        if (sb) {
679            sb->release();
680            // not technically needed but safer
681            visibleRegion.numRects = 0;
682            visibleRegion.rects = NULL;
683        }
684
685        getLayer()->acquireFenceFd = -1;
686    }
687};
688
689/*
690 * returns an iterator initialized at a given index in the layer list
691 */
692HWComposer::LayerListIterator HWComposer::getLayerIterator(int32_t id, size_t index) {
693    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
694        return LayerListIterator();
695    }
696    const DisplayData& disp(mDisplayData[id]);
697    if (!mHwc || !disp.list || index > disp.list->numHwLayers) {
698        return LayerListIterator();
699    }
700    return LayerListIterator(new HWCLayerVersion1(disp.list->hwLayers), index);
701}
702
703/*
704 * returns an iterator on the beginning of the layer list
705 */
706HWComposer::LayerListIterator HWComposer::begin(int32_t id) {
707    return getLayerIterator(id, 0);
708}
709
710/*
711 * returns an iterator on the end of the layer list
712 */
713HWComposer::LayerListIterator HWComposer::end(int32_t id) {
714    return getLayerIterator(id, getNumLayers(id));
715}
716
717void HWComposer::dump(String8& result, char* buffer, size_t SIZE,
718        const Vector< sp<LayerBase> >& visibleLayersSortedByZ) const {
719    if (mHwc) {
720        result.append("Hardware Composer state:\n");
721        result.appendFormat("  mDebugForceFakeVSync=%d\n", mDebugForceFakeVSync);
722        for (size_t i=0 ; i<mNumDisplays ; i++) {
723            const DisplayData& disp(mDisplayData[i]);
724            if (disp.list) {
725                result.appendFormat("  id=%d, numHwLayers=%u, flags=%08x\n",
726                        i, disp.list->numHwLayers, disp.list->flags);
727                result.append(
728                        "   type   |  handle  |   hints  |   flags  | tr | blend |  format  |       source crop         |           frame           name \n"
729                        "----------+----------+----------+----------+----+-------+----------+---------------------------+--------------------------------\n");
730                //      " ________ | ________ | ________ | ________ | __ | _____ | ________ | [_____,_____,_____,_____] | [_____,_____,_____,_____]
731                for (size_t i=0 ; i<disp.list->numHwLayers ; i++) {
732                    const hwc_layer_1_t&l = disp.list->hwLayers[i];
733                    const sp<LayerBase> layer(visibleLayersSortedByZ[i]);
734                    int32_t format = -1;
735                    if (layer->getLayer() != NULL) {
736                        const sp<GraphicBuffer>& buffer(
737                                layer->getLayer()->getActiveBuffer());
738                        if (buffer != NULL) {
739                            format = buffer->getPixelFormat();
740                        }
741                    }
742                    result.appendFormat(
743                            " %8s | %08x | %08x | %08x | %02x | %05x | %08x | [%5d,%5d,%5d,%5d] | [%5d,%5d,%5d,%5d] %s\n",
744                            l.compositionType ? "OVERLAY" : "FB",
745                                    intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, format,
746                                    l.sourceCrop.left, l.sourceCrop.top, l.sourceCrop.right, l.sourceCrop.bottom,
747                                    l.displayFrame.left, l.displayFrame.top, l.displayFrame.right, l.displayFrame.bottom,
748                                    layer->getName().string());
749                }
750            }
751        }
752    }
753
754    if (mHwc && mHwc->dump) {
755        mHwc->dump(mHwc, buffer, SIZE);
756        result.append(buffer);
757    }
758}
759
760// ---------------------------------------------------------------------------
761
762HWComposer::VSyncThread::VSyncThread(HWComposer& hwc)
763    : mHwc(hwc), mEnabled(false),
764      mNextFakeVSync(0),
765      mRefreshPeriod(hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY))
766{
767}
768
769void HWComposer::VSyncThread::setEnabled(bool enabled) {
770    Mutex::Autolock _l(mLock);
771    mEnabled = enabled;
772    mCondition.signal();
773}
774
775void HWComposer::VSyncThread::onFirstRef() {
776    run("VSyncThread", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
777}
778
779bool HWComposer::VSyncThread::threadLoop() {
780    { // scope for lock
781        Mutex::Autolock _l(mLock);
782        while (!mEnabled) {
783            mCondition.wait(mLock);
784        }
785    }
786
787    const nsecs_t period = mRefreshPeriod;
788    const nsecs_t now = systemTime(CLOCK_MONOTONIC);
789    nsecs_t next_vsync = mNextFakeVSync;
790    nsecs_t sleep = next_vsync - now;
791    if (sleep < 0) {
792        // we missed, find where the next vsync should be
793        sleep = (period - ((now - next_vsync) % period));
794        next_vsync = now + sleep;
795    }
796    mNextFakeVSync = next_vsync + period;
797
798    struct timespec spec;
799    spec.tv_sec  = next_vsync / 1000000000;
800    spec.tv_nsec = next_vsync % 1000000000;
801
802    int err;
803    do {
804        err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, NULL);
805    } while (err<0 && errno == EINTR);
806
807    if (err == 0) {
808        mHwc.mEventHandler.onVSyncReceived(0, next_vsync);
809    }
810
811    return true;
812}
813
814// ---------------------------------------------------------------------------
815}; // namespace android
816