Home | History | Annotate | Download | only in libhwcomposer
      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.
      6  *
      7  * Licensed under the Apache License, Version 2.0 (the "License");
      8  * you may not use this file except in compliance with the License.
      9  * You may obtain a copy of the License at
     10  *
     11  *      http://www.apache.org/licenses/LICENSE-2.0
     12  *
     13  * Unless required by applicable law or agreed to in writing, software
     14  * distributed under the License is distributed on an "AS IS" BASIS,
     15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     16  * See the License for the specific language governing permissions and
     17  * limitations under the License.
     18  */
     19 
     20 #define DEBUG_COPYBIT 0
     21 #include <copybit.h>
     22 #include <utils/Timers.h>
     23 #include <mdp_version.h>
     24 #include "hwc_copybit.h"
     25 #include "comptype.h"
     26 #include "gr.h"
     27 #include "cb_utils.h"
     28 #include "cb_swap_rect.h"
     29 #include "math.h"
     30 #include "sync/sync.h"
     31 
     32 using namespace qdutils;
     33 namespace qhwc {
     34 
     35 struct range {
     36     int current;
     37     int end;
     38 };
     39 struct region_iterator : public copybit_region_t {
     40 
     41     region_iterator(hwc_region_t region) {
     42         mRegion = region;
     43         r.end = (int)region.numRects;
     44         r.current = 0;
     45         this->next = iterate;
     46     }
     47 
     48 private:
     49     static int iterate(copybit_region_t const * self, copybit_rect_t* rect){
     50         if (!self || !rect) {
     51             ALOGE("iterate invalid parameters");
     52             return 0;
     53         }
     54 
     55         region_iterator const* me =
     56                                   static_cast<region_iterator const*>(self);
     57         if (me->r.current != me->r.end) {
     58             rect->l = me->mRegion.rects[me->r.current].left;
     59             rect->t = me->mRegion.rects[me->r.current].top;
     60             rect->r = me->mRegion.rects[me->r.current].right;
     61             rect->b = me->mRegion.rects[me->r.current].bottom;
     62             me->r.current++;
     63             return 1;
     64         }
     65         return 0;
     66     }
     67 
     68     hwc_region_t mRegion;
     69     mutable range r;
     70 };
     71 
     72 void CopyBit::reset() {
     73     mIsModeOn = false;
     74     mCopyBitDraw = false;
     75 }
     76 
     77 bool CopyBit::canUseCopybitForYUV(hwc_context_t *ctx) {
     78     // return true for non-overlay targets
     79     if(ctx->mMDP.hasOverlay && ctx->mMDP.version >= qdutils::MDP_V4_0) {
     80        return false;
     81     }
     82     return true;
     83 }
     84 
     85 bool CopyBit::canUseCopybitForRGB(hwc_context_t *ctx,
     86                                         hwc_display_contents_1_t *list,
     87                                         int dpy) {
     88     int compositionType = qdutils::QCCompositionType::
     89                                     getInstance().getCompositionType();
     90 
     91     if (compositionType & qdutils::COMPOSITION_TYPE_DYN) {
     92         // DYN Composition:
     93         // use copybit, if (TotalRGBRenderArea < threashold * FB Area)
     94         // this is done based on perf inputs in ICS
     95         // TODO: Above condition needs to be re-evaluated in JB
     96         int fbWidth =  ctx->dpyAttr[dpy].xres;
     97         int fbHeight =  ctx->dpyAttr[dpy].yres;
     98         unsigned int fbArea = (fbWidth * fbHeight);
     99         unsigned int renderArea = getRGBRenderingArea(ctx, list);
    100             ALOGD_IF (DEBUG_COPYBIT, "%s:renderArea %u, fbArea %u",
    101                                   __FUNCTION__, renderArea, fbArea);
    102         if (renderArea < (mDynThreshold * fbArea)) {
    103             return true;
    104         }
    105     } else if ((compositionType & qdutils::COMPOSITION_TYPE_MDP)) {
    106       // MDP composition, use COPYBIT always
    107       return true;
    108     } else if ((compositionType & qdutils::COMPOSITION_TYPE_C2D)) {
    109       // C2D composition, use COPYBIT
    110       return true;
    111     }
    112     return false;
    113 }
    114 
    115 unsigned int CopyBit::getRGBRenderingArea (const hwc_context_t *ctx,
    116                                      const hwc_display_contents_1_t *list) {
    117     //Calculates total rendering area for RGB layers
    118     unsigned int renderArea = 0;
    119     unsigned int w=0, h=0;
    120     // Skipping last layer since FrameBuffer layer should not affect
    121     // which composition to choose
    122     for (unsigned int i=0; i<list->numHwLayers -1; i++) {
    123          private_handle_t *hnd = (private_handle_t *)list->hwLayers[i].handle;
    124          if (hnd) {
    125              if (BUFFER_TYPE_UI == hnd->bufferType && !ctx->copybitDrop[i]) {
    126                  getLayerResolution(&list->hwLayers[i], w, h);
    127                  renderArea += (w*h);
    128              }
    129          }
    130     }
    131     return renderArea;
    132 }
    133 
    134 int CopyBit::getLayersChanging(hwc_context_t *ctx,
    135                       hwc_display_contents_1_t *list,
    136                       int dpy){
    137 
    138    int changingLayerIndex = -1;
    139    if(mLayerCache.layerCount != ctx->listStats[dpy].numAppLayers) {
    140         mLayerCache.reset();
    141         mFbCache.reset();
    142         mLayerCache.updateCounts(ctx,list,dpy);
    143         return -1;
    144     }
    145 
    146     int updatingLayerCount = 0;
    147     for (int k = ctx->listStats[dpy].numAppLayers-1; k >= 0 ; k--){
    148        //swap rect will kick in only for single updating layer
    149        if(mLayerCache.hnd[k] != list->hwLayers[k].handle){
    150            updatingLayerCount ++;
    151            if(updatingLayerCount == 1)
    152              changingLayerIndex = k;
    153        }
    154     }
    155     //since we are using more than one framebuffers,we have to
    156     //kick in swap rect only if we are getting continuous same
    157     //dirty rect for same layer at least equal of number of
    158     //framebuffers
    159 
    160     if ( updatingLayerCount ==  1 ) {
    161        hwc_rect_t dirtyRect = list->hwLayers[changingLayerIndex].displayFrame;
    162 #ifdef QCOM_BSP
    163        dirtyRect = list->hwLayers[changingLayerIndex].dirtyRect;
    164 #endif
    165 
    166        for (int k = ctx->listStats[dpy].numAppLayers-1; k >= 0 ; k--){
    167             //disable swap rect for overlapping visible layer(s)
    168             hwc_rect_t displayFrame = list->hwLayers[k].displayFrame;
    169             hwc_rect_t result = getIntersection(displayFrame,dirtyRect);
    170             if((k != changingLayerIndex) && isValidRect(result)){
    171               return -1;
    172            }
    173        }
    174        mFbCache.insertAndUpdateFbCache(dirtyRect);
    175        if(mFbCache.getUnchangedFbDRCount(dirtyRect) <
    176                                              NUM_RENDER_BUFFERS)
    177               changingLayerIndex =  -1;
    178     }else {
    179        mFbCache.reset();
    180        changingLayerIndex =  -1;
    181     }
    182     mLayerCache.updateCounts(ctx,list,dpy);
    183     return changingLayerIndex;
    184 }
    185 
    186 int CopyBit::checkDirtyRect(hwc_context_t *ctx,
    187                            hwc_display_contents_1_t *list,
    188                            int dpy) {
    189 
    190    //dirty rect will enable only if
    191    //1.Only single layer is updating.
    192    //2.No overlapping
    193    //3.No scaling
    194    //4.No video layer
    195    if(mSwapRectEnable == false)
    196       return -1;
    197    int changingLayerIndex =  getLayersChanging(ctx, list, dpy);
    198    //swap rect will kick in only for single updating layer
    199    if(changingLayerIndex == -1){
    200       return -1;
    201    }
    202    if(!needsScaling(&list->hwLayers[changingLayerIndex])){
    203      private_handle_t *hnd =
    204          (private_handle_t *)list->hwLayers[changingLayerIndex].handle;
    205       if( hnd && !isYuvBuffer(hnd))
    206            return  changingLayerIndex;
    207    }
    208    return -1;
    209 }
    210 
    211 bool CopyBit::prepareOverlap(hwc_context_t *ctx,
    212                              hwc_display_contents_1_t *list) {
    213 
    214     if (ctx->mMDP.version < qdutils::MDP_V4_0) {
    215         ALOGE("%s: Invalid request", __FUNCTION__);
    216         return false;
    217     }
    218 
    219     if (mEngine == NULL || !(validateParams(ctx, list))) {
    220         ALOGE("%s: Invalid Params", __FUNCTION__);
    221         return false;
    222     }
    223     PtorInfo* ptorInfo = &(ctx->mPtorInfo);
    224 
    225     // Allocate render buffers if they're not allocated
    226     int alignW = 0, alignH = 0;
    227     int finalW = 0, finalH = 0;
    228     for (int i = 0; i < ptorInfo->count; i++) {
    229         int ovlapIndex = ptorInfo->layerIndex[i];
    230         hwc_rect_t overlap = list->hwLayers[ovlapIndex].displayFrame;
    231         // render buffer width will be the max of two layers
    232         // Align Widht and height to 32, Mdp would be configured
    233         // with Aligned overlap w/h
    234         finalW = max(finalW, ALIGN((overlap.right - overlap.left), 32));
    235         finalH += ALIGN((overlap.bottom - overlap.top), 32);
    236         if(finalH > ALIGN((overlap.bottom - overlap.top), 32)) {
    237             // Calculate the dest top, left will always be zero
    238             ptorInfo->displayFrame[i].top = (finalH -
    239                                 (ALIGN((overlap.bottom - overlap.top), 32)));
    240         }
    241         // calculate the right and bottom values
    242         ptorInfo->displayFrame[i].right =  ptorInfo->displayFrame[i].left +
    243                                             (overlap.right - overlap.left);
    244         ptorInfo->displayFrame[i].bottom = ptorInfo->displayFrame[i].top +
    245                                             (overlap.bottom - overlap.top);
    246     }
    247 
    248     getBufferSizeAndDimensions(finalW, finalH, HAL_PIXEL_FORMAT_RGBA_8888,
    249                                alignW, alignH);
    250 
    251     if ((mAlignedWidth != alignW) || (mAlignedHeight != alignH)) {
    252         // Overlap rect has changed, so free render buffers
    253         freeRenderBuffers();
    254     }
    255 
    256     int ret = allocRenderBuffers(alignW, alignH, HAL_PIXEL_FORMAT_RGBA_8888);
    257 
    258     if (ret < 0) {
    259         ALOGE("%s: Render buffer allocation failed", __FUNCTION__);
    260         return false;
    261     }
    262 
    263     mAlignedWidth = alignW;
    264     mAlignedHeight = alignH;
    265     mCurRenderBufferIndex = (mCurRenderBufferIndex + 1) % NUM_RENDER_BUFFERS;
    266     return true;
    267 }
    268 
    269 bool CopyBit::prepare(hwc_context_t *ctx, hwc_display_contents_1_t *list,
    270                                                             int dpy) {
    271 
    272     if(mEngine == NULL) {
    273         // No copybit device found - cannot use copybit
    274         return false;
    275     }
    276 
    277     if(ctx->mThermalBurstMode) {
    278         ALOGD_IF (DEBUG_COPYBIT, "%s:Copybit failed,"
    279                 "Running in Thermal Burst mode",__FUNCTION__);
    280         return false;
    281     }
    282 
    283     int compositionType = qdutils::QCCompositionType::
    284                                     getInstance().getCompositionType();
    285 
    286     if ((compositionType == qdutils::COMPOSITION_TYPE_GPU) ||
    287         (compositionType == qdutils::COMPOSITION_TYPE_CPU))   {
    288         //GPU/CPU composition, don't change layer composition type
    289         return true;
    290     }
    291 
    292     if(!(validateParams(ctx, list))) {
    293         ALOGE("%s:Invalid Params", __FUNCTION__);
    294         return false;
    295     }
    296 
    297     if(ctx->listStats[dpy].skipCount) {
    298         //GPU will be anyways used
    299         return false;
    300     }
    301 
    302     if (ctx->listStats[dpy].numAppLayers > MAX_NUM_APP_LAYERS) {
    303         // Reached max layers supported by HWC.
    304         return false;
    305     }
    306 
    307     bool useCopybitForYUV = canUseCopybitForYUV(ctx);
    308     bool useCopybitForRGB = canUseCopybitForRGB(ctx, list, dpy);
    309     LayerProp *layerProp = ctx->layerProp[dpy];
    310 
    311     // Following are MDP3 limitations for which we
    312     // need to fallback to GPU composition:
    313     // 1. Plane alpha is not supported by MDP3.
    314     // 2. Scaling is within range
    315     if (qdutils::MDPVersion::getInstance().getMDPVersion() < 400) {
    316         for (int i = ctx->listStats[dpy].numAppLayers-1; i >= 0 ; i--) {
    317             int dst_h, dst_w, src_h, src_w;
    318             float dx, dy;
    319             if(ctx->copybitDrop[i]) {
    320                 continue;
    321             }
    322             hwc_layer_1_t *layer = (hwc_layer_1_t *) &list->hwLayers[i];
    323             if (layer->planeAlpha != 0xFF)
    324                 return true;
    325             hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf);
    326 
    327             if (has90Transform(layer)) {
    328                 src_h = sourceCrop.right - sourceCrop.left;
    329                 src_w = sourceCrop.bottom - sourceCrop.top;
    330             } else {
    331                 src_h = sourceCrop.bottom - sourceCrop.top;
    332                 src_w = sourceCrop.right - sourceCrop.left;
    333             }
    334             dst_h = layer->displayFrame.bottom - layer->displayFrame.top;
    335             dst_w = layer->displayFrame.right - layer->displayFrame.left;
    336 
    337             if(src_w <=0 || src_h<=0 ||dst_w<=0 || dst_h<=0 ) {
    338               ALOGE("%s: wrong params for display screen_w=%d \
    339                          src_crop_width=%d screen_h=%d src_crop_height=%d",
    340                          __FUNCTION__, dst_w,src_w,dst_h,src_h);
    341               return false;
    342             }
    343             dx = (float)dst_w/(float)src_w;
    344             dy = (float)dst_h/(float)src_h;
    345 
    346             if (dx > MAX_SCALE_FACTOR || dx < MIN_SCALE_FACTOR)
    347                 return false;
    348 
    349             if (dy > MAX_SCALE_FACTOR || dy < MIN_SCALE_FACTOR)
    350                 return false;
    351         }
    352     }
    353 
    354     //Allocate render buffers if they're not allocated
    355     if ((ctx->mMDP.version != qdutils::MDP_V3_0_4 &&
    356         ctx->mMDP.version != qdutils::MDP_V3_0_5) &&
    357             (useCopybitForYUV || useCopybitForRGB)) {
    358         int ret = allocRenderBuffers(mAlignedWidth,
    359                                      mAlignedHeight,
    360                                      HAL_PIXEL_FORMAT_RGBA_8888);
    361         if (ret < 0) {
    362             return false;
    363         } else {
    364             mCurRenderBufferIndex = (mCurRenderBufferIndex + 1) %
    365                 NUM_RENDER_BUFFERS;
    366         }
    367     }
    368 
    369     // We cannot mix copybit layer with layers marked to be drawn on FB
    370     if (!useCopybitForYUV && ctx->listStats[dpy].yuvCount)
    371         return true;
    372 
    373     mCopyBitDraw = false;
    374     if (useCopybitForRGB &&
    375         (useCopybitForYUV || !ctx->listStats[dpy].yuvCount)) {
    376         mCopyBitDraw =  true;
    377         // numAppLayers-1, as we iterate till 0th layer index
    378         // Mark all layers to be drawn by copybit
    379         for (int i = ctx->listStats[dpy].numAppLayers-1; i >= 0 ; i--) {
    380             layerProp[i].mFlags |= HWC_COPYBIT;
    381 #ifdef QCOM_BSP
    382             if (ctx->mMDP.version == qdutils::MDP_V3_0_4 ||
    383                ctx->mMDP.version == qdutils::MDP_V3_0_5)
    384                 list->hwLayers[i].compositionType = HWC_BLIT;
    385             else
    386 #endif
    387                 list->hwLayers[i].compositionType = HWC_OVERLAY;
    388         }
    389     }
    390 
    391     return true;
    392 }
    393 
    394 int CopyBit::clear (private_handle_t* hnd, hwc_rect_t& rect)
    395 {
    396     int ret = 0;
    397     copybit_rect_t clear_rect = {rect.left, rect.top,
    398         rect.right,
    399         rect.bottom};
    400 
    401     copybit_image_t buf;
    402     buf.w = ALIGN(getWidth(hnd),32);
    403     buf.h = getHeight(hnd);
    404     buf.format = hnd->format;
    405     buf.base = (void *)hnd->base;
    406     buf.handle = (native_handle_t *)hnd;
    407 
    408     copybit_device_t *copybit = mEngine;
    409     ret = copybit->clear(copybit, &buf, &clear_rect);
    410     return ret;
    411 }
    412 
    413 bool CopyBit::drawUsingAppBufferComposition(hwc_context_t *ctx,
    414                                       hwc_display_contents_1_t *list,
    415                                       int dpy, int *copybitFd) {
    416      int layerCount = 0;
    417      uint32_t last = (uint32_t)list->numHwLayers - 1;
    418      hwc_layer_1_t *fbLayer = &list->hwLayers[last];
    419      private_handle_t *fbhnd = (private_handle_t *)fbLayer->handle;
    420 
    421     if(ctx->enableABC == false)
    422        return false;
    423 
    424     if(ctx->listStats[dpy].numAppLayers > MAX_LAYERS_FOR_ABC )
    425        return false;
    426 
    427     layerCount = ctx->listStats[dpy].numAppLayers;
    428     //bottom most layer should
    429     //equal to FB
    430     hwc_layer_1_t *tmpLayer = &list->hwLayers[0];
    431     private_handle_t *hnd = (private_handle_t *)tmpLayer->handle;
    432     if(hnd && fbhnd && (hnd->size == fbhnd->size) &&
    433     (hnd->width == fbhnd->width) && (hnd->height == fbhnd->height)){
    434        if(tmpLayer->transform  ||
    435        (!(hnd->format == HAL_PIXEL_FORMAT_RGBA_8888 ||
    436        hnd->format == HAL_PIXEL_FORMAT_RGBX_8888))  ||
    437                    (needsScaling(tmpLayer) == true)) {
    438           return false;
    439        }else {
    440           ctx->listStats[dpy].renderBufIndexforABC = 0;
    441        }
    442     }
    443 
    444     if(ctx->listStats[dpy].renderBufIndexforABC == 0) {
    445        if(layerCount == 1)
    446           return true;
    447 
    448        if(layerCount ==  MAX_LAYERS_FOR_ABC) {
    449           int abcRenderBufIdx = ctx->listStats[dpy].renderBufIndexforABC;
    450           //enable ABC only for non intersecting layers.
    451           hwc_rect_t displayFrame =
    452                   list->hwLayers[abcRenderBufIdx].displayFrame;
    453           for (int i = abcRenderBufIdx + 1; i < layerCount; i++) {
    454              hwc_rect_t tmpDisplayFrame = list->hwLayers[i].displayFrame;
    455              hwc_rect_t result = getIntersection(displayFrame,tmpDisplayFrame);
    456              if (isValidRect(result)) {
    457                 ctx->listStats[dpy].renderBufIndexforABC = -1;
    458                 return false;
    459              }
    460           }
    461           // Pass the Acquire Fence FD to driver for base layer
    462           private_handle_t *renderBuffer =
    463           (private_handle_t *)list->hwLayers[abcRenderBufIdx].handle;
    464           copybit_device_t *copybit = getCopyBitDevice();
    465           if(list->hwLayers[abcRenderBufIdx].acquireFenceFd >=0){
    466              copybit->set_sync(copybit,
    467              list->hwLayers[abcRenderBufIdx].acquireFenceFd);
    468           }
    469           for(int i = abcRenderBufIdx + 1; i < layerCount; i++){
    470              int retVal = drawLayerUsingCopybit(ctx,
    471                &(list->hwLayers[i]),renderBuffer, 0);
    472              if(retVal < 0) {
    473                 ALOGE("%s : Copybit failed", __FUNCTION__);
    474              }
    475           }
    476           // Get Release Fence FD of copybit for the App layer(s)
    477           copybit->flush_get_fence(copybit, copybitFd);
    478           close(list->hwLayers[abcRenderBufIdx].acquireFenceFd);
    479           list->hwLayers[abcRenderBufIdx].acquireFenceFd = -1;
    480           return true;
    481        }
    482     }
    483     return false;
    484 }
    485 
    486 bool  CopyBit::draw(hwc_context_t *ctx, hwc_display_contents_1_t *list,
    487                                                           int dpy, int32_t *fd) {
    488     // draw layers marked for COPYBIT
    489     int retVal = true;
    490     int copybitLayerCount = 0;
    491     uint32_t last = 0;
    492     LayerProp *layerProp = ctx->layerProp[dpy];
    493     private_handle_t *renderBuffer;
    494 
    495     if(mCopyBitDraw == false){
    496        mFbCache.reset(); // there is no layer marked for copybit
    497        return false ;
    498     }
    499 
    500     if(drawUsingAppBufferComposition(ctx, list, dpy, fd)) {
    501        return true;
    502     }
    503     //render buffer
    504     if (ctx->mMDP.version == qdutils::MDP_V3_0_4 ||
    505         ctx->mMDP.version == qdutils::MDP_V3_0_5) {
    506         last = (uint32_t)list->numHwLayers - 1;
    507         renderBuffer = (private_handle_t *)list->hwLayers[last].handle;
    508     } else {
    509         renderBuffer = getCurrentRenderBuffer();
    510     }
    511     if (!renderBuffer) {
    512         ALOGE("%s: Render buffer layer handle is NULL", __FUNCTION__);
    513         return false;
    514     }
    515 
    516     if (ctx->mMDP.version >= qdutils::MDP_V4_0) {
    517         //Wait for the previous frame to complete before rendering onto it
    518         if(mRelFd[mCurRenderBufferIndex] >=0) {
    519             sync_wait(mRelFd[mCurRenderBufferIndex], 1000);
    520             close(mRelFd[mCurRenderBufferIndex]);
    521             mRelFd[mCurRenderBufferIndex] = -1;
    522         }
    523     } else {
    524         if(list->hwLayers[last].acquireFenceFd >=0) {
    525             copybit_device_t *copybit = getCopyBitDevice();
    526             copybit->set_sync(copybit, list->hwLayers[last].acquireFenceFd);
    527         }
    528     }
    529 
    530     mDirtyLayerIndex =  checkDirtyRect(ctx, list, dpy);
    531     if( mDirtyLayerIndex != -1){
    532           hwc_layer_1_t *layer = &list->hwLayers[mDirtyLayerIndex];
    533 #ifdef QCOM_BSP
    534           clear(renderBuffer,layer->dirtyRect);
    535 #else
    536           clear(renderBuffer,layer->displayFrame);
    537 #endif
    538     } else {
    539           hwc_rect_t clearRegion = {0,0,0,0};
    540           if(CBUtils::getuiClearRegion(list, clearRegion, layerProp))
    541              clear(renderBuffer, clearRegion);
    542     }
    543 
    544     // numAppLayers-1, as we iterate from 0th layer index with HWC_COPYBIT flag
    545     for (int i = 0; i <= (ctx->listStats[dpy].numAppLayers-1); i++) {
    546         if(!(layerProp[i].mFlags & HWC_COPYBIT)) {
    547             ALOGD_IF(DEBUG_COPYBIT, "%s: Not Marked for copybit", __FUNCTION__);
    548             continue;
    549         }
    550         if(ctx->copybitDrop[i]) {
    551             continue;
    552         }
    553         //skip non updating layers
    554         if((mDirtyLayerIndex != -1) && (mDirtyLayerIndex != i) )
    555             continue;
    556         int ret = -1;
    557         if (list->hwLayers[i].acquireFenceFd != -1
    558                 && ctx->mMDP.version >= qdutils::MDP_V4_0) {
    559             // Wait for acquire Fence on the App buffers.
    560             ret = sync_wait(list->hwLayers[i].acquireFenceFd, 1000);
    561             if(ret < 0) {
    562                 ALOGE("%s: sync_wait error!! error no = %d err str = %s",
    563                                     __FUNCTION__, errno, strerror(errno));
    564             }
    565             close(list->hwLayers[i].acquireFenceFd);
    566             list->hwLayers[i].acquireFenceFd = -1;
    567         }
    568         retVal = drawLayerUsingCopybit(ctx, &(list->hwLayers[i]),
    569                                           renderBuffer, !i);
    570         copybitLayerCount++;
    571         if(retVal < 0) {
    572             ALOGE("%s : drawLayerUsingCopybit failed", __FUNCTION__);
    573         }
    574     }
    575 
    576     if (copybitLayerCount) {
    577         copybit_device_t *copybit = getCopyBitDevice();
    578         // Async mode
    579         copybit->flush_get_fence(copybit, fd);
    580         if((ctx->mMDP.version == qdutils::MDP_V3_0_4 ||
    581            ctx->mMDP.version == qdutils::MDP_V3_0_5) &&
    582                 list->hwLayers[last].acquireFenceFd >= 0) {
    583             close(list->hwLayers[last].acquireFenceFd);
    584             list->hwLayers[last].acquireFenceFd = -1;
    585         }
    586     }
    587     return true;
    588 }
    589 
    590 int CopyBit::drawOverlap(hwc_context_t *ctx, hwc_display_contents_1_t *list) {
    591     int fd = -1;
    592     PtorInfo* ptorInfo = &(ctx->mPtorInfo);
    593 
    594     if (ctx->mMDP.version < qdutils::MDP_V4_0) {
    595         ALOGE("%s: Invalid request", __FUNCTION__);
    596         return fd;
    597     }
    598 
    599     private_handle_t *renderBuffer = getCurrentRenderBuffer();
    600 
    601     if (!renderBuffer) {
    602         ALOGE("%s: Render buffer layer handle is NULL", __FUNCTION__);
    603         return fd;
    604     }
    605 
    606     //Clear the transparent or left out region on the render buffer
    607     hwc_rect_t clearRegion = {0,0,0,0};
    608     LayerProp *layerProp = ctx->layerProp[0];
    609     if(CBUtils::getuiClearRegion(list, clearRegion, layerProp))
    610         clear(renderBuffer, clearRegion);
    611 
    612     int copybitLayerCount = 0;
    613     for(int j = 0; j < ptorInfo->count; j++) {
    614         int ovlapIndex = ptorInfo->layerIndex[j];
    615         hwc_rect_t overlap = list->hwLayers[ovlapIndex].displayFrame;
    616         if(j) {
    617             /**
    618              * It's possible that 2 PTOR layers might have overlapping.
    619              * In such case, remove the intersection(again if peripheral)
    620              * from the lower PTOR layer to avoid overlapping.
    621              * If intersection is not on peripheral then compromise
    622              * by reducing number of PTOR layers.
    623              **/
    624             int prevOvlapIndex = ptorInfo->layerIndex[0];
    625             hwc_rect_t prevOvlap = list->hwLayers[prevOvlapIndex].displayFrame;
    626             hwc_rect_t commonRect = getIntersection(prevOvlap, overlap);
    627             if(isValidRect(commonRect)) {
    628                 overlap = deductRect(overlap, commonRect);
    629             }
    630         }
    631 
    632         // Draw overlapped content of layers on render buffer
    633         for (int i = 0; i <= ovlapIndex; i++) {
    634             hwc_layer_1_t *layer = &list->hwLayers[i];
    635             if(!isValidRect(getIntersection(layer->displayFrame,
    636                                                overlap))) {
    637                 continue;
    638             }
    639             if ((list->hwLayers[i].acquireFenceFd != -1)) {
    640                 // Wait for acquire fence on the App buffers.
    641                 if(sync_wait(list->hwLayers[i].acquireFenceFd, 1000) < 0) {
    642                     ALOGE("%s: sync_wait error!! error no = %d err str = %s",
    643                           __FUNCTION__, errno, strerror(errno));
    644                 }
    645                 close(list->hwLayers[i].acquireFenceFd);
    646                 list->hwLayers[i].acquireFenceFd = -1;
    647             }
    648             /*
    649              * Find the intersection of layer display frame with PTOR layer
    650              * with respect to screen co-ordinates
    651              *
    652              * Calculated the destination rect by transforming the overlapping
    653              * region of layer display frame with respect to PTOR display frame
    654              *
    655              * Transform the destination rect on to render buffer
    656              * */
    657             hwc_rect_t destRect = getIntersection(overlap, layer->displayFrame);
    658             destRect.left = destRect.left - overlap.left +
    659                                             ptorInfo->displayFrame[j].left;
    660             destRect.right = destRect.right- overlap.left +
    661                                             ptorInfo->displayFrame[j].left;
    662             destRect.top = destRect.top - overlap.top +
    663                                             ptorInfo->displayFrame[j].top;
    664             destRect.bottom = destRect.bottom - overlap.top +
    665                                             ptorInfo->displayFrame[j].top;
    666 
    667             int retVal = drawRectUsingCopybit(ctx, layer, renderBuffer,
    668                                                           overlap, destRect);
    669             copybitLayerCount++;
    670             if(retVal < 0) {
    671                 ALOGE("%s: drawRectUsingCopybit failed", __FUNCTION__);
    672                 copybitLayerCount = 0;
    673             }
    674         }
    675     }
    676 
    677     if (copybitLayerCount) {
    678         copybit_device_t *copybit = getCopyBitDevice();
    679         copybit->flush_get_fence(copybit, &fd);
    680     }
    681 
    682     ALOGD_IF(DEBUG_COPYBIT, "%s: done! copybitLayerCount = %d", __FUNCTION__,
    683              copybitLayerCount);
    684     return fd;
    685 }
    686 
    687 int CopyBit::drawRectUsingCopybit(hwc_context_t *dev, hwc_layer_1_t *layer,
    688                         private_handle_t *renderBuffer, hwc_rect_t overlap,
    689                         hwc_rect_t destRect)
    690 {
    691     hwc_context_t* ctx = (hwc_context_t*)(dev);
    692     if (!ctx) {
    693         ALOGE("%s: null context ", __FUNCTION__);
    694         return -1;
    695     }
    696 
    697     private_handle_t *hnd = (private_handle_t *)layer->handle;
    698     if (!hnd) {
    699         ALOGE("%s: invalid handle", __FUNCTION__);
    700         return -1;
    701     }
    702 
    703     private_handle_t *dstHandle = (private_handle_t *)renderBuffer;
    704     if (!dstHandle) {
    705         ALOGE("%s: RenderBuffer handle is NULL", __FUNCTION__);
    706         return -1;
    707     }
    708 
    709     // Set the Copybit Source
    710     copybit_image_t src;
    711     src.handle = (native_handle_t *)layer->handle;
    712     src.w = hnd->width;
    713     src.h = hnd->height;
    714     src.base = (void *)hnd->base;
    715     src.format = hnd->format;
    716     src.horiz_padding = 0;
    717     src.vert_padding = 0;
    718 
    719 
    720     hwc_rect_t dispFrame = layer->displayFrame;
    721     hwc_rect_t iRect = getIntersection(dispFrame, overlap);
    722     hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
    723     qhwc::calculate_crop_rects(crop, dispFrame, iRect,
    724                                layer->transform);
    725 
    726     // Copybit source rect
    727     copybit_rect_t srcRect = {crop.left, crop.top, crop.right,
    728         crop.bottom};
    729 
    730     // Copybit destination rect
    731     copybit_rect_t dstRect = {destRect.left, destRect.top, destRect.right,
    732         destRect.bottom};
    733 
    734     // Copybit dst
    735     copybit_image_t dst;
    736     dst.handle = (native_handle_t *)dstHandle;
    737     dst.w = ALIGN(dstHandle->width, 32);
    738     dst.h = dstHandle->height;
    739     dst.base = (void *)dstHandle->base;
    740     dst.format = dstHandle->format;
    741 
    742     copybit_device_t *copybit = mEngine;
    743 
    744     // Copybit region is the destRect
    745     hwc_rect_t regRect = {dstRect.l,dstRect.t, dstRect.r, dstRect.b};
    746     hwc_region_t region;
    747     region.numRects = 1;
    748     region.rects  = &regRect;
    749     region_iterator copybitRegion(region);
    750     int acquireFd = layer->acquireFenceFd;
    751 
    752     copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_WIDTH,
    753                            renderBuffer->width);
    754     copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_HEIGHT,
    755                            renderBuffer->height);
    756     copybit->set_parameter(copybit, COPYBIT_TRANSFORM, layer->transform);
    757     copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, layer->planeAlpha);
    758     copybit->set_parameter(copybit, COPYBIT_BLEND_MODE, layer->blending);
    759     copybit->set_parameter(copybit, COPYBIT_DITHER,
    760         (dst.format == HAL_PIXEL_FORMAT_RGB_565) ? COPYBIT_ENABLE :
    761         COPYBIT_DISABLE);
    762     copybit->set_sync(copybit, acquireFd);
    763     int err = copybit->stretch(copybit, &dst, &src, &dstRect, &srcRect,
    764                                &copybitRegion);
    765 
    766     if (err < 0)
    767         ALOGE("%s: copybit stretch failed",__FUNCTION__);
    768 
    769     return err;
    770 }
    771 
    772 int  CopyBit::drawLayerUsingCopybit(hwc_context_t *dev, hwc_layer_1_t *layer,
    773                           private_handle_t *renderBuffer, bool isFG)
    774 {
    775     hwc_context_t* ctx = (hwc_context_t*)(dev);
    776     int err = 0, acquireFd;
    777     if(!ctx) {
    778          ALOGE("%s: null context ", __FUNCTION__);
    779          return -1;
    780     }
    781 
    782     private_handle_t *hnd = (private_handle_t *)layer->handle;
    783     if(!hnd) {
    784         if (layer->flags & HWC_COLOR_FILL) { // Color layer
    785             return fillColorUsingCopybit(layer, renderBuffer);
    786         }
    787         ALOGE("%s: invalid handle", __FUNCTION__);
    788         return -1;
    789     }
    790 
    791     private_handle_t *fbHandle = (private_handle_t *)renderBuffer;
    792     if(!fbHandle) {
    793         ALOGE("%s: Framebuffer handle is NULL", __FUNCTION__);
    794         return -1;
    795     }
    796 
    797     // Set the copybit source:
    798     copybit_image_t src;
    799     src.w = getWidth(hnd);
    800     src.h = getHeight(hnd);
    801     src.format = hnd->format;
    802 
    803     // Handle R/B swap
    804     if ((layer->flags & HWC_FORMAT_RB_SWAP)) {
    805         if (src.format == HAL_PIXEL_FORMAT_RGBA_8888) {
    806             src.format = HAL_PIXEL_FORMAT_BGRA_8888;
    807         } else if (src.format == HAL_PIXEL_FORMAT_RGBX_8888) {
    808             src.format = HAL_PIXEL_FORMAT_BGRX_8888;
    809         }
    810     }
    811 
    812     src.base = (void *)hnd->base;
    813     src.handle = (native_handle_t *)layer->handle;
    814     src.horiz_padding = src.w - getWidth(hnd);
    815     // Initialize vertical padding to zero for now,
    816     // this needs to change to accomodate vertical stride
    817     // if needed in the future
    818     src.vert_padding = 0;
    819 
    820     int layerTransform = layer->transform ;
    821     // When flip and rotation(90) are present alter the flip,
    822     // as GPU is doing the flip and rotation in opposite order
    823     // to that of MDP3.0
    824     // For 270 degrees, we get 90 + (H+V) which is same as doing
    825     // flip first and then rotation (H+V) + 90
    826     if (qdutils::MDPVersion::getInstance().getMDPVersion() < 400) {
    827                 if (((layer->transform& HAL_TRANSFORM_FLIP_H) ||
    828                 (layer->transform & HAL_TRANSFORM_FLIP_V)) &&
    829                 (layer->transform &  HAL_TRANSFORM_ROT_90) &&
    830                 !(layer->transform ==  HAL_TRANSFORM_ROT_270)){
    831                       if(layer->transform & HAL_TRANSFORM_FLIP_H){
    832                                  layerTransform ^= HAL_TRANSFORM_FLIP_H;
    833                                  layerTransform |= HAL_TRANSFORM_FLIP_V;
    834                       }
    835                       if(layer->transform & HAL_TRANSFORM_FLIP_V){
    836                                  layerTransform ^= HAL_TRANSFORM_FLIP_V;
    837                                  layerTransform |= HAL_TRANSFORM_FLIP_H;
    838                       }
    839                }
    840     }
    841     // Copybit source rect
    842     hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf);
    843     copybit_rect_t srcRect = {sourceCrop.left, sourceCrop.top,
    844                               sourceCrop.right,
    845                               sourceCrop.bottom};
    846 
    847     // Copybit destination rect
    848     hwc_rect_t displayFrame = layer->displayFrame;
    849     copybit_rect_t dstRect = {displayFrame.left, displayFrame.top,
    850                               displayFrame.right,
    851                               displayFrame.bottom};
    852 #ifdef QCOM_BSP
    853     //change src and dst with dirtyRect
    854     if(mDirtyLayerIndex != -1) {
    855       srcRect.l = layer->dirtyRect.left;
    856       srcRect.t = layer->dirtyRect.top;
    857       srcRect.r = layer->dirtyRect.right;
    858       srcRect.b = layer->dirtyRect.bottom;
    859       dstRect = srcRect;
    860     }
    861 #endif
    862     // Copybit dst
    863     copybit_image_t dst;
    864     dst.w = ALIGN(fbHandle->width,32);
    865     dst.h = fbHandle->height;
    866     dst.format = fbHandle->format;
    867     dst.base = (void *)fbHandle->base;
    868     dst.handle = (native_handle_t *)fbHandle;
    869 
    870     copybit_device_t *copybit = mEngine;
    871 
    872     int32_t screen_w        = displayFrame.right - displayFrame.left;
    873     int32_t screen_h        = displayFrame.bottom - displayFrame.top;
    874     int32_t src_crop_width  = sourceCrop.right - sourceCrop.left;
    875     int32_t src_crop_height = sourceCrop.bottom -sourceCrop.top;
    876 
    877     // Copybit dst
    878     float copybitsMaxScale =
    879                       (float)copybit->get(copybit,COPYBIT_MAGNIFICATION_LIMIT);
    880     float copybitsMinScale =
    881                        (float)copybit->get(copybit,COPYBIT_MINIFICATION_LIMIT);
    882 
    883     if (layer->transform & HWC_TRANSFORM_ROT_90) {
    884         //swap screen width and height
    885         int tmp = screen_w;
    886         screen_w  = screen_h;
    887         screen_h = tmp;
    888     }
    889     private_handle_t *tmpHnd = NULL;
    890 
    891     if(screen_w <=0 || screen_h<=0 ||src_crop_width<=0 || src_crop_height<=0 ) {
    892         ALOGE("%s: wrong params for display screen_w=%d src_crop_width=%d \
    893         screen_h=%d src_crop_height=%d", __FUNCTION__, screen_w,
    894                                 src_crop_width,screen_h,src_crop_height);
    895         return -1;
    896     }
    897 
    898     float dsdx = (float)screen_w/(float)src_crop_width;
    899     float dtdy = (float)screen_h/(float)src_crop_height;
    900 
    901     float scaleLimitMax = copybitsMaxScale * copybitsMaxScale;
    902     float scaleLimitMin = copybitsMinScale * copybitsMinScale;
    903     if(dsdx > scaleLimitMax ||
    904         dtdy > scaleLimitMax ||
    905         dsdx < 1/scaleLimitMin ||
    906         dtdy < 1/scaleLimitMin) {
    907         ALOGW("%s: greater than max supported size dsdx=%f dtdy=%f \
    908               scaleLimitMax=%f scaleLimitMin=%f", __FUNCTION__,dsdx,dtdy,
    909                                           scaleLimitMax,1/scaleLimitMin);
    910         return -1;
    911     }
    912     acquireFd = layer->acquireFenceFd;
    913     if(dsdx > copybitsMaxScale ||
    914         dtdy > copybitsMaxScale ||
    915         dsdx < 1/copybitsMinScale ||
    916         dtdy < 1/copybitsMinScale){
    917         // The requested scale is out of the range the hardware
    918         // can support.
    919        ALOGD("%s:%d::Need to scale twice dsdx=%f, dtdy=%f,copybitsMaxScale=%f,\
    920                                  copybitsMinScale=%f,screen_w=%d,screen_h=%d \
    921                   src_crop_width=%d src_crop_height=%d",__FUNCTION__,__LINE__,
    922               dsdx,dtdy,copybitsMaxScale,1/copybitsMinScale,screen_w,screen_h,
    923                                               src_crop_width,src_crop_height);
    924 
    925 
    926        int tmp_w =  src_crop_width;
    927        int tmp_h =  src_crop_height;
    928 
    929        if (dsdx > copybitsMaxScale || dtdy > copybitsMaxScale ){
    930          tmp_w = (int)((float)src_crop_width*copybitsMaxScale);
    931          tmp_h = (int)((float)src_crop_height*copybitsMaxScale);
    932        }else if (dsdx < 1/copybitsMinScale ||dtdy < 1/copybitsMinScale ){
    933          // ceil the tmp_w and tmp_h value to maintain proper ratio
    934          // b/w src and dst (should not cross the desired scale limit
    935          // due to float -> int )
    936          tmp_w = (int)ceil((float)src_crop_width/copybitsMinScale);
    937          tmp_h = (int)ceil((float)src_crop_height/copybitsMinScale);
    938        }
    939        ALOGD("%s:%d::tmp_w = %d,tmp_h = %d",__FUNCTION__,__LINE__,tmp_w,tmp_h);
    940 
    941        int usage = GRALLOC_USAGE_PRIVATE_IOMMU_HEAP;
    942        int format = fbHandle->format;
    943 
    944        // We do not want copybit to generate alpha values from nothing
    945        if (format == HAL_PIXEL_FORMAT_RGBA_8888 &&
    946                src.format != HAL_PIXEL_FORMAT_RGBA_8888) {
    947            format = HAL_PIXEL_FORMAT_RGBX_8888;
    948        }
    949        if (0 == alloc_buffer(&tmpHnd, tmp_w, tmp_h, format, usage) && tmpHnd) {
    950             copybit_image_t tmp_dst;
    951             copybit_rect_t tmp_rect;
    952             tmp_dst.w = tmp_w;
    953             tmp_dst.h = tmp_h;
    954             tmp_dst.format = tmpHnd->format;
    955             tmp_dst.handle = tmpHnd;
    956             tmp_dst.horiz_padding = src.horiz_padding;
    957             tmp_dst.vert_padding = src.vert_padding;
    958             tmp_rect.l = 0;
    959             tmp_rect.t = 0;
    960             tmp_rect.r = tmp_dst.w;
    961             tmp_rect.b = tmp_dst.h;
    962             //create one clip region
    963             hwc_rect tmp_hwc_rect = {0,0,tmp_rect.r,tmp_rect.b};
    964             hwc_region_t tmp_hwc_reg = {1,(hwc_rect_t const*)&tmp_hwc_rect};
    965             region_iterator tmp_it(tmp_hwc_reg);
    966             copybit->set_parameter(copybit,COPYBIT_TRANSFORM,0);
    967             //TODO: once, we are able to read layer alpha, update this
    968             copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, 255);
    969             copybit->set_sync(copybit, acquireFd);
    970             err = copybit->stretch(copybit,&tmp_dst, &src, &tmp_rect,
    971                                                            &srcRect, &tmp_it);
    972             if(err < 0){
    973                 ALOGE("%s:%d::tmp copybit stretch failed",__FUNCTION__,
    974                                                              __LINE__);
    975                 if(tmpHnd)
    976                     free_buffer(tmpHnd);
    977                 return err;
    978             }
    979             // use release fence as aquire fd for next stretch
    980             if (ctx->mMDP.version < qdutils::MDP_V4_0) {
    981                 copybit->flush_get_fence(copybit, &acquireFd);
    982                 close(acquireFd);
    983                 acquireFd = -1;
    984             }
    985             // copy new src and src rect crop
    986             src = tmp_dst;
    987             srcRect = tmp_rect;
    988       }
    989     }
    990     // Copybit region
    991     hwc_region_t region = layer->visibleRegionScreen;
    992     region_iterator copybitRegion(region);
    993 
    994     copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_WIDTH,
    995                                           renderBuffer->width);
    996     copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_HEIGHT,
    997                                           renderBuffer->height);
    998     copybit->set_parameter(copybit, COPYBIT_TRANSFORM,
    999                                               layerTransform);
   1000     //TODO: once, we are able to read layer alpha, update this
   1001     copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, 255);
   1002     copybit->set_parameter(copybit, COPYBIT_BLEND_MODE,
   1003                                               layer->blending);
   1004     copybit->set_parameter(copybit, COPYBIT_DITHER,
   1005                              (dst.format == HAL_PIXEL_FORMAT_RGB_565)?
   1006                                              COPYBIT_ENABLE : COPYBIT_DISABLE);
   1007     copybit->set_parameter(copybit, COPYBIT_FG_LAYER, isFG ?
   1008                                              COPYBIT_ENABLE : COPYBIT_DISABLE);
   1009 
   1010     copybit->set_parameter(copybit, COPYBIT_BLIT_TO_FRAMEBUFFER,
   1011                                                 COPYBIT_ENABLE);
   1012     copybit->set_sync(copybit, acquireFd);
   1013     err = copybit->stretch(copybit, &dst, &src, &dstRect, &srcRect,
   1014                                                    &copybitRegion);
   1015     copybit->set_parameter(copybit, COPYBIT_BLIT_TO_FRAMEBUFFER,
   1016                                                COPYBIT_DISABLE);
   1017 
   1018     if(tmpHnd) {
   1019         if (ctx->mMDP.version < qdutils::MDP_V4_0){
   1020             int ret = -1, releaseFd;
   1021             // we need to wait for the buffer before freeing
   1022             copybit->flush_get_fence(copybit, &releaseFd);
   1023             ret = sync_wait(releaseFd, 1000);
   1024             if(ret < 0) {
   1025                 ALOGE("%s: sync_wait error!! error no = %d err str = %s",
   1026                     __FUNCTION__, errno, strerror(errno));
   1027             }
   1028             close(releaseFd);
   1029         }
   1030         free_buffer(tmpHnd);
   1031     }
   1032 
   1033     if(err < 0)
   1034         ALOGE("%s: copybit stretch failed",__FUNCTION__);
   1035     return err;
   1036 }
   1037 
   1038 int CopyBit::fillColorUsingCopybit(hwc_layer_1_t *layer,
   1039                           private_handle_t *renderBuffer)
   1040 {
   1041     if (!renderBuffer) {
   1042         ALOGE("%s: Render Buffer is NULL", __FUNCTION__);
   1043         return -1;
   1044     }
   1045 
   1046     // Copybit dst
   1047     copybit_image_t dst;
   1048     dst.w = ALIGN(renderBuffer->width, 32);
   1049     dst.h = renderBuffer->height;
   1050     dst.format = renderBuffer->format;
   1051     dst.base = (void *)renderBuffer->base;
   1052     dst.handle = (native_handle_t *)renderBuffer;
   1053 
   1054     // Copybit dst rect
   1055     hwc_rect_t displayFrame = layer->displayFrame;
   1056     copybit_rect_t dstRect = {displayFrame.left, displayFrame.top,
   1057                               displayFrame.right, displayFrame.bottom};
   1058 
   1059     uint32_t color = layer->transform;
   1060     copybit_device_t *copybit = mEngine;
   1061     copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_WIDTH,
   1062                            renderBuffer->width);
   1063     copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_HEIGHT,
   1064                            renderBuffer->height);
   1065     copybit->set_parameter(copybit, COPYBIT_DITHER,
   1066                            (dst.format == HAL_PIXEL_FORMAT_RGB_565) ?
   1067                            COPYBIT_ENABLE : COPYBIT_DISABLE);
   1068     copybit->set_parameter(copybit, COPYBIT_TRANSFORM, 0);
   1069     copybit->set_parameter(copybit, COPYBIT_BLEND_MODE, layer->blending);
   1070     copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, layer->planeAlpha);
   1071     copybit->set_parameter(copybit, COPYBIT_BLIT_TO_FRAMEBUFFER,COPYBIT_ENABLE);
   1072     int res = copybit->fill_color(copybit, &dst, &dstRect, color);
   1073     copybit->set_parameter(copybit,COPYBIT_BLIT_TO_FRAMEBUFFER,COPYBIT_DISABLE);
   1074     return res;
   1075 }
   1076 
   1077 void CopyBit::getLayerResolution(const hwc_layer_1_t* layer,
   1078                                  unsigned int& width, unsigned int& height)
   1079 {
   1080     hwc_rect_t displayFrame  = layer->displayFrame;
   1081 
   1082     width = displayFrame.right - displayFrame.left;
   1083     height = displayFrame.bottom - displayFrame.top;
   1084 }
   1085 
   1086 bool CopyBit::validateParams(hwc_context_t *ctx,
   1087                                         const hwc_display_contents_1_t *list) {
   1088     //Validate parameters
   1089     if (!ctx) {
   1090         ALOGE("%s:Invalid HWC context", __FUNCTION__);
   1091         return false;
   1092     } else if (!list) {
   1093         ALOGE("%s:Invalid HWC layer list", __FUNCTION__);
   1094         return false;
   1095     }
   1096     return true;
   1097 }
   1098 
   1099 
   1100 int CopyBit::allocRenderBuffers(int w, int h, int f)
   1101 {
   1102     int ret = 0;
   1103     for (int i = 0; i < NUM_RENDER_BUFFERS; i++) {
   1104         if (mRenderBuffer[i] == NULL) {
   1105             ret = alloc_buffer(&mRenderBuffer[i],
   1106                                w, h, f,
   1107                                GRALLOC_USAGE_PRIVATE_IOMMU_HEAP);
   1108         }
   1109         if(ret < 0) {
   1110             freeRenderBuffers();
   1111             break;
   1112         }
   1113     }
   1114     return ret;
   1115 }
   1116 
   1117 void CopyBit::freeRenderBuffers()
   1118 {
   1119     for (int i = 0; i < NUM_RENDER_BUFFERS; i++) {
   1120         if(mRenderBuffer[i]) {
   1121             //Since we are freeing buffer close the fence if it has a valid one.
   1122             if(mRelFd[i] >= 0) {
   1123                 close(mRelFd[i]);
   1124                 mRelFd[i] = -1;
   1125             }
   1126             free_buffer(mRenderBuffer[i]);
   1127             mRenderBuffer[i] = NULL;
   1128         }
   1129     }
   1130 }
   1131 
   1132 private_handle_t * CopyBit::getCurrentRenderBuffer() {
   1133     return mRenderBuffer[mCurRenderBufferIndex];
   1134 }
   1135 
   1136 void CopyBit::setReleaseFd(int fd) {
   1137     if(mRelFd[mCurRenderBufferIndex] >=0)
   1138         close(mRelFd[mCurRenderBufferIndex]);
   1139     mRelFd[mCurRenderBufferIndex] = dup(fd);
   1140 }
   1141 
   1142 void CopyBit::setReleaseFdSync(int fd) {
   1143     if (mRelFd[mCurRenderBufferIndex] >=0) {
   1144         int ret = -1;
   1145         ret = sync_wait(mRelFd[mCurRenderBufferIndex], 1000);
   1146         if (ret < 0)
   1147             ALOGE("%s: sync_wait error! errno = %d, err str = %s",
   1148                   __FUNCTION__, errno, strerror(errno));
   1149         close(mRelFd[mCurRenderBufferIndex]);
   1150     }
   1151     mRelFd[mCurRenderBufferIndex] = dup(fd);
   1152 }
   1153 
   1154 struct copybit_device_t* CopyBit::getCopyBitDevice() {
   1155     return mEngine;
   1156 }
   1157 
   1158 CopyBit::CopyBit(hwc_context_t *ctx, const int& dpy) :  mEngine(0),
   1159     mIsModeOn(false), mCopyBitDraw(false), mCurRenderBufferIndex(0) {
   1160 
   1161     getBufferSizeAndDimensions(ctx->dpyAttr[dpy].xres,
   1162             ctx->dpyAttr[dpy].yres,
   1163             HAL_PIXEL_FORMAT_RGBA_8888,
   1164             mAlignedWidth,
   1165             mAlignedHeight);
   1166 
   1167     hw_module_t const *module;
   1168     for (int i = 0; i < NUM_RENDER_BUFFERS; i++) {
   1169         mRenderBuffer[i] = NULL;
   1170         mRelFd[i] = -1;
   1171     }
   1172 
   1173     char value[PROPERTY_VALUE_MAX];
   1174     property_get("debug.hwc.dynThreshold", value, "2");
   1175     mDynThreshold = atof(value);
   1176 
   1177     property_get("debug.sf.swaprect", value, "0");
   1178     mSwapRectEnable = atoi(value) ? true:false ;
   1179     mDirtyLayerIndex = -1;
   1180     if (hw_get_module(COPYBIT_HARDWARE_MODULE_ID, &module) == 0) {
   1181         if(copybit_open(module, &mEngine) < 0) {
   1182             ALOGE("FATAL ERROR: copybit open failed.");
   1183         }
   1184     } else {
   1185         ALOGE("FATAL ERROR: copybit hw module not found");
   1186     }
   1187 }
   1188 
   1189 CopyBit::~CopyBit()
   1190 {
   1191     freeRenderBuffers();
   1192     if(mEngine)
   1193     {
   1194         copybit_close(mEngine);
   1195         mEngine = NULL;
   1196     }
   1197 }
   1198 CopyBit::LayerCache::LayerCache() {
   1199     reset();
   1200 }
   1201 void CopyBit::LayerCache::reset() {
   1202     memset(&hnd, 0, sizeof(hnd));
   1203     layerCount = 0;
   1204 }
   1205 void CopyBit::LayerCache::updateCounts(hwc_context_t *ctx,
   1206               hwc_display_contents_1_t *list, int dpy)
   1207 {
   1208    layerCount = ctx->listStats[dpy].numAppLayers;
   1209    for (int i=0; i<ctx->listStats[dpy].numAppLayers; i++){
   1210       hnd[i] = list->hwLayers[i].handle;
   1211    }
   1212 }
   1213 
   1214 CopyBit::FbCache::FbCache() {
   1215      reset();
   1216 }
   1217 void CopyBit::FbCache::reset() {
   1218      memset(&FbdirtyRect, 0, sizeof(FbdirtyRect));
   1219      FbIndex =0;
   1220 }
   1221 
   1222 void CopyBit::FbCache::insertAndUpdateFbCache(hwc_rect_t dirtyRect) {
   1223    FbIndex =  FbIndex % NUM_RENDER_BUFFERS;
   1224    FbdirtyRect[FbIndex] = dirtyRect;
   1225    FbIndex++;
   1226 }
   1227 
   1228 int CopyBit::FbCache::getUnchangedFbDRCount(hwc_rect_t dirtyRect){
   1229     int sameDirtyCount = 0;
   1230     for (int i = 0 ; i < NUM_RENDER_BUFFERS ; i++ ){
   1231       if( FbdirtyRect[i] == dirtyRect)
   1232            sameDirtyCount++;
   1233    }
   1234    return sameDirtyCount;
   1235 }
   1236 
   1237 }; //namespace qhwc
   1238