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 package org.tensorflow.lite; 16 17 import android.content.Context; 18 import java.io.Closeable; 19 20 /** {@link Delegate} for Hexagon inference. */ 21 public class HexagonDelegate implements Delegate, Closeable { 22 23 private static final long INVALID_DELEGATE_HANDLE = 0; 24 private static final String TFLITE_HEXAGON_LIB = "tensorflowlite_hexagon_jni"; 25 private static volatile boolean nativeLibraryLoaded = false; 26 27 private long delegateHandle; 28 29 /* 30 * Creates a new HexagonDelegate object given the current 'context'. 31 * Throws UnsupportedOperationException if Hexagon DSP delegation is not available 32 * on this device. 33 */ HexagonDelegate(Context context)34 public HexagonDelegate(Context context) throws UnsupportedOperationException { 35 ensureNativeLibraryLoaded(); 36 setAdspLibraryPath(context.getApplicationInfo().nativeLibraryDir); 37 delegateHandle = createDelegate(); 38 if (delegateHandle == INVALID_DELEGATE_HANDLE) { 39 throw new UnsupportedOperationException("This Device doesn't support Hexagon DSP execution."); 40 } 41 } 42 43 @Override getNativeHandle()44 public long getNativeHandle() { 45 return delegateHandle; 46 } 47 48 /** 49 * Frees TFLite resources in C runtime. 50 * 51 * <p>User is expected to call this method explicitly. 52 */ 53 @Override close()54 public void close() { 55 if (delegateHandle != INVALID_DELEGATE_HANDLE) { 56 deleteDelegate(delegateHandle); 57 delegateHandle = INVALID_DELEGATE_HANDLE; 58 } 59 } 60 ensureNativeLibraryLoaded()61 private static void ensureNativeLibraryLoaded() { 62 if (nativeLibraryLoaded) { 63 return; 64 } 65 try { 66 System.loadLibrary(TFLITE_HEXAGON_LIB); 67 nativeLibraryLoaded = true; 68 } catch (Exception e) { 69 throw new UnsupportedOperationException("Failed to load native Hexagon shared library: " + e); 70 } 71 } 72 createDelegate()73 private static native long createDelegate(); 74 deleteDelegate(long delegateHandle)75 private static native void deleteDelegate(long delegateHandle); 76 setAdspLibraryPath(String libraryPath)77 private static native boolean setAdspLibraryPath(String libraryPath); 78 } 79