AvifImageDecoder.kt
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/image/AvifImageDecoder.kt
1package eu.friedcutlet.yokan.ui.image23import coil3.ImageLoader4import coil3.asImage5import coil3.decode.DecodeResult6import coil3.decode.DecodeUtils7import coil3.decode.Decoder8import coil3.decode.ImageSource9import coil3.fetch.SourceFetchResult10import coil3.request.Options11import coil3.request.maxBitmapSize12import coil3.size.Scale13import coil3.size.isOriginal14import coil3.size.pxOrElse15import kotlinx.coroutines.Dispatchers16import kotlinx.coroutines.ensureActive17import kotlinx.coroutines.sync.Semaphore18import kotlinx.coroutines.sync.withPermit19import kotlinx.coroutines.withContext20import okio.BufferedSource21import org.glavo.avif.AvifImageReaderFactory22import org.glavo.avif.AvifPixelFormat23import org.glavo.avif.av1.Av1DecoderConfig24import org.jetbrains.skia.Bitmap25import org.jetbrains.skia.Canvas26import org.jetbrains.skia.ColorAlphaType27import org.jetbrains.skia.ColorType28import org.jetbrains.skia.Image29import org.jetbrains.skia.ImageInfo30import org.jetbrains.skia.Rect31import java.io.IOException32import kotlin.coroutines.coroutineContext3334/** First-frame AVIF decoding for reader pages, covers, local files and cached responses. */35internal class AvifImageDecoder(36 private val source: ImageSource,37 private val options: Options,38) : Decoder {39 override suspend fun decode(): DecodeResult = decodePermit.withPermit {40 withContext(Dispatchers.Default) {41 coroutineContext.ensureActive()42 val bytes = source.source().use {43 if (it.request(MAX_INPUT_BYTES + 1)) throw IOException("AVIF exceeds encoded image size limit")44 it.readByteArray()45 }46 val frame = readerFactory.open(bytes).use { reader ->47 val info = reader.info()48 if (info.width().toLong() * info.height() > MAX_PIXELS) {49 throw IOException("AVIF exceeds decoded image size limit")50 }51 requireNotNull(reader.readFrame()) { "AVIF contains no image frame" }52 }53 coroutineContext.ensureActive()54 val width = frame.width()55 val height = frame.height()56 val pixels = frame.intPixelBuffer()57 val rgba = ByteArray(width * height * 4)58 repeat(width * height) { index ->59 val argb = pixels.get(index)60 val offset = index * 461 rgba[offset] = (argb ushr 16).toByte()62 rgba[offset + 1] = (argb ushr 8).toByte()63 rgba[offset + 2] = argb.toByte()64 rgba[offset + 3] = (argb ushr 24).toByte()65 }66 val undefinedDimension = if (options.scale == Scale.FIT) Int.MAX_VALUE else 067 val targetWidth = if (options.size.isOriginal) width else options.size.width.pxOrElse { undefinedDimension }68 val targetHeight = if (options.size.isOriginal) height else options.size.height.pxOrElse { undefinedDimension }69 val multiplier = DecodeUtils.computeSizeMultiplier(70 width, height, targetWidth, targetHeight, options.scale, options.maxBitmapSize,71 ).coerceAtMost(1.0)72 val outWidth = (width * multiplier).toInt().coerceAtLeast(1)73 val outHeight = (height * multiplier).toInt().coerceAtLeast(1)74 val output = Bitmap()75 try {76 Bitmap().use { original ->77 check(original.installPixels(78 ImageInfo(width, height, ColorType.RGBA_8888, ColorAlphaType.UNPREMUL),79 rgba, width * 4,80 )) { "Unable to allocate AVIF pixels" }81 check(output.allocN32Pixels(outWidth, outHeight)) { "Unable to allocate AVIF bitmap" }82 output.erase(0) // Source-over must preserve alpha over a transparent destination.83 Image.makeFromBitmap(original).use { image ->84 Canvas(output).use { canvas ->85 canvas.drawImageRect(image, Rect.makeWH(outWidth.toFloat(), outHeight.toFloat()))86 }87 }88 }89 coroutineContext.ensureActive()90 output.setImmutable()91 DecodeResult(output.asImage(), outWidth < width || outHeight < height)92 } catch (failure: Throwable) {93 output.close()94 throw failure95 }96 }97 }9899 class Factory : Decoder.Factory {100 override fun create(result: SourceFetchResult, options: Options, imageLoader: ImageLoader): Decoder? =101 if (isAvifSource(result.source.source())) AvifImageDecoder(result.source, options) else null102 }103104 private companion object {105 // Serialize expensive AV1 reconstruction even when several pages are prefetched.106 val decodePermit = Semaphore(1)107 const val MAX_INPUT_BYTES = 64L * 1024 * 1024108 const val MAX_PIXELS = 32L * 1024 * 1024109 val readerFactory = AvifImageReaderFactory.DEFAULT110 .withOutputPixelFormat(AvifPixelFormat.ARGB_8888)111 .withInputSizeLimit(MAX_INPUT_BYTES)112 .withMetadataSizeLimit(4L * 1024 * 1024)113 .withAv1DecoderConfig(Av1DecoderConfig.DEFAULT.withFrameSizeLimit(MAX_PIXELS))114 }115}116117/** Sniff bytes, not extensions/MIME: sources and offline caches often omit both. */118internal fun isAvifSource(source: BufferedSource): Boolean {119 val peek = source.peek()120 if (!peek.request(16)) return false121 val boxSize = peek.readInt().toLong() and 0xffffffffL122 if (peek.readUtf8(4) != "ftyp" || boxSize < 16 || boxSize > 4096) return false123 val majorBrand = peek.readUtf8(4)124 peek.skip(4) // minor version is not a compatible brand125 if (majorBrand == "avif" || majorBrand == "avis") return true126 repeat(((boxSize - 16) / 4).toInt()) {127 if (!peek.request(4)) return false128 if (peek.readUtf8(4) in setOf("avif", "avis")) return true129 }130 return false131}132