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