Skip to content

Instantly share code, notes, and snippets.

@LiewJunTung
Last active July 9, 2019 17:27
Show Gist options
  • Select an option

  • Save LiewJunTung/f93f39ec4e02a97b6e745de78d387abf to your computer and use it in GitHub Desktop.

Select an option

Save LiewJunTung/f93f39ec4e02a97b6e745de78d387abf to your computer and use it in GitHub Desktop.
Best performance
class RsYuvToRgb(private val rs: RenderScript) {
private var mOutputAllocation: Allocation? = null
private var mInputAllocation: Allocation? = null
private val rsYuvToRgb = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs))
private var yArray: ByteArray? = null
private var uArray: ByteArray? = null
private var vArray: ByteArray? = null
private fun ByteBuffer.initByteArray(): ByteArray {
return ByteArray(capacity())
}
fun yuvToRgb(yBuffer: ByteBuffer, uBuffer: ByteBuffer, vBuffer: ByteBuffer, width: Int, height: Int): ByteBuffer {
if (mInputAllocation == null){
val totalSize = yBuffer.capacity() + uBuffer.capacity() + vBuffer.capacity()
val yuvType = Type.Builder(rs, Element.U8(rs)).apply {
setX(totalSize)
}
mInputAllocation = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT)
}
if (mOutputAllocation == null){
val rgbType = Type.createXY(rs, Element.RGBA_8888(rs), width, height)
mOutputAllocation = Allocation.createTyped(rs, rgbType, Allocation.USAGE_SCRIPT)
}
if (yArray == null) {
yArray = yBuffer.initByteArray()
}
if (uArray == null) {
uArray = uBuffer.initByteArray()
}
if (vArray == null) {
vArray = vBuffer.initByteArray()
}
yBuffer.get(yArray)
uBuffer.get(uArray)
vBuffer.get(vArray)
mInputAllocation!!.copy1DRangeFrom(0, yArray!!.size, yArray)
mInputAllocation!!.copy1DRangeFrom(yArray!!.size, uArray!!.size, uArray)
mInputAllocation!!.copy1DRangeFrom(yArray!!.size + uArray!!.size, vArray!!.size, vArray)
rsYuvToRgb.setInput(mInputAllocation)
rsYuvToRgb.forEach(mOutputAllocation)
return mOutputAllocation!!.byteBuffer
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment