rsAllocation.cpp revision 366c9c85196675437a8dd74c1cf6b63ddbde3d6a
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef ANDROID_RS_BUILD_FOR_HOST
17#include "rsContext.h"
18
19#include <GLES/gl.h>
20#include <GLES2/gl2.h>
21#include <GLES/glext.h>
22#else
23#include "rsContextHostStub.h"
24
25#include <OpenGL/gl.h>
26#include <OpenGl/glext.h>
27#endif
28
29#include "utils/StopWatch.h"
30
31using namespace android;
32using namespace android::renderscript;
33
34Allocation::Allocation(Context *rsc, const Type *type, uint32_t usages) : ObjectBase(rsc) {
35    init(rsc, type);
36
37    mUsageFlags = usages;
38
39    mPtr = malloc(mType->getSizeBytes());
40    if (mType->getElement()->getHasReferences()) {
41        memset(mPtr, 0, mType->getSizeBytes());
42    }
43    if (!mPtr) {
44        LOGE("Allocation::Allocation, alloc failure");
45    }
46}
47
48Allocation::Allocation(Context *rsc, const Type *type, void *bmp,
49                       void *callbackData, RsBitmapCallback_t callback)
50                       : ObjectBase(rsc) {
51    init(rsc, type);
52
53    mUsageFlags = RS_ALLOCATION_USAGE_SCRIPT | RS_ALLOCATION_USAGE_GRAPHICS_TEXTURE;
54
55    mPtr = bmp;
56    mUserBitmapCallback = callback;
57    mUserBitmapCallbackData = callbackData;
58}
59
60void Allocation::init(Context *rsc, const Type *type) {
61    mPtr = NULL;
62
63    mCpuWrite = false;
64    mCpuRead = false;
65    mGpuWrite = false;
66    mGpuRead = false;
67
68    mReadWriteRatio = 0;
69    mUpdateSize = 0;
70
71    mIsTexture = false;
72    mTextureID = 0;
73    mIsVertexBuffer = false;
74    mBufferID = 0;
75    mUploadDefered = false;
76
77    mUserBitmapCallback = NULL;
78    mUserBitmapCallbackData = NULL;
79
80    mType.set(type);
81    rsAssert(type);
82
83    mPtr = NULL;
84}
85
86Allocation::~Allocation() {
87    if (mUserBitmapCallback != NULL) {
88        mUserBitmapCallback(mUserBitmapCallbackData);
89    } else {
90        free(mPtr);
91    }
92    mPtr = NULL;
93
94    if (mBufferID) {
95        // Causes a SW crash....
96        //LOGV(" mBufferID %i", mBufferID);
97        //glDeleteBuffers(1, &mBufferID);
98        //mBufferID = 0;
99    }
100    if (mTextureID) {
101        glDeleteTextures(1, &mTextureID);
102        mTextureID = 0;
103    }
104}
105
106void Allocation::setCpuWritable(bool) {
107}
108
109void Allocation::setGpuWritable(bool) {
110}
111
112void Allocation::setCpuReadable(bool) {
113}
114
115void Allocation::setGpuReadable(bool) {
116}
117
118bool Allocation::fixAllocation() {
119    return false;
120}
121
122void Allocation::deferedUploadToTexture(const Context *rsc, bool genMipmap, uint32_t lodOffset) {
123    rsAssert(lodOffset < mType->getLODCount());
124    mIsTexture = true;
125    mTextureLOD = lodOffset;
126    mUploadDefered = true;
127    mTextureGenMipmap = !mType->getDimLOD() && genMipmap;
128}
129
130uint32_t Allocation::getGLTarget() const {
131    if (mIsTexture) {
132        if (mType->getDimFaces()) {
133            return GL_TEXTURE_CUBE_MAP;
134        } else {
135            return GL_TEXTURE_2D;
136        }
137    }
138    if (mIsVertexBuffer) {
139        return GL_ARRAY_BUFFER;
140    }
141    return 0;
142}
143
144void Allocation::syncAll(Context *rsc, RsAllocationUsageType src) {
145    rsAssert(src == RS_ALLOCATION_USAGE_SCRIPT);
146
147    if (mIsTexture) {
148        uploadToTexture(rsc);
149    }
150    if (mIsVertexBuffer) {
151        uploadToBufferObject(rsc);
152    }
153
154    mUploadDefered = false;
155}
156
157void Allocation::uploadToTexture(const Context *rsc) {
158
159    mIsTexture = true;
160    GLenum type = mType->getElement()->getComponent().getGLType();
161    GLenum format = mType->getElement()->getComponent().getGLFormat();
162
163    if (!type || !format) {
164        return;
165    }
166
167    bool isFirstUpload = false;
168
169    if (!mTextureID) {
170        glGenTextures(1, &mTextureID);
171
172        if (!mTextureID) {
173            // This should not happen, however, its likely the cause of the
174            // white sqare bug.
175            // Force a crash to 1: restart the app, 2: make sure we get a bugreport.
176            LOGE("Upload to texture failed to gen mTextureID");
177            rsc->dumpDebug();
178            mUploadDefered = true;
179            return;
180        }
181        isFirstUpload = true;
182    }
183
184    GLenum target = (GLenum)getGLTarget();
185    glBindTexture(target, mTextureID);
186    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
187
188    if (target == GL_TEXTURE_2D) {
189        upload2DTexture(isFirstUpload);
190    } else if (target == GL_TEXTURE_CUBE_MAP) {
191        uploadCubeTexture(isFirstUpload);
192    }
193
194    if (mTextureGenMipmap) {
195#ifndef ANDROID_RS_BUILD_FOR_HOST
196        glGenerateMipmap(target);
197#endif //ANDROID_RS_BUILD_FOR_HOST
198    }
199
200    rsc->checkError("Allocation::uploadToTexture");
201}
202
203void Allocation::upload2DTexture(bool isFirstUpload) {
204    GLenum type = mType->getElement()->getComponent().getGLType();
205    GLenum format = mType->getElement()->getComponent().getGLFormat();
206
207    Adapter2D adapt(getContext(), this);
208    for (uint32_t lod = 0; (lod + mTextureLOD) < mType->getLODCount(); lod++) {
209        adapt.setLOD(lod+mTextureLOD);
210
211        uint16_t * ptr = static_cast<uint16_t *>(adapt.getElement(0,0));
212        if (isFirstUpload) {
213            glTexImage2D(GL_TEXTURE_2D, lod, format,
214                         adapt.getDimX(), adapt.getDimY(),
215                         0, format, type, ptr);
216        } else {
217            glTexSubImage2D(GL_TEXTURE_2D, lod, 0, 0,
218                            adapt.getDimX(), adapt.getDimY(),
219                            format, type, ptr);
220        }
221    }
222}
223
224void Allocation::uploadCubeTexture(bool isFirstUpload) {
225    GLenum type = mType->getElement()->getComponent().getGLType();
226    GLenum format = mType->getElement()->getComponent().getGLFormat();
227
228    GLenum faceOrder[] = {
229        GL_TEXTURE_CUBE_MAP_POSITIVE_X,
230        GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
231        GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
232        GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
233        GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
234        GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
235    };
236
237    Adapter2D adapt(getContext(), this);
238    for (uint32_t face = 0; face < 6; face ++) {
239        adapt.setFace(face);
240
241        for (uint32_t lod = 0; (lod + mTextureLOD) < mType->getLODCount(); lod++) {
242            adapt.setLOD(lod+mTextureLOD);
243
244            uint16_t * ptr = static_cast<uint16_t *>(adapt.getElement(0,0));
245
246            if (isFirstUpload) {
247                glTexImage2D(faceOrder[face], lod, format,
248                             adapt.getDimX(), adapt.getDimY(),
249                             0, format, type, ptr);
250            } else {
251                glTexSubImage2D(faceOrder[face], lod, 0, 0,
252                                adapt.getDimX(), adapt.getDimY(),
253                                format, type, ptr);
254            }
255        }
256    }
257}
258
259void Allocation::deferedUploadToBufferObject(const Context *rsc) {
260    mIsVertexBuffer = true;
261    mUploadDefered = true;
262}
263
264void Allocation::uploadToBufferObject(const Context *rsc) {
265    rsAssert(!mType->getDimY());
266    rsAssert(!mType->getDimZ());
267
268    mIsVertexBuffer = true;
269
270    if (!mBufferID) {
271        glGenBuffers(1, &mBufferID);
272    }
273    if (!mBufferID) {
274        LOGE("Upload to buffer object failed");
275        mUploadDefered = true;
276        return;
277    }
278    GLenum target = (GLenum)getGLTarget();
279    glBindBuffer(target, mBufferID);
280    glBufferData(target, mType->getSizeBytes(), getPtr(), GL_DYNAMIC_DRAW);
281    glBindBuffer(target, 0);
282    rsc->checkError("Allocation::uploadToBufferObject");
283}
284
285void Allocation::uploadCheck(Context *rsc) {
286    if (mUploadDefered) {
287        syncAll(rsc, RS_ALLOCATION_USAGE_SCRIPT);
288    }
289}
290
291
292void Allocation::data(Context *rsc, const void *data, uint32_t sizeBytes) {
293    uint32_t size = mType->getSizeBytes();
294    if (size != sizeBytes) {
295        LOGE("Allocation::data called with mismatched size expected %i, got %i", size, sizeBytes);
296        return;
297    }
298
299    if (mType->getElement()->getHasReferences()) {
300        incRefs(data, sizeBytes / mType->getElement()->getSizeBytes());
301        decRefs(mPtr, sizeBytes / mType->getElement()->getSizeBytes());
302    }
303
304    memcpy(mPtr, data, size);
305    sendDirty();
306    mUploadDefered = true;
307}
308
309void Allocation::read(void *data) {
310    memcpy(data, mPtr, mType->getSizeBytes());
311}
312
313void Allocation::subData(Context *rsc, uint32_t xoff, uint32_t count, const void *data, uint32_t sizeBytes) {
314    uint32_t eSize = mType->getElementSizeBytes();
315    uint8_t * ptr = static_cast<uint8_t *>(mPtr);
316    ptr += eSize * xoff;
317    uint32_t size = count * eSize;
318
319    if (size != sizeBytes) {
320        LOGE("Allocation::subData called with mismatched size expected %i, got %i", size, sizeBytes);
321        mType->dumpLOGV("type info");
322        return;
323    }
324
325    if (mType->getElement()->getHasReferences()) {
326        incRefs(data, count);
327        decRefs(ptr, count);
328    }
329
330    memcpy(ptr, data, size);
331    sendDirty();
332    mUploadDefered = true;
333}
334
335void Allocation::subData(Context *rsc, uint32_t xoff, uint32_t yoff,
336             uint32_t w, uint32_t h, const void *data, uint32_t sizeBytes) {
337    uint32_t eSize = mType->getElementSizeBytes();
338    uint32_t lineSize = eSize * w;
339    uint32_t destW = mType->getDimX();
340
341    const uint8_t *src = static_cast<const uint8_t *>(data);
342    uint8_t *dst = static_cast<uint8_t *>(mPtr);
343    dst += eSize * (xoff + yoff * destW);
344
345    if ((lineSize * eSize * h) != sizeBytes) {
346        rsAssert(!"Allocation::subData called with mismatched size");
347        return;
348    }
349
350    for (uint32_t line=yoff; line < (yoff+h); line++) {
351        if (mType->getElement()->getHasReferences()) {
352            incRefs(src, w);
353            decRefs(dst, w);
354        }
355        memcpy(dst, src, lineSize);
356        src += lineSize;
357        dst += destW * eSize;
358    }
359    sendDirty();
360    mUploadDefered = true;
361}
362
363void Allocation::subData(Context *rsc, uint32_t xoff, uint32_t yoff, uint32_t zoff,
364             uint32_t w, uint32_t h, uint32_t d, const void *data, uint32_t sizeBytes) {
365}
366
367void Allocation::subElementData(Context *rsc, uint32_t x, const void *data,
368                                uint32_t cIdx, uint32_t sizeBytes) {
369    uint32_t eSize = mType->getElementSizeBytes();
370    uint8_t * ptr = static_cast<uint8_t *>(mPtr);
371    ptr += eSize * x;
372
373    if (cIdx >= mType->getElement()->getFieldCount()) {
374        LOGE("Error Allocation::subElementData component %i out of range.", cIdx);
375        rsc->setError(RS_ERROR_BAD_VALUE, "subElementData component out of range.");
376        return;
377    }
378
379    if (x >= mType->getDimX()) {
380        LOGE("Error Allocation::subElementData X offset %i out of range.", x);
381        rsc->setError(RS_ERROR_BAD_VALUE, "subElementData X offset out of range.");
382        return;
383    }
384
385    const Element * e = mType->getElement()->getField(cIdx);
386    ptr += mType->getElement()->getFieldOffsetBytes(cIdx);
387
388    if (sizeBytes != e->getSizeBytes()) {
389        LOGE("Error Allocation::subElementData data size %i does not match field size %i.", sizeBytes, e->getSizeBytes());
390        rsc->setError(RS_ERROR_BAD_VALUE, "subElementData bad size.");
391        return;
392    }
393
394    if (e->getHasReferences()) {
395        e->incRefs(data);
396        e->decRefs(ptr);
397    }
398
399    memcpy(ptr, data, sizeBytes);
400    sendDirty();
401    mUploadDefered = true;
402}
403
404void Allocation::subElementData(Context *rsc, uint32_t x, uint32_t y,
405                                const void *data, uint32_t cIdx, uint32_t sizeBytes) {
406    uint32_t eSize = mType->getElementSizeBytes();
407    uint8_t * ptr = static_cast<uint8_t *>(mPtr);
408    ptr += eSize * (x + y * mType->getDimX());
409
410    if (x >= mType->getDimX()) {
411        LOGE("Error Allocation::subElementData X offset %i out of range.", x);
412        rsc->setError(RS_ERROR_BAD_VALUE, "subElementData X offset out of range.");
413        return;
414    }
415
416    if (y >= mType->getDimY()) {
417        LOGE("Error Allocation::subElementData X offset %i out of range.", x);
418        rsc->setError(RS_ERROR_BAD_VALUE, "subElementData X offset out of range.");
419        return;
420    }
421
422    if (cIdx >= mType->getElement()->getFieldCount()) {
423        LOGE("Error Allocation::subElementData component %i out of range.", cIdx);
424        rsc->setError(RS_ERROR_BAD_VALUE, "subElementData component out of range.");
425        return;
426    }
427
428    const Element * e = mType->getElement()->getField(cIdx);
429    ptr += mType->getElement()->getFieldOffsetBytes(cIdx);
430
431    if (sizeBytes != e->getSizeBytes()) {
432        LOGE("Error Allocation::subElementData data size %i does not match field size %i.", sizeBytes, e->getSizeBytes());
433        rsc->setError(RS_ERROR_BAD_VALUE, "subElementData bad size.");
434        return;
435    }
436
437    if (e->getHasReferences()) {
438        e->incRefs(data);
439        e->decRefs(ptr);
440    }
441
442    memcpy(ptr, data, sizeBytes);
443    sendDirty();
444    mUploadDefered = true;
445}
446
447void Allocation::addProgramToDirty(const Program *p) {
448    mToDirtyList.push(p);
449}
450
451void Allocation::removeProgramToDirty(const Program *p) {
452    for (size_t ct=0; ct < mToDirtyList.size(); ct++) {
453        if (mToDirtyList[ct] == p) {
454            mToDirtyList.removeAt(ct);
455            return;
456        }
457    }
458    rsAssert(0);
459}
460
461void Allocation::dumpLOGV(const char *prefix) const {
462    ObjectBase::dumpLOGV(prefix);
463
464    String8 s(prefix);
465    s.append(" type ");
466    if (mType.get()) {
467        mType->dumpLOGV(s.string());
468    }
469
470    LOGV("%s allocation ptr=%p mCpuWrite=%i, mCpuRead=%i, mGpuWrite=%i, mGpuRead=%i",
471          prefix, mPtr, mCpuWrite, mCpuRead, mGpuWrite, mGpuRead);
472
473    LOGV("%s allocation mIsTexture=%i mTextureID=%i, mIsVertexBuffer=%i, mBufferID=%i",
474          prefix, mIsTexture, mTextureID, mIsVertexBuffer, mBufferID);
475}
476
477void Allocation::serialize(OStream *stream) const {
478    // Need to identify ourselves
479    stream->addU32((uint32_t)getClassId());
480
481    String8 name(getName());
482    stream->addString(&name);
483
484    // First thing we need to serialize is the type object since it will be needed
485    // to initialize the class
486    mType->serialize(stream);
487
488    uint32_t dataSize = mType->getSizeBytes();
489    // Write how much data we are storing
490    stream->addU32(dataSize);
491    // Now write the data
492    stream->addByteArray(mPtr, dataSize);
493}
494
495Allocation *Allocation::createFromStream(Context *rsc, IStream *stream) {
496    // First make sure we are reading the correct object
497    RsA3DClassID classID = (RsA3DClassID)stream->loadU32();
498    if (classID != RS_A3D_CLASS_ID_ALLOCATION) {
499        LOGE("allocation loading skipped due to invalid class id\n");
500        return NULL;
501    }
502
503    String8 name;
504    stream->loadString(&name);
505
506    Type *type = Type::createFromStream(rsc, stream);
507    if (!type) {
508        return NULL;
509    }
510    type->compute();
511
512    // Number of bytes we wrote out for this allocation
513    uint32_t dataSize = stream->loadU32();
514    if (dataSize != type->getSizeBytes()) {
515        LOGE("failed to read allocation because numbytes written is not the same loaded type wants\n");
516        ObjectBase::checkDelete(type);
517        return NULL;
518    }
519
520    Allocation *alloc = new Allocation(rsc, type, RS_ALLOCATION_USAGE_ALL);
521    alloc->setName(name.string(), name.size());
522
523    // Read in all of our allocation data
524    alloc->data(rsc, stream->getPtr() + stream->getPos(), dataSize);
525    stream->reset(stream->getPos() + dataSize);
526
527    return alloc;
528}
529
530void Allocation::sendDirty() const {
531    for (size_t ct=0; ct < mToDirtyList.size(); ct++) {
532        mToDirtyList[ct]->forceDirty();
533    }
534}
535
536void Allocation::incRefs(const void *ptr, size_t ct, size_t startOff) const {
537    const uint8_t *p = static_cast<const uint8_t *>(ptr);
538    const Element *e = mType->getElement();
539    uint32_t stride = e->getSizeBytes();
540
541    p += stride * startOff;
542    while (ct > 0) {
543        e->incRefs(p);
544        ct --;
545        p += stride;
546    }
547}
548
549void Allocation::decRefs(const void *ptr, size_t ct, size_t startOff) const {
550    const uint8_t *p = static_cast<const uint8_t *>(ptr);
551    const Element *e = mType->getElement();
552    uint32_t stride = e->getSizeBytes();
553
554    p += stride * startOff;
555    while (ct > 0) {
556        e->decRefs(p);
557        ct --;
558        p += stride;
559    }
560}
561
562void Allocation::copyRange1D(Context *rsc, const Allocation *src, int32_t srcOff, int32_t destOff, int32_t len) {
563}
564
565void Allocation::resize1D(Context *rsc, uint32_t dimX) {
566    Type *t = mType->cloneAndResize1D(rsc, dimX);
567
568    uint32_t oldDimX = mType->getDimX();
569    if (dimX == oldDimX) {
570        return;
571    }
572
573    if (dimX < oldDimX) {
574        decRefs(mPtr, oldDimX - dimX, dimX);
575    }
576    mPtr = realloc(mPtr, t->getSizeBytes());
577
578    if (dimX > oldDimX) {
579        const Element *e = mType->getElement();
580        uint32_t stride = e->getSizeBytes();
581        memset(((uint8_t *)mPtr) + stride * oldDimX, 0, stride * (dimX - oldDimX));
582    }
583    mType.set(t);
584}
585
586void Allocation::resize2D(Context *rsc, uint32_t dimX, uint32_t dimY) {
587    LOGE("not implemented");
588}
589
590/////////////////
591//
592
593
594namespace android {
595namespace renderscript {
596
597void rsi_AllocationUploadToTexture(Context *rsc, RsAllocation va, bool genmip, uint32_t baseMipLevel) {
598    Allocation *alloc = static_cast<Allocation *>(va);
599    alloc->deferedUploadToTexture(rsc, genmip, baseMipLevel);
600}
601
602void rsi_AllocationUploadToBufferObject(Context *rsc, RsAllocation va) {
603    Allocation *alloc = static_cast<Allocation *>(va);
604    alloc->deferedUploadToBufferObject(rsc);
605}
606
607static void mip565(const Adapter2D &out, const Adapter2D &in) {
608    uint32_t w = out.getDimX();
609    uint32_t h = out.getDimY();
610
611    for (uint32_t y=0; y < h; y++) {
612        uint16_t *oPtr = static_cast<uint16_t *>(out.getElement(0, y));
613        const uint16_t *i1 = static_cast<uint16_t *>(in.getElement(0, y*2));
614        const uint16_t *i2 = static_cast<uint16_t *>(in.getElement(0, y*2+1));
615
616        for (uint32_t x=0; x < w; x++) {
617            *oPtr = rsBoxFilter565(i1[0], i1[1], i2[0], i2[1]);
618            oPtr ++;
619            i1 += 2;
620            i2 += 2;
621        }
622    }
623}
624
625static void mip8888(const Adapter2D &out, const Adapter2D &in) {
626    uint32_t w = out.getDimX();
627    uint32_t h = out.getDimY();
628
629    for (uint32_t y=0; y < h; y++) {
630        uint32_t *oPtr = static_cast<uint32_t *>(out.getElement(0, y));
631        const uint32_t *i1 = static_cast<uint32_t *>(in.getElement(0, y*2));
632        const uint32_t *i2 = static_cast<uint32_t *>(in.getElement(0, y*2+1));
633
634        for (uint32_t x=0; x < w; x++) {
635            *oPtr = rsBoxFilter8888(i1[0], i1[1], i2[0], i2[1]);
636            oPtr ++;
637            i1 += 2;
638            i2 += 2;
639        }
640    }
641}
642
643static void mip8(const Adapter2D &out, const Adapter2D &in) {
644    uint32_t w = out.getDimX();
645    uint32_t h = out.getDimY();
646
647    for (uint32_t y=0; y < h; y++) {
648        uint8_t *oPtr = static_cast<uint8_t *>(out.getElement(0, y));
649        const uint8_t *i1 = static_cast<uint8_t *>(in.getElement(0, y*2));
650        const uint8_t *i2 = static_cast<uint8_t *>(in.getElement(0, y*2+1));
651
652        for (uint32_t x=0; x < w; x++) {
653            *oPtr = (uint8_t)(((uint32_t)i1[0] + i1[1] + i2[0] + i2[1]) * 0.25f);
654            oPtr ++;
655            i1 += 2;
656            i2 += 2;
657        }
658    }
659}
660
661static void mip(const Adapter2D &out, const Adapter2D &in) {
662    switch (out.getBaseType()->getElement()->getSizeBits()) {
663    case 32:
664        mip8888(out, in);
665        break;
666    case 16:
667        mip565(out, in);
668        break;
669    case 8:
670        mip8(out, in);
671        break;
672    }
673}
674
675typedef void (*ElementConverter_t)(void *dst, const void *src, uint32_t count);
676
677static void elementConverter_cpy_16(void *dst, const void *src, uint32_t count) {
678    memcpy(dst, src, count * 2);
679}
680static void elementConverter_cpy_8(void *dst, const void *src, uint32_t count) {
681    memcpy(dst, src, count);
682}
683static void elementConverter_cpy_32(void *dst, const void *src, uint32_t count) {
684    memcpy(dst, src, count * 4);
685}
686
687static void elementConverter_888_to_565(void *dst, const void *src, uint32_t count) {
688    uint16_t *d = static_cast<uint16_t *>(dst);
689    const uint8_t *s = static_cast<const uint8_t *>(src);
690
691    while (count--) {
692        *d = rs888to565(s[0], s[1], s[2]);
693        d++;
694        s+= 3;
695    }
696}
697
698static void elementConverter_8888_to_565(void *dst, const void *src, uint32_t count) {
699    uint16_t *d = static_cast<uint16_t *>(dst);
700    const uint8_t *s = static_cast<const uint8_t *>(src);
701
702    while (count--) {
703        *d = rs888to565(s[0], s[1], s[2]);
704        d++;
705        s+= 4;
706    }
707}
708
709static ElementConverter_t pickConverter(const Element *dst, const Element *src) {
710    GLenum srcGLType = src->getComponent().getGLType();
711    GLenum srcGLFmt = src->getComponent().getGLFormat();
712    GLenum dstGLType = dst->getComponent().getGLType();
713    GLenum dstGLFmt = dst->getComponent().getGLFormat();
714
715    if (srcGLFmt == dstGLFmt && srcGLType == dstGLType) {
716        switch (dst->getSizeBytes()) {
717        case 4:
718            return elementConverter_cpy_32;
719        case 2:
720            return elementConverter_cpy_16;
721        case 1:
722            return elementConverter_cpy_8;
723        }
724    }
725
726    if (srcGLType == GL_UNSIGNED_BYTE &&
727        srcGLFmt == GL_RGB &&
728        dstGLType == GL_UNSIGNED_SHORT_5_6_5 &&
729        dstGLFmt == GL_RGB) {
730
731        return elementConverter_888_to_565;
732    }
733
734    if (srcGLType == GL_UNSIGNED_BYTE &&
735        srcGLFmt == GL_RGBA &&
736        dstGLType == GL_UNSIGNED_SHORT_5_6_5 &&
737        dstGLFmt == GL_RGB) {
738
739        return elementConverter_8888_to_565;
740    }
741
742    LOGE("pickConverter, unsuported combo, src %p,  dst %p", src, dst);
743    LOGE("pickConverter, srcGLType = %x,  srcGLFmt = %x", srcGLType, srcGLFmt);
744    LOGE("pickConverter, dstGLType = %x,  dstGLFmt = %x", dstGLType, dstGLFmt);
745    src->dumpLOGV("SRC ");
746    dst->dumpLOGV("DST ");
747    return 0;
748}
749
750#ifndef ANDROID_RS_BUILD_FOR_HOST
751
752void rsi_AllocationSyncAll(Context *rsc, RsAllocation va, RsAllocationUsageType src) {
753    Allocation *a = static_cast<Allocation *>(va);
754    a->syncAll(rsc, src);
755}
756
757RsAllocation rsi_AllocationCreateBitmapRef(Context *rsc, RsType vtype,
758                                           void *bmp, void *callbackData,
759                                           RsBitmapCallback_t callback) {
760    const Type * type = static_cast<const Type *>(vtype);
761    Allocation * alloc = new Allocation(rsc, type, bmp, callbackData, callback);
762    alloc->incUserRef();
763    return alloc;
764}
765
766void rsi_AllocationUpdateFromBitmap(Context *rsc, RsAllocation va,
767                                    RsElement _src, const void *data) {
768    Allocation *texAlloc = static_cast<Allocation *>(va);
769    const Element *src = static_cast<const Element *>(_src);
770    const Element *dst = texAlloc->getType()->getElement();
771    uint32_t w = texAlloc->getType()->getDimX();
772    uint32_t h = texAlloc->getType()->getDimY();
773    bool genMips = texAlloc->getType()->getDimLOD();
774
775    ElementConverter_t cvt = pickConverter(dst, src);
776    if (cvt) {
777        cvt(texAlloc->getPtr(), data, w * h);
778        if (genMips) {
779            Adapter2D adapt(rsc, texAlloc);
780            Adapter2D adapt2(rsc, texAlloc);
781            for (uint32_t lod=0; lod < (texAlloc->getType()->getLODCount() -1); lod++) {
782                adapt.setLOD(lod);
783                adapt2.setLOD(lod + 1);
784                mip(adapt2, adapt);
785            }
786        }
787    } else {
788        rsc->setError(RS_ERROR_BAD_VALUE, "Unsupported bitmap format");
789    }
790}
791
792void rsi_AllocationData(Context *rsc, RsAllocation va, const void *data, uint32_t sizeBytes) {
793    Allocation *a = static_cast<Allocation *>(va);
794    a->data(rsc, data, sizeBytes);
795}
796
797void rsi_Allocation1DSubData(Context *rsc, RsAllocation va, uint32_t xoff, uint32_t count, const void *data, uint32_t sizeBytes) {
798    Allocation *a = static_cast<Allocation *>(va);
799    a->subData(rsc, xoff, count, data, sizeBytes);
800}
801
802void rsi_Allocation2DSubElementData(Context *rsc, RsAllocation va, uint32_t x, uint32_t y, const void *data, uint32_t eoff, uint32_t sizeBytes) {
803    Allocation *a = static_cast<Allocation *>(va);
804    a->subElementData(rsc, x, y, data, eoff, sizeBytes);
805}
806
807void rsi_Allocation1DSubElementData(Context *rsc, RsAllocation va, uint32_t x, const void *data, uint32_t eoff, uint32_t sizeBytes) {
808    Allocation *a = static_cast<Allocation *>(va);
809    a->subElementData(rsc, x, data, eoff, sizeBytes);
810}
811
812void rsi_Allocation2DSubData(Context *rsc, RsAllocation va, uint32_t xoff, uint32_t yoff, uint32_t w, uint32_t h, const void *data, uint32_t sizeBytes) {
813    Allocation *a = static_cast<Allocation *>(va);
814    a->subData(rsc, xoff, yoff, w, h, data, sizeBytes);
815}
816
817void rsi_AllocationRead(Context *rsc, RsAllocation va, void *data) {
818    Allocation *a = static_cast<Allocation *>(va);
819    a->read(data);
820}
821
822void rsi_AllocationResize1D(Context *rsc, RsAllocation va, uint32_t dimX) {
823    Allocation *a = static_cast<Allocation *>(va);
824    a->resize1D(rsc, dimX);
825}
826
827void rsi_AllocationResize2D(Context *rsc, RsAllocation va, uint32_t dimX, uint32_t dimY) {
828    Allocation *a = static_cast<Allocation *>(va);
829    a->resize2D(rsc, dimX, dimY);
830}
831
832#endif //ANDROID_RS_BUILD_FOR_HOST
833
834}
835}
836
837const void * rsaAllocationGetType(RsContext con, RsAllocation va) {
838    Allocation *a = static_cast<Allocation *>(va);
839    a->getType()->incUserRef();
840
841    return a->getType();
842}
843
844RsAllocation rsaAllocationCreateTyped(RsContext con, RsType vtype,
845                                      RsAllocationMipmapGenerationControl mips,
846                                      uint32_t usages) {
847    Context *rsc = static_cast<Context *>(con);
848    Allocation * alloc = new Allocation(rsc, static_cast<Type *>(vtype), usages);
849    alloc->incUserRef();
850    return alloc;
851}
852
853
854RsAllocation rsaAllocationCreateFromBitmap(RsContext con, RsType vtype,
855                                           RsAllocationMipmapGenerationControl mips,
856                                           const void *data, uint32_t usages) {
857    Context *rsc = static_cast<Context *>(con);
858    Type *t = static_cast<Type *>(vtype);
859
860    RsAllocation vTexAlloc = rsaAllocationCreateTyped(rsc, vtype, mips, usages);
861    Allocation *texAlloc = static_cast<Allocation *>(vTexAlloc);
862    if (texAlloc == NULL) {
863        LOGE("Memory allocation failure");
864        return NULL;
865    }
866
867    memcpy(texAlloc->getPtr(), data, t->getDimX() * t->getDimY() * t->getElementSizeBytes());
868    if (mips == RS_MIPMAP_FULL) {
869        Adapter2D adapt(rsc, texAlloc);
870        Adapter2D adapt2(rsc, texAlloc);
871        for (uint32_t lod=0; lod < (texAlloc->getType()->getLODCount() -1); lod++) {
872            adapt.setLOD(lod);
873            adapt2.setLOD(lod + 1);
874            mip(adapt2, adapt);
875        }
876    }
877
878    return texAlloc;
879}
880
881RsAllocation rsaAllocationCubeCreateFromBitmap(RsContext con, RsType vtype,
882                                               RsAllocationMipmapGenerationControl mips,
883                                               const void *data, uint32_t usages) {
884    Context *rsc = static_cast<Context *>(con);
885    Type *t = static_cast<Type *>(vtype);
886
887    // Cubemap allocation's faces should be Width by Width each.
888    // Source data should have 6 * Width by Width pixels
889    // Error checking is done in the java layer
890    RsAllocation vTexAlloc = rsaAllocationCreateTyped(rsc, t, mips, usages);
891    Allocation *texAlloc = static_cast<Allocation *>(vTexAlloc);
892    if (texAlloc == NULL) {
893        LOGE("Memory allocation failure");
894        return NULL;
895    }
896
897    uint8_t *sourcePtr = (uint8_t*)data;
898    for (uint32_t face = 0; face < 6; face ++) {
899        Adapter2D faceAdapter(rsc, texAlloc);
900        faceAdapter.setFace(face);
901
902        size_t cpySize = t->getDimX() * t->getDimX() * t->getElementSizeBytes();
903        memcpy(faceAdapter.getElement(0, 0), sourcePtr, cpySize);
904
905        // Move the data pointer to the next cube face
906        sourcePtr += cpySize;
907
908        if (mips == RS_MIPMAP_FULL) {
909            Adapter2D adapt(rsc, texAlloc);
910            Adapter2D adapt2(rsc, texAlloc);
911            adapt.setFace(face);
912            adapt2.setFace(face);
913            for (uint32_t lod=0; lod < (texAlloc->getType()->getLODCount() -1); lod++) {
914                adapt.setLOD(lod);
915                adapt2.setLOD(lod + 1);
916                mip(adapt2, adapt);
917            }
918        }
919    }
920
921    return texAlloc;
922}
923