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