hwc_copybit.cpp revision 0c3cc78a939cbb9f9770670cd224a2dabd6d1a41
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 * Copyright (C) 2012-2013, The Linux Foundation. All rights reserved.
4 *
5 * Not a Contribution, Apache license notifications and license are retained
6 * for attribution purposes only.
7 *
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 *      http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 */
20
21#define DEBUG_COPYBIT 0
22#include <copybit.h>
23#include <utils/Timers.h>
24#include <mdp_version.h>
25#include "hwc_copybit.h"
26#include "comptype.h"
27#include "gr.h"
28
29namespace qhwc {
30
31struct range {
32    int current;
33    int end;
34};
35struct region_iterator : public copybit_region_t {
36
37    region_iterator(hwc_region_t region) {
38        mRegion = region;
39        r.end = region.numRects;
40        r.current = 0;
41        this->next = iterate;
42    }
43
44private:
45    static int iterate(copybit_region_t const * self, copybit_rect_t* rect){
46        if (!self || !rect) {
47            ALOGE("iterate invalid parameters");
48            return 0;
49        }
50
51        region_iterator const* me =
52                                  static_cast<region_iterator const*>(self);
53        if (me->r.current != me->r.end) {
54            rect->l = me->mRegion.rects[me->r.current].left;
55            rect->t = me->mRegion.rects[me->r.current].top;
56            rect->r = me->mRegion.rects[me->r.current].right;
57            rect->b = me->mRegion.rects[me->r.current].bottom;
58            me->r.current++;
59            return 1;
60        }
61        return 0;
62    }
63
64    hwc_region_t mRegion;
65    mutable range r;
66};
67
68void CopyBit::reset() {
69    mIsModeOn = false;
70    mCopyBitDraw = false;
71}
72
73bool CopyBit::canUseCopybitForYUV(hwc_context_t *ctx) {
74    // return true for non-overlay targets
75    if(ctx->mMDP.hasOverlay) {
76       return false;
77    }
78    return true;
79}
80
81bool CopyBit::canUseCopybitForRGB(hwc_context_t *ctx,
82                                        hwc_display_contents_1_t *list,
83                                        int dpy) {
84    int compositionType = qdutils::QCCompositionType::
85                                    getInstance().getCompositionType();
86
87    if ((compositionType & qdutils::COMPOSITION_TYPE_C2D) ||
88        (compositionType & qdutils::COMPOSITION_TYPE_DYN)) {
89         if(ctx->listStats[dpy].yuvCount) {
90             //Overlay up & running. Dont use COPYBIT for RGB layers.
91             return false;
92         }
93    }
94
95    if (compositionType & qdutils::COMPOSITION_TYPE_DYN) {
96        // DYN Composition:
97        // use copybit, if (TotalRGBRenderArea < threashold * FB Area)
98        // this is done based on perf inputs in ICS
99        // TODO: Above condition needs to be re-evaluated in JB
100        int fbWidth =  ctx->dpyAttr[dpy].xres;
101        int fbHeight =  ctx->dpyAttr[dpy].yres;
102        unsigned int fbArea = (fbWidth * fbHeight);
103        unsigned int renderArea = getRGBRenderingArea(list);
104            ALOGD_IF (DEBUG_COPYBIT, "%s:renderArea %u, fbArea %u",
105                                  __FUNCTION__, renderArea, fbArea);
106        if (renderArea < (mDynThreshold * fbArea)) {
107            return true;
108        }
109    } else if ((compositionType & qdutils::COMPOSITION_TYPE_MDP)) {
110      // MDP composition, use COPYBIT always
111      return true;
112    } else if ((compositionType & qdutils::COMPOSITION_TYPE_C2D)) {
113      // C2D composition, use COPYBIT
114      return true;
115    }
116    return false;
117}
118
119unsigned int CopyBit::getRGBRenderingArea
120                                    (const hwc_display_contents_1_t *list) {
121    //Calculates total rendering area for RGB layers
122    unsigned int renderArea = 0;
123    unsigned int w=0, h=0;
124    for (unsigned int i=0; i<list->numHwLayers; i++) {
125         private_handle_t *hnd = (private_handle_t *)list->hwLayers[i].handle;
126         if (hnd) {
127             if (BUFFER_TYPE_UI == hnd->bufferType) {
128                 getLayerResolution(&list->hwLayers[i], w, h);
129                 renderArea += (w*h);
130             }
131         }
132    }
133    return renderArea;
134}
135
136bool CopyBit::prepare(hwc_context_t *ctx, hwc_display_contents_1_t *list,
137                                                            int dpy) {
138
139    if(mEngine == NULL) {
140        // No copybit device found - cannot use copybit
141        return false;
142    }
143    int compositionType = qdutils::QCCompositionType::
144                                    getInstance().getCompositionType();
145
146    if ((compositionType == qdutils::COMPOSITION_TYPE_GPU) ||
147        (compositionType == qdutils::COMPOSITION_TYPE_CPU))   {
148        //GPU/CPU composition, don't change layer composition type
149        return true;
150    }
151
152    if(!(validateParams(ctx, list))) {
153        ALOGE("%s:Invalid Params", __FUNCTION__);
154        return false;
155    }
156
157    if(ctx->listStats[dpy].skipCount) {
158        //GPU will be anyways used
159        return false;
160    }
161
162    if (ctx->listStats[dpy].numAppLayers > MAX_NUM_LAYERS) {
163        // Reached max layers supported by HWC.
164        return false;
165    }
166
167    bool useCopybitForYUV = canUseCopybitForYUV(ctx);
168    bool useCopybitForRGB = canUseCopybitForRGB(ctx, list, dpy);
169    LayerProp *layerProp = ctx->layerProp[dpy];
170    size_t fbLayerIndex = ctx->listStats[dpy].fbLayerIndex;
171    hwc_layer_1_t *fbLayer = &list->hwLayers[fbLayerIndex];
172    private_handle_t *fbHnd = (private_handle_t *)fbLayer->handle;
173
174
175
176    //Allocate render buffers if they're not allocated
177    if (useCopybitForYUV || useCopybitForRGB) {
178        int ret = allocRenderBuffers(fbHnd->width,
179                                     fbHnd->height,
180                                     fbHnd->format);
181        if (ret < 0) {
182            return false;
183        } else {
184            mCurRenderBufferIndex = (mCurRenderBufferIndex + 1) %
185                NUM_RENDER_BUFFERS;
186        }
187    }
188
189
190    // numAppLayers-1, as we iterate till 0th layer index
191    for (int i = ctx->listStats[dpy].numAppLayers-1; i >= 0 ; i--) {
192        private_handle_t *hnd = (private_handle_t *)list->hwLayers[i].handle;
193
194        if ((hnd->bufferType == BUFFER_TYPE_VIDEO && useCopybitForYUV) ||
195            (hnd->bufferType == BUFFER_TYPE_UI && useCopybitForRGB)) {
196            layerProp[i].mFlags |= HWC_COPYBIT;
197            list->hwLayers[i].compositionType = HWC_OVERLAY;
198            mCopyBitDraw = true;
199        } else {
200            // We currently cannot mix copybit layers with layers marked to
201            // be drawn on the framebuffer or that are on the layer cache.
202            mCopyBitDraw = false;
203            //There is no need to reset layer properties here as we return in
204            //draw if mCopyBitDraw is false
205        }
206    }
207    return true;
208}
209
210int CopyBit::clear (private_handle_t* hnd, hwc_rect_t& rect)
211{
212    int ret = 0;
213    copybit_rect_t clear_rect = {rect.left, rect.top,
214        rect.right,
215        rect.bottom};
216
217    copybit_image_t buf;
218    buf.w = ALIGN(hnd->width,32);
219    buf.h = hnd->height;
220    buf.format = hnd->format;
221    buf.base = (void *)hnd->base;
222    buf.handle = (native_handle_t *)hnd;
223
224    copybit_device_t *copybit = mEngine;
225    ret = copybit->clear(copybit, &buf, &clear_rect);
226    return ret;
227}
228
229bool CopyBit::draw(hwc_context_t *ctx, hwc_display_contents_1_t *list,
230                                                        int dpy, int32_t *fd) {
231    // draw layers marked for COPYBIT
232    int retVal = true;
233    int copybitLayerCount = 0;
234    LayerProp *layerProp = ctx->layerProp[dpy];
235
236    if(mCopyBitDraw == false) // there is no layer marked for copybit
237        return false ;
238
239    //render buffer
240    private_handle_t *renderBuffer = getCurrentRenderBuffer();
241    if (!renderBuffer) {
242        ALOGE("%s: Render buffer layer handle is NULL", __FUNCTION__);
243        return false;
244    }
245
246    //Wait for the previous frame to complete before rendering onto it
247    if(mRelFd[0] >=0) {
248        sync_wait(mRelFd[0], 1000);
249        close(mRelFd[0]);
250        mRelFd[0] = -1;
251    }
252
253    if (ctx->mMDP.version >= qdutils::MDP_V4_0) {
254        //Clear the visible region on the render buffer
255        //XXX: Do this only when needed.
256        hwc_rect_t clearRegion;
257        getNonWormholeRegion(list, clearRegion);
258        clear(renderBuffer, clearRegion);
259    }
260    // numAppLayers-1, as we iterate from 0th layer index with HWC_COPYBIT flag
261    for (int i = 0; i <= (ctx->listStats[dpy].numAppLayers-1); i++) {
262        hwc_layer_1_t *layer = &list->hwLayers[i];
263        if(!(layerProp[i].mFlags & HWC_COPYBIT)) {
264            ALOGD_IF(DEBUG_COPYBIT, "%s: Not Marked for copybit", __FUNCTION__);
265            continue;
266        }
267        int ret = -1;
268        if (list->hwLayers[i].acquireFenceFd != -1 ) {
269            // Wait for acquire Fence on the App buffers.
270            ret = sync_wait(list->hwLayers[i].acquireFenceFd, 1000);
271            if(ret < 0) {
272                ALOGE("%s: sync_wait error!! error no = %d err str = %s",
273                                    __FUNCTION__, errno, strerror(errno));
274            }
275            close(list->hwLayers[i].acquireFenceFd);
276            list->hwLayers[i].acquireFenceFd = -1;
277        }
278        retVal = drawLayerUsingCopybit(ctx, &(list->hwLayers[i]),
279                                                    renderBuffer, dpy);
280        copybitLayerCount++;
281        if(retVal < 0) {
282            ALOGE("%s : drawLayerUsingCopybit failed", __FUNCTION__);
283        }
284    }
285
286    if (copybitLayerCount) {
287        copybit_device_t *copybit = getCopyBitDevice();
288        // Async mode
289        copybit->flush_get_fence(copybit, fd);
290    }
291    return true;
292}
293
294int  CopyBit::drawLayerUsingCopybit(hwc_context_t *dev, hwc_layer_1_t *layer,
295                                     private_handle_t *renderBuffer, int dpy)
296{
297    hwc_context_t* ctx = (hwc_context_t*)(dev);
298    int err = 0;
299    if(!ctx) {
300         ALOGE("%s: null context ", __FUNCTION__);
301         return -1;
302    }
303
304    private_handle_t *hnd = (private_handle_t *)layer->handle;
305    if(!hnd) {
306        ALOGE("%s: invalid handle", __FUNCTION__);
307        return -1;
308    }
309
310    private_handle_t *fbHandle = (private_handle_t *)renderBuffer;
311    if(!fbHandle) {
312        ALOGE("%s: Framebuffer handle is NULL", __FUNCTION__);
313        return -1;
314    }
315
316    // Set the copybit source:
317    copybit_image_t src;
318    src.w = hnd->width;
319    src.h = hnd->height;
320    src.format = hnd->format;
321    src.base = (void *)hnd->base;
322    src.handle = (native_handle_t *)layer->handle;
323    src.horiz_padding = src.w - hnd->width;
324    // Initialize vertical padding to zero for now,
325    // this needs to change to accomodate vertical stride
326    // if needed in the future
327    src.vert_padding = 0;
328
329    // Copybit source rect
330    hwc_rect_t sourceCrop = layer->sourceCrop;
331    copybit_rect_t srcRect = {sourceCrop.left, sourceCrop.top,
332                              sourceCrop.right,
333                              sourceCrop.bottom};
334
335    // Copybit destination rect
336    hwc_rect_t displayFrame = layer->displayFrame;
337    copybit_rect_t dstRect = {displayFrame.left, displayFrame.top,
338                              displayFrame.right,
339                              displayFrame.bottom};
340
341    // Copybit dst
342    copybit_image_t dst;
343    dst.w = ALIGN(fbHandle->width,32);
344    dst.h = fbHandle->height;
345    dst.format = fbHandle->format;
346    dst.base = (void *)fbHandle->base;
347    dst.handle = (native_handle_t *)fbHandle;
348
349    copybit_device_t *copybit = mEngine;
350
351    int32_t screen_w        = displayFrame.right - displayFrame.left;
352    int32_t screen_h        = displayFrame.bottom - displayFrame.top;
353    int32_t src_crop_width  = sourceCrop.right - sourceCrop.left;
354    int32_t src_crop_height = sourceCrop.bottom -sourceCrop.top;
355
356    // Copybit dst
357    float copybitsMaxScale =
358                      (float)copybit->get(copybit,COPYBIT_MAGNIFICATION_LIMIT);
359    float copybitsMinScale =
360                       (float)copybit->get(copybit,COPYBIT_MINIFICATION_LIMIT);
361
362    if((layer->transform == HWC_TRANSFORM_ROT_90) ||
363                           (layer->transform == HWC_TRANSFORM_ROT_270)) {
364        //swap screen width and height
365        int tmp = screen_w;
366        screen_w  = screen_h;
367        screen_h = tmp;
368    }
369    private_handle_t *tmpHnd = NULL;
370
371    if(screen_w <=0 || screen_h<=0 ||src_crop_width<=0 || src_crop_height<=0 ) {
372        ALOGE("%s: wrong params for display screen_w=%d src_crop_width=%d \
373        screen_w=%d src_crop_width=%d", __FUNCTION__, screen_w,
374                                src_crop_width,screen_w,src_crop_width);
375        return -1;
376    }
377
378    float dsdx = (float)screen_w/src_crop_width;
379    float dtdy = (float)screen_h/src_crop_height;
380
381    float scaleLimitMax = copybitsMaxScale * copybitsMaxScale;
382    float scaleLimitMin = copybitsMinScale * copybitsMinScale;
383    if(dsdx > scaleLimitMax ||
384        dtdy > scaleLimitMax ||
385        dsdx < 1/scaleLimitMin ||
386        dtdy < 1/scaleLimitMin) {
387        ALOGE("%s: greater than max supported size dsdx=%f dtdy=%f \
388              scaleLimitMax=%f scaleLimitMin=%f", __FUNCTION__,dsdx,dtdy,
389                                          scaleLimitMax,1/scaleLimitMin);
390        return -1;
391    }
392    if(dsdx > copybitsMaxScale ||
393        dtdy > copybitsMaxScale ||
394        dsdx < 1/copybitsMinScale ||
395        dtdy < 1/copybitsMinScale){
396        // The requested scale is out of the range the hardware
397        // can support.
398       ALOGE("%s:%d::Need to scale twice dsdx=%f, dtdy=%f,copybitsMaxScale=%f,\
399                                 copybitsMinScale=%f,screen_w=%d,screen_h=%d \
400                  src_crop_width=%d src_crop_height=%d",__FUNCTION__,__LINE__,
401              dsdx,dtdy,copybitsMaxScale,1/copybitsMinScale,screen_w,screen_h,
402                                              src_crop_width,src_crop_height);
403
404       //Driver makes width and height as even
405       //that may cause wrong calculation of the ratio
406       //in display and crop.Hence we make
407       //crop width and height as even.
408       src_crop_width  = (src_crop_width/2)*2;
409       src_crop_height = (src_crop_height/2)*2;
410
411       int tmp_w =  src_crop_width;
412       int tmp_h =  src_crop_height;
413
414       if (dsdx > copybitsMaxScale || dtdy > copybitsMaxScale ){
415         tmp_w = src_crop_width*copybitsMaxScale;
416         tmp_h = src_crop_height*copybitsMaxScale;
417       }else if (dsdx < 1/copybitsMinScale ||dtdy < 1/copybitsMinScale ){
418         tmp_w = src_crop_width/copybitsMinScale;
419         tmp_h = src_crop_height/copybitsMinScale;
420         tmp_w  = (tmp_w/2)*2;
421         tmp_h = (tmp_h/2)*2;
422       }
423       ALOGE("%s:%d::tmp_w = %d,tmp_h = %d",__FUNCTION__,__LINE__,tmp_w,tmp_h);
424
425       int usage = GRALLOC_USAGE_PRIVATE_IOMMU_HEAP;
426
427       if (0 == alloc_buffer(&tmpHnd, tmp_w, tmp_h, fbHandle->format, usage)){
428            copybit_image_t tmp_dst;
429            copybit_rect_t tmp_rect;
430            tmp_dst.w = tmp_w;
431            tmp_dst.h = tmp_h;
432            tmp_dst.format = tmpHnd->format;
433            tmp_dst.handle = tmpHnd;
434            tmp_dst.horiz_padding = src.horiz_padding;
435            tmp_dst.vert_padding = src.vert_padding;
436            tmp_rect.l = 0;
437            tmp_rect.t = 0;
438            tmp_rect.r = tmp_dst.w;
439            tmp_rect.b = tmp_dst.h;
440            //create one clip region
441            hwc_rect tmp_hwc_rect = {0,0,tmp_rect.r,tmp_rect.b};
442            hwc_region_t tmp_hwc_reg = {1,(hwc_rect_t const*)&tmp_hwc_rect};
443            region_iterator tmp_it(tmp_hwc_reg);
444            copybit->set_parameter(copybit,COPYBIT_TRANSFORM,0);
445            //TODO: once, we are able to read layer alpha, update this
446            copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, 255);
447            err = copybit->stretch(copybit,&tmp_dst, &src, &tmp_rect,
448                                                           &srcRect, &tmp_it);
449            if(err < 0){
450                ALOGE("%s:%d::tmp copybit stretch failed",__FUNCTION__,
451                                                             __LINE__);
452                if(tmpHnd)
453                    free_buffer(tmpHnd);
454                return err;
455            }
456            // copy new src and src rect crop
457            src = tmp_dst;
458            srcRect = tmp_rect;
459      }
460    }
461    // Copybit region
462    hwc_region_t region = layer->visibleRegionScreen;
463    region_iterator copybitRegion(region);
464
465    copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_WIDTH,
466                                          renderBuffer->width);
467    copybit->set_parameter(copybit, COPYBIT_FRAMEBUFFER_HEIGHT,
468                                          renderBuffer->height);
469    copybit->set_parameter(copybit, COPYBIT_TRANSFORM,
470                                              layer->transform);
471    //TODO: once, we are able to read layer alpha, update this
472    copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, 255);
473    copybit->set_parameter(copybit, COPYBIT_BLEND_MODE,
474                                              layer->blending);
475    copybit->set_parameter(copybit, COPYBIT_DITHER,
476                             (dst.format == HAL_PIXEL_FORMAT_RGB_565)?
477                                             COPYBIT_ENABLE : COPYBIT_DISABLE);
478    copybit->set_parameter(copybit, COPYBIT_BLIT_TO_FRAMEBUFFER,
479                                                COPYBIT_ENABLE);
480    err = copybit->stretch(copybit, &dst, &src, &dstRect, &srcRect,
481                                                   &copybitRegion);
482    copybit->set_parameter(copybit, COPYBIT_BLIT_TO_FRAMEBUFFER,
483                                               COPYBIT_DISABLE);
484
485    if(tmpHnd)
486        free_buffer(tmpHnd);
487
488    if(err < 0)
489        ALOGE("%s: copybit stretch failed",__FUNCTION__);
490    return err;
491}
492
493void CopyBit::getLayerResolution(const hwc_layer_1_t* layer,
494                                 unsigned int& width, unsigned int& height)
495{
496    hwc_rect_t displayFrame  = layer->displayFrame;
497
498    width = displayFrame.right - displayFrame.left;
499    height = displayFrame.bottom - displayFrame.top;
500}
501
502bool CopyBit::validateParams(hwc_context_t *ctx,
503                                        const hwc_display_contents_1_t *list) {
504    //Validate parameters
505    if (!ctx) {
506        ALOGE("%s:Invalid HWC context", __FUNCTION__);
507        return false;
508    } else if (!list) {
509        ALOGE("%s:Invalid HWC layer list", __FUNCTION__);
510        return false;
511    }
512    return true;
513}
514
515
516int CopyBit::allocRenderBuffers(int w, int h, int f)
517{
518    int ret = 0;
519    for (int i = 0; i < NUM_RENDER_BUFFERS; i++) {
520        if (mRenderBuffer[i] == NULL) {
521            ret = alloc_buffer(&mRenderBuffer[i],
522                               w, h, f,
523                               GRALLOC_USAGE_PRIVATE_IOMMU_HEAP);
524        }
525        if(ret < 0) {
526            freeRenderBuffers();
527            break;
528        }
529    }
530    return ret;
531}
532
533void CopyBit::freeRenderBuffers()
534{
535    for (int i = 0; i < NUM_RENDER_BUFFERS; i++) {
536        if(mRenderBuffer[i]) {
537            free_buffer(mRenderBuffer[i]);
538            mRenderBuffer[i] = NULL;
539        }
540    }
541}
542
543private_handle_t * CopyBit::getCurrentRenderBuffer() {
544    return mRenderBuffer[mCurRenderBufferIndex];
545}
546
547void CopyBit::setReleaseFd(int fd) {
548    if(mRelFd[0] >=0)
549        close(mRelFd[0]);
550    mRelFd[0] = mRelFd[1];
551    mRelFd[1] = dup(fd);
552}
553
554struct copybit_device_t* CopyBit::getCopyBitDevice() {
555    return mEngine;
556}
557
558CopyBit::CopyBit():mIsModeOn(false), mCopyBitDraw(false),
559    mCurRenderBufferIndex(0){
560    hw_module_t const *module;
561    for (int i = 0; i < NUM_RENDER_BUFFERS; i++)
562        mRenderBuffer[i] = NULL;
563    mRelFd[0] = -1;
564    mRelFd[1] = -1;
565
566    char value[PROPERTY_VALUE_MAX];
567    property_get("debug.hwc.dynThreshold", value, "2");
568    mDynThreshold = atof(value);
569
570    if (hw_get_module(COPYBIT_HARDWARE_MODULE_ID, &module) == 0) {
571        if(copybit_open(module, &mEngine) < 0) {
572            ALOGE("FATAL ERROR: copybit open failed.");
573        }
574    } else {
575        ALOGE("FATAL ERROR: copybit hw module not found");
576    }
577}
578
579CopyBit::~CopyBit()
580{
581    freeRenderBuffers();
582    if(mRelFd[0] >=0)
583        close(mRelFd[0]);
584    if(mRelFd[1] >=0)
585        close(mRelFd[1]);
586    if(mEngine)
587    {
588        copybit_close(mEngine);
589        mEngine = NULL;
590    }
591}
592}; //namespace qhwc
593