1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 * Copyright (C) 2012-2014, The Linux Foundation. All rights reserved.
4 *
5 * Not a Contribution.
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 *      http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 */
19
20#define DEBUG_COPYBIT 0
21#include <copybit.h>
22#include <utils/Timers.h>
23#include <mdp_version.h>
24#include "hwc_copybit.h"
25#include "comptype.h"
26#include "gr.h"
27#include "cb_utils.h"
28#include "cb_swap_rect.h"
29#include "math.h"
30#include "sync/sync.h"
31
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::canUseCopybitForRGB(hwc_context_t *ctx,
86                                        hwc_display_contents_1_t *list,
87                                        int dpy) {
88    int compositionType = qdutils::QCCompositionType::
89                                    getInstance().getCompositionType();
90
91    if (compositionType & qdutils::COMPOSITION_TYPE_DYN) {
92        // DYN Composition:
93        // use copybit, if (TotalRGBRenderArea < threashold * FB Area)
94        // this is done based on perf inputs in ICS
95        // TODO: Above condition needs to be re-evaluated in JB
96        int fbWidth =  ctx->dpyAttr[dpy].xres;
97        int fbHeight =  ctx->dpyAttr[dpy].yres;
98        unsigned int fbArea = (fbWidth * fbHeight);
99        unsigned int renderArea = getRGBRenderingArea(list);
100            ALOGD_IF (DEBUG_COPYBIT, "%s:renderArea %u, fbArea %u",
101                                  __FUNCTION__, renderArea, fbArea);
102        if (renderArea < (mDynThreshold * fbArea)) {
103            return true;
104        }
105    } else if ((compositionType & qdutils::COMPOSITION_TYPE_MDP)) {
106      // MDP composition, use COPYBIT always
107      return true;
108    } else if ((compositionType & qdutils::COMPOSITION_TYPE_C2D)) {
109      // C2D composition, use COPYBIT
110      return true;
111    }
112    return false;
113}
114
115unsigned int CopyBit::getRGBRenderingArea
116                                    (const hwc_display_contents_1_t *list) {
117    //Calculates total rendering area for RGB layers
118    unsigned int renderArea = 0;
119    unsigned int w=0, h=0;
120    // Skipping last layer since FrameBuffer layer should not affect
121    // which composition to choose
122    for (unsigned int i=0; i<list->numHwLayers -1; i++) {
123         private_handle_t *hnd = (private_handle_t *)list->hwLayers[i].handle;
124         if (hnd) {
125             if (BUFFER_TYPE_UI == hnd->bufferType) {
126                 getLayerResolution(&list->hwLayers[i], w, h);
127                 renderArea += (w*h);
128             }
129         }
130    }
131    return renderArea;
132}
133
134bool CopyBit::prepare(hwc_context_t *ctx, hwc_display_contents_1_t *list,
135                                                            int dpy) {
136
137    if(mEngine == NULL) {
138        // No copybit device found - cannot use copybit
139        return false;
140    }
141    int compositionType = qdutils::QCCompositionType::
142                                    getInstance().getCompositionType();
143
144    if ((compositionType == qdutils::COMPOSITION_TYPE_GPU) ||
145        (compositionType == qdutils::COMPOSITION_TYPE_CPU))   {
146        //GPU/CPU composition, don't change layer composition type
147        return true;
148    }
149
150    if(!(validateParams(ctx, list))) {
151        ALOGE("%s:Invalid Params", __FUNCTION__);
152        return false;
153    }
154
155    if(ctx->listStats[dpy].skipCount) {
156        //GPU will be anyways used
157        return false;
158    }
159
160    if (ctx->listStats[dpy].numAppLayers > MAX_NUM_APP_LAYERS) {
161        // Reached max layers supported by HWC.
162        return false;
163    }
164
165    bool useCopybitForYUV = canUseCopybitForYUV(ctx);
166    bool useCopybitForRGB = canUseCopybitForRGB(ctx, list, dpy);
167    LayerProp *layerProp = ctx->layerProp[dpy];
168
169    // Following are MDP3 limitations for which we
170    // need to fallback to GPU composition:
171    // 1. Plane alpha is not supported by MDP3.
172    // 2. Scaling is within range
173    if (qdutils::MDPVersion::getInstance().getMDPVersion() < 400) {
174        for (int i = ctx->listStats[dpy].numAppLayers-1; i >= 0 ; i--) {
175            int dst_h, dst_w, src_h, src_w;
176            float dx, dy;
177            hwc_layer_1_t *layer = (hwc_layer_1_t *) &list->hwLayers[i];
178            if (layer->planeAlpha != 0xFF)
179                return true;
180            hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf);
181
182            if (layer->transform & HAL_TRANSFORM_ROT_90) {
183                src_h = sourceCrop.right - sourceCrop.left;
184                src_w = sourceCrop.bottom - sourceCrop.top;
185            } else {
186                src_h = sourceCrop.bottom - sourceCrop.top;
187                src_w = sourceCrop.right - sourceCrop.left;
188            }
189            dst_h = layer->displayFrame.bottom - layer->displayFrame.top;
190            dst_w = layer->displayFrame.right - layer->displayFrame.left;
191
192            if(src_w <=0 || src_h<=0 ||dst_w<=0 || dst_h<=0 ) {
193              ALOGE("%s: wrong params for display screen_w=%d \
194                         src_crop_width=%d screen_h=%d src_crop_height=%d",
195                         __FUNCTION__, dst_w,src_w,dst_h,src_h);
196              return false;
197            }
198            dx = (float)dst_w/(float)src_w;
199            dy = (float)dst_h/(float)src_h;
200
201            if (dx > MAX_SCALE_FACTOR || dx < MIN_SCALE_FACTOR)
202                return false;
203
204            if (dy > MAX_SCALE_FACTOR || dy < MIN_SCALE_FACTOR)
205                return false;
206        }
207    }
208
209    //Allocate render buffers if they're not allocated
210    if (ctx->mMDP.version != qdutils::MDP_V3_0_4 &&
211            (useCopybitForYUV || useCopybitForRGB)) {
212        int ret = allocRenderBuffers(mAlignedFBWidth,
213                                     mAlignedFBHeight,
214                                     HAL_PIXEL_FORMAT_RGBA_8888);
215        if (ret < 0) {
216            return false;
217        } else {
218            mCurRenderBufferIndex = (mCurRenderBufferIndex + 1) %
219                NUM_RENDER_BUFFERS;
220        }
221    }
222
223    // We cannot mix copybit layer with layers marked to be drawn on FB
224    if (!useCopybitForYUV && ctx->listStats[dpy].yuvCount)
225        return true;
226
227    mCopyBitDraw = false;
228    if (useCopybitForRGB &&
229        (useCopybitForYUV || !ctx->listStats[dpy].yuvCount)) {
230        mCopyBitDraw =  true;
231        // numAppLayers-1, as we iterate till 0th layer index
232        // Mark all layers to be drawn by copybit
233        for (int i = ctx->listStats[dpy].numAppLayers-1; i >= 0 ; i--) {
234            layerProp[i].mFlags |= HWC_COPYBIT;
235#ifdef QCOM_BSP
236            if (ctx->mMDP.version == qdutils::MDP_V3_0_4)
237                list->hwLayers[i].compositionType = HWC_BLIT;
238            else
239#endif
240                list->hwLayers[i].compositionType = HWC_OVERLAY;
241        }
242    }
243
244    return true;
245}
246
247int CopyBit::clear (private_handle_t* hnd, hwc_rect_t& rect)
248{
249    int ret = 0;
250    copybit_rect_t clear_rect = {rect.left, rect.top,
251        rect.right,
252        rect.bottom};
253
254    copybit_image_t buf;
255    buf.w = ALIGN(getWidth(hnd),32);
256    buf.h = getHeight(hnd);
257    buf.format = hnd->format;
258    buf.base = (void *)hnd->base;
259    buf.handle = (native_handle_t *)hnd;
260
261    copybit_device_t *copybit = mEngine;
262    ret = copybit->clear(copybit, &buf, &clear_rect);
263    return ret;
264}
265
266bool CopyBit::draw(hwc_context_t *ctx, hwc_display_contents_1_t *list,
267                                                        int dpy, int32_t *fd) {
268    // draw layers marked for COPYBIT
269    int retVal = true;
270    int copybitLayerCount = 0;
271    uint32_t last = 0;
272    LayerProp *layerProp = ctx->layerProp[dpy];
273    private_handle_t *renderBuffer;
274
275    if(mCopyBitDraw == false) // there is no layer marked for copybit
276        return false ;
277
278    //render buffer
279    if (ctx->mMDP.version == qdutils::MDP_V3_0_4) {
280        last = (uint32_t)list->numHwLayers - 1;
281        renderBuffer = (private_handle_t *)list->hwLayers[last].handle;
282    } else {
283        renderBuffer = getCurrentRenderBuffer();
284    }
285    if (!renderBuffer) {
286        ALOGE("%s: Render buffer layer handle is NULL", __FUNCTION__);
287        return false;
288    }
289
290    if (ctx->mMDP.version >= qdutils::MDP_V4_0) {
291        //Wait for the previous frame to complete before rendering onto it
292        if(mRelFd[mCurRenderBufferIndex] >=0) {
293            sync_wait(mRelFd[mCurRenderBufferIndex], 1000);
294            close(mRelFd[mCurRenderBufferIndex]);
295            mRelFd[mCurRenderBufferIndex] = -1;
296        }
297    } else {
298        if(list->hwLayers[last].acquireFenceFd >=0) {
299            copybit_device_t *copybit = getCopyBitDevice();
300            copybit->set_sync(copybit, list->hwLayers[last].acquireFenceFd);
301        }
302    }
303
304    //Clear the transparent or left out region on the render buffer
305    hwc_rect_t clearRegion = {0,0,0,0};
306    if(CBUtils::getuiClearRegion(list, clearRegion, layerProp))
307        clear(renderBuffer, clearRegion);
308
309    // numAppLayers-1, as we iterate from 0th layer index with HWC_COPYBIT flag
310    for (int i = 0; i <= (ctx->listStats[dpy].numAppLayers-1); i++) {
311        hwc_layer_1_t *layer = &list->hwLayers[i];
312        if(!(layerProp[i].mFlags & HWC_COPYBIT)) {
313            ALOGD_IF(DEBUG_COPYBIT, "%s: Not Marked for copybit", __FUNCTION__);
314            continue;
315        }
316        if(layer->flags & HWC_SKIP_HWC_COMPOSITION){
317            continue;
318        }
319        int ret = -1;
320        if (list->hwLayers[i].acquireFenceFd != -1
321                && ctx->mMDP.version >= qdutils::MDP_V4_0) {
322            // Wait for acquire Fence on the App buffers.
323            ret = sync_wait(list->hwLayers[i].acquireFenceFd, 1000);
324            if(ret < 0) {
325                ALOGE("%s: sync_wait error!! error no = %d err str = %s",
326                                    __FUNCTION__, errno, strerror(errno));
327            }
328            close(list->hwLayers[i].acquireFenceFd);
329            list->hwLayers[i].acquireFenceFd = -1;
330        }
331        retVal = drawLayerUsingCopybit(ctx, &(list->hwLayers[i]),
332                                                    renderBuffer, !i);
333        copybitLayerCount++;
334        if(retVal < 0) {
335            ALOGE("%s : drawLayerUsingCopybit failed", __FUNCTION__);
336        }
337    }
338
339    if (copybitLayerCount) {
340        copybit_device_t *copybit = getCopyBitDevice();
341        // Async mode
342        copybit->flush_get_fence(copybit, fd);
343        if(ctx->mMDP.version == qdutils::MDP_V3_0_4 &&
344                list->hwLayers[last].acquireFenceFd >= 0) {
345            close(list->hwLayers[last].acquireFenceFd);
346            list->hwLayers[last].acquireFenceFd = -1;
347        }
348    }
349    return true;
350}
351
352int  CopyBit::drawLayerUsingCopybit(hwc_context_t *dev, hwc_layer_1_t *layer,
353                          private_handle_t *renderBuffer, bool isFG)
354{
355    hwc_context_t* ctx = (hwc_context_t*)(dev);
356    int err = 0, acquireFd;
357    if(!ctx) {
358         ALOGE("%s: null context ", __FUNCTION__);
359         return -1;
360    }
361
362    private_handle_t *hnd = (private_handle_t *)layer->handle;
363    if(!hnd) {
364        if (layer->flags & HWC_COLOR_FILL) { // Color layer
365            return fillColorUsingCopybit(layer, renderBuffer);
366        }
367        ALOGE("%s: invalid handle", __FUNCTION__);
368        return -1;
369    }
370
371    private_handle_t *fbHandle = (private_handle_t *)renderBuffer;
372    if(!fbHandle) {
373        ALOGE("%s: Framebuffer handle is NULL", __FUNCTION__);
374        return -1;
375    }
376
377    // Set the copybit source:
378    copybit_image_t src;
379    src.w = getWidth(hnd);
380    src.h = getHeight(hnd);
381    src.format = hnd->format;
382
383    // Handle R/B swap
384    if ((layer->flags & HWC_FORMAT_RB_SWAP)) {
385        if (src.format == HAL_PIXEL_FORMAT_RGBA_8888) {
386            src.format = HAL_PIXEL_FORMAT_BGRA_8888;
387        } else if (src.format == HAL_PIXEL_FORMAT_RGBX_8888) {
388            src.format = HAL_PIXEL_FORMAT_BGRX_8888;
389        }
390    }
391
392    src.base = (void *)hnd->base;
393    src.handle = (native_handle_t *)layer->handle;
394    src.horiz_padding = src.w - getWidth(hnd);
395    // Initialize vertical padding to zero for now,
396    // this needs to change to accomodate vertical stride
397    // if needed in the future
398    src.vert_padding = 0;
399
400    int layerTransform = layer->transform ;
401    // When flip and rotation(90) are present alter the flip,
402    // as GPU is doing the flip and rotation in opposite order
403    // to that of MDP3.0
404    // For 270 degrees, we get 90 + (H+V) which is same as doing
405    // flip first and then rotation (H+V) + 90
406    if (qdutils::MDPVersion::getInstance().getMDPVersion() < 400) {
407                if (((layer->transform& HAL_TRANSFORM_FLIP_H) ||
408                (layer->transform & HAL_TRANSFORM_FLIP_V)) &&
409                (layer->transform &  HAL_TRANSFORM_ROT_90) &&
410                !(layer->transform ==  HAL_TRANSFORM_ROT_270)){
411                      if(layer->transform & HAL_TRANSFORM_FLIP_H){
412                                 layerTransform ^= HAL_TRANSFORM_FLIP_H;
413                                 layerTransform |= HAL_TRANSFORM_FLIP_V;
414                      }
415                      if(layer->transform & HAL_TRANSFORM_FLIP_V){
416                                 layerTransform ^= HAL_TRANSFORM_FLIP_V;
417                                 layerTransform |= HAL_TRANSFORM_FLIP_H;
418                      }
419               }
420    }
421    // Copybit source rect
422    hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf);
423    copybit_rect_t srcRect = {sourceCrop.left, sourceCrop.top,
424                              sourceCrop.right,
425                              sourceCrop.bottom};
426
427    // Copybit destination rect
428    hwc_rect_t displayFrame = layer->displayFrame;
429    copybit_rect_t dstRect = {displayFrame.left, displayFrame.top,
430                              displayFrame.right,
431                              displayFrame.bottom};
432
433    // Copybit dst
434    copybit_image_t dst;
435    dst.w = ALIGN(fbHandle->width,32);
436    dst.h = fbHandle->height;
437    dst.format = fbHandle->format;
438    dst.base = (void *)fbHandle->base;
439    dst.handle = (native_handle_t *)fbHandle;
440
441    copybit_device_t *copybit = mEngine;
442
443    int32_t screen_w        = displayFrame.right - displayFrame.left;
444    int32_t screen_h        = displayFrame.bottom - displayFrame.top;
445    int32_t src_crop_width  = sourceCrop.right - sourceCrop.left;
446    int32_t src_crop_height = sourceCrop.bottom -sourceCrop.top;
447
448    // Copybit dst
449    float copybitsMaxScale =
450                      (float)copybit->get(copybit,COPYBIT_MAGNIFICATION_LIMIT);
451    float copybitsMinScale =
452                       (float)copybit->get(copybit,COPYBIT_MINIFICATION_LIMIT);
453
454    if (layer->transform & HWC_TRANSFORM_ROT_90) {
455        //swap screen width and height
456        int tmp = screen_w;
457        screen_w  = screen_h;
458        screen_h = tmp;
459    }
460    private_handle_t *tmpHnd = NULL;
461
462    if(screen_w <=0 || screen_h<=0 ||src_crop_width<=0 || src_crop_height<=0 ) {
463        ALOGE("%s: wrong params for display screen_w=%d src_crop_width=%d \
464        screen_h=%d src_crop_height=%d", __FUNCTION__, screen_w,
465                                src_crop_width,screen_h,src_crop_height);
466        return -1;
467    }
468
469    float dsdx = (float)screen_w/(float)src_crop_width;
470    float dtdy = (float)screen_h/(float)src_crop_height;
471
472    float scaleLimitMax = copybitsMaxScale * copybitsMaxScale;
473    float scaleLimitMin = copybitsMinScale * copybitsMinScale;
474    if(dsdx > scaleLimitMax ||
475        dtdy > scaleLimitMax ||
476        dsdx < 1/scaleLimitMin ||
477        dtdy < 1/scaleLimitMin) {
478        ALOGW("%s: greater than max supported size dsdx=%f dtdy=%f \
479              scaleLimitMax=%f scaleLimitMin=%f", __FUNCTION__,dsdx,dtdy,
480                                          scaleLimitMax,1/scaleLimitMin);
481        return -1;
482    }
483    acquireFd = layer->acquireFenceFd;
484    if(dsdx > copybitsMaxScale ||
485        dtdy > copybitsMaxScale ||
486        dsdx < 1/copybitsMinScale ||
487        dtdy < 1/copybitsMinScale){
488        // The requested scale is out of the range the hardware
489        // can support.
490       ALOGD("%s:%d::Need to scale twice dsdx=%f, dtdy=%f,copybitsMaxScale=%f,\
491                                 copybitsMinScale=%f,screen_w=%d,screen_h=%d \
492                  src_crop_width=%d src_crop_height=%d",__FUNCTION__,__LINE__,
493              dsdx,dtdy,copybitsMaxScale,1/copybitsMinScale,screen_w,screen_h,
494                                              src_crop_width,src_crop_height);
495
496
497       int tmp_w =  src_crop_width;
498       int tmp_h =  src_crop_height;
499
500       if (dsdx > copybitsMaxScale || dtdy > copybitsMaxScale ){
501         tmp_w = (int)((float)src_crop_width*copybitsMaxScale);
502         tmp_h = (int)((float)src_crop_height*copybitsMaxScale);
503       }else if (dsdx < 1/copybitsMinScale ||dtdy < 1/copybitsMinScale ){
504         // ceil the tmp_w and tmp_h value to maintain proper ratio
505         // b/w src and dst (should not cross the desired scale limit
506         // due to float -> int )
507         tmp_w = (int)ceil((float)src_crop_width/copybitsMinScale);
508         tmp_h = (int)ceil((float)src_crop_height/copybitsMinScale);
509       }
510       ALOGD("%s:%d::tmp_w = %d,tmp_h = %d",__FUNCTION__,__LINE__,tmp_w,tmp_h);
511
512       int usage = GRALLOC_USAGE_PRIVATE_IOMMU_HEAP;
513       int format = fbHandle->format;
514
515       // We do not want copybit to generate alpha values from nothing
516       if (format == HAL_PIXEL_FORMAT_RGBA_8888 &&
517               src.format != HAL_PIXEL_FORMAT_RGBA_8888) {
518           format = HAL_PIXEL_FORMAT_RGBX_8888;
519       }
520       if (0 == alloc_buffer(&tmpHnd, tmp_w, tmp_h, format, usage) && tmpHnd) {
521            copybit_image_t tmp_dst;
522            copybit_rect_t tmp_rect;
523            tmp_dst.w = tmp_w;
524            tmp_dst.h = tmp_h;
525            tmp_dst.format = tmpHnd->format;
526            tmp_dst.handle = tmpHnd;
527            tmp_dst.horiz_padding = src.horiz_padding;
528            tmp_dst.vert_padding = src.vert_padding;
529            tmp_rect.l = 0;
530            tmp_rect.t = 0;
531            tmp_rect.r = tmp_dst.w;
532            tmp_rect.b = tmp_dst.h;
533            //create one clip region
534            hwc_rect tmp_hwc_rect = {0,0,tmp_rect.r,tmp_rect.b};
535            hwc_region_t tmp_hwc_reg = {1,(hwc_rect_t const*)&tmp_hwc_rect};
536            region_iterator tmp_it(tmp_hwc_reg);
537            copybit->set_parameter(copybit,COPYBIT_TRANSFORM,0);
538            //TODO: once, we are able to read layer alpha, update this
539            copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, 255);
540            copybit->set_sync(copybit, acquireFd);
541            err = copybit->stretch(copybit,&tmp_dst, &src, &tmp_rect,
542                                                           &srcRect, &tmp_it);
543            if(err < 0){
544                ALOGE("%s:%d::tmp copybit stretch failed",__FUNCTION__,
545                                                             __LINE__);
546                if(tmpHnd)
547                    free_buffer(tmpHnd);
548                return err;
549            }
550            // use release fence as aquire fd for next stretch
551            if (ctx->mMDP.version < qdutils::MDP_V4_0) {
552                copybit->flush_get_fence(copybit, &acquireFd);
553                close(acquireFd);
554                acquireFd = -1;
555            }
556            // copy new src and src rect crop
557            src = tmp_dst;
558            srcRect = tmp_rect;
559      }
560    }
561    // Copybit region
562    hwc_region_t region = layer->visibleRegionScreen;
563    region_iterator copybitRegion(region);
564
565    copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_WIDTH,
566                                          renderBuffer->width);
567    copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_HEIGHT,
568                                          renderBuffer->height);
569    copybit->set_parameter(copybit, COPYBIT_TRANSFORM,
570                                              layerTransform);
571    //TODO: once, we are able to read layer alpha, update this
572    copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, 255);
573    copybit->set_parameter(copybit, COPYBIT_BLEND_MODE,
574                                              layer->blending);
575    copybit->set_parameter(copybit, COPYBIT_DITHER,
576                             (dst.format == HAL_PIXEL_FORMAT_RGB_565)?
577                                             COPYBIT_ENABLE : COPYBIT_DISABLE);
578    copybit->set_parameter(copybit, COPYBIT_FG_LAYER, isFG ?
579                                             COPYBIT_ENABLE : COPYBIT_DISABLE);
580
581    copybit->set_parameter(copybit, COPYBIT_BLIT_TO_FRAMEBUFFER,
582                                                COPYBIT_ENABLE);
583    copybit->set_sync(copybit, acquireFd);
584    err = copybit->stretch(copybit, &dst, &src, &dstRect, &srcRect,
585                                                   &copybitRegion);
586    copybit->set_parameter(copybit, COPYBIT_BLIT_TO_FRAMEBUFFER,
587                                               COPYBIT_DISABLE);
588
589    if(tmpHnd) {
590        if (ctx->mMDP.version < qdutils::MDP_V4_0){
591            int ret = -1, releaseFd;
592            // we need to wait for the buffer before freeing
593            copybit->flush_get_fence(copybit, &releaseFd);
594            ret = sync_wait(releaseFd, 1000);
595            if(ret < 0) {
596                ALOGE("%s: sync_wait error!! error no = %d err str = %s",
597                    __FUNCTION__, errno, strerror(errno));
598            }
599            close(releaseFd);
600        }
601        free_buffer(tmpHnd);
602    }
603
604    if(err < 0)
605        ALOGE("%s: copybit stretch failed",__FUNCTION__);
606    return err;
607}
608
609int CopyBit::fillColorUsingCopybit(hwc_layer_1_t *layer,
610                          private_handle_t *renderBuffer)
611{
612    if (!renderBuffer) {
613        ALOGE("%s: Render Buffer is NULL", __FUNCTION__);
614        return -1;
615    }
616
617    // Copybit dst
618    copybit_image_t dst;
619    dst.w = ALIGN(renderBuffer->width, 32);
620    dst.h = renderBuffer->height;
621    dst.format = renderBuffer->format;
622    dst.base = (void *)renderBuffer->base;
623    dst.handle = (native_handle_t *)renderBuffer;
624
625    // Copybit dst rect
626    hwc_rect_t displayFrame = layer->displayFrame;
627    copybit_rect_t dstRect = {displayFrame.left, displayFrame.top,
628                              displayFrame.right, displayFrame.bottom};
629
630    uint32_t color = layer->transform;
631    copybit_device_t *copybit = mEngine;
632    copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_WIDTH,
633                           renderBuffer->width);
634    copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_HEIGHT,
635                           renderBuffer->height);
636    copybit->set_parameter(copybit, COPYBIT_DITHER,
637                           (dst.format == HAL_PIXEL_FORMAT_RGB_565) ?
638                           COPYBIT_ENABLE : COPYBIT_DISABLE);
639    copybit->set_parameter(copybit, COPYBIT_TRANSFORM, 0);
640    copybit->set_parameter(copybit, COPYBIT_BLEND_MODE, layer->blending);
641    copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, layer->planeAlpha);
642    copybit->set_parameter(copybit, COPYBIT_BLIT_TO_FRAMEBUFFER,COPYBIT_ENABLE);
643    int res = copybit->fill_color(copybit, &dst, &dstRect, color);
644    copybit->set_parameter(copybit,COPYBIT_BLIT_TO_FRAMEBUFFER,COPYBIT_DISABLE);
645    return res;
646}
647
648void CopyBit::getLayerResolution(const hwc_layer_1_t* layer,
649                                 unsigned int& width, unsigned int& height)
650{
651    hwc_rect_t displayFrame  = layer->displayFrame;
652
653    width = displayFrame.right - displayFrame.left;
654    height = displayFrame.bottom - displayFrame.top;
655}
656
657bool CopyBit::validateParams(hwc_context_t *ctx,
658                                        const hwc_display_contents_1_t *list) {
659    //Validate parameters
660    if (!ctx) {
661        ALOGE("%s:Invalid HWC context", __FUNCTION__);
662        return false;
663    } else if (!list) {
664        ALOGE("%s:Invalid HWC layer list", __FUNCTION__);
665        return false;
666    }
667    return true;
668}
669
670
671int CopyBit::allocRenderBuffers(int w, int h, int f)
672{
673    int ret = 0;
674    for (int i = 0; i < NUM_RENDER_BUFFERS; i++) {
675        if (mRenderBuffer[i] == NULL) {
676            ret = alloc_buffer(&mRenderBuffer[i],
677                               w, h, f,
678                               GRALLOC_USAGE_PRIVATE_IOMMU_HEAP);
679        }
680        if(ret < 0) {
681            freeRenderBuffers();
682            break;
683        }
684    }
685    return ret;
686}
687
688void CopyBit::freeRenderBuffers()
689{
690    for (int i = 0; i < NUM_RENDER_BUFFERS; i++) {
691        if(mRenderBuffer[i]) {
692            //Since we are freeing buffer close the fence if it has a valid one.
693            if(mRelFd[i] >= 0) {
694                close(mRelFd[i]);
695                mRelFd[i] = -1;
696            }
697            free_buffer(mRenderBuffer[i]);
698            mRenderBuffer[i] = NULL;
699        }
700    }
701}
702
703private_handle_t * CopyBit::getCurrentRenderBuffer() {
704    return mRenderBuffer[mCurRenderBufferIndex];
705}
706
707void CopyBit::setReleaseFd(int fd) {
708    if(mRelFd[mCurRenderBufferIndex] >=0)
709        close(mRelFd[mCurRenderBufferIndex]);
710    mRelFd[mCurRenderBufferIndex] = dup(fd);
711}
712
713struct copybit_device_t* CopyBit::getCopyBitDevice() {
714    return mEngine;
715}
716
717CopyBit::CopyBit(hwc_context_t *ctx, const int& dpy) : mIsModeOn(false),
718        mCopyBitDraw(false), mCurRenderBufferIndex(0) {
719
720    getBufferSizeAndDimensions(ctx->dpyAttr[dpy].xres,
721            ctx->dpyAttr[dpy].yres,
722            HAL_PIXEL_FORMAT_RGBA_8888,
723            mAlignedFBWidth,
724            mAlignedFBHeight);
725
726    hw_module_t const *module;
727    for (int i = 0; i < NUM_RENDER_BUFFERS; i++) {
728        mRenderBuffer[i] = NULL;
729        mRelFd[i] = -1;
730    }
731
732    char value[PROPERTY_VALUE_MAX];
733    property_get("debug.hwc.dynThreshold", value, "2");
734    mDynThreshold = atof(value);
735
736    if (hw_get_module(COPYBIT_HARDWARE_MODULE_ID, &module) == 0) {
737        if(copybit_open(module, &mEngine) < 0) {
738            ALOGE("FATAL ERROR: copybit open failed.");
739        }
740    } else {
741        ALOGE("FATAL ERROR: copybit hw module not found");
742    }
743}
744
745CopyBit::~CopyBit()
746{
747    freeRenderBuffers();
748    if(mEngine)
749    {
750        copybit_close(mEngine);
751        mEngine = NULL;
752    }
753}
754}; //namespace qhwc
755