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