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