rsScriptC.cpp revision b26fb04770442244233b630960f419cb154abc77
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
17#include "rsContext.h"
18#include "rsScriptC.h"
19#include "rsMatrix.h"
20#include "../../compile/libbcc/include/bcc/bcc.h"
21#include "utils/Timers.h"
22#include "utils/StopWatch.h"
23
24#include <GLES/gl.h>
25#include <GLES/glext.h>
26
27using namespace android;
28using namespace android::renderscript;
29
30#define GET_TLS()  Context::ScriptTLSStruct * tls = \
31    (Context::ScriptTLSStruct *)pthread_getspecific(Context::gThreadTLSKey); \
32    Context * rsc = tls->mContext; \
33    ScriptC * sc = (ScriptC *) tls->mScript
34
35
36ScriptC::ScriptC(Context *rsc) : Script(rsc)
37{
38    mAllocFile = __FILE__;
39    mAllocLine = __LINE__;
40    mBccScript = NULL;
41    memset(&mProgram, 0, sizeof(mProgram));
42}
43
44ScriptC::~ScriptC()
45{
46    if (mBccScript) {
47        bccDeleteScript(mBccScript);
48    }
49    free(mEnviroment.mScriptText);
50    mEnviroment.mScriptText = NULL;
51}
52
53void ScriptC::setupScript(Context *rsc)
54{
55    setupGLState(rsc);
56    mEnviroment.mStartTimeMillis
57                = nanoseconds_to_milliseconds(systemTime(SYSTEM_TIME_MONOTONIC));
58
59    for (uint32_t ct=0; ct < mEnviroment.mFieldCount; ct++) {
60        if (mSlots[ct].get() && !mTypes[ct].get()) {
61            mTypes[ct].set(mSlots[ct]->getType());
62        }
63
64        if (!mTypes[ct].get())
65            continue;
66        void *ptr = NULL;
67        if (mSlots[ct].get()) {
68            ptr = mSlots[ct]->getPtr();
69        }
70        void **dest = ((void ***)mEnviroment.mFieldAddress)[ct];
71
72        if (rsc->props.mLogScripts) {
73            LOGV("%p ScriptC::setupScript slot=%i  dst=%p  src=%p  type=%p", rsc, ct, dest, ptr, mSlots[ct]->getType());
74
75            //const uint32_t *p32 = (const uint32_t *)ptr;
76            //for (uint32_t ct2=0; ct2 < mSlots[ct]->getType()->getDimX(); ct2++) {
77                //LOGE("  %i = 0x%08x ", ct2, p32[ct2]);
78            //}
79        }
80
81        if (dest) {
82            *dest = ptr;
83        } else {
84            LOGE("ScriptC::setupScript, NULL var binding address.");
85        }
86    }
87}
88
89const Allocation *ScriptC::ptrToAllocation(const void *ptr) const
90{
91    if (!ptr) {
92        return NULL;
93    }
94    for (uint32_t ct=0; ct < mEnviroment.mFieldCount; ct++) {
95        if (!mSlots[ct].get())
96            continue;
97        if (mSlots[ct]->getPtr() == ptr) {
98            return mSlots[ct].get();
99        }
100    }
101    LOGE("ScriptC::ptrToAllocation, failed to find %p", ptr);
102    return NULL;
103}
104
105Script * ScriptC::setTLS(Script *sc)
106{
107    Context::ScriptTLSStruct * tls = (Context::ScriptTLSStruct *)
108                                  pthread_getspecific(Context::gThreadTLSKey);
109    rsAssert(tls);
110    Script *old = tls->mScript;
111    tls->mScript = sc;
112    return old;
113}
114
115
116void ScriptC::setupGLState(Context *rsc)
117{
118    if (mEnviroment.mFragmentStore.get()) {
119        rsc->setFragmentStore(mEnviroment.mFragmentStore.get());
120    }
121    if (mEnviroment.mFragment.get()) {
122        rsc->setFragment(mEnviroment.mFragment.get());
123    }
124    if (mEnviroment.mVertex.get()) {
125        rsc->setVertex(mEnviroment.mVertex.get());
126    }
127    if (mEnviroment.mRaster.get()) {
128        rsc->setRaster(mEnviroment.mRaster.get());
129    }
130}
131
132uint32_t ScriptC::run(Context *rsc)
133{
134    if (mProgram.mRoot == NULL) {
135        rsc->setError(RS_ERROR_BAD_SCRIPT, "Attempted to run bad script");
136        return 0;
137    }
138
139    setupScript(rsc);
140
141    uint32_t ret = 0;
142    Script * oldTLS = setTLS(this);
143
144    if (rsc->props.mLogScripts) {
145        LOGV("%p ScriptC::run invoking root,  ptr %p", rsc, mProgram.mRoot);
146    }
147
148    ret = mProgram.mRoot();
149
150    if (rsc->props.mLogScripts) {
151        LOGV("%p ScriptC::run invoking complete, ret=%i", rsc, ret);
152    }
153
154    setTLS(oldTLS);
155    return ret;
156}
157
158
159typedef struct {
160    Context *rsc;
161    ScriptC *script;
162    const Allocation * ain;
163    Allocation * aout;
164    const void * usr;
165
166    uint32_t mSliceSize;
167    volatile int mSliceNum;
168
169    const uint8_t *ptrIn;
170    uint32_t eStrideIn;
171    uint8_t *ptrOut;
172    uint32_t eStrideOut;
173
174    uint32_t xStart;
175    uint32_t xEnd;
176    uint32_t yStart;
177    uint32_t yEnd;
178    uint32_t zStart;
179    uint32_t zEnd;
180    uint32_t arrayStart;
181    uint32_t arrayEnd;
182
183    uint32_t dimX;
184    uint32_t dimY;
185    uint32_t dimZ;
186    uint32_t dimArray;
187} MTLaunchStruct;
188typedef int (*rs_t)(const void *, void *, const void *, uint32_t, uint32_t, uint32_t, uint32_t);
189
190static void wc_xy(void *usr, uint32_t idx)
191{
192    MTLaunchStruct *mtls = (MTLaunchStruct *)usr;
193
194    while (1) {
195        uint32_t slice = (uint32_t)android_atomic_inc(&mtls->mSliceNum);
196        uint32_t yStart = mtls->yStart + slice * mtls->mSliceSize;
197        uint32_t yEnd = yStart + mtls->mSliceSize;
198        yEnd = rsMin(yEnd, mtls->yEnd);
199        if (yEnd <= yStart) {
200            return;
201        }
202
203        //LOGE("usr idx %i, x %i,%i  y %i,%i", idx, mtls->xStart, mtls->xEnd, yStart, yEnd);
204
205        for (uint32_t y = yStart; y < yEnd; y++) {
206            uint32_t offset = mtls->dimX * y;
207            uint8_t *xPtrOut = mtls->ptrOut + (mtls->eStrideOut * offset);
208            const uint8_t *xPtrIn = mtls->ptrIn + (mtls->eStrideIn * offset);
209
210            for (uint32_t x = mtls->xStart; x < mtls->xEnd; x++) {
211                ((rs_t)mtls->script->mProgram.mRoot) (xPtrIn, xPtrOut, mtls->usr, x, y, 0, 0);
212                xPtrIn += mtls->eStrideIn;
213                xPtrOut += mtls->eStrideOut;
214            }
215        }
216    }
217
218}
219
220void ScriptC::runForEach(Context *rsc,
221                         const Allocation * ain,
222                         Allocation * aout,
223                         const void * usr,
224                         const RsScriptCall *sc)
225{
226    MTLaunchStruct mtls;
227    memset(&mtls, 0, sizeof(mtls));
228
229    if (ain) {
230        mtls.dimX = ain->getType()->getDimX();
231        mtls.dimY = ain->getType()->getDimY();
232        mtls.dimZ = ain->getType()->getDimZ();
233        //mtls.dimArray = ain->getType()->getDimArray();
234    } else if (aout) {
235        mtls.dimX = aout->getType()->getDimX();
236        mtls.dimY = aout->getType()->getDimY();
237        mtls.dimZ = aout->getType()->getDimZ();
238        //mtls.dimArray = aout->getType()->getDimArray();
239    } else {
240        rsc->setError(RS_ERROR_BAD_SCRIPT, "rsForEach called with null allocations");
241        return;
242    }
243
244    if (!sc || (sc->xEnd == 0)) {
245        mtls.xEnd = mtls.dimX;
246    } else {
247        rsAssert(sc->xStart < mtls.dimX);
248        rsAssert(sc->xEnd <= mtls.dimX);
249        rsAssert(sc->xStart < sc->xEnd);
250        mtls.xStart = rsMin(mtls.dimX, sc->xStart);
251        mtls.xEnd = rsMin(mtls.dimX, sc->xEnd);
252        if (mtls.xStart >= mtls.xEnd) return;
253    }
254
255    if (!sc || (sc->yEnd == 0)) {
256        mtls.yEnd = mtls.dimY;
257    } else {
258        rsAssert(sc->yStart < mtls.dimY);
259        rsAssert(sc->yEnd <= mtls.dimY);
260        rsAssert(sc->yStart < sc->yEnd);
261        mtls.yStart = rsMin(mtls.dimY, sc->yStart);
262        mtls.yEnd = rsMin(mtls.dimY, sc->yEnd);
263        if (mtls.yStart >= mtls.yEnd) return;
264    }
265
266    mtls.xEnd = rsMax((uint32_t)1, mtls.xEnd);
267    mtls.yEnd = rsMax((uint32_t)1, mtls.yEnd);
268    mtls.zEnd = rsMax((uint32_t)1, mtls.zEnd);
269    mtls.arrayEnd = rsMax((uint32_t)1, mtls.arrayEnd);
270
271    rsAssert(ain->getType()->getDimZ() == 0);
272
273    setupScript(rsc);
274    Script * oldTLS = setTLS(this);
275
276
277    mtls.rsc = rsc;
278    mtls.ain = ain;
279    mtls.aout = aout;
280    mtls.script = this;
281    mtls.usr = usr;
282    mtls.mSliceSize = 10;
283    mtls.mSliceNum = 0;
284
285    mtls.ptrIn = NULL;
286    mtls.eStrideIn = 0;
287    if (ain) {
288        mtls.ptrIn = (const uint8_t *)ain->getPtr();
289        mtls.eStrideIn = ain->getType()->getElementSizeBytes();
290    }
291
292    mtls.ptrOut = NULL;
293    mtls.eStrideOut = 0;
294    if (aout) {
295        mtls.ptrOut = (uint8_t *)aout->getPtr();
296        mtls.eStrideOut = aout->getType()->getElementSizeBytes();
297    }
298
299
300    if ((rsc->getWorkerPoolSize() > 1) && mEnviroment.mIsThreadable &&
301        ((mtls.dimY * mtls.dimZ * mtls.dimArray) > 1)) {
302
303        //LOGE("launch 1");
304        rsc->launchThreads(wc_xy, &mtls);
305        //LOGE("launch 2");
306    } else {
307        for (uint32_t ar = mtls.arrayStart; ar < mtls.arrayEnd; ar++) {
308            for (uint32_t z = mtls.zStart; z < mtls.zEnd; z++) {
309                for (uint32_t y = mtls.yStart; y < mtls.yEnd; y++) {
310                    uint32_t offset = mtls.dimX * mtls.dimY * mtls.dimZ * ar +
311                                      mtls.dimX * mtls.dimY * z +
312                                      mtls.dimX * y;
313                    uint8_t *xPtrOut = mtls.ptrOut + (mtls.eStrideOut * offset);
314                    const uint8_t *xPtrIn = mtls.ptrIn + (mtls.eStrideIn * offset);
315
316                    for (uint32_t x = mtls.xStart; x < mtls.xEnd; x++) {
317                        ((rs_t)mProgram.mRoot) (xPtrIn, xPtrOut, usr, x, y, z, ar);
318                        xPtrIn += mtls.eStrideIn;
319                        xPtrOut += mtls.eStrideOut;
320                    }
321                }
322            }
323        }
324    }
325
326    setTLS(oldTLS);
327}
328
329void ScriptC::Invoke(Context *rsc, uint32_t slot, const void *data, uint32_t len)
330{
331    //LOGE("rsi_ScriptInvoke %i", slot);
332    if ((slot >= mEnviroment.mInvokeFunctionCount) ||
333        (mEnviroment.mInvokeFunctions[slot] == NULL)) {
334        rsc->setError(RS_ERROR_BAD_SCRIPT, "Calling invoke on bad script");
335        return;
336    }
337    setupScript(rsc);
338    Script * oldTLS = setTLS(this);
339
340    if (rsc->props.mLogScripts) {
341        LOGV("%p ScriptC::Invoke invoking slot %i,  ptr %p", rsc, slot, mEnviroment.mInvokeFunctions[slot]);
342    }
343    ((void (*)(const void *, uint32_t))
344        mEnviroment.mInvokeFunctions[slot])(data, len);
345    if (rsc->props.mLogScripts) {
346        LOGV("%p ScriptC::Invoke complete", rsc);
347    }
348
349    setTLS(oldTLS);
350}
351
352ScriptCState::ScriptCState()
353{
354    mScript = NULL;
355    clear();
356}
357
358ScriptCState::~ScriptCState()
359{
360    delete mScript;
361    mScript = NULL;
362}
363
364void ScriptCState::clear()
365{
366    for (uint32_t ct=0; ct < MAX_SCRIPT_BANKS; ct++) {
367        mConstantBufferTypes[ct].clear();
368        mSlotWritable[ct] = false;
369    }
370
371    delete mScript;
372    mScript = new ScriptC(NULL);
373}
374
375static BCCvoid* symbolLookup(BCCvoid* pContext, const BCCchar* name)
376{
377    const ScriptCState::SymbolTable_t *sym;
378    ScriptC *s = (ScriptC *)pContext;
379    sym = ScriptCState::lookupSymbol(name);
380    if (sym) {
381        return sym->mPtr;
382    }
383    s->mEnviroment.mIsThreadable = false;
384    sym = ScriptCState::lookupSymbolCL(name);
385    if (sym) {
386        return sym->mPtr;
387    }
388    sym = ScriptCState::lookupSymbolGL(name);
389    if (sym) {
390        return sym->mPtr;
391    }
392    LOGE("ScriptC sym lookup failed for %s", name);
393    return NULL;
394}
395
396void ScriptCState::runCompiler(Context *rsc, ScriptC *s)
397{
398    LOGV("%p ScriptCState::runCompiler ", rsc);
399    {
400        StopWatch compileTimer("RenderScript compile time");
401        s->mBccScript = bccCreateScript();
402        s->mEnviroment.mIsThreadable = true;
403        bccScriptBitcode(s->mBccScript, s->mEnviroment.mScriptText, s->mEnviroment.mScriptTextLength);
404        bccRegisterSymbolCallback(s->mBccScript, symbolLookup, s);
405        bccCompileScript(s->mBccScript);
406        bccGetScriptLabel(s->mBccScript, "root", (BCCvoid**) &s->mProgram.mRoot);
407        bccGetScriptLabel(s->mBccScript, "init", (BCCvoid**) &s->mProgram.mInit);
408    }
409    LOGV("%p ScriptCState::runCompiler root %p,  init %p", rsc, s->mProgram.mRoot, s->mProgram.mInit);
410
411    if (s->mProgram.mInit) {
412        s->mProgram.mInit();
413    }
414
415    bccGetExportFuncs(s->mBccScript, (BCCsizei*) &s->mEnviroment.mInvokeFunctionCount, 0, NULL);
416    if(s->mEnviroment.mInvokeFunctionCount <= 0)
417        s->mEnviroment.mInvokeFunctions = NULL;
418    else {
419        s->mEnviroment.mInvokeFunctions = (Script::InvokeFunc_t*) calloc(s->mEnviroment.mInvokeFunctionCount, sizeof(Script::InvokeFunc_t));
420        bccGetExportFuncs(s->mBccScript, NULL, s->mEnviroment.mInvokeFunctionCount, (BCCvoid **) s->mEnviroment.mInvokeFunctions);
421    }
422
423    bccGetExportVars(s->mBccScript, (BCCsizei*) &s->mEnviroment.mFieldCount, 0, NULL);
424    if(s->mEnviroment.mFieldCount <= 0)
425        s->mEnviroment.mFieldAddress = NULL;
426    else {
427        s->mEnviroment.mFieldAddress = (void **) calloc(s->mEnviroment.mFieldCount, sizeof(void *));
428        bccGetExportVars(s->mBccScript, NULL, s->mEnviroment.mFieldCount, (BCCvoid **) s->mEnviroment.mFieldAddress);
429    }
430
431    s->mEnviroment.mFragment.set(rsc->getDefaultProgramFragment());
432    s->mEnviroment.mVertex.set(rsc->getDefaultProgramVertex());
433    s->mEnviroment.mFragmentStore.set(rsc->getDefaultProgramStore());
434    s->mEnviroment.mRaster.set(rsc->getDefaultProgramRaster());
435
436    if (s->mProgram.mRoot) {
437        const static int pragmaMax = 16;
438        BCCsizei pragmaCount;
439        BCCchar * str[pragmaMax];
440        bccGetPragmas(s->mBccScript, &pragmaCount, pragmaMax, &str[0]);
441
442        for (int ct=0; ct < pragmaCount; ct+=2) {
443            //LOGE("pragme %s %s", str[ct], str[ct+1]);
444            if (!strcmp(str[ct], "version")) {
445                continue;
446            }
447
448            if (!strcmp(str[ct], "stateVertex")) {
449                if (!strcmp(str[ct+1], "default")) {
450                    continue;
451                }
452                if (!strcmp(str[ct+1], "parent")) {
453                    s->mEnviroment.mVertex.clear();
454                    continue;
455                }
456                LOGE("Unreconized value %s passed to stateVertex", str[ct+1]);
457            }
458
459            if (!strcmp(str[ct], "stateRaster")) {
460                if (!strcmp(str[ct+1], "default")) {
461                    continue;
462                }
463                if (!strcmp(str[ct+1], "parent")) {
464                    s->mEnviroment.mRaster.clear();
465                    continue;
466                }
467                LOGE("Unreconized value %s passed to stateRaster", str[ct+1]);
468            }
469
470            if (!strcmp(str[ct], "stateFragment")) {
471                if (!strcmp(str[ct+1], "default")) {
472                    continue;
473                }
474                if (!strcmp(str[ct+1], "parent")) {
475                    s->mEnviroment.mFragment.clear();
476                    continue;
477                }
478                LOGE("Unreconized value %s passed to stateFragment", str[ct+1]);
479            }
480
481            if (!strcmp(str[ct], "stateStore")) {
482                if (!strcmp(str[ct+1], "default")) {
483                    continue;
484                }
485                if (!strcmp(str[ct+1], "parent")) {
486                    s->mEnviroment.mFragmentStore.clear();
487                    continue;
488                }
489                LOGE("Unreconized value %s passed to stateStore", str[ct+1]);
490            }
491
492        }
493
494
495    } else {
496        // Deal with an error.
497    }
498}
499
500
501
502namespace android {
503namespace renderscript {
504
505void rsi_ScriptCBegin(Context * rsc)
506{
507    ScriptCState *ss = &rsc->mScriptC;
508    ss->clear();
509}
510
511void rsi_ScriptCSetText(Context *rsc, const char *text, uint32_t len)
512{
513    ScriptCState *ss = &rsc->mScriptC;
514
515    char *t = (char *)malloc(len + 1);
516    memcpy(t, text, len);
517    t[len] = 0;
518    ss->mScript->mEnviroment.mScriptText = t;
519    ss->mScript->mEnviroment.mScriptTextLength = len;
520}
521
522
523RsScript rsi_ScriptCCreate(Context * rsc)
524{
525    ScriptCState *ss = &rsc->mScriptC;
526
527    ScriptC *s = ss->mScript;
528    ss->mScript = NULL;
529
530    ss->runCompiler(rsc, s);
531    s->incUserRef();
532    s->setContext(rsc);
533    for (int ct=0; ct < MAX_SCRIPT_BANKS; ct++) {
534        s->mTypes[ct].set(ss->mConstantBufferTypes[ct].get());
535        s->mSlotWritable[ct] = ss->mSlotWritable[ct];
536    }
537
538    ss->clear();
539    return s;
540}
541
542}
543}
544
545
546