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