rsContext.cpp revision bad807405b2b9764372af1ad24bcfd4fb1f33d8e
1/* 2 * Copyright (C) 2009 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 "rsDevice.h" 18#include "rsContext.h" 19#include "rsThreadIO.h" 20#include <ui/FramebufferNativeWindow.h> 21#include <ui/PixelFormat.h> 22#include <ui/EGLUtils.h> 23#include <ui/egl/android_natives.h> 24 25#include <sys/types.h> 26#include <sys/resource.h> 27#include <sched.h> 28 29#include <cutils/properties.h> 30 31#include <GLES/gl.h> 32#include <GLES/glext.h> 33#include <GLES2/gl2.h> 34#include <GLES2/gl2ext.h> 35 36#include <cutils/sched_policy.h> 37#include <sys/syscall.h> 38#include <string.h> 39 40using namespace android; 41using namespace android::renderscript; 42 43pthread_key_t Context::gThreadTLSKey = 0; 44uint32_t Context::gThreadTLSKeyCount = 0; 45uint32_t Context::gGLContextCount = 0; 46pthread_mutex_t Context::gInitMutex = PTHREAD_MUTEX_INITIALIZER; 47pthread_mutex_t Context::gLibMutex = PTHREAD_MUTEX_INITIALIZER; 48 49static void checkEglError(const char* op, EGLBoolean returnVal = EGL_TRUE) { 50 if (returnVal != EGL_TRUE) { 51 fprintf(stderr, "%s() returned %d\n", op, returnVal); 52 } 53 54 for (EGLint error = eglGetError(); error != EGL_SUCCESS; error 55 = eglGetError()) { 56 fprintf(stderr, "after %s() eglError %s (0x%x)\n", op, EGLUtils::strerror(error), 57 error); 58 } 59} 60 61void printEGLConfiguration(EGLDisplay dpy, EGLConfig config) { 62 63#define X(VAL) {VAL, #VAL} 64 struct {EGLint attribute; const char* name;} names[] = { 65 X(EGL_BUFFER_SIZE), 66 X(EGL_ALPHA_SIZE), 67 X(EGL_BLUE_SIZE), 68 X(EGL_GREEN_SIZE), 69 X(EGL_RED_SIZE), 70 X(EGL_DEPTH_SIZE), 71 X(EGL_STENCIL_SIZE), 72 X(EGL_CONFIG_CAVEAT), 73 X(EGL_CONFIG_ID), 74 X(EGL_LEVEL), 75 X(EGL_MAX_PBUFFER_HEIGHT), 76 X(EGL_MAX_PBUFFER_PIXELS), 77 X(EGL_MAX_PBUFFER_WIDTH), 78 X(EGL_NATIVE_RENDERABLE), 79 X(EGL_NATIVE_VISUAL_ID), 80 X(EGL_NATIVE_VISUAL_TYPE), 81 X(EGL_SAMPLES), 82 X(EGL_SAMPLE_BUFFERS), 83 X(EGL_SURFACE_TYPE), 84 X(EGL_TRANSPARENT_TYPE), 85 X(EGL_TRANSPARENT_RED_VALUE), 86 X(EGL_TRANSPARENT_GREEN_VALUE), 87 X(EGL_TRANSPARENT_BLUE_VALUE), 88 X(EGL_BIND_TO_TEXTURE_RGB), 89 X(EGL_BIND_TO_TEXTURE_RGBA), 90 X(EGL_MIN_SWAP_INTERVAL), 91 X(EGL_MAX_SWAP_INTERVAL), 92 X(EGL_LUMINANCE_SIZE), 93 X(EGL_ALPHA_MASK_SIZE), 94 X(EGL_COLOR_BUFFER_TYPE), 95 X(EGL_RENDERABLE_TYPE), 96 X(EGL_CONFORMANT), 97 }; 98#undef X 99 100 for (size_t j = 0; j < sizeof(names) / sizeof(names[0]); j++) { 101 EGLint value = -1; 102 EGLint returnVal = eglGetConfigAttrib(dpy, config, names[j].attribute, &value); 103 EGLint error = eglGetError(); 104 if (returnVal && error == EGL_SUCCESS) { 105 LOGV(" %s: %d (0x%x)", names[j].name, value, value); 106 } 107 } 108} 109 110 111bool Context::initGLThread() { 112 pthread_mutex_lock(&gInitMutex); 113 LOGV("initGLThread start %p", this); 114 115 mEGL.mNumConfigs = -1; 116 EGLint configAttribs[128]; 117 EGLint *configAttribsPtr = configAttribs; 118 EGLint context_attribs2[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; 119 120 memset(configAttribs, 0, sizeof(configAttribs)); 121 122 configAttribsPtr[0] = EGL_SURFACE_TYPE; 123 configAttribsPtr[1] = EGL_WINDOW_BIT; 124 configAttribsPtr += 2; 125 126 configAttribsPtr[0] = EGL_RENDERABLE_TYPE; 127 configAttribsPtr[1] = EGL_OPENGL_ES2_BIT; 128 configAttribsPtr += 2; 129 130 if (mUserSurfaceConfig.depthMin > 0) { 131 configAttribsPtr[0] = EGL_DEPTH_SIZE; 132 configAttribsPtr[1] = mUserSurfaceConfig.depthMin; 133 configAttribsPtr += 2; 134 } 135 136 if (mDev->mForceSW) { 137 configAttribsPtr[0] = EGL_CONFIG_CAVEAT; 138 configAttribsPtr[1] = EGL_SLOW_CONFIG; 139 configAttribsPtr += 2; 140 } 141 142 configAttribsPtr[0] = EGL_NONE; 143 rsAssert(configAttribsPtr < (configAttribs + (sizeof(configAttribs) / sizeof(EGLint)))); 144 145 LOGV("%p initEGL start", this); 146 mEGL.mDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); 147 checkEglError("eglGetDisplay"); 148 149 eglInitialize(mEGL.mDisplay, &mEGL.mMajorVersion, &mEGL.mMinorVersion); 150 checkEglError("eglInitialize"); 151 152#if 1 153 PixelFormat pf = PIXEL_FORMAT_RGBA_8888; 154 if (mUserSurfaceConfig.alphaMin == 0) { 155 pf = PIXEL_FORMAT_RGBX_8888; 156 } 157 158 status_t err = EGLUtils::selectConfigForPixelFormat(mEGL.mDisplay, configAttribs, pf, &mEGL.mConfig); 159 if (err) { 160 LOGE("%p, couldn't find an EGLConfig matching the screen format\n", this); 161 } 162 if (props.mLogVisual) { 163 printEGLConfiguration(mEGL.mDisplay, mEGL.mConfig); 164 } 165#else 166 eglChooseConfig(mEGL.mDisplay, configAttribs, &mEGL.mConfig, 1, &mEGL.mNumConfigs); 167#endif 168 169 mEGL.mContext = eglCreateContext(mEGL.mDisplay, mEGL.mConfig, EGL_NO_CONTEXT, context_attribs2); 170 checkEglError("eglCreateContext"); 171 if (mEGL.mContext == EGL_NO_CONTEXT) { 172 pthread_mutex_unlock(&gInitMutex); 173 LOGE("%p, eglCreateContext returned EGL_NO_CONTEXT", this); 174 return false; 175 } 176 gGLContextCount++; 177 178 179 EGLint pbuffer_attribs[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE }; 180 mEGL.mSurfaceDefault = eglCreatePbufferSurface(mEGL.mDisplay, mEGL.mConfig, pbuffer_attribs); 181 checkEglError("eglCreatePbufferSurface"); 182 if (mEGL.mSurfaceDefault == EGL_NO_SURFACE) { 183 LOGE("eglCreatePbufferSurface returned EGL_NO_SURFACE"); 184 pthread_mutex_unlock(&gInitMutex); 185 deinitEGL(); 186 return false; 187 } 188 189 EGLBoolean ret = eglMakeCurrent(mEGL.mDisplay, mEGL.mSurfaceDefault, mEGL.mSurfaceDefault, mEGL.mContext); 190 if (ret == EGL_FALSE) { 191 LOGE("eglMakeCurrent returned EGL_FALSE"); 192 checkEglError("eglMakeCurrent", ret); 193 pthread_mutex_unlock(&gInitMutex); 194 deinitEGL(); 195 return false; 196 } 197 198 mGL.mVersion = glGetString(GL_VERSION); 199 mGL.mVendor = glGetString(GL_VENDOR); 200 mGL.mRenderer = glGetString(GL_RENDERER); 201 mGL.mExtensions = glGetString(GL_EXTENSIONS); 202 203 //LOGV("EGL Version %i %i", mEGL.mMajorVersion, mEGL.mMinorVersion); 204 //LOGV("GL Version %s", mGL.mVersion); 205 //LOGV("GL Vendor %s", mGL.mVendor); 206 //LOGV("GL Renderer %s", mGL.mRenderer); 207 //LOGV("GL Extensions %s", mGL.mExtensions); 208 209 const char *verptr = NULL; 210 if (strlen((const char *)mGL.mVersion) > 9) { 211 if (!memcmp(mGL.mVersion, "OpenGL ES-CM", 12)) { 212 verptr = (const char *)mGL.mVersion + 12; 213 } 214 if (!memcmp(mGL.mVersion, "OpenGL ES ", 10)) { 215 verptr = (const char *)mGL.mVersion + 9; 216 } 217 } 218 219 if (!verptr) { 220 LOGE("Error, OpenGL ES Lite not supported"); 221 pthread_mutex_unlock(&gInitMutex); 222 deinitEGL(); 223 return false; 224 } else { 225 sscanf(verptr, " %i.%i", &mGL.mMajorVersion, &mGL.mMinorVersion); 226 } 227 228 glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &mGL.mMaxVertexAttribs); 229 glGetIntegerv(GL_MAX_VERTEX_UNIFORM_VECTORS, &mGL.mMaxVertexUniformVectors); 230 glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &mGL.mMaxVertexTextureUnits); 231 232 glGetIntegerv(GL_MAX_VARYING_VECTORS, &mGL.mMaxVaryingVectors); 233 glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &mGL.mMaxTextureImageUnits); 234 235 glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &mGL.mMaxFragmentTextureImageUnits); 236 glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_VECTORS, &mGL.mMaxFragmentUniformVectors); 237 238 mGL.OES_texture_npot = NULL != strstr((const char *)mGL.mExtensions, "GL_OES_texture_npot"); 239 mGL.GL_IMG_texture_npot = NULL != strstr((const char *)mGL.mExtensions, "GL_IMG_texture_npot"); 240 mGL.GL_NV_texture_npot_2D_mipmap = NULL != strstr((const char *)mGL.mExtensions, "GL_NV_texture_npot_2D_mipmap"); 241 mGL.EXT_texture_max_aniso = 1.0f; 242 bool hasAniso = NULL != strstr((const char *)mGL.mExtensions, "GL_EXT_texture_filter_anisotropic"); 243 if (hasAniso) { 244 glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &mGL.EXT_texture_max_aniso); 245 } 246 247 LOGV("initGLThread end %p", this); 248 pthread_mutex_unlock(&gInitMutex); 249 return true; 250} 251 252void Context::deinitEGL() { 253 LOGV("%p, deinitEGL", this); 254 255 if (mEGL.mContext != EGL_NO_CONTEXT) { 256 eglMakeCurrent(mEGL.mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); 257 eglDestroySurface(mEGL.mDisplay, mEGL.mSurfaceDefault); 258 if (mEGL.mSurface != EGL_NO_SURFACE) { 259 eglDestroySurface(mEGL.mDisplay, mEGL.mSurface); 260 } 261 eglDestroyContext(mEGL.mDisplay, mEGL.mContext); 262 checkEglError("eglDestroyContext"); 263 } 264 265 gGLContextCount--; 266 if (!gGLContextCount) { 267 eglTerminate(mEGL.mDisplay); 268 } 269} 270 271Context::PushState::PushState(Context *con) { 272 mRsc = con; 273 if (con->mIsGraphicsContext) { 274 mFragment.set(con->getProgramFragment()); 275 mVertex.set(con->getProgramVertex()); 276 mStore.set(con->getProgramStore()); 277 mRaster.set(con->getProgramRaster()); 278 mFont.set(con->getFont()); 279 } 280} 281 282Context::PushState::~PushState() { 283 if (mRsc->mIsGraphicsContext) { 284 mRsc->setProgramFragment(mFragment.get()); 285 mRsc->setProgramVertex(mVertex.get()); 286 mRsc->setProgramStore(mStore.get()); 287 mRsc->setProgramRaster(mRaster.get()); 288 mRsc->setFont(mFont.get()); 289 } 290} 291 292 293uint32_t Context::runScript(Script *s) { 294 PushState(this); 295 296 uint32_t ret = s->run(this); 297 return ret; 298} 299 300void Context::checkError(const char *msg, bool isFatal) const { 301 302 GLenum err = glGetError(); 303 if (err != GL_NO_ERROR) { 304 char buf[1024]; 305 snprintf(buf, sizeof(buf), "GL Error = 0x%08x, from: %s", err, msg); 306 307 if (isFatal) { 308 setError(RS_ERROR_FATAL_DRIVER, buf); 309 } else { 310 switch (err) { 311 case GL_OUT_OF_MEMORY: 312 setError(RS_ERROR_OUT_OF_MEMORY, buf); 313 break; 314 default: 315 setError(RS_ERROR_DRIVER, buf); 316 break; 317 } 318 } 319 320 LOGE("%p, %s", this, buf); 321 } 322} 323 324uint32_t Context::runRootScript() { 325 glViewport(0, 0, mWidth, mHeight); 326 327 timerSet(RS_TIMER_SCRIPT); 328 mStateFragmentStore.mLast.clear(); 329 uint32_t ret = runScript(mRootScript.get()); 330 331 checkError("runRootScript"); 332 return ret; 333} 334 335uint64_t Context::getTime() const { 336 struct timespec t; 337 clock_gettime(CLOCK_MONOTONIC, &t); 338 return t.tv_nsec + ((uint64_t)t.tv_sec * 1000 * 1000 * 1000); 339} 340 341void Context::timerReset() { 342 for (int ct=0; ct < _RS_TIMER_TOTAL; ct++) { 343 mTimers[ct] = 0; 344 } 345} 346 347void Context::timerInit() { 348 mTimeLast = getTime(); 349 mTimeFrame = mTimeLast; 350 mTimeLastFrame = mTimeLast; 351 mTimerActive = RS_TIMER_INTERNAL; 352 mAverageFPSFrameCount = 0; 353 mAverageFPSStartTime = mTimeLast; 354 mAverageFPS = 0; 355 timerReset(); 356} 357 358void Context::timerFrame() { 359 mTimeLastFrame = mTimeFrame; 360 mTimeFrame = getTime(); 361 // Update average fps 362 const uint64_t averageFramerateInterval = 1000 * 1000000; 363 mAverageFPSFrameCount ++; 364 uint64_t inverval = mTimeFrame - mAverageFPSStartTime; 365 if (inverval >= averageFramerateInterval) { 366 inverval = inverval / 1000000; 367 mAverageFPS = (mAverageFPSFrameCount * 1000) / inverval; 368 mAverageFPSFrameCount = 0; 369 mAverageFPSStartTime = mTimeFrame; 370 } 371} 372 373void Context::timerSet(Timers tm) { 374 uint64_t last = mTimeLast; 375 mTimeLast = getTime(); 376 mTimers[mTimerActive] += mTimeLast - last; 377 mTimerActive = tm; 378} 379 380void Context::timerPrint() { 381 double total = 0; 382 for (int ct = 0; ct < _RS_TIMER_TOTAL; ct++) { 383 total += mTimers[ct]; 384 } 385 uint64_t frame = mTimeFrame - mTimeLastFrame; 386 mTimeMSLastFrame = frame / 1000000; 387 mTimeMSLastScript = mTimers[RS_TIMER_SCRIPT] / 1000000; 388 mTimeMSLastSwap = mTimers[RS_TIMER_CLEAR_SWAP] / 1000000; 389 390 391 if (props.mLogTimes) { 392 LOGV("RS: Frame (%i), Script %2.1f%% (%i), Swap %2.1f%% (%i), Idle %2.1f%% (%lli), Internal %2.1f%% (%lli), Avg fps: %u", 393 mTimeMSLastFrame, 394 100.0 * mTimers[RS_TIMER_SCRIPT] / total, mTimeMSLastScript, 395 100.0 * mTimers[RS_TIMER_CLEAR_SWAP] / total, mTimeMSLastSwap, 396 100.0 * mTimers[RS_TIMER_IDLE] / total, mTimers[RS_TIMER_IDLE] / 1000000, 397 100.0 * mTimers[RS_TIMER_INTERNAL] / total, mTimers[RS_TIMER_INTERNAL] / 1000000, 398 mAverageFPS); 399 } 400} 401 402bool Context::setupCheck() { 403 if (!mShaderCache.lookup(this, mVertex.get(), mFragment.get())) { 404 LOGE("Context::setupCheck() 1 fail"); 405 return false; 406 } 407 408 mFragmentStore->setupGL2(this, &mStateFragmentStore); 409 mFragment->setupGL2(this, &mStateFragment, &mShaderCache); 410 mRaster->setupGL2(this, &mStateRaster); 411 mVertex->setupGL2(this, &mStateVertex, &mShaderCache); 412 return true; 413} 414 415void Context::setupProgramStore() { 416 mFragmentStore->setupGL2(this, &mStateFragmentStore); 417} 418 419static bool getProp(const char *str) { 420 char buf[PROPERTY_VALUE_MAX]; 421 property_get(str, buf, "0"); 422 return 0 != strcmp(buf, "0"); 423} 424 425void Context::displayDebugStats() { 426 char buffer[128]; 427 sprintf(buffer, "Avg fps %u, Frame %i ms, Script %i ms", mAverageFPS, mTimeMSLastFrame, mTimeMSLastScript); 428 float oldR, oldG, oldB, oldA; 429 mStateFont.getFontColor(&oldR, &oldG, &oldB, &oldA); 430 uint32_t bufferLen = strlen(buffer); 431 432 ObjectBaseRef<Font> lastFont(getFont()); 433 setFont(NULL); 434 float shadowCol = 0.1f; 435 mStateFont.setFontColor(shadowCol, shadowCol, shadowCol, 1.0f); 436 mStateFont.renderText(buffer, bufferLen, 5, getHeight() - 6); 437 438 mStateFont.setFontColor(1.0f, 0.7f, 0.0f, 1.0f); 439 mStateFont.renderText(buffer, bufferLen, 4, getHeight() - 7); 440 441 setFont(lastFont.get()); 442 mStateFont.setFontColor(oldR, oldG, oldB, oldA); 443} 444 445void * Context::threadProc(void *vrsc) { 446 Context *rsc = static_cast<Context *>(vrsc); 447 rsc->mNativeThreadId = gettid(); 448 449 setpriority(PRIO_PROCESS, rsc->mNativeThreadId, ANDROID_PRIORITY_DISPLAY); 450 rsc->mThreadPriority = ANDROID_PRIORITY_DISPLAY; 451 452 rsc->props.mLogTimes = getProp("debug.rs.profile"); 453 rsc->props.mLogScripts = getProp("debug.rs.script"); 454 rsc->props.mLogObjects = getProp("debug.rs.object"); 455 rsc->props.mLogShaders = getProp("debug.rs.shader"); 456 rsc->props.mLogShadersAttr = getProp("debug.rs.shader.attributes"); 457 rsc->props.mLogShadersUniforms = getProp("debug.rs.shader.uniforms"); 458 rsc->props.mLogVisual = getProp("debug.rs.visual"); 459 460 rsc->mTlsStruct = new ScriptTLSStruct; 461 if (!rsc->mTlsStruct) { 462 LOGE("Error allocating tls storage"); 463 rsc->setError(RS_ERROR_OUT_OF_MEMORY, "Failed allocation for TLS"); 464 return NULL; 465 } 466 rsc->mTlsStruct->mContext = rsc; 467 rsc->mTlsStruct->mScript = NULL; 468 int status = pthread_setspecific(rsc->gThreadTLSKey, rsc->mTlsStruct); 469 if (status) { 470 LOGE("pthread_setspecific %i", status); 471 } 472 473 if (!rsc->initGLThread()) { 474 rsc->setError(RS_ERROR_OUT_OF_MEMORY, "Failed initializing GL"); 475 return NULL; 476 } 477 478 if (rsc->mIsGraphicsContext) { 479 rsc->mStateRaster.init(rsc); 480 rsc->setProgramRaster(NULL); 481 rsc->mStateVertex.init(rsc); 482 rsc->setProgramVertex(NULL); 483 rsc->mStateFragment.init(rsc); 484 rsc->setProgramFragment(NULL); 485 rsc->mStateFragmentStore.init(rsc); 486 rsc->setProgramStore(NULL); 487 rsc->mStateFont.init(rsc); 488 rsc->setFont(NULL); 489 rsc->mStateVertexArray.init(rsc); 490 } 491 492 rsc->mRunning = true; 493 bool mDraw = true; 494 while (!rsc->mExit) { 495 mDraw |= rsc->mIO.playCoreCommands(rsc, !mDraw); 496 mDraw &= (rsc->mRootScript.get() != NULL); 497 mDraw &= (rsc->mWndSurface != NULL); 498 499 uint32_t targetTime = 0; 500 if (mDraw && rsc->mIsGraphicsContext) { 501 targetTime = rsc->runRootScript(); 502 503 if (rsc->props.mLogVisual) { 504 rsc->displayDebugStats(); 505 } 506 507 mDraw = targetTime && !rsc->mPaused; 508 rsc->timerSet(RS_TIMER_CLEAR_SWAP); 509 eglSwapBuffers(rsc->mEGL.mDisplay, rsc->mEGL.mSurface); 510 rsc->timerFrame(); 511 rsc->timerSet(RS_TIMER_INTERNAL); 512 rsc->timerPrint(); 513 rsc->timerReset(); 514 } 515 if (targetTime > 1) { 516 int32_t t = (targetTime - (int32_t)(rsc->mTimeMSLastScript + rsc->mTimeMSLastSwap)) * 1000; 517 if (t > 0) { 518 usleep(t); 519 } 520 } 521 } 522 523 LOGV("%p, RS Thread exiting", rsc); 524 525 if (rsc->mIsGraphicsContext) { 526 pthread_mutex_lock(&gInitMutex); 527 rsc->deinitEGL(); 528 pthread_mutex_unlock(&gInitMutex); 529 } 530 delete rsc->mTlsStruct; 531 532 LOGV("%p, RS Thread exited", rsc); 533 return NULL; 534} 535 536void Context::destroyWorkerThreadResources() { 537 //LOGV("destroyWorkerThreadResources 1"); 538 ObjectBase::zeroAllUserRef(this); 539 if (mIsGraphicsContext) { 540 mRaster.clear(); 541 mFragment.clear(); 542 mVertex.clear(); 543 mFragmentStore.clear(); 544 mFont.clear(); 545 mRootScript.clear(); 546 mStateRaster.deinit(this); 547 mStateVertex.deinit(this); 548 mStateFragment.deinit(this); 549 mStateFragmentStore.deinit(this); 550 mStateFont.deinit(this); 551 mShaderCache.cleanupAll(); 552 } 553 //LOGV("destroyWorkerThreadResources 2"); 554 mExit = true; 555} 556 557void * Context::helperThreadProc(void *vrsc) { 558 Context *rsc = static_cast<Context *>(vrsc); 559 uint32_t idx = (uint32_t)android_atomic_inc(&rsc->mWorkers.mLaunchCount); 560 561 //LOGV("RS helperThread starting %p idx=%i", rsc, idx); 562 563 rsc->mWorkers.mLaunchSignals[idx].init(); 564 rsc->mWorkers.mNativeThreadId[idx] = gettid(); 565 566#if 0 567 typedef struct {uint64_t bits[1024 / 64]; } cpu_set_t; 568 cpu_set_t cpuset; 569 memset(&cpuset, 0, sizeof(cpuset)); 570 cpuset.bits[idx / 64] |= 1ULL << (idx % 64); 571 int ret = syscall(241, rsc->mWorkers.mNativeThreadId[idx], 572 sizeof(cpuset), &cpuset); 573 LOGE("SETAFFINITY ret = %i %s", ret, EGLUtils::strerror(ret)); 574#endif 575 576 setpriority(PRIO_PROCESS, rsc->mWorkers.mNativeThreadId[idx], rsc->mThreadPriority); 577 int status = pthread_setspecific(rsc->gThreadTLSKey, rsc->mTlsStruct); 578 if (status) { 579 LOGE("pthread_setspecific %i", status); 580 } 581 582 while (!rsc->mExit) { 583 rsc->mWorkers.mLaunchSignals[idx].wait(); 584 if (rsc->mWorkers.mLaunchCallback) { 585 rsc->mWorkers.mLaunchCallback(rsc->mWorkers.mLaunchData, idx); 586 } 587 android_atomic_dec(&rsc->mWorkers.mRunningCount); 588 rsc->mWorkers.mCompleteSignal.set(); 589 } 590 591 //LOGV("RS helperThread exited %p idx=%i", rsc, idx); 592 return NULL; 593} 594 595void Context::launchThreads(WorkerCallback_t cbk, void *data) { 596 mWorkers.mLaunchData = data; 597 mWorkers.mLaunchCallback = cbk; 598 android_atomic_release_store(mWorkers.mCount, &mWorkers.mRunningCount); 599 for (uint32_t ct = 0; ct < mWorkers.mCount; ct++) { 600 mWorkers.mLaunchSignals[ct].set(); 601 } 602 while (android_atomic_acquire_load(&mWorkers.mRunningCount) != 0) { 603 mWorkers.mCompleteSignal.wait(); 604 } 605} 606 607void Context::setPriority(int32_t p) { 608 // Note: If we put this in the proper "background" policy 609 // the wallpapers can become completly unresponsive at times. 610 // This is probably not what we want for something the user is actively 611 // looking at. 612 mThreadPriority = p; 613#if 0 614 SchedPolicy pol = SP_FOREGROUND; 615 if (p > 0) { 616 pol = SP_BACKGROUND; 617 } 618 if (!set_sched_policy(mNativeThreadId, pol)) { 619 // success; reset the priority as well 620 } 621#else 622 setpriority(PRIO_PROCESS, mNativeThreadId, p); 623 for (uint32_t ct=0; ct < mWorkers.mCount; ct++) { 624 setpriority(PRIO_PROCESS, mWorkers.mNativeThreadId[ct], p); 625 } 626#endif 627} 628 629Context::Context() { 630 mDev = NULL; 631 mRunning = false; 632 mExit = false; 633 mPaused = false; 634 mObjHead = NULL; 635 mError = RS_ERROR_NONE; 636 mDPI = 96; 637} 638 639Context * Context::createContext(Device *dev, const RsSurfaceConfig *sc) { 640 Context * rsc = new Context(); 641 if (!rsc->initContext(dev, sc)) { 642 delete rsc; 643 return NULL; 644 } 645 return rsc; 646} 647 648bool Context::initContext(Device *dev, const RsSurfaceConfig *sc) { 649 pthread_mutex_lock(&gInitMutex); 650 651 dev->addContext(this); 652 mDev = dev; 653 if (sc) { 654 mUserSurfaceConfig = *sc; 655 } else { 656 memset(&mUserSurfaceConfig, 0, sizeof(mUserSurfaceConfig)); 657 } 658 659 memset(&mEGL, 0, sizeof(mEGL)); 660 memset(&mGL, 0, sizeof(mGL)); 661 mIsGraphicsContext = sc != NULL; 662 663 int status; 664 pthread_attr_t threadAttr; 665 666 if (!gThreadTLSKeyCount) { 667 status = pthread_key_create(&gThreadTLSKey, NULL); 668 if (status) { 669 LOGE("Failed to init thread tls key."); 670 pthread_mutex_unlock(&gInitMutex); 671 return false; 672 } 673 } 674 gThreadTLSKeyCount++; 675 676 pthread_mutex_unlock(&gInitMutex); 677 678 // Global init done at this point. 679 680 status = pthread_attr_init(&threadAttr); 681 if (status) { 682 LOGE("Failed to init thread attribute."); 683 return false; 684 } 685 686 mWndSurface = NULL; 687 688 timerInit(); 689 timerSet(RS_TIMER_INTERNAL); 690 691 if (!rsdHalInit(this, 0, 0)) { 692 return false; 693 } 694 695 int cpu = sysconf(_SC_NPROCESSORS_ONLN); 696 LOGV("RS Launching thread(s), reported CPU count %i", cpu); 697 if (cpu < 2) cpu = 0; 698 699 mWorkers.mCount = (uint32_t)cpu; 700 mWorkers.mThreadId = (pthread_t *) calloc(mWorkers.mCount, sizeof(pthread_t)); 701 mWorkers.mNativeThreadId = (pid_t *) calloc(mWorkers.mCount, sizeof(pid_t)); 702 mWorkers.mLaunchSignals = new Signal[mWorkers.mCount]; 703 mWorkers.mLaunchCallback = NULL; 704 status = pthread_create(&mThreadId, &threadAttr, threadProc, this); 705 if (status) { 706 LOGE("Failed to start rs context thread."); 707 return false; 708 } 709 while (!mRunning && (mError == RS_ERROR_NONE)) { 710 usleep(100); 711 } 712 713 if (mError != RS_ERROR_NONE) { 714 return false; 715 } 716 717 mWorkers.mCompleteSignal.init(); 718 android_atomic_release_store(mWorkers.mCount, &mWorkers.mRunningCount); 719 android_atomic_release_store(0, &mWorkers.mLaunchCount); 720 for (uint32_t ct=0; ct < mWorkers.mCount; ct++) { 721 status = pthread_create(&mWorkers.mThreadId[ct], &threadAttr, helperThreadProc, this); 722 if (status) { 723 mWorkers.mCount = ct; 724 LOGE("Created fewer than expected number of RS threads."); 725 break; 726 } 727 } 728 while (android_atomic_acquire_load(&mWorkers.mRunningCount) != 0) { 729 usleep(100); 730 } 731 pthread_attr_destroy(&threadAttr); 732 return true; 733} 734 735Context::~Context() { 736 LOGV("Context::~Context"); 737 738 mIO.mToCore.flush(); 739 rsAssert(mExit); 740 mExit = true; 741 mPaused = false; 742 void *res; 743 744 mIO.shutdown(); 745 int status = pthread_join(mThreadId, &res); 746 747 // Cleanup compute threads. 748 mWorkers.mLaunchData = NULL; 749 mWorkers.mLaunchCallback = NULL; 750 android_atomic_release_store(mWorkers.mCount, &mWorkers.mRunningCount); 751 for (uint32_t ct = 0; ct < mWorkers.mCount; ct++) { 752 mWorkers.mLaunchSignals[ct].set(); 753 } 754 for (uint32_t ct = 0; ct < mWorkers.mCount; ct++) { 755 status = pthread_join(mWorkers.mThreadId[ct], &res); 756 } 757 rsAssert(android_atomic_acquire_load(&mWorkers.mRunningCount) == 0); 758 759 // Global structure cleanup. 760 pthread_mutex_lock(&gInitMutex); 761 if (mDev) { 762 mDev->removeContext(this); 763 --gThreadTLSKeyCount; 764 if (!gThreadTLSKeyCount) { 765 pthread_key_delete(gThreadTLSKey); 766 } 767 mDev = NULL; 768 } 769 pthread_mutex_unlock(&gInitMutex); 770 LOGV("Context::~Context done"); 771} 772 773void Context::setSurface(uint32_t w, uint32_t h, ANativeWindow *sur) { 774 rsAssert(mIsGraphicsContext); 775 776 EGLBoolean ret; 777 // WAR: Some drivers fail to handle 0 size surfaces correcntly. 778 // Use the pbuffer to avoid this pitfall. 779 if ((mEGL.mSurface != NULL) || (w == 0) || (h == 0)) { 780 ret = eglMakeCurrent(mEGL.mDisplay, mEGL.mSurfaceDefault, mEGL.mSurfaceDefault, mEGL.mContext); 781 checkEglError("eglMakeCurrent", ret); 782 783 ret = eglDestroySurface(mEGL.mDisplay, mEGL.mSurface); 784 checkEglError("eglDestroySurface", ret); 785 786 mEGL.mSurface = NULL; 787 mWidth = 1; 788 mHeight = 1; 789 } 790 791 mWndSurface = sur; 792 if (mWndSurface != NULL) { 793 mWidth = w; 794 mHeight = h; 795 796 mEGL.mSurface = eglCreateWindowSurface(mEGL.mDisplay, mEGL.mConfig, mWndSurface, NULL); 797 checkEglError("eglCreateWindowSurface"); 798 if (mEGL.mSurface == EGL_NO_SURFACE) { 799 LOGE("eglCreateWindowSurface returned EGL_NO_SURFACE"); 800 } 801 802 ret = eglMakeCurrent(mEGL.mDisplay, mEGL.mSurface, mEGL.mSurface, mEGL.mContext); 803 checkEglError("eglMakeCurrent", ret); 804 805 mStateVertex.updateSize(this); 806 } 807} 808 809void Context::pause() { 810 rsAssert(mIsGraphicsContext); 811 mPaused = true; 812} 813 814void Context::resume() { 815 rsAssert(mIsGraphicsContext); 816 mPaused = false; 817} 818 819void Context::setRootScript(Script *s) { 820 rsAssert(mIsGraphicsContext); 821 mRootScript.set(s); 822} 823 824void Context::setProgramStore(ProgramStore *pfs) { 825 rsAssert(mIsGraphicsContext); 826 if (pfs == NULL) { 827 mFragmentStore.set(mStateFragmentStore.mDefault); 828 } else { 829 mFragmentStore.set(pfs); 830 } 831} 832 833void Context::setProgramFragment(ProgramFragment *pf) { 834 rsAssert(mIsGraphicsContext); 835 if (pf == NULL) { 836 mFragment.set(mStateFragment.mDefault); 837 } else { 838 mFragment.set(pf); 839 } 840} 841 842void Context::setProgramRaster(ProgramRaster *pr) { 843 rsAssert(mIsGraphicsContext); 844 if (pr == NULL) { 845 mRaster.set(mStateRaster.mDefault); 846 } else { 847 mRaster.set(pr); 848 } 849} 850 851void Context::setProgramVertex(ProgramVertex *pv) { 852 rsAssert(mIsGraphicsContext); 853 if (pv == NULL) { 854 mVertex.set(mStateVertex.mDefault); 855 } else { 856 mVertex.set(pv); 857 } 858} 859 860void Context::setFont(Font *f) { 861 rsAssert(mIsGraphicsContext); 862 if (f == NULL) { 863 mFont.set(mStateFont.mDefault); 864 } else { 865 mFont.set(f); 866 } 867} 868 869void Context::assignName(ObjectBase *obj, const char *name, uint32_t len) { 870 rsAssert(!obj->getName()); 871 obj->setName(name, len); 872 mNames.add(obj); 873} 874 875void Context::removeName(ObjectBase *obj) { 876 for (size_t ct=0; ct < mNames.size(); ct++) { 877 if (obj == mNames[ct]) { 878 mNames.removeAt(ct); 879 return; 880 } 881 } 882} 883 884RsMessageToClientType Context::peekMessageToClient(size_t *receiveLen, uint32_t *subID, bool wait) { 885 *receiveLen = 0; 886 if (!wait && mIO.mToClient.isEmpty()) { 887 return RS_MESSAGE_TO_CLIENT_NONE; 888 } 889 890 uint32_t bytesData = 0; 891 uint32_t commandID = 0; 892 const uint32_t *d = (const uint32_t *)mIO.mToClient.get(&commandID, &bytesData); 893 *receiveLen = bytesData - sizeof(uint32_t); 894 if (bytesData) { 895 *subID = d[0]; 896 } 897 return (RsMessageToClientType)commandID; 898} 899 900RsMessageToClientType Context::getMessageToClient(void *data, size_t *receiveLen, uint32_t *subID, size_t bufferLen, bool wait) { 901 //LOGE("getMessageToClient %i %i", bufferLen, wait); 902 *receiveLen = 0; 903 if (!wait && mIO.mToClient.isEmpty()) { 904 return RS_MESSAGE_TO_CLIENT_NONE; 905 } 906 907 //LOGE("getMessageToClient 2 con=%p", this); 908 uint32_t bytesData = 0; 909 uint32_t commandID = 0; 910 const uint32_t *d = (const uint32_t *)mIO.mToClient.get(&commandID, &bytesData); 911 //LOGE("getMessageToClient 3 %i %i", commandID, bytesData); 912 913 *receiveLen = bytesData - sizeof(uint32_t); 914 *subID = d[0]; 915 916 //LOGE("getMessageToClient %i %i", commandID, *subID); 917 if (bufferLen >= bytesData) { 918 memcpy(data, d+1, *receiveLen); 919 mIO.mToClient.next(); 920 return (RsMessageToClientType)commandID; 921 } 922 return RS_MESSAGE_TO_CLIENT_RESIZE; 923} 924 925bool Context::sendMessageToClient(const void *data, RsMessageToClientType cmdID, 926 uint32_t subID, size_t len, bool waitForSpace) const { 927 //LOGE("sendMessageToClient %i %i %i %i", cmdID, subID, len, waitForSpace); 928 if (cmdID == 0) { 929 LOGE("Attempting to send invalid command 0 to client."); 930 return false; 931 } 932 if (!waitForSpace) { 933 if (!mIO.mToClient.makeSpaceNonBlocking(len + 12)) { 934 // Not enough room, and not waiting. 935 return false; 936 } 937 } 938 //LOGE("sendMessageToClient 2"); 939 uint32_t *p = (uint32_t *)mIO.mToClient.reserve(len + sizeof(subID)); 940 p[0] = subID; 941 if (len > 0) { 942 memcpy(p+1, data, len); 943 } 944 mIO.mToClient.commit(cmdID, len + sizeof(subID)); 945 //LOGE("sendMessageToClient 3"); 946 return true; 947} 948 949void Context::initToClient() { 950 while (!mRunning) { 951 usleep(100); 952 } 953} 954 955void Context::deinitToClient() { 956 mIO.mToClient.shutdown(); 957} 958 959void Context::setError(RsError e, const char *msg) const { 960 mError = e; 961 sendMessageToClient(msg, RS_MESSAGE_TO_CLIENT_ERROR, e, strlen(msg) + 1, true); 962} 963 964 965void Context::dumpDebug() const { 966 LOGE("RS Context debug %p", this); 967 LOGE("RS Context debug"); 968 969 LOGE(" EGL ver %i %i", mEGL.mMajorVersion, mEGL.mMinorVersion); 970 LOGE(" EGL context %p surface %p, Display=%p", mEGL.mContext, mEGL.mSurface, mEGL.mDisplay); 971 LOGE(" GL vendor: %s", mGL.mVendor); 972 LOGE(" GL renderer: %s", mGL.mRenderer); 973 LOGE(" GL Version: %s", mGL.mVersion); 974 LOGE(" GL Extensions: %s", mGL.mExtensions); 975 LOGE(" GL int Versions %i %i", mGL.mMajorVersion, mGL.mMinorVersion); 976 LOGE(" RS width %i, height %i", mWidth, mHeight); 977 LOGE(" RS running %i, exit %i, paused %i", mRunning, mExit, mPaused); 978 LOGE(" RS pThreadID %li, nativeThreadID %i", mThreadId, mNativeThreadId); 979 980 LOGV("MAX Textures %i, %i %i", mGL.mMaxVertexTextureUnits, mGL.mMaxFragmentTextureImageUnits, mGL.mMaxTextureImageUnits); 981 LOGV("MAX Attribs %i", mGL.mMaxVertexAttribs); 982 LOGV("MAX Uniforms %i, %i", mGL.mMaxVertexUniformVectors, mGL.mMaxFragmentUniformVectors); 983 LOGV("MAX Varyings %i", mGL.mMaxVaryingVectors); 984} 985 986/////////////////////////////////////////////////////////////////////////////////////////// 987// 988 989namespace android { 990namespace renderscript { 991 992void rsi_ContextFinish(Context *rsc) { 993} 994 995void rsi_ContextBindRootScript(Context *rsc, RsScript vs) { 996 Script *s = static_cast<Script *>(vs); 997 rsc->setRootScript(s); 998} 999 1000void rsi_ContextBindSampler(Context *rsc, uint32_t slot, RsSampler vs) { 1001 Sampler *s = static_cast<Sampler *>(vs); 1002 1003 if (slot > RS_MAX_SAMPLER_SLOT) { 1004 LOGE("Invalid sampler slot"); 1005 return; 1006 } 1007 1008 s->bindToContext(&rsc->mStateSampler, slot); 1009} 1010 1011void rsi_ContextBindProgramStore(Context *rsc, RsProgramStore vpfs) { 1012 ProgramStore *pfs = static_cast<ProgramStore *>(vpfs); 1013 rsc->setProgramStore(pfs); 1014} 1015 1016void rsi_ContextBindProgramFragment(Context *rsc, RsProgramFragment vpf) { 1017 ProgramFragment *pf = static_cast<ProgramFragment *>(vpf); 1018 rsc->setProgramFragment(pf); 1019} 1020 1021void rsi_ContextBindProgramRaster(Context *rsc, RsProgramRaster vpr) { 1022 ProgramRaster *pr = static_cast<ProgramRaster *>(vpr); 1023 rsc->setProgramRaster(pr); 1024} 1025 1026void rsi_ContextBindProgramVertex(Context *rsc, RsProgramVertex vpv) { 1027 ProgramVertex *pv = static_cast<ProgramVertex *>(vpv); 1028 rsc->setProgramVertex(pv); 1029} 1030 1031void rsi_ContextBindFont(Context *rsc, RsFont vfont) { 1032 Font *font = static_cast<Font *>(vfont); 1033 rsc->setFont(font); 1034} 1035 1036void rsi_AssignName(Context *rsc, void * obj, const char *name, uint32_t len) { 1037 ObjectBase *ob = static_cast<ObjectBase *>(obj); 1038 rsc->assignName(ob, name, len); 1039} 1040 1041void rsi_ObjDestroy(Context *rsc, void *optr) { 1042 ObjectBase *ob = static_cast<ObjectBase *>(optr); 1043 rsc->removeName(ob); 1044 ob->decUserRef(); 1045} 1046 1047void rsi_ContextPause(Context *rsc) { 1048 rsc->pause(); 1049} 1050 1051void rsi_ContextResume(Context *rsc) { 1052 rsc->resume(); 1053} 1054 1055void rsi_ContextSetSurface(Context *rsc, uint32_t w, uint32_t h, ANativeWindow *sur) { 1056 rsc->setSurface(w, h, sur); 1057} 1058 1059void rsi_ContextSetPriority(Context *rsc, int32_t p) { 1060 rsc->setPriority(p); 1061} 1062 1063void rsi_ContextDump(Context *rsc, int32_t bits) { 1064 ObjectBase::dumpAll(rsc); 1065} 1066 1067void rsi_ContextDestroyWorker(Context *rsc) { 1068 rsc->destroyWorkerThreadResources();; 1069} 1070 1071} 1072} 1073 1074void rsContextDestroy(RsContext vcon) { 1075 LOGV("rsContextDestroy %p", vcon); 1076 Context *rsc = static_cast<Context *>(vcon); 1077 rsContextDestroyWorker(rsc); 1078 delete rsc; 1079 LOGV("rsContextDestroy 2 %p", vcon); 1080} 1081 1082RsContext rsContextCreate(RsDevice vdev, uint32_t version) { 1083 LOGV("rsContextCreate %p", vdev); 1084 Device * dev = static_cast<Device *>(vdev); 1085 Context *rsc = Context::createContext(dev, NULL); 1086 return rsc; 1087} 1088 1089RsContext rsContextCreateGL(RsDevice vdev, uint32_t version, 1090 RsSurfaceConfig sc, uint32_t dpi) { 1091 LOGV("rsContextCreateGL %p", vdev); 1092 Device * dev = static_cast<Device *>(vdev); 1093 Context *rsc = Context::createContext(dev, &sc); 1094 rsc->setDPI(dpi); 1095 LOGV("rsContextCreateGL ret %p ", rsc); 1096 return rsc; 1097} 1098 1099RsMessageToClientType rsContextPeekMessage(RsContext vrsc, size_t *receiveLen, uint32_t *subID, bool wait) { 1100 Context * rsc = static_cast<Context *>(vrsc); 1101 return rsc->peekMessageToClient(receiveLen, subID, wait); 1102} 1103 1104RsMessageToClientType rsContextGetMessage(RsContext vrsc, void *data, size_t *receiveLen, uint32_t *subID, size_t bufferLen, bool wait) { 1105 Context * rsc = static_cast<Context *>(vrsc); 1106 return rsc->getMessageToClient(data, receiveLen, subID, bufferLen, wait); 1107} 1108 1109void rsContextInitToClient(RsContext vrsc) { 1110 Context * rsc = static_cast<Context *>(vrsc); 1111 rsc->initToClient(); 1112} 1113 1114void rsContextDeinitToClient(RsContext vrsc) { 1115 Context * rsc = static_cast<Context *>(vrsc); 1116 rsc->deinitToClient(); 1117} 1118 1119// Only to be called at a3d load time, before object is visible to user 1120// not thread safe 1121void rsaGetName(RsContext con, void * obj, const char **name) { 1122 ObjectBase *ob = static_cast<ObjectBase *>(obj); 1123 (*name) = ob->getName(); 1124} 1125