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