1/*
2 * Copyright (C) 2009-2012 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 "rsContext.h"
18#include "rsScriptC.h"
19#include "rsMatrix4x4.h"
20#include "rsMatrix3x3.h"
21#include "rsMatrix2x2.h"
22#include "rsgApiStructs.h"
23
24#include <time.h>
25#include <sstream>
26
27
28namespace android {
29namespace renderscript {
30
31
32//////////////////////////////////////////////////////////////////////////////
33// Math routines
34//////////////////////////////////////////////////////////////////////////////
35
36#if 0
37static float SC_sinf_fast(float x) {
38    const float A =   1.0f / (2.0f * M_PI);
39    const float B = -16.0f;
40    const float C =   8.0f;
41
42    // scale angle for easy argument reduction
43    x *= A;
44
45    if (fabsf(x) >= 0.5f) {
46        // argument reduction
47        x = x - ceilf(x + 0.5f) + 1.0f;
48    }
49
50    const float y = B * x * fabsf(x) + C * x;
51    return 0.2215f * (y * fabsf(y) - y) + y;
52}
53
54static float SC_cosf_fast(float x) {
55    x += float(M_PI / 2);
56
57    const float A =   1.0f / (2.0f * M_PI);
58    const float B = -16.0f;
59    const float C =   8.0f;
60
61    // scale angle for easy argument reduction
62    x *= A;
63
64    if (fabsf(x) >= 0.5f) {
65        // argument reduction
66        x = x - ceilf(x + 0.5f) + 1.0f;
67    }
68
69    const float y = B * x * fabsf(x) + C * x;
70    return 0.2215f * (y * fabsf(y) - y) + y;
71}
72#endif
73
74//////////////////////////////////////////////////////////////////////////////
75// Time routines
76//////////////////////////////////////////////////////////////////////////////
77
78time_t rsrTime(Context *rsc, time_t *timer) {
79    return time(timer);
80}
81
82tm* rsrLocalTime(Context *rsc, tm *local, time_t *timer) {
83    if (!local) {
84      return nullptr;
85    }
86
87    // The native localtime function is not thread-safe, so we
88    // have to apply locking for proper behavior in RenderScript.
89    pthread_mutex_lock(&rsc->gLibMutex);
90    tm *tmp = localtime(timer);
91    memcpy(local, tmp, sizeof(int)*9);
92    pthread_mutex_unlock(&rsc->gLibMutex);
93    return local;
94}
95
96int64_t rsrUptimeMillis(Context *rsc) {
97    return nanoseconds_to_milliseconds(systemTime(SYSTEM_TIME_MONOTONIC));
98}
99
100int64_t rsrUptimeNanos(Context *rsc) {
101    return systemTime(SYSTEM_TIME_MONOTONIC);
102}
103
104float rsrGetDt(Context *rsc, const Script *sc) {
105    int64_t l = sc->mEnviroment.mLastDtTime;
106    sc->mEnviroment.mLastDtTime = systemTime(SYSTEM_TIME_MONOTONIC);
107    return ((float)(sc->mEnviroment.mLastDtTime - l)) / 1.0e9;
108}
109
110//////////////////////////////////////////////////////////////////////////////
111//
112//////////////////////////////////////////////////////////////////////////////
113
114static void SetObjectRef(const Context *rsc, const ObjectBase *dst, const ObjectBase *src) {
115    //ALOGE("setObjectRef  %p,%p  %p", rsc, dst, src);
116    if (src) {
117        CHECK_OBJ(src);
118        src->incSysRef();
119    }
120    if (dst) {
121        CHECK_OBJ(dst);
122        dst->decSysRef();
123    }
124}
125
126// Legacy, remove when drivers are updated
127void rsrClearObject(const Context *rsc, void *dst) {
128    ObjectBase **odst = (ObjectBase **)dst;
129    if (ObjectBase::gDebugReferences) {
130        ALOGE("rsrClearObject  %p,%p", odst, *odst);
131    }
132    if (odst[0]) {
133        CHECK_OBJ(odst[0]);
134        odst[0]->decSysRef();
135    }
136    *odst = nullptr;
137}
138
139void rsrClearObject(rs_object_base *dst) {
140    if (ObjectBase::gDebugReferences) {
141        ALOGE("rsrClearObject  %p,%p", dst, dst->p);
142    }
143    if (dst->p) {
144        CHECK_OBJ(dst->p);
145        dst->p->decSysRef();
146    }
147    dst->p = nullptr;
148}
149
150// Legacy, remove when drivers are updated
151void rsrClearObject(const Context *rsc, rs_object_base *dst) {
152    rsrClearObject(dst);
153}
154
155// Legacy, remove when drivers are updated
156void rsrSetObject(const Context *rsc, void *dst, ObjectBase *src) {
157    if (src == nullptr) {
158        rsrClearObject(rsc, dst);
159        return;
160    }
161
162    ObjectBase **odst = (ObjectBase **)dst;
163    if (ObjectBase::gDebugReferences) {
164        ALOGE("rsrSetObject (base) %p,%p  %p", dst, *odst, src);
165    }
166    SetObjectRef(rsc, odst[0], src);
167    src->callUpdateCacheObject(rsc, dst);
168}
169
170void rsrSetObject(const Context *rsc, rs_object_base *dst, const ObjectBase *src) {
171    if (src == nullptr) {
172        rsrClearObject(rsc, dst);
173        return;
174    }
175
176    ObjectBase **odst = (ObjectBase **)dst;
177    if (ObjectBase::gDebugReferences) {
178        ALOGE("rsrSetObject (base) %p,%p  %p", dst, *odst, src);
179    }
180    SetObjectRef(rsc, odst[0], src);
181    src->callUpdateCacheObject(rsc, dst);
182}
183
184// Legacy, remove when drivers are updated
185bool rsrIsObject(const Context *, ObjectBase* src) {
186    ObjectBase **osrc = (ObjectBase **)src;
187    return osrc != nullptr;
188}
189
190bool rsrIsObject(const Context *rsc, rs_object_base o) {
191    return o.p != nullptr;
192}
193
194
195
196uint32_t rsrToClient(Context *rsc, int cmdID, const void *data, int len) {
197    //ALOGE("SC_toClient %i %i %i", cmdID, len);
198    return rsc->sendMessageToClient(data, RS_MESSAGE_TO_CLIENT_USER, cmdID, len, false);
199}
200
201uint32_t rsrToClientBlocking(Context *rsc, int cmdID, const void *data, int len) {
202    //ALOGE("SC_toClientBlocking %i %i", cmdID, len);
203    return rsc->sendMessageToClient(data, RS_MESSAGE_TO_CLIENT_USER, cmdID, len, true);
204}
205
206// Keep these two routines (using non-const void pointers) so that we can
207// still use existing GPU drivers.
208uint32_t rsrToClient(Context *rsc, int cmdID, void *data, int len) {
209    return rsrToClient(rsc, cmdID, (const void *)data, len);
210}
211
212uint32_t rsrToClientBlocking(Context *rsc, int cmdID, void *data, int len) {
213    return rsrToClientBlocking(rsc, cmdID, (const void *)data, len);
214}
215
216void rsrAllocationIoSend(Context *rsc, Allocation *src) {
217    src->ioSend(rsc);
218}
219
220void rsrAllocationIoReceive(Context *rsc, Allocation *src) {
221    src->ioReceive(rsc);
222}
223
224void rsrForEach(Context *rsc,
225                Script *target,
226                uint32_t slot,
227                uint32_t numInputs,
228                Allocation **in, Allocation *out,
229                const void *usr, uint32_t usrBytes,
230                const RsScriptCall *call) {
231    target->runForEach(rsc, slot, (const Allocation**)in, numInputs, out, usr, usrBytes, call);
232}
233
234void rsrAllocationSyncAll(Context *rsc, Allocation *a, RsAllocationUsageType usage) {
235    a->syncAll(rsc, usage);
236}
237
238// Helper for validateCopyArgs() - initialize the error message; only called on
239// infrequently executed paths
240static void initializeErrorMsg(std::stringstream &ss, int expectDim, bool isSrc) {
241    ss << (expectDim == 1 ? "rsAllocationCopy1DRange" : "rsAllocationCopy2DRange") << ": ";
242    ss << (isSrc? "source" : "destination") << " ";
243}
244
245// We are doing the check even in a non-debug context, which is permissible because in that case
246// a failed bound check results in unspecified behavior.
247static bool validateCopyArgs(Context *rsc, bool isSrc, uint32_t expectDim,
248                             const Allocation *alloc, uint32_t xoff, uint32_t yoff,
249                             uint32_t lod, uint32_t w, uint32_t h) {
250    std::stringstream ss;
251
252    if (lod >= alloc->mHal.drvState.lodCount) {
253        initializeErrorMsg(ss, expectDim, isSrc);
254        ss << "Mip level out of range: ";
255        ss << lod << " >= " << alloc->mHal.drvState.lodCount;
256        rsc->setError(RS_ERROR_FATAL_DEBUG, ss.str().c_str());
257        return false;
258    }
259
260    const uint32_t allocDimX = alloc->mHal.drvState.lod[lod].dimX;
261
262    // Check both in case xoff + w overflows
263    if (xoff >= allocDimX || (xoff + w) > allocDimX) {
264        initializeErrorMsg(ss, expectDim, isSrc);
265        ss << "X range: ";
266        ss << "[" << xoff << ", " << xoff + w << ") outside ";
267        ss << "[0, " << allocDimX << ")";
268        rsc->setError(RS_ERROR_FATAL_DEBUG, ss.str().c_str());
269        return false;
270    }
271
272    const uint32_t allocDimY = alloc->mHal.drvState.lod[lod].dimY;
273
274    if (expectDim > 1) {
275        if (allocDimY == 0) {  // Copy2D was given an allocation of 1D
276            initializeErrorMsg(ss, expectDim, isSrc);
277            ss << "dimensionality invalid: expected 2D; given 1D rs_allocation";
278            rsc->setError(RS_ERROR_FATAL_DEBUG, ss.str().c_str());
279            return false;
280        }
281        // Check both in case yoff + h overflows
282        if (yoff >= allocDimY || (yoff + h) > allocDimY) {
283            initializeErrorMsg(ss, expectDim, isSrc);
284            ss << "Y range: ";
285            ss << "[" << yoff << ", " << yoff + h << ") outside ";
286            ss << "[0, " << allocDimY << ")";
287            rsc->setError(RS_ERROR_FATAL_DEBUG, ss.str().c_str());
288            return false;
289        }
290    } else {
291        if (allocDimY != 0) {  // Copy1D was given an allocation of 2D
292            initializeErrorMsg(ss, expectDim, isSrc);
293            ss << "dimensionality invalid: expected 1D; given 2D rs_allocation";
294            rsc->setError(RS_ERROR_FATAL_DEBUG, ss.str().c_str());
295            return false;
296        }
297    }
298
299    return true;
300}
301
302void rsrAllocationCopy1DRange(Context *rsc, Allocation *dstAlloc,
303                              uint32_t dstOff,
304                              uint32_t dstMip,
305                              uint32_t count,
306                              Allocation *srcAlloc,
307                              uint32_t srcOff, uint32_t srcMip) {
308    if (!validateCopyArgs(rsc, false, 1, dstAlloc, dstOff, 0, dstMip, count, 1) ||
309        !validateCopyArgs(rsc, true, 1, srcAlloc, srcOff, 0, srcMip, count, 1)) {
310        return;
311    }
312    rsi_AllocationCopy2DRange(rsc, dstAlloc, dstOff, 0,
313                              dstMip, 0, count, 1,
314                              srcAlloc, srcOff, 0, srcMip, 0);
315}
316
317void rsrAllocationCopy2DRange(Context *rsc, Allocation *dstAlloc,
318                              uint32_t dstXoff, uint32_t dstYoff,
319                              uint32_t dstMip, uint32_t dstFace,
320                              uint32_t width, uint32_t height,
321                              Allocation *srcAlloc,
322                              uint32_t srcXoff, uint32_t srcYoff,
323                              uint32_t srcMip, uint32_t srcFace) {
324    if (!validateCopyArgs(rsc, false, 2, dstAlloc, dstXoff, dstYoff, dstMip, width, height) ||
325        !validateCopyArgs(rsc, true, 2, srcAlloc, srcXoff, srcYoff, srcMip, width, height)) {
326        return;
327    }
328
329    rsi_AllocationCopy2DRange(rsc, dstAlloc, dstXoff, dstYoff,
330                              dstMip, dstFace, width, height,
331                              srcAlloc, srcXoff, srcYoff, srcMip, srcFace);
332}
333
334RsElement rsrElementCreate(Context *rsc, RsDataType dt, RsDataKind dk,
335                           bool norm, uint32_t vecSize) {
336    return rsi_ElementCreate(rsc, dt, dk, norm, vecSize);
337}
338
339RsType rsrTypeCreate(Context *rsc, const RsElement element, uint32_t dimX,
340                     uint32_t dimY, uint32_t dimZ, bool mipmaps, bool faces,
341                     uint32_t yuv) {
342    return rsi_TypeCreate(rsc, element, dimX, dimY, dimZ, mipmaps, faces, yuv);
343}
344
345RsAllocation rsrAllocationCreateTyped(Context *rsc, const RsType type,
346                                      RsAllocationMipmapControl mipmaps,
347                                      uint32_t usages, uintptr_t ptr) {
348    return rsi_AllocationCreateTyped(rsc, type, mipmaps, usages, ptr);
349}
350
351} // namespace renderscript
352} // namespace android
353