hwc_utils.cpp revision 050c8e4005bd400436a48e34289b8ce7defe614d
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 HWC_UTILS_DEBUG 0
21#include <math.h>
22#include <sys/ioctl.h>
23#include <linux/fb.h>
24#include <binder/IServiceManager.h>
25#include <EGL/egl.h>
26#include <cutils/properties.h>
27#include <gralloc_priv.h>
28#include <overlay.h>
29#include <overlayRotator.h>
30#include <overlayWriteback.h>
31#include "hwc_utils.h"
32#include "hwc_mdpcomp.h"
33#include "hwc_fbupdate.h"
34#include "hwc_ad.h"
35#include "mdp_version.h"
36#include "hwc_copybit.h"
37#include "hwc_dump_layers.h"
38#include "external.h"
39#include "virtual.h"
40#include "hwc_qclient.h"
41#include "QService.h"
42#include "comptype.h"
43
44using namespace qClient;
45using namespace qService;
46using namespace android;
47using namespace overlay;
48using namespace overlay::utils;
49namespace ovutils = overlay::utils;
50
51namespace qhwc {
52
53static int openFramebufferDevice(hwc_context_t *ctx)
54{
55    struct fb_fix_screeninfo finfo;
56    struct fb_var_screeninfo info;
57
58    int fb_fd = openFb(HWC_DISPLAY_PRIMARY);
59    if(fb_fd < 0) {
60        ALOGE("%s: Error Opening FB : %s", __FUNCTION__, strerror(errno));
61        return -errno;
62    }
63
64    if (ioctl(fb_fd, FBIOGET_VSCREENINFO, &info) == -1) {
65        ALOGE("%s:Error in ioctl FBIOGET_VSCREENINFO: %s", __FUNCTION__,
66                                                       strerror(errno));
67        close(fb_fd);
68        return -errno;
69    }
70
71    if (int(info.width) <= 0 || int(info.height) <= 0) {
72        // the driver doesn't return that information
73        // default to 160 dpi
74        info.width  = ((info.xres * 25.4f)/160.0f + 0.5f);
75        info.height = ((info.yres * 25.4f)/160.0f + 0.5f);
76    }
77
78    float xdpi = (info.xres * 25.4f) / info.width;
79    float ydpi = (info.yres * 25.4f) / info.height;
80
81#ifdef MSMFB_METADATA_GET
82    struct msmfb_metadata metadata;
83    memset(&metadata, 0 , sizeof(metadata));
84    metadata.op = metadata_op_frame_rate;
85
86    if (ioctl(fb_fd, MSMFB_METADATA_GET, &metadata) == -1) {
87        ALOGE("%s:Error retrieving panel frame rate: %s", __FUNCTION__,
88                                                      strerror(errno));
89        close(fb_fd);
90        return -errno;
91    }
92
93    float fps  = metadata.data.panel_frame_rate;
94#else
95    //XXX: Remove reserved field usage on all baselines
96    //The reserved[3] field is used to store FPS by the driver.
97    float fps  = info.reserved[3] & 0xFF;
98#endif
99
100    if (ioctl(fb_fd, FBIOGET_FSCREENINFO, &finfo) == -1) {
101        ALOGE("%s:Error in ioctl FBIOGET_FSCREENINFO: %s", __FUNCTION__,
102                                                       strerror(errno));
103        close(fb_fd);
104        return -errno;
105    }
106
107    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd = fb_fd;
108    //xres, yres may not be 32 aligned
109    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].stride = finfo.line_length /(info.xres/8);
110    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres = info.xres;
111    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres = info.yres;
112    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xdpi = xdpi;
113    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].ydpi = ydpi;
114    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].vsync_period = 1000000000l / fps;
115
116    //Unblank primary on first boot
117    if(ioctl(fb_fd, FBIOBLANK,FB_BLANK_UNBLANK) < 0) {
118        ALOGE("%s: Failed to unblank display", __FUNCTION__);
119        return -errno;
120    }
121    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].isActive = true;
122
123    return 0;
124}
125
126void initContext(hwc_context_t *ctx)
127{
128    openFramebufferDevice(ctx);
129    ctx->mMDP.version = qdutils::MDPVersion::getInstance().getMDPVersion();
130    ctx->mMDP.hasOverlay = qdutils::MDPVersion::getInstance().hasOverlay();
131    ctx->mMDP.panel = qdutils::MDPVersion::getInstance().getPanelType();
132    const int rightSplit = qdutils::MDPVersion::getInstance().getRightSplit();
133    overlay::Overlay::initOverlay();
134    ctx->mOverlay = overlay::Overlay::getInstance();
135    ctx->mRotMgr = new RotMgr();
136
137    //Is created and destroyed only once for primary
138    //For external it could get created and destroyed multiple times depending
139    //on what external we connect to.
140    ctx->mFBUpdate[HWC_DISPLAY_PRIMARY] =
141        IFBUpdate::getObject(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres,
142                rightSplit, HWC_DISPLAY_PRIMARY);
143
144    // Check if the target supports copybit compostion (dyn/mdp/c2d) to
145    // decide if we need to open the copybit module.
146    int compositionType =
147        qdutils::QCCompositionType::getInstance().getCompositionType();
148
149    if (compositionType & (qdutils::COMPOSITION_TYPE_DYN |
150                           qdutils::COMPOSITION_TYPE_MDP |
151                           qdutils::COMPOSITION_TYPE_C2D)) {
152            ctx->mCopyBit[HWC_DISPLAY_PRIMARY] = new CopyBit();
153    }
154
155    ctx->mExtDisplay = new ExternalDisplay(ctx);
156    ctx->mVirtualDisplay = new VirtualDisplay(ctx);
157    ctx->mVirtualonExtActive = false;
158    ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].isActive = false;
159    ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].connected = false;
160    ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].isActive = false;
161    ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].connected = false;
162    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].mDownScaleMode= false;
163    ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].mDownScaleMode = false;
164    ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].mDownScaleMode = false;
165
166    ctx->mMDPComp[HWC_DISPLAY_PRIMARY] =
167         MDPComp::getObject(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres,
168                rightSplit, HWC_DISPLAY_PRIMARY);
169    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].connected = true;
170
171    for (uint32_t i = 0; i < HWC_NUM_DISPLAY_TYPES; i++) {
172        ctx->mHwcDebug[i] = new HwcDebug(i);
173        ctx->mLayerRotMap[i] = new LayerRotMap();
174    }
175
176    MDPComp::init(ctx);
177    ctx->mAD = new AssertiveDisplay();
178
179    ctx->vstate.enable = false;
180    ctx->vstate.fakevsync = false;
181    ctx->mExtOrientation = 0;
182
183    //Right now hwc starts the service but anybody could do it, or it could be
184    //independent process as well.
185    QService::init();
186    sp<IQClient> client = new QClient(ctx);
187    interface_cast<IQService>(
188            defaultServiceManager()->getService(
189            String16("display.qservice")))->connect(client);
190
191    // Initialize "No animation on external display" related  parameters.
192    ctx->deviceOrientation = 0;
193    ctx->mPrevCropVideo.left = ctx->mPrevCropVideo.top =
194        ctx->mPrevCropVideo.right = ctx->mPrevCropVideo.bottom = 0;
195    ctx->mPrevDestVideo.left = ctx->mPrevDestVideo.top =
196        ctx->mPrevDestVideo.right = ctx->mPrevDestVideo.bottom = 0;
197    ctx->mPrevTransformVideo = 0;
198
199    ctx->mBufferMirrorMode = false;
200
201    ALOGI("Initializing Qualcomm Hardware Composer");
202    ALOGI("MDP version: %d", ctx->mMDP.version);
203}
204
205void closeContext(hwc_context_t *ctx)
206{
207    if(ctx->mOverlay) {
208        delete ctx->mOverlay;
209        ctx->mOverlay = NULL;
210    }
211
212    if(ctx->mRotMgr) {
213        delete ctx->mRotMgr;
214        ctx->mRotMgr = NULL;
215    }
216
217    for(int i = 0; i < HWC_NUM_DISPLAY_TYPES; i++) {
218        if(ctx->mCopyBit[i]) {
219            delete ctx->mCopyBit[i];
220            ctx->mCopyBit[i] = NULL;
221        }
222    }
223
224    if(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd) {
225        close(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd);
226        ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd = -1;
227    }
228
229    if(ctx->mExtDisplay) {
230        delete ctx->mExtDisplay;
231        ctx->mExtDisplay = NULL;
232    }
233
234    for(int i = 0; i < HWC_NUM_DISPLAY_TYPES; i++) {
235        if(ctx->mFBUpdate[i]) {
236            delete ctx->mFBUpdate[i];
237            ctx->mFBUpdate[i] = NULL;
238        }
239        if(ctx->mMDPComp[i]) {
240            delete ctx->mMDPComp[i];
241            ctx->mMDPComp[i] = NULL;
242        }
243        if(ctx->mHwcDebug[i]) {
244            delete ctx->mHwcDebug[i];
245            ctx->mHwcDebug[i] = NULL;
246        }
247        if(ctx->mLayerRotMap[i]) {
248            delete ctx->mLayerRotMap[i];
249            ctx->mLayerRotMap[i] = NULL;
250        }
251    }
252    if(ctx->mAD) {
253        delete ctx->mAD;
254        ctx->mAD = NULL;
255    }
256
257
258}
259
260
261void dumpsys_log(android::String8& buf, const char* fmt, ...)
262{
263    va_list varargs;
264    va_start(varargs, fmt);
265    buf.appendFormatV(fmt, varargs);
266    va_end(varargs);
267}
268
269int getExtOrientation(hwc_context_t* ctx) {
270    int extOrient = ctx->mExtOrientation;
271    if(ctx->mBufferMirrorMode)
272        extOrient = getMirrorModeOrientation(ctx);
273    return extOrient;
274}
275
276/* Calculates the destination position based on the action safe rectangle */
277void getActionSafePosition(hwc_context_t *ctx, int dpy, hwc_rect_t& rect) {
278    // Position
279    int x = rect.left, y = rect.top;
280    int w = rect.right - rect.left;
281    int h = rect.bottom - rect.top;
282
283    // if external supports underscan, do nothing
284    // it will be taken care in the driver
285    if(ctx->mExtDisplay->isCEUnderscanSupported())
286        return;
287
288    char value[PROPERTY_VALUE_MAX];
289    // Read action safe properties
290    property_get("persist.sys.actionsafe.width", value, "0");
291    int asWidthRatio = atoi(value);
292    property_get("persist.sys.actionsafe.height", value, "0");
293    int asHeightRatio = atoi(value);
294
295    if(!asWidthRatio && !asHeightRatio) {
296        //No action safe ratio set, return
297        return;
298    }
299
300    float wRatio = 1.0;
301    float hRatio = 1.0;
302    float xRatio = 1.0;
303    float yRatio = 1.0;
304
305    float fbWidth = ctx->dpyAttr[dpy].xres;
306    float fbHeight = ctx->dpyAttr[dpy].yres;
307
308    // Since external is rotated 90, need to swap width/height
309    int extOrient = getExtOrientation(ctx);
310
311    if(extOrient & HWC_TRANSFORM_ROT_90)
312        swap(fbWidth, fbHeight);
313
314    float asX = 0;
315    float asY = 0;
316    float asW = fbWidth;
317    float asH= fbHeight;
318
319    // based on the action safe ratio, get the Action safe rectangle
320    asW = fbWidth * (1.0f -  asWidthRatio / 100.0f);
321    asH = fbHeight * (1.0f -  asHeightRatio / 100.0f);
322    asX = (fbWidth - asW) / 2;
323    asY = (fbHeight - asH) / 2;
324
325    // calculate the position ratio
326    xRatio = (float)x/fbWidth;
327    yRatio = (float)y/fbHeight;
328    wRatio = (float)w/fbWidth;
329    hRatio = (float)h/fbHeight;
330
331    //Calculate the position...
332    x = (xRatio * asW) + asX;
333    y = (yRatio * asH) + asY;
334    w = (wRatio * asW);
335    h = (hRatio * asH);
336
337    // Convert it back to hwc_rect_t
338    rect.left = x;
339    rect.top = y;
340    rect.right = w + rect.left;
341    rect.bottom = h + rect.top;
342
343    return;
344}
345
346/* Calculates the aspect ratio for based on src & dest */
347void getAspectRatioPosition(int destWidth, int destHeight, int srcWidth,
348                                int srcHeight, hwc_rect_t& rect) {
349   int x =0, y =0;
350
351   if (srcWidth * destHeight > destWidth * srcHeight) {
352        srcHeight = destWidth * srcHeight / srcWidth;
353        srcWidth = destWidth;
354    } else if (srcWidth * destHeight < destWidth * srcHeight) {
355        srcWidth = destHeight * srcWidth / srcHeight;
356        srcHeight = destHeight;
357    } else {
358        srcWidth = destWidth;
359        srcHeight = destHeight;
360    }
361    if (srcWidth > destWidth) srcWidth = destWidth;
362    if (srcHeight > destHeight) srcHeight = destHeight;
363    x = (destWidth - srcWidth) / 2;
364    y = (destHeight - srcHeight) / 2;
365    ALOGD_IF(HWC_UTILS_DEBUG, "%s: AS Position: x = %d, y = %d w = %d h = %d",
366             __FUNCTION__, x, y, srcWidth , srcHeight);
367    // Convert it back to hwc_rect_t
368    rect.left = x;
369    rect.top = y;
370    rect.right = srcWidth + rect.left;
371    rect.bottom = srcHeight + rect.top;
372}
373
374// This function gets the destination position for Seconday display
375// based on the position and aspect ratio with orientation
376void getAspectRatioPosition(hwc_context_t* ctx, int dpy, int extOrientation,
377                            hwc_rect_t& inRect, hwc_rect_t& outRect) {
378    // Physical display resolution
379    float fbWidth  = ctx->dpyAttr[dpy].xres;
380    float fbHeight = ctx->dpyAttr[dpy].yres;
381    //display position(x,y,w,h) in correct aspectratio after rotation
382    int xPos = 0;
383    int yPos = 0;
384    float width = fbWidth;
385    float height = fbHeight;
386    // Width/Height used for calculation, after rotation
387    float actualWidth = fbWidth;
388    float actualHeight = fbHeight;
389
390    float wRatio = 1.0;
391    float hRatio = 1.0;
392    float xRatio = 1.0;
393    float yRatio = 1.0;
394    hwc_rect_t rect = {0, 0, (int)fbWidth, (int)fbHeight};
395
396    Dim inPos(inRect.left, inRect.top, inRect.right - inRect.left,
397                inRect.bottom - inRect.top);
398    Dim outPos(outRect.left, outRect.top, outRect.right - outRect.left,
399                outRect.bottom - outRect.top);
400
401    Whf whf(fbWidth, fbHeight, 0);
402    eTransform extorient = static_cast<eTransform>(extOrientation);
403    // To calculate the destination co-ordinates in the new orientation
404    preRotateSource(extorient, whf, inPos);
405
406    if(extOrientation & HAL_TRANSFORM_ROT_90) {
407        // Swap width/height for input position
408        swapWidthHeight(actualWidth, actualHeight);
409        getAspectRatioPosition(fbWidth, fbHeight, (int)actualWidth,
410                               (int)actualHeight, rect);
411        xPos = rect.left;
412        yPos = rect.top;
413        width = rect.right - rect.left;
414        height = rect.bottom - rect.top;
415    }
416
417    //Calculate the position...
418    xRatio = inPos.x/actualWidth;
419    yRatio = inPos.y/actualHeight;
420    wRatio = inPos.w/actualWidth;
421    hRatio = inPos.h/actualHeight;
422
423    outPos.x = (xRatio * width) + xPos;
424    outPos.y = (yRatio * height) + yPos;
425    outPos.w = wRatio * width;
426    outPos.h = hRatio * height;
427    ALOGD_IF(HWC_UTILS_DEBUG, "%s: Calculated AspectRatio Position: x = %d,"
428                 "y = %d w = %d h = %d", __FUNCTION__, outPos.x, outPos.y,
429                 outPos.w, outPos.h);
430
431    // For sidesync, the dest fb will be in portrait orientation, and the crop
432    // will be updated to avoid the black side bands, and it will be upscaled
433    // to fit the dest RB, so recalculate
434    // the position based on the new width and height
435    if ((extOrientation & HWC_TRANSFORM_ROT_90) &&
436                        isOrientationPortrait(ctx)) {
437        hwc_rect_t r;
438        //Calculate the position
439        xRatio = (outPos.x - xPos)/width;
440        // GetaspectRatio -- tricky to get the correct aspect ratio
441        // But we need to do this.
442        getAspectRatioPosition(width, height, width, height, r);
443        xPos = r.left;
444        yPos = r.top;
445        float tempWidth = r.right - r.left;
446        float tempHeight = r.bottom - r.top;
447        yRatio = yPos/height;
448        wRatio = outPos.w/width;
449        hRatio = tempHeight/height;
450
451        //Map the coordinates back to Framebuffer domain
452        outPos.x = (xRatio * fbWidth);
453        outPos.y = (yRatio * fbHeight);
454        outPos.w = wRatio * fbWidth;
455        outPos.h = hRatio * fbHeight;
456
457        ALOGD_IF(HWC_UTILS_DEBUG, "%s: Calculated AspectRatio for device in"
458                 "portrait: x = %d,y = %d w = %d h = %d", __FUNCTION__,
459                 outPos.x, outPos.y,
460                 outPos.w, outPos.h);
461    }
462    if(ctx->dpyAttr[dpy].mDownScaleMode) {
463        int extW, extH;
464        if(dpy == HWC_DISPLAY_EXTERNAL)
465            ctx->mExtDisplay->getAttributes(extW, extH);
466        else
467            ctx->mVirtualDisplay->getAttributes(extW, extH);
468        fbWidth  = ctx->dpyAttr[dpy].xres;
469        fbHeight = ctx->dpyAttr[dpy].yres;
470        //Calculate the position...
471        xRatio = outPos.x/fbWidth;
472        yRatio = outPos.y/fbHeight;
473        wRatio = outPos.w/fbWidth;
474        hRatio = outPos.h/fbHeight;
475
476        outPos.x = xRatio * extW;
477        outPos.y = yRatio * extH;
478        outPos.w = wRatio * extW;
479        outPos.h = hRatio * extH;
480    }
481    // Convert Dim to hwc_rect_t
482    outRect.left = outPos.x;
483    outRect.top = outPos.y;
484    outRect.right = outPos.x + outPos.w;
485    outRect.bottom = outPos.y + outPos.h;
486
487    return;
488}
489
490bool isPrimaryPortrait(hwc_context_t *ctx) {
491    int fbWidth = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres;
492    int fbHeight = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres;
493    if(fbWidth < fbHeight) {
494        return true;
495    }
496    return false;
497}
498
499bool isOrientationPortrait(hwc_context_t *ctx) {
500    if(isPrimaryPortrait(ctx)) {
501        return !(ctx->deviceOrientation & 0x1);
502    }
503    return (ctx->deviceOrientation & 0x1);
504}
505
506void calcExtDisplayPosition(hwc_context_t *ctx,
507                               private_handle_t *hnd,
508                               int dpy,
509                               hwc_rect_t& sourceCrop,
510                               hwc_rect_t& displayFrame,
511                               int& transform,
512                               ovutils::eTransform& orient) {
513    // Swap width and height when there is a 90deg transform
514    int extOrient = getExtOrientation(ctx);
515    if(dpy && !qdutils::MDPVersion::getInstance().is8x26()) {
516        if(!isYuvBuffer(hnd)) {
517            if(extOrient & HWC_TRANSFORM_ROT_90) {
518                int dstWidth = ctx->dpyAttr[dpy].xres;
519                int dstHeight = ctx->dpyAttr[dpy].yres;;
520                int srcWidth = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres;
521                int srcHeight = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres;
522                if(!isPrimaryPortrait(ctx)) {
523                    swap(srcWidth, srcHeight);
524                }                    // Get Aspect Ratio for external
525                getAspectRatioPosition(dstWidth, dstHeight, srcWidth,
526                                    srcHeight, displayFrame);
527                // Crop - this is needed, because for sidesync, the dest fb will
528                // be in portrait orientation, so update the crop to not show the
529                // black side bands.
530                if (isOrientationPortrait(ctx)) {
531                    sourceCrop = displayFrame;
532                    displayFrame.left = 0;
533                    displayFrame.top = 0;
534                    displayFrame.right = dstWidth;
535                    displayFrame.bottom = dstHeight;
536                }
537            }
538            if(ctx->dpyAttr[dpy].mDownScaleMode) {
539                int extW, extH;
540                // if downscale is enabled, map the co-ordinates to new
541                // domain(downscaled)
542                float fbWidth  = ctx->dpyAttr[dpy].xres;
543                float fbHeight = ctx->dpyAttr[dpy].yres;
544                // query MDP configured attributes
545                if(dpy == HWC_DISPLAY_EXTERNAL)
546                    ctx->mExtDisplay->getAttributes(extW, extH);
547                else
548                    ctx->mVirtualDisplay->getAttributes(extW, extH);
549                //Calculate the ratio...
550                float wRatio = ((float)extW)/fbWidth;
551                float hRatio = ((float)extH)/fbHeight;
552
553                //convert Dim to hwc_rect_t
554                displayFrame.left *= wRatio;
555                displayFrame.top *= hRatio;
556                displayFrame.right *= wRatio;
557                displayFrame.bottom *= hRatio;
558            }
559        }else {
560            if(extOrient || ctx->dpyAttr[dpy].mDownScaleMode) {
561                getAspectRatioPosition(ctx, dpy, extOrient,
562                                       displayFrame, displayFrame);
563            }
564        }
565        // If there is a external orientation set, use that
566        if(extOrient) {
567            transform = extOrient;
568            orient = static_cast<ovutils::eTransform >(extOrient);
569        }
570        // Calculate the actionsafe dimensions for External(dpy = 1 or 2)
571        getActionSafePosition(ctx, dpy, displayFrame);
572    }
573}
574
575/* Returns the orientation which needs to be set on External for
576 *  SideSync/Buffer Mirrormode
577 */
578int getMirrorModeOrientation(hwc_context_t *ctx) {
579    int extOrientation = 0;
580    int deviceOrientation = ctx->deviceOrientation;
581    if(!isPrimaryPortrait(ctx))
582        deviceOrientation = (deviceOrientation + 1) % 4;
583     if (deviceOrientation == 0)
584         extOrientation = HWC_TRANSFORM_ROT_270;
585     else if (deviceOrientation == 1)//90
586         extOrientation = 0;
587     else if (deviceOrientation == 2)//180
588         extOrientation = HWC_TRANSFORM_ROT_90;
589     else if (deviceOrientation == 3)//270
590         extOrientation = HWC_TRANSFORM_FLIP_V | HWC_TRANSFORM_FLIP_H;
591
592    return extOrientation;
593}
594
595bool needsScaling(hwc_context_t* ctx, hwc_layer_1_t const* layer,
596        const int& dpy) {
597    int dst_w, dst_h, src_w, src_h;
598
599    hwc_rect_t displayFrame  = layer->displayFrame;
600    hwc_rect_t sourceCrop = layer->sourceCrop;
601    trimLayer(ctx, dpy, layer->transform, sourceCrop, displayFrame);
602
603    dst_w = displayFrame.right - displayFrame.left;
604    dst_h = displayFrame.bottom - displayFrame.top;
605    src_w = sourceCrop.right - sourceCrop.left;
606    src_h = sourceCrop.bottom - sourceCrop.top;
607
608    if(((src_w != dst_w) || (src_h != dst_h)))
609        return true;
610
611    return false;
612}
613
614bool isAlphaScaled(hwc_context_t* ctx, hwc_layer_1_t const* layer,
615        const int& dpy) {
616    if(needsScaling(ctx, layer, dpy) && isAlphaPresent(layer)) {
617        return true;
618    }
619    return false;
620}
621
622bool isAlphaPresent(hwc_layer_1_t const* layer) {
623    private_handle_t *hnd = (private_handle_t *)layer->handle;
624    if(hnd) {
625        int format = hnd->format;
626        switch(format) {
627        case HAL_PIXEL_FORMAT_RGBA_8888:
628        case HAL_PIXEL_FORMAT_BGRA_8888:
629            // In any more formats with Alpha go here..
630            return true;
631        default : return false;
632        }
633    }
634    return false;
635}
636
637void setListStats(hwc_context_t *ctx,
638        const hwc_display_contents_1_t *list, int dpy) {
639    const int prevYuvCount = ctx->listStats[dpy].yuvCount;
640    memset(&ctx->listStats[dpy], 0, sizeof(ListStats));
641    ctx->listStats[dpy].numAppLayers = list->numHwLayers - 1;
642    ctx->listStats[dpy].fbLayerIndex = list->numHwLayers - 1;
643    ctx->listStats[dpy].skipCount = 0;
644    ctx->listStats[dpy].needsAlphaScale = false;
645    ctx->listStats[dpy].preMultipliedAlpha = false;
646    ctx->listStats[dpy].yuvCount = 0;
647    char property[PROPERTY_VALUE_MAX];
648    ctx->listStats[dpy].extOnlyLayerIndex = -1;
649    ctx->listStats[dpy].isDisplayAnimating = false;
650
651    for (size_t i = 0; i < (size_t)ctx->listStats[dpy].numAppLayers; i++) {
652        hwc_layer_1_t const* layer = &list->hwLayers[i];
653        private_handle_t *hnd = (private_handle_t *)layer->handle;
654
655#ifdef QCOM_BSP
656        if (layer->flags & HWC_SCREENSHOT_ANIMATOR_LAYER) {
657            ctx->listStats[dpy].isDisplayAnimating = true;
658        }
659#endif
660        // continue if number of app layers exceeds MAX_NUM_APP_LAYERS
661        if(ctx->listStats[dpy].numAppLayers > MAX_NUM_APP_LAYERS)
662            continue;
663
664        //reset yuv indices
665        ctx->listStats[dpy].yuvIndices[i] = -1;
666
667        if (isSkipLayer(&list->hwLayers[i])) {
668            ctx->listStats[dpy].skipCount++;
669        }
670
671        if (UNLIKELY(isYuvBuffer(hnd))) {
672            int& yuvCount = ctx->listStats[dpy].yuvCount;
673            ctx->listStats[dpy].yuvIndices[yuvCount] = i;
674            yuvCount++;
675
676            if((layer->transform & HWC_TRANSFORM_ROT_90) &&
677                    canUseRotator(ctx, dpy)) {
678                if( (dpy == HWC_DISPLAY_PRIMARY) &&
679                        ctx->mOverlay->isPipeTypeAttached(OV_MDP_PIPE_DMA)) {
680                    ctx->isPaddingRound = true;
681                }
682                Overlay::setDMAMode(Overlay::DMA_BLOCK_MODE);
683            }
684        }
685        if(layer->blending == HWC_BLENDING_PREMULT)
686            ctx->listStats[dpy].preMultipliedAlpha = true;
687
688        if(!ctx->listStats[dpy].needsAlphaScale)
689            ctx->listStats[dpy].needsAlphaScale =
690                    isAlphaScaled(ctx, layer, dpy);
691
692        if(UNLIKELY(isExtOnly(hnd))){
693            ctx->listStats[dpy].extOnlyLayerIndex = i;
694        }
695    }
696    if(ctx->listStats[dpy].yuvCount > 0) {
697        if (property_get("hw.cabl.yuv", property, NULL) > 0) {
698            if (atoi(property) != 1) {
699                property_set("hw.cabl.yuv", "1");
700            }
701        }
702    } else {
703        if (property_get("hw.cabl.yuv", property, NULL) > 0) {
704            if (atoi(property) != 0) {
705                property_set("hw.cabl.yuv", "0");
706            }
707        }
708    }
709    if(dpy) {
710        //uncomment the below code for testing purpose.
711        /* char value[PROPERTY_VALUE_MAX];
712        property_get("sys.ext_orientation", value, "0");
713        // Assuming the orientation value is in terms of HAL_TRANSFORM,
714        // This needs mapping to HAL, if its in different convention
715        ctx->mExtOrientation = atoi(value); */
716        // Assuming the orientation value is in terms of HAL_TRANSFORM,
717        // This needs mapping to HAL, if its in different convention
718        if(ctx->mExtOrientation || ctx->mBufferMirrorMode) {
719            ALOGD_IF(HWC_UTILS_DEBUG, "%s: ext orientation = %d"
720                     "BufferMirrorMode = %d", __FUNCTION__,
721                     ctx->mExtOrientation, ctx->mBufferMirrorMode);
722            if(ctx->mOverlay->isPipeTypeAttached(OV_MDP_PIPE_DMA)) {
723                ctx->isPaddingRound = true;
724            }
725            Overlay::setDMAMode(Overlay::DMA_BLOCK_MODE);
726        }
727    }
728
729    //The marking of video begin/end is useful on some targets where we need
730    //to have a padding round to be able to shift pipes across mixers.
731    if(prevYuvCount != ctx->listStats[dpy].yuvCount) {
732        ctx->mVideoTransFlag = true;
733    }
734    if(dpy == HWC_DISPLAY_PRIMARY) {
735        ctx->mAD->markDoable(ctx, list);
736    }
737}
738
739
740static void calc_cut(double& leftCutRatio, double& topCutRatio,
741        double& rightCutRatio, double& bottomCutRatio, int orient) {
742    if(orient & HAL_TRANSFORM_FLIP_H) {
743        swap(leftCutRatio, rightCutRatio);
744    }
745    if(orient & HAL_TRANSFORM_FLIP_V) {
746        swap(topCutRatio, bottomCutRatio);
747    }
748    if(orient & HAL_TRANSFORM_ROT_90) {
749        //Anti clock swapping
750        double tmpCutRatio = leftCutRatio;
751        leftCutRatio = topCutRatio;
752        topCutRatio = rightCutRatio;
753        rightCutRatio = bottomCutRatio;
754        bottomCutRatio = tmpCutRatio;
755    }
756}
757
758bool isSecuring(hwc_context_t* ctx, hwc_layer_1_t const* layer) {
759    if((ctx->mMDP.version < qdutils::MDSS_V5) &&
760       (ctx->mMDP.version > qdutils::MDP_V3_0) &&
761        ctx->mSecuring) {
762        return true;
763    }
764    if (isSecureModePolicy(ctx->mMDP.version)) {
765        private_handle_t *hnd = (private_handle_t *)layer->handle;
766        if(ctx->mSecureMode) {
767            if (! isSecureBuffer(hnd)) {
768                ALOGD_IF(HWC_UTILS_DEBUG,"%s:Securing Turning ON ...",
769                         __FUNCTION__);
770                return true;
771            }
772        } else {
773            if (isSecureBuffer(hnd)) {
774                ALOGD_IF(HWC_UTILS_DEBUG,"%s:Securing Turning OFF ...",
775                         __FUNCTION__);
776                return true;
777            }
778        }
779    }
780    return false;
781}
782
783bool isSecureModePolicy(int mdpVersion) {
784    if (mdpVersion < qdutils::MDSS_V5)
785        return true;
786    else
787        return false;
788}
789
790int getBlending(int blending) {
791    switch(blending) {
792    case HWC_BLENDING_NONE:
793        return overlay::utils::OVERLAY_BLENDING_OPAQUE;
794    case HWC_BLENDING_PREMULT:
795        return overlay::utils::OVERLAY_BLENDING_PREMULT;
796    case HWC_BLENDING_COVERAGE :
797    default:
798        return overlay::utils::OVERLAY_BLENDING_COVERAGE;
799    }
800}
801
802//Crops source buffer against destination and FB boundaries
803void calculate_crop_rects(hwc_rect_t& crop, hwc_rect_t& dst,
804                          const hwc_rect_t& scissor, int orient) {
805
806    int& crop_l = crop.left;
807    int& crop_t = crop.top;
808    int& crop_r = crop.right;
809    int& crop_b = crop.bottom;
810    int crop_w = crop.right - crop.left;
811    int crop_h = crop.bottom - crop.top;
812
813    int& dst_l = dst.left;
814    int& dst_t = dst.top;
815    int& dst_r = dst.right;
816    int& dst_b = dst.bottom;
817    int dst_w = abs(dst.right - dst.left);
818    int dst_h = abs(dst.bottom - dst.top);
819
820    const int& sci_l = scissor.left;
821    const int& sci_t = scissor.top;
822    const int& sci_r = scissor.right;
823    const int& sci_b = scissor.bottom;
824    int sci_w = abs(sci_r - sci_l);
825    int sci_h = abs(sci_b - sci_t);
826
827    double leftCutRatio = 0.0, rightCutRatio = 0.0, topCutRatio = 0.0,
828            bottomCutRatio = 0.0;
829
830    if(dst_l < sci_l) {
831        leftCutRatio = (double)(sci_l - dst_l) / (double)dst_w;
832        dst_l = sci_l;
833    }
834
835    if(dst_r > sci_r) {
836        rightCutRatio = (double)(dst_r - sci_r) / (double)dst_w;
837        dst_r = sci_r;
838    }
839
840    if(dst_t < sci_t) {
841        topCutRatio = (double)(sci_t - dst_t) / (double)dst_h;
842        dst_t = sci_t;
843    }
844
845    if(dst_b > sci_b) {
846        bottomCutRatio = (double)(dst_b - sci_b) / (double)dst_h;
847        dst_b = sci_b;
848    }
849
850    calc_cut(leftCutRatio, topCutRatio, rightCutRatio, bottomCutRatio, orient);
851    crop_l += crop_w * leftCutRatio;
852    crop_t += crop_h * topCutRatio;
853    crop_r -= crop_w * rightCutRatio;
854    crop_b -= crop_h * bottomCutRatio;
855}
856
857void getNonWormholeRegion(hwc_display_contents_1_t* list,
858                              hwc_rect_t& nwr)
859{
860    uint32_t last = list->numHwLayers - 1;
861    hwc_rect_t fbDisplayFrame = list->hwLayers[last].displayFrame;
862    //Initiliaze nwr to first frame
863    nwr.left =  list->hwLayers[0].displayFrame.left;
864    nwr.top =  list->hwLayers[0].displayFrame.top;
865    nwr.right =  list->hwLayers[0].displayFrame.right;
866    nwr.bottom =  list->hwLayers[0].displayFrame.bottom;
867
868    for (uint32_t i = 1; i < last; i++) {
869        hwc_rect_t displayFrame = list->hwLayers[i].displayFrame;
870        nwr.left   = min(nwr.left, displayFrame.left);
871        nwr.top    = min(nwr.top, displayFrame.top);
872        nwr.right  = max(nwr.right, displayFrame.right);
873        nwr.bottom = max(nwr.bottom, displayFrame.bottom);
874    }
875
876    //Intersect with the framebuffer
877    nwr.left   = max(nwr.left, fbDisplayFrame.left);
878    nwr.top    = max(nwr.top, fbDisplayFrame.top);
879    nwr.right  = min(nwr.right, fbDisplayFrame.right);
880    nwr.bottom = min(nwr.bottom, fbDisplayFrame.bottom);
881
882}
883
884bool isExternalActive(hwc_context_t* ctx) {
885    return ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].isActive;
886}
887
888void closeAcquireFds(hwc_display_contents_1_t* list) {
889    for(uint32_t i = 0; list && i < list->numHwLayers; i++) {
890        //Close the acquireFenceFds
891        //HWC_FRAMEBUFFER are -1 already by SF, rest we close.
892        if(list->hwLayers[i].acquireFenceFd >= 0) {
893            close(list->hwLayers[i].acquireFenceFd);
894            list->hwLayers[i].acquireFenceFd = -1;
895        }
896    }
897}
898
899int hwc_sync(hwc_context_t *ctx, hwc_display_contents_1_t* list, int dpy,
900        int fd) {
901    int ret = 0;
902    int acquireFd[MAX_NUM_APP_LAYERS];
903    int count = 0;
904    int releaseFd = -1;
905    int fbFd = -1;
906    bool swapzero = false;
907    int mdpVersion = qdutils::MDPVersion::getInstance().getMDPVersion();
908
909    struct mdp_buf_sync data;
910    memset(&data, 0, sizeof(data));
911    data.acq_fen_fd = acquireFd;
912    data.rel_fen_fd = &releaseFd;
913
914    char property[PROPERTY_VALUE_MAX];
915    if(property_get("debug.egl.swapinterval", property, "1") > 0) {
916        if(atoi(property) == 0)
917            swapzero = true;
918    }
919
920    bool isExtAnimating = false;
921    if(dpy)
922       isExtAnimating = ctx->listStats[dpy].isDisplayAnimating;
923
924    //Send acquireFenceFds to rotator
925    for(uint32_t i = 0; i < ctx->mLayerRotMap[dpy]->getCount(); i++) {
926        int rotFd = ctx->mRotMgr->getRotDevFd();
927        int rotReleaseFd = -1;
928        struct mdp_buf_sync rotData;
929        memset(&rotData, 0, sizeof(rotData));
930        rotData.acq_fen_fd =
931                &ctx->mLayerRotMap[dpy]->getLayer(i)->acquireFenceFd;
932        rotData.rel_fen_fd = &rotReleaseFd; //driver to populate this
933        rotData.session_id = ctx->mLayerRotMap[dpy]->getRot(i)->getSessId();
934        int ret = 0;
935        ret = ioctl(rotFd, MSMFB_BUFFER_SYNC, &rotData);
936        if(ret < 0) {
937            ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed for rot sync, err=%s",
938                    __FUNCTION__, strerror(errno));
939        } else {
940            close(ctx->mLayerRotMap[dpy]->getLayer(i)->acquireFenceFd);
941            //For MDP to wait on.
942            ctx->mLayerRotMap[dpy]->getLayer(i)->acquireFenceFd =
943                    dup(rotReleaseFd);
944            //A buffer is free to be used by producer as soon as its copied to
945            //rotator
946            ctx->mLayerRotMap[dpy]->getLayer(i)->releaseFenceFd =
947                    rotReleaseFd;
948        }
949    }
950
951    //Accumulate acquireFenceFds for MDP
952    for(uint32_t i = 0; i < list->numHwLayers; i++) {
953        if(list->hwLayers[i].compositionType == HWC_OVERLAY &&
954                        list->hwLayers[i].acquireFenceFd >= 0) {
955            if(UNLIKELY(swapzero))
956                acquireFd[count++] = -1;
957            else
958                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
959        }
960        if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
961            if(UNLIKELY(swapzero))
962                acquireFd[count++] = -1;
963            else if(fd >= 0) {
964                //set the acquireFD from fd - which is coming from c2d
965                acquireFd[count++] = fd;
966                // Buffer sync IOCTL should be async when using c2d fence is
967                // used
968                data.flags &= ~MDP_BUF_SYNC_FLAG_WAIT;
969            } else if(list->hwLayers[i].acquireFenceFd >= 0)
970                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
971        }
972    }
973
974    data.acq_fen_fd_cnt = count;
975    fbFd = ctx->dpyAttr[dpy].fd;
976
977    //Waits for acquire fences, returns a release fence
978    if(LIKELY(!swapzero)) {
979        uint64_t start = systemTime();
980        ret = ioctl(fbFd, MSMFB_BUFFER_SYNC, &data);
981        ALOGD_IF(HWC_UTILS_DEBUG, "%s: time taken for MSMFB_BUFFER_SYNC IOCTL = %d",
982                            __FUNCTION__, (size_t) ns2ms(systemTime() - start));
983    }
984
985    if(ret < 0) {
986        ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed, err=%s",
987                  __FUNCTION__, strerror(errno));
988        ALOGE("%s: acq_fen_fd_cnt=%d flags=%d fd=%d dpy=%d numHwLayers=%d",
989              __FUNCTION__, data.acq_fen_fd_cnt, data.flags, fbFd,
990              dpy, list->numHwLayers);
991    }
992
993    for(uint32_t i = 0; i < list->numHwLayers; i++) {
994        if(list->hwLayers[i].compositionType == HWC_OVERLAY ||
995           list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
996            //Populate releaseFenceFds.
997            if(UNLIKELY(swapzero)) {
998                list->hwLayers[i].releaseFenceFd = -1;
999            } else if(isExtAnimating) {
1000                // Release all the app layer fds immediately,
1001                // if animation is in progress.
1002                hwc_layer_1_t const* layer = &list->hwLayers[i];
1003                private_handle_t *hnd = (private_handle_t *)layer->handle;
1004                if(isYuvBuffer(hnd)) {
1005                    list->hwLayers[i].releaseFenceFd = dup(releaseFd);
1006                } else
1007                    list->hwLayers[i].releaseFenceFd = -1;
1008            } else if(list->hwLayers[i].releaseFenceFd < 0) {
1009                //If rotator has not already populated this field.
1010                list->hwLayers[i].releaseFenceFd = dup(releaseFd);
1011            }
1012        }
1013    }
1014
1015    if(fd >= 0) {
1016        close(fd);
1017        fd = -1;
1018    }
1019
1020    if (ctx->mCopyBit[dpy])
1021        ctx->mCopyBit[dpy]->setReleaseFd(releaseFd);
1022
1023    //Signals when MDP finishes reading rotator buffers.
1024    ctx->mLayerRotMap[dpy]->setReleaseFd(releaseFd);
1025
1026    // if external is animating, close the relaseFd
1027    if(isExtAnimating) {
1028        close(releaseFd);
1029        releaseFd = -1;
1030    }
1031
1032    if(UNLIKELY(swapzero)){
1033        list->retireFenceFd = -1;
1034        close(releaseFd);
1035    } else {
1036        list->retireFenceFd = releaseFd;
1037    }
1038
1039    return ret;
1040}
1041
1042void trimLayer(hwc_context_t *ctx, const int& dpy, const int& transform,
1043        hwc_rect_t& crop, hwc_rect_t& dst) {
1044    int hw_w = ctx->dpyAttr[dpy].xres;
1045    int hw_h = ctx->dpyAttr[dpy].yres;
1046    if(dst.left < 0 || dst.top < 0 ||
1047            dst.right > hw_w || dst.bottom > hw_h) {
1048        hwc_rect_t scissor = {0, 0, hw_w, hw_h };
1049        qhwc::calculate_crop_rects(crop, dst, scissor, transform);
1050    }
1051}
1052
1053void setMdpFlags(hwc_layer_1_t *layer,
1054        ovutils::eMdpFlags &mdpFlags,
1055        int rotDownscale, int transform) {
1056    private_handle_t *hnd = (private_handle_t *)layer->handle;
1057    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
1058
1059    if(layer->blending == HWC_BLENDING_PREMULT) {
1060        ovutils::setMdpFlags(mdpFlags,
1061                ovutils::OV_MDP_BLEND_FG_PREMULT);
1062    }
1063
1064    if(isYuvBuffer(hnd)) {
1065        if(isSecureBuffer(hnd)) {
1066            ovutils::setMdpFlags(mdpFlags,
1067                    ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
1068        }
1069        if(metadata && (metadata->operation & PP_PARAM_INTERLACED) &&
1070                metadata->interlaced) {
1071            ovutils::setMdpFlags(mdpFlags,
1072                    ovutils::OV_MDP_DEINTERLACE);
1073        }
1074        //Pre-rotation will be used using rotator.
1075        if(transform & HWC_TRANSFORM_ROT_90) {
1076            ovutils::setMdpFlags(mdpFlags,
1077                    ovutils::OV_MDP_SOURCE_ROTATED_90);
1078        }
1079    }
1080
1081    //No 90 component and no rot-downscale then flips done by MDP
1082    //If we use rot then it might as well do flips
1083    if(!(transform & HWC_TRANSFORM_ROT_90) && !rotDownscale) {
1084        if(transform & HWC_TRANSFORM_FLIP_H) {
1085            ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_FLIP_H);
1086        }
1087
1088        if(transform & HWC_TRANSFORM_FLIP_V) {
1089            ovutils::setMdpFlags(mdpFlags,  ovutils::OV_MDP_FLIP_V);
1090        }
1091    }
1092
1093    if(metadata &&
1094        ((metadata->operation & PP_PARAM_HSIC)
1095        || (metadata->operation & PP_PARAM_IGC)
1096        || (metadata->operation & PP_PARAM_SHARP2))) {
1097        ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_PP_EN);
1098    }
1099}
1100
1101int configRotator(Rotator *rot, Whf& whf,
1102        hwc_rect_t& crop, const eMdpFlags& mdpFlags,
1103        const eTransform& orient, const int& downscale) {
1104
1105    // Fix alignments for TILED format
1106    if(whf.format == MDP_Y_CRCB_H2V2_TILE ||
1107                            whf.format == MDP_Y_CBCR_H2V2_TILE) {
1108        whf.w =  utils::alignup(whf.w, 64);
1109        whf.h = utils::alignup(whf.h, 32);
1110    }
1111    rot->setSource(whf);
1112
1113    if (qdutils::MDPVersion::getInstance().getMDPVersion() >=
1114        qdutils::MDSS_V5) {
1115        uint32_t crop_w = (crop.right - crop.left);
1116        uint32_t crop_h = (crop.bottom - crop.top);
1117        if (ovutils::isYuv(whf.format)) {
1118            ovutils::normalizeCrop((uint32_t&)crop.left, crop_w);
1119            ovutils::normalizeCrop((uint32_t&)crop.top, crop_h);
1120            // For interlaced, crop.h should be 4-aligned
1121            if ((mdpFlags & ovutils::OV_MDP_DEINTERLACE) && (crop_h % 4))
1122                crop_h = ovutils::aligndown(crop_h, 4);
1123            crop.right = crop.left + crop_w;
1124            crop.bottom = crop.top + crop_h;
1125        }
1126        Dim rotCrop(crop.left, crop.top, crop_w, crop_h);
1127        rot->setCrop(rotCrop);
1128    }
1129
1130    rot->setFlags(mdpFlags);
1131    rot->setTransform(orient);
1132    rot->setDownscale(downscale);
1133    if(!rot->commit()) return -1;
1134    return 0;
1135}
1136
1137int configMdp(Overlay *ov, const PipeArgs& parg,
1138        const eTransform& orient, const hwc_rect_t& crop,
1139        const hwc_rect_t& pos, const MetaData_t *metadata,
1140        const eDest& dest) {
1141    ov->setSource(parg, dest);
1142    ov->setTransform(orient, dest);
1143
1144    int crop_w = crop.right - crop.left;
1145    int crop_h = crop.bottom - crop.top;
1146    Dim dcrop(crop.left, crop.top, crop_w, crop_h);
1147    ov->setCrop(dcrop, dest);
1148
1149    int posW = pos.right - pos.left;
1150    int posH = pos.bottom - pos.top;
1151    Dim position(pos.left, pos.top, posW, posH);
1152    ov->setPosition(position, dest);
1153
1154    if (metadata)
1155        ov->setVisualParams(*metadata, dest);
1156
1157    if (!ov->commit(dest)) {
1158        return -1;
1159    }
1160    return 0;
1161}
1162
1163void updateSource(eTransform& orient, Whf& whf,
1164        hwc_rect_t& crop) {
1165    Dim srcCrop(crop.left, crop.top,
1166            crop.right - crop.left,
1167            crop.bottom - crop.top);
1168    orient = static_cast<eTransform>(ovutils::getMdpOrient(orient));
1169    preRotateSource(orient, whf, srcCrop);
1170    if (qdutils::MDPVersion::getInstance().getMDPVersion() >=
1171        qdutils::MDSS_V5) {
1172        // Source for overlay will be the cropped (and rotated)
1173        crop.left = 0;
1174        crop.top = 0;
1175        crop.right = srcCrop.w;
1176        crop.bottom = srcCrop.h;
1177        // Set width & height equal to sourceCrop w & h
1178        whf.w = srcCrop.w;
1179        whf.h = srcCrop.h;
1180    } else {
1181        crop.left = srcCrop.x;
1182        crop.top = srcCrop.y;
1183        crop.right = srcCrop.x + srcCrop.w;
1184        crop.bottom = srcCrop.y + srcCrop.h;
1185    }
1186}
1187
1188int configureLowRes(hwc_context_t *ctx, hwc_layer_1_t *layer,
1189        const int& dpy, eMdpFlags& mdpFlags, eZorder& z,
1190        eIsFg& isFg, const eDest& dest, Rotator **rot) {
1191
1192    private_handle_t *hnd = (private_handle_t *)layer->handle;
1193    if(!hnd) {
1194        ALOGE("%s: layer handle is NULL", __FUNCTION__);
1195        return -1;
1196    }
1197
1198    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
1199
1200    hwc_rect_t crop = layer->sourceCrop;
1201    hwc_rect_t dst = layer->displayFrame;
1202    int transform = layer->transform;
1203    eTransform orient = static_cast<eTransform>(transform);
1204    int downscale = 0;
1205    int rotFlags = ovutils::ROT_FLAGS_NONE;
1206    Whf whf(hnd->width, hnd->height,
1207            getMdpFormat(hnd->format), hnd->size);
1208
1209    if(dpy && isYuvBuffer(hnd)) {
1210        if(!ctx->listStats[dpy].isDisplayAnimating) {
1211            ctx->mPrevCropVideo = crop;
1212            ctx->mPrevDestVideo = dst;
1213            ctx->mPrevTransformVideo = transform;
1214        } else {
1215            // Restore the previous crop, dest rect and transform values, during
1216            // animation to avoid displaying videos at random coordinates.
1217            crop = ctx->mPrevCropVideo;
1218            dst = ctx->mPrevDestVideo;
1219            transform = ctx->mPrevTransformVideo;
1220            orient = static_cast<eTransform>(transform);
1221            //In you tube use case when a device rotated from landscape to
1222            // portrait, set the isFg flag and zOrder to avoid displaying UI on
1223            // hdmi during animation
1224            if(ctx->deviceOrientation) {
1225                isFg = ovutils::IS_FG_SET;
1226                z = ZORDER_1;
1227            }
1228        }
1229        calcExtDisplayPosition(ctx, hnd, dpy, crop, dst,
1230                                           transform, orient);
1231    }
1232
1233    if(isYuvBuffer(hnd) && ctx->mMDP.version >= qdutils::MDP_V4_2 &&
1234       ctx->mMDP.version < qdutils::MDSS_V5) {
1235        downscale =  getDownscaleFactor(
1236            crop.right - crop.left,
1237            crop.bottom - crop.top,
1238            dst.right - dst.left,
1239            dst.bottom - dst.top);
1240        if(downscale) {
1241            rotFlags = ROT_DOWNSCALE_ENABLED;
1242        }
1243    }
1244
1245    setMdpFlags(layer, mdpFlags, downscale, transform);
1246    trimLayer(ctx, dpy, transform, crop, dst);
1247
1248    //Will do something only if feature enabled and conditions suitable
1249    //hollow call otherwise
1250    if(ctx->mAD->prepare(ctx, crop, whf, hnd)) {
1251        overlay::Writeback *wb = overlay::Writeback::getInstance();
1252        whf.format = wb->getOutputFormat();
1253    }
1254
1255    if(isYuvBuffer(hnd) && //if 90 component or downscale, use rot
1256            ((transform & HWC_TRANSFORM_ROT_90) || downscale)) {
1257        *rot = ctx->mRotMgr->getNext();
1258        if(*rot == NULL) return -1;
1259        BwcPM::setBwc(ctx, crop, dst, transform, mdpFlags);
1260        //Configure rotator for pre-rotation
1261        if(configRotator(*rot, whf, crop, mdpFlags, orient, downscale) < 0) {
1262            ALOGE("%s: configRotator failed!", __FUNCTION__);
1263            ctx->mOverlay->clear(dpy);
1264            return -1;
1265        }
1266        ctx->mLayerRotMap[dpy]->add(layer, *rot);
1267        whf.format = (*rot)->getDstFormat();
1268        updateSource(orient, whf, crop);
1269        rotFlags |= ovutils::ROT_PREROTATED;
1270    }
1271
1272    //For the mdp, since either we are pre-rotating or MDP does flips
1273    orient = OVERLAY_TRANSFORM_0;
1274    transform = 0;
1275    PipeArgs parg(mdpFlags, whf, z, isFg,
1276                  static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
1277                  (ovutils::eBlending) getBlending(layer->blending));
1278
1279    if(configMdp(ctx->mOverlay, parg, orient, crop, dst, metadata, dest) < 0) {
1280        ALOGE("%s: commit failed for low res panel", __FUNCTION__);
1281        return -1;
1282    }
1283    return 0;
1284}
1285
1286int configureHighRes(hwc_context_t *ctx, hwc_layer_1_t *layer,
1287        const int& dpy, eMdpFlags& mdpFlagsL, eZorder& z,
1288        eIsFg& isFg, const eDest& lDest, const eDest& rDest,
1289        Rotator **rot) {
1290    private_handle_t *hnd = (private_handle_t *)layer->handle;
1291    if(!hnd) {
1292        ALOGE("%s: layer handle is NULL", __FUNCTION__);
1293        return -1;
1294    }
1295
1296    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
1297
1298    int hw_w = ctx->dpyAttr[dpy].xres;
1299    int hw_h = ctx->dpyAttr[dpy].yres;
1300    hwc_rect_t crop = layer->sourceCrop;
1301    hwc_rect_t dst = layer->displayFrame;
1302    int transform = layer->transform;
1303    eTransform orient = static_cast<eTransform>(transform);
1304    const int downscale = 0;
1305    int rotFlags = ROT_FLAGS_NONE;
1306
1307    Whf whf(hnd->width, hnd->height,
1308            getMdpFormat(hnd->format), hnd->size);
1309
1310    if(dpy && isYuvBuffer(hnd)) {
1311        if(!ctx->listStats[dpy].isDisplayAnimating) {
1312            ctx->mPrevCropVideo = crop;
1313            ctx->mPrevDestVideo = dst;
1314            ctx->mPrevTransformVideo = transform;
1315        } else {
1316            // Restore the previous crop, dest rect and transform values, during
1317            // animation to avoid displaying videos at random coordinates.
1318            crop = ctx->mPrevCropVideo;
1319            dst = ctx->mPrevDestVideo;
1320            transform = ctx->mPrevTransformVideo;
1321            orient = static_cast<eTransform>(transform);
1322            //In you tube use case when a device rotated from landscape to
1323            // portrait, set the isFg flag and zOrder to avoid displaying UI on
1324            // hdmi during animation
1325            if(ctx->deviceOrientation) {
1326                isFg = ovutils::IS_FG_SET;
1327                z = ZORDER_1;
1328            }
1329        }
1330    }
1331
1332
1333    setMdpFlags(layer, mdpFlagsL, 0, transform);
1334    trimLayer(ctx, dpy, transform, crop, dst);
1335
1336    //Will do something only if feature enabled and conditions suitable
1337    //hollow call otherwise
1338    if(ctx->mAD->prepare(ctx, crop, whf, hnd)) {
1339        overlay::Writeback *wb = overlay::Writeback::getInstance();
1340        whf.format = wb->getOutputFormat();
1341    }
1342
1343    if(isYuvBuffer(hnd) && (transform & HWC_TRANSFORM_ROT_90)) {
1344        (*rot) = ctx->mRotMgr->getNext();
1345        if((*rot) == NULL) return -1;
1346        //Configure rotator for pre-rotation
1347        if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale) < 0) {
1348            ALOGE("%s: configRotator failed!", __FUNCTION__);
1349            ctx->mOverlay->clear(dpy);
1350            return -1;
1351        }
1352        ctx->mLayerRotMap[dpy]->add(layer, *rot);
1353        whf.format = (*rot)->getDstFormat();
1354        updateSource(orient, whf, crop);
1355        rotFlags |= ROT_PREROTATED;
1356    }
1357
1358    eMdpFlags mdpFlagsR = mdpFlagsL;
1359    setMdpFlags(mdpFlagsR, OV_MDSS_MDP_RIGHT_MIXER);
1360
1361    hwc_rect_t tmp_cropL, tmp_dstL;
1362    hwc_rect_t tmp_cropR, tmp_dstR;
1363
1364    const int lSplit = getLeftSplit(ctx, dpy);
1365
1366    if(lDest != OV_INVALID) {
1367        tmp_cropL = crop;
1368        tmp_dstL = dst;
1369        hwc_rect_t scissor = {0, 0, lSplit, hw_h };
1370        qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
1371    }
1372    if(rDest != OV_INVALID) {
1373        tmp_cropR = crop;
1374        tmp_dstR = dst;
1375        hwc_rect_t scissor = {lSplit, 0, hw_w, hw_h };
1376        qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
1377    }
1378
1379    //When buffer is H-flipped, contents of mixer config also needs to swapped
1380    //Not needed if the layer is confined to one half of the screen.
1381    //If rotator has been used then it has also done the flips, so ignore them.
1382    if((orient & OVERLAY_TRANSFORM_FLIP_H) && lDest != OV_INVALID
1383            && rDest != OV_INVALID && (*rot) == NULL) {
1384        hwc_rect_t new_cropR;
1385        new_cropR.left = tmp_cropL.left;
1386        new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
1387
1388        hwc_rect_t new_cropL;
1389        new_cropL.left  = new_cropR.right;
1390        new_cropL.right = tmp_cropR.right;
1391
1392        tmp_cropL.left =  new_cropL.left;
1393        tmp_cropL.right =  new_cropL.right;
1394
1395        tmp_cropR.left = new_cropR.left;
1396        tmp_cropR.right =  new_cropR.right;
1397
1398    }
1399
1400    //For the mdp, since either we are pre-rotating or MDP does flips
1401    orient = OVERLAY_TRANSFORM_0;
1402    transform = 0;
1403
1404    //configure left mixer
1405    if(lDest != OV_INVALID) {
1406        PipeArgs pargL(mdpFlagsL, whf, z, isFg,
1407                       static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
1408                       (ovutils::eBlending) getBlending(layer->blending));
1409
1410        if(configMdp(ctx->mOverlay, pargL, orient,
1411                tmp_cropL, tmp_dstL, metadata, lDest) < 0) {
1412            ALOGE("%s: commit failed for left mixer config", __FUNCTION__);
1413            return -1;
1414        }
1415    }
1416
1417    //configure right mixer
1418    if(rDest != OV_INVALID) {
1419        PipeArgs pargR(mdpFlagsR, whf, z, isFg,
1420                       static_cast<eRotFlags>(rotFlags),
1421                       layer->planeAlpha,
1422                       (ovutils::eBlending) getBlending(layer->blending));
1423        tmp_dstR.right = tmp_dstR.right - lSplit;
1424        tmp_dstR.left = tmp_dstR.left - lSplit;
1425        if(configMdp(ctx->mOverlay, pargR, orient,
1426                tmp_cropR, tmp_dstR, metadata, rDest) < 0) {
1427            ALOGE("%s: commit failed for right mixer config", __FUNCTION__);
1428            return -1;
1429        }
1430    }
1431
1432    return 0;
1433}
1434
1435bool canUseRotator(hwc_context_t *ctx, int dpy) {
1436    if(qdutils::MDPVersion::getInstance().is8x26() &&
1437            ctx->mVirtualDisplay->isConnected() &&
1438            !ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].isPause) {
1439        // Allow if YUV needs rotation and DMA is configured to BLOCK mode for
1440        // primary. For portrait videos usecase on WFD, Driver supports
1441        // multiplexing of DMA pipe in LINE and BLOCK mode.
1442        if(dpy == HWC_DISPLAY_PRIMARY)
1443            return false;
1444    }
1445    if(ctx->mMDP.version == qdutils::MDP_V3_0_4)
1446        return false;
1447    return true;
1448}
1449
1450int getLeftSplit(hwc_context_t *ctx, const int& dpy) {
1451    //Default even split for all displays with high res
1452    int lSplit = ctx->dpyAttr[dpy].xres / 2;
1453    if(dpy == HWC_DISPLAY_PRIMARY &&
1454            qdutils::MDPVersion::getInstance().getLeftSplit()) {
1455        //Override if split published by driver for primary
1456        lSplit = qdutils::MDPVersion::getInstance().getLeftSplit();
1457    }
1458    return lSplit;
1459}
1460
1461void BwcPM::setBwc(hwc_context_t *ctx, const hwc_rect_t& crop,
1462            const hwc_rect_t& dst, const int& transform,
1463            ovutils::eMdpFlags& mdpFlags) {
1464    //Target doesnt support Bwc
1465    if(!qdutils::MDPVersion::getInstance().supportsBWC()) {
1466        return;
1467    }
1468    //src width > MAX mixer supported dim
1469    if((crop.right - crop.left) > qdutils::MAX_DISPLAY_DIM) {
1470        return;
1471    }
1472    //External connected
1473    if(ctx->mExtDisplay->isConnected()|| ctx->mVirtualDisplay->isConnected()) {
1474        return;
1475    }
1476    //Decimation necessary, cannot use BWC. H/W requirement.
1477    if(qdutils::MDPVersion::getInstance().supportsDecimation()) {
1478        int src_w = crop.right - crop.left;
1479        int src_h = crop.bottom - crop.top;
1480        int dst_w = dst.right - dst.left;
1481        int dst_h = dst.bottom - dst.top;
1482        if(transform & HAL_TRANSFORM_ROT_90) {
1483            swap(src_w, src_h);
1484        }
1485        float horDscale = 0.0f;
1486        float verDscale = 0.0f;
1487        int horzDeci = 0;
1488        int vertDeci = 0;
1489        ovutils::getDecimationFactor(src_w, src_h, dst_w, dst_h, horDscale,
1490                verDscale);
1491        //TODO Use log2f once math.h has it
1492        if((int)horDscale)
1493            horzDeci = (int)(log(horDscale) / log(2));
1494        if((int)verDscale)
1495            vertDeci = (int)(log(verDscale) / log(2));
1496        if(horzDeci || vertDeci) return;
1497    }
1498    //Property
1499    char value[PROPERTY_VALUE_MAX];
1500    property_get("debug.disable.bwc", value, "0");
1501     if(atoi(value)) return;
1502
1503    ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDSS_MDP_BWC_EN);
1504}
1505
1506void LayerRotMap::add(hwc_layer_1_t* layer, Rotator *rot) {
1507    if(mCount >= MAX_SESS) return;
1508    mLayer[mCount] = layer;
1509    mRot[mCount] = rot;
1510    mCount++;
1511}
1512
1513void LayerRotMap::reset() {
1514    for (int i = 0; i < MAX_SESS; i++) {
1515        mLayer[i] = 0;
1516        mRot[i] = 0;
1517    }
1518    mCount = 0;
1519}
1520
1521void LayerRotMap::setReleaseFd(const int& fence) {
1522    for(uint32_t i = 0; i < mCount; i++) {
1523        mRot[i]->setReleaseFd(dup(fence));
1524    }
1525}
1526
1527};//namespace qhwc
1528