|
| 1 | +/* |
| 2 | + * Copyright 2024 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 | + * https://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 | +package com.example.platform.media.video; |
| 18 | + |
| 19 | +import android.content.Context; |
| 20 | +import android.graphics.Bitmap; |
| 21 | +import android.graphics.BitmapFactory; |
| 22 | +import android.opengl.GLES20; |
| 23 | +import android.opengl.GLUtils; |
| 24 | +import android.util.Log; |
| 25 | + |
| 26 | +import androidx.media3.common.VideoFrameProcessingException; |
| 27 | +import androidx.media3.common.util.GlProgram; |
| 28 | +import androidx.media3.common.util.GlUtil; |
| 29 | +import androidx.media3.common.util.Size; |
| 30 | +import androidx.media3.common.util.UnstableApi; |
| 31 | +import androidx.media3.effect.BaseGlShaderProgram; |
| 32 | + |
| 33 | +import com.google.common.collect.ImmutableMap; |
| 34 | + |
| 35 | +import org.tensorflow.lite.DataType; |
| 36 | +import org.tensorflow.lite.Interpreter; |
| 37 | +import org.tensorflow.lite.InterpreterApi; |
| 38 | +import org.tensorflow.lite.gpu.CompatibilityList; |
| 39 | +import org.tensorflow.lite.gpu.GpuDelegate; |
| 40 | +import org.tensorflow.lite.support.common.FileUtil; |
| 41 | +import org.tensorflow.lite.support.common.ops.DequantizeOp; |
| 42 | +import org.tensorflow.lite.support.common.ops.NormalizeOp; |
| 43 | +import org.tensorflow.lite.support.image.ImageProcessor; |
| 44 | +import org.tensorflow.lite.support.image.TensorImage; |
| 45 | +import org.tensorflow.lite.support.image.ops.ResizeOp; |
| 46 | +import org.tensorflow.lite.support.image.ops.ResizeWithCropOrPadOp; |
| 47 | +import org.tensorflow.lite.support.tensorbuffer.TensorBuffer; |
| 48 | + |
| 49 | +import java.io.IOException; |
| 50 | +import java.io.InputStream; |
| 51 | +import java.nio.ByteBuffer; |
| 52 | + |
| 53 | +import javax.microedition.khronos.opengles.GL10; |
| 54 | + |
| 55 | +// TODO: Migrate this class to Kotlin |
| 56 | +@UnstableApi |
| 57 | +final class StyleTransferShaderProgram extends BaseGlShaderProgram { |
| 58 | + |
| 59 | + private static final String TAG = "StyleTransferSP"; |
| 60 | + private static final String VERTEX_SHADER_PATH = "shaders/vertex_shader_transformation_es2.glsl"; |
| 61 | + private static final String FRAGMENT_SHADER_PATH = "shaders/fragment_shader_copy_es2.glsl"; |
| 62 | + |
| 63 | + private final GlProgram glProgram; |
| 64 | + private final InterpreterApi transformInterpreter; |
| 65 | + private final int inputTransformTargetHeight; |
| 66 | + private final int inputTransformTargetWidth; |
| 67 | + private final int[] outputTransformShape; |
| 68 | + |
| 69 | + private final TensorBuffer predictOutput; |
| 70 | + |
| 71 | + private int width; |
| 72 | + private int height; |
| 73 | + |
| 74 | + public StyleTransferShaderProgram(Context context, String styleAssetFileName) |
| 75 | + throws VideoFrameProcessingException { |
| 76 | + super(/* useHighPrecisionColorComponents= */ false, /* texturePoolCapacity= */ 1); |
| 77 | + |
| 78 | + try { |
| 79 | + glProgram = new GlProgram(context, VERTEX_SHADER_PATH, FRAGMENT_SHADER_PATH); |
| 80 | + |
| 81 | + Interpreter.Options options = new Interpreter.Options(); |
| 82 | + |
| 83 | + CompatibilityList compatibilityList = new CompatibilityList(); |
| 84 | + if (compatibilityList.isDelegateSupportedOnThisDevice()) { |
| 85 | + GpuDelegate.Options gpuDelegateOptions = compatibilityList.getBestOptionsForThisDevice(); |
| 86 | + GpuDelegate gpuDelegate = new GpuDelegate(gpuDelegateOptions); |
| 87 | + options.addDelegate(gpuDelegate); |
| 88 | + } else { |
| 89 | + options.setNumThreads(6); |
| 90 | + } |
| 91 | + String predictModel = "predict_float16.tflite"; |
| 92 | + String transferModel = "transfer_float16.tflite"; |
| 93 | + Interpreter predictInterpeter = |
| 94 | + new Interpreter(FileUtil.loadMappedFile(context, predictModel), options); |
| 95 | + transformInterpreter = |
| 96 | + InterpreterApi.create(FileUtil.loadMappedFile(context, transferModel), options); |
| 97 | + int inputPredictTargetHeight = predictInterpeter.getInputTensor(0).shape()[1]; |
| 98 | + int inputPredictTargetWidth = predictInterpeter.getInputTensor(0).shape()[2]; |
| 99 | + int[] outputPredictShape = predictInterpeter.getOutputTensor(0).shape(); |
| 100 | + |
| 101 | + inputTransformTargetHeight = transformInterpreter.getInputTensor(0).shape()[1]; |
| 102 | + inputTransformTargetWidth = transformInterpreter.getInputTensor(0).shape()[2]; |
| 103 | + outputTransformShape = transformInterpreter.getOutputTensor(0).shape(); |
| 104 | + |
| 105 | + InputStream inputStream = context.getAssets().open(styleAssetFileName); |
| 106 | + Bitmap styleImage = BitmapFactory.decodeStream(inputStream); |
| 107 | + inputStream.close(); |
| 108 | + TensorImage styleTensorImage = |
| 109 | + getScaledTensorImage(styleImage, inputPredictTargetWidth, inputPredictTargetHeight); |
| 110 | + predictOutput = TensorBuffer.createFixedSize(outputPredictShape, DataType.FLOAT32); |
| 111 | + predictInterpeter.run(styleTensorImage.getBuffer(), predictOutput.getBuffer()); |
| 112 | + } catch (IOException | GlUtil.GlException e) { |
| 113 | + Log.w(TAG, "Error setting up TfShaderProgram", e); |
| 114 | + throw new VideoFrameProcessingException(e); |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + @Override |
| 119 | + public Size configure(int inputWidth, int inputHeight) { |
| 120 | + width = inputWidth; |
| 121 | + height = inputHeight; |
| 122 | + return new Size(inputWidth, inputHeight); |
| 123 | + } |
| 124 | + |
| 125 | + @Override |
| 126 | + public void drawFrame(int inputTexId, long presentationTimeUs) |
| 127 | + throws VideoFrameProcessingException { |
| 128 | + ByteBuffer pixelBuffer = ByteBuffer.allocateDirect(width * height * 4); |
| 129 | + |
| 130 | + Bitmap bitmap; |
| 131 | + int texId; |
| 132 | + try { |
| 133 | + int[] boundFramebuffer = new int[1]; |
| 134 | + GLES20.glGetIntegerv(GLES20.GL_FRAMEBUFFER_BINDING, boundFramebuffer, /* offset= */ 0); |
| 135 | + |
| 136 | + int fboId = GlUtil.createFboForTexture(inputTexId); |
| 137 | + GlUtil.focusFramebufferUsingCurrentContext(fboId, width, height); |
| 138 | + GLES20.glReadPixels( |
| 139 | + /* x= */ 0, |
| 140 | + /* y= */ 0, |
| 141 | + width, |
| 142 | + height, |
| 143 | + GLES20.GL_RGBA, |
| 144 | + GLES20.GL_UNSIGNED_BYTE, |
| 145 | + pixelBuffer); |
| 146 | + GlUtil.checkGlError(); |
| 147 | + bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); |
| 148 | + bitmap.copyPixelsFromBuffer(pixelBuffer); |
| 149 | + |
| 150 | + Log.w(TAG, "Process frame at " + (presentationTimeUs / 1000) + " ms"); |
| 151 | + long before = System.currentTimeMillis(); |
| 152 | + TensorImage tensorImage = |
| 153 | + getScaledTensorImage(bitmap, inputTransformTargetWidth, inputTransformTargetHeight); |
| 154 | + Log.w(TAG, "- Scale " + (System.currentTimeMillis() - before) + " ms"); |
| 155 | + TensorBuffer outputImage = |
| 156 | + TensorBuffer.createFixedSize(outputTransformShape, DataType.FLOAT32); |
| 157 | + |
| 158 | + before = System.currentTimeMillis(); |
| 159 | + transformInterpreter.runForMultipleInputsOutputs( |
| 160 | + new Object[] {tensorImage.getBuffer(), predictOutput.getBuffer()}, |
| 161 | + ImmutableMap.<Integer, Object>builder().put(0, outputImage.getBuffer()).build()); |
| 162 | + |
| 163 | + Log.w(TAG, "- Run " + (System.currentTimeMillis() - before) + " ms"); |
| 164 | + |
| 165 | + before = System.currentTimeMillis(); |
| 166 | + ImageProcessor imagePostProcessor = |
| 167 | + new ImageProcessor.Builder() |
| 168 | + .add(new DequantizeOp(/* zeroPoint= */ 0f, /* scale= */ 255f)) |
| 169 | + .build(); |
| 170 | + TensorImage outputTensorImage = new TensorImage(DataType.FLOAT32); |
| 171 | + outputTensorImage.load(outputImage); |
| 172 | + Log.w(TAG, "- Load output " + (System.currentTimeMillis() - before) + " ms"); |
| 173 | + |
| 174 | + before = System.currentTimeMillis(); |
| 175 | + Bitmap outputBitmap = imagePostProcessor.process(outputTensorImage).getBitmap(); |
| 176 | + Log.w(TAG, "- Post process output " + (System.currentTimeMillis() - before) + " ms"); |
| 177 | + |
| 178 | + texId = |
| 179 | + GlUtil.createTexture( |
| 180 | + outputBitmap.getWidth(), |
| 181 | + outputBitmap.getHeight(), |
| 182 | + /* useHighPrecisionColorComponents= */ false); |
| 183 | + GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texId); |
| 184 | + GLES20.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); |
| 185 | + GLES20.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); |
| 186 | + GLES20.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); |
| 187 | + GLES20.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); |
| 188 | + GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, /* level= */ 0, outputBitmap, /* border= */ 0); |
| 189 | + GlUtil.checkGlError(); |
| 190 | + |
| 191 | + GlUtil.focusFramebufferUsingCurrentContext(boundFramebuffer[0], width, height); |
| 192 | + |
| 193 | + glProgram.use(); |
| 194 | + glProgram.setSamplerTexIdUniform("uTexSampler", texId, /* texUnitIndex= */ 0); |
| 195 | + float[] identityMatrix = GlUtil.create4x4IdentityMatrix(); |
| 196 | + glProgram.setFloatsUniform("uTexTransformationMatrix", identityMatrix); |
| 197 | + glProgram.setFloatsUniform("uTransformationMatrix", identityMatrix); |
| 198 | + glProgram.setBufferAttribute( |
| 199 | + "aFramePosition", |
| 200 | + GlUtil.getNormalizedCoordinateBounds(), |
| 201 | + GlUtil.HOMOGENEOUS_COORDINATE_VECTOR_SIZE); |
| 202 | + glProgram.bindAttributesAndUniforms(); |
| 203 | + |
| 204 | + GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, /* first= */ 0, /* count= */ 4); |
| 205 | + GlUtil.checkGlError(); |
| 206 | + |
| 207 | + GlUtil.deleteTexture(texId); |
| 208 | + } catch (GlUtil.GlException e) { |
| 209 | + throw VideoFrameProcessingException.from(e); |
| 210 | + } |
| 211 | + } |
| 212 | + |
| 213 | + private static TensorImage getScaledTensorImage( |
| 214 | + Bitmap bitmap, int targetWidth, int targetHeight) { |
| 215 | + int cropSize = Math.min(bitmap.getWidth(), bitmap.getHeight()); |
| 216 | + ImageProcessor imageProcessor = |
| 217 | + new ImageProcessor.Builder() |
| 218 | + .add(new ResizeWithCropOrPadOp(cropSize, cropSize)) |
| 219 | + .add( |
| 220 | + new ResizeOp( |
| 221 | + targetHeight, |
| 222 | + targetWidth, |
| 223 | + ResizeOp.ResizeMethod.BILINEAR)) // TODO: Not sure why they are swapped? |
| 224 | + .add(new NormalizeOp(/* mean= */ 0f, /* stddev= */ 255f)) |
| 225 | + .build(); |
| 226 | + TensorImage tensorImage = new TensorImage(DataType.FLOAT32); |
| 227 | + tensorImage.load(bitmap); |
| 228 | + return imageProcessor.process(tensorImage); |
| 229 | + } |
| 230 | +} |
0 commit comments