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