hwc_utils.cpp revision d706f8d6183a49fd5f48b642cbbd0c8a868fc830
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 * Copyright (C) 2012-2014, 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 ATRACE_TAG (ATRACE_TAG_GRAPHICS | ATRACE_TAG_HAL)
21#define HWC_UTILS_DEBUG 0
22#include <math.h>
23#include <sys/ioctl.h>
24#include <linux/fb.h>
25#include <binder/IServiceManager.h>
26#include <EGL/egl.h>
27#include <cutils/properties.h>
28#include <utils/Trace.h>
29#include <gralloc_priv.h>
30#include <overlay.h>
31#include <overlayRotator.h>
32#include <overlayWriteback.h>
33#include "hwc_utils.h"
34#include "hwc_mdpcomp.h"
35#include "hwc_fbupdate.h"
36#include "hwc_ad.h"
37#include "mdp_version.h"
38#include "hwc_copybit.h"
39#include "hwc_dump_layers.h"
40#include "hwc_vpuclient.h"
41#include "external.h"
42#include "virtual.h"
43#include "hwc_qclient.h"
44#include "QService.h"
45#include "comptype.h"
46#include "hwc_virtual.h"
47
48using namespace qClient;
49using namespace qService;
50using namespace android;
51using namespace overlay;
52using namespace overlay::utils;
53namespace ovutils = overlay::utils;
54
55namespace qhwc {
56
57bool isValidResolution(hwc_context_t *ctx, uint32_t xres, uint32_t yres)
58{
59    return !((xres > qdutils::MAX_DISPLAY_DIM &&
60                !isDisplaySplit(ctx, HWC_DISPLAY_PRIMARY)) ||
61            (xres < MIN_DISPLAY_XRES || yres < MIN_DISPLAY_YRES));
62}
63
64void changeResolution(hwc_context_t *ctx, int xres_orig, int yres_orig) {
65    //Store original display resolution.
66    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres_orig = xres_orig;
67    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres_orig = yres_orig;
68    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].customFBSize = false;
69
70    char property[PROPERTY_VALUE_MAX] = {'\0'};
71    char *yptr = NULL;
72    if (property_get("debug.hwc.fbsize", property, NULL) > 0) {
73        yptr = strcasestr(property,"x");
74        int xres = atoi(property);
75        int yres = atoi(yptr + 1);
76        if (isValidResolution(ctx,xres,yres) &&
77                 xres != xres_orig && yres != yres_orig) {
78            ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres = xres;
79            ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres = yres;
80            ctx->dpyAttr[HWC_DISPLAY_PRIMARY].customFBSize = true;
81        }
82    }
83}
84
85static int openFramebufferDevice(hwc_context_t *ctx)
86{
87    struct fb_fix_screeninfo finfo;
88    struct fb_var_screeninfo info;
89
90    int fb_fd = openFb(HWC_DISPLAY_PRIMARY);
91    if(fb_fd < 0) {
92        ALOGE("%s: Error Opening FB : %s", __FUNCTION__, strerror(errno));
93        return -errno;
94    }
95
96    if (ioctl(fb_fd, FBIOGET_VSCREENINFO, &info) == -1) {
97        ALOGE("%s:Error in ioctl FBIOGET_VSCREENINFO: %s", __FUNCTION__,
98                                                       strerror(errno));
99        close(fb_fd);
100        return -errno;
101    }
102
103    if (int(info.width) <= 0 || int(info.height) <= 0) {
104        // the driver doesn't return that information
105        // default to 160 dpi
106        info.width  = ((info.xres * 25.4f)/160.0f + 0.5f);
107        info.height = ((info.yres * 25.4f)/160.0f + 0.5f);
108    }
109
110    float xdpi = (info.xres * 25.4f) / info.width;
111    float ydpi = (info.yres * 25.4f) / info.height;
112
113#ifdef MSMFB_METADATA_GET
114    struct msmfb_metadata metadata;
115    memset(&metadata, 0 , sizeof(metadata));
116    metadata.op = metadata_op_frame_rate;
117
118    if (ioctl(fb_fd, MSMFB_METADATA_GET, &metadata) == -1) {
119        ALOGE("%s:Error retrieving panel frame rate: %s", __FUNCTION__,
120                                                      strerror(errno));
121        close(fb_fd);
122        return -errno;
123    }
124
125    float fps  = metadata.data.panel_frame_rate;
126#else
127    //XXX: Remove reserved field usage on all baselines
128    //The reserved[3] field is used to store FPS by the driver.
129    float fps  = info.reserved[3] & 0xFF;
130#endif
131
132    if (ioctl(fb_fd, FBIOGET_FSCREENINFO, &finfo) == -1) {
133        ALOGE("%s:Error in ioctl FBIOGET_FSCREENINFO: %s", __FUNCTION__,
134                                                       strerror(errno));
135        close(fb_fd);
136        return -errno;
137    }
138
139    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd = fb_fd;
140    //xres, yres may not be 32 aligned
141    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].stride = finfo.line_length /(info.xres/8);
142    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres = info.xres;
143    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres = info.yres;
144    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xdpi = xdpi;
145    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].ydpi = ydpi;
146    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].vsync_period = 1000000000l / fps;
147
148    //To change resolution of primary display
149    changeResolution(ctx, info.xres, info.yres);
150
151    //Unblank primary on first boot
152    if(ioctl(fb_fd, FBIOBLANK,FB_BLANK_UNBLANK) < 0) {
153        ALOGE("%s: Failed to unblank display", __FUNCTION__);
154        return -errno;
155    }
156    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].isActive = true;
157
158    return 0;
159}
160
161void initContext(hwc_context_t *ctx)
162{
163    openFramebufferDevice(ctx);
164    ctx->mMDP.version = qdutils::MDPVersion::getInstance().getMDPVersion();
165    ctx->mMDP.hasOverlay = qdutils::MDPVersion::getInstance().hasOverlay();
166    ctx->mMDP.panel = qdutils::MDPVersion::getInstance().getPanelType();
167    overlay::Overlay::initOverlay();
168    ctx->mOverlay = overlay::Overlay::getInstance();
169    ctx->mRotMgr = RotMgr::getInstance();
170
171    //Is created and destroyed only once for primary
172    //For external it could get created and destroyed multiple times depending
173    //on what external we connect to.
174    ctx->mFBUpdate[HWC_DISPLAY_PRIMARY] =
175        IFBUpdate::getObject(ctx, HWC_DISPLAY_PRIMARY);
176
177    // Check if the target supports copybit compostion (dyn/mdp) to
178    // decide if we need to open the copybit module.
179    int compositionType =
180        qdutils::QCCompositionType::getInstance().getCompositionType();
181
182    // Only MDP copybit is used
183    if ((compositionType & (qdutils::COMPOSITION_TYPE_DYN |
184            qdutils::COMPOSITION_TYPE_MDP)) &&
185            (qdutils::MDPVersion::getInstance().getMDPVersion() ==
186            qdutils::MDP_V3_0_4)) {
187        ctx->mCopyBit[HWC_DISPLAY_PRIMARY] = new CopyBit(ctx,
188                                                         HWC_DISPLAY_PRIMARY);
189    }
190
191    ctx->mExtDisplay = new ExternalDisplay(ctx);
192    ctx->mVirtualDisplay = new VirtualDisplay(ctx);
193    ctx->mVirtualonExtActive = false;
194    ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].isActive = false;
195    ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].connected = false;
196    ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].isActive = false;
197    ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].connected = false;
198    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].mDownScaleMode= false;
199    ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].mDownScaleMode = false;
200    ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].mDownScaleMode = false;
201
202    ctx->mMDPComp[HWC_DISPLAY_PRIMARY] =
203         MDPComp::getObject(ctx, HWC_DISPLAY_PRIMARY);
204    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].connected = true;
205    ctx->mHWCVirtual = HWCVirtualBase::getObject();
206
207    for (uint32_t i = 0; i < HWC_NUM_DISPLAY_TYPES; i++) {
208        ctx->mHwcDebug[i] = new HwcDebug(i);
209        ctx->mLayerRotMap[i] = new LayerRotMap();
210        ctx->mAnimationState[i] = ANIMATION_STOPPED;
211        ctx->dpyAttr[i].mActionSafePresent = false;
212        ctx->dpyAttr[i].mAsWidthRatio = 0;
213        ctx->dpyAttr[i].mAsHeightRatio = 0;
214    }
215
216    MDPComp::init(ctx);
217    ctx->mAD = new AssertiveDisplay(ctx);
218
219    ctx->vstate.enable = false;
220    ctx->vstate.fakevsync = false;
221    ctx->mExtOrientation = 0;
222    ctx->numActiveDisplays = 1;
223
224    //Right now hwc starts the service but anybody could do it, or it could be
225    //independent process as well.
226    QService::init();
227    sp<IQClient> client = new QClient(ctx);
228    interface_cast<IQService>(
229            defaultServiceManager()->getService(
230            String16("display.qservice")))->connect(client);
231
232    // Initialize device orientation to its default orientation
233    ctx->deviceOrientation = 0;
234    ctx->mBufferMirrorMode = false;
235#ifdef VPU_TARGET
236    ctx->mVPUClient = new VPUClient();
237#endif
238
239    ALOGI("Initializing Qualcomm Hardware Composer");
240    ALOGI("MDP version: %d", ctx->mMDP.version);
241}
242
243void closeContext(hwc_context_t *ctx)
244{
245    if(ctx->mOverlay) {
246        delete ctx->mOverlay;
247        ctx->mOverlay = NULL;
248    }
249
250    if(ctx->mRotMgr) {
251        delete ctx->mRotMgr;
252        ctx->mRotMgr = NULL;
253    }
254
255    for(int i = 0; i < HWC_NUM_DISPLAY_TYPES; i++) {
256        if(ctx->mCopyBit[i]) {
257            delete ctx->mCopyBit[i];
258            ctx->mCopyBit[i] = NULL;
259        }
260    }
261
262    if(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd) {
263        close(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd);
264        ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd = -1;
265    }
266
267    if(ctx->mExtDisplay) {
268        delete ctx->mExtDisplay;
269        ctx->mExtDisplay = NULL;
270    }
271
272#ifdef VPU_TARGET
273    if(ctx->mVPUClient) {
274        delete ctx->mVPUClient;
275    }
276#endif
277
278    for(int i = 0; i < HWC_NUM_DISPLAY_TYPES; i++) {
279        if(ctx->mFBUpdate[i]) {
280            delete ctx->mFBUpdate[i];
281            ctx->mFBUpdate[i] = NULL;
282        }
283        if(ctx->mMDPComp[i]) {
284            delete ctx->mMDPComp[i];
285            ctx->mMDPComp[i] = NULL;
286        }
287        if(ctx->mHwcDebug[i]) {
288            delete ctx->mHwcDebug[i];
289            ctx->mHwcDebug[i] = NULL;
290        }
291        if(ctx->mLayerRotMap[i]) {
292            delete ctx->mLayerRotMap[i];
293            ctx->mLayerRotMap[i] = NULL;
294        }
295    }
296    if(ctx->mHWCVirtual) {
297        delete ctx->mHWCVirtual;
298        ctx->mHWCVirtual = NULL;
299    }
300    if(ctx->mAD) {
301        delete ctx->mAD;
302        ctx->mAD = NULL;
303    }
304
305
306}
307
308
309void dumpsys_log(android::String8& buf, const char* fmt, ...)
310{
311    va_list varargs;
312    va_start(varargs, fmt);
313    buf.appendFormatV(fmt, varargs);
314    va_end(varargs);
315}
316
317int getExtOrientation(hwc_context_t* ctx) {
318    int extOrient = ctx->mExtOrientation;
319    if(ctx->mBufferMirrorMode)
320        extOrient = getMirrorModeOrientation(ctx);
321    return extOrient;
322}
323
324/* Calculates the destination position based on the action safe rectangle */
325void getActionSafePosition(hwc_context_t *ctx, int dpy, hwc_rect_t& rect) {
326    // Position
327    int x = rect.left, y = rect.top;
328    int w = rect.right - rect.left;
329    int h = rect.bottom - rect.top;
330
331    if(!ctx->dpyAttr[dpy].mActionSafePresent)
332        return;
333   // Read action safe properties
334    int asWidthRatio = ctx->dpyAttr[dpy].mAsWidthRatio;
335    int asHeightRatio = ctx->dpyAttr[dpy].mAsHeightRatio;
336
337    float wRatio = 1.0;
338    float hRatio = 1.0;
339    float xRatio = 1.0;
340    float yRatio = 1.0;
341
342    int fbWidth = ctx->dpyAttr[dpy].xres;
343    int fbHeight = ctx->dpyAttr[dpy].yres;
344    if(ctx->dpyAttr[dpy].mDownScaleMode) {
345        // if downscale Mode is enabled for external, need to query
346        // the actual width and height, as that is the physical w & h
347         ctx->mExtDisplay->getAttributes(fbWidth, fbHeight);
348    }
349
350
351    // Since external is rotated 90, need to swap width/height
352    int extOrient = getExtOrientation(ctx);
353
354    if(extOrient & HWC_TRANSFORM_ROT_90)
355        swap(fbWidth, fbHeight);
356
357    float asX = 0;
358    float asY = 0;
359    float asW = fbWidth;
360    float asH = fbHeight;
361
362    // based on the action safe ratio, get the Action safe rectangle
363    asW = fbWidth * (1.0f -  asWidthRatio / 100.0f);
364    asH = fbHeight * (1.0f -  asHeightRatio / 100.0f);
365    asX = (fbWidth - asW) / 2;
366    asY = (fbHeight - asH) / 2;
367
368    // calculate the position ratio
369    xRatio = (float)x/fbWidth;
370    yRatio = (float)y/fbHeight;
371    wRatio = (float)w/fbWidth;
372    hRatio = (float)h/fbHeight;
373
374    //Calculate the position...
375    x = (xRatio * asW) + asX;
376    y = (yRatio * asH) + asY;
377    w = (wRatio * asW);
378    h = (hRatio * asH);
379
380    // Convert it back to hwc_rect_t
381    rect.left = x;
382    rect.top = y;
383    rect.right = w + rect.left;
384    rect.bottom = h + rect.top;
385
386    return;
387}
388
389/* Calculates the aspect ratio for based on src & dest */
390void getAspectRatioPosition(int destWidth, int destHeight, int srcWidth,
391                                int srcHeight, hwc_rect_t& rect) {
392   int x =0, y =0;
393
394   if (srcWidth * destHeight > destWidth * srcHeight) {
395        srcHeight = destWidth * srcHeight / srcWidth;
396        srcWidth = destWidth;
397    } else if (srcWidth * destHeight < destWidth * srcHeight) {
398        srcWidth = destHeight * srcWidth / srcHeight;
399        srcHeight = destHeight;
400    } else {
401        srcWidth = destWidth;
402        srcHeight = destHeight;
403    }
404    if (srcWidth > destWidth) srcWidth = destWidth;
405    if (srcHeight > destHeight) srcHeight = destHeight;
406    x = (destWidth - srcWidth) / 2;
407    y = (destHeight - srcHeight) / 2;
408    ALOGD_IF(HWC_UTILS_DEBUG, "%s: AS Position: x = %d, y = %d w = %d h = %d",
409             __FUNCTION__, x, y, srcWidth , srcHeight);
410    // Convert it back to hwc_rect_t
411    rect.left = x;
412    rect.top = y;
413    rect.right = srcWidth + rect.left;
414    rect.bottom = srcHeight + rect.top;
415}
416
417// This function gets the destination position for Seconday display
418// based on the position and aspect ratio with orientation
419void getAspectRatioPosition(hwc_context_t* ctx, int dpy, int extOrientation,
420                            hwc_rect_t& inRect, hwc_rect_t& outRect) {
421    hwc_rect_t viewFrame = ctx->mViewFrame[dpy];
422    // Physical display resolution
423    float fbWidth  = ctx->dpyAttr[dpy].xres;
424    float fbHeight = ctx->dpyAttr[dpy].yres;
425    //display position(x,y,w,h) in correct aspectratio after rotation
426    int xPos = 0;
427    int yPos = 0;
428    float width = fbWidth;
429    float height = fbHeight;
430    // Width/Height used for calculation, after rotation
431    float actualWidth = fbWidth;
432    float actualHeight = fbHeight;
433
434    float wRatio = 1.0;
435    float hRatio = 1.0;
436    float xRatio = 1.0;
437    float yRatio = 1.0;
438    hwc_rect_t rect = {0, 0, (int)fbWidth, (int)fbHeight};
439
440    Dim inPos(inRect.left, inRect.top, inRect.right - inRect.left,
441                inRect.bottom - inRect.top);
442    Dim outPos(outRect.left, outRect.top, outRect.right - outRect.left,
443                outRect.bottom - outRect.top);
444
445    Whf whf(fbWidth, fbHeight, 0);
446    eTransform extorient = static_cast<eTransform>(extOrientation);
447    // To calculate the destination co-ordinates in the new orientation
448    preRotateSource(extorient, whf, inPos);
449
450    if(extOrientation & HAL_TRANSFORM_ROT_90) {
451        // Swap width/height for input position
452        swapWidthHeight(actualWidth, actualHeight);
453        getAspectRatioPosition(fbWidth, fbHeight, (int)actualWidth,
454                               (int)actualHeight, rect);
455        xPos = rect.left;
456        yPos = rect.top;
457        width = rect.right - rect.left;
458        height = rect.bottom - rect.top;
459        // swap viewframe coordinates for 90 degree rotation.
460        swap(viewFrame.left, viewFrame.top);
461        swap(viewFrame.right, viewFrame.bottom);
462    }
463    // if viewframe left and top coordinates are non zero value then exclude it
464    // during the computation of xRatio and yRatio
465    xRatio = (inPos.x - viewFrame.left)/actualWidth;
466    yRatio = (inPos.y - viewFrame.top)/actualHeight;
467    // Use viewframe width and height to compute wRatio and hRatio.
468    wRatio = (float)inPos.w/(float)(viewFrame.right - viewFrame.left);
469    hRatio = (float)inPos.h/(float)(viewFrame.bottom - viewFrame.top);
470
471
472    //Calculate the position...
473    outPos.x = (xRatio * width) + xPos;
474    outPos.y = (yRatio * height) + yPos;
475    outPos.w = wRatio * width;
476    outPos.h = hRatio * height;
477    ALOGD_IF(HWC_UTILS_DEBUG, "%s: Calculated AspectRatio Position: x = %d,"
478                 "y = %d w = %d h = %d", __FUNCTION__, outPos.x, outPos.y,
479                 outPos.w, outPos.h);
480
481    // For sidesync, the dest fb will be in portrait orientation, and the crop
482    // will be updated to avoid the black side bands, and it will be upscaled
483    // to fit the dest RB, so recalculate
484    // the position based on the new width and height
485    if ((extOrientation & HWC_TRANSFORM_ROT_90) &&
486                        isOrientationPortrait(ctx)) {
487        hwc_rect_t r;
488        //Calculate the position
489        xRatio = (outPos.x - xPos)/width;
490        // GetaspectRatio -- tricky to get the correct aspect ratio
491        // But we need to do this.
492        getAspectRatioPosition(width, height, width, height, r);
493        xPos = r.left;
494        yPos = r.top;
495        float tempWidth = r.right - r.left;
496        float tempHeight = r.bottom - r.top;
497        yRatio = yPos/height;
498        wRatio = outPos.w/width;
499        hRatio = tempHeight/height;
500
501        //Map the coordinates back to Framebuffer domain
502        outPos.x = (xRatio * fbWidth);
503        outPos.y = (yRatio * fbHeight);
504        outPos.w = wRatio * fbWidth;
505        outPos.h = hRatio * fbHeight;
506
507        ALOGD_IF(HWC_UTILS_DEBUG, "%s: Calculated AspectRatio for device in"
508                 "portrait: x = %d,y = %d w = %d h = %d", __FUNCTION__,
509                 outPos.x, outPos.y,
510                 outPos.w, outPos.h);
511    }
512    if(ctx->dpyAttr[dpy].mDownScaleMode) {
513        int extW, extH;
514        if(dpy == HWC_DISPLAY_EXTERNAL)
515            ctx->mExtDisplay->getAttributes(extW, extH);
516        else
517            ctx->mVirtualDisplay->getAttributes(extW, extH);
518        fbWidth  = ctx->dpyAttr[dpy].xres;
519        fbHeight = ctx->dpyAttr[dpy].yres;
520        //Calculate the position...
521        xRatio = outPos.x/fbWidth;
522        yRatio = outPos.y/fbHeight;
523        wRatio = outPos.w/fbWidth;
524        hRatio = outPos.h/fbHeight;
525
526        outPos.x = xRatio * extW;
527        outPos.y = yRatio * extH;
528        outPos.w = wRatio * extW;
529        outPos.h = hRatio * extH;
530    }
531    // Convert Dim to hwc_rect_t
532    outRect.left = outPos.x;
533    outRect.top = outPos.y;
534    outRect.right = outPos.x + outPos.w;
535    outRect.bottom = outPos.y + outPos.h;
536
537    return;
538}
539
540bool isPrimaryPortrait(hwc_context_t *ctx) {
541    int fbWidth = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres;
542    int fbHeight = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres;
543    if(fbWidth < fbHeight) {
544        return true;
545    }
546    return false;
547}
548
549bool isOrientationPortrait(hwc_context_t *ctx) {
550    if(isPrimaryPortrait(ctx)) {
551        return !(ctx->deviceOrientation & 0x1);
552    }
553    return (ctx->deviceOrientation & 0x1);
554}
555
556void calcExtDisplayPosition(hwc_context_t *ctx,
557                               private_handle_t *hnd,
558                               int dpy,
559                               hwc_rect_t& sourceCrop,
560                               hwc_rect_t& displayFrame,
561                               int& transform,
562                               ovutils::eTransform& orient) {
563    // Swap width and height when there is a 90deg transform
564    int extOrient = getExtOrientation(ctx);
565    if(dpy && !qdutils::MDPVersion::getInstance().is8x26()) {
566        if(!isYuvBuffer(hnd)) {
567            if(extOrient & HWC_TRANSFORM_ROT_90) {
568                int dstWidth = ctx->dpyAttr[dpy].xres;
569                int dstHeight = ctx->dpyAttr[dpy].yres;;
570                int srcWidth = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres;
571                int srcHeight = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres;
572                if(!isPrimaryPortrait(ctx)) {
573                    swap(srcWidth, srcHeight);
574                }                    // Get Aspect Ratio for external
575                getAspectRatioPosition(dstWidth, dstHeight, srcWidth,
576                                    srcHeight, displayFrame);
577                // Crop - this is needed, because for sidesync, the dest fb will
578                // be in portrait orientation, so update the crop to not show the
579                // black side bands.
580                if (isOrientationPortrait(ctx)) {
581                    sourceCrop = displayFrame;
582                    displayFrame.left = 0;
583                    displayFrame.top = 0;
584                    displayFrame.right = dstWidth;
585                    displayFrame.bottom = dstHeight;
586                }
587            }
588            if(ctx->dpyAttr[dpy].mDownScaleMode) {
589                int extW, extH;
590                // if downscale is enabled, map the co-ordinates to new
591                // domain(downscaled)
592                float fbWidth  = ctx->dpyAttr[dpy].xres;
593                float fbHeight = ctx->dpyAttr[dpy].yres;
594                // query MDP configured attributes
595                if(dpy == HWC_DISPLAY_EXTERNAL)
596                    ctx->mExtDisplay->getAttributes(extW, extH);
597                else
598                    ctx->mVirtualDisplay->getAttributes(extW, extH);
599                //Calculate the ratio...
600                float wRatio = ((float)extW)/fbWidth;
601                float hRatio = ((float)extH)/fbHeight;
602
603                //convert Dim to hwc_rect_t
604                displayFrame.left *= wRatio;
605                displayFrame.top *= hRatio;
606                displayFrame.right *= wRatio;
607                displayFrame.bottom *= hRatio;
608            }
609        }else {
610            if(extOrient || ctx->dpyAttr[dpy].mDownScaleMode) {
611                getAspectRatioPosition(ctx, dpy, extOrient,
612                                       displayFrame, displayFrame);
613            }
614        }
615        // If there is a external orientation set, use that
616        if(extOrient) {
617            transform = extOrient;
618            orient = static_cast<ovutils::eTransform >(extOrient);
619        }
620        // Calculate the actionsafe dimensions for External(dpy = 1 or 2)
621        getActionSafePosition(ctx, dpy, displayFrame);
622    }
623}
624
625/* Returns the orientation which needs to be set on External for
626 *  SideSync/Buffer Mirrormode
627 */
628int getMirrorModeOrientation(hwc_context_t *ctx) {
629    int extOrientation = 0;
630    int deviceOrientation = ctx->deviceOrientation;
631    if(!isPrimaryPortrait(ctx))
632        deviceOrientation = (deviceOrientation + 1) % 4;
633     if (deviceOrientation == 0)
634         extOrientation = HWC_TRANSFORM_ROT_270;
635     else if (deviceOrientation == 1)//90
636         extOrientation = 0;
637     else if (deviceOrientation == 2)//180
638         extOrientation = HWC_TRANSFORM_ROT_90;
639     else if (deviceOrientation == 3)//270
640         extOrientation = HWC_TRANSFORM_FLIP_V | HWC_TRANSFORM_FLIP_H;
641
642    return extOrientation;
643}
644
645bool isDownscaleRequired(hwc_layer_1_t const* layer) {
646    hwc_rect_t displayFrame  = layer->displayFrame;
647    hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf);
648    int dst_w, dst_h, src_w, src_h;
649    dst_w = displayFrame.right - displayFrame.left;
650    dst_h = displayFrame.bottom - displayFrame.top;
651    src_w = sourceCrop.right - sourceCrop.left;
652    src_h = sourceCrop.bottom - sourceCrop.top;
653
654    if(((src_w > dst_w) || (src_h > dst_h)))
655        return true;
656
657    return false;
658}
659bool needsScaling(hwc_layer_1_t const* layer) {
660    int dst_w, dst_h, src_w, src_h;
661    hwc_rect_t displayFrame  = layer->displayFrame;
662    hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf);
663
664    dst_w = displayFrame.right - displayFrame.left;
665    dst_h = displayFrame.bottom - displayFrame.top;
666    src_w = sourceCrop.right - sourceCrop.left;
667    src_h = sourceCrop.bottom - sourceCrop.top;
668
669    if(((src_w != dst_w) || (src_h != dst_h)))
670        return true;
671
672    return false;
673}
674
675// Checks if layer needs scaling with split
676bool needsScalingWithSplit(hwc_context_t* ctx, hwc_layer_1_t const* layer,
677        const int& dpy) {
678
679    int src_width_l, src_height_l;
680    int src_width_r, src_height_r;
681    int dst_width_l, dst_height_l;
682    int dst_width_r, dst_height_r;
683    int hw_w = ctx->dpyAttr[dpy].xres;
684    int hw_h = ctx->dpyAttr[dpy].yres;
685    hwc_rect_t cropL, dstL, cropR, dstR;
686    const int lSplit = getLeftSplit(ctx, dpy);
687    hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf);
688    hwc_rect_t displayFrame  = layer->displayFrame;
689    private_handle_t *hnd = (private_handle_t *)layer->handle;
690
691    cropL = sourceCrop;
692    dstL = displayFrame;
693    hwc_rect_t scissorL = { 0, 0, lSplit, hw_h };
694    scissorL = getIntersection(ctx->mViewFrame[dpy], scissorL);
695    qhwc::calculate_crop_rects(cropL, dstL, scissorL, 0);
696
697    cropR = sourceCrop;
698    dstR = displayFrame;
699    hwc_rect_t scissorR = { lSplit, 0, hw_w, hw_h };
700    scissorR = getIntersection(ctx->mViewFrame[dpy], scissorR);
701    qhwc::calculate_crop_rects(cropR, dstR, scissorR, 0);
702
703    // Sanitize Crop to stitch
704    sanitizeSourceCrop(cropL, cropR, hnd);
705
706    // Calculate the left dst
707    dst_width_l = dstL.right - dstL.left;
708    dst_height_l = dstL.bottom - dstL.top;
709    src_width_l = cropL.right - cropL.left;
710    src_height_l = cropL.bottom - cropL.top;
711
712    // check if there is any scaling on the left
713    if(((src_width_l != dst_width_l) || (src_height_l != dst_height_l)))
714        return true;
715
716    // Calculate the right dst
717    dst_width_r = dstR.right - dstR.left;
718    dst_height_r = dstR.bottom - dstR.top;
719    src_width_r = cropR.right - cropR.left;
720    src_height_r = cropR.bottom - cropR.top;
721
722    // check if there is any scaling on the right
723    if(((src_width_r != dst_width_r) || (src_height_r != dst_height_r)))
724        return true;
725
726    return false;
727}
728
729bool isAlphaScaled(hwc_layer_1_t const* layer) {
730    if(needsScaling(layer) && isAlphaPresent(layer)) {
731        return true;
732    }
733    return false;
734}
735
736bool isAlphaPresent(hwc_layer_1_t const* layer) {
737    private_handle_t *hnd = (private_handle_t *)layer->handle;
738    if(hnd) {
739        int format = hnd->format;
740        switch(format) {
741        case HAL_PIXEL_FORMAT_RGBA_8888:
742        case HAL_PIXEL_FORMAT_BGRA_8888:
743            // In any more formats with Alpha go here..
744            return true;
745        default : return false;
746        }
747    }
748    return false;
749}
750
751static void trimLayer(hwc_context_t *ctx, const int& dpy, const int& transform,
752        hwc_rect_t& crop, hwc_rect_t& dst) {
753    int hw_w = ctx->dpyAttr[dpy].xres;
754    int hw_h = ctx->dpyAttr[dpy].yres;
755    if(dst.left < 0 || dst.top < 0 ||
756            dst.right > hw_w || dst.bottom > hw_h) {
757        hwc_rect_t scissor = {0, 0, hw_w, hw_h };
758        scissor = getIntersection(ctx->mViewFrame[dpy], scissor);
759        qhwc::calculate_crop_rects(crop, dst, scissor, transform);
760    }
761}
762
763static void trimList(hwc_context_t *ctx, hwc_display_contents_1_t *list,
764        const int& dpy) {
765    for(uint32_t i = 0; i < list->numHwLayers - 1; i++) {
766        hwc_layer_1_t *layer = &list->hwLayers[i];
767        hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
768        trimLayer(ctx, dpy,
769                list->hwLayers[i].transform,
770                (hwc_rect_t&)crop,
771                (hwc_rect_t&)list->hwLayers[i].displayFrame);
772        layer->sourceCropf.left = crop.left;
773        layer->sourceCropf.right = crop.right;
774        layer->sourceCropf.top = crop.top;
775        layer->sourceCropf.bottom = crop.bottom;
776    }
777}
778
779void setListStats(hwc_context_t *ctx,
780        hwc_display_contents_1_t *list, int dpy) {
781    const int prevYuvCount = ctx->listStats[dpy].yuvCount;
782    memset(&ctx->listStats[dpy], 0, sizeof(ListStats));
783    ctx->listStats[dpy].numAppLayers = list->numHwLayers - 1;
784    ctx->listStats[dpy].fbLayerIndex = list->numHwLayers - 1;
785    ctx->listStats[dpy].skipCount = 0;
786    ctx->listStats[dpy].preMultipliedAlpha = false;
787    ctx->listStats[dpy].isSecurePresent = false;
788    ctx->listStats[dpy].yuvCount = 0;
789    char property[PROPERTY_VALUE_MAX];
790    ctx->listStats[dpy].extOnlyLayerIndex = -1;
791    ctx->listStats[dpy].isDisplayAnimating = false;
792    ctx->listStats[dpy].roi = ovutils::Dim(0, 0,
793                      (int)ctx->dpyAttr[dpy].xres, (int)ctx->dpyAttr[dpy].yres);
794    ctx->listStats[dpy].secureUI = false;
795    ctx->listStats[dpy].yuv4k2kCount = 0;
796    ctx->mViewFrame[dpy] = (hwc_rect_t){0, 0, 0, 0};
797    ctx->dpyAttr[dpy].mActionSafePresent = isActionSafePresent(ctx, dpy);
798
799    trimList(ctx, list, dpy);
800    optimizeLayerRects(ctx, list, dpy);
801
802    for (size_t i = 0; i < (size_t)ctx->listStats[dpy].numAppLayers; i++) {
803        hwc_layer_1_t const* layer = &list->hwLayers[i];
804        private_handle_t *hnd = (private_handle_t *)layer->handle;
805
806        // Calculate view frame of each display from the layer displayframe
807        ctx->mViewFrame[dpy] = getUnion(ctx->mViewFrame[dpy],
808                                        layer->displayFrame);
809#ifdef QCOM_BSP
810        if (layer->flags & HWC_SCREENSHOT_ANIMATOR_LAYER) {
811            ctx->listStats[dpy].isDisplayAnimating = true;
812        }
813        if(isSecureDisplayBuffer(hnd)) {
814            ctx->listStats[dpy].secureUI = true;
815        }
816#endif
817        // continue if number of app layers exceeds MAX_NUM_APP_LAYERS
818        if(ctx->listStats[dpy].numAppLayers > MAX_NUM_APP_LAYERS)
819            continue;
820
821        //reset yuv indices
822        ctx->listStats[dpy].yuvIndices[i] = -1;
823        ctx->listStats[dpy].yuv4k2kIndices[i] = -1;
824
825        if (isSecureBuffer(hnd)) {
826            ctx->listStats[dpy].isSecurePresent = true;
827        }
828
829        if (isSkipLayer(&list->hwLayers[i])) {
830            ctx->listStats[dpy].skipCount++;
831        }
832
833        if (UNLIKELY(isYuvBuffer(hnd))) {
834            int& yuvCount = ctx->listStats[dpy].yuvCount;
835            ctx->listStats[dpy].yuvIndices[yuvCount] = i;
836            yuvCount++;
837
838            if(UNLIKELY(is4kx2kYuvBuffer(hnd))){
839                int& yuv4k2kCount = ctx->listStats[dpy].yuv4k2kCount;
840                ctx->listStats[dpy].yuv4k2kIndices[yuv4k2kCount] = i;
841                yuv4k2kCount++;
842            }
843
844            if((layer->transform & HWC_TRANSFORM_ROT_90) &&
845                    canUseRotator(ctx, dpy)) {
846                if( (dpy == HWC_DISPLAY_PRIMARY) &&
847                        ctx->mOverlay->isPipeTypeAttached(OV_MDP_PIPE_DMA)) {
848                    ctx->isPaddingRound = true;
849                }
850                Overlay::setDMAMode(Overlay::DMA_BLOCK_MODE);
851            }
852        }
853        if(layer->blending == HWC_BLENDING_PREMULT)
854            ctx->listStats[dpy].preMultipliedAlpha = true;
855
856
857        if(UNLIKELY(isExtOnly(hnd))){
858            ctx->listStats[dpy].extOnlyLayerIndex = i;
859        }
860    }
861    if(ctx->listStats[dpy].yuvCount > 0) {
862        if (property_get("hw.cabl.yuv", property, NULL) > 0) {
863            if (atoi(property) != 1) {
864                property_set("hw.cabl.yuv", "1");
865            }
866        }
867    } else {
868        if (property_get("hw.cabl.yuv", property, NULL) > 0) {
869            if (atoi(property) != 0) {
870                property_set("hw.cabl.yuv", "0");
871            }
872        }
873    }
874    if(dpy) {
875        //uncomment the below code for testing purpose.
876        /* char value[PROPERTY_VALUE_MAX];
877        property_get("sys.ext_orientation", value, "0");
878        // Assuming the orientation value is in terms of HAL_TRANSFORM,
879        // This needs mapping to HAL, if its in different convention
880        ctx->mExtOrientation = atoi(value); */
881        // Assuming the orientation value is in terms of HAL_TRANSFORM,
882        // This needs mapping to HAL, if its in different convention
883        if(ctx->mExtOrientation || ctx->mBufferMirrorMode) {
884            ALOGD_IF(HWC_UTILS_DEBUG, "%s: ext orientation = %d"
885                     "BufferMirrorMode = %d", __FUNCTION__,
886                     ctx->mExtOrientation, ctx->mBufferMirrorMode);
887            if(ctx->mOverlay->isPipeTypeAttached(OV_MDP_PIPE_DMA)) {
888                ctx->isPaddingRound = true;
889            }
890            Overlay::setDMAMode(Overlay::DMA_BLOCK_MODE);
891        }
892    }
893
894    //The marking of video begin/end is useful on some targets where we need
895    //to have a padding round to be able to shift pipes across mixers.
896    if(prevYuvCount != ctx->listStats[dpy].yuvCount) {
897        ctx->mVideoTransFlag = true;
898    }
899    if(dpy == HWC_DISPLAY_PRIMARY) {
900        ctx->mAD->markDoable(ctx, list);
901    }
902}
903
904
905static void calc_cut(double& leftCutRatio, double& topCutRatio,
906        double& rightCutRatio, double& bottomCutRatio, int orient) {
907    if(orient & HAL_TRANSFORM_FLIP_H) {
908        swap(leftCutRatio, rightCutRatio);
909    }
910    if(orient & HAL_TRANSFORM_FLIP_V) {
911        swap(topCutRatio, bottomCutRatio);
912    }
913    if(orient & HAL_TRANSFORM_ROT_90) {
914        //Anti clock swapping
915        double tmpCutRatio = leftCutRatio;
916        leftCutRatio = topCutRatio;
917        topCutRatio = rightCutRatio;
918        rightCutRatio = bottomCutRatio;
919        bottomCutRatio = tmpCutRatio;
920    }
921}
922
923bool isSecuring(hwc_context_t* ctx, hwc_layer_1_t const* layer) {
924    if((ctx->mMDP.version < qdutils::MDSS_V5) &&
925       (ctx->mMDP.version > qdutils::MDP_V3_0) &&
926        ctx->mSecuring) {
927        return true;
928    }
929    if (isSecureModePolicy(ctx->mMDP.version)) {
930        private_handle_t *hnd = (private_handle_t *)layer->handle;
931        if(ctx->mSecureMode) {
932            if (! isSecureBuffer(hnd)) {
933                ALOGD_IF(HWC_UTILS_DEBUG,"%s:Securing Turning ON ...",
934                         __FUNCTION__);
935                return true;
936            }
937        } else {
938            if (isSecureBuffer(hnd)) {
939                ALOGD_IF(HWC_UTILS_DEBUG,"%s:Securing Turning OFF ...",
940                         __FUNCTION__);
941                return true;
942            }
943        }
944    }
945    return false;
946}
947
948bool isSecureModePolicy(int mdpVersion) {
949    if (mdpVersion < qdutils::MDSS_V5)
950        return true;
951    else
952        return false;
953}
954
955// returns true if Action safe dimensions are set and target supports Actionsafe
956bool isActionSafePresent(hwc_context_t *ctx, int dpy) {
957    // if external supports underscan, do nothing
958    // it will be taken care in the driver
959    if(!dpy || ctx->mExtDisplay->isCEUnderscanSupported())
960        return false;
961
962    char value[PROPERTY_VALUE_MAX];
963    // Read action safe properties
964    property_get("persist.sys.actionsafe.width", value, "0");
965    ctx->dpyAttr[dpy].mAsWidthRatio = atoi(value);
966    property_get("persist.sys.actionsafe.height", value, "0");
967    ctx->dpyAttr[dpy].mAsHeightRatio = atoi(value);
968
969    if(!ctx->dpyAttr[dpy].mAsWidthRatio && !ctx->dpyAttr[dpy].mAsHeightRatio) {
970        //No action safe ratio set, return
971        return false;
972    }
973    return true;
974}
975
976int getBlending(int blending) {
977    switch(blending) {
978    case HWC_BLENDING_NONE:
979        return overlay::utils::OVERLAY_BLENDING_OPAQUE;
980    case HWC_BLENDING_PREMULT:
981        return overlay::utils::OVERLAY_BLENDING_PREMULT;
982    case HWC_BLENDING_COVERAGE :
983    default:
984        return overlay::utils::OVERLAY_BLENDING_COVERAGE;
985    }
986}
987
988//Crops source buffer against destination and FB boundaries
989void calculate_crop_rects(hwc_rect_t& crop, hwc_rect_t& dst,
990                          const hwc_rect_t& scissor, int orient) {
991
992    int& crop_l = crop.left;
993    int& crop_t = crop.top;
994    int& crop_r = crop.right;
995    int& crop_b = crop.bottom;
996    int crop_w = crop.right - crop.left;
997    int crop_h = crop.bottom - crop.top;
998
999    int& dst_l = dst.left;
1000    int& dst_t = dst.top;
1001    int& dst_r = dst.right;
1002    int& dst_b = dst.bottom;
1003    int dst_w = abs(dst.right - dst.left);
1004    int dst_h = abs(dst.bottom - dst.top);
1005
1006    const int& sci_l = scissor.left;
1007    const int& sci_t = scissor.top;
1008    const int& sci_r = scissor.right;
1009    const int& sci_b = scissor.bottom;
1010    int sci_w = abs(sci_r - sci_l);
1011    int sci_h = abs(sci_b - sci_t);
1012
1013    double leftCutRatio = 0.0, rightCutRatio = 0.0, topCutRatio = 0.0,
1014            bottomCutRatio = 0.0;
1015
1016    if(dst_l < sci_l) {
1017        leftCutRatio = (double)(sci_l - dst_l) / (double)dst_w;
1018        dst_l = sci_l;
1019    }
1020
1021    if(dst_r > sci_r) {
1022        rightCutRatio = (double)(dst_r - sci_r) / (double)dst_w;
1023        dst_r = sci_r;
1024    }
1025
1026    if(dst_t < sci_t) {
1027        topCutRatio = (double)(sci_t - dst_t) / (double)dst_h;
1028        dst_t = sci_t;
1029    }
1030
1031    if(dst_b > sci_b) {
1032        bottomCutRatio = (double)(dst_b - sci_b) / (double)dst_h;
1033        dst_b = sci_b;
1034    }
1035
1036    calc_cut(leftCutRatio, topCutRatio, rightCutRatio, bottomCutRatio, orient);
1037    crop_l += crop_w * leftCutRatio;
1038    crop_t += crop_h * topCutRatio;
1039    crop_r -= crop_w * rightCutRatio;
1040    crop_b -= crop_h * bottomCutRatio;
1041}
1042
1043bool areLayersIntersecting(const hwc_layer_1_t* layer1,
1044        const hwc_layer_1_t* layer2) {
1045    hwc_rect_t irect = getIntersection(layer1->displayFrame,
1046            layer2->displayFrame);
1047    return isValidRect(irect);
1048}
1049
1050bool isValidRect(const hwc_rect& rect)
1051{
1052   return ((rect.bottom > rect.top) && (rect.right > rect.left)) ;
1053}
1054
1055/* computes the intersection of two rects */
1056hwc_rect_t getIntersection(const hwc_rect_t& rect1, const hwc_rect_t& rect2)
1057{
1058   hwc_rect_t res;
1059
1060   if(!isValidRect(rect1) || !isValidRect(rect2)){
1061      return (hwc_rect_t){0, 0, 0, 0};
1062   }
1063
1064
1065   res.left = max(rect1.left, rect2.left);
1066   res.top = max(rect1.top, rect2.top);
1067   res.right = min(rect1.right, rect2.right);
1068   res.bottom = min(rect1.bottom, rect2.bottom);
1069
1070   if(!isValidRect(res))
1071      return (hwc_rect_t){0, 0, 0, 0};
1072
1073   return res;
1074}
1075
1076/* computes the union of two rects */
1077hwc_rect_t getUnion(const hwc_rect &rect1, const hwc_rect &rect2)
1078{
1079   hwc_rect_t res;
1080
1081   if(!isValidRect(rect1)){
1082      return rect2;
1083   }
1084
1085   if(!isValidRect(rect2)){
1086      return rect1;
1087   }
1088
1089   res.left = min(rect1.left, rect2.left);
1090   res.top = min(rect1.top, rect2.top);
1091   res.right =  max(rect1.right, rect2.right);
1092   res.bottom =  max(rect1.bottom, rect2.bottom);
1093
1094   return res;
1095}
1096
1097/* Not a geometrical rect deduction. Deducts rect2 from rect1 only if it results
1098 * a single rect */
1099hwc_rect_t deductRect(const hwc_rect_t& rect1, const hwc_rect_t& rect2) {
1100
1101   hwc_rect_t res = rect1;
1102
1103   if((rect1.left == rect2.left) && (rect1.right == rect2.right)) {
1104      if((rect1.top == rect2.top) && (rect2.bottom <= rect1.bottom))
1105         res.top = rect2.bottom;
1106      else if((rect1.bottom == rect2.bottom)&& (rect2.top >= rect1.top))
1107         res.bottom = rect2.top;
1108   }
1109   else if((rect1.top == rect2.top) && (rect1.bottom == rect2.bottom)) {
1110      if((rect1.left == rect2.left) && (rect2.right <= rect1.right))
1111         res.left = rect2.right;
1112      else if((rect1.right == rect2.right)&& (rect2.left >= rect1.left))
1113         res.right = rect2.left;
1114   }
1115   return res;
1116}
1117
1118void optimizeLayerRects(hwc_context_t *ctx,
1119                        const hwc_display_contents_1_t *list, const int& dpy) {
1120    int i=list->numHwLayers-2;
1121    hwc_rect_t irect;
1122    while(i > 0) {
1123
1124        //see if there is no blending required.
1125        //If it is opaque see if we can substract this region from below layers.
1126        if(list->hwLayers[i].blending == HWC_BLENDING_NONE) {
1127            int j= i-1;
1128            hwc_rect_t& topframe =
1129                (hwc_rect_t&)list->hwLayers[i].displayFrame;
1130            while(j >= 0) {
1131               if(!needsScaling(&list->hwLayers[j])) {
1132                  hwc_layer_1_t* layer = (hwc_layer_1_t*)&list->hwLayers[j];
1133                  hwc_rect_t& bottomframe = layer->displayFrame;
1134                  hwc_rect_t bottomCrop =
1135                      integerizeSourceCrop(layer->sourceCropf);
1136                  int transform =layer->transform;
1137
1138                  hwc_rect_t irect = getIntersection(bottomframe, topframe);
1139                  if(isValidRect(irect)) {
1140                     hwc_rect_t dest_rect;
1141                     //if intersection is valid rect, deduct it
1142                     dest_rect  = deductRect(bottomframe, irect);
1143                     qhwc::calculate_crop_rects(bottomCrop, bottomframe,
1144                                                dest_rect, transform);
1145                     //Update layer sourceCropf
1146                     layer->sourceCropf.left = bottomCrop.left;
1147                     layer->sourceCropf.top = bottomCrop.top;
1148                     layer->sourceCropf.right = bottomCrop.right;
1149                     layer->sourceCropf.bottom = bottomCrop.bottom;
1150                  }
1151               }
1152               j--;
1153            }
1154        }
1155        i--;
1156    }
1157}
1158
1159void getNonWormholeRegion(hwc_display_contents_1_t* list,
1160                              hwc_rect_t& nwr)
1161{
1162    uint32_t last = list->numHwLayers - 1;
1163    hwc_rect_t fbDisplayFrame = list->hwLayers[last].displayFrame;
1164    //Initiliaze nwr to first frame
1165    nwr.left =  list->hwLayers[0].displayFrame.left;
1166    nwr.top =  list->hwLayers[0].displayFrame.top;
1167    nwr.right =  list->hwLayers[0].displayFrame.right;
1168    nwr.bottom =  list->hwLayers[0].displayFrame.bottom;
1169
1170    for (uint32_t i = 1; i < last; i++) {
1171        hwc_rect_t displayFrame = list->hwLayers[i].displayFrame;
1172        nwr = getUnion(nwr, displayFrame);
1173    }
1174
1175    //Intersect with the framebuffer
1176    nwr = getIntersection(nwr, fbDisplayFrame);
1177}
1178
1179bool isExternalActive(hwc_context_t* ctx) {
1180    return ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].isActive;
1181}
1182
1183void closeAcquireFds(hwc_display_contents_1_t* list) {
1184    if(LIKELY(list)) {
1185        for(uint32_t i = 0; i < list->numHwLayers; i++) {
1186            //Close the acquireFenceFds
1187            //HWC_FRAMEBUFFER are -1 already by SF, rest we close.
1188            if(list->hwLayers[i].acquireFenceFd >= 0) {
1189                close(list->hwLayers[i].acquireFenceFd);
1190                list->hwLayers[i].acquireFenceFd = -1;
1191            }
1192        }
1193        //Writeback
1194        if(list->outbufAcquireFenceFd >= 0) {
1195            close(list->outbufAcquireFenceFd);
1196            list->outbufAcquireFenceFd = -1;
1197        }
1198    }
1199}
1200
1201int hwc_sync(hwc_context_t *ctx, hwc_display_contents_1_t* list, int dpy,
1202        int fd) {
1203    ATRACE_CALL();
1204    int ret = 0;
1205    int acquireFd[MAX_NUM_APP_LAYERS];
1206    int count = 0;
1207    int releaseFd = -1;
1208    int retireFd = -1;
1209    int fbFd = -1;
1210    bool swapzero = false;
1211    int mdpVersion = qdutils::MDPVersion::getInstance().getMDPVersion();
1212
1213    struct mdp_buf_sync data;
1214    memset(&data, 0, sizeof(data));
1215    data.acq_fen_fd = acquireFd;
1216    data.rel_fen_fd = &releaseFd;
1217    data.retire_fen_fd = &retireFd;
1218    data.flags = MDP_BUF_SYNC_FLAG_RETIRE_FENCE;
1219
1220    char property[PROPERTY_VALUE_MAX];
1221    if(property_get("debug.egl.swapinterval", property, "1") > 0) {
1222        if(atoi(property) == 0)
1223            swapzero = true;
1224    }
1225
1226    bool isExtAnimating = false;
1227    if(dpy)
1228       isExtAnimating = ctx->listStats[dpy].isDisplayAnimating;
1229
1230    //Send acquireFenceFds to rotator
1231    for(uint32_t i = 0; i < ctx->mLayerRotMap[dpy]->getCount(); i++) {
1232        int rotFd = ctx->mRotMgr->getRotDevFd();
1233        int rotReleaseFd = -1;
1234        struct mdp_buf_sync rotData;
1235        memset(&rotData, 0, sizeof(rotData));
1236        rotData.acq_fen_fd =
1237                &ctx->mLayerRotMap[dpy]->getLayer(i)->acquireFenceFd;
1238        rotData.rel_fen_fd = &rotReleaseFd; //driver to populate this
1239        rotData.session_id = ctx->mLayerRotMap[dpy]->getRot(i)->getSessId();
1240        int ret = 0;
1241        ret = ioctl(rotFd, MSMFB_BUFFER_SYNC, &rotData);
1242        if(ret < 0) {
1243            ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed for rot sync, err=%s",
1244                    __FUNCTION__, strerror(errno));
1245        } else {
1246            close(ctx->mLayerRotMap[dpy]->getLayer(i)->acquireFenceFd);
1247            //For MDP to wait on.
1248            ctx->mLayerRotMap[dpy]->getLayer(i)->acquireFenceFd =
1249                    dup(rotReleaseFd);
1250            //A buffer is free to be used by producer as soon as its copied to
1251            //rotator
1252            ctx->mLayerRotMap[dpy]->getLayer(i)->releaseFenceFd =
1253                    rotReleaseFd;
1254        }
1255    }
1256
1257    //Accumulate acquireFenceFds for MDP
1258    if(list->outbufAcquireFenceFd >= 0) {
1259        //Writeback output buffer
1260        acquireFd[count++] = list->outbufAcquireFenceFd;
1261    }
1262
1263    for(uint32_t i = 0; i < list->numHwLayers; i++) {
1264        if((list->hwLayers[i].compositionType == HWC_OVERLAY  ||
1265                        list->hwLayers[i].compositionType == HWC_BLIT) &&
1266                        list->hwLayers[i].acquireFenceFd >= 0) {
1267            if(UNLIKELY(swapzero))
1268                acquireFd[count++] = -1;
1269            else
1270                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
1271        }
1272        if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
1273            if(UNLIKELY(swapzero))
1274                acquireFd[count++] = -1;
1275            else if(fd >= 0) {
1276                //set the acquireFD from fd - which is coming from c2d
1277                acquireFd[count++] = fd;
1278                // Buffer sync IOCTL should be async when using c2d fence is
1279                // used
1280                data.flags &= ~MDP_BUF_SYNC_FLAG_WAIT;
1281            } else if(list->hwLayers[i].acquireFenceFd >= 0)
1282                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
1283        }
1284    }
1285
1286    data.acq_fen_fd_cnt = count;
1287    fbFd = ctx->dpyAttr[dpy].fd;
1288
1289    //Waits for acquire fences, returns a release fence
1290    if(LIKELY(!swapzero)) {
1291        uint64_t start = systemTime();
1292        ret = ioctl(fbFd, MSMFB_BUFFER_SYNC, &data);
1293        ALOGD_IF(HWC_UTILS_DEBUG, "%s: time taken for MSMFB_BUFFER_SYNC IOCTL = %d",
1294                            __FUNCTION__, (size_t) ns2ms(systemTime() - start));
1295    }
1296
1297    if(ret < 0) {
1298        ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed, err=%s",
1299                  __FUNCTION__, strerror(errno));
1300        ALOGE("%s: acq_fen_fd_cnt=%d flags=%d fd=%d dpy=%d numHwLayers=%d",
1301              __FUNCTION__, data.acq_fen_fd_cnt, data.flags, fbFd,
1302              dpy, list->numHwLayers);
1303    }
1304
1305    for(uint32_t i = 0; i < list->numHwLayers; i++) {
1306        if(list->hwLayers[i].compositionType == HWC_OVERLAY ||
1307           list->hwLayers[i].compositionType == HWC_BLIT ||
1308           list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
1309            //Populate releaseFenceFds.
1310            if(UNLIKELY(swapzero)) {
1311                list->hwLayers[i].releaseFenceFd = -1;
1312            } else if(isExtAnimating) {
1313                // Release all the app layer fds immediately,
1314                // if animation is in progress.
1315                list->hwLayers[i].releaseFenceFd = -1;
1316            } else if(list->hwLayers[i].releaseFenceFd < 0) {
1317                //If rotator has not already populated this field.
1318                list->hwLayers[i].releaseFenceFd = dup(releaseFd);
1319            }
1320        }
1321    }
1322
1323    if(fd >= 0) {
1324        close(fd);
1325        fd = -1;
1326    }
1327
1328    if (ctx->mCopyBit[dpy])
1329        ctx->mCopyBit[dpy]->setReleaseFd(releaseFd);
1330
1331    //Signals when MDP finishes reading rotator buffers.
1332    ctx->mLayerRotMap[dpy]->setReleaseFd(releaseFd);
1333    close(releaseFd);
1334    releaseFd = -1;
1335
1336    if(UNLIKELY(swapzero)) {
1337        list->retireFenceFd = -1;
1338    } else {
1339        list->retireFenceFd = retireFd;
1340    }
1341    return ret;
1342}
1343
1344void setMdpFlags(hwc_layer_1_t *layer,
1345        ovutils::eMdpFlags &mdpFlags,
1346        int rotDownscale, int transform) {
1347    private_handle_t *hnd = (private_handle_t *)layer->handle;
1348    MetaData_t *metadata = hnd ? (MetaData_t *)hnd->base_metadata : NULL;
1349
1350    if(layer->blending == HWC_BLENDING_PREMULT) {
1351        ovutils::setMdpFlags(mdpFlags,
1352                ovutils::OV_MDP_BLEND_FG_PREMULT);
1353    }
1354
1355    if (layer->flags & HWC_VPU_PIPE) {
1356        ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_VPU_PIPE);
1357    }
1358
1359    if(isYuvBuffer(hnd)) {
1360        if(isSecureBuffer(hnd)) {
1361            ovutils::setMdpFlags(mdpFlags,
1362                    ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
1363        }
1364        if(metadata && (metadata->operation & PP_PARAM_INTERLACED) &&
1365                metadata->interlaced) {
1366            ovutils::setMdpFlags(mdpFlags,
1367                    ovutils::OV_MDP_DEINTERLACE);
1368        }
1369        //Pre-rotation will be used using rotator.
1370        if(transform & HWC_TRANSFORM_ROT_90) {
1371            ovutils::setMdpFlags(mdpFlags,
1372                    ovutils::OV_MDP_SOURCE_ROTATED_90);
1373        }
1374    }
1375
1376    if(isSecureDisplayBuffer(hnd)) {
1377        // Secure display needs both SECURE_OVERLAY and SECURE_DISPLAY_OV
1378        ovutils::setMdpFlags(mdpFlags,
1379                             ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
1380        ovutils::setMdpFlags(mdpFlags,
1381                             ovutils::OV_MDP_SECURE_DISPLAY_OVERLAY_SESSION);
1382    }
1383    //No 90 component and no rot-downscale then flips done by MDP
1384    //If we use rot then it might as well do flips
1385    if(!(transform & HWC_TRANSFORM_ROT_90) && !rotDownscale) {
1386        if(transform & HWC_TRANSFORM_FLIP_H) {
1387            ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_FLIP_H);
1388        }
1389
1390        if(transform & HWC_TRANSFORM_FLIP_V) {
1391            ovutils::setMdpFlags(mdpFlags,  ovutils::OV_MDP_FLIP_V);
1392        }
1393    }
1394
1395    if(metadata &&
1396        ((metadata->operation & PP_PARAM_HSIC)
1397        || (metadata->operation & PP_PARAM_IGC)
1398        || (metadata->operation & PP_PARAM_SHARP2))) {
1399        ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_PP_EN);
1400    }
1401}
1402
1403int configRotator(Rotator *rot, Whf& whf,
1404        hwc_rect_t& crop, const eMdpFlags& mdpFlags,
1405        const eTransform& orient, const int& downscale) {
1406
1407    // Fix alignments for TILED format
1408    if(whf.format == MDP_Y_CRCB_H2V2_TILE ||
1409                            whf.format == MDP_Y_CBCR_H2V2_TILE) {
1410        whf.w =  utils::alignup(whf.w, 64);
1411        whf.h = utils::alignup(whf.h, 32);
1412    }
1413    rot->setSource(whf);
1414
1415    if (qdutils::MDPVersion::getInstance().getMDPVersion() >=
1416        qdutils::MDSS_V5) {
1417        uint32_t crop_w = (crop.right - crop.left);
1418        uint32_t crop_h = (crop.bottom - crop.top);
1419        if (ovutils::isYuv(whf.format)) {
1420            ovutils::normalizeCrop((uint32_t&)crop.left, crop_w);
1421            ovutils::normalizeCrop((uint32_t&)crop.top, crop_h);
1422            // For interlaced, crop.h should be 4-aligned
1423            if ((mdpFlags & ovutils::OV_MDP_DEINTERLACE) && (crop_h % 4))
1424                crop_h = ovutils::aligndown(crop_h, 4);
1425            crop.right = crop.left + crop_w;
1426            crop.bottom = crop.top + crop_h;
1427        }
1428        Dim rotCrop(crop.left, crop.top, crop_w, crop_h);
1429        rot->setCrop(rotCrop);
1430    }
1431
1432    rot->setFlags(mdpFlags);
1433    rot->setTransform(orient);
1434    rot->setDownscale(downscale);
1435    if(!rot->commit()) return -1;
1436    return 0;
1437}
1438
1439int configMdp(Overlay *ov, const PipeArgs& parg,
1440        const eTransform& orient, const hwc_rect_t& crop,
1441        const hwc_rect_t& pos, const MetaData_t *metadata,
1442        const eDest& dest) {
1443    ov->setSource(parg, dest);
1444    ov->setTransform(orient, dest);
1445
1446    int crop_w = crop.right - crop.left;
1447    int crop_h = crop.bottom - crop.top;
1448    Dim dcrop(crop.left, crop.top, crop_w, crop_h);
1449    ov->setCrop(dcrop, dest);
1450
1451    int posW = pos.right - pos.left;
1452    int posH = pos.bottom - pos.top;
1453    Dim position(pos.left, pos.top, posW, posH);
1454    ov->setPosition(position, dest);
1455
1456    if (metadata)
1457        ov->setVisualParams(*metadata, dest);
1458
1459    if (!ov->commit(dest)) {
1460        return -1;
1461    }
1462    return 0;
1463}
1464
1465int configColorLayer(hwc_context_t *ctx, hwc_layer_1_t *layer,
1466        const int& dpy, eMdpFlags& mdpFlags, eZorder& z,
1467        eIsFg& isFg, const eDest& dest) {
1468
1469    hwc_rect_t dst = layer->displayFrame;
1470    trimLayer(ctx, dpy, 0, dst, dst);
1471
1472    int w = ctx->dpyAttr[dpy].xres;
1473    int h = ctx->dpyAttr[dpy].yres;
1474    int dst_w = dst.right - dst.left;
1475    int dst_h = dst.bottom - dst.top;
1476    uint32_t color = layer->transform;
1477    Whf whf(w, h, getMdpFormat(HAL_PIXEL_FORMAT_RGBA_8888), 0);
1478
1479    ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_SOLID_FILL);
1480    if (layer->blending == HWC_BLENDING_PREMULT)
1481        ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_BLEND_FG_PREMULT);
1482
1483    PipeArgs parg(mdpFlags, whf, z, isFg, static_cast<eRotFlags>(0),
1484                  layer->planeAlpha,
1485                  (ovutils::eBlending) getBlending(layer->blending));
1486
1487    // Configure MDP pipe for Color layer
1488    Dim pos(dst.left, dst.top, dst_w, dst_h);
1489    ctx->mOverlay->setSource(parg, dest);
1490    ctx->mOverlay->setColor(color, dest);
1491    ctx->mOverlay->setTransform(0, dest);
1492    ctx->mOverlay->setCrop(pos, dest);
1493    ctx->mOverlay->setPosition(pos, dest);
1494
1495    if (!ctx->mOverlay->commit(dest)) {
1496        ALOGE("%s: Configure color layer failed!", __FUNCTION__);
1497        return -1;
1498    }
1499    return 0;
1500}
1501
1502void updateSource(eTransform& orient, Whf& whf,
1503        hwc_rect_t& crop) {
1504    Dim srcCrop(crop.left, crop.top,
1505            crop.right - crop.left,
1506            crop.bottom - crop.top);
1507    orient = static_cast<eTransform>(ovutils::getMdpOrient(orient));
1508    preRotateSource(orient, whf, srcCrop);
1509    if (qdutils::MDPVersion::getInstance().getMDPVersion() >=
1510        qdutils::MDSS_V5) {
1511        // Source for overlay will be the cropped (and rotated)
1512        crop.left = 0;
1513        crop.top = 0;
1514        crop.right = srcCrop.w;
1515        crop.bottom = srcCrop.h;
1516        // Set width & height equal to sourceCrop w & h
1517        whf.w = srcCrop.w;
1518        whf.h = srcCrop.h;
1519    } else {
1520        crop.left = srcCrop.x;
1521        crop.top = srcCrop.y;
1522        crop.right = srcCrop.x + srcCrop.w;
1523        crop.bottom = srcCrop.y + srcCrop.h;
1524    }
1525}
1526
1527int configureNonSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
1528        const int& dpy, eMdpFlags& mdpFlags, eZorder& z,
1529        eIsFg& isFg, const eDest& dest, Rotator **rot) {
1530
1531    private_handle_t *hnd = (private_handle_t *)layer->handle;
1532
1533    if(!hnd) {
1534        if (layer->flags & HWC_COLOR_FILL) {
1535            // Configure Color layer
1536            return configColorLayer(ctx, layer, dpy, mdpFlags, z, isFg, dest);
1537        }
1538        ALOGE("%s: layer handle is NULL", __FUNCTION__);
1539        return -1;
1540    }
1541
1542    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
1543
1544    hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
1545    hwc_rect_t dst = layer->displayFrame;
1546    int transform = layer->transform;
1547    eTransform orient = static_cast<eTransform>(transform);
1548    int downscale = 0;
1549    int rotFlags = ovutils::ROT_FLAGS_NONE;
1550    uint32_t format = ovutils::getMdpFormat(hnd->format, isTileRendered(hnd));
1551    Whf whf(getWidth(hnd), getHeight(hnd), format, hnd->size);
1552
1553    // Handle R/B swap
1554    if (layer->flags & HWC_FORMAT_RB_SWAP) {
1555        if (hnd->format == HAL_PIXEL_FORMAT_RGBA_8888)
1556            whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRA_8888);
1557        else if (hnd->format == HAL_PIXEL_FORMAT_RGBX_8888)
1558            whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRX_8888);
1559    }
1560
1561    calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient);
1562
1563    if(isYuvBuffer(hnd) && ctx->mMDP.version >= qdutils::MDP_V4_2 &&
1564       ctx->mMDP.version < qdutils::MDSS_V5) {
1565        downscale =  getDownscaleFactor(
1566            crop.right - crop.left,
1567            crop.bottom - crop.top,
1568            dst.right - dst.left,
1569            dst.bottom - dst.top);
1570        if(downscale) {
1571            rotFlags = ROT_DOWNSCALE_ENABLED;
1572        }
1573    }
1574
1575    setMdpFlags(layer, mdpFlags, downscale, transform);
1576
1577    if(isYuvBuffer(hnd) && //if 90 component or downscale, use rot
1578            ((transform & HWC_TRANSFORM_ROT_90) || downscale)) {
1579        *rot = ctx->mRotMgr->getNext();
1580        if(*rot == NULL) return -1;
1581        if(!dpy)
1582            BwcPM::setBwc(ctx, crop, dst, transform, mdpFlags);
1583        //Configure rotator for pre-rotation
1584        if(configRotator(*rot, whf, crop, mdpFlags, orient, downscale) < 0) {
1585            ALOGE("%s: configRotator failed!", __FUNCTION__);
1586            return -1;
1587        }
1588        ctx->mLayerRotMap[dpy]->add(layer, *rot);
1589        whf.format = (*rot)->getDstFormat();
1590        updateSource(orient, whf, crop);
1591        rotFlags |= ovutils::ROT_PREROTATED;
1592    }
1593
1594    //For the mdp, since either we are pre-rotating or MDP does flips
1595    orient = OVERLAY_TRANSFORM_0;
1596    transform = 0;
1597    PipeArgs parg(mdpFlags, whf, z, isFg,
1598                  static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
1599                  (ovutils::eBlending) getBlending(layer->blending));
1600
1601    if(configMdp(ctx->mOverlay, parg, orient, crop, dst, metadata, dest) < 0) {
1602        ALOGE("%s: commit failed for low res panel", __FUNCTION__);
1603        return -1;
1604    }
1605    return 0;
1606}
1607
1608//Helper to 1) Ensure crops dont have gaps 2) Ensure L and W are even
1609void sanitizeSourceCrop(hwc_rect_t& cropL, hwc_rect_t& cropR,
1610        private_handle_t *hnd) {
1611    if(cropL.right - cropL.left) {
1612        if(isYuvBuffer(hnd)) {
1613            //Always safe to even down left
1614            ovutils::even_floor(cropL.left);
1615            //If right is even, automatically width is even, since left is
1616            //already even
1617            ovutils::even_floor(cropL.right);
1618        }
1619        //Make sure there are no gaps between left and right splits if the layer
1620        //is spread across BOTH halves
1621        if(cropR.right - cropR.left) {
1622            cropR.left = cropL.right;
1623        }
1624    }
1625
1626    if(cropR.right - cropR.left) {
1627        if(isYuvBuffer(hnd)) {
1628            //Always safe to even down left
1629            ovutils::even_floor(cropR.left);
1630            //If right is even, automatically width is even, since left is
1631            //already even
1632            ovutils::even_floor(cropR.right);
1633        }
1634    }
1635}
1636
1637int configureSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
1638        const int& dpy, eMdpFlags& mdpFlagsL, eZorder& z,
1639        eIsFg& isFg, const eDest& lDest, const eDest& rDest,
1640        Rotator **rot) {
1641    private_handle_t *hnd = (private_handle_t *)layer->handle;
1642    if(!hnd) {
1643        ALOGE("%s: layer handle is NULL", __FUNCTION__);
1644        return -1;
1645    }
1646
1647    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
1648
1649    int hw_w = ctx->dpyAttr[dpy].xres;
1650    int hw_h = ctx->dpyAttr[dpy].yres;
1651    hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
1652    hwc_rect_t dst = layer->displayFrame;
1653    int transform = layer->transform;
1654    eTransform orient = static_cast<eTransform>(transform);
1655    const int downscale = 0;
1656    int rotFlags = ROT_FLAGS_NONE;
1657    uint32_t format = ovutils::getMdpFormat(hnd->format, isTileRendered(hnd));
1658    Whf whf(getWidth(hnd), getHeight(hnd), format, hnd->size);
1659
1660    // Handle R/B swap
1661    if (layer->flags & HWC_FORMAT_RB_SWAP) {
1662        if (hnd->format == HAL_PIXEL_FORMAT_RGBA_8888)
1663            whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRA_8888);
1664        else if (hnd->format == HAL_PIXEL_FORMAT_RGBX_8888)
1665            whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRX_8888);
1666    }
1667
1668    setMdpFlags(layer, mdpFlagsL, 0, transform);
1669
1670    if(lDest != OV_INVALID && rDest != OV_INVALID) {
1671        //Enable overfetch
1672        setMdpFlags(mdpFlagsL, OV_MDSS_MDP_DUAL_PIPE);
1673    }
1674
1675    //Will do something only if feature enabled and conditions suitable
1676    //hollow call otherwise
1677    if(ctx->mAD->prepare(ctx, crop, whf, hnd)) {
1678        overlay::Writeback *wb = overlay::Writeback::getInstance();
1679        whf.format = wb->getOutputFormat();
1680    }
1681
1682    if(isYuvBuffer(hnd) && (transform & HWC_TRANSFORM_ROT_90)) {
1683        (*rot) = ctx->mRotMgr->getNext();
1684        if((*rot) == NULL) return -1;
1685        //Configure rotator for pre-rotation
1686        if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale) < 0) {
1687            ALOGE("%s: configRotator failed!", __FUNCTION__);
1688            return -1;
1689        }
1690        ctx->mLayerRotMap[dpy]->add(layer, *rot);
1691        whf.format = (*rot)->getDstFormat();
1692        updateSource(orient, whf, crop);
1693        rotFlags |= ROT_PREROTATED;
1694    }
1695
1696    eMdpFlags mdpFlagsR = mdpFlagsL;
1697    setMdpFlags(mdpFlagsR, OV_MDSS_MDP_RIGHT_MIXER);
1698
1699    hwc_rect_t tmp_cropL = {0}, tmp_dstL = {0};
1700    hwc_rect_t tmp_cropR = {0}, tmp_dstR = {0};
1701
1702    const int lSplit = getLeftSplit(ctx, dpy);
1703
1704    if(lDest != OV_INVALID) {
1705        tmp_cropL = crop;
1706        tmp_dstL = dst;
1707        hwc_rect_t scissor = {0, 0, lSplit, hw_h };
1708        scissor = getIntersection(ctx->mViewFrame[dpy], scissor);
1709        qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
1710    }
1711    if(rDest != OV_INVALID) {
1712        tmp_cropR = crop;
1713        tmp_dstR = dst;
1714        hwc_rect_t scissor = {lSplit, 0, hw_w, hw_h };
1715        scissor = getIntersection(ctx->mViewFrame[dpy], scissor);
1716        qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
1717    }
1718
1719    sanitizeSourceCrop(tmp_cropL, tmp_cropR, hnd);
1720
1721    //When buffer is H-flipped, contents of mixer config also needs to swapped
1722    //Not needed if the layer is confined to one half of the screen.
1723    //If rotator has been used then it has also done the flips, so ignore them.
1724    if((orient & OVERLAY_TRANSFORM_FLIP_H) && lDest != OV_INVALID
1725            && rDest != OV_INVALID && (*rot) == NULL) {
1726        hwc_rect_t new_cropR;
1727        new_cropR.left = tmp_cropL.left;
1728        new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
1729
1730        hwc_rect_t new_cropL;
1731        new_cropL.left  = new_cropR.right;
1732        new_cropL.right = tmp_cropR.right;
1733
1734        tmp_cropL.left =  new_cropL.left;
1735        tmp_cropL.right =  new_cropL.right;
1736
1737        tmp_cropR.left = new_cropR.left;
1738        tmp_cropR.right =  new_cropR.right;
1739
1740    }
1741
1742    //For the mdp, since either we are pre-rotating or MDP does flips
1743    orient = OVERLAY_TRANSFORM_0;
1744    transform = 0;
1745
1746    //configure left mixer
1747    if(lDest != OV_INVALID) {
1748        PipeArgs pargL(mdpFlagsL, whf, z, isFg,
1749                       static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
1750                       (ovutils::eBlending) getBlending(layer->blending));
1751
1752        if(configMdp(ctx->mOverlay, pargL, orient,
1753                tmp_cropL, tmp_dstL, metadata, lDest) < 0) {
1754            ALOGE("%s: commit failed for left mixer config", __FUNCTION__);
1755            return -1;
1756        }
1757    }
1758
1759    //configure right mixer
1760    if(rDest != OV_INVALID) {
1761        PipeArgs pargR(mdpFlagsR, whf, z, isFg,
1762                       static_cast<eRotFlags>(rotFlags),
1763                       layer->planeAlpha,
1764                       (ovutils::eBlending) getBlending(layer->blending));
1765        tmp_dstR.right = tmp_dstR.right - lSplit;
1766        tmp_dstR.left = tmp_dstR.left - lSplit;
1767        if(configMdp(ctx->mOverlay, pargR, orient,
1768                tmp_cropR, tmp_dstR, metadata, rDest) < 0) {
1769            ALOGE("%s: commit failed for right mixer config", __FUNCTION__);
1770            return -1;
1771        }
1772    }
1773
1774    return 0;
1775}
1776
1777int configureSourceSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
1778        const int& dpy, eMdpFlags& mdpFlagsL, eZorder& z,
1779        eIsFg& isFg, const eDest& lDest, const eDest& rDest,
1780        Rotator **rot) {
1781    private_handle_t *hnd = (private_handle_t *)layer->handle;
1782    if(!hnd) {
1783        ALOGE("%s: layer handle is NULL", __FUNCTION__);
1784        return -1;
1785    }
1786
1787    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
1788
1789    int hw_w = ctx->dpyAttr[dpy].xres;
1790    int hw_h = ctx->dpyAttr[dpy].yres;
1791    hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);;
1792    hwc_rect_t dst = layer->displayFrame;
1793    int transform = layer->transform;
1794    eTransform orient = static_cast<eTransform>(transform);
1795    const int downscale = 0;
1796    int rotFlags = ROT_FLAGS_NONE;
1797    //Splitting only YUV layer on primary panel needs different zorders
1798    //for both layers as both the layers are configured to single mixer
1799    eZorder lz = z;
1800    eZorder rz = (eZorder)(z + 1);
1801
1802    Whf whf(getWidth(hnd), getHeight(hnd),
1803            getMdpFormat(hnd->format), hnd->size);
1804
1805    setMdpFlags(layer, mdpFlagsL, 0, transform);
1806    trimLayer(ctx, dpy, transform, crop, dst);
1807
1808    if(isYuvBuffer(hnd) && (transform & HWC_TRANSFORM_ROT_90)) {
1809        (*rot) = ctx->mRotMgr->getNext();
1810        if((*rot) == NULL) return -1;
1811        if(!dpy)
1812            BwcPM::setBwc(ctx, crop, dst, transform, mdpFlagsL);
1813        //Configure rotator for pre-rotation
1814        if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale) < 0) {
1815            ALOGE("%s: configRotator failed!", __FUNCTION__);
1816            return -1;
1817        }
1818        ctx->mLayerRotMap[dpy]->add(layer, *rot);
1819        whf.format = (*rot)->getDstFormat();
1820        updateSource(orient, whf, crop);
1821        rotFlags |= ROT_PREROTATED;
1822    }
1823
1824    eMdpFlags mdpFlagsR = mdpFlagsL;
1825    int lSplit = dst.left + (dst.right - dst.left)/2;
1826
1827    hwc_rect_t tmp_cropL = {0}, tmp_dstL = {0};
1828    hwc_rect_t tmp_cropR = {0}, tmp_dstR = {0};
1829
1830    if(lDest != OV_INVALID) {
1831        tmp_cropL = crop;
1832        tmp_dstL = dst;
1833        hwc_rect_t scissor = {dst.left, dst.top, lSplit, dst.bottom };
1834        qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
1835    }
1836    if(rDest != OV_INVALID) {
1837        tmp_cropR = crop;
1838        tmp_dstR = dst;
1839        hwc_rect_t scissor = {lSplit, dst.top, dst.right, dst.bottom };
1840        qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
1841    }
1842
1843    sanitizeSourceCrop(tmp_cropL, tmp_cropR, hnd);
1844
1845    //When buffer is H-flipped, contents of mixer config also needs to swapped
1846    //Not needed if the layer is confined to one half of the screen.
1847    //If rotator has been used then it has also done the flips, so ignore them.
1848    if((orient & OVERLAY_TRANSFORM_FLIP_H) && lDest != OV_INVALID
1849            && rDest != OV_INVALID && (*rot) == NULL) {
1850        hwc_rect_t new_cropR;
1851        new_cropR.left = tmp_cropL.left;
1852        new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
1853
1854        hwc_rect_t new_cropL;
1855        new_cropL.left  = new_cropR.right;
1856        new_cropL.right = tmp_cropR.right;
1857
1858        tmp_cropL.left =  new_cropL.left;
1859        tmp_cropL.right =  new_cropL.right;
1860
1861        tmp_cropR.left = new_cropR.left;
1862        tmp_cropR.right =  new_cropR.right;
1863
1864    }
1865
1866    //For the mdp, since either we are pre-rotating or MDP does flips
1867    orient = OVERLAY_TRANSFORM_0;
1868    transform = 0;
1869
1870    //configure left half
1871    if(lDest != OV_INVALID) {
1872        PipeArgs pargL(mdpFlagsL, whf, lz, isFg,
1873                static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
1874                (ovutils::eBlending) getBlending(layer->blending));
1875
1876        if(configMdp(ctx->mOverlay, pargL, orient,
1877                    tmp_cropL, tmp_dstL, metadata, lDest) < 0) {
1878            ALOGE("%s: commit failed for left half config", __FUNCTION__);
1879            return -1;
1880        }
1881    }
1882
1883    //configure right half
1884    if(rDest != OV_INVALID) {
1885        PipeArgs pargR(mdpFlagsR, whf, rz, isFg,
1886                static_cast<eRotFlags>(rotFlags),
1887                layer->planeAlpha,
1888                (ovutils::eBlending) getBlending(layer->blending));
1889        if(configMdp(ctx->mOverlay, pargR, orient,
1890                    tmp_cropR, tmp_dstR, metadata, rDest) < 0) {
1891            ALOGE("%s: commit failed for right half config", __FUNCTION__);
1892            return -1;
1893        }
1894    }
1895
1896    return 0;
1897}
1898
1899bool canUseRotator(hwc_context_t *ctx, int dpy) {
1900    if(qdutils::MDPVersion::getInstance().is8x26() &&
1901            isSecondaryConnected(ctx) &&
1902            !ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].isPause) {
1903        /* 8x26 mdss driver supports multiplexing of DMA pipe
1904         * in LINE and BLOCK modes for writeback panels.
1905         */
1906        if(dpy == HWC_DISPLAY_PRIMARY)
1907            return false;
1908    }
1909    if(ctx->mMDP.version == qdutils::MDP_V3_0_4)
1910        return false;
1911    return true;
1912}
1913
1914int getLeftSplit(hwc_context_t *ctx, const int& dpy) {
1915    //Default even split for all displays with high res
1916    int lSplit = ctx->dpyAttr[dpy].xres / 2;
1917    if(dpy == HWC_DISPLAY_PRIMARY &&
1918            qdutils::MDPVersion::getInstance().getLeftSplit()) {
1919        //Override if split published by driver for primary
1920        lSplit = qdutils::MDPVersion::getInstance().getLeftSplit();
1921    }
1922    return lSplit;
1923}
1924
1925bool isDisplaySplit(hwc_context_t* ctx, int dpy) {
1926    if(ctx->dpyAttr[dpy].xres > qdutils::MAX_DISPLAY_DIM) {
1927        return true;
1928    }
1929    //For testing we could split primary via device tree values
1930    if(dpy == HWC_DISPLAY_PRIMARY &&
1931        qdutils::MDPVersion::getInstance().getRightSplit()) {
1932        return true;
1933    }
1934    return false;
1935}
1936
1937//clear prev layer prop flags and realloc for current frame
1938void reset_layer_prop(hwc_context_t* ctx, int dpy, int numAppLayers) {
1939    if(ctx->layerProp[dpy]) {
1940       delete[] ctx->layerProp[dpy];
1941       ctx->layerProp[dpy] = NULL;
1942    }
1943    ctx->layerProp[dpy] = new LayerProp[numAppLayers];
1944}
1945
1946/* Since we fake non-Hybrid WFD solution as external display, this
1947 * function helps us in determining the priority between external
1948 * (hdmi/non-Hybrid WFD display) and virtual display devices(SSD/
1949 * screenrecord). This can be removed once wfd-client migrates to
1950 * using virtual-display api's.
1951 */
1952bool canUseMDPforVirtualDisplay(hwc_context_t* ctx,
1953                                const hwc_display_contents_1_t *list) {
1954
1955    /* We rely on the fact that for pure virtual display solution
1956     * list->outbuf will be a non-NULL handle.
1957     *
1958     * If there are three active displays (which means there is one
1959     * primary, one external and one virtual active display)
1960     * we give mdss/mdp hw resources(pipes,smp,etc) for external
1961     * display(hdmi/non-Hybrid WFD display) rather than for virtual
1962     * display(SSD/screenrecord)
1963     */
1964
1965    if(list->outbuf and (ctx->numActiveDisplays == HWC_NUM_DISPLAY_TYPES)) {
1966        return false;
1967    }
1968
1969    return true;
1970}
1971
1972void BwcPM::setBwc(hwc_context_t *ctx, const hwc_rect_t& crop,
1973            const hwc_rect_t& dst, const int& transform,
1974            ovutils::eMdpFlags& mdpFlags) {
1975    //Target doesnt support Bwc
1976    if(!qdutils::MDPVersion::getInstance().supportsBWC()) {
1977        return;
1978    }
1979    //src width > MAX mixer supported dim
1980    if((crop.right - crop.left) > qdutils::MAX_DISPLAY_DIM) {
1981        return;
1982    }
1983    //Decimation necessary, cannot use BWC. H/W requirement.
1984    if(qdutils::MDPVersion::getInstance().supportsDecimation()) {
1985        int src_w = crop.right - crop.left;
1986        int src_h = crop.bottom - crop.top;
1987        int dst_w = dst.right - dst.left;
1988        int dst_h = dst.bottom - dst.top;
1989        if(transform & HAL_TRANSFORM_ROT_90) {
1990            swap(src_w, src_h);
1991        }
1992        float horDscale = 0.0f;
1993        float verDscale = 0.0f;
1994        int horzDeci = 0;
1995        int vertDeci = 0;
1996        ovutils::getDecimationFactor(src_w, src_h, dst_w, dst_h, horDscale,
1997                verDscale);
1998        //TODO Use log2f once math.h has it
1999        if((int)horDscale)
2000            horzDeci = (int)(log(horDscale) / log(2));
2001        if((int)verDscale)
2002            vertDeci = (int)(log(verDscale) / log(2));
2003        if(horzDeci || vertDeci) return;
2004    }
2005    //Property
2006    char value[PROPERTY_VALUE_MAX];
2007    property_get("debug.disable.bwc", value, "0");
2008     if(atoi(value)) return;
2009
2010    ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDSS_MDP_BWC_EN);
2011}
2012
2013void LayerRotMap::add(hwc_layer_1_t* layer, Rotator *rot) {
2014    if(mCount >= MAX_SESS) return;
2015    mLayer[mCount] = layer;
2016    mRot[mCount] = rot;
2017    mCount++;
2018}
2019
2020void LayerRotMap::reset() {
2021    for (int i = 0; i < MAX_SESS; i++) {
2022        mLayer[i] = 0;
2023        mRot[i] = 0;
2024    }
2025    mCount = 0;
2026}
2027
2028void LayerRotMap::clear() {
2029    RotMgr::getInstance()->markUnusedTop(mCount);
2030    reset();
2031}
2032
2033void LayerRotMap::setReleaseFd(const int& fence) {
2034    for(uint32_t i = 0; i < mCount; i++) {
2035        mRot[i]->setReleaseFd(dup(fence));
2036    }
2037}
2038
2039};//namespace qhwc
2040