1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 * Copyright (C)2012-2013, The Linux Foundation. All rights reserved.
4 *
5 * Not a Contribution, Apache license notifications and license are retained
6 * for attribution purposes only.
7 *
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 *      http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 */
20
21#ifndef HWC_UTILS_H
22#define HWC_UTILS_H
23
24#define HWC_REMOVE_DEPRECATED_VERSIONS 1
25#include <fcntl.h>
26#include <math.h>
27#include <hardware/hwcomposer.h>
28#include <gr.h>
29#include <gralloc_priv.h>
30#include <utils/String8.h>
31#include <linux/fb.h>
32#include "qdMetaData.h"
33#include <overlayUtils.h>
34
35#define ALIGN_TO(x, align)     (((x) + ((align)-1)) & ~((align)-1))
36#define LIKELY( exp )       (__builtin_expect( (exp) != 0, true  ))
37#define UNLIKELY( exp )     (__builtin_expect( (exp) != 0, false ))
38#define MAX_NUM_APP_LAYERS 32
39
40// For support of virtual displays
41#define MAX_DISPLAYS            (HWC_NUM_DISPLAY_TYPES)
42
43//Fwrd decls
44struct hwc_context_t;
45
46namespace ovutils = overlay::utils;
47
48namespace overlay {
49class Overlay;
50class Rotator;
51class RotMgr;
52}
53
54namespace qhwc {
55//fwrd decl
56class QueuedBufferStore;
57class ExternalDisplay;
58class IFBUpdate;
59class IVideoOverlay;
60class MDPComp;
61class CopyBit;
62class AssertiveDisplay;
63
64
65struct MDPInfo {
66    int version;
67    char panel;
68    bool hasOverlay;
69};
70
71struct DisplayAttributes {
72    uint32_t vsync_period; //nanos
73    uint32_t xres;
74    uint32_t yres;
75    uint32_t stride;
76    float xdpi;
77    float ydpi;
78    int fd;
79    bool connected; //Applies only to secondary displays
80    //Connected does not mean it ready to use.
81    //It should be active also. (UNBLANKED)
82    bool isActive;
83    // In pause state, composition is bypassed
84    // used for WFD displays only
85    bool isPause;
86    //Secondary displays will have this set until they are able to acquire
87    //pipes.
88    bool isConfiguring;
89};
90
91struct ListStats {
92    int numAppLayers; //Total - 1, excluding FB layer.
93    int skipCount;
94    int fbLayerIndex; //Always last for now. = numAppLayers
95    //Video specific
96    int yuvCount;
97    int yuvIndices[MAX_NUM_APP_LAYERS];
98    bool needsAlphaScale;
99    bool preMultipliedAlpha;
100    bool planeAlpha;
101    bool isSecurePresent;
102};
103
104struct LayerProp {
105    uint32_t mFlags; //qcom specific layer flags
106    LayerProp():mFlags(0) {};
107};
108
109struct VsyncState {
110    bool enable;
111    bool fakevsync;
112};
113
114struct BwcPM {
115    static void setBwc(hwc_context_t *ctx, const hwc_rect_t& crop,
116            const hwc_rect_t& dst, const int& transform,
117            ovutils::eMdpFlags& mdpFlags);
118};
119
120// LayerProp::flag values
121enum {
122    HWC_MDPCOMP = 0x00000001,
123    HWC_COPYBIT = 0x00000002,
124};
125
126class LayerRotMap {
127public:
128    LayerRotMap() { reset(); }
129    enum { MAX_SESS = 3 };
130    void add(hwc_layer_1_t* layer, overlay::Rotator *rot);
131    void reset();
132    uint32_t getCount() const;
133    hwc_layer_1_t* getLayer(uint32_t index) const;
134    overlay::Rotator* getRot(uint32_t index) const;
135    void setReleaseFd(const int& fence);
136private:
137    hwc_layer_1_t* mLayer[MAX_SESS];
138    overlay::Rotator* mRot[MAX_SESS];
139    uint32_t mCount;
140};
141
142inline uint32_t LayerRotMap::getCount() const {
143    return mCount;
144}
145
146inline hwc_layer_1_t* LayerRotMap::getLayer(uint32_t index) const {
147    if(index >= mCount) return NULL;
148    return mLayer[index];
149}
150
151inline overlay::Rotator* LayerRotMap::getRot(uint32_t index) const {
152    if(index >= mCount) return NULL;
153    return mRot[index];
154}
155
156inline hwc_rect_t integerizeSourceCrop(const hwc_frect_t& cropF) {
157    hwc_rect_t cropI = {0};
158    cropI.left = int(ceilf(cropF.left));
159    cropI.top = int(ceilf(cropF.top));
160    cropI.right = int(floorf(cropF.right));
161    cropI.bottom = int(floorf(cropF.bottom));
162    return cropI;
163}
164
165inline bool isNonIntegralSourceCrop(const hwc_frect_t& cropF) {
166    if(cropF.left - roundf(cropF.left)     ||
167       cropF.top - roundf(cropF.top)       ||
168       cropF.right - roundf(cropF.right)   ||
169       cropF.bottom - roundf(cropF.bottom))
170        return true;
171    else
172        return false;
173}
174
175// -----------------------------------------------------------------------------
176// Utility functions - implemented in hwc_utils.cpp
177void dumpLayer(hwc_layer_1_t const* l);
178void setListStats(hwc_context_t *ctx, const hwc_display_contents_1_t *list,
179        int dpy);
180void initContext(hwc_context_t *ctx);
181void closeContext(hwc_context_t *ctx);
182//Crops source buffer against destination and FB boundaries
183void calculate_crop_rects(hwc_rect_t& crop, hwc_rect_t& dst,
184                         const hwc_rect_t& scissor, int orient);
185void getNonWormholeRegion(hwc_display_contents_1_t* list,
186                              hwc_rect_t& nwr);
187bool isSecuring(hwc_context_t* ctx, hwc_layer_1_t const* layer);
188bool isSecureModePolicy(int mdpVersion);
189bool needsScaling(hwc_context_t* ctx, hwc_layer_1_t const* layer, const int& dpy);
190bool isAlphaPresent(hwc_layer_1_t const* layer);
191int hwc_vsync_control(hwc_context_t* ctx, int dpy, int enable);
192int getBlending(int blending);
193bool isGLESOnlyComp(hwc_context_t *ctx, const int& dpy);
194
195//Helper function to dump logs
196void dumpsys_log(android::String8& buf, const char* fmt, ...);
197
198/* Calculates the destination position based on the action safe rectangle */
199void getActionSafePosition(hwc_context_t *ctx, int dpy, uint32_t& x,
200                                        uint32_t& y, uint32_t& w, uint32_t& h);
201
202//Close acquireFenceFds of all layers of incoming list
203void closeAcquireFds(hwc_display_contents_1_t* list, int dpy);
204
205//Sync point impl.
206int hwc_sync(hwc_context_t *ctx, hwc_display_contents_1_t* list, int dpy,
207        int fd);
208
209//Trims a layer's source crop which is outside of screen boundary.
210void trimLayer(hwc_context_t *ctx, const int& dpy, const int& transform,
211        hwc_rect_t& crop, hwc_rect_t& dst);
212
213//Sets appropriate mdp flags for a layer.
214void setMdpFlags(hwc_layer_1_t *layer,
215        ovutils::eMdpFlags &mdpFlags,
216        int rotDownscale);
217
218int configRotator(overlay::Rotator *rot, const ovutils::Whf& whf,
219        hwc_rect_t& crop, const ovutils::eMdpFlags& mdpFlags,
220        const ovutils::eTransform& orient, const int& downscale);
221
222int configMdp(overlay::Overlay *ov, const ovutils::PipeArgs& parg,
223        const ovutils::eTransform& orient, const hwc_rect_t& crop,
224        const hwc_rect_t& pos, const MetaData_t *metadata,
225        const ovutils::eDest& dest);
226
227void updateSource(ovutils::eTransform& orient, ovutils::Whf& whf,
228        hwc_rect_t& crop);
229
230//Routine to configure low resolution panels (<= 2048 width)
231int configureLowRes(hwc_context_t *ctx, hwc_layer_1_t *layer, const int& dpy,
232        ovutils::eMdpFlags& mdpFlags, const ovutils::eZorder& z,
233        const ovutils::eIsFg& isFg, const ovutils::eDest& dest,
234        overlay::Rotator **rot);
235
236//Routine to configure high resolution panels (> 2048 width)
237int configureHighRes(hwc_context_t *ctx, hwc_layer_1_t *layer, const int& dpy,
238        ovutils::eMdpFlags& mdpFlags, const ovutils::eZorder& z,
239        const ovutils::eIsFg& isFg, const ovutils::eDest& lDest,
240        const ovutils::eDest& rDest, overlay::Rotator **rot);
241
242//On certain targets DMA pipes are used for rotation and they won't be available
243//for line operations. On a per-target basis we can restrict certain use cases
244//from using rotator, since we know before-hand that such scenarios can lead to
245//extreme unavailability of pipes. This can also be done via hybrid calculations
246//also involving many more variables like number of write-back interfaces etc,
247//but the variety of scenarios is too high to warrant that.
248bool canUseRotator(hwc_context_t *ctx, int dpy);
249
250int getLeftSplit(hwc_context_t *ctx, const int& dpy);
251
252//Sets up composition objects for secondary displays when they are added.
253//Should be called with extlock held.
254void setupSecondaryObjs(hwc_context_t *ctx, const int& dpy);
255void clearSecondaryObjs(hwc_context_t *ctx, const int& dpy);
256
257// Inline utility functions
258static inline bool isSkipLayer(const hwc_layer_1_t* l) {
259    return (UNLIKELY(l && (l->flags & HWC_SKIP_LAYER)));
260}
261
262// Returns true if the buffer is yuv
263static inline bool isYuvBuffer(const private_handle_t* hnd) {
264    return (hnd && (hnd->bufferType == BUFFER_TYPE_VIDEO));
265}
266
267// Returns true if the buffer is secure
268static inline bool isSecureBuffer(const private_handle_t* hnd) {
269    return (hnd && (private_handle_t::PRIV_FLAGS_SECURE_BUFFER & hnd->flags));
270}
271
272// Returns true if the buffer is marked for L3 DRM
273static inline bool isL3SecureBuffer(const private_handle_t* hnd) {
274    return (hnd &&
275            (private_handle_t::PRIV_FLAGS_L3_SECURE_BUFFER & hnd->flags));
276}
277//Return true if buffer is marked locked
278static inline bool isBufferLocked(const private_handle_t* hnd) {
279    return (hnd && (private_handle_t::PRIV_FLAGS_HWC_LOCK & hnd->flags));
280}
281
282//Return true if buffer is for external display only
283static inline bool isExtOnly(const private_handle_t* hnd) {
284    return (hnd && (hnd->flags & private_handle_t::PRIV_FLAGS_EXTERNAL_ONLY));
285}
286
287//Return true if buffer is for external display only with a BLOCK flag.
288static inline bool isExtBlock(const private_handle_t* hnd) {
289    return (hnd && (hnd->flags & private_handle_t::PRIV_FLAGS_EXTERNAL_BLOCK));
290}
291
292//Return true if buffer is for external display only with a Close Caption flag.
293static inline bool isExtCC(const private_handle_t* hnd) {
294    return (hnd && (hnd->flags & private_handle_t::PRIV_FLAGS_EXTERNAL_CC));
295}
296
297static inline int getWidth(const private_handle_t* hnd) {
298    if(isYuvBuffer(hnd)) {
299        MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
300        if(metadata && metadata->operation & UPDATE_BUFFER_GEOMETRY) {
301            return metadata->bufferDim.sliceWidth;
302        }
303    }
304    return hnd->width;
305}
306
307static inline int getHeight(const private_handle_t* hnd) {
308    if(isYuvBuffer(hnd)) {
309        MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
310        if(metadata && metadata->operation & UPDATE_BUFFER_GEOMETRY) {
311            return metadata->bufferDim.sliceHeight;
312        }
313    }
314    return hnd->height;
315}
316
317template<typename T> inline T max(T a, T b) { return (a > b) ? a : b; }
318template<typename T> inline T min(T a, T b) { return (a < b) ? a : b; }
319
320// Initialize uevent thread
321void init_uevent_thread(hwc_context_t* ctx);
322// Initialize vsync thread
323void init_vsync_thread(hwc_context_t* ctx);
324
325inline void getLayerResolution(const hwc_layer_1_t* layer,
326                               int& width, int& height) {
327    hwc_rect_t displayFrame  = layer->displayFrame;
328    width = displayFrame.right - displayFrame.left;
329    height = displayFrame.bottom - displayFrame.top;
330}
331
332static inline int openFb(int dpy) {
333    int fd = -1;
334    const char *devtmpl = "/dev/graphics/fb%u";
335    char name[64] = {0};
336    snprintf(name, 64, devtmpl, dpy);
337    fd = open(name, O_RDWR);
338    return fd;
339}
340
341template <class T>
342inline void swap(T& a, T& b) {
343    T tmp = a;
344    a = b;
345    b = tmp;
346}
347
348}; //qhwc namespace
349
350// -----------------------------------------------------------------------------
351// HWC context
352// This structure contains overall state
353struct hwc_context_t {
354    hwc_composer_device_1_t device;
355    const hwc_procs_t* proc;
356
357    //CopyBit objects
358    qhwc::CopyBit *mCopyBit[MAX_DISPLAYS];
359
360    //Overlay object - NULL for non overlay devices
361    overlay::Overlay *mOverlay;
362    //Holds a few rot objects
363    overlay::RotMgr *mRotMgr;
364
365    //Primary and external FB updater
366    qhwc::IFBUpdate *mFBUpdate[MAX_DISPLAYS];
367    // External display related information
368    qhwc::ExternalDisplay *mExtDisplay;
369    qhwc::MDPInfo mMDP;
370    qhwc::VsyncState vstate;
371    qhwc::DisplayAttributes dpyAttr[MAX_DISPLAYS];
372    qhwc::ListStats listStats[MAX_DISPLAYS];
373    qhwc::LayerProp *layerProp[MAX_DISPLAYS];
374    qhwc::LayerRotMap *mLayerRotMap[MAX_DISPLAYS];
375    qhwc::MDPComp *mMDPComp[MAX_DISPLAYS];
376    qhwc::AssertiveDisplay *mAD;
377
378    //Securing in progress indicator
379    bool mSecuring;
380    //Display in secure mode indicator
381    bool mSecureMode;
382    //Lock to protect drawing data structures
383    mutable Locker mDrawLock;
384    //Drawing round when we use GPU
385    bool isPaddingRound;
386    //Flags the transition of a video session
387    bool mVideoTransFlag;
388};
389
390namespace qhwc {
391static inline bool isSkipPresent (hwc_context_t *ctx, int dpy) {
392    return  ctx->listStats[dpy].skipCount;
393}
394
395static inline bool isYuvPresent (hwc_context_t *ctx, int dpy) {
396    return  ctx->listStats[dpy].yuvCount;
397}
398
399static inline bool has90Transform(hwc_layer_1_t *layer) {
400    return (layer->transform & HWC_TRANSFORM_ROT_90);
401}
402
403inline bool isSecurePresent(hwc_context_t *ctx, int dpy) {
404    return ctx->listStats[dpy].isSecurePresent;
405}
406
407static inline bool isSecondaryConfiguring(hwc_context_t* ctx) {
408    return (ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].isConfiguring ||
409            ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].isConfiguring);
410}
411
412static inline bool isSecondaryConnected(hwc_context_t* ctx) {
413    return (ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].connected ||
414            ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].connected);
415}
416
417};
418
419#endif //HWC_UTILS_H
420