hwc_utils.cpp revision a54b064d29f742af11cd4394a4e00af750108ef8
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 * Copyright (C) 2012-2013, The Linux Foundation All rights reserved.
4 *
5 * Not a Contribution, Apache license notifications and license are retained
6 * for attribution purposes only.
7 *
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 *      http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 */
20#define HWC_UTILS_DEBUG 0
21#include <sys/ioctl.h>
22#include <linux/fb.h>
23#include <binder/IServiceManager.h>
24#include <EGL/egl.h>
25#include <cutils/properties.h>
26#include <gralloc_priv.h>
27#include <overlay.h>
28#include <overlayRotator.h>
29#include "hwc_utils.h"
30#include "hwc_mdpcomp.h"
31#include "hwc_fbupdate.h"
32#include "mdp_version.h"
33#include "hwc_copybit.h"
34#include "hwc_dump_layers.h"
35#include "external.h"
36#include "hwc_qclient.h"
37#include "QService.h"
38#include "comptype.h"
39
40using namespace qClient;
41using namespace qService;
42using namespace android;
43using namespace overlay;
44using namespace overlay::utils;
45namespace ovutils = overlay::utils;
46
47namespace qhwc {
48
49static int openFramebufferDevice(hwc_context_t *ctx)
50{
51    struct fb_fix_screeninfo finfo;
52    struct fb_var_screeninfo info;
53
54    int fb_fd = openFb(HWC_DISPLAY_PRIMARY);
55    if(fb_fd < 0) {
56        ALOGE("%s: Error Opening FB : %s", __FUNCTION__, strerror(errno));
57        return -errno;
58    }
59
60    if (ioctl(fb_fd, FBIOGET_VSCREENINFO, &info) == -1) {
61        ALOGE("%s:Error in ioctl FBIOGET_VSCREENINFO: %s", __FUNCTION__,
62                                                       strerror(errno));
63        close(fb_fd);
64        return -errno;
65    }
66
67    if (int(info.width) <= 0 || int(info.height) <= 0) {
68        // the driver doesn't return that information
69        // default to 160 dpi
70        info.width  = ((info.xres * 25.4f)/160.0f + 0.5f);
71        info.height = ((info.yres * 25.4f)/160.0f + 0.5f);
72    }
73
74    float xdpi = (info.xres * 25.4f) / info.width;
75    float ydpi = (info.yres * 25.4f) / info.height;
76
77#ifdef MSMFB_METADATA_GET
78    struct msmfb_metadata metadata;
79    memset(&metadata, 0 , sizeof(metadata));
80    metadata.op = metadata_op_frame_rate;
81
82    if (ioctl(fb_fd, MSMFB_METADATA_GET, &metadata) == -1) {
83        ALOGE("%s:Error retrieving panel frame rate: %s", __FUNCTION__,
84                                                      strerror(errno));
85        close(fb_fd);
86        return -errno;
87    }
88
89    float fps  = metadata.data.panel_frame_rate;
90#else
91    //XXX: Remove reserved field usage on all baselines
92    //The reserved[3] field is used to store FPS by the driver.
93    float fps  = info.reserved[3] & 0xFF;
94#endif
95
96    if (ioctl(fb_fd, FBIOGET_FSCREENINFO, &finfo) == -1) {
97        ALOGE("%s:Error in ioctl FBIOGET_FSCREENINFO: %s", __FUNCTION__,
98                                                       strerror(errno));
99        close(fb_fd);
100        return -errno;
101    }
102
103    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd = fb_fd;
104    //xres, yres may not be 32 aligned
105    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].stride = finfo.line_length /(info.xres/8);
106    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres = info.xres;
107    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres = info.yres;
108    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xdpi = xdpi;
109    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].ydpi = ydpi;
110    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].vsync_period = 1000000000l / fps;
111
112    return 0;
113}
114
115void initContext(hwc_context_t *ctx)
116{
117    openFramebufferDevice(ctx);
118    ctx->mMDP.version = qdutils::MDPVersion::getInstance().getMDPVersion();
119    ctx->mMDP.hasOverlay = qdutils::MDPVersion::getInstance().hasOverlay();
120    ctx->mMDP.panel = qdutils::MDPVersion::getInstance().getPanelType();
121    overlay::Overlay::initOverlay();
122    ctx->mOverlay = overlay::Overlay::getInstance();
123    ctx->mRotMgr = new RotMgr();
124
125    //Is created and destroyed only once for primary
126    //For external it could get created and destroyed multiple times depending
127    //on what external we connect to.
128    ctx->mFBUpdate[HWC_DISPLAY_PRIMARY] =
129        IFBUpdate::getObject(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres,
130        HWC_DISPLAY_PRIMARY);
131
132    // Check if the target supports copybit compostion (dyn/mdp/c2d) to
133    // decide if we need to open the copybit module.
134    int compositionType =
135        qdutils::QCCompositionType::getInstance().getCompositionType();
136
137    if (compositionType & (qdutils::COMPOSITION_TYPE_DYN |
138                           qdutils::COMPOSITION_TYPE_MDP |
139                           qdutils::COMPOSITION_TYPE_C2D)) {
140            ctx->mCopyBit[HWC_DISPLAY_PRIMARY] = new CopyBit();
141    }
142
143    ctx->mExtDisplay = new ExternalDisplay(ctx);
144
145    ctx->mMDPComp[HWC_DISPLAY_PRIMARY] =
146         MDPComp::getObject(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres,
147         HWC_DISPLAY_PRIMARY);
148
149    for (uint32_t i = 0; i < MAX_DISPLAYS; i++) {
150        ctx->mHwcDebug[i] = new HwcDebug(i);
151    }
152    MDPComp::init(ctx);
153
154    pthread_mutex_init(&(ctx->vstate.lock), NULL);
155    pthread_cond_init(&(ctx->vstate.cond), NULL);
156    ctx->vstate.enable = false;
157    ctx->vstate.fakevsync = false;
158    ctx->mExtDispConfiguring = false;
159
160    //Right now hwc starts the service but anybody could do it, or it could be
161    //independent process as well.
162    QService::init();
163    sp<IQClient> client = new QClient(ctx);
164    interface_cast<IQService>(
165            defaultServiceManager()->getService(
166            String16("display.qservice")))->connect(client);
167
168    ALOGI("Initializing Qualcomm Hardware Composer");
169    ALOGI("MDP version: %d", ctx->mMDP.version);
170}
171
172void closeContext(hwc_context_t *ctx)
173{
174    if(ctx->mOverlay) {
175        delete ctx->mOverlay;
176        ctx->mOverlay = NULL;
177    }
178
179    if(ctx->mRotMgr) {
180        delete ctx->mRotMgr;
181        ctx->mRotMgr = NULL;
182    }
183
184    for(int i = 0; i < MAX_DISPLAYS; i++) {
185        if(ctx->mCopyBit[i]) {
186            delete ctx->mCopyBit[i];
187            ctx->mCopyBit[i] = NULL;
188        }
189    }
190
191    if(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd) {
192        close(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd);
193        ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd = -1;
194    }
195
196    if(ctx->mExtDisplay) {
197        delete ctx->mExtDisplay;
198        ctx->mExtDisplay = NULL;
199    }
200
201    for(int i = 0; i < MAX_DISPLAYS; i++) {
202        if(ctx->mFBUpdate[i]) {
203            delete ctx->mFBUpdate[i];
204            ctx->mFBUpdate[i] = NULL;
205        }
206        if(ctx->mMDPComp[i]) {
207            delete ctx->mMDPComp[i];
208            ctx->mMDPComp[i] = NULL;
209        }
210        if(ctx->mHwcDebug[i]) {
211            delete ctx->mHwcDebug[i];
212            ctx->mHwcDebug[i] = NULL;
213        }
214    }
215
216
217    pthread_mutex_destroy(&(ctx->vstate.lock));
218    pthread_cond_destroy(&(ctx->vstate.cond));
219}
220
221
222void dumpsys_log(android::String8& buf, const char* fmt, ...)
223{
224    va_list varargs;
225    va_start(varargs, fmt);
226    buf.appendFormatV(fmt, varargs);
227    va_end(varargs);
228}
229
230/* Calculates the destination position based on the action safe rectangle */
231void getActionSafePosition(hwc_context_t *ctx, int dpy, uint32_t& x,
232                           uint32_t& y, uint32_t& w, uint32_t& h) {
233
234    // if external supports underscan, do nothing
235    // it will be taken care in the driver
236    if(ctx->mExtDisplay->isCEUnderscanSupported())
237        return;
238
239    float wRatio = 1.0;
240    float hRatio = 1.0;
241    float xRatio = 1.0;
242    float yRatio = 1.0;
243
244    float fbWidth = ctx->dpyAttr[dpy].xres;
245    float fbHeight = ctx->dpyAttr[dpy].yres;
246
247    float asX = 0;
248    float asY = 0;
249    float asW = fbWidth;
250    float asH= fbHeight;
251    char value[PROPERTY_VALUE_MAX];
252
253    // Apply action safe parameters
254    property_get("persist.sys.actionsafe.width", value, "0");
255    int asWidthRatio = atoi(value);
256    property_get("persist.sys.actionsafe.height", value, "0");
257    int asHeightRatio = atoi(value);
258    // based on the action safe ratio, get the Action safe rectangle
259    asW = fbWidth * (1.0f -  asWidthRatio / 100.0f);
260    asH = fbHeight * (1.0f -  asHeightRatio / 100.0f);
261    asX = (fbWidth - asW) / 2;
262    asY = (fbHeight - asH) / 2;
263
264    // calculate the position ratio
265    xRatio = (float)x/fbWidth;
266    yRatio = (float)y/fbHeight;
267    wRatio = (float)w/fbWidth;
268    hRatio = (float)h/fbHeight;
269
270    //Calculate the position...
271    x = (xRatio * asW) + asX;
272    y = (yRatio * asH) + asY;
273    w = (wRatio * asW);
274    h = (hRatio * asH);
275
276    return;
277}
278
279bool needsScaling(hwc_layer_1_t const* layer) {
280    int dst_w, dst_h, src_w, src_h;
281
282    hwc_rect_t displayFrame  = layer->displayFrame;
283    hwc_rect_t sourceCrop = layer->sourceCrop;
284
285    dst_w = displayFrame.right - displayFrame.left;
286    dst_h = displayFrame.bottom - displayFrame.top;
287
288    src_w = sourceCrop.right - sourceCrop.left;
289    src_h = sourceCrop.bottom - sourceCrop.top;
290
291    if(((src_w != dst_w) || (src_h != dst_h)))
292        return true;
293
294    return false;
295}
296
297bool isAlphaScaled(hwc_layer_1_t const* layer) {
298    if(needsScaling(layer) && isAlphaPresent(layer)) {
299        return true;
300    }
301    return false;
302}
303
304bool isAlphaPresent(hwc_layer_1_t const* layer) {
305    private_handle_t *hnd = (private_handle_t *)layer->handle;
306    if(hnd) {
307        int format = hnd->format;
308        switch(format) {
309        case HAL_PIXEL_FORMAT_RGBA_8888:
310        case HAL_PIXEL_FORMAT_BGRA_8888:
311            // In any more formats with Alpha go here..
312            return true;
313        default : return false;
314        }
315    }
316    return false;
317}
318
319void setListStats(hwc_context_t *ctx,
320        const hwc_display_contents_1_t *list, int dpy) {
321
322    ctx->listStats[dpy].numAppLayers = list->numHwLayers - 1;
323    ctx->listStats[dpy].fbLayerIndex = list->numHwLayers - 1;
324    ctx->listStats[dpy].skipCount = 0;
325    ctx->listStats[dpy].needsAlphaScale = false;
326    ctx->listStats[dpy].preMultipliedAlpha = false;
327    ctx->listStats[dpy].yuvCount = 0;
328    char property[PROPERTY_VALUE_MAX];
329
330    for (size_t i = 0; i < list->numHwLayers; i++) {
331        hwc_layer_1_t const* layer = &list->hwLayers[i];
332        private_handle_t *hnd = (private_handle_t *)layer->handle;
333
334        //reset stored yuv index
335        ctx->listStats[dpy].yuvIndices[i] = -1;
336
337        if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
338            continue;
339        //We disregard FB being skip for now! so the else if
340        } else if (isSkipLayer(&list->hwLayers[i])) {
341            ctx->listStats[dpy].skipCount++;
342        } else if (UNLIKELY(isYuvBuffer(hnd))) {
343            int& yuvCount = ctx->listStats[dpy].yuvCount;
344            ctx->listStats[dpy].yuvIndices[yuvCount] = i;
345            yuvCount++;
346
347            if(layer->transform & HWC_TRANSFORM_ROT_90) {
348                if(ctx->mOverlay->isPipeTypeAttached(OV_MDP_PIPE_DMA)) {
349                    ctx->isPaddingRound = true;
350                }
351                Overlay::setDMAMode(Overlay::DMA_BLOCK_MODE);
352            }
353        }
354        if(layer->blending == HWC_BLENDING_PREMULT)
355            ctx->listStats[dpy].preMultipliedAlpha = true;
356
357        if(!ctx->listStats[dpy].needsAlphaScale)
358            ctx->listStats[dpy].needsAlphaScale = isAlphaScaled(layer);
359    }
360    if(ctx->listStats[dpy].yuvCount > 0) {
361        if (property_get("hw.cabl.yuv", property, NULL) > 0) {
362            if (atoi(property) != 1) {
363                property_set("hw.cabl.yuv", "1");
364            }
365        }
366    } else {
367        if (property_get("hw.cabl.yuv", property, NULL) > 0) {
368            if (atoi(property) != 0) {
369                property_set("hw.cabl.yuv", "0");
370            }
371        }
372    }
373}
374
375
376static inline void calc_cut(float& leftCutRatio, float& topCutRatio,
377        float& rightCutRatio, float& bottomCutRatio, int orient) {
378    if(orient & HAL_TRANSFORM_FLIP_H) {
379        swap(leftCutRatio, rightCutRatio);
380    }
381    if(orient & HAL_TRANSFORM_FLIP_V) {
382        swap(topCutRatio, bottomCutRatio);
383    }
384    if(orient & HAL_TRANSFORM_ROT_90) {
385        //Anti clock swapping
386        float tmpCutRatio = leftCutRatio;
387        leftCutRatio = topCutRatio;
388        topCutRatio = rightCutRatio;
389        rightCutRatio = bottomCutRatio;
390        bottomCutRatio = tmpCutRatio;
391    }
392}
393
394bool isSecuring(hwc_context_t* ctx, hwc_layer_1_t const* layer) {
395    if((ctx->mMDP.version < qdutils::MDSS_V5) &&
396       (ctx->mMDP.version > qdutils::MDP_V3_0) &&
397        ctx->mSecuring) {
398        return true;
399    }
400    if (isSecureModePolicy(ctx->mMDP.version)) {
401        private_handle_t *hnd = (private_handle_t *)layer->handle;
402        if(ctx->mSecureMode) {
403            if (! isSecureBuffer(hnd)) {
404                ALOGD_IF(HWC_UTILS_DEBUG,"%s:Securing Turning ON ...",
405                         __FUNCTION__);
406                return true;
407            }
408        } else {
409            if (isSecureBuffer(hnd)) {
410                ALOGD_IF(HWC_UTILS_DEBUG,"%s:Securing Turning OFF ...",
411                         __FUNCTION__);
412                return true;
413            }
414        }
415    }
416    return false;
417}
418
419bool isSecureModePolicy(int mdpVersion) {
420    if (mdpVersion < qdutils::MDSS_V5)
421        return true;
422    else
423        return false;
424}
425
426//Crops source buffer against destination and FB boundaries
427void calculate_crop_rects(hwc_rect_t& crop, hwc_rect_t& dst,
428                          const hwc_rect_t& scissor, int orient) {
429
430    int& crop_l = crop.left;
431    int& crop_t = crop.top;
432    int& crop_r = crop.right;
433    int& crop_b = crop.bottom;
434    int crop_w = crop.right - crop.left;
435    int crop_h = crop.bottom - crop.top;
436
437    int& dst_l = dst.left;
438    int& dst_t = dst.top;
439    int& dst_r = dst.right;
440    int& dst_b = dst.bottom;
441    int dst_w = abs(dst.right - dst.left);
442    int dst_h = abs(dst.bottom - dst.top);
443
444    const int& sci_l = scissor.left;
445    const int& sci_t = scissor.top;
446    const int& sci_r = scissor.right;
447    const int& sci_b = scissor.bottom;
448    int sci_w = abs(sci_r - sci_l);
449    int sci_h = abs(sci_b - sci_t);
450
451    float leftCutRatio = 0.0f, rightCutRatio = 0.0f, topCutRatio = 0.0f,
452            bottomCutRatio = 0.0f;
453
454    if(dst_l < sci_l) {
455        leftCutRatio = (float)(sci_l - dst_l) / (float)dst_w;
456        dst_l = sci_l;
457    }
458
459    if(dst_r > sci_r) {
460        rightCutRatio = (float)(dst_r - sci_r) / (float)dst_w;
461        dst_r = sci_r;
462    }
463
464    if(dst_t < sci_t) {
465        topCutRatio = (float)(sci_t - dst_t) / (float)dst_h;
466        dst_t = sci_t;
467    }
468
469    if(dst_b > sci_b) {
470        bottomCutRatio = (float)(dst_b - sci_b) / (float)dst_h;
471        dst_b = sci_b;
472    }
473
474    calc_cut(leftCutRatio, topCutRatio, rightCutRatio, bottomCutRatio, orient);
475    crop_l += crop_w * leftCutRatio;
476    crop_t += crop_h * topCutRatio;
477    crop_r -= crop_w * rightCutRatio;
478    crop_b -= crop_h * bottomCutRatio;
479}
480
481void getNonWormholeRegion(hwc_display_contents_1_t* list,
482                              hwc_rect_t& nwr)
483{
484    uint32_t last = list->numHwLayers - 1;
485    hwc_rect_t fbDisplayFrame = list->hwLayers[last].displayFrame;
486    //Initiliaze nwr to first frame
487    nwr.left =  list->hwLayers[0].displayFrame.left;
488    nwr.top =  list->hwLayers[0].displayFrame.top;
489    nwr.right =  list->hwLayers[0].displayFrame.right;
490    nwr.bottom =  list->hwLayers[0].displayFrame.bottom;
491
492    for (uint32_t i = 1; i < last; i++) {
493        hwc_rect_t displayFrame = list->hwLayers[i].displayFrame;
494        nwr.left   = min(nwr.left, displayFrame.left);
495        nwr.top    = min(nwr.top, displayFrame.top);
496        nwr.right  = max(nwr.right, displayFrame.right);
497        nwr.bottom = max(nwr.bottom, displayFrame.bottom);
498    }
499
500    //Intersect with the framebuffer
501    nwr.left   = max(nwr.left, fbDisplayFrame.left);
502    nwr.top    = max(nwr.top, fbDisplayFrame.top);
503    nwr.right  = min(nwr.right, fbDisplayFrame.right);
504    nwr.bottom = min(nwr.bottom, fbDisplayFrame.bottom);
505
506}
507
508bool isExternalActive(hwc_context_t* ctx) {
509    return ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].isActive;
510}
511
512void closeAcquireFds(hwc_display_contents_1_t* list) {
513    for(uint32_t i = 0; list && i < list->numHwLayers; i++) {
514        //Close the acquireFenceFds
515        //HWC_FRAMEBUFFER are -1 already by SF, rest we close.
516        if(list->hwLayers[i].acquireFenceFd >= 0) {
517            close(list->hwLayers[i].acquireFenceFd);
518            list->hwLayers[i].acquireFenceFd = -1;
519        }
520    }
521}
522
523int hwc_sync(hwc_context_t *ctx, hwc_display_contents_1_t* list, int dpy,
524                                                        int fd) {
525    int ret = 0;
526    struct mdp_buf_sync data;
527    int acquireFd[MAX_NUM_LAYERS];
528    int count = 0;
529    int releaseFd = -1;
530    int fbFd = -1;
531    memset(&data, 0, sizeof(data));
532    bool swapzero = false;
533    data.flags = MDP_BUF_SYNC_FLAG_WAIT;
534    data.acq_fen_fd = acquireFd;
535    data.rel_fen_fd = &releaseFd;
536    char property[PROPERTY_VALUE_MAX];
537    if(property_get("debug.egl.swapinterval", property, "1") > 0) {
538        if(atoi(property) == 0)
539            swapzero = true;
540    }
541
542    //Accumulate acquireFenceFds
543    for(uint32_t i = 0; i < list->numHwLayers; i++) {
544        if(list->hwLayers[i].compositionType == HWC_OVERLAY &&
545                        list->hwLayers[i].acquireFenceFd != -1) {
546            if(UNLIKELY(swapzero))
547                acquireFd[count++] = -1;
548            else
549                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
550        }
551        if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
552            if(UNLIKELY(swapzero))
553                acquireFd[count++] = -1;
554            else if(fd != -1) {
555                //set the acquireFD from fd - which is coming from c2d
556                acquireFd[count++] = fd;
557                // Buffer sync IOCTL should be async when using c2d fence is
558                // used
559                data.flags &= ~MDP_BUF_SYNC_FLAG_WAIT;
560            } else if(list->hwLayers[i].acquireFenceFd != -1)
561                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
562        }
563    }
564
565    data.acq_fen_fd_cnt = count;
566    fbFd = ctx->dpyAttr[dpy].fd;
567    //Waits for acquire fences, returns a release fence
568    if(LIKELY(!swapzero)) {
569        uint64_t start = systemTime();
570        ret = ioctl(fbFd, MSMFB_BUFFER_SYNC, &data);
571        ALOGD_IF(HWC_UTILS_DEBUG, "%s: time taken for MSMFB_BUFFER_SYNC IOCTL = %d",
572                            __FUNCTION__, (size_t) ns2ms(systemTime() - start));
573    }
574
575    if(ret < 0) {
576        ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed, err=%s",
577                  __FUNCTION__, strerror(errno));
578        ALOGE("%s: acq_fen_fd_cnt=%d flags=%d fd=%d dpy=%d numHwLayers=%d",
579              __FUNCTION__, data.acq_fen_fd_cnt, data.flags, fbFd,
580              dpy, list->numHwLayers);
581    }
582
583    for(uint32_t i = 0; i < list->numHwLayers; i++) {
584        if(list->hwLayers[i].compositionType == HWC_OVERLAY ||
585           list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
586            //Populate releaseFenceFds.
587            if(UNLIKELY(swapzero))
588                list->hwLayers[i].releaseFenceFd = -1;
589            else
590                list->hwLayers[i].releaseFenceFd = dup(releaseFd);
591        }
592    }
593
594    if(fd >= 0) {
595        close(fd);
596        fd = -1;
597    }
598
599    if (ctx->mCopyBit[dpy])
600        ctx->mCopyBit[dpy]->setReleaseFd(releaseFd);
601    if(UNLIKELY(swapzero)){
602        list->retireFenceFd = -1;
603        close(releaseFd);
604    } else {
605        list->retireFenceFd = releaseFd;
606    }
607
608    return ret;
609}
610
611void trimLayer(hwc_context_t *ctx, const int& dpy, const int& transform,
612        hwc_rect_t& crop, hwc_rect_t& dst) {
613    int hw_w = ctx->dpyAttr[dpy].xres;
614    int hw_h = ctx->dpyAttr[dpy].yres;
615    if(dst.left < 0 || dst.top < 0 ||
616            dst.right > hw_w || dst.bottom > hw_h) {
617        hwc_rect_t scissor = {0, 0, hw_w, hw_h };
618        qhwc::calculate_crop_rects(crop, dst, scissor, transform);
619    }
620}
621
622void setMdpFlags(hwc_layer_1_t *layer,
623        ovutils::eMdpFlags &mdpFlags,
624        int rotDownscale) {
625    private_handle_t *hnd = (private_handle_t *)layer->handle;
626    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
627    const int& transform = layer->transform;
628
629    if(layer->blending == HWC_BLENDING_PREMULT) {
630        ovutils::setMdpFlags(mdpFlags,
631                ovutils::OV_MDP_BLEND_FG_PREMULT);
632    }
633
634    if(isYuvBuffer(hnd)) {
635        if(isSecureBuffer(hnd)) {
636            ovutils::setMdpFlags(mdpFlags,
637                    ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
638        }
639        if(metadata && (metadata->operation & PP_PARAM_INTERLACED) &&
640                metadata->interlaced) {
641            ovutils::setMdpFlags(mdpFlags,
642                    ovutils::OV_MDP_DEINTERLACE);
643        }
644        //Pre-rotation will be used using rotator.
645        if(transform & HWC_TRANSFORM_ROT_90) {
646            ovutils::setMdpFlags(mdpFlags,
647                    ovutils::OV_MDP_SOURCE_ROTATED_90);
648            // enable bandwidth compression only if src width < 2048
649            if(qdutils::MDPVersion::getInstance().supportsBWC() &&
650                hnd->width < qdutils::MAX_DISPLAY_DIM) {
651                ovutils::setMdpFlags(mdpFlags,
652                                 ovutils::OV_MDSS_MDP_BWC_EN);
653            }
654        }
655    }
656
657    //No 90 component and no rot-downscale then flips done by MDP
658    //If we use rot then it might as well do flips
659    if(!(layer->transform & HWC_TRANSFORM_ROT_90) && !rotDownscale) {
660        if(layer->transform & HWC_TRANSFORM_FLIP_H) {
661            ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_FLIP_H);
662        }
663
664        if(layer->transform & HWC_TRANSFORM_FLIP_V) {
665            ovutils::setMdpFlags(mdpFlags,  ovutils::OV_MDP_FLIP_V);
666        }
667    }
668
669    if(metadata &&
670        ((metadata->operation & PP_PARAM_HSIC)
671        || (metadata->operation & PP_PARAM_IGC)
672        || (metadata->operation & PP_PARAM_SHARP2))) {
673        ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_PP_EN);
674    }
675}
676
677static inline int configRotator(Rotator *rot, const Whf& whf,
678        const hwc_rect_t& crop, const eMdpFlags& mdpFlags,
679        const eTransform& orient, const int& downscale) {
680    Dim rotCrop(crop.left, crop.top, (crop.right - crop.left),
681        (crop.bottom - crop.top));
682    rot->setSource(whf);
683    rot->setCrop(rotCrop);
684    rot->setFlags(mdpFlags);
685    rot->setTransform(orient);
686    rot->setDownscale(downscale);
687    if(!rot->commit()) return -1;
688    return 0;
689}
690
691static inline int configMdp(Overlay *ov, const PipeArgs& parg,
692        const eTransform& orient, const hwc_rect_t& crop,
693        const hwc_rect_t& pos, const MetaData_t *metadata,
694        const eDest& dest) {
695    ov->setSource(parg, dest);
696    ov->setTransform(orient, dest);
697
698    int crop_w = crop.right - crop.left;
699    int crop_h = crop.bottom - crop.top;
700    Dim dcrop(crop.left, crop.top, crop_w, crop_h);
701    ov->setCrop(dcrop, dest);
702
703    int posW = pos.right - pos.left;
704    int posH = pos.bottom - pos.top;
705    Dim position(pos.left, pos.top, posW, posH);
706    ov->setPosition(position, dest);
707
708    if (metadata)
709        ov->setVisualParams(*metadata, dest);
710
711    if (!ov->commit(dest)) {
712        return -1;
713    }
714    return 0;
715}
716
717static inline void updateSource(eTransform& orient, Whf& whf,
718        hwc_rect_t& crop) {
719    Dim srcCrop(crop.left, crop.top,
720            crop.right - crop.left,
721            crop.bottom - crop.top);
722    orient = static_cast<eTransform>(ovutils::getMdpOrient(orient));
723    preRotateSource(orient, whf, srcCrop);
724    if (qdutils::MDPVersion::getInstance().getMDPVersion() >=
725        qdutils::MDSS_V5) {
726        // Source for overlay will be the cropped (and rotated)
727        crop.left = 0;
728        crop.top = 0;
729        crop.right = srcCrop.w;
730        crop.bottom = srcCrop.h;
731        // Set width & height equal to sourceCrop w & h
732        whf.w = srcCrop.w;
733        whf.h = srcCrop.h;
734    } else {
735        crop.left = srcCrop.x;
736        crop.top = srcCrop.y;
737        crop.right = srcCrop.x + srcCrop.w;
738        crop.bottom = srcCrop.y + srcCrop.h;
739    }
740}
741
742int configureLowRes(hwc_context_t *ctx, hwc_layer_1_t *layer,
743        const int& dpy, eMdpFlags& mdpFlags, const eZorder& z,
744        const eIsFg& isFg, const eDest& dest, Rotator **rot) {
745
746    private_handle_t *hnd = (private_handle_t *)layer->handle;
747    if(!hnd) {
748        ALOGE("%s: layer handle is NULL", __FUNCTION__);
749        return -1;
750    }
751
752    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
753
754    hwc_rect_t crop = layer->sourceCrop;
755    hwc_rect_t dst = layer->displayFrame;
756    int transform = layer->transform;
757    eTransform orient = static_cast<eTransform>(transform);
758    int downscale = 0;
759    int rotFlags = ovutils::ROT_FLAGS_NONE;
760    Whf whf(hnd->width, hnd->height,
761            getMdpFormat(hnd->format), hnd->size);
762
763    if(isYuvBuffer(hnd) && ctx->mMDP.version >= qdutils::MDP_V4_2 &&
764       ctx->mMDP.version < qdutils::MDSS_V5) {
765        downscale =  getDownscaleFactor(
766            crop.right - crop.left,
767            crop.bottom - crop.top,
768            dst.right - dst.left,
769            dst.bottom - dst.top);
770        if(downscale) {
771            rotFlags = ROT_DOWNSCALE_ENABLED;
772        }
773    }
774
775    setMdpFlags(layer, mdpFlags, downscale);
776    trimLayer(ctx, dpy, transform, crop, dst);
777
778    if(isYuvBuffer(hnd) && //if 90 component or downscale, use rot
779            ((transform & HWC_TRANSFORM_ROT_90) || downscale)) {
780        *rot = ctx->mRotMgr->getNext();
781        if(*rot == NULL) return -1;
782        //Configure rotator for pre-rotation
783        if(configRotator(*rot, whf, crop, mdpFlags, orient, downscale) < 0) {
784            ALOGE("%s: configRotator failed!", __FUNCTION__);
785            return -1;
786        }
787        whf.format = (*rot)->getDstFormat();
788        updateSource(orient, whf, crop);
789        rotFlags |= ovutils::ROT_PREROTATED;
790    }
791
792    //For the mdp, since either we are pre-rotating or MDP does flips
793    orient = OVERLAY_TRANSFORM_0;
794    transform = 0;
795
796    PipeArgs parg(mdpFlags, whf, z, isFg, static_cast<eRotFlags>(rotFlags));
797    if(configMdp(ctx->mOverlay, parg, orient, crop, dst, metadata, dest) < 0) {
798        ALOGE("%s: commit failed for low res panel", __FUNCTION__);
799        return -1;
800    }
801    return 0;
802}
803
804int configureHighRes(hwc_context_t *ctx, hwc_layer_1_t *layer,
805        const int& dpy, eMdpFlags& mdpFlagsL, const eZorder& z,
806        const eIsFg& isFg, const eDest& lDest, const eDest& rDest,
807        Rotator **rot) {
808    private_handle_t *hnd = (private_handle_t *)layer->handle;
809    if(!hnd) {
810        ALOGE("%s: layer handle is NULL", __FUNCTION__);
811        return -1;
812    }
813
814    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
815
816    int hw_w = ctx->dpyAttr[dpy].xres;
817    int hw_h = ctx->dpyAttr[dpy].yres;
818    hwc_rect_t crop = layer->sourceCrop;
819    hwc_rect_t dst = layer->displayFrame;
820    int transform = layer->transform;
821    eTransform orient = static_cast<eTransform>(transform);
822    const int downscale = 0;
823    int rotFlags = ROT_FLAGS_NONE;
824
825    Whf whf(hnd->width, hnd->height,
826            getMdpFormat(hnd->format), hnd->size);
827
828    setMdpFlags(layer, mdpFlagsL);
829    trimLayer(ctx, dpy, transform, crop, dst);
830
831    if(isYuvBuffer(hnd) && (transform & HWC_TRANSFORM_ROT_90)) {
832        (*rot) = ctx->mRotMgr->getNext();
833        if((*rot) == NULL) return -1;
834        //Configure rotator for pre-rotation
835        if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale) < 0) {
836            ALOGE("%s: configRotator failed!", __FUNCTION__);
837            return -1;
838        }
839        whf.format = (*rot)->getDstFormat();
840        updateSource(orient, whf, crop);
841        rotFlags |= ROT_PREROTATED;
842    }
843
844    eMdpFlags mdpFlagsR = mdpFlagsL;
845    setMdpFlags(mdpFlagsR, OV_MDSS_MDP_RIGHT_MIXER);
846
847    hwc_rect_t tmp_cropL, tmp_dstL;
848    hwc_rect_t tmp_cropR, tmp_dstR;
849
850    if(lDest != OV_INVALID) {
851        tmp_cropL = crop;
852        tmp_dstL = dst;
853        hwc_rect_t scissor = {0, 0, hw_w/2, hw_h };
854        qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
855    }
856    if(rDest != OV_INVALID) {
857        tmp_cropR = crop;
858        tmp_dstR = dst;
859        hwc_rect_t scissor = {hw_w/2, 0, hw_w, hw_h };
860        qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
861    }
862
863    //When buffer is flipped, contents of mixer config also needs to swapped.
864    //Not needed if the layer is confined to one half of the screen.
865    //If rotator has been used then it has also done the flips, so ignore them.
866    if((orient & OVERLAY_TRANSFORM_FLIP_V) && lDest != OV_INVALID
867            && rDest != OV_INVALID && (*rot) == NULL) {
868        hwc_rect_t new_cropR;
869        new_cropR.left = tmp_cropL.left;
870        new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
871
872        hwc_rect_t new_cropL;
873        new_cropL.left  = new_cropR.right;
874        new_cropL.right = tmp_cropR.right;
875
876        tmp_cropL.left =  new_cropL.left;
877        tmp_cropL.right =  new_cropL.right;
878
879        tmp_cropR.left = new_cropR.left;
880        tmp_cropR.right =  new_cropR.right;
881
882    }
883
884    //For the mdp, since either we are pre-rotating or MDP does flips
885    orient = OVERLAY_TRANSFORM_0;
886    transform = 0;
887
888    //configure left mixer
889    if(lDest != OV_INVALID) {
890        PipeArgs pargL(mdpFlagsL, whf, z, isFg,
891                static_cast<eRotFlags>(rotFlags));
892        if(configMdp(ctx->mOverlay, pargL, orient,
893                tmp_cropL, tmp_dstL, metadata, lDest) < 0) {
894            ALOGE("%s: commit failed for left mixer config", __FUNCTION__);
895            return -1;
896        }
897    }
898
899    //configure right mixer
900    if(rDest != OV_INVALID) {
901        PipeArgs pargR(mdpFlagsR, whf, z, isFg,
902                static_cast<eRotFlags>(rotFlags));
903        tmp_dstR.right = tmp_dstR.right - hw_w/2;
904        tmp_dstR.left = tmp_dstR.left - hw_w/2;
905        if(configMdp(ctx->mOverlay, pargR, orient,
906                tmp_cropR, tmp_dstR, metadata, rDest) < 0) {
907            ALOGE("%s: commit failed for right mixer config", __FUNCTION__);
908            return -1;
909        }
910    }
911
912    return 0;
913}
914};//namespace qhwc
915