hwc_utils.cpp revision 5c937230915bced21130a3e5d129c4f470fd74d3
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 * Copyright (C) 2012-2013, The Linux Foundation All rights reserved.
4 *
5 * Not a Contribution, Apache license notifications and license are retained
6 * for attribution purposes only.
7 *
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 *      http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 */
20#define HWC_UTILS_DEBUG 0
21#include <sys/ioctl.h>
22#include <linux/fb.h>
23#include <binder/IServiceManager.h>
24#include <EGL/egl.h>
25#include <cutils/properties.h>
26#include <gralloc_priv.h>
27#include <overlay.h>
28#include <overlayRotator.h>
29#include "hwc_utils.h"
30#include "hwc_mdpcomp.h"
31#include "hwc_fbupdate.h"
32#include "hwc_video.h"
33#include "mdp_version.h"
34#include "hwc_copybit.h"
35#include "external.h"
36#include "hwc_qclient.h"
37#include "QService.h"
38#include "comptype.h"
39
40using namespace qClient;
41using namespace qService;
42using namespace android;
43using namespace overlay;
44using namespace overlay::utils;
45namespace ovutils = overlay::utils;
46
47namespace qhwc {
48
49static int openFramebufferDevice(hwc_context_t *ctx)
50{
51    struct fb_fix_screeninfo finfo;
52    struct fb_var_screeninfo info;
53
54    int fb_fd = openFb(HWC_DISPLAY_PRIMARY);
55
56    if (ioctl(fb_fd, FBIOGET_VSCREENINFO, &info) == -1)
57        return -errno;
58
59    if (int(info.width) <= 0 || int(info.height) <= 0) {
60        // the driver doesn't return that information
61        // default to 160 dpi
62        info.width  = ((info.xres * 25.4f)/160.0f + 0.5f);
63        info.height = ((info.yres * 25.4f)/160.0f + 0.5f);
64    }
65
66    float xdpi = (info.xres * 25.4f) / info.width;
67    float ydpi = (info.yres * 25.4f) / info.height;
68
69#ifdef MSMFB_METADATA_GET
70    struct msmfb_metadata metadata;
71    memset(&metadata, 0 , sizeof(metadata));
72    metadata.op = metadata_op_frame_rate;
73
74    if (ioctl(fb_fd, MSMFB_METADATA_GET, &metadata) == -1) {
75        ALOGE("Error retrieving panel frame rate");
76        return -errno;
77    }
78
79    float fps  = metadata.data.panel_frame_rate;
80#else
81    //XXX: Remove reserved field usage on all baselines
82    //The reserved[3] field is used to store FPS by the driver.
83    float fps  = info.reserved[3] & 0xFF;
84#endif
85
86    if (ioctl(fb_fd, FBIOGET_FSCREENINFO, &finfo) == -1)
87        return -errno;
88
89    if (finfo.smem_len <= 0)
90        return -errno;
91
92    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd = fb_fd;
93    //xres, yres may not be 32 aligned
94    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].stride = finfo.line_length /(info.xres/8);
95    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres = info.xres;
96    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres = info.yres;
97    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xdpi = xdpi;
98    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].ydpi = ydpi;
99    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].vsync_period = 1000000000l / fps;
100
101    return 0;
102}
103
104void initContext(hwc_context_t *ctx)
105{
106    openFramebufferDevice(ctx);
107    ctx->mMDP.version = qdutils::MDPVersion::getInstance().getMDPVersion();
108    ctx->mMDP.hasOverlay = qdutils::MDPVersion::getInstance().hasOverlay();
109    ctx->mMDP.panel = qdutils::MDPVersion::getInstance().getPanelType();
110    overlay::Overlay::initOverlay();
111    ctx->mOverlay = overlay::Overlay::getInstance();
112    ctx->mRotMgr = new RotMgr();
113
114    //Is created and destroyed only once for primary
115    //For external it could get created and destroyed multiple times depending
116    //on what external we connect to.
117    ctx->mFBUpdate[HWC_DISPLAY_PRIMARY] =
118        IFBUpdate::getObject(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres,
119        HWC_DISPLAY_PRIMARY);
120
121    ctx->mVidOv[HWC_DISPLAY_PRIMARY] =
122        IVideoOverlay::getObject(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres,
123        HWC_DISPLAY_PRIMARY);
124
125    char value[PROPERTY_VALUE_MAX];
126    // Check if the target supports copybit compostion (dyn/mdp/c2d) to
127    // decide if we need to open the copybit module.
128    int compositionType =
129        qdutils::QCCompositionType::getInstance().getCompositionType();
130
131    if (compositionType & (qdutils::COMPOSITION_TYPE_DYN |
132                           qdutils::COMPOSITION_TYPE_MDP |
133                           qdutils::COMPOSITION_TYPE_C2D)) {
134            ctx->mCopyBit[HWC_DISPLAY_PRIMARY] = new CopyBit();
135    }
136
137    ctx->mExtDisplay = new ExternalDisplay(ctx);
138    for (uint32_t i = 0; i < MAX_DISPLAYS; i++)
139        ctx->mLayerCache[i] = new LayerCache();
140    ctx->mMDPComp = MDPComp::getObject(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres);
141    MDPComp::init(ctx);
142
143    pthread_mutex_init(&(ctx->vstate.lock), NULL);
144    pthread_cond_init(&(ctx->vstate.cond), NULL);
145    ctx->vstate.enable = false;
146    ctx->vstate.fakevsync = false;
147    ctx->mExtDispConfiguring = false;
148
149    //Right now hwc starts the service but anybody could do it, or it could be
150    //independent process as well.
151    QService::init();
152    sp<IQClient> client = new QClient(ctx);
153    interface_cast<IQService>(
154            defaultServiceManager()->getService(
155            String16("display.qservice")))->connect(client);
156
157    ALOGI("Initializing Qualcomm Hardware Composer");
158    ALOGI("MDP version: %d", ctx->mMDP.version);
159}
160
161void closeContext(hwc_context_t *ctx)
162{
163    if(ctx->mOverlay) {
164        delete ctx->mOverlay;
165        ctx->mOverlay = NULL;
166    }
167
168    if(ctx->mRotMgr) {
169        delete ctx->mRotMgr;
170        ctx->mRotMgr = NULL;
171    }
172
173    for(int i = 0; i < MAX_DISPLAYS; i++) {
174        if(ctx->mCopyBit[i]) {
175            delete ctx->mCopyBit[i];
176            ctx->mCopyBit[i] = NULL;
177        }
178    }
179
180    if(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd) {
181        close(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd);
182        ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd = -1;
183    }
184
185    if(ctx->mExtDisplay) {
186        delete ctx->mExtDisplay;
187        ctx->mExtDisplay = NULL;
188    }
189
190    for(int i = 0; i < MAX_DISPLAYS; i++) {
191        if(ctx->mFBUpdate[i]) {
192            delete ctx->mFBUpdate[i];
193            ctx->mFBUpdate[i] = NULL;
194        }
195        if(ctx->mVidOv[i]) {
196            delete ctx->mVidOv[i];
197            ctx->mVidOv[i] = NULL;
198        }
199    }
200
201    if(ctx->mMDPComp) {
202        delete ctx->mMDPComp;
203        ctx->mMDPComp = NULL;
204    }
205
206    pthread_mutex_destroy(&(ctx->vstate.lock));
207    pthread_cond_destroy(&(ctx->vstate.cond));
208}
209
210
211void dumpsys_log(android::String8& buf, const char* fmt, ...)
212{
213    va_list varargs;
214    va_start(varargs, fmt);
215    buf.appendFormatV(fmt, varargs);
216    va_end(varargs);
217}
218
219/* Calculates the destination position based on the action safe rectangle */
220void getActionSafePosition(hwc_context_t *ctx, int dpy, uint32_t& x,
221                           uint32_t& y, uint32_t& w, uint32_t& h) {
222
223    // if external supports underscan, do nothing
224    // it will be taken care in the driver
225    if(ctx->mExtDisplay->isCEUnderscanSupported())
226        return;
227
228    float wRatio = 1.0;
229    float hRatio = 1.0;
230    float xRatio = 1.0;
231    float yRatio = 1.0;
232
233    float fbWidth = ctx->dpyAttr[dpy].xres;
234    float fbHeight = ctx->dpyAttr[dpy].yres;
235
236    float asX = 0;
237    float asY = 0;
238    float asW = fbWidth;
239    float asH= fbHeight;
240    char value[PROPERTY_VALUE_MAX];
241
242    // Apply action safe parameters
243    property_get("hw.actionsafe.width", value, "0");
244    int asWidthRatio = atoi(value);
245    property_get("hw.actionsafe.height", value, "0");
246    int asHeightRatio = atoi(value);
247    // based on the action safe ratio, get the Action safe rectangle
248    asW = fbWidth * (1.0f -  asWidthRatio / 100.0f);
249    asH = fbHeight * (1.0f -  asHeightRatio / 100.0f);
250    asX = (fbWidth - asW) / 2;
251    asY = (fbHeight - asH) / 2;
252
253    // calculate the position ratio
254    xRatio = (float)x/fbWidth;
255    yRatio = (float)y/fbHeight;
256    wRatio = (float)w/fbWidth;
257    hRatio = (float)h/fbHeight;
258
259    //Calculate the position...
260    x = (xRatio * asW) + asX;
261    y = (yRatio * asH) + asY;
262    w = (wRatio * asW);
263    h = (hRatio * asH);
264
265    return;
266}
267
268bool needsScaling(hwc_layer_1_t const* layer) {
269    int dst_w, dst_h, src_w, src_h;
270
271    hwc_rect_t displayFrame  = layer->displayFrame;
272    hwc_rect_t sourceCrop = layer->sourceCrop;
273
274    dst_w = displayFrame.right - displayFrame.left;
275    dst_h = displayFrame.bottom - displayFrame.top;
276
277    src_w = sourceCrop.right - sourceCrop.left;
278    src_h = sourceCrop.bottom - sourceCrop.top;
279
280    if(((src_w != dst_w) || (src_h != dst_h)))
281        return true;
282
283    return false;
284}
285
286bool isAlphaScaled(hwc_layer_1_t const* layer) {
287    if(needsScaling(layer)) {
288        if(layer->blending != HWC_BLENDING_NONE)
289            return true;
290    }
291    return false;
292}
293
294void setListStats(hwc_context_t *ctx,
295        const hwc_display_contents_1_t *list, int dpy) {
296
297    ctx->listStats[dpy].numAppLayers = list->numHwLayers - 1;
298    ctx->listStats[dpy].fbLayerIndex = list->numHwLayers - 1;
299    ctx->listStats[dpy].skipCount = 0;
300    ctx->listStats[dpy].needsAlphaScale = false;
301    ctx->listStats[dpy].preMultipliedAlpha = false;
302    ctx->listStats[dpy].yuvCount = 0;
303
304    for (size_t i = 0; i < list->numHwLayers; i++) {
305        hwc_layer_1_t const* layer = &list->hwLayers[i];
306        private_handle_t *hnd = (private_handle_t *)layer->handle;
307
308        //reset stored yuv index
309        ctx->listStats[dpy].yuvIndices[i] = -1;
310
311        if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
312            continue;
313        //We disregard FB being skip for now! so the else if
314        } else if (isSkipLayer(&list->hwLayers[i])) {
315            ctx->listStats[dpy].skipCount++;
316        } else if (UNLIKELY(isYuvBuffer(hnd))) {
317            int& yuvCount = ctx->listStats[dpy].yuvCount;
318            ctx->listStats[dpy].yuvIndices[yuvCount] = i;
319            yuvCount++;
320
321            if(layer->transform & HWC_TRANSFORM_ROT_90)
322                ctx->mNeedsRotator = true;
323        }
324        if(layer->blending == HWC_BLENDING_PREMULT)
325            ctx->listStats[dpy].preMultipliedAlpha = true;
326
327        if(!ctx->listStats[dpy].needsAlphaScale)
328            ctx->listStats[dpy].needsAlphaScale = isAlphaScaled(layer);
329    }
330}
331
332
333static inline void calc_cut(float& leftCutRatio, float& topCutRatio,
334        float& rightCutRatio, float& bottomCutRatio, int orient) {
335    if(orient & HAL_TRANSFORM_FLIP_H) {
336        swap(leftCutRatio, rightCutRatio);
337    }
338    if(orient & HAL_TRANSFORM_FLIP_V) {
339        swap(topCutRatio, bottomCutRatio);
340    }
341    if(orient & HAL_TRANSFORM_ROT_90) {
342        //Anti clock swapping
343        float tmpCutRatio = leftCutRatio;
344        leftCutRatio = topCutRatio;
345        topCutRatio = rightCutRatio;
346        rightCutRatio = bottomCutRatio;
347        bottomCutRatio = tmpCutRatio;
348    }
349}
350
351bool isSecuring(hwc_context_t* ctx) {
352    if((ctx->mMDP.version < qdutils::MDSS_V5) &&
353       (ctx->mMDP.version > qdutils::MDP_V3_0) &&
354        ctx->mSecuring) {
355        return true;
356    }
357    return false;
358}
359
360bool isSecureModePolicy(int mdpVersion) {
361    if (mdpVersion < qdutils::MDSS_V5)
362        return true;
363    else
364        return false;
365}
366
367//Crops source buffer against destination and FB boundaries
368void calculate_crop_rects(hwc_rect_t& crop, hwc_rect_t& dst,
369                          const hwc_rect_t& scissor, int orient) {
370
371    int& crop_l = crop.left;
372    int& crop_t = crop.top;
373    int& crop_r = crop.right;
374    int& crop_b = crop.bottom;
375    int crop_w = crop.right - crop.left;
376    int crop_h = crop.bottom - crop.top;
377
378    int& dst_l = dst.left;
379    int& dst_t = dst.top;
380    int& dst_r = dst.right;
381    int& dst_b = dst.bottom;
382    int dst_w = abs(dst.right - dst.left);
383    int dst_h = abs(dst.bottom - dst.top);
384
385    const int& sci_l = scissor.left;
386    const int& sci_t = scissor.top;
387    const int& sci_r = scissor.right;
388    const int& sci_b = scissor.bottom;
389    int sci_w = abs(sci_r - sci_l);
390    int sci_h = abs(sci_b - sci_t);
391
392    float leftCutRatio = 0.0f, rightCutRatio = 0.0f, topCutRatio = 0.0f,
393            bottomCutRatio = 0.0f;
394
395    if(dst_l < sci_l) {
396        leftCutRatio = (float)(sci_l - dst_l) / (float)dst_w;
397        dst_l = sci_l;
398    }
399
400    if(dst_r > sci_r) {
401        rightCutRatio = (float)(dst_r - sci_r) / (float)dst_w;
402        dst_r = sci_r;
403    }
404
405    if(dst_t < sci_t) {
406        topCutRatio = (float)(sci_t - dst_t) / (float)dst_h;
407        dst_t = sci_t;
408    }
409
410    if(dst_b > sci_b) {
411        bottomCutRatio = (float)(dst_b - sci_b) / (float)dst_h;
412        dst_b = sci_b;
413    }
414
415    calc_cut(leftCutRatio, topCutRatio, rightCutRatio, bottomCutRatio, orient);
416    crop_l += crop_w * leftCutRatio;
417    crop_t += crop_h * topCutRatio;
418    crop_r -= crop_w * rightCutRatio;
419    crop_b -= crop_h * bottomCutRatio;
420}
421
422void getNonWormholeRegion(hwc_display_contents_1_t* list,
423                              hwc_rect_t& nwr)
424{
425    uint32_t last = list->numHwLayers - 1;
426    hwc_rect_t fbDisplayFrame = list->hwLayers[last].displayFrame;
427    //Initiliaze nwr to first frame
428    nwr.left =  list->hwLayers[0].displayFrame.left;
429    nwr.top =  list->hwLayers[0].displayFrame.top;
430    nwr.right =  list->hwLayers[0].displayFrame.right;
431    nwr.bottom =  list->hwLayers[0].displayFrame.bottom;
432
433    for (uint32_t i = 1; i < last; i++) {
434        hwc_rect_t displayFrame = list->hwLayers[i].displayFrame;
435        nwr.left   = min(nwr.left, displayFrame.left);
436        nwr.top    = min(nwr.top, displayFrame.top);
437        nwr.right  = max(nwr.right, displayFrame.right);
438        nwr.bottom = max(nwr.bottom, displayFrame.bottom);
439    }
440
441    //Intersect with the framebuffer
442    nwr.left   = max(nwr.left, fbDisplayFrame.left);
443    nwr.top    = max(nwr.top, fbDisplayFrame.top);
444    nwr.right  = min(nwr.right, fbDisplayFrame.right);
445    nwr.bottom = min(nwr.bottom, fbDisplayFrame.bottom);
446
447}
448
449bool isExternalActive(hwc_context_t* ctx) {
450    return ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].isActive;
451}
452
453void closeAcquireFds(hwc_display_contents_1_t* list) {
454    for(uint32_t i = 0; list && i < list->numHwLayers; i++) {
455        //Close the acquireFenceFds
456        //HWC_FRAMEBUFFER are -1 already by SF, rest we close.
457        if(list->hwLayers[i].acquireFenceFd >= 0) {
458            close(list->hwLayers[i].acquireFenceFd);
459            list->hwLayers[i].acquireFenceFd = -1;
460        }
461    }
462}
463
464int hwc_sync(hwc_context_t *ctx, hwc_display_contents_1_t* list, int dpy,
465                                                        int fd) {
466    int ret = 0;
467    struct mdp_buf_sync data;
468    int acquireFd[MAX_NUM_LAYERS];
469    int count = 0;
470    int releaseFd = -1;
471    int fbFd = -1;
472    memset(&data, 0, sizeof(data));
473    bool swapzero = false;
474    data.flags = MDP_BUF_SYNC_FLAG_WAIT;
475    data.acq_fen_fd = acquireFd;
476    data.rel_fen_fd = &releaseFd;
477    char property[PROPERTY_VALUE_MAX];
478    if(property_get("debug.egl.swapinterval", property, "1") > 0) {
479        if(atoi(property) == 0)
480            swapzero = true;
481    }
482
483    //Accumulate acquireFenceFds
484    for(uint32_t i = 0; i < list->numHwLayers; i++) {
485        if(list->hwLayers[i].compositionType == HWC_OVERLAY &&
486                        list->hwLayers[i].acquireFenceFd != -1) {
487            if(UNLIKELY(swapzero))
488                acquireFd[count++] = -1;
489            else
490                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
491        }
492        if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
493            if(UNLIKELY(swapzero))
494                acquireFd[count++] = -1;
495            else if(fd != -1) {
496                //set the acquireFD from fd - which is coming from c2d
497                acquireFd[count++] = fd;
498                // Buffer sync IOCTL should be async when using c2d fence is
499                // used
500                data.flags &= ~MDP_BUF_SYNC_FLAG_WAIT;
501            } else if(list->hwLayers[i].acquireFenceFd != -1)
502                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
503        }
504    }
505
506    data.acq_fen_fd_cnt = count;
507    fbFd = ctx->dpyAttr[dpy].fd;
508    //Waits for acquire fences, returns a release fence
509    if(LIKELY(!swapzero)) {
510        uint64_t start = systemTime();
511        ret = ioctl(fbFd, MSMFB_BUFFER_SYNC, &data);
512        ALOGD_IF(HWC_UTILS_DEBUG, "%s: time taken for MSMFB_BUFFER_SYNC IOCTL = %d",
513                            __FUNCTION__, (size_t) ns2ms(systemTime() - start));
514    }
515
516    if(ret < 0) {
517        ALOGE("ioctl MSMFB_BUFFER_SYNC failed, err=%s",
518                strerror(errno));
519    }
520
521    for(uint32_t i = 0; i < list->numHwLayers; i++) {
522        if(list->hwLayers[i].compositionType == HWC_OVERLAY ||
523           list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
524            //Populate releaseFenceFds.
525            if(UNLIKELY(swapzero))
526                list->hwLayers[i].releaseFenceFd = -1;
527            else
528                list->hwLayers[i].releaseFenceFd = dup(releaseFd);
529        }
530    }
531
532    if(fd >= 0) {
533        close(fd);
534        fd = -1;
535    }
536
537    if (ctx->mCopyBit[dpy])
538        ctx->mCopyBit[dpy]->setReleaseFd(releaseFd);
539    if(UNLIKELY(swapzero)){
540        list->retireFenceFd = -1;
541        close(releaseFd);
542    } else {
543        list->retireFenceFd = releaseFd;
544    }
545
546    return ret;
547}
548
549void trimLayer(hwc_context_t *ctx, const int& dpy, const int& transform,
550        hwc_rect_t& crop, hwc_rect_t& dst) {
551    int hw_w = ctx->dpyAttr[dpy].xres;
552    int hw_h = ctx->dpyAttr[dpy].yres;
553    if(dst.left < 0 || dst.top < 0 ||
554            dst.right > hw_w || dst.bottom > hw_h) {
555        hwc_rect_t scissor = {0, 0, hw_w, hw_h };
556        qhwc::calculate_crop_rects(crop, dst, scissor, transform);
557    }
558}
559
560void setMdpFlags(hwc_layer_1_t *layer,
561        ovutils::eMdpFlags &mdpFlags,
562        int rotDownscale) {
563    private_handle_t *hnd = (private_handle_t *)layer->handle;
564    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
565    const int& transform = layer->transform;
566
567    if(layer->blending == HWC_BLENDING_PREMULT) {
568        ovutils::setMdpFlags(mdpFlags,
569                ovutils::OV_MDP_BLEND_FG_PREMULT);
570    }
571
572    if(isYuvBuffer(hnd)) {
573        if(isSecureBuffer(hnd)) {
574            ovutils::setMdpFlags(mdpFlags,
575                    ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
576        }
577        if(metadata && (metadata->operation & PP_PARAM_INTERLACED) &&
578                metadata->interlaced) {
579            ovutils::setMdpFlags(mdpFlags,
580                    ovutils::OV_MDP_DEINTERLACE);
581        }
582        //Pre-rotation will be used using rotator.
583        if(transform & HWC_TRANSFORM_ROT_90) {
584            ovutils::setMdpFlags(mdpFlags,
585                    ovutils::OV_MDP_SOURCE_ROTATED_90);
586        }
587    }
588
589    //No 90 component and no rot-downscale then flips done by MDP
590    //If we use rot then it might as well do flips
591    if(!(layer->transform & HWC_TRANSFORM_ROT_90) && !rotDownscale) {
592        if(layer->transform & HWC_TRANSFORM_FLIP_H) {
593            ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_FLIP_H);
594        }
595
596        if(layer->transform & HWC_TRANSFORM_FLIP_V) {
597            ovutils::setMdpFlags(mdpFlags,  ovutils::OV_MDP_FLIP_V);
598        }
599    }
600}
601
602static inline int configRotator(Rotator *rot, const Whf& whf,
603        const eMdpFlags& mdpFlags, const eTransform& orient,
604        const int& downscale) {
605    rot->setSource(whf);
606    rot->setFlags(mdpFlags);
607    rot->setTransform(orient);
608    rot->setDownscale(downscale);
609    if(!rot->commit()) return -1;
610    return 0;
611}
612
613static inline int configMdp(Overlay *ov, const PipeArgs& parg,
614        const eTransform& orient, const hwc_rect_t& crop,
615        const hwc_rect_t& pos, const eDest& dest) {
616    ov->setSource(parg, dest);
617    ov->setTransform(orient, dest);
618
619    int crop_w = crop.right - crop.left;
620    int crop_h = crop.bottom - crop.top;
621    Dim dcrop(crop.left, crop.top, crop_w, crop_h);
622    ov->setCrop(dcrop, dest);
623
624    int posW = pos.right - pos.left;
625    int posH = pos.bottom - pos.top;
626    Dim position(pos.left, pos.top, posW, posH);
627    ov->setPosition(position, dest);
628
629    if (!ov->commit(dest)) {
630        return -1;
631    }
632    return 0;
633}
634
635static inline void updateSource(eTransform& orient, Whf& whf,
636        hwc_rect_t& crop) {
637    Dim srcCrop(crop.left, crop.top,
638            crop.right - crop.left,
639            crop.bottom - crop.top);
640    //getMdpOrient will switch the flips if the source is 90 rotated.
641    //Clients in Android dont factor in 90 rotation while deciding the flip.
642    orient = static_cast<eTransform>(ovutils::getMdpOrient(orient));
643    preRotateSource(orient, whf, srcCrop);
644    crop.left = srcCrop.x;
645    crop.top = srcCrop.y;
646    crop.right = srcCrop.x + srcCrop.w;
647    crop.bottom = srcCrop.y + srcCrop.h;
648}
649
650int configureLowRes(hwc_context_t *ctx, hwc_layer_1_t *layer,
651        const int& dpy, eMdpFlags& mdpFlags, const eZorder& z,
652        const eIsFg& isFg, const eDest& dest, Rotator **rot) {
653
654    private_handle_t *hnd = (private_handle_t *)layer->handle;
655    if(!hnd) {
656        ALOGE("%s: layer handle is NULL", __FUNCTION__);
657        return -1;
658    }
659
660    hwc_rect_t crop = layer->sourceCrop;
661    hwc_rect_t dst = layer->displayFrame;
662    int transform = layer->transform;
663    eTransform orient = static_cast<eTransform>(transform);
664    int downscale = 0;
665    int rotFlags = ovutils::ROT_FLAGS_NONE;
666    Whf whf(hnd->width, hnd->height,
667            getMdpFormat(hnd->format), hnd->size);
668
669    if(isYuvBuffer(hnd) && ctx->mMDP.version >= qdutils::MDP_V4_2 &&
670                ctx->mMDP.version < qdutils::MDSS_V5) {
671        downscale = getDownscaleFactor(
672                crop.right - crop.left,
673                crop.bottom - crop.top,
674                dst.right - dst.left,
675                dst.bottom - dst.top);
676        if(downscale) {
677            rotFlags = ROT_DOWNSCALE_ENABLED;
678        }
679    }
680
681    setMdpFlags(layer, mdpFlags, downscale);
682    trimLayer(ctx, dpy, transform, crop, dst);
683
684    if(isYuvBuffer(hnd) && //if 90 component or downscale, use rot
685            ((transform & HWC_TRANSFORM_ROT_90) || downscale)) {
686        *rot = ctx->mRotMgr->getNext();
687        if(*rot == NULL) return -1;
688        //Configure rotator for pre-rotation
689        if(configRotator(*rot, whf, mdpFlags, orient, downscale) < 0)
690            return -1;
691        whf.format = (*rot)->getDstFormat();
692        updateSource(orient, whf, crop);
693        rotFlags |= ovutils::ROT_PREROTATED;
694    }
695
696    //For the mdp, since either we are pre-rotating or MDP does flips
697    orient = OVERLAY_TRANSFORM_0;
698    transform = 0;
699
700    PipeArgs parg(mdpFlags, whf, z, isFg, static_cast<eRotFlags>(rotFlags));
701    if(configMdp(ctx->mOverlay, parg, orient, crop, dst, dest) < 0) {
702        ALOGE("%s: commit failed for low res panel", __FUNCTION__);
703        return -1;
704    }
705    return 0;
706}
707
708int configureHighRes(hwc_context_t *ctx, hwc_layer_1_t *layer,
709        const int& dpy, eMdpFlags& mdpFlagsL, const eZorder& z,
710        const eIsFg& isFg, const eDest& lDest, const eDest& rDest,
711        Rotator **rot) {
712    private_handle_t *hnd = (private_handle_t *)layer->handle;
713    if(!hnd) {
714        ALOGE("%s: layer handle is NULL", __FUNCTION__);
715        return -1;
716    }
717
718    int hw_w = ctx->dpyAttr[dpy].xres;
719    int hw_h = ctx->dpyAttr[dpy].yres;
720    hwc_rect_t crop = layer->sourceCrop;
721    hwc_rect_t dst = layer->displayFrame;
722    int transform = layer->transform;
723    eTransform orient = static_cast<eTransform>(transform);
724    const int downscale = 0;
725    int rotFlags = ROT_FLAGS_NONE;
726
727    Whf whf(hnd->width, hnd->height,
728            getMdpFormat(hnd->format), hnd->size);
729
730    setMdpFlags(layer, mdpFlagsL);
731    trimLayer(ctx, dpy, transform, crop, dst);
732
733    if(isYuvBuffer(hnd) && (transform & HWC_TRANSFORM_ROT_90)) {
734        (*rot) = ctx->mRotMgr->getNext();
735        if((*rot) == NULL) return -1;
736        //Configure rotator for pre-rotation
737        if(configRotator(*rot, whf, mdpFlagsL, orient, downscale) < 0)
738            return -1;
739        whf.format = (*rot)->getDstFormat();
740        updateSource(orient, whf, crop);
741        rotFlags |= ROT_PREROTATED;
742    }
743
744    eMdpFlags mdpFlagsR = mdpFlagsL;
745    setMdpFlags(mdpFlagsR, OV_MDSS_MDP_RIGHT_MIXER);
746
747    hwc_rect_t tmp_cropL, tmp_dstL;
748    hwc_rect_t tmp_cropR, tmp_dstR;
749
750    if(lDest != OV_INVALID) {
751        tmp_cropL = crop;
752        tmp_dstL = dst;
753        hwc_rect_t scissor = {0, 0, hw_w/2, hw_h };
754        qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
755    }
756    if(rDest != OV_INVALID) {
757        tmp_cropR = crop;
758        tmp_dstR = dst;
759        hwc_rect_t scissor = {hw_w/2, 0, hw_w, hw_h };
760        qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
761    }
762
763    //When buffer is flipped, contents of mixer config also needs to swapped.
764    //Not needed if the layer is confined to one half of the screen.
765    //If rotator has been used then it has also done the flips, so ignore them.
766    if((orient & OVERLAY_TRANSFORM_FLIP_V) && lDest != OV_INVALID
767            && rDest != OV_INVALID && rot == NULL) {
768        hwc_rect_t new_cropR;
769        new_cropR.left = tmp_cropL.left;
770        new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
771
772        hwc_rect_t new_cropL;
773        new_cropL.left  = new_cropR.right;
774        new_cropL.right = tmp_cropR.right;
775
776        tmp_cropL.left =  new_cropL.left;
777        tmp_cropL.right =  new_cropL.right;
778
779        tmp_cropR.left = new_cropR.left;
780        tmp_cropR.right =  new_cropR.right;
781
782    }
783
784    //For the mdp, since either we are pre-rotating or MDP does flips
785    orient = OVERLAY_TRANSFORM_0;
786    transform = 0;
787
788    //configure left mixer
789    if(lDest != OV_INVALID) {
790        PipeArgs pargL(mdpFlagsL, whf, z, isFg,
791                static_cast<eRotFlags>(rotFlags));
792        if(configMdp(ctx->mOverlay, pargL, orient,
793                tmp_cropL, tmp_dstL, lDest) < 0) {
794            ALOGE("%s: commit failed for left mixer config", __FUNCTION__);
795            return -1;
796        }
797    }
798
799    //configure right mixer
800    if(rDest != OV_INVALID) {
801        PipeArgs pargR(mdpFlagsR, whf, z, isFg,
802                static_cast<eRotFlags>(rotFlags));
803        tmp_dstR.right = tmp_dstR.right - tmp_dstR.left;
804        tmp_dstR.left = 0;
805        if(configMdp(ctx->mOverlay, pargR, orient,
806                tmp_cropR, tmp_dstR, rDest) < 0) {
807            ALOGE("%s: commit failed for right mixer config", __FUNCTION__);
808            return -1;
809        }
810    }
811
812    return 0;
813}
814
815void LayerCache::resetLayerCache(int num) {
816    for(uint32_t i = 0; i < MAX_NUM_LAYERS; i++) {
817        hnd[i] = NULL;
818    }
819    numHwLayers = num;
820}
821
822void LayerCache::updateLayerCache(hwc_display_contents_1_t* list) {
823
824    int numFbLayers = 0;
825    int numCacheableLayers = 0;
826
827    canUseLayerCache = false;
828    //Bail if geometry changed or num of layers changed
829    if(list->flags & HWC_GEOMETRY_CHANGED ||
830       list->numHwLayers != numHwLayers ) {
831        resetLayerCache(list->numHwLayers);
832        return;
833    }
834
835    for(uint32_t i = 0; i < list->numHwLayers; i++) {
836        //Bail on skip layers
837        if(list->hwLayers[i].flags & HWC_SKIP_LAYER) {
838            resetLayerCache(list->numHwLayers);
839            return;
840        }
841
842        if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER) {
843            numFbLayers++;
844            if(hnd[i] == NULL) {
845                hnd[i] = list->hwLayers[i].handle;
846            } else if (hnd[i] ==
847                       list->hwLayers[i].handle) {
848                numCacheableLayers++;
849            } else {
850                hnd[i] = NULL;
851                return;
852            }
853        } else {
854            hnd[i] = NULL;
855        }
856    }
857    if(numFbLayers == numCacheableLayers)
858        canUseLayerCache = true;
859
860    //XXX: The marking part is separate, if MDP comp wants
861    // to use it in the future. Right now getting MDP comp
862    // to use this is more trouble than it is worth.
863    markCachedLayersAsOverlay(list);
864}
865
866void LayerCache::markCachedLayersAsOverlay(hwc_display_contents_1_t* list) {
867    //This optimization only works if ALL the layer handles
868    //that were on the framebuffer didn't change.
869    if(canUseLayerCache){
870        for(uint32_t i = 0; i < list->numHwLayers; i++) {
871            if (list->hwLayers[i].handle &&
872                list->hwLayers[i].handle == hnd[i] &&
873                list->hwLayers[i].compositionType != HWC_FRAMEBUFFER_TARGET)
874            {
875                list->hwLayers[i].compositionType = HWC_OVERLAY;
876            }
877        }
878    }
879}
880
881};//namespace qhwc
882