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