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#ifndef RASTERMILL_STREAM_H
18#define RASTERMILL_STREAM_H
19
20#include <jni.h>
21#include <stdio.h>
22#include <sys/types.h>
23
24class Stream {
25public:
26    Stream();
27    virtual ~Stream();
28
29    size_t peek(void* buffer, size_t size);
30    size_t read(void* buffer, size_t size);
31    virtual uint8_t* getRawBufferAddr();
32    virtual jobject getRawBuffer();
33    virtual int getRawBufferSize();
34
35protected:
36    virtual size_t doRead(void* buffer, size_t size) = 0;
37
38private:
39    char* mPeekBuffer;
40    size_t mPeekSize;
41    size_t mPeekOffset;
42};
43
44class MemoryStream : public Stream {
45public:
46    MemoryStream(void* buffer, size_t size, jobject buf) :
47            mBuffer((uint8_t*)buffer),
48            mRemaining(size),
49            mRawBuffer(buf) {}
50    virtual uint8_t* getRawBufferAddr();
51    virtual jobject getRawBuffer();
52    virtual int getRawBufferSize();
53
54protected:
55    virtual size_t doRead(void* buffer, size_t size);
56
57private:
58    uint8_t* mBuffer;
59    size_t mRemaining;
60    jobject mRawBuffer;
61};
62
63class FileStream : public Stream {
64public:
65    FileStream(FILE* fd) : mFd(fd) {}
66
67protected:
68    virtual size_t doRead(void* buffer, size_t size);
69
70private:
71    FILE* mFd;
72};
73
74class JavaInputStream : public Stream {
75public:
76    JavaInputStream(JNIEnv* env, jobject inputStream, jbyteArray byteArray) :
77            mEnv(env),
78            mInputStream(inputStream),
79            mByteArray(byteArray),
80            mByteArrayLength(env->GetArrayLength(byteArray)) {}
81
82protected:
83    virtual size_t doRead(void* buffer, size_t size);
84
85private:
86    JNIEnv* mEnv;
87    const jobject mInputStream;
88    const jbyteArray mByteArray;
89    const size_t mByteArrayLength;
90};
91
92jint JavaStream_OnLoad(JNIEnv* env);
93
94#endif //RASTERMILL_STREAM_H
95