RenderScript.cpp revision 48d2eae90f08dc33754a9d280337249690a954d6
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(HAVE_ANDROID_OS)
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            RS::dispatch->ContextDeinitToClient(mContext);
63
64            void *res = nullptr;
65            int status = pthread_join(mMessageThreadId, &res);
66
67            RS::dispatch->ContextDestroy(mContext);
68            mContext = nullptr;
69        }
70        if (mDev) {
71            RS::dispatch->DeviceDestroy(mDev);
72            mDev = nullptr;
73        }
74    }
75}
76
77bool RS::init(std::string name, uint32_t flags) {
78    return RS::init(name, RS_VERSION, flags);
79}
80
81// this will only open API 19+ libRS
82// because that's when we changed libRS to extern "C" entry points
83static bool loadSO(const char* filename) {
84    void* handle = dlopen(filename, RTLD_LAZY | RTLD_LOCAL);
85    if (handle == nullptr) {
86        ALOGV("couldn't dlopen %s, %s", filename, dlerror());
87        return false;
88    }
89
90    if (loadSymbols(handle, *RS::dispatch) == false) {
91        ALOGV("%s init failed!", filename);
92        return false;
93    }
94    //ALOGE("Successfully loaded %s", filename);
95    return true;
96}
97
98static uint32_t getProp(const char *str) {
99#if !defined(__LP64__) && !defined(RS_SERVER) && defined(HAVE_ANDROID_OS)
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");
123    }
124    if (usingNative == false) {
125        if (loadSO("libRSSupport.so") == 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(std::string &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    mCacheDir = name;
153
154    mDev = RS::dispatch->DeviceCreate();
155    if (mDev == 0) {
156        ALOGE("Device creation failed");
157        return false;
158    }
159
160    if (flags & ~(RS_CONTEXT_SYNCHRONOUS | RS_CONTEXT_LOW_LATENCY |
161                  RS_CONTEXT_LOW_POWER)) {
162        ALOGE("Invalid flags passed");
163        return false;
164    }
165
166    mContext = RS::dispatch->ContextCreate(mDev, 0, targetApi, RS_CONTEXT_TYPE_NORMAL, flags);
167    if (mContext == 0) {
168        ALOGE("Context creation failed");
169        return false;
170    }
171
172    pid_t mNativeMessageThreadId;
173
174    int status = pthread_create(&mMessageThreadId, nullptr, threadProc, this);
175    if (status) {
176        ALOGE("Failed to start RS message thread.");
177        return false;
178    }
179    // Wait for the message thread to be active.
180    while (!mMessageRun) {
181        usleep(1000);
182    }
183
184    mInit = true;
185
186    return true;
187}
188
189void RS::throwError(RSError error, const char *errMsg) {
190    if (mCurrentError == RS_SUCCESS) {
191        mCurrentError = error;
192        ALOGE("RS CPP error: %s", errMsg);
193    } else {
194        ALOGE("RS CPP error (masked by previous error): %s", errMsg);
195    }
196}
197
198RSError RS::getError() {
199    return mCurrentError;
200}
201
202
203void * RS::threadProc(void *vrsc) {
204    RS *rs = static_cast<RS *>(vrsc);
205    size_t rbuf_size = 256;
206    void * rbuf = malloc(rbuf_size);
207
208    RS::dispatch->ContextInitToClient(rs->mContext);
209    rs->mMessageRun = true;
210
211    while (rs->mMessageRun) {
212        size_t receiveLen = 0;
213        uint32_t usrID = 0;
214        uint32_t subID = 0;
215        RsMessageToClientType r = RS::dispatch->ContextPeekMessage(rs->mContext,
216                                                                   &receiveLen, sizeof(receiveLen),
217                                                                   &usrID, sizeof(usrID));
218
219        if (receiveLen >= rbuf_size) {
220            rbuf_size = receiveLen + 32;
221            rbuf = realloc(rbuf, rbuf_size);
222        }
223        if (!rbuf) {
224            ALOGE("RS::message handler realloc error %zu", rbuf_size);
225            // No clean way to recover now?
226        }
227        RS::dispatch->ContextGetMessage(rs->mContext, rbuf, rbuf_size, &receiveLen, sizeof(receiveLen),
228                            &subID, sizeof(subID));
229
230        switch(r) {
231        case RS_MESSAGE_TO_CLIENT_ERROR:
232            ALOGE("RS Error %s", (const char *)rbuf);
233            rs->throwError(RS_ERROR_RUNTIME_ERROR, "Error returned from runtime");
234            if(rs->mMessageFunc != nullptr) {
235                rs->mErrorFunc(usrID, (const char *)rbuf);
236            }
237            break;
238        case RS_MESSAGE_TO_CLIENT_NONE:
239        case RS_MESSAGE_TO_CLIENT_EXCEPTION:
240        case RS_MESSAGE_TO_CLIENT_RESIZE:
241            // teardown. But we want to avoid starving other threads during
242            // teardown by yielding until the next line in the destructor can
243            // execute to set mRun = false. Note that the FIFO sends an
244            // empty NONE message when it reaches its destructor.
245            usleep(1000);
246            break;
247        case RS_MESSAGE_TO_CLIENT_USER:
248            if(rs->mMessageFunc != nullptr) {
249                rs->mMessageFunc(usrID, rbuf, receiveLen);
250            } else {
251                ALOGE("Received a message from the script with no message handler installed.");
252            }
253            break;
254
255        default:
256            ALOGE("RS unknown message type %i", r);
257        }
258    }
259
260    if (rbuf) {
261        free(rbuf);
262    }
263    ALOGV("RS Message thread exiting.");
264    return nullptr;
265}
266
267void RS::setErrorHandler(ErrorHandlerFunc_t func) {
268    mErrorFunc = func;
269}
270
271void RS::setMessageHandler(MessageHandlerFunc_t func) {
272    mMessageFunc  = func;
273}
274
275void RS::finish() {
276    RS::dispatch->ContextFinish(mContext);
277}
278