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