RenderScript.cpp revision cf067b8c4d1e53bc4768fbad239851c579717f2c
1/*
2 * Copyright (C) 2013 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 <malloc.h>
18#include <string.h>
19#include <pthread.h>
20
21#include "RenderScript.h"
22#include "rsCppStructs.h"
23#include "rsCppInternal.h"
24
25#include <dlfcn.h>
26#include <unistd.h>
27
28#if !defined(RS_SERVER) && !defined(RS_COMPATIBILITY_LIB) && defined(__ANDROID__)
29#include <cutils/properties.h>
30#else
31#include "rsCompatibilityLib.h"
32#endif
33
34
35using namespace android;
36using namespace RSC;
37
38bool RS::gInitialized = false;
39bool RS::usingNative = false;
40pthread_mutex_t RS::gInitMutex = PTHREAD_MUTEX_INITIALIZER;
41dispatchTable* RS::dispatch = nullptr;
42static int gInitError = 0;
43
44RS::RS() {
45    mDev = nullptr;
46    mContext = nullptr;
47    mErrorFunc = nullptr;
48    mMessageFunc = nullptr;
49    mMessageRun = false;
50    mInit = false;
51    mCurrentError = RS_SUCCESS;
52
53    memset(&mElements, 0, sizeof(mElements));
54    memset(&mSamplers, 0, sizeof(mSamplers));
55}
56
57RS::~RS() {
58    if (mInit == true) {
59        mMessageRun = false;
60
61        if (mContext) {
62            finish();
63            RS::dispatch->ContextDeinitToClient(mContext);
64
65            void *res = nullptr;
66            int status = pthread_join(mMessageThreadId, &res);
67
68            RS::dispatch->ContextDestroy(mContext);
69            mContext = nullptr;
70        }
71        if (mDev) {
72            RS::dispatch->DeviceDestroy(mDev);
73            mDev = nullptr;
74        }
75    }
76}
77
78bool RS::init(const char * name, uint32_t flags) {
79    return RS::init(name, RS_VERSION, flags);
80}
81
82// This will only open API 19+ libRS, because that's when
83// we changed libRS to extern "C" entry points.
84static bool loadSO(const char* filename, int targetApi) {
85    void* handle = dlopen(filename, RTLD_LAZY | RTLD_LOCAL);
86    if (handle == nullptr) {
87        ALOGV("couldn't dlopen %s, %s", filename, dlerror());
88        return false;
89    }
90
91    if (loadSymbols(handle, *RS::dispatch, targetApi) == false) {
92        ALOGV("%s init failed!", filename);
93        return false;
94    }
95    return true;
96}
97
98static uint32_t getProp(const char *str) {
99#if !defined(__LP64__) && !defined(RS_SERVER) && defined(__ANDROID__)
100    char buf[256];
101    property_get(str, buf, "0");
102    return atoi(buf);
103#else
104    return 0;
105#endif
106}
107
108bool RS::initDispatch(int targetApi) {
109    pthread_mutex_lock(&gInitMutex);
110    if (gInitError) {
111        goto error;
112    } else if (gInitialized) {
113        pthread_mutex_unlock(&gInitMutex);
114        return true;
115    }
116
117    RS::dispatch = new dispatchTable;
118
119    // Attempt to load libRS, load libRSSupport on failure.
120    // If property is set, proceed directly to libRSSupport.
121    if (getProp("debug.rs.forcecompat") == 0) {
122        usingNative = loadSO("libRS.so", targetApi);
123    }
124    if (usingNative == false) {
125        if (loadSO("libRSSupport.so", targetApi) == false) {
126            ALOGE("Failed to load libRS.so and libRSSupport.so");
127            goto error;
128        }
129    }
130
131    gInitialized = true;
132
133    pthread_mutex_unlock(&gInitMutex);
134    return true;
135
136 error:
137    gInitError = 1;
138    pthread_mutex_unlock(&gInitMutex);
139    return false;
140}
141
142bool RS::init(const char * name, int targetApi, uint32_t flags) {
143    if (mInit) {
144        return true;
145    }
146
147    if (initDispatch(targetApi) == false) {
148        ALOGE("Couldn't initialize dispatch table");
149        return false;
150    }
151
152    uint32_t nameLen = strlen(name);
153    if (nameLen > PATH_MAX) {
154        ALOGE("The path to the cache directory is too long");
155        return false;
156    }
157    memcpy(mCacheDir, name, nameLen);
158    // Add the null character even if the user does not.
159    mCacheDir[nameLen] = 0;
160    mCacheDirLen = nameLen + 1;
161
162    mDev = RS::dispatch->DeviceCreate();
163    if (mDev == 0) {
164        ALOGE("Device creation failed");
165        return false;
166    }
167
168    if (flags & ~(RS_CONTEXT_SYNCHRONOUS | RS_CONTEXT_LOW_LATENCY |
169                  RS_CONTEXT_LOW_POWER | RS_CONTEXT_WAIT_FOR_ATTACH |
170                  RS_CONTEXT_OPT_LEVEL_0)) {
171        ALOGE("Invalid flags passed");
172        return false;
173    }
174
175    mContext = RS::dispatch->ContextCreate(mDev, 0, targetApi, RS_CONTEXT_TYPE_NORMAL, flags);
176    if (mContext == 0) {
177        ALOGE("Context creation failed");
178        return false;
179    }
180
181    pid_t mNativeMessageThreadId;
182
183    int status = pthread_create(&mMessageThreadId, nullptr, threadProc, this);
184    if (status) {
185        ALOGE("Failed to start RS message thread.");
186        return false;
187    }
188    // Wait for the message thread to be active.
189    while (!mMessageRun) {
190        usleep(1000);
191    }
192
193    mInit = true;
194
195    return true;
196}
197
198void RS::throwError(RSError error, const char *errMsg) {
199    if (mCurrentError == RS_SUCCESS) {
200        mCurrentError = error;
201        ALOGE("RS CPP error: %s", errMsg);
202    } else {
203        ALOGE("RS CPP error (masked by previous error): %s", errMsg);
204    }
205}
206
207RSError RS::getError() {
208    return mCurrentError;
209}
210
211
212void * RS::threadProc(void *vrsc) {
213    RS *rs = static_cast<RS *>(vrsc);
214    size_t rbuf_size = 256;
215    void * rbuf = malloc(rbuf_size);
216
217    RS::dispatch->ContextInitToClient(rs->mContext);
218    rs->mMessageRun = true;
219
220    while (rs->mMessageRun) {
221        size_t receiveLen = 0;
222        uint32_t usrID = 0;
223        uint32_t subID = 0;
224        RsMessageToClientType r = RS::dispatch->ContextPeekMessage(rs->mContext,
225                                                                   &receiveLen, sizeof(receiveLen),
226                                                                   &usrID, sizeof(usrID));
227
228        if (receiveLen >= rbuf_size) {
229            rbuf_size = receiveLen + 32;
230            rbuf = realloc(rbuf, rbuf_size);
231        }
232        if (!rbuf) {
233            ALOGE("RS::message handler realloc error %zu", rbuf_size);
234            // No clean way to recover now?
235        }
236        RS::dispatch->ContextGetMessage(rs->mContext, rbuf, rbuf_size, &receiveLen, sizeof(receiveLen),
237                            &subID, sizeof(subID));
238
239        switch(r) {
240        case RS_MESSAGE_TO_CLIENT_ERROR:
241            ALOGE("RS Error %s", (const char *)rbuf);
242            rs->throwError(RS_ERROR_RUNTIME_ERROR, "Error returned from runtime");
243            if(rs->mMessageFunc != nullptr) {
244                rs->mErrorFunc(usrID, (const char *)rbuf);
245            }
246            break;
247        case RS_MESSAGE_TO_CLIENT_NONE:
248        case RS_MESSAGE_TO_CLIENT_EXCEPTION:
249        case RS_MESSAGE_TO_CLIENT_RESIZE:
250            /*
251             * Teardown. We want to avoid starving other threads during
252             * teardown by yielding until the next line in the destructor can
253             * execute to set mRun = false. Note that the FIFO sends an
254             * empty NONE message when it reaches its destructor.
255             */
256            usleep(1000);
257            break;
258        case RS_MESSAGE_TO_CLIENT_USER:
259            if(rs->mMessageFunc != nullptr) {
260                rs->mMessageFunc(usrID, rbuf, receiveLen);
261            } else {
262                ALOGE("Received a message from the script with no message handler installed.");
263            }
264            break;
265
266        default:
267            ALOGE("RS unknown message type %i", r);
268        }
269    }
270
271    if (rbuf) {
272        free(rbuf);
273    }
274    ALOGV("RS Message thread exiting.");
275    return nullptr;
276}
277
278void RS::setErrorHandler(ErrorHandlerFunc_t func) {
279    mErrorFunc = func;
280}
281
282void RS::setMessageHandler(MessageHandlerFunc_t func) {
283    mMessageFunc  = func;
284}
285
286void RS::finish() {
287    RS::dispatch->ContextFinish(mContext);
288}
289