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 "stream_wrapper.h" 18 19 const int32_t StreamWrapper::END_OF_STREAM = -1; 20 const int32_t StreamWrapper::DEFAULT_BUFFER_SIZE = 1 << 16; // 64Kb 21 22 StreamWrapper::StreamWrapper() : mEnv(NULL), 23 mStream(NULL), 24 mByteArray(NULL), 25 mBytes(NULL), 26 mByteArrayLen(0) {} 27 28 StreamWrapper::~StreamWrapper() { 29 cleanup(); 30 } 31 32 void StreamWrapper::updateEnv(JNIEnv *env) { 33 if (env == NULL) { 34 LOGE("Cannot update StreamWrapper with a null JNIEnv pointer!"); 35 return; 36 } 37 mEnv = env; 38 } 39 40 bool StreamWrapper::init(JNIEnv *env, jobject stream) { 41 if (mEnv != NULL) { 42 LOGW("StreamWrapper already initialized!"); 43 return false; 44 } 45 mEnv = env; 46 mStream = env->NewGlobalRef(stream); 47 if (mStream == NULL || env->ExceptionCheck()) { 48 cleanup(); 49 return false; 50 } 51 mByteArrayLen = DEFAULT_BUFFER_SIZE; 52 jbyteArray tmp = env->NewByteArray(getBufferSize()); 53 if (tmp == NULL || env->ExceptionCheck()){ 54 cleanup(); 55 return false; 56 } 57 mByteArray = reinterpret_cast<jbyteArray>(env->NewGlobalRef(tmp)); 58 if (mByteArray == NULL || env->ExceptionCheck()){ 59 cleanup(); 60 return false; 61 } 62 mBytes = env->GetByteArrayElements(mByteArray, NULL); 63 if (mBytes == NULL || env->ExceptionCheck()){ 64 cleanup(); 65 return false; 66 } 67 return true; 68 } 69 70 void StreamWrapper::cleanup() { 71 if (mEnv != NULL) { 72 if (mStream != NULL) { 73 mEnv->DeleteGlobalRef(mStream); 74 mStream = NULL; 75 } 76 if (mByteArray != NULL) { 77 if (mBytes != NULL) { 78 mEnv->ReleaseByteArrayElements(mByteArray, mBytes, JNI_ABORT); 79 mBytes = NULL; 80 } 81 mEnv->DeleteGlobalRef(mByteArray); 82 mByteArray = NULL; 83 } else { 84 mBytes = NULL; 85 } 86 mByteArrayLen = 0; 87 mEnv = NULL; 88 } 89 } 90 91 int32_t StreamWrapper::getBufferSize() { 92 return mByteArrayLen; 93 } 94 95 jbyte* StreamWrapper::getBufferPtr() { 96 return mBytes; 97 } 98