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 
21 #ifndef HWC_UTILS_H
22 #define HWC_UTILS_H
23 
24 #define DEBUG_MDPDOWNSCALE 0
25 #define HWC_REMOVE_DEPRECATED_VERSIONS 1
26 
27 #include <fcntl.h>
28 #include <math.h>
29 #include <hardware/hwcomposer.h>
30 #include <gr.h>
31 #include <gralloc_priv.h>
32 #include <utils/String8.h>
33 #include "qdMetaData.h"
34 #include "mdp_version.h"
35 #include <overlayUtils.h>
36 #include <overlayRotator.h>
37 #include <EGL/egl.h>
38 
39 
40 #define ALIGN_TO(x, align)     (((x) + ((align)-1)) & ~((align)-1))
41 #define LIKELY( exp )       (__builtin_expect( (exp) != 0, true  ))
42 #define UNLIKELY( exp )     (__builtin_expect( (exp) != 0, false ))
43 #define MAX_NUM_APP_LAYERS 32
44 #define MAX_NUM_BLEND_STAGES 16
45 #define MIN_DISPLAY_XRES 200
46 #define MIN_DISPLAY_YRES 200
47 #define HWC_WFDDISPSYNC_LOG 0
48 #define STR(f) #f;
49 // Max number of PTOR layers handled
50 #define MAX_PTOR_LAYERS 2
51 #define MAX_NUM_COLOR_MODES 32
52 
53 //Fwrd decls
54 struct hwc_context_t;
55 
56 namespace ovutils = overlay::utils;
57 
58 namespace overlay {
59 class Overlay;
60 class Rotator;
61 class RotMgr;
62 }
63 
64 namespace qhwc {
65 //fwrd decl
66 class QueuedBufferStore;
67 class HDMIDisplay;
68 class VirtualDisplay;
69 class IFBUpdate;
70 class IVideoOverlay;
71 class MDPComp;
72 class CopyBit;
73 class HwcDebug;
74 class AssertiveDisplay;
75 class HWCVirtualVDS;
76 
77 
78 struct MDPInfo {
79     int version;
80     char panel;
81     bool hasOverlay;
82 };
83 
84 struct DisplayAttributes {
85     uint32_t refreshRate;
86     uint32_t dynRefreshRate;
87     uint32_t vsync_period; //nanos
88     uint32_t xres;
89     uint32_t yres;
90     uint32_t stride;
91     float xdpi;
92     float ydpi;
93     bool secure;
94     int fd;
95     bool connected; //Applies only to pluggable disp.
96     //Connected does not mean it ready to use.
97     //It should be active also. (UNBLANKED)
98     bool isActive;
99     // In pause state, composition is bypassed
100     // used for WFD displays and in QDCM calibration mode
101     bool isPause;
102     // To trigger padding round to clean up mdp
103     // pipes
104     bool isConfiguring;
105     // Indicates whether external/virtual display is in MDP scaling mode
106     bool mMDPScalingMode;
107     // Ext dst Rect
108     hwc_rect_t mDstRect;
109     //Action safe attributes
110     // Flag to indicate the presence of action safe dimensions for external
111     bool mActionSafePresent;
112     int mAsWidthRatio;
113     int mAsHeightRatio;
114 
115     //If property fbsize set via adb shell debug.hwc.fbsize = XRESxYRES
116     //following fields are used.
117     bool customFBSize;
118     uint32_t xres_new;
119     uint32_t yres_new;
120 
121 };
122 
123 struct ListStats {
124     int numAppLayers; //Total - 1, excluding FB layer.
125     int skipCount;
126     int fbLayerIndex; //Always last for now. = numAppLayers
127     //Video specific
128     int yuvCount;
129     int yuvIndices[MAX_NUM_APP_LAYERS];
130     bool preMultipliedAlpha;
131     int yuv4k2kIndices[MAX_NUM_APP_LAYERS];
132     int yuv4k2kCount;
133     // Notifies hwcomposer about the start and end of animation
134     // This will be set to true during animation, otherwise false.
135     bool isDisplayAnimating;
136     bool secureUI; // Secure display layer
137     bool isSecurePresent;
138     hwc_rect_t lRoi;  //left ROI
139     hwc_rect_t rRoi;  //right ROI. Unused in single DSI panels.
140     //App Buffer Composition index
141     int  renderBufIndexforABC;
142     // Secure RGB specific
143     int secureRGBCount;
144     int secureRGBIndices[MAX_NUM_APP_LAYERS];
145     //dyn refresh rate-Client requested refreshrate
146     uint32_t refreshRateRequest;
147     // Flag related to windowboxing feature
148     bool mAIVVideoMode;
149 };
150 
151 //PTOR Comp info
152 struct PtorInfo {
153     int count;
154     int layerIndex[MAX_PTOR_LAYERS];
155     hwc_rect_t displayFrame[MAX_PTOR_LAYERS];
isActivePtorInfo156     bool isActive() { return (count>0); }
getPTORArrayIndexPtorInfo157     int getPTORArrayIndex(int index) {
158         int idx = -1;
159         for(int i = 0; i < count; i++) {
160             if(index == layerIndex[i])
161                 idx = i;
162         }
163         return idx;
164     }
165 };
166 
167 struct LayerProp {
168     uint32_t mFlags; //qcom specific layer flags
LayerPropLayerProp169     LayerProp():mFlags(0){};
170 };
171 
172 struct VsyncState {
173     bool enable;
174     bool fakevsync;
175     bool debug;
176 };
177 
178 struct BwcPM {
179     static void setBwc(const hwc_context_t *ctx, const int& dpy,
180             const private_handle_t *hnd,
181             const hwc_rect_t& crop, const hwc_rect_t& dst,
182             const int& transform, const int& downscale,
183             ovutils::eMdpFlags& mdpFlags);
184 };
185 
186 // LayerProp::flag values
187 enum {
188     HWC_MDPCOMP = 0x00000001,
189     HWC_COPYBIT = 0x00000002,
190 };
191 
192 // AIV specific flags
193 enum {
194     HWC_AIV_VIDEO = 0x80000000,
195     HWC_AIV_CC    = 0x40000000,
196 };
197 
198 // HAL specific features
199 enum {
200     HWC_COLOR_FILL = 0x00000008,
201     HWC_FORMAT_RB_SWAP = 0x00000040,
202 };
203 
204 /* External Display states */
205 enum {
206     EXTERNAL_OFFLINE = 0,
207     EXTERNAL_ONLINE,
208     EXTERNAL_PAUSE,
209     EXTERNAL_RESUME,
210     EXTERNAL_MAXSTATES
211 };
212 
213 class LayerRotMap {
214 public:
LayerRotMap()215     LayerRotMap() { reset(); }
216     void add(hwc_layer_1_t* layer, overlay::Rotator *rot);
217     //Resets the mapping of layer to rotator
218     void reset();
219     //Clears mappings and existing rotator fences
220     //Intended to be used during errors
221     void clear();
222     uint32_t getCount() const;
223     hwc_layer_1_t* getLayer(uint32_t index) const;
224     overlay::Rotator* getRot(uint32_t index) const;
225     bool isRotCached(uint32_t index) const;
226     void setReleaseFd(const int& fence);
227 private:
228     hwc_layer_1_t* mLayer[overlay::RotMgr::MAX_ROT_SESS];
229     overlay::Rotator* mRot[overlay::RotMgr::MAX_ROT_SESS];
230     uint32_t mCount;
231 };
232 
233 //ColorModes for primary displays
234 class ColorMode {
235 public:
236     void init();
237     void destroy();
getNumModes()238     int32_t getNumModes() { return mNumModes; }
getModeList()239     const int32_t* getModeList() { return mModeList; }
240     int32_t getModeForIndex(int32_t index);
241     int32_t getIndexForMode(int32_t mode);
242     int applyDefaultMode();
243     int applyModeByID(int modeID);
244     int applyModeByIndex(int index);
245     int setDefaultMode(int modeID);
getActiveModeIndex()246     int getActiveModeIndex() { return mCurModeIndex; }
247 private:
248     int32_t (*fnGetNumModes)(int /*dispID*/);
249     int32_t (*fnGetCurrentMode)(int /*dispID*/);
250     int32_t (*fnGetModeList)(int32_t* /*mModeList*/, int32_t* /*current default*/,
251             int32_t /*dispID*/);
252     int (*fnApplyDefaultMode)(int /*dispID*/);
253     int (*fnApplyModeById)(int /*modeID*/, int /*dispID*/);
254     int (*fnSetDefaultMode)(int /*modeID*/, int /*dispID*/);
255     int (*fnDeleteInstance)();
256 
257     void*     mModeHandle = NULL;
258     int32_t   mModeList[MAX_NUM_COLOR_MODES];
259     int32_t   mNumModes = 0;
260     int32_t   mCurModeIndex = 0;
261     int32_t   mCurMode = 0;
262 
263 };
264 
getCount()265 inline uint32_t LayerRotMap::getCount() const {
266     return mCount;
267 }
268 
getLayer(uint32_t index)269 inline hwc_layer_1_t* LayerRotMap::getLayer(uint32_t index) const {
270     if(index >= mCount) return NULL;
271     return mLayer[index];
272 }
273 
getRot(uint32_t index)274 inline overlay::Rotator* LayerRotMap::getRot(uint32_t index) const {
275     if(index >= mCount) return NULL;
276     return mRot[index];
277 }
278 
integerizeSourceCrop(const hwc_frect_t & cropF)279 inline hwc_rect_t integerizeSourceCrop(const hwc_frect_t& cropF) {
280     hwc_rect_t cropI = {0,0,0,0};
281     cropI.left = int(ceilf(cropF.left));
282     cropI.top = int(ceilf(cropF.top));
283     cropI.right = int(floorf(cropF.right));
284     cropI.bottom = int(floorf(cropF.bottom));
285     return cropI;
286 }
287 
isNonIntegralSourceCrop(const hwc_frect_t & cropF)288 inline bool isNonIntegralSourceCrop(const hwc_frect_t& cropF) {
289     if(cropF.left - roundf(cropF.left)     ||
290        cropF.top - roundf(cropF.top)       ||
291        cropF.right - roundf(cropF.right)   ||
292        cropF.bottom - roundf(cropF.bottom))
293         return true;
294     else
295         return false;
296 }
297 
298 // -----------------------------------------------------------------------------
299 // Utility functions - implemented in hwc_utils.cpp
300 void dumpLayer(hwc_layer_1_t const* l);
301 void setListStats(hwc_context_t *ctx, hwc_display_contents_1_t *list,
302         int dpy);
303 void initContext(hwc_context_t *ctx);
304 void closeContext(hwc_context_t *ctx);
305 //Crops source buffer against destination and FB boundaries
306 void calculate_crop_rects(hwc_rect_t& crop, hwc_rect_t& dst,
307                          const hwc_rect_t& scissor, int orient);
308 void getNonWormholeRegion(hwc_display_contents_1_t* list,
309                               hwc_rect_t& nwr);
310 bool isSecuring(hwc_context_t* ctx, hwc_layer_1_t const* layer);
311 bool isSecureModePolicy(int mdpVersion);
312 // Returns true, if the input layer format is supported by rotator
313 bool isRotatorSupportedFormat(private_handle_t *hnd);
314 //Returns true, if the layer is YUV or the layer has been rendered by CPU
315 bool isRotationDoable(hwc_context_t *ctx, private_handle_t *hnd);
316 bool isExternalActive(hwc_context_t* ctx);
317 bool isAlphaScaled(hwc_layer_1_t const* layer);
318 bool needsScaling(hwc_layer_1_t const* layer);
319 bool isDownscaleRequired(hwc_layer_1_t const* layer);
320 bool needsScalingWithSplit(hwc_context_t* ctx, hwc_layer_1_t const* layer,
321                            const int& dpy);
322 void sanitizeSourceCrop(hwc_rect_t& cropL, hwc_rect_t& cropR,
323                         private_handle_t *hnd);
324 bool isAlphaPresent(hwc_layer_1_t const* layer);
325 int hwc_vsync_control(hwc_context_t* ctx, int dpy, int enable);
326 int getBlending(int blending);
327 bool isGLESOnlyComp(hwc_context_t *ctx, const int& dpy);
328 void reset_layer_prop(hwc_context_t* ctx, int dpy, int numAppLayers);
329 bool isAbcInUse(hwc_context_t *ctx);
330 
331 void dumpBuffer(private_handle_t *ohnd, char *bufferName);
332 void updateDisplayInfo(hwc_context_t* ctx, int dpy);
333 void resetDisplayInfo(hwc_context_t* ctx, int dpy);
334 void initCompositionResources(hwc_context_t* ctx, int dpy);
335 void destroyCompositionResources(hwc_context_t* ctx, int dpy);
336 void clearPipeResources(hwc_context_t* ctx, int dpy);
337 
338 //Helper function to dump logs
339 void dumpsys_log(android::String8& buf, const char* fmt, ...);
340 
341 int getExtOrientation(hwc_context_t* ctx);
342 bool isValidRect(const hwc_rect_t& rect);
343 hwc_rect_t deductRect(const hwc_rect_t& rect1, const hwc_rect_t& rect2);
344 bool isSameRect(const hwc_rect& rect1, const hwc_rect& rect2);
345 hwc_rect_t moveRect(const hwc_rect_t& rect, const int& x_off, const int& y_off);
346 hwc_rect_t getIntersection(const hwc_rect_t& rect1, const hwc_rect_t& rect2);
347 hwc_rect_t getUnion(const hwc_rect_t& rect1, const hwc_rect_t& rect2);
348 void optimizeLayerRects(const hwc_display_contents_1_t *list);
349 bool areLayersIntersecting(const hwc_layer_1_t* layer1,
350         const hwc_layer_1_t* layer2);
351 bool operator ==(const hwc_rect_t& lhs, const hwc_rect_t& rhs);
352 bool layerUpdating(const hwc_layer_1_t* layer);
353 
354 // returns true if Action safe dimensions are set and target supports Actionsafe
355 bool isActionSafePresent(hwc_context_t *ctx, int dpy);
356 
357 /* Calculates the destination position based on the action safe rectangle */
358 void getActionSafePosition(hwc_context_t *ctx, int dpy, hwc_rect_t& dst);
359 
360 void getAspectRatioPosition(hwc_context_t* ctx, int dpy, int extOrientation,
361                                 hwc_rect_t& inRect, hwc_rect_t& outRect);
362 
363 uint32_t roundOff(uint32_t refreshRate);
364 
365 void setRefreshRate(hwc_context_t *ctx, int dpy, uint32_t refreshRate);
366 
367 bool isPrimaryPortrait(hwc_context_t *ctx);
368 
369 bool isOrientationPortrait(hwc_context_t *ctx);
370 
371 void calcExtDisplayPosition(hwc_context_t *ctx,
372                                private_handle_t *hnd,
373                                int dpy,
374                                hwc_rect_t& sourceCrop,
375                                hwc_rect_t& displayFrame,
376                                int& transform,
377                                ovutils::eTransform& orient);
378 
379 // Returns the orientation that needs to be set on external for
380 // BufferMirrirMode(Sidesync)
381 int getMirrorModeOrientation(hwc_context_t *ctx);
382 
383 /* Get External State names */
384 const char* getExternalDisplayState(uint32_t external_state);
385 
386 // Resets display ROI to full panel resoluion
387 void resetROI(hwc_context_t *ctx, const int dpy);
388 
389 // Modifies ROI even from middle of the screen
390 hwc_rect expandROIFromMidPoint(hwc_rect roi, hwc_rect fullFrame);
391 
392 // Aligns updating ROI to panel restrictions
393 hwc_rect_t getSanitizeROI(struct hwc_rect roi, hwc_rect boundary);
394 
395 // Handles wfd Pause and resume events
396 void handle_pause(hwc_context_t *ctx, int dpy);
397 void handle_resume(hwc_context_t *ctx, int dpy);
398 
399 // Handle ONLINE/OFFLINE for HDMI display
400 void handle_online(hwc_context_t* ctx, int dpy);
401 void handle_offline(hwc_context_t* ctx, int dpy);
402 
403 //Close acquireFenceFds of all layers of incoming list
404 void closeAcquireFds(hwc_display_contents_1_t* list);
405 
406 //Sync point impl.
407 int hwc_sync(hwc_context_t *ctx, hwc_display_contents_1_t* list, int dpy,
408         int fd);
409 
410 //Sets appropriate mdp flags for a layer.
411 void setMdpFlags(hwc_context_t *ctx, hwc_layer_1_t *layer,
412         ovutils::eMdpFlags &mdpFlags,
413         int rotDownscale, int transform);
414 
415 int configRotator(overlay::Rotator *rot, ovutils::Whf& whf,
416         hwc_rect_t& crop, const ovutils::eMdpFlags& mdpFlags,
417         const ovutils::eTransform& orient, const int& downscale);
418 
419 int configMdp(overlay::Overlay *ov, const ovutils::PipeArgs& parg,
420         const ovutils::eTransform& orient, const hwc_rect_t& crop,
421         const hwc_rect_t& pos, const MetaData_t *metadata,
422         const ovutils::eDest& dest);
423 
424 int configColorLayer(hwc_context_t *ctx, hwc_layer_1_t *layer, const int& dpy,
425         ovutils::eMdpFlags& mdpFlags, ovutils::eZorder& z,
426         const ovutils::eDest& dest);
427 
428 void updateSource(ovutils::eTransform& orient, ovutils::Whf& whf,
429         hwc_rect_t& crop, overlay::Rotator *rot);
430 
431 bool isZoomModeEnabled(hwc_rect_t crop);
432 void updateCropAIVVideoMode(hwc_context_t *ctx, hwc_rect_t& crop, int dpy);
433 void updateDestAIVVideoMode(hwc_context_t *ctx, hwc_rect_t& dst, int dpy);
434 void updateCoordinates(hwc_context_t *ctx, hwc_rect_t& crop,
435                            hwc_rect_t& dst, int dpy);
436 
437 //Routine to configure low resolution panels (<= 2048 width)
438 int configureNonSplit(hwc_context_t *ctx, hwc_layer_1_t *layer, const int& dpy,
439         ovutils::eMdpFlags& mdpFlags, ovutils::eZorder& z,
440         const ovutils::eDest& dest,
441         overlay::Rotator **rot);
442 
443 //Routine to configure high resolution panels (> 2048 width)
444 int configureSplit(hwc_context_t *ctx, hwc_layer_1_t *layer, const int& dpy,
445         ovutils::eMdpFlags& mdpFlags, ovutils::eZorder& z,
446         const ovutils::eDest& lDest,
447         const ovutils::eDest& rDest, overlay::Rotator **rot);
448 
449 //Routine to split and configure high resolution YUV layer (> 2048 width)
450 int configureSourceSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
451         const int& dpy,
452         ovutils::eMdpFlags& mdpFlags, ovutils::eZorder& z,
453         const ovutils::eDest& lDest,
454         const ovutils::eDest& rDest, overlay::Rotator **rot);
455 
456 //On certain targets DMA pipes are used for rotation and they won't be available
457 //for line operations. On a per-target basis we can restrict certain use cases
458 //from using rotator, since we know before-hand that such scenarios can lead to
459 //extreme unavailability of pipes. This can also be done via hybrid calculations
460 //also involving many more variables like number of write-back interfaces etc,
461 //but the variety of scenarios is too high to warrant that.
462 bool canUseRotator(hwc_context_t *ctx, int dpy);
463 
464 int getLeftSplit(hwc_context_t *ctx, const int& dpy);
465 
466 bool isDisplaySplit(hwc_context_t* ctx, int dpy);
467 
468 int getRotDownscale(hwc_context_t *ctx, const hwc_layer_1_t *layer);
469 
470 // Set the GPU hint flag to high for MIXED/GPU composition only for
471 // first frame after MDP to GPU/MIXED mode transition.
472 // Set the GPU hint to default if the current composition type is GPU
473 // due to idle fallback or MDP composition.
474 void setGPUHint(hwc_context_t* ctx, hwc_display_contents_1_t* list);
475 
476 // Returns true if rect1 is peripheral to rect2, false otherwise.
477 bool isPeripheral(const hwc_rect_t& rect1, const hwc_rect_t& rect2);
478 
479 // Applies default mode at boot
480 void applyDefaultMode(hwc_context_t *ctx);
481 
482 // Inline utility functions
isSkipLayer(const hwc_layer_1_t * l)483 static inline bool isSkipLayer(const hwc_layer_1_t* l) {
484     return (UNLIKELY(l && (l->flags & HWC_SKIP_LAYER)));
485 }
486 
isAIVVideoLayer(const hwc_layer_1_t * l)487 static inline bool isAIVVideoLayer(const hwc_layer_1_t* l) {
488     return (UNLIKELY(l && (l->flags & HWC_AIV_VIDEO)));
489 }
490 
isAIVCCLayer(const hwc_layer_1_t * l)491 static inline bool isAIVCCLayer(const hwc_layer_1_t* l) {
492     return (UNLIKELY(l && (l->flags & HWC_AIV_CC)));
493 }
494 
495 // Returns true if the buffer is yuv
isYuvBuffer(const private_handle_t * hnd)496 static inline bool isYuvBuffer(const private_handle_t* hnd) {
497     return (hnd && (hnd->bufferType == BUFFER_TYPE_VIDEO));
498 }
499 
500 // Returns true if the buffer is yuv and exceeds the mixer width
isYUVSplitNeeded(const private_handle_t * hnd)501 static inline bool isYUVSplitNeeded(const private_handle_t* hnd) {
502     int maxPipeWidth = qdutils::MDPVersion::getInstance().getMaxPipeWidth();
503     return (hnd && (hnd->bufferType == BUFFER_TYPE_VIDEO) &&
504             (hnd->width > maxPipeWidth));
505 }
506 
507 // Returns true if the buffer is secure
isSecureBuffer(const private_handle_t * hnd)508 static inline bool isSecureBuffer(const private_handle_t* hnd) {
509     return (hnd && (private_handle_t::PRIV_FLAGS_SECURE_BUFFER & hnd->flags));
510 }
511 
512 // Returns true if the buffer is protected
isProtectedBuffer(const private_handle_t * hnd)513 static inline bool isProtectedBuffer(const private_handle_t* hnd) {
514     return (hnd && (private_handle_t::PRIV_FLAGS_PROTECTED_BUFFER & hnd->flags));
515 }
516 
517 
isTileRendered(const private_handle_t * hnd)518 static inline bool isTileRendered(const private_handle_t* hnd) {
519     return (hnd && (private_handle_t::PRIV_FLAGS_TILE_RENDERED & hnd->flags));
520 }
521 
522 //Return true if the buffer is intended for Secure Display
isSecureDisplayBuffer(const private_handle_t * hnd)523 static inline bool isSecureDisplayBuffer(const private_handle_t* hnd) {
524     return (hnd && (hnd->flags & private_handle_t::PRIV_FLAGS_SECURE_DISPLAY));
525 }
526 
getWidth(const private_handle_t * hnd)527 static inline int getWidth(const private_handle_t* hnd) {
528     MetaData_t *metadata = reinterpret_cast<MetaData_t*>(hnd->base_metadata);
529     if(metadata && metadata->operation & UPDATE_BUFFER_GEOMETRY) {
530         return metadata->bufferDim.sliceWidth;
531     }
532     return hnd->width;
533 }
534 
getHeight(const private_handle_t * hnd)535 static inline int getHeight(const private_handle_t* hnd) {
536     MetaData_t *metadata = reinterpret_cast<MetaData_t*>(hnd->base_metadata);
537     if(metadata && metadata->operation & UPDATE_BUFFER_GEOMETRY) {
538         return metadata->bufferDim.sliceHeight;
539     }
540     return hnd->height;
541 }
542 
max(T a,T b)543 template<typename T> inline T max(T a, T b) { return (a > b) ? a : b; }
min(T a,T b)544 template<typename T> inline T min(T a, T b) { return (a < b) ? a : b; }
545 
546 // Initialize uevent thread
547 void init_uevent_thread(hwc_context_t* ctx);
548 // Initialize vsync thread
549 void init_vsync_thread(hwc_context_t* ctx);
550 
getLayerResolution(const hwc_layer_1_t * layer,int & width,int & height)551 inline void getLayerResolution(const hwc_layer_1_t* layer,
552                                int& width, int& height) {
553     hwc_rect_t displayFrame  = layer->displayFrame;
554     width = displayFrame.right - displayFrame.left;
555     height = displayFrame.bottom - displayFrame.top;
556 }
557 
openFb(int dpy)558 static inline int openFb(int dpy) {
559     int fd = -1;
560     const char *devtmpl = "/dev/graphics/fb%u";
561     char name[64] = {0};
562     snprintf(name, 64, devtmpl, dpy);
563     fd = open(name, O_RDWR);
564     return fd;
565 }
566 
567 template <class T>
swap(T & a,T & b)568 inline void swap(T& a, T& b) {
569     T tmp = a;
570     a = b;
571     b = tmp;
572 }
573 
574 }; //qhwc namespace
575 
576 enum eAnimationState{
577     ANIMATION_STOPPED,
578     ANIMATION_STARTED,
579 };
580 
581 enum eCompositionState {
582     COMPOSITION_STATE_MDP = 0,        // Set if composition type is MDP
583     COMPOSITION_STATE_GPU,            // Set if composition type is GPU or MIXED
584     COMPOSITION_STATE_IDLE_FALLBACK,  // Set if it is idlefallback
585 };
586 
587 // Structure holds the information about the GPU hint.
588 struct gpu_hint_info {
589     // system level flag to enable gpu_perf_mode
590     bool mGpuPerfModeEnable;
591     // Stores the current GPU performance mode DEFAULT/HIGH
592     bool mCurrGPUPerfMode;
593     // Stores the compositon state GPU, MDP or IDLE_FALLBACK
594     bool mCompositionState;
595     // Stores the EGLContext of current process
596     EGLContext mEGLContext;
597     // Stores the EGLDisplay of current process
598     EGLDisplay mEGLDisplay;
599 };
600 
601 // -----------------------------------------------------------------------------
602 // HWC context
603 // This structure contains overall state
604 struct hwc_context_t {
605     hwc_composer_device_1_t device;
606     const hwc_procs_t* proc;
607 
608     //CopyBit objects
609     qhwc::CopyBit *mCopyBit[HWC_NUM_DISPLAY_TYPES];
610 
611     //Overlay object - NULL for non overlay devices
612     overlay::Overlay *mOverlay;
613     //Holds a few rot objects
614     overlay::RotMgr *mRotMgr;
615 
616     //Primary and external FB updater
617     qhwc::IFBUpdate *mFBUpdate[HWC_NUM_DISPLAY_TYPES];
618     // HDMI display related object. Used to configure/teardown
619     // HDMI when it is connected as primary or external.
620     qhwc::HDMIDisplay *mHDMIDisplay;
621     qhwc::MDPInfo mMDP;
622     qhwc::VsyncState vstate;
623     qhwc::DisplayAttributes dpyAttr[HWC_NUM_DISPLAY_TYPES];
624     qhwc::ListStats listStats[HWC_NUM_DISPLAY_TYPES];
625     qhwc::LayerProp *layerProp[HWC_NUM_DISPLAY_TYPES];
626     qhwc::MDPComp *mMDPComp[HWC_NUM_DISPLAY_TYPES];
627     qhwc::HwcDebug *mHwcDebug[HWC_NUM_DISPLAY_TYPES];
628     hwc_rect_t mViewFrame[HWC_NUM_DISPLAY_TYPES];
629     qhwc::AssertiveDisplay *mAD;
630     eAnimationState mAnimationState[HWC_NUM_DISPLAY_TYPES];
631     qhwc::HWCVirtualVDS *mHWCVirtual;
632 
633     // stores the #numHwLayers of the previous frame
634     // for each display device
635     int mPrevHwLayerCount[HWC_NUM_DISPLAY_TYPES];
636 
637     // stores the primary device orientation
638     int deviceOrientation;
639     //Securing in progress indicator
640     bool mSecuring;
641     //Display in secure mode indicator
642     bool mSecureMode;
643     //Lock to protect drawing data structures
644     mutable Locker mDrawLock;
645     //Drawing round when we use GPU
646     bool isPaddingRound;
647     // Used to mark composition cycle when DMA state change is required
648     bool isDMAStateChanging;
649     // External Orientation
650     int mExtOrientation;
651     //Flags the transition of a video session
652     bool mVideoTransFlag;
653     //Used for SideSync feature
654     //which overrides the mExtOrientation
655     bool mBufferMirrorMode;
656     // Used to synchronize between WFD and Display modules
657     mutable Locker mWfdSyncLock;
658 
659     qhwc::LayerRotMap *mLayerRotMap[HWC_NUM_DISPLAY_TYPES];
660     // Panel reset flag will be set if BTA check fails
661     bool mPanelResetStatus;
662     // number of active Displays
663     int numActiveDisplays;
664     struct gpu_hint_info mGPUHintInfo;
665     //App Buffer Composition
666     bool enableABC;
667     // PTOR Info
668     qhwc::PtorInfo mPtorInfo;
669     //Running in Thermal burst mode
670     bool mThermalBurstMode;
671     //Layers out of ROI
672     bool copybitDrop[MAX_NUM_APP_LAYERS];
673     // Flag related to windowboxing feature
674     bool mWindowboxFeature;
675     // This denotes the tolerance between video layer and external display
676     // aspect ratio
677     float mAspectRatioToleranceLevel;
678     // Runtime switch for BWC for targets that support it
679     bool mBWCEnabled;
680     // Provides a way for OEM's to disable setting dynfps via metadata.
681     bool mUseMetaDataRefreshRate;
682    // Stores the hpd enabled status- avoids re-enabling HDP on suspend resume.
683     bool mHPDEnabled;
684     //Used to notify that default mode has been applied
685     bool mDefaultModeApplied;
686     //Manages color modes
687     qhwc::ColorMode *mColorMode;
688     // Indicates whether cool color temperature is enabled.
689     bool mCoolColorTemperatureEnabled;
690 };
691 
692 namespace qhwc {
isSkipPresent(hwc_context_t * ctx,int dpy)693 static inline bool isSkipPresent (hwc_context_t *ctx, int dpy) {
694     return  ctx->listStats[dpy].skipCount;
695 }
696 
isYuvPresent(hwc_context_t * ctx,int dpy)697 static inline bool isYuvPresent (hwc_context_t *ctx, int dpy) {
698     return  ctx->listStats[dpy].yuvCount;
699 }
700 
has90Transform(hwc_layer_1_t const * layer)701 static inline bool has90Transform(hwc_layer_1_t const* layer) {
702     return ((layer->transform & HWC_TRANSFORM_ROT_90) &&
703             !(layer->flags & HWC_COLOR_FILL));
704 }
705 
isSecurePresent(hwc_context_t * ctx,int dpy)706 inline bool isSecurePresent(hwc_context_t *ctx, int dpy) {
707     return ctx->listStats[dpy].isSecurePresent;
708 }
709 
isSecondaryConfiguring(hwc_context_t * ctx)710 static inline bool isSecondaryConfiguring(hwc_context_t* ctx) {
711     return (ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].isConfiguring ||
712             ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].isConfiguring);
713 }
714 
isSecondaryConnected(hwc_context_t * ctx)715 static inline bool isSecondaryConnected(hwc_context_t* ctx) {
716     return (ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].connected ||
717             ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].connected);
718 }
719 
720 /* Return Virtual Display connection status */
isVDConnected(hwc_context_t * ctx)721 static inline bool isVDConnected(hwc_context_t* ctx) {
722     return ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].connected;
723 }
724 
getLayerClock(const uint32_t & dstW,const uint32_t & dstH,const uint32_t & srcH)725 inline uint32_t getLayerClock(const uint32_t& dstW, const uint32_t& dstH,
726         const uint32_t& srcH) {
727     return max(dstW, (srcH * dstW) / dstH);
728 }
729 
730 };
731 
732 #endif //HWC_UTILS_H
733