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