/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "rsDevice.h" #include "rsContext.h" #include "rsThreadIO.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace android; using namespace android::renderscript; pthread_key_t Context::gThreadTLSKey = 0; uint32_t Context::gThreadTLSKeyCount = 0; pthread_mutex_t Context::gInitMutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t Context::gLibMutex = PTHREAD_MUTEX_INITIALIZER; bool Context::initGLThread() { pthread_mutex_lock(&gInitMutex); LOGV("initGLThread start %p", this); if (!mHal.funcs.initGraphics(this)) { pthread_mutex_unlock(&gInitMutex); LOGE("%p, initGraphics failed", this); return false; } const char * ext = (const char *)glGetString(GL_EXTENSIONS); glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &mGL.mMaxVertexAttribs); glGetIntegerv(GL_MAX_VERTEX_UNIFORM_VECTORS, &mGL.mMaxVertexUniformVectors); glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &mGL.mMaxVertexTextureUnits); glGetIntegerv(GL_MAX_VARYING_VECTORS, &mGL.mMaxVaryingVectors); glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &mGL.mMaxTextureImageUnits); glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &mGL.mMaxFragmentTextureImageUnits); glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_VECTORS, &mGL.mMaxFragmentUniformVectors); mGL.OES_texture_npot = NULL != strstr(ext, "GL_OES_texture_npot"); mGL.GL_IMG_texture_npot = NULL != strstr(ext, "GL_IMG_texture_npot"); mGL.GL_NV_texture_npot_2D_mipmap = NULL != strstr(ext, "GL_NV_texture_npot_2D_mipmap"); mGL.EXT_texture_max_aniso = 1.0f; bool hasAniso = NULL != strstr(ext, "GL_EXT_texture_filter_anisotropic"); if (hasAniso) { glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &mGL.EXT_texture_max_aniso); } LOGV("initGLThread end %p", this); pthread_mutex_unlock(&gInitMutex); return true; } void Context::deinitEGL() { LOGV("%p, deinitEGL", this); mHal.funcs.shutdownGraphics(this); } Context::PushState::PushState(Context *con) { mRsc = con; if (con->mIsGraphicsContext) { mFragment.set(con->getProgramFragment()); mVertex.set(con->getProgramVertex()); mStore.set(con->getProgramStore()); mRaster.set(con->getProgramRaster()); mFont.set(con->getFont()); } } Context::PushState::~PushState() { if (mRsc->mIsGraphicsContext) { mRsc->setProgramFragment(mFragment.get()); mRsc->setProgramVertex(mVertex.get()); mRsc->setProgramStore(mStore.get()); mRsc->setProgramRaster(mRaster.get()); mRsc->setFont(mFont.get()); } } uint32_t Context::runScript(Script *s) { PushState(this); uint32_t ret = s->run(this); return ret; } void Context::checkError(const char *msg, bool isFatal) const { GLenum err = glGetError(); if (err != GL_NO_ERROR) { char buf[1024]; snprintf(buf, sizeof(buf), "GL Error = 0x%08x, from: %s", err, msg); if (isFatal) { setError(RS_ERROR_FATAL_DRIVER, buf); } else { switch (err) { case GL_OUT_OF_MEMORY: setError(RS_ERROR_OUT_OF_MEMORY, buf); break; default: setError(RS_ERROR_DRIVER, buf); break; } } LOGE("%p, %s", this, buf); } } uint32_t Context::runRootScript() { glViewport(0, 0, mWidth, mHeight); timerSet(RS_TIMER_SCRIPT); mStateFragmentStore.mLast.clear(); uint32_t ret = runScript(mRootScript.get()); checkError("runRootScript"); return ret; } uint64_t Context::getTime() const { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_nsec + ((uint64_t)t.tv_sec * 1000 * 1000 * 1000); } void Context::timerReset() { for (int ct=0; ct < _RS_TIMER_TOTAL; ct++) { mTimers[ct] = 0; } } void Context::timerInit() { mTimeLast = getTime(); mTimeFrame = mTimeLast; mTimeLastFrame = mTimeLast; mTimerActive = RS_TIMER_INTERNAL; mAverageFPSFrameCount = 0; mAverageFPSStartTime = mTimeLast; mAverageFPS = 0; timerReset(); } void Context::timerFrame() { mTimeLastFrame = mTimeFrame; mTimeFrame = getTime(); // Update average fps const uint64_t averageFramerateInterval = 1000 * 1000000; mAverageFPSFrameCount ++; uint64_t inverval = mTimeFrame - mAverageFPSStartTime; if (inverval >= averageFramerateInterval) { inverval = inverval / 1000000; mAverageFPS = (mAverageFPSFrameCount * 1000) / inverval; mAverageFPSFrameCount = 0; mAverageFPSStartTime = mTimeFrame; } } void Context::timerSet(Timers tm) { uint64_t last = mTimeLast; mTimeLast = getTime(); mTimers[mTimerActive] += mTimeLast - last; mTimerActive = tm; } void Context::timerPrint() { double total = 0; for (int ct = 0; ct < _RS_TIMER_TOTAL; ct++) { total += mTimers[ct]; } uint64_t frame = mTimeFrame - mTimeLastFrame; mTimeMSLastFrame = frame / 1000000; mTimeMSLastScript = mTimers[RS_TIMER_SCRIPT] / 1000000; mTimeMSLastSwap = mTimers[RS_TIMER_CLEAR_SWAP] / 1000000; if (props.mLogTimes) { LOGV("RS: Frame (%i), Script %2.1f%% (%i), Swap %2.1f%% (%i), Idle %2.1f%% (%lli), Internal %2.1f%% (%lli), Avg fps: %u", mTimeMSLastFrame, 100.0 * mTimers[RS_TIMER_SCRIPT] / total, mTimeMSLastScript, 100.0 * mTimers[RS_TIMER_CLEAR_SWAP] / total, mTimeMSLastSwap, 100.0 * mTimers[RS_TIMER_IDLE] / total, mTimers[RS_TIMER_IDLE] / 1000000, 100.0 * mTimers[RS_TIMER_INTERNAL] / total, mTimers[RS_TIMER_INTERNAL] / 1000000, mAverageFPS); } } bool Context::setupCheck() { if (!mShaderCache.lookup(this, mVertex.get(), mFragment.get())) { LOGE("Context::setupCheck() 1 fail"); return false; } mFragmentStore->setup(this, &mStateFragmentStore); mFragment->setupGL2(this, &mStateFragment, &mShaderCache); mRaster->setup(this, &mStateRaster); mVertex->setupGL2(this, &mStateVertex, &mShaderCache); mFBOCache.setupGL2(this); return true; } void Context::setupProgramStore() { mFragmentStore->setup(this, &mStateFragmentStore); } static bool getProp(const char *str) { char buf[PROPERTY_VALUE_MAX]; property_get(str, buf, "0"); return 0 != strcmp(buf, "0"); } void Context::displayDebugStats() { char buffer[128]; sprintf(buffer, "Avg fps %u, Frame %i ms, Script %i ms", mAverageFPS, mTimeMSLastFrame, mTimeMSLastScript); float oldR, oldG, oldB, oldA; mStateFont.getFontColor(&oldR, &oldG, &oldB, &oldA); uint32_t bufferLen = strlen(buffer); ObjectBaseRef lastFont(getFont()); setFont(NULL); float shadowCol = 0.1f; mStateFont.setFontColor(shadowCol, shadowCol, shadowCol, 1.0f); mStateFont.renderText(buffer, bufferLen, 5, getHeight() - 6); mStateFont.setFontColor(1.0f, 0.7f, 0.0f, 1.0f); mStateFont.renderText(buffer, bufferLen, 4, getHeight() - 7); setFont(lastFont.get()); mStateFont.setFontColor(oldR, oldG, oldB, oldA); } void * Context::threadProc(void *vrsc) { Context *rsc = static_cast(vrsc); rsc->mNativeThreadId = gettid(); setpriority(PRIO_PROCESS, rsc->mNativeThreadId, ANDROID_PRIORITY_DISPLAY); rsc->mThreadPriority = ANDROID_PRIORITY_DISPLAY; rsc->props.mLogTimes = getProp("debug.rs.profile"); rsc->props.mLogScripts = getProp("debug.rs.script"); rsc->props.mLogObjects = getProp("debug.rs.object"); rsc->props.mLogShaders = getProp("debug.rs.shader"); rsc->props.mLogShadersAttr = getProp("debug.rs.shader.attributes"); rsc->props.mLogShadersUniforms = getProp("debug.rs.shader.uniforms"); rsc->props.mLogVisual = getProp("debug.rs.visual"); rsc->mTlsStruct = new ScriptTLSStruct; if (!rsc->mTlsStruct) { LOGE("Error allocating tls storage"); rsc->setError(RS_ERROR_OUT_OF_MEMORY, "Failed allocation for TLS"); return NULL; } rsc->mTlsStruct->mContext = rsc; rsc->mTlsStruct->mScript = NULL; int status = pthread_setspecific(rsc->gThreadTLSKey, rsc->mTlsStruct); if (status) { LOGE("pthread_setspecific %i", status); } if (!rsc->initGLThread()) { rsc->setError(RS_ERROR_OUT_OF_MEMORY, "Failed initializing GL"); return NULL; } if (rsc->mIsGraphicsContext) { rsc->mStateRaster.init(rsc); rsc->setProgramRaster(NULL); rsc->mStateVertex.init(rsc); rsc->setProgramVertex(NULL); rsc->mStateFragment.init(rsc); rsc->setProgramFragment(NULL); rsc->mStateFragmentStore.init(rsc); rsc->setProgramStore(NULL); rsc->mStateFont.init(rsc); rsc->setFont(NULL); rsc->mStateVertexArray.init(rsc); } rsc->mRunning = true; bool mDraw = true; while (!rsc->mExit) { mDraw |= rsc->mIO.playCoreCommands(rsc, !mDraw); mDraw &= (rsc->mRootScript.get() != NULL); mDraw &= (rsc->mWndSurface != NULL); uint32_t targetTime = 0; if (mDraw && rsc->mIsGraphicsContext) { targetTime = rsc->runRootScript(); if (rsc->props.mLogVisual) { rsc->displayDebugStats(); } mDraw = targetTime && !rsc->mPaused; rsc->timerSet(RS_TIMER_CLEAR_SWAP); rsc->mHal.funcs.swap(rsc); rsc->timerFrame(); rsc->timerSet(RS_TIMER_INTERNAL); rsc->timerPrint(); rsc->timerReset(); } if (targetTime > 1) { int32_t t = (targetTime - (int32_t)(rsc->mTimeMSLastScript + rsc->mTimeMSLastSwap)) * 1000; if (t > 0) { usleep(t); } } } LOGV("%p, RS Thread exiting", rsc); if (rsc->mIsGraphicsContext) { pthread_mutex_lock(&gInitMutex); rsc->deinitEGL(); pthread_mutex_unlock(&gInitMutex); } delete rsc->mTlsStruct; LOGV("%p, RS Thread exited", rsc); return NULL; } void Context::destroyWorkerThreadResources() { //LOGV("destroyWorkerThreadResources 1"); ObjectBase::zeroAllUserRef(this); if (mIsGraphicsContext) { mRaster.clear(); mFragment.clear(); mVertex.clear(); mFragmentStore.clear(); mFont.clear(); mRootScript.clear(); mStateRaster.deinit(this); mStateVertex.deinit(this); mStateFragment.deinit(this); mStateFragmentStore.deinit(this); mStateFont.deinit(this); mShaderCache.cleanupAll(); } //LOGV("destroyWorkerThreadResources 2"); mExit = true; } void Context::setPriority(int32_t p) { // Note: If we put this in the proper "background" policy // the wallpapers can become completly unresponsive at times. // This is probably not what we want for something the user is actively // looking at. mThreadPriority = p; #if 0 SchedPolicy pol = SP_FOREGROUND; if (p > 0) { pol = SP_BACKGROUND; } if (!set_sched_policy(mNativeThreadId, pol)) { // success; reset the priority as well } #else setpriority(PRIO_PROCESS, mNativeThreadId, p); #endif } Context::Context() { mDev = NULL; mRunning = false; mExit = false; mPaused = false; mObjHead = NULL; mError = RS_ERROR_NONE; mDPI = 96; } Context * Context::createContext(Device *dev, const RsSurfaceConfig *sc) { Context * rsc = new Context(); if (!rsc->initContext(dev, sc)) { delete rsc; return NULL; } return rsc; } bool Context::initContext(Device *dev, const RsSurfaceConfig *sc) { pthread_mutex_lock(&gInitMutex); dev->addContext(this); mDev = dev; if (sc) { mUserSurfaceConfig = *sc; } else { memset(&mUserSurfaceConfig, 0, sizeof(mUserSurfaceConfig)); } memset(&mGL, 0, sizeof(mGL)); mIsGraphicsContext = sc != NULL; int status; pthread_attr_t threadAttr; if (!gThreadTLSKeyCount) { status = pthread_key_create(&gThreadTLSKey, NULL); if (status) { LOGE("Failed to init thread tls key."); pthread_mutex_unlock(&gInitMutex); return false; } } gThreadTLSKeyCount++; pthread_mutex_unlock(&gInitMutex); // Global init done at this point. status = pthread_attr_init(&threadAttr); if (status) { LOGE("Failed to init thread attribute."); return false; } mWndSurface = NULL; timerInit(); timerSet(RS_TIMER_INTERNAL); if (!rsdHalInit(this, 0, 0)) { LOGE("Hal init failed"); return false; } mHal.funcs.setPriority(this, mThreadPriority); status = pthread_create(&mThreadId, &threadAttr, threadProc, this); if (status) { LOGE("Failed to start rs context thread."); return false; } while (!mRunning && (mError == RS_ERROR_NONE)) { usleep(100); } if (mError != RS_ERROR_NONE) { LOGE("Errors during thread init"); return false; } pthread_attr_destroy(&threadAttr); return true; } Context::~Context() { LOGV("Context::~Context"); mIO.mToCore.flush(); rsAssert(mExit); mExit = true; mPaused = false; void *res; mIO.shutdown(); int status = pthread_join(mThreadId, &res); if (mHal.funcs.shutdownDriver) { mHal.funcs.shutdownDriver(this); } // Global structure cleanup. pthread_mutex_lock(&gInitMutex); if (mDev) { mDev->removeContext(this); --gThreadTLSKeyCount; if (!gThreadTLSKeyCount) { pthread_key_delete(gThreadTLSKey); } mDev = NULL; } pthread_mutex_unlock(&gInitMutex); LOGV("Context::~Context done"); } void Context::setSurface(uint32_t w, uint32_t h, ANativeWindow *sur) { rsAssert(mIsGraphicsContext); mHal.funcs.setSurface(this, w, h, sur); mWndSurface = sur; mWidth = w; mHeight = h; if (mWidth && mHeight) { mStateVertex.updateSize(this); } } void Context::pause() { rsAssert(mIsGraphicsContext); mPaused = true; } void Context::resume() { rsAssert(mIsGraphicsContext); mPaused = false; } void Context::setRootScript(Script *s) { rsAssert(mIsGraphicsContext); mRootScript.set(s); } void Context::setProgramStore(ProgramStore *pfs) { rsAssert(mIsGraphicsContext); if (pfs == NULL) { mFragmentStore.set(mStateFragmentStore.mDefault); } else { mFragmentStore.set(pfs); } } void Context::setProgramFragment(ProgramFragment *pf) { rsAssert(mIsGraphicsContext); if (pf == NULL) { mFragment.set(mStateFragment.mDefault); } else { mFragment.set(pf); } } void Context::setProgramRaster(ProgramRaster *pr) { rsAssert(mIsGraphicsContext); if (pr == NULL) { mRaster.set(mStateRaster.mDefault); } else { mRaster.set(pr); } } void Context::setProgramVertex(ProgramVertex *pv) { rsAssert(mIsGraphicsContext); if (pv == NULL) { mVertex.set(mStateVertex.mDefault); } else { mVertex.set(pv); } } void Context::setFont(Font *f) { rsAssert(mIsGraphicsContext); if (f == NULL) { mFont.set(mStateFont.mDefault); } else { mFont.set(f); } } void Context::assignName(ObjectBase *obj, const char *name, uint32_t len) { rsAssert(!obj->getName()); obj->setName(name, len); mNames.add(obj); } void Context::removeName(ObjectBase *obj) { for (size_t ct=0; ct < mNames.size(); ct++) { if (obj == mNames[ct]) { mNames.removeAt(ct); return; } } } RsMessageToClientType Context::peekMessageToClient(size_t *receiveLen, uint32_t *subID, bool wait) { *receiveLen = 0; if (!wait && mIO.mToClient.isEmpty()) { return RS_MESSAGE_TO_CLIENT_NONE; } uint32_t bytesData = 0; uint32_t commandID = 0; const uint32_t *d = (const uint32_t *)mIO.mToClient.get(&commandID, &bytesData); *receiveLen = bytesData - sizeof(uint32_t); if (bytesData) { *subID = d[0]; } return (RsMessageToClientType)commandID; } RsMessageToClientType Context::getMessageToClient(void *data, size_t *receiveLen, uint32_t *subID, size_t bufferLen, bool wait) { //LOGE("getMessageToClient %i %i", bufferLen, wait); *receiveLen = 0; if (!wait && mIO.mToClient.isEmpty()) { return RS_MESSAGE_TO_CLIENT_NONE; } //LOGE("getMessageToClient 2 con=%p", this); uint32_t bytesData = 0; uint32_t commandID = 0; const uint32_t *d = (const uint32_t *)mIO.mToClient.get(&commandID, &bytesData); //LOGE("getMessageToClient 3 %i %i", commandID, bytesData); *receiveLen = bytesData - sizeof(uint32_t); *subID = d[0]; //LOGE("getMessageToClient %i %i", commandID, *subID); if (bufferLen >= bytesData) { memcpy(data, d+1, *receiveLen); mIO.mToClient.next(); return (RsMessageToClientType)commandID; } return RS_MESSAGE_TO_CLIENT_RESIZE; } bool Context::sendMessageToClient(const void *data, RsMessageToClientType cmdID, uint32_t subID, size_t len, bool waitForSpace) const { //LOGE("sendMessageToClient %i %i %i %i", cmdID, subID, len, waitForSpace); if (cmdID == 0) { LOGE("Attempting to send invalid command 0 to client."); return false; } if (!waitForSpace) { if (!mIO.mToClient.makeSpaceNonBlocking(len + 12)) { // Not enough room, and not waiting. return false; } } //LOGE("sendMessageToClient 2"); uint32_t *p = (uint32_t *)mIO.mToClient.reserve(len + sizeof(subID)); p[0] = subID; if (len > 0) { memcpy(p+1, data, len); } mIO.mToClient.commit(cmdID, len + sizeof(subID)); //LOGE("sendMessageToClient 3"); return true; } void Context::initToClient() { while (!mRunning) { usleep(100); } } void Context::deinitToClient() { mIO.mToClient.shutdown(); } void Context::setError(RsError e, const char *msg) const { mError = e; sendMessageToClient(msg, RS_MESSAGE_TO_CLIENT_ERROR, e, strlen(msg) + 1, true); } void Context::dumpDebug() const { LOGE("RS Context debug %p", this); LOGE("RS Context debug"); LOGE(" RS width %i, height %i", mWidth, mHeight); LOGE(" RS running %i, exit %i, paused %i", mRunning, mExit, mPaused); LOGE(" RS pThreadID %li, nativeThreadID %i", mThreadId, mNativeThreadId); } /////////////////////////////////////////////////////////////////////////////////////////// // namespace android { namespace renderscript { void rsi_ContextFinish(Context *rsc) { } void rsi_ContextBindRootScript(Context *rsc, RsScript vs) { Script *s = static_cast