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