rsContext.cpp revision 6f01bcf691433b8413e57fe8b67b0f5dba4d0013
1/*
2 * Copyright (C) 2011 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 "rs.h"
18#include "rsDevice.h"
19#include "rsContext.h"
20#include "rsThreadIO.h"
21#include "rsMesh.h"
22#include <ui/FramebufferNativeWindow.h>
23#include <gui/DisplayEventReceiver.h>
24
25#include <sys/types.h>
26#include <sys/resource.h>
27#include <sched.h>
28
29#include <cutils/properties.h>
30
31#include <sys/syscall.h>
32
33#include <dlfcn.h>
34
35using namespace android;
36using namespace android::renderscript;
37
38pthread_mutex_t Context::gInitMutex = PTHREAD_MUTEX_INITIALIZER;
39pthread_mutex_t Context::gLibMutex = PTHREAD_MUTEX_INITIALIZER;
40
41bool Context::initGLThread() {
42    pthread_mutex_lock(&gInitMutex);
43
44    if (!mHal.funcs.initGraphics(this)) {
45        pthread_mutex_unlock(&gInitMutex);
46        ALOGE("%p initGraphics failed", this);
47        return false;
48    }
49
50    pthread_mutex_unlock(&gInitMutex);
51    return true;
52}
53
54void Context::deinitEGL() {
55    mHal.funcs.shutdownGraphics(this);
56}
57
58Context::PushState::PushState(Context *con) {
59    mRsc = con;
60    if (con->mIsGraphicsContext) {
61        mFragment.set(con->getProgramFragment());
62        mVertex.set(con->getProgramVertex());
63        mStore.set(con->getProgramStore());
64        mRaster.set(con->getProgramRaster());
65        mFont.set(con->getFont());
66    }
67}
68
69Context::PushState::~PushState() {
70    if (mRsc->mIsGraphicsContext) {
71        mRsc->setProgramFragment(mFragment.get());
72        mRsc->setProgramVertex(mVertex.get());
73        mRsc->setProgramStore(mStore.get());
74        mRsc->setProgramRaster(mRaster.get());
75        mRsc->setFont(mFont.get());
76    }
77}
78
79
80uint32_t Context::runScript(Script *s) {
81    PushState ps(this);
82
83    uint32_t ret = s->run(this);
84    return ret;
85}
86
87uint32_t Context::runRootScript() {
88    timerSet(RS_TIMER_SCRIPT);
89    mStateFragmentStore.mLast.clear();
90    watchdog.inRoot = true;
91    uint32_t ret = runScript(mRootScript.get());
92    watchdog.inRoot = false;
93
94    return ret;
95}
96
97uint64_t Context::getTime() const {
98#ifndef ANDROID_RS_SERIALIZE
99    struct timespec t;
100    clock_gettime(CLOCK_MONOTONIC, &t);
101    return t.tv_nsec + ((uint64_t)t.tv_sec * 1000 * 1000 * 1000);
102#else
103    return 0;
104#endif //ANDROID_RS_SERIALIZE
105}
106
107void Context::timerReset() {
108    for (int ct=0; ct < _RS_TIMER_TOTAL; ct++) {
109        mTimers[ct] = 0;
110    }
111}
112
113void Context::timerInit() {
114    mTimeLast = getTime();
115    mTimeFrame = mTimeLast;
116    mTimeLastFrame = mTimeLast;
117    mTimerActive = RS_TIMER_INTERNAL;
118    mAverageFPSFrameCount = 0;
119    mAverageFPSStartTime = mTimeLast;
120    mAverageFPS = 0;
121    timerReset();
122}
123
124void Context::timerFrame() {
125    mTimeLastFrame = mTimeFrame;
126    mTimeFrame = getTime();
127    // Update average fps
128    const uint64_t averageFramerateInterval = 1000 * 1000000;
129    mAverageFPSFrameCount ++;
130    uint64_t inverval = mTimeFrame - mAverageFPSStartTime;
131    if (inverval >= averageFramerateInterval) {
132        inverval = inverval / 1000000;
133        mAverageFPS = (mAverageFPSFrameCount * 1000) / inverval;
134        mAverageFPSFrameCount = 0;
135        mAverageFPSStartTime = mTimeFrame;
136    }
137}
138
139void Context::timerSet(Timers tm) {
140    uint64_t last = mTimeLast;
141    mTimeLast = getTime();
142    mTimers[mTimerActive] += mTimeLast - last;
143    mTimerActive = tm;
144}
145
146void Context::timerPrint() {
147    double total = 0;
148    for (int ct = 0; ct < _RS_TIMER_TOTAL; ct++) {
149        total += mTimers[ct];
150    }
151    uint64_t frame = mTimeFrame - mTimeLastFrame;
152    mTimeMSLastFrame = frame / 1000000;
153    mTimeMSLastScript = mTimers[RS_TIMER_SCRIPT] / 1000000;
154    mTimeMSLastSwap = mTimers[RS_TIMER_CLEAR_SWAP] / 1000000;
155
156
157    if (props.mLogTimes) {
158        ALOGV("RS: Frame (%i),   Script %2.1f%% (%i),  Swap %2.1f%% (%i),  Idle %2.1f%% (%lli),  Internal %2.1f%% (%lli), Avg fps: %u",
159             mTimeMSLastFrame,
160             100.0 * mTimers[RS_TIMER_SCRIPT] / total, mTimeMSLastScript,
161             100.0 * mTimers[RS_TIMER_CLEAR_SWAP] / total, mTimeMSLastSwap,
162             100.0 * mTimers[RS_TIMER_IDLE] / total, mTimers[RS_TIMER_IDLE] / 1000000,
163             100.0 * mTimers[RS_TIMER_INTERNAL] / total, mTimers[RS_TIMER_INTERNAL] / 1000000,
164             mAverageFPS);
165    }
166}
167
168bool Context::setupCheck() {
169
170    mFragmentStore->setup(this, &mStateFragmentStore);
171    mFragment->setup(this, &mStateFragment);
172    mRaster->setup(this, &mStateRaster);
173    mVertex->setup(this, &mStateVertex);
174    mFBOCache.setup(this);
175    return true;
176}
177
178void Context::setupProgramStore() {
179    mFragmentStore->setup(this, &mStateFragmentStore);
180}
181
182static uint32_t getProp(const char *str) {
183    char buf[PROPERTY_VALUE_MAX];
184    property_get(str, buf, "0");
185    return atoi(buf);
186}
187
188void Context::displayDebugStats() {
189    char buffer[128];
190    sprintf(buffer, "Avg fps %u, Frame %i ms, Script %i ms", mAverageFPS, mTimeMSLastFrame, mTimeMSLastScript);
191    float oldR, oldG, oldB, oldA;
192    mStateFont.getFontColor(&oldR, &oldG, &oldB, &oldA);
193    uint32_t bufferLen = strlen(buffer);
194
195    ObjectBaseRef<Font> lastFont(getFont());
196    setFont(NULL);
197    float shadowCol = 0.1f;
198    mStateFont.setFontColor(shadowCol, shadowCol, shadowCol, 1.0f);
199    mStateFont.renderText(buffer, bufferLen, 5, getHeight() - 6);
200
201    mStateFont.setFontColor(1.0f, 0.7f, 0.0f, 1.0f);
202    mStateFont.renderText(buffer, bufferLen, 4, getHeight() - 7);
203
204    setFont(lastFont.get());
205    mStateFont.setFontColor(oldR, oldG, oldB, oldA);
206}
207
208bool Context::loadRuntime(const char* filename, Context* rsc) {
209
210    // TODO: store the driverSO somewhere so we can dlclose later
211    void *driverSO = NULL;
212
213    driverSO = dlopen(filename, RTLD_LAZY);
214    if (driverSO == NULL) {
215        ALOGE("Failed loading RS driver: %s", dlerror());
216        return false;
217    }
218
219    // Need to call dlerror() to clear buffer before using it for dlsym().
220    (void) dlerror();
221    typedef bool (*HalSig)(Context*, uint32_t, uint32_t);
222    HalSig halInit = (HalSig) dlsym(driverSO, "rsdHalInit");
223
224    // If we can't find the C variant, we go looking for the C++ version.
225    if (halInit == NULL) {
226        ALOGW("Falling back to find C++ rsdHalInit: %s", dlerror());
227        halInit = (HalSig) dlsym(driverSO,
228                "_Z10rsdHalInitPN7android12renderscript7ContextEjj");
229    }
230
231    if (halInit == NULL) {
232        dlclose(driverSO);
233        ALOGE("Failed to find rsdHalInit: %s", dlerror());
234        return false;
235    }
236
237    if (!(*halInit)(rsc, 0, 0)) {
238        dlclose(driverSO);
239        ALOGE("Hal init failed");
240        return false;
241    }
242
243    //validate HAL struct
244
245
246    return true;
247}
248
249void * Context::threadProc(void *vrsc) {
250    Context *rsc = static_cast<Context *>(vrsc);
251#ifndef ANDROID_RS_SERIALIZE
252    rsc->mNativeThreadId = gettid();
253    setpriority(PRIO_PROCESS, rsc->mNativeThreadId, ANDROID_PRIORITY_DISPLAY);
254    rsc->mThreadPriority = ANDROID_PRIORITY_DISPLAY;
255#endif //ANDROID_RS_SERIALIZE
256    rsc->props.mLogTimes = getProp("debug.rs.profile") != 0;
257    rsc->props.mLogScripts = getProp("debug.rs.script") != 0;
258    rsc->props.mLogObjects = getProp("debug.rs.object") != 0;
259    rsc->props.mLogShaders = getProp("debug.rs.shader") != 0;
260    rsc->props.mLogShadersAttr = getProp("debug.rs.shader.attributes") != 0;
261    rsc->props.mLogShadersUniforms = getProp("debug.rs.shader.uniforms") != 0;
262    rsc->props.mLogVisual = getProp("debug.rs.visual") != 0;
263    rsc->props.mDebugMaxThreads = getProp("debug.rs.max-threads");
264
265    bool loadDefault = true;
266
267    // Provide a mechanism for dropping in a different RS driver.
268#ifdef OVERRIDE_RS_DRIVER
269#define XSTR(S) #S
270#define STR(S) XSTR(S)
271#define OVERRIDE_RS_DRIVER_STRING STR(OVERRIDE_RS_DRIVER)
272
273    if (getProp("debug.rs.default-CPU-driver") != 0) {
274        ALOGE("Skipping override driver and loading default CPU driver");
275    } else if (rsc->mForceCpu) {
276        ALOGV("Application requested CPU execution");
277    } else {
278        if (loadRuntime(OVERRIDE_RS_DRIVER_STRING, rsc)) {
279            ALOGE("Successfully loaded runtime: %s", OVERRIDE_RS_DRIVER_STRING);
280            loadDefault = false;
281        } else {
282            ALOGE("Failed to load runtime %s, loading default", OVERRIDE_RS_DRIVER_STRING);
283        }
284    }
285
286#undef XSTR
287#undef STR
288#endif  // OVERRIDE_RS_DRIVER
289
290    if (loadDefault) {
291        if (!loadRuntime("libRSDriver.so", rsc)) {
292            ALOGE("Failed to load default runtime!");
293            rsc->setError(RS_ERROR_FATAL_DRIVER, "Failed loading RS driver");
294            return NULL;
295        }
296    }
297
298    rsc->mHal.funcs.setPriority(rsc, rsc->mThreadPriority);
299
300    if (rsc->mIsGraphicsContext) {
301        if (!rsc->initGLThread()) {
302            rsc->setError(RS_ERROR_OUT_OF_MEMORY, "Failed initializing GL");
303            return NULL;
304        }
305
306        rsc->mStateRaster.init(rsc);
307        rsc->setProgramRaster(NULL);
308        rsc->mStateVertex.init(rsc);
309        rsc->setProgramVertex(NULL);
310        rsc->mStateFragment.init(rsc);
311        rsc->setProgramFragment(NULL);
312        rsc->mStateFragmentStore.init(rsc);
313        rsc->setProgramStore(NULL);
314        rsc->mStateFont.init(rsc);
315        rsc->setFont(NULL);
316        rsc->mStateSampler.init(rsc);
317        rsc->mFBOCache.init(rsc);
318    }
319
320    rsc->mRunning = true;
321    if (!rsc->mIsGraphicsContext) {
322        while (!rsc->mExit) {
323            rsc->mIO.playCoreCommands(rsc, -1);
324        }
325    } else {
326#ifndef ANDROID_RS_SERIALIZE
327        DisplayEventReceiver displayEvent;
328        DisplayEventReceiver::Event eventBuffer[1];
329#endif
330        int vsyncRate = 0;
331        int targetRate = 0;
332
333        bool drawOnce = false;
334        while (!rsc->mExit) {
335            rsc->timerSet(RS_TIMER_IDLE);
336
337#ifndef ANDROID_RS_SERIALIZE
338            if (!rsc->mRootScript.get() || !rsc->mHasSurface || rsc->mPaused) {
339                targetRate = 0;
340            }
341
342            if (vsyncRate != targetRate) {
343                displayEvent.setVsyncRate(targetRate);
344                vsyncRate = targetRate;
345            }
346            if (targetRate) {
347                drawOnce |= rsc->mIO.playCoreCommands(rsc, displayEvent.getFd());
348                while (displayEvent.getEvents(eventBuffer, 1) != 0) {
349                    //ALOGE("vs2 time past %lld", (rsc->getTime() - eventBuffer[0].header.timestamp) / 1000000);
350                }
351            } else
352#endif
353            {
354                drawOnce |= rsc->mIO.playCoreCommands(rsc, -1);
355            }
356
357            if ((rsc->mRootScript.get() != NULL) && rsc->mHasSurface &&
358                (targetRate || drawOnce) && !rsc->mPaused) {
359
360                drawOnce = false;
361                targetRate = ((rsc->runRootScript() + 15) / 16);
362
363                if (rsc->props.mLogVisual) {
364                    rsc->displayDebugStats();
365                }
366
367                rsc->timerSet(RS_TIMER_CLEAR_SWAP);
368                rsc->mHal.funcs.swap(rsc);
369                rsc->timerFrame();
370                rsc->timerSet(RS_TIMER_INTERNAL);
371                rsc->timerPrint();
372                rsc->timerReset();
373            }
374        }
375    }
376
377    ALOGV("%p RS Thread exiting", rsc);
378
379    if (rsc->mIsGraphicsContext) {
380        pthread_mutex_lock(&gInitMutex);
381        rsc->deinitEGL();
382        pthread_mutex_unlock(&gInitMutex);
383    }
384
385    ALOGV("%p RS Thread exited", rsc);
386    return NULL;
387}
388
389void Context::destroyWorkerThreadResources() {
390    //ALOGV("destroyWorkerThreadResources 1");
391    ObjectBase::zeroAllUserRef(this);
392    if (mIsGraphicsContext) {
393         mRaster.clear();
394         mFragment.clear();
395         mVertex.clear();
396         mFragmentStore.clear();
397         mFont.clear();
398         mRootScript.clear();
399         mStateRaster.deinit(this);
400         mStateVertex.deinit(this);
401         mStateFragment.deinit(this);
402         mStateFragmentStore.deinit(this);
403         mStateFont.deinit(this);
404         mStateSampler.deinit(this);
405         mFBOCache.deinit(this);
406    }
407    ObjectBase::freeAllChildren(this);
408    mExit = true;
409    //ALOGV("destroyWorkerThreadResources 2");
410}
411
412void Context::printWatchdogInfo(void *ctx) {
413    Context *rsc = (Context *)ctx;
414    if (rsc->watchdog.command && rsc->watchdog.file) {
415        ALOGE("RS watchdog timeout: %i  %s  line %i %s", rsc->watchdog.inRoot,
416             rsc->watchdog.command, rsc->watchdog.line, rsc->watchdog.file);
417    } else {
418        ALOGE("RS watchdog timeout: %i", rsc->watchdog.inRoot);
419    }
420}
421
422
423void Context::setPriority(int32_t p) {
424    // Note: If we put this in the proper "background" policy
425    // the wallpapers can become completly unresponsive at times.
426    // This is probably not what we want for something the user is actively
427    // looking at.
428    mThreadPriority = p;
429    setpriority(PRIO_PROCESS, mNativeThreadId, p);
430    mHal.funcs.setPriority(this, mThreadPriority);
431}
432
433Context::Context() {
434    mDev = NULL;
435    mRunning = false;
436    mExit = false;
437    mPaused = false;
438    mObjHead = NULL;
439    mError = RS_ERROR_NONE;
440    mTargetSdkVersion = 14;
441    mDPI = 96;
442    mIsContextLite = false;
443    memset(&watchdog, 0, sizeof(watchdog));
444    mForceCpu = false;
445}
446
447Context * Context::createContext(Device *dev, const RsSurfaceConfig *sc) {
448    return createContext(dev, sc, false);
449}
450
451Context * Context::createContext(Device *dev, const RsSurfaceConfig *sc,
452                                 bool forceCpu) {
453    Context * rsc = new Context();
454
455    rsc->mForceCpu = forceCpu;
456
457    if (!rsc->initContext(dev, sc)) {
458        delete rsc;
459        return NULL;
460    }
461    return rsc;
462}
463
464Context * Context::createContextLite() {
465    Context * rsc = new Context();
466    rsc->mIsContextLite = true;
467    return rsc;
468}
469
470bool Context::initContext(Device *dev, const RsSurfaceConfig *sc) {
471    pthread_mutex_lock(&gInitMutex);
472
473    mIO.init();
474    mIO.setTimeoutCallback(printWatchdogInfo, this, 2e9);
475
476    dev->addContext(this);
477    mDev = dev;
478    if (sc) {
479        mUserSurfaceConfig = *sc;
480    } else {
481        memset(&mUserSurfaceConfig, 0, sizeof(mUserSurfaceConfig));
482    }
483
484    mIsGraphicsContext = sc != NULL;
485
486    int status;
487    pthread_attr_t threadAttr;
488
489    pthread_mutex_unlock(&gInitMutex);
490
491    // Global init done at this point.
492
493    status = pthread_attr_init(&threadAttr);
494    if (status) {
495        ALOGE("Failed to init thread attribute.");
496        return false;
497    }
498
499    mHasSurface = false;
500
501    timerInit();
502    timerSet(RS_TIMER_INTERNAL);
503
504    status = pthread_create(&mThreadId, &threadAttr, threadProc, this);
505    if (status) {
506        ALOGE("Failed to start rs context thread.");
507        return false;
508    }
509    while (!mRunning && (mError == RS_ERROR_NONE)) {
510        usleep(100);
511    }
512
513    if (mError != RS_ERROR_NONE) {
514        ALOGE("Errors during thread init");
515        return false;
516    }
517
518    pthread_attr_destroy(&threadAttr);
519    return true;
520}
521
522Context::~Context() {
523    ALOGV("%p Context::~Context", this);
524
525    if (!mIsContextLite) {
526        mPaused = false;
527        void *res;
528
529        mIO.shutdown();
530        int status = pthread_join(mThreadId, &res);
531        rsAssert(mExit);
532
533        if (mHal.funcs.shutdownDriver) {
534            mHal.funcs.shutdownDriver(this);
535        }
536
537        // Global structure cleanup.
538        pthread_mutex_lock(&gInitMutex);
539        if (mDev) {
540            mDev->removeContext(this);
541            mDev = NULL;
542        }
543        pthread_mutex_unlock(&gInitMutex);
544    }
545    ALOGV("%p Context::~Context done", this);
546}
547
548void Context::setSurface(uint32_t w, uint32_t h, RsNativeWindow sur) {
549    rsAssert(mIsGraphicsContext);
550    mHal.funcs.setSurface(this, w, h, sur);
551
552    mHasSurface = sur != NULL;
553    mWidth = w;
554    mHeight = h;
555
556    if (mWidth && mHeight) {
557        mStateVertex.updateSize(this);
558        mFBOCache.updateSize();
559    }
560}
561
562uint32_t Context::getCurrentSurfaceWidth() const {
563    for (uint32_t i = 0; i < mFBOCache.mHal.state.colorTargetsCount; i ++) {
564        if (mFBOCache.mHal.state.colorTargets[i] != NULL) {
565            return mFBOCache.mHal.state.colorTargets[i]->getType()->getDimX();
566        }
567    }
568    if (mFBOCache.mHal.state.depthTarget != NULL) {
569        return mFBOCache.mHal.state.depthTarget->getType()->getDimX();
570    }
571    return mWidth;
572}
573
574uint32_t Context::getCurrentSurfaceHeight() const {
575    for (uint32_t i = 0; i < mFBOCache.mHal.state.colorTargetsCount; i ++) {
576        if (mFBOCache.mHal.state.colorTargets[i] != NULL) {
577            return mFBOCache.mHal.state.colorTargets[i]->getType()->getDimY();
578        }
579    }
580    if (mFBOCache.mHal.state.depthTarget != NULL) {
581        return mFBOCache.mHal.state.depthTarget->getType()->getDimY();
582    }
583    return mHeight;
584}
585
586void Context::pause() {
587    rsAssert(mIsGraphicsContext);
588    mPaused = true;
589}
590
591void Context::resume() {
592    rsAssert(mIsGraphicsContext);
593    mPaused = false;
594}
595
596void Context::setRootScript(Script *s) {
597    rsAssert(mIsGraphicsContext);
598    mRootScript.set(s);
599}
600
601void Context::setProgramStore(ProgramStore *pfs) {
602    rsAssert(mIsGraphicsContext);
603    if (pfs == NULL) {
604        mFragmentStore.set(mStateFragmentStore.mDefault);
605    } else {
606        mFragmentStore.set(pfs);
607    }
608}
609
610void Context::setProgramFragment(ProgramFragment *pf) {
611    rsAssert(mIsGraphicsContext);
612    if (pf == NULL) {
613        mFragment.set(mStateFragment.mDefault);
614    } else {
615        mFragment.set(pf);
616    }
617}
618
619void Context::setProgramRaster(ProgramRaster *pr) {
620    rsAssert(mIsGraphicsContext);
621    if (pr == NULL) {
622        mRaster.set(mStateRaster.mDefault);
623    } else {
624        mRaster.set(pr);
625    }
626}
627
628void Context::setProgramVertex(ProgramVertex *pv) {
629    rsAssert(mIsGraphicsContext);
630    if (pv == NULL) {
631        mVertex.set(mStateVertex.mDefault);
632    } else {
633        mVertex.set(pv);
634    }
635}
636
637void Context::setFont(Font *f) {
638    rsAssert(mIsGraphicsContext);
639    if (f == NULL) {
640        mFont.set(mStateFont.mDefault);
641    } else {
642        mFont.set(f);
643    }
644}
645
646void Context::assignName(ObjectBase *obj, const char *name, uint32_t len) {
647    rsAssert(!obj->getName());
648    obj->setName(name, len);
649    mNames.add(obj);
650}
651
652void Context::removeName(ObjectBase *obj) {
653    for (size_t ct=0; ct < mNames.size(); ct++) {
654        if (obj == mNames[ct]) {
655            mNames.removeAt(ct);
656            return;
657        }
658    }
659}
660
661RsMessageToClientType Context::peekMessageToClient(size_t *receiveLen, uint32_t *subID) {
662    return (RsMessageToClientType)mIO.getClientHeader(receiveLen, subID);
663}
664
665RsMessageToClientType Context::getMessageToClient(void *data, size_t *receiveLen, uint32_t *subID, size_t bufferLen) {
666    return (RsMessageToClientType)mIO.getClientPayload(data, receiveLen, subID, bufferLen);
667}
668
669bool Context::sendMessageToClient(const void *data, RsMessageToClientType cmdID,
670                                  uint32_t subID, size_t len, bool waitForSpace) const {
671
672    return mIO.sendToClient(cmdID, subID, data, len, waitForSpace);
673}
674
675void Context::initToClient() {
676    while (!mRunning) {
677        usleep(100);
678    }
679}
680
681void Context::deinitToClient() {
682    mIO.clientShutdown();
683}
684
685void Context::setError(RsError e, const char *msg) const {
686    mError = e;
687    sendMessageToClient(msg, RS_MESSAGE_TO_CLIENT_ERROR, e, strlen(msg) + 1, true);
688}
689
690
691void Context::dumpDebug() const {
692    ALOGE("RS Context debug %p", this);
693    ALOGE("RS Context debug");
694
695    ALOGE(" RS width %i, height %i", mWidth, mHeight);
696    ALOGE(" RS running %i, exit %i, paused %i", mRunning, mExit, mPaused);
697    ALOGE(" RS pThreadID %li, nativeThreadID %i", (long int)mThreadId, mNativeThreadId);
698}
699
700///////////////////////////////////////////////////////////////////////////////////////////
701//
702
703namespace android {
704namespace renderscript {
705
706void rsi_ContextFinish(Context *rsc) {
707}
708
709void rsi_ContextBindRootScript(Context *rsc, RsScript vs) {
710    Script *s = static_cast<Script *>(vs);
711    rsc->setRootScript(s);
712}
713
714void rsi_ContextBindSampler(Context *rsc, uint32_t slot, RsSampler vs) {
715    Sampler *s = static_cast<Sampler *>(vs);
716
717    if (slot > RS_MAX_SAMPLER_SLOT) {
718        ALOGE("Invalid sampler slot");
719        return;
720    }
721
722    s->bindToContext(&rsc->mStateSampler, slot);
723}
724
725void rsi_ContextBindProgramStore(Context *rsc, RsProgramStore vpfs) {
726    ProgramStore *pfs = static_cast<ProgramStore *>(vpfs);
727    rsc->setProgramStore(pfs);
728}
729
730void rsi_ContextBindProgramFragment(Context *rsc, RsProgramFragment vpf) {
731    ProgramFragment *pf = static_cast<ProgramFragment *>(vpf);
732    rsc->setProgramFragment(pf);
733}
734
735void rsi_ContextBindProgramRaster(Context *rsc, RsProgramRaster vpr) {
736    ProgramRaster *pr = static_cast<ProgramRaster *>(vpr);
737    rsc->setProgramRaster(pr);
738}
739
740void rsi_ContextBindProgramVertex(Context *rsc, RsProgramVertex vpv) {
741    ProgramVertex *pv = static_cast<ProgramVertex *>(vpv);
742    rsc->setProgramVertex(pv);
743}
744
745void rsi_ContextBindFont(Context *rsc, RsFont vfont) {
746    Font *font = static_cast<Font *>(vfont);
747    rsc->setFont(font);
748}
749
750void rsi_AssignName(Context *rsc, RsObjectBase obj, const char *name, size_t name_length) {
751    ObjectBase *ob = static_cast<ObjectBase *>(obj);
752    rsc->assignName(ob, name, name_length);
753}
754
755void rsi_ObjDestroy(Context *rsc, void *optr) {
756    ObjectBase *ob = static_cast<ObjectBase *>(optr);
757    rsc->removeName(ob);
758    ob->decUserRef();
759}
760
761void rsi_ContextPause(Context *rsc) {
762    rsc->pause();
763}
764
765void rsi_ContextResume(Context *rsc) {
766    rsc->resume();
767}
768
769void rsi_ContextSetSurface(Context *rsc, uint32_t w, uint32_t h, RsNativeWindow sur) {
770    rsc->setSurface(w, h, sur);
771}
772
773void rsi_ContextSetPriority(Context *rsc, int32_t p) {
774    rsc->setPriority(p);
775}
776
777void rsi_ContextDump(Context *rsc, int32_t bits) {
778    ObjectBase::dumpAll(rsc);
779}
780
781void rsi_ContextDestroyWorker(Context *rsc) {
782    rsc->destroyWorkerThreadResources();
783}
784
785void rsi_ContextDestroy(Context *rsc) {
786    ALOGV("%p rsContextDestroy", rsc);
787    rsContextDestroyWorker(rsc);
788    delete rsc;
789    ALOGV("%p rsContextDestroy done", rsc);
790}
791
792
793RsMessageToClientType rsi_ContextPeekMessage(Context *rsc,
794                                           size_t * receiveLen, size_t receiveLen_length,
795                                           uint32_t * subID, size_t subID_length) {
796    return rsc->peekMessageToClient(receiveLen, subID);
797}
798
799RsMessageToClientType rsi_ContextGetMessage(Context *rsc, void * data, size_t data_length,
800                                          size_t * receiveLen, size_t receiveLen_length,
801                                          uint32_t * subID, size_t subID_length) {
802    rsAssert(subID_length == sizeof(uint32_t));
803    rsAssert(receiveLen_length == sizeof(size_t));
804    return rsc->getMessageToClient(data, receiveLen, subID, data_length);
805}
806
807void rsi_ContextInitToClient(Context *rsc) {
808    rsc->initToClient();
809}
810
811void rsi_ContextDeinitToClient(Context *rsc) {
812    rsc->deinitToClient();
813}
814
815}
816}
817
818RsContext rsContextCreate(RsDevice vdev, uint32_t version,
819                          uint32_t sdkVersion) {
820    return rsContextCreate(vdev, version, sdkVersion, false);
821}
822
823RsContext rsContextCreate(RsDevice vdev, uint32_t version,
824                          uint32_t sdkVersion, bool forceCpu) {
825    ALOGV("rsContextCreate dev=%p", vdev);
826    Device * dev = static_cast<Device *>(vdev);
827    Context *rsc = Context::createContext(dev, NULL, forceCpu);
828    if (rsc) {
829        rsc->setTargetSdkVersion(sdkVersion);
830    }
831    return rsc;
832}
833
834RsContext rsContextCreateGL(RsDevice vdev, uint32_t version,
835                            uint32_t sdkVersion, RsSurfaceConfig sc,
836                            uint32_t dpi) {
837    ALOGV("rsContextCreateGL dev=%p", vdev);
838    Device * dev = static_cast<Device *>(vdev);
839    Context *rsc = Context::createContext(dev, &sc);
840    if (rsc) {
841        rsc->setTargetSdkVersion(sdkVersion);
842        rsc->setDPI(dpi);
843    }
844    ALOGV("%p rsContextCreateGL ret", rsc);
845    return rsc;
846}
847
848// Only to be called at a3d load time, before object is visible to user
849// not thread safe
850void rsaGetName(RsContext con, void * obj, const char **name) {
851    ObjectBase *ob = static_cast<ObjectBase *>(obj);
852    (*name) = ob->getName();
853}
854