• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  * Copyright (C) 2012-2016, 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 
region_iteratorqhwc::region_iterator41     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:
iterateqhwc::region_iterator49     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 
reset()72 void CopyBit::reset() {
73     mIsModeOn = false;
74     mCopyBitDraw = false;
75 }
76 
canUseCopybitForYUV(hwc_context_t * ctx)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 
isSmartBlitPossible(const hwc_display_contents_1_t * list)85 bool 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 
canUseCopybitForRGB(hwc_context_t * ctx,hwc_display_contents_1_t * list,int dpy)134 bool 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 
getRGBRenderingArea(const hwc_context_t * ctx,const hwc_display_contents_1_t * list)168 unsigned 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 
isLayerChanging(hwc_context_t * ctx,hwc_display_contents_1_t * list,int k)187 bool 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 
prepareSwapRect(hwc_context_t * ctx,hwc_display_contents_1_t * list,int dpy)204 bool 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 
prepareOverlap(hwc_context_t * ctx,hwc_display_contents_1_t * list)288 bool 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 
prepare(hwc_context_t * ctx,hwc_display_contents_1_t * list,int dpy)346 bool 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 
410             if (layer->transform) {
411                 ALOGD_IF (DEBUG_COPYBIT, "%s: Do GPU comp Transform : %d",
412                     __FUNCTION__, layer->transform);
413                 return true;
414             }
415             hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf);
416 
417             if (has90Transform(layer)) {
418                 src_h = sourceCrop.right - sourceCrop.left;
419                 src_w = sourceCrop.bottom - sourceCrop.top;
420             } else {
421                 src_h = sourceCrop.bottom - sourceCrop.top;
422                 src_w = sourceCrop.right - sourceCrop.left;
423             }
424             dst_h = layer->displayFrame.bottom - layer->displayFrame.top;
425             dst_w = layer->displayFrame.right - layer->displayFrame.left;
426 
427             if(src_w <=0 || src_h<=0 ||dst_w<=0 || dst_h<=0 ) {
428               ALOGE("%s: wrong params for display screen_w=%d \
429                          src_crop_width=%d screen_h=%d src_crop_height=%d",
430                          __FUNCTION__, dst_w,src_w,dst_h,src_h);
431               return false;
432             }
433             dx = (float)dst_w/(float)src_w;
434             dy = (float)dst_h/(float)src_h;
435 
436             float scale_factor_max = MAX_SCALE_FACTOR;
437             float scale_factor_min = MIN_SCALE_FACTOR;
438 
439             if (isAlphaPresent(layer)) {
440                scale_factor_max = MAX_SCALE_FACTOR/4;
441                scale_factor_min = MIN_SCALE_FACTOR*4;
442             }
443 
444             if (dx > scale_factor_max || dx < scale_factor_min)
445                 return false;
446 
447             if (dy > scale_factor_max || dy < scale_factor_min)
448                 return false;
449         }
450     }
451 
452     //Allocate render buffers if they're not allocated
453     if ((ctx->mMDP.version != qdutils::MDP_V3_0_4 &&
454 #ifdef SUPPORT_BLIT_TO_FB
455             ctx->mMDP.version == qdutils::MDP_V3_0_5
456 #else
457             ctx->mMDP.version != qdutils::MDP_V3_0_5
458 #endif
459             ) && (useCopybitForYUV || useCopybitForRGB)) {
460         int ret = allocRenderBuffers(mAlignedWidth,
461                                      mAlignedHeight,
462                                      HAL_PIXEL_FORMAT_RGBA_8888);
463         if (ret < 0) {
464             return false;
465         } else {
466             mCurRenderBufferIndex = (mCurRenderBufferIndex + 1) %
467                 NUM_RENDER_BUFFERS;
468         }
469     }
470 
471     // We cannot mix copybit layer with layers marked to be drawn on FB
472     if (!useCopybitForYUV && ctx->listStats[dpy].yuvCount)
473         return true;
474 
475     mCopyBitDraw = false;
476     if (useCopybitForRGB &&
477         (useCopybitForYUV || !ctx->listStats[dpy].yuvCount)) {
478         mCopyBitDraw =  true;
479         // numAppLayers-1, as we iterate till 0th layer index
480         // Mark all layers to be drawn by copybit
481         for (int i = ctx->listStats[dpy].numAppLayers-1; i >= 0 ; i--) {
482             layerProp[i].mFlags |= HWC_COPYBIT;
483 #ifdef QTI_BSP
484             if (ctx->mMDP.version == qdutils::MDP_V3_0_4 ||
485                ctx->mMDP.version == qdutils::MDP_V3_0_5)
486                 list->hwLayers[i].compositionType = HWC_BLIT;
487             else
488 #endif
489                 list->hwLayers[i].compositionType = HWC_OVERLAY;
490         }
491     }
492 
493     return true;
494 }
495 
clear(private_handle_t * hnd,hwc_rect_t & rect)496 int CopyBit::clear (private_handle_t* hnd, hwc_rect_t& rect)
497 {
498     int ret = 0;
499     copybit_rect_t clear_rect = {rect.left, rect.top,
500         rect.right,
501         rect.bottom};
502 
503     copybit_image_t buf;
504     buf.w = ALIGN(getWidth(hnd),32);
505     buf.h = getHeight(hnd);
506     buf.format = hnd->format;
507     buf.base = (void *)hnd->base;
508     buf.handle = (native_handle_t *)hnd;
509 
510     copybit_device_t *copybit = mEngine;
511     ret = copybit->clear(copybit, &buf, &clear_rect);
512     return ret;
513 }
514 
drawUsingAppBufferComposition(hwc_context_t * ctx,hwc_display_contents_1_t * list,int dpy,int * copybitFd)515 bool CopyBit::drawUsingAppBufferComposition(hwc_context_t *ctx,
516                                       hwc_display_contents_1_t *list,
517                                       int dpy, int *copybitFd) {
518      int layerCount = 0;
519      uint32_t last = (uint32_t)list->numHwLayers - 1;
520      hwc_layer_1_t *fbLayer = &list->hwLayers[last];
521      private_handle_t *fbhnd = (private_handle_t *)fbLayer->handle;
522 
523     if(ctx->enableABC == false)
524        return false;
525 
526     if(ctx->listStats[dpy].numAppLayers > MAX_LAYERS_FOR_ABC )
527        return false;
528 
529     layerCount = ctx->listStats[dpy].numAppLayers;
530     //bottom most layer should
531     //equal to FB
532     hwc_layer_1_t *tmpLayer = &list->hwLayers[0];
533     private_handle_t *hnd = (private_handle_t *)tmpLayer->handle;
534     if(hnd && fbhnd && (hnd->size == fbhnd->size) &&
535     (hnd->width == fbhnd->width) && (hnd->height == fbhnd->height)){
536        if(tmpLayer->transform  ||
537         (list->flags & HWC_GEOMETRY_CHANGED) ||
538        (!(hnd->format == HAL_PIXEL_FORMAT_RGBA_8888 ||
539        hnd->format == HAL_PIXEL_FORMAT_RGBX_8888))  ||
540                    (needsScaling(tmpLayer) == true)) {
541           return false;
542        }else {
543           ctx->listStats[dpy].renderBufIndexforABC = 0;
544        }
545     }
546 
547     if(ctx->listStats[dpy].renderBufIndexforABC == 0) {
548        if(layerCount == 1)
549           return true;
550 
551        if(layerCount ==  MAX_LAYERS_FOR_ABC) {
552           int abcRenderBufIdx = ctx->listStats[dpy].renderBufIndexforABC;
553           //enable ABC only for non intersecting layers.
554           hwc_rect_t displayFrame =
555                   list->hwLayers[abcRenderBufIdx].displayFrame;
556           for (int i = abcRenderBufIdx + 1; i < layerCount; i++) {
557              hwc_rect_t tmpDisplayFrame = list->hwLayers[i].displayFrame;
558              hwc_rect_t result = getIntersection(displayFrame,tmpDisplayFrame);
559              if (isValidRect(result)) {
560                 ctx->listStats[dpy].renderBufIndexforABC = -1;
561                 return false;
562              }
563           }
564           // Pass the Acquire Fence FD to driver for base layer
565           private_handle_t *renderBuffer =
566           (private_handle_t *)list->hwLayers[abcRenderBufIdx].handle;
567           copybit_device_t *copybit = getCopyBitDevice();
568           if(list->hwLayers[abcRenderBufIdx].acquireFenceFd >=0){
569              copybit->set_sync(copybit,
570              list->hwLayers[abcRenderBufIdx].acquireFenceFd);
571           }
572           for(int i = abcRenderBufIdx + 1; i < layerCount; i++){
573              mSwapRect = 0;
574              int retVal = drawLayerUsingCopybit(ctx,
575                &(list->hwLayers[i]),renderBuffer, 0);
576              if(retVal < 0) {
577                 ALOGE("%s : Copybit failed", __FUNCTION__);
578              }
579           }
580           // Get Release Fence FD of copybit for the App layer(s)
581           copybit->flush_get_fence(copybit, copybitFd);
582           close(list->hwLayers[last].acquireFenceFd);
583           list->hwLayers[last].acquireFenceFd = -1;
584           return true;
585        }
586     }
587     return false;
588 }
589 
draw(hwc_context_t * ctx,hwc_display_contents_1_t * list,int dpy,int32_t * fd)590 bool  CopyBit::draw(hwc_context_t *ctx, hwc_display_contents_1_t *list,
591                                                           int dpy, int32_t *fd) {
592     // draw layers marked for COPYBIT
593     int retVal = true;
594     int copybitLayerCount = 0;
595     uint32_t last = 0;
596     LayerProp *layerProp = ctx->layerProp[dpy];
597     private_handle_t *renderBuffer;
598 
599     if(mCopyBitDraw == false){
600        mFbCache.reset(); // there is no layer marked for copybit
601        return false ;
602     }
603 
604     if(drawUsingAppBufferComposition(ctx, list, dpy, fd)) {
605        mFbCache.reset();
606        return true;
607     }
608     //render buffer
609     if (ctx->mMDP.version == qdutils::MDP_V3_0_4 ||
610 #ifdef SUPPORT_BLIT_TO_FB
611         ctx->mMDP.version != qdutils::MDP_V3_0_5
612 #else
613         ctx->mMDP.version == qdutils::MDP_V3_0_5
614 #endif
615        ) {
616         last = (uint32_t)list->numHwLayers - 1;
617         renderBuffer = (private_handle_t *)list->hwLayers[last].handle;
618     } else {
619         renderBuffer = getCurrentRenderBuffer();
620     }
621     if (!renderBuffer) {
622         ALOGE("%s: Render buffer layer handle is NULL", __FUNCTION__);
623         return false;
624     }
625 
626     if ((ctx->mMDP.version >= qdutils::MDP_V4_0)
627 #ifdef SUPPORT_BLIT_TO_FB
628         || (ctx->mMDP.version == qdutils::MDP_V3_0_5)
629 #endif
630        ) {
631         //Wait for the previous frame to complete before rendering onto it
632         if(mRelFd[mCurRenderBufferIndex] >=0) {
633             sync_wait(mRelFd[mCurRenderBufferIndex], 1000);
634             close(mRelFd[mCurRenderBufferIndex]);
635             mRelFd[mCurRenderBufferIndex] = -1;
636         }
637     } else {
638         if(list->hwLayers[last].acquireFenceFd >=0) {
639             copybit_device_t *copybit = getCopyBitDevice();
640             copybit->set_sync(copybit, list->hwLayers[last].acquireFenceFd);
641         }
642     }
643 
644     //if swap rect on and not getting valid dirtyRect
645     //means calling only commit without any draw. Hence avoid
646     //clear call as well.
647     if (not mSwapRect || isValidRect(mDirtyRect)) {
648        if (not CBUtils::uiClearRegion(list, ctx->mMDP.version, layerProp,
649                                       mDirtyRect, mEngine, renderBuffer)){
650            mSwapRect = 0;
651        }
652     }
653 
654     // numAppLayers-1, as we iterate from 0th layer index with HWC_COPYBIT flag
655     for (int i = 0; i <= (ctx->listStats[dpy].numAppLayers-1); i++) {
656         if(!(layerProp[i].mFlags & HWC_COPYBIT)) {
657             ALOGD_IF(DEBUG_COPYBIT, "%s: Not Marked for copybit", __FUNCTION__);
658             continue;
659         }
660         if(ctx->copybitDrop[i]) {
661             continue;
662         }
663         int ret = -1;
664         if (list->hwLayers[i].acquireFenceFd != -1
665                 && ctx->mMDP.version >= qdutils::MDP_V4_0) {
666             // Wait for acquire Fence on the App buffers.
667             ret = sync_wait(list->hwLayers[i].acquireFenceFd, 1000);
668             if(ret < 0) {
669                 ALOGE("%s: sync_wait error!! error no = %d err str = %s",
670                                     __FUNCTION__, errno, strerror(errno));
671             }
672             close(list->hwLayers[i].acquireFenceFd);
673             list->hwLayers[i].acquireFenceFd = -1;
674         }
675         retVal = drawLayerUsingCopybit(ctx, &(list->hwLayers[i]),
676                                           renderBuffer, !i);
677         copybitLayerCount++;
678         if(retVal < 0) {
679             ALOGE("%s : drawLayerUsingCopybit failed", __FUNCTION__);
680         }
681     }
682 
683     if (copybitLayerCount) {
684         copybit_device_t *copybit = getCopyBitDevice();
685         // Async mode
686         copybit->flush_get_fence(copybit, fd);
687         if((ctx->mMDP.version == qdutils::MDP_V3_0_4 ||
688 #ifdef SUPPORT_BLIT_TO_FB
689            ctx->mMDP.version != qdutils::MDP_V3_0_5
690 #else
691            ctx->mMDP.version == qdutils::MDP_V3_0_5
692 #endif
693                 ) && list->hwLayers[last].acquireFenceFd >= 0) {
694             close(list->hwLayers[last].acquireFenceFd);
695             list->hwLayers[last].acquireFenceFd = -1;
696         }
697     }
698     return true;
699 }
700 
drawOverlap(hwc_context_t * ctx,hwc_display_contents_1_t * list)701 int CopyBit::drawOverlap(hwc_context_t *ctx, hwc_display_contents_1_t *list) {
702     int fd = -1;
703     PtorInfo* ptorInfo = &(ctx->mPtorInfo);
704 
705     if (ctx->mMDP.version < qdutils::MDP_V4_0) {
706         ALOGE("%s: Invalid request", __FUNCTION__);
707         return fd;
708     }
709 
710     private_handle_t *renderBuffer = getCurrentRenderBuffer();
711 
712     if (!renderBuffer) {
713         ALOGE("%s: Render buffer layer handle is NULL", __FUNCTION__);
714         return fd;
715     }
716 
717     //Clear the transparent or left out region on the render buffer
718     LayerProp *layerProp = ctx->layerProp[0];
719     hwc_rect_t clearRegion = {0, 0, 0, 0};
720     CBUtils::uiClearRegion(list, ctx->mMDP.version, layerProp, clearRegion,
721                                                     mEngine, renderBuffer);
722 
723     int copybitLayerCount = 0;
724     for(int j = 0; j < ptorInfo->count; j++) {
725         int ovlapIndex = ptorInfo->layerIndex[j];
726         hwc_rect_t overlap = list->hwLayers[ovlapIndex].displayFrame;
727         if(j) {
728             /**
729              * It's possible that 2 PTOR layers might have overlapping.
730              * In such case, remove the intersection(again if peripheral)
731              * from the lower PTOR layer to avoid overlapping.
732              * If intersection is not on peripheral then compromise
733              * by reducing number of PTOR layers.
734              **/
735             int prevOvlapIndex = ptorInfo->layerIndex[0];
736             hwc_rect_t prevOvlap = list->hwLayers[prevOvlapIndex].displayFrame;
737             hwc_rect_t commonRect = getIntersection(prevOvlap, overlap);
738             if(isValidRect(commonRect)) {
739                 overlap = deductRect(overlap, commonRect);
740             }
741         }
742 
743         // Draw overlapped content of layers on render buffer
744         for (int i = 0; i <= ovlapIndex; i++) {
745             hwc_layer_1_t *layer = &list->hwLayers[i];
746             if(!isValidRect(getIntersection(layer->displayFrame,
747                                                overlap))) {
748                 continue;
749             }
750             if ((list->hwLayers[i].acquireFenceFd != -1)) {
751                 // Wait for acquire fence on the App buffers.
752                 if(sync_wait(list->hwLayers[i].acquireFenceFd, 1000) < 0) {
753                     ALOGE("%s: sync_wait error!! error no = %d err str = %s",
754                           __FUNCTION__, errno, strerror(errno));
755                 }
756                 close(list->hwLayers[i].acquireFenceFd);
757                 list->hwLayers[i].acquireFenceFd = -1;
758             }
759             /*
760              * Find the intersection of layer display frame with PTOR layer
761              * with respect to screen co-ordinates
762              *
763              * Calculated the destination rect by transforming the overlapping
764              * region of layer display frame with respect to PTOR display frame
765              *
766              * Transform the destination rect on to render buffer
767              * */
768             hwc_rect_t destRect = getIntersection(overlap, layer->displayFrame);
769             destRect.left = destRect.left - overlap.left +
770                                             ptorInfo->displayFrame[j].left;
771             destRect.right = destRect.right- overlap.left +
772                                             ptorInfo->displayFrame[j].left;
773             destRect.top = destRect.top - overlap.top +
774                                             ptorInfo->displayFrame[j].top;
775             destRect.bottom = destRect.bottom - overlap.top +
776                                             ptorInfo->displayFrame[j].top;
777 
778             int retVal = drawRectUsingCopybit(ctx, layer, renderBuffer,
779                                                           overlap, destRect);
780             copybitLayerCount++;
781             if(retVal < 0) {
782                 ALOGE("%s: drawRectUsingCopybit failed", __FUNCTION__);
783                 copybitLayerCount = 0;
784             }
785         }
786     }
787 
788     if (copybitLayerCount) {
789         copybit_device_t *copybit = getCopyBitDevice();
790         copybit->flush_get_fence(copybit, &fd);
791     }
792 
793     ALOGD_IF(DEBUG_COPYBIT, "%s: done! copybitLayerCount = %d", __FUNCTION__,
794              copybitLayerCount);
795     return fd;
796 }
797 
drawRectUsingCopybit(hwc_context_t * dev,hwc_layer_1_t * layer,private_handle_t * renderBuffer,hwc_rect_t overlap,hwc_rect_t destRect)798 int CopyBit::drawRectUsingCopybit(hwc_context_t *dev, hwc_layer_1_t *layer,
799                         private_handle_t *renderBuffer, hwc_rect_t overlap,
800                         hwc_rect_t destRect)
801 {
802     hwc_context_t* ctx = (hwc_context_t*)(dev);
803     if (!ctx) {
804         ALOGE("%s: null context ", __FUNCTION__);
805         return -1;
806     }
807 
808     private_handle_t *hnd = (private_handle_t *)layer->handle;
809     if (!hnd) {
810         ALOGE("%s: invalid handle", __FUNCTION__);
811         return -1;
812     }
813 
814     private_handle_t *dstHandle = (private_handle_t *)renderBuffer;
815     if (!dstHandle) {
816         ALOGE("%s: RenderBuffer handle is NULL", __FUNCTION__);
817         return -1;
818     }
819 
820     // Set the Copybit Source
821     copybit_image_t src;
822     src.handle = (native_handle_t *)layer->handle;
823     src.w = hnd->width;
824     src.h = hnd->height;
825     src.base = (void *)hnd->base;
826     src.format = hnd->format;
827     src.horiz_padding = 0;
828     src.vert_padding = 0;
829 
830 
831     hwc_rect_t dispFrame = layer->displayFrame;
832     hwc_rect_t iRect = getIntersection(dispFrame, overlap);
833     hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
834     qhwc::calculate_crop_rects(crop, dispFrame, iRect,
835                                layer->transform);
836 
837     // Copybit source rect
838     copybit_rect_t srcRect = {crop.left, crop.top, crop.right,
839         crop.bottom};
840 
841     // Copybit destination rect
842     copybit_rect_t dstRect = {destRect.left, destRect.top, destRect.right,
843         destRect.bottom};
844 
845     // Copybit dst
846     copybit_image_t dst;
847     dst.handle = (native_handle_t *)dstHandle;
848     dst.w = ALIGN(dstHandle->width, 32);
849     dst.h = dstHandle->height;
850     dst.base = (void *)dstHandle->base;
851     dst.format = dstHandle->format;
852 
853     copybit_device_t *copybit = mEngine;
854 
855     // Copybit region is the destRect
856     hwc_rect_t regRect = {dstRect.l,dstRect.t, dstRect.r, dstRect.b};
857     hwc_region_t region;
858     region.numRects = 1;
859     region.rects  = &regRect;
860     region_iterator copybitRegion(region);
861     int acquireFd = layer->acquireFenceFd;
862 
863     copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_WIDTH,
864                            renderBuffer->width);
865     copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_HEIGHT,
866                            renderBuffer->height);
867     copybit->set_parameter(copybit, COPYBIT_TRANSFORM, layer->transform);
868     copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, layer->planeAlpha);
869     copybit->set_parameter(copybit, COPYBIT_BLEND_MODE, layer->blending);
870     copybit->set_parameter(copybit, COPYBIT_DITHER,
871         (dst.format == HAL_PIXEL_FORMAT_RGB_565) ? COPYBIT_ENABLE :
872         COPYBIT_DISABLE);
873     copybit->set_sync(copybit, acquireFd);
874     int err = copybit->stretch(copybit, &dst, &src, &dstRect, &srcRect,
875                                &copybitRegion);
876 
877     if (err < 0)
878         ALOGE("%s: copybit stretch failed",__FUNCTION__);
879 
880     return err;
881 }
882 
drawLayerUsingCopybit(hwc_context_t * dev,hwc_layer_1_t * layer,private_handle_t * renderBuffer,bool isFG)883 int  CopyBit::drawLayerUsingCopybit(hwc_context_t *dev, hwc_layer_1_t *layer,
884                           private_handle_t *renderBuffer, bool isFG)
885 {
886     hwc_context_t* ctx = (hwc_context_t*)(dev);
887     int err = 0, acquireFd;
888     if(!ctx) {
889          ALOGE("%s: null context ", __FUNCTION__);
890          return -1;
891     }
892 
893     private_handle_t *hnd = (private_handle_t *)layer->handle;
894     if(!hnd) {
895         if (layer->flags & HWC_COLOR_FILL) { // Color layer
896             return fillColorUsingCopybit(layer, renderBuffer);
897         }
898         ALOGE("%s: invalid handle", __FUNCTION__);
899         return -1;
900     }
901 
902     private_handle_t *fbHandle = (private_handle_t *)renderBuffer;
903     if(!fbHandle) {
904         ALOGE("%s: Framebuffer handle is NULL", __FUNCTION__);
905         return -1;
906     }
907     uint32_t dynamic_fps = 0;
908 #ifdef DYNAMIC_FPS
909     MetaData_t *mdata = hnd ? (MetaData_t *)hnd->base_metadata : NULL;
910     if (mdata && (mdata->operation & UPDATE_REFRESH_RATE)) {
911        dynamic_fps  = roundOff(mdata->refreshrate);
912     }
913 #endif
914     // Set the copybit source:
915     copybit_image_t src;
916     src.w = getWidth(hnd);
917     src.h = getHeight(hnd);
918     src.format = hnd->format;
919 
920     // Handle R/B swap
921     if ((layer->flags & HWC_FORMAT_RB_SWAP)) {
922         if (src.format == HAL_PIXEL_FORMAT_RGBA_8888) {
923             src.format = HAL_PIXEL_FORMAT_BGRA_8888;
924         } else if (src.format == HAL_PIXEL_FORMAT_RGBX_8888) {
925             src.format = HAL_PIXEL_FORMAT_BGRX_8888;
926         }
927     }
928 
929     src.base = (void *)hnd->base;
930     src.handle = (native_handle_t *)layer->handle;
931     src.horiz_padding = src.w - getWidth(hnd);
932     // Initialize vertical padding to zero for now,
933     // this needs to change to accomodate vertical stride
934     // if needed in the future
935     src.vert_padding = 0;
936 
937     int layerTransform = layer->transform ;
938     // When flip and rotation(90) are present alter the flip,
939     // as GPU is doing the flip and rotation in opposite order
940     // to that of MDP3.0
941     // For 270 degrees, we get 90 + (H+V) which is same as doing
942     // flip first and then rotation (H+V) + 90
943     if (qdutils::MDPVersion::getInstance().getMDPVersion() < 400) {
944                 if (((layer->transform& HAL_TRANSFORM_FLIP_H) ||
945                 (layer->transform & HAL_TRANSFORM_FLIP_V)) &&
946                 (layer->transform &  HAL_TRANSFORM_ROT_90) &&
947                 !(layer->transform ==  HAL_TRANSFORM_ROT_270)){
948                       if(layer->transform & HAL_TRANSFORM_FLIP_H){
949                                  layerTransform ^= HAL_TRANSFORM_FLIP_H;
950                                  layerTransform |= HAL_TRANSFORM_FLIP_V;
951                       }
952                       if(layer->transform & HAL_TRANSFORM_FLIP_V){
953                                  layerTransform ^= HAL_TRANSFORM_FLIP_V;
954                                  layerTransform |= HAL_TRANSFORM_FLIP_H;
955                       }
956                }
957     }
958     // Copybit source rect
959     hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf);
960     copybit_rect_t srcRect = {sourceCrop.left, sourceCrop.top,
961                               sourceCrop.right,
962                               sourceCrop.bottom};
963 
964     // Copybit destination rect
965     hwc_rect_t displayFrame = layer->displayFrame;
966     copybit_rect_t dstRect = {displayFrame.left, displayFrame.top,
967                               displayFrame.right,
968                               displayFrame.bottom};
969 #ifdef QTI_BSP
970     //change src and dst with dirtyRect
971     if(mSwapRect) {
972       hwc_rect_t result = getIntersection(displayFrame, mDirtyRect);
973       if(!isValidRect(result))
974              return true;
975       dstRect.l = result.left;
976       dstRect.t = result.top;
977       dstRect.r = result.right;
978       dstRect.b = result.bottom;
979 
980       srcRect.l += (result.left - displayFrame.left);
981       srcRect.t += (result.top - displayFrame.top);
982       srcRect.r -= (displayFrame.right - result.right);
983       srcRect.b -= (displayFrame.bottom - result.bottom);
984     }
985 #endif
986     // Copybit dst
987     copybit_image_t dst;
988     dst.w = ALIGN(fbHandle->width,32);
989     dst.h = fbHandle->height;
990     dst.format = fbHandle->format;
991     dst.base = (void *)fbHandle->base;
992     dst.handle = (native_handle_t *)fbHandle;
993 
994     copybit_device_t *copybit = mEngine;
995 
996     int32_t screen_w        = displayFrame.right - displayFrame.left;
997     int32_t screen_h        = displayFrame.bottom - displayFrame.top;
998     int32_t src_crop_width  = sourceCrop.right - sourceCrop.left;
999     int32_t src_crop_height = sourceCrop.bottom -sourceCrop.top;
1000 
1001     // Copybit dst
1002     float copybitsMaxScale =
1003                       (float)copybit->get(copybit,COPYBIT_MAGNIFICATION_LIMIT);
1004     float copybitsMinScale =
1005                        (float)copybit->get(copybit,COPYBIT_MINIFICATION_LIMIT);
1006 
1007     if (layer->transform & HWC_TRANSFORM_ROT_90) {
1008         //swap screen width and height
1009         int tmp = screen_w;
1010         screen_w  = screen_h;
1011         screen_h = tmp;
1012     }
1013     private_handle_t *tmpHnd = NULL;
1014 
1015     if(screen_w <=0 || screen_h<=0 ||src_crop_width<=0 || src_crop_height<=0 ) {
1016         ALOGE("%s: wrong params for display screen_w=%d src_crop_width=%d \
1017         screen_h=%d src_crop_height=%d", __FUNCTION__, screen_w,
1018                                 src_crop_width,screen_h,src_crop_height);
1019         return -1;
1020     }
1021 
1022     float dsdx = (float)screen_w/(float)src_crop_width;
1023     float dtdy = (float)screen_h/(float)src_crop_height;
1024 
1025     float scaleLimitMax = copybitsMaxScale * copybitsMaxScale;
1026     float scaleLimitMin = copybitsMinScale * copybitsMinScale;
1027     if(dsdx > scaleLimitMax ||
1028         dtdy > scaleLimitMax ||
1029         dsdx < 1/scaleLimitMin ||
1030         dtdy < 1/scaleLimitMin) {
1031         ALOGW("%s: greater than max supported size dsdx=%f dtdy=%f \
1032               scaleLimitMax=%f scaleLimitMin=%f", __FUNCTION__,dsdx,dtdy,
1033                                           scaleLimitMax,1/scaleLimitMin);
1034         return -1;
1035     }
1036     acquireFd = layer->acquireFenceFd;
1037     if(dsdx > copybitsMaxScale ||
1038         dtdy > copybitsMaxScale ||
1039         dsdx < 1/copybitsMinScale ||
1040         dtdy < 1/copybitsMinScale){
1041         // The requested scale is out of the range the hardware
1042         // can support.
1043        ALOGD("%s:%d::Need to scale twice dsdx=%f, dtdy=%f,copybitsMaxScale=%f,\
1044                                  copybitsMinScale=%f,screen_w=%d,screen_h=%d \
1045                   src_crop_width=%d src_crop_height=%d",__FUNCTION__,__LINE__,
1046               dsdx,dtdy,copybitsMaxScale,1/copybitsMinScale,screen_w,screen_h,
1047                                               src_crop_width,src_crop_height);
1048 
1049 
1050        int tmp_w =  src_crop_width;
1051        int tmp_h =  src_crop_height;
1052 
1053        if (dsdx > copybitsMaxScale)
1054          tmp_w = (int)((float)src_crop_width*copybitsMaxScale);
1055        if (dtdy > copybitsMaxScale)
1056          tmp_h = (int)((float)src_crop_height*copybitsMaxScale);
1057        // ceil the tmp_w and tmp_h value to maintain proper ratio
1058        // b/w src and dst (should not cross the desired scale limit
1059        // due to float -> int )
1060        if (dsdx < 1/copybitsMinScale)
1061          tmp_w = (int)ceil((float)src_crop_width/copybitsMinScale);
1062        if (dtdy < 1/copybitsMinScale)
1063          tmp_h = (int)ceil((float)src_crop_height/copybitsMinScale);
1064 
1065        ALOGD("%s:%d::tmp_w = %d,tmp_h = %d",__FUNCTION__,__LINE__,tmp_w,tmp_h);
1066 
1067        int usage = GRALLOC_USAGE_PRIVATE_IOMMU_HEAP;
1068        int format = fbHandle->format;
1069 
1070        // We do not want copybit to generate alpha values from nothing
1071        if (format == HAL_PIXEL_FORMAT_RGBA_8888 &&
1072                src.format != HAL_PIXEL_FORMAT_RGBA_8888) {
1073            format = HAL_PIXEL_FORMAT_RGBX_8888;
1074        }
1075        if (0 == alloc_buffer(&tmpHnd, tmp_w, tmp_h, format, usage) && tmpHnd) {
1076             copybit_image_t tmp_dst;
1077             copybit_rect_t tmp_rect;
1078             tmp_dst.w = tmp_w;
1079             tmp_dst.h = tmp_h;
1080             tmp_dst.format = tmpHnd->format;
1081             tmp_dst.handle = tmpHnd;
1082             tmp_dst.horiz_padding = src.horiz_padding;
1083             tmp_dst.vert_padding = src.vert_padding;
1084             tmp_rect.l = 0;
1085             tmp_rect.t = 0;
1086             tmp_rect.r = tmp_dst.w;
1087             tmp_rect.b = tmp_dst.h;
1088             //create one clip region
1089             hwc_rect tmp_hwc_rect = {0,0,tmp_rect.r,tmp_rect.b};
1090             hwc_region_t tmp_hwc_reg = {1,(hwc_rect_t const*)&tmp_hwc_rect};
1091             region_iterator tmp_it(tmp_hwc_reg);
1092             copybit->set_parameter(copybit,COPYBIT_TRANSFORM,0);
1093             //TODO: once, we are able to read layer alpha, update this
1094             copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, 255);
1095             copybit->set_sync(copybit, acquireFd);
1096             err = copybit->stretch(copybit,&tmp_dst, &src, &tmp_rect,
1097                                                            &srcRect, &tmp_it);
1098             if(err < 0){
1099                 ALOGE("%s:%d::tmp copybit stretch failed",__FUNCTION__,
1100                                                              __LINE__);
1101                 if(tmpHnd)
1102                     free_buffer(tmpHnd);
1103                 return err;
1104             }
1105             // use release fence as aquire fd for next stretch
1106             if (ctx->mMDP.version < qdutils::MDP_V4_0) {
1107                 copybit->flush_get_fence(copybit, &acquireFd);
1108                 close(acquireFd);
1109                 acquireFd = -1;
1110             }
1111             // copy new src and src rect crop
1112             src = tmp_dst;
1113             srcRect = tmp_rect;
1114       }
1115     }
1116     // Copybit region
1117     hwc_region_t region = layer->visibleRegionScreen;
1118     //Do not use visible regions in case of scaling
1119     if (region.numRects > 1) {
1120         if (needsScaling(layer)) {
1121             region.numRects = 1;
1122             region.rects = &layer->displayFrame;
1123         }
1124     }
1125 
1126     region_iterator copybitRegion(region);
1127 
1128     copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_WIDTH,
1129                                           renderBuffer->width);
1130     copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_HEIGHT,
1131                                           renderBuffer->height);
1132     copybit->set_parameter(copybit, COPYBIT_TRANSFORM,
1133                                               layerTransform);
1134     //TODO: once, we are able to read layer alpha, update this
1135     copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, 255);
1136     copybit->set_parameter(copybit, COPYBIT_DYNAMIC_FPS, dynamic_fps);
1137     copybit->set_parameter(copybit, COPYBIT_BLEND_MODE,
1138                                               layer->blending);
1139     copybit->set_parameter(copybit, COPYBIT_DITHER,
1140                              (dst.format == HAL_PIXEL_FORMAT_RGB_565)?
1141                                              COPYBIT_ENABLE : COPYBIT_DISABLE);
1142     copybit->set_parameter(copybit, COPYBIT_FG_LAYER,
1143                            (layer->blending == HWC_BLENDING_NONE || isFG ) ?
1144                                              COPYBIT_ENABLE : COPYBIT_DISABLE);
1145 
1146     copybit->set_parameter(copybit, COPYBIT_BLIT_TO_FRAMEBUFFER,
1147                                                 COPYBIT_ENABLE);
1148     copybit->set_sync(copybit, acquireFd);
1149     err = copybit->stretch(copybit, &dst, &src, &dstRect, &srcRect,
1150                                                    &copybitRegion);
1151     copybit->set_parameter(copybit, COPYBIT_BLIT_TO_FRAMEBUFFER,
1152                                                COPYBIT_DISABLE);
1153 
1154     if(tmpHnd) {
1155         if (ctx->mMDP.version < qdutils::MDP_V4_0){
1156             int ret = -1, releaseFd;
1157             // we need to wait for the buffer before freeing
1158             copybit->flush_get_fence(copybit, &releaseFd);
1159             ret = sync_wait(releaseFd, 1000);
1160             if(ret < 0) {
1161                 ALOGE("%s: sync_wait error!! error no = %d err str = %s",
1162                     __FUNCTION__, errno, strerror(errno));
1163             }
1164             close(releaseFd);
1165         }
1166         free_buffer(tmpHnd);
1167     }
1168 
1169     if(err < 0)
1170         ALOGE("%s: copybit stretch failed",__FUNCTION__);
1171     return err;
1172 }
1173 
fillColorUsingCopybit(hwc_layer_1_t * layer,private_handle_t * renderBuffer)1174 int CopyBit::fillColorUsingCopybit(hwc_layer_1_t *layer,
1175                           private_handle_t *renderBuffer)
1176 {
1177     if (!renderBuffer) {
1178         ALOGE("%s: Render Buffer is NULL", __FUNCTION__);
1179         return -1;
1180     }
1181 
1182     // Copybit dst
1183     copybit_image_t dst;
1184     dst.w = ALIGN(renderBuffer->width, 32);
1185     dst.h = renderBuffer->height;
1186     dst.format = renderBuffer->format;
1187     dst.base = (void *)renderBuffer->base;
1188     dst.handle = (native_handle_t *)renderBuffer;
1189 
1190     // Copybit dst rect
1191     hwc_rect_t displayFrame = layer->displayFrame;
1192     copybit_rect_t dstRect = {displayFrame.left, displayFrame.top,
1193                               displayFrame.right, displayFrame.bottom};
1194 
1195     uint32_t color = layer->transform;
1196     copybit_device_t *copybit = mEngine;
1197     copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_WIDTH,
1198                            renderBuffer->width);
1199     copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_HEIGHT,
1200                            renderBuffer->height);
1201     copybit->set_parameter(copybit, COPYBIT_DITHER,
1202                            (dst.format == HAL_PIXEL_FORMAT_RGB_565) ?
1203                            COPYBIT_ENABLE : COPYBIT_DISABLE);
1204     copybit->set_parameter(copybit, COPYBIT_TRANSFORM, 0);
1205     copybit->set_parameter(copybit, COPYBIT_BLEND_MODE, layer->blending);
1206     copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, layer->planeAlpha);
1207     copybit->set_parameter(copybit, COPYBIT_BLIT_TO_FRAMEBUFFER,COPYBIT_ENABLE);
1208     int res = copybit->fill_color(copybit, &dst, &dstRect, color);
1209     copybit->set_parameter(copybit,COPYBIT_BLIT_TO_FRAMEBUFFER,COPYBIT_DISABLE);
1210     return res;
1211 }
1212 
getLayerResolution(const hwc_layer_1_t * layer,unsigned int & width,unsigned int & height)1213 void CopyBit::getLayerResolution(const hwc_layer_1_t* layer,
1214                                  unsigned int& width, unsigned int& height)
1215 {
1216     hwc_rect_t result  = layer->displayFrame;
1217     if (mSwapRect)
1218        result = getIntersection(mDirtyRect, result);
1219 
1220     width = result.right - result.left;
1221     height = result.bottom - result.top;
1222 }
1223 
validateParams(hwc_context_t * ctx,const hwc_display_contents_1_t * list)1224 bool CopyBit::validateParams(hwc_context_t *ctx,
1225                                         const hwc_display_contents_1_t *list) {
1226     //Validate parameters
1227     if (!ctx) {
1228         ALOGE("%s:Invalid HWC context", __FUNCTION__);
1229         return false;
1230     } else if (!list) {
1231         ALOGE("%s:Invalid HWC layer list", __FUNCTION__);
1232         return false;
1233     }
1234     return true;
1235 }
1236 
1237 
allocRenderBuffers(int w,int h,int f)1238 int CopyBit::allocRenderBuffers(int w, int h, int f)
1239 {
1240     int ret = 0;
1241     for (int i = 0; i < NUM_RENDER_BUFFERS; i++) {
1242         if (mRenderBuffer[i] == NULL) {
1243             ret = alloc_buffer(&mRenderBuffer[i],
1244                                w, h, f,
1245                                GRALLOC_USAGE_PRIVATE_IOMMU_HEAP);
1246         }
1247         if(ret < 0) {
1248             freeRenderBuffers();
1249             break;
1250         }
1251     }
1252     return ret;
1253 }
1254 
freeRenderBuffers()1255 void CopyBit::freeRenderBuffers()
1256 {
1257     for (int i = 0; i < NUM_RENDER_BUFFERS; i++) {
1258         if(mRenderBuffer[i]) {
1259             //Since we are freeing buffer close the fence if it has a valid one.
1260             if(mRelFd[i] >= 0) {
1261                 close(mRelFd[i]);
1262                 mRelFd[i] = -1;
1263             }
1264             free_buffer(mRenderBuffer[i]);
1265             mRenderBuffer[i] = NULL;
1266         }
1267     }
1268 }
1269 
getCurrentRenderBuffer()1270 private_handle_t * CopyBit::getCurrentRenderBuffer() {
1271     return mRenderBuffer[mCurRenderBufferIndex];
1272 }
1273 
setReleaseFd(int fd)1274 void CopyBit::setReleaseFd(int fd) {
1275     if(mRelFd[mCurRenderBufferIndex] >=0)
1276         close(mRelFd[mCurRenderBufferIndex]);
1277     mRelFd[mCurRenderBufferIndex] = dup(fd);
1278 }
1279 
setReleaseFdSync(int fd)1280 void CopyBit::setReleaseFdSync(int fd) {
1281     if (mRelFd[mCurRenderBufferIndex] >=0) {
1282         int ret = -1;
1283         ret = sync_wait(mRelFd[mCurRenderBufferIndex], 1000);
1284         if (ret < 0)
1285             ALOGE("%s: sync_wait error! errno = %d, err str = %s",
1286                   __FUNCTION__, errno, strerror(errno));
1287         close(mRelFd[mCurRenderBufferIndex]);
1288     }
1289     mRelFd[mCurRenderBufferIndex] = dup(fd);
1290 }
1291 
getCopyBitDevice()1292 struct copybit_device_t* CopyBit::getCopyBitDevice() {
1293     return mEngine;
1294 }
1295 
CopyBit(hwc_context_t * ctx,const int & dpy)1296 CopyBit::CopyBit(hwc_context_t *ctx, const int& dpy) :  mEngine(0),
1297     mIsModeOn(false), mCopyBitDraw(false), mCurRenderBufferIndex(0) {
1298 
1299     getBufferSizeAndDimensions(ctx->dpyAttr[dpy].xres,
1300             ctx->dpyAttr[dpy].yres,
1301             HAL_PIXEL_FORMAT_RGBA_8888,
1302             mAlignedWidth,
1303             mAlignedHeight);
1304 
1305     hw_module_t const *module;
1306     for (int i = 0; i < NUM_RENDER_BUFFERS; i++) {
1307         mRenderBuffer[i] = NULL;
1308         mRelFd[i] = -1;
1309     }
1310 
1311     char value[PROPERTY_VALUE_MAX];
1312     property_get("debug.hwc.dynThreshold", value, "2");
1313     mDynThreshold = atof(value);
1314 
1315     property_get("debug.sf.swaprect", value, "0");
1316     mSwapRectEnable = atoi(value) ? true:false ;
1317     mSwapRect = 0;
1318     if (hw_get_module(COPYBIT_HARDWARE_MODULE_ID, &module) == 0) {
1319         if(copybit_open(module, &mEngine) < 0) {
1320             ALOGE("FATAL ERROR: copybit open failed.");
1321         }
1322     } else {
1323         ALOGE("FATAL ERROR: copybit hw module not found");
1324     }
1325 }
1326 
~CopyBit()1327 CopyBit::~CopyBit()
1328 {
1329     freeRenderBuffers();
1330     if(mEngine)
1331     {
1332         copybit_close(mEngine);
1333         mEngine = NULL;
1334     }
1335 }
LayerCache()1336 CopyBit::LayerCache::LayerCache() {
1337     reset();
1338 }
reset()1339 void CopyBit::LayerCache::reset() {
1340     memset(&hnd, 0, sizeof(hnd));
1341     layerCount = 0;
1342 }
updateCounts(hwc_context_t * ctx,hwc_display_contents_1_t * list,int dpy)1343 void CopyBit::LayerCache::updateCounts(hwc_context_t *ctx,
1344               hwc_display_contents_1_t *list, int dpy)
1345 {
1346    layerCount = ctx->listStats[dpy].numAppLayers;
1347    for (int i=0; i<ctx->listStats[dpy].numAppLayers; i++){
1348       hnd[i] = list->hwLayers[i].handle;
1349       displayFrame[i] = list->hwLayers[i].displayFrame;
1350       drop[i] = ctx->copybitDrop[i];
1351    }
1352 }
1353 
FbCache()1354 CopyBit::FbCache::FbCache() {
1355      reset();
1356 }
reset()1357 void CopyBit::FbCache::reset() {
1358      memset(&FbdirtyRect, 0, sizeof(FbdirtyRect));
1359      memset(&FbdisplayRect, 0, sizeof(FbdisplayRect));
1360      FbIndex =0;
1361 }
1362 
insertAndUpdateFbCache(hwc_rect_t dirtyRect,hwc_rect_t displayRect)1363 void CopyBit::FbCache::insertAndUpdateFbCache(hwc_rect_t dirtyRect,
1364                                              hwc_rect_t displayRect) {
1365    FbIndex =  FbIndex % NUM_RENDER_BUFFERS;
1366    FbdirtyRect[FbIndex] = dirtyRect;
1367    FbdisplayRect[FbIndex] = displayRect;
1368    FbIndex++;
1369 }
1370 
getUnchangedFbDRCount(hwc_rect_t dirtyRect,hwc_rect_t displayRect)1371 int CopyBit::FbCache::getUnchangedFbDRCount(hwc_rect_t dirtyRect,
1372                                           hwc_rect_t displayRect){
1373     int sameDirtyCount = 0;
1374     for (int i = 0 ; i < NUM_RENDER_BUFFERS ; i++ ){
1375       if( FbdirtyRect[i] == dirtyRect &&
1376           FbdisplayRect[i] == displayRect)
1377            sameDirtyCount++;
1378    }
1379    return sameDirtyCount;
1380 }
1381 
1382 }; //namespace qhwc
1383