1 /* Copyright 2019 The TensorFlow Authors. All Rights Reserved. 2 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 7 http://www.apache.org/licenses/LICENSE-2.0 8 9 Unless required by applicable law or agreed to in writing, software 10 distributed under the License is distributed on an "AS IS" BASIS, 11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 See the License for the specific language governing permissions and 13 limitations under the License. 14 ==============================================================================*/ 15 16 package org.tensorflow.lite.flex; 17 18 import java.io.Closeable; 19 import org.tensorflow.lite.Delegate; 20 import org.tensorflow.lite.annotations.UsedByReflection; 21 22 /** {@link Delegate} for using select TensorFlow ops. */ 23 @UsedByReflection("Interpreter") 24 public class FlexDelegate implements Delegate, Closeable { 25 26 private static final long INVALID_DELEGATE_HANDLE = 0; 27 private static final String TFLITE_FLEX_LIB = "tensorflowlite_flex_jni"; 28 29 private long delegateHandle; 30 31 @UsedByReflection("Interpreter") FlexDelegate()32 public FlexDelegate() { 33 delegateHandle = nativeCreateDelegate(); 34 } 35 36 @Override 37 @UsedByReflection("Interpreter") getNativeHandle()38 public long getNativeHandle() { 39 return delegateHandle; 40 } 41 42 /** 43 * Releases native resources held by the delegate. 44 * 45 * <p>User is expected to call this method explicitly. 46 */ 47 @Override 48 @UsedByReflection("Interpreter") close()49 public void close() { 50 if (delegateHandle != INVALID_DELEGATE_HANDLE) { 51 nativeDeleteDelegate(delegateHandle); 52 delegateHandle = INVALID_DELEGATE_HANDLE; 53 } 54 } 55 initTensorFlowForTesting()56 public static void initTensorFlowForTesting() { 57 nativeInitTensorFlow(); 58 } 59 60 static { 61 System.loadLibrary(TFLITE_FLEX_LIB); 62 } 63 nativeInitTensorFlow()64 private static native long nativeInitTensorFlow(); 65 nativeCreateDelegate()66 private static native long nativeCreateDelegate(); 67 nativeDeleteDelegate(long delegateHandle)68 private static native void nativeDeleteDelegate(long delegateHandle); 69 } 70