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