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