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