1 /*
2  * Copyright (C) 2021 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 package com.example.testapp
18 
19 import android.graphics.ImageFormat
20 import android.renderscript.Allocation
21 import android.renderscript.Element
22 import android.renderscript.RenderScript
23 import android.renderscript.ScriptIntrinsicYuvToRGB
24 import android.renderscript.Type
25 import android.renderscript.toolkit.YuvFormat
26 
27 /**
28  * Does a YUV to RGB operation using the RenderScript Intrinsics.
29  */
intrinsicYuvToRgbnull30 fun intrinsicYuvToRgb(
31     context: RenderScript,
32     inputArray: ByteArray,
33     sizeX: Int,
34     sizeY: Int,
35     format: YuvFormat
36 ): ByteArray {
37     val scriptYuvToRgb = ScriptIntrinsicYuvToRGB.create(
38         context,
39         Element.YUV(context)
40     )
41     val inputBuilder = Type.Builder(context, Element.YUV(context))
42     inputBuilder.setX(sizeX)
43     inputBuilder.setY(sizeY)
44     when (format) {
45         YuvFormat.NV21 -> inputBuilder.setYuvFormat(ImageFormat.NV21)
46         YuvFormat.YV12 -> inputBuilder.setYuvFormat(ImageFormat.YV12)
47         else -> require(false) { "Unknown YUV format $format" }
48     }
49     val inputArrayType = inputBuilder.create()
50     val inputAllocation = Allocation.createTyped(context, inputArrayType)
51 
52     val outputBuilder = Type.Builder(context, Element.U8_4(context))
53     outputBuilder.setX(sizeX)
54     outputBuilder.setY(sizeY)
55     val outputArrayType = outputBuilder.create()
56     val outAllocation = Allocation.createTyped(context, outputArrayType)
57     val intrinsicOutArray = ByteArray(sizeX * sizeY * 4)
58 
59     inputAllocation.copyFrom(inputArray)
60     scriptYuvToRgb.setInput(inputAllocation)
61     scriptYuvToRgb.forEach(outAllocation)
62     outAllocation.copyTo(intrinsicOutArray)
63 
64     inputAllocation.destroy()
65     outAllocation.destroy()
66     inputArrayType.destroy()
67     outputArrayType.destroy()
68     scriptYuvToRgb.destroy()
69     return intrinsicOutArray
70 }
71