package eu.friedcutlet.yokan.ui.image import coil3.ImageLoader import coil3.asImage import coil3.decode.DecodeResult import coil3.decode.DecodeUtils import coil3.decode.Decoder import coil3.decode.ImageSource import coil3.fetch.SourceFetchResult import coil3.request.Options import coil3.request.maxBitmapSize import coil3.size.Scale import coil3.size.isOriginal import coil3.size.pxOrElse import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ensureActive import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit import kotlinx.coroutines.withContext import okio.BufferedSource import org.glavo.avif.AvifImageReaderFactory import org.glavo.avif.AvifPixelFormat import org.glavo.avif.av1.Av1DecoderConfig import org.jetbrains.skia.Bitmap import org.jetbrains.skia.Canvas import org.jetbrains.skia.ColorAlphaType import org.jetbrains.skia.ColorType import org.jetbrains.skia.Image import org.jetbrains.skia.ImageInfo import org.jetbrains.skia.Rect import java.io.IOException import kotlin.coroutines.coroutineContext /** First-frame AVIF decoding for reader pages, covers, local files and cached responses. */ internal class AvifImageDecoder( private val source: ImageSource, private val options: Options, ) : Decoder { override suspend fun decode(): DecodeResult = decodePermit.withPermit { withContext(Dispatchers.Default) { coroutineContext.ensureActive() val bytes = source.source().use { if (it.request(MAX_INPUT_BYTES + 1)) throw IOException("AVIF exceeds encoded image size limit") it.readByteArray() } val frame = readerFactory.open(bytes).use { reader -> val info = reader.info() if (info.width().toLong() * info.height() > MAX_PIXELS) { throw IOException("AVIF exceeds decoded image size limit") } requireNotNull(reader.readFrame()) { "AVIF contains no image frame" } } coroutineContext.ensureActive() val width = frame.width() val height = frame.height() val pixels = frame.intPixelBuffer() val rgba = ByteArray(width * height * 4) repeat(width * height) { index -> val argb = pixels.get(index) val offset = index * 4 rgba[offset] = (argb ushr 16).toByte() rgba[offset + 1] = (argb ushr 8).toByte() rgba[offset + 2] = argb.toByte() rgba[offset + 3] = (argb ushr 24).toByte() } val undefinedDimension = if (options.scale == Scale.FIT) Int.MAX_VALUE else 0 val targetWidth = if (options.size.isOriginal) width else options.size.width.pxOrElse { undefinedDimension } val targetHeight = if (options.size.isOriginal) height else options.size.height.pxOrElse { undefinedDimension } val multiplier = DecodeUtils.computeSizeMultiplier( width, height, targetWidth, targetHeight, options.scale, options.maxBitmapSize, ).coerceAtMost(1.0) val outWidth = (width * multiplier).toInt().coerceAtLeast(1) val outHeight = (height * multiplier).toInt().coerceAtLeast(1) val output = Bitmap() try { Bitmap().use { original -> check(original.installPixels( ImageInfo(width, height, ColorType.RGBA_8888, ColorAlphaType.UNPREMUL), rgba, width * 4, )) { "Unable to allocate AVIF pixels" } check(output.allocN32Pixels(outWidth, outHeight)) { "Unable to allocate AVIF bitmap" } output.erase(0) // Source-over must preserve alpha over a transparent destination. Image.makeFromBitmap(original).use { image -> Canvas(output).use { canvas -> canvas.drawImageRect(image, Rect.makeWH(outWidth.toFloat(), outHeight.toFloat())) } } } coroutineContext.ensureActive() output.setImmutable() DecodeResult(output.asImage(), outWidth < width || outHeight < height) } catch (failure: Throwable) { output.close() throw failure } } } class Factory : Decoder.Factory { override fun create(result: SourceFetchResult, options: Options, imageLoader: ImageLoader): Decoder? = if (isAvifSource(result.source.source())) AvifImageDecoder(result.source, options) else null } private companion object { // Serialize expensive AV1 reconstruction even when several pages are prefetched. val decodePermit = Semaphore(1) const val MAX_INPUT_BYTES = 64L * 1024 * 1024 const val MAX_PIXELS = 32L * 1024 * 1024 val readerFactory = AvifImageReaderFactory.DEFAULT .withOutputPixelFormat(AvifPixelFormat.ARGB_8888) .withInputSizeLimit(MAX_INPUT_BYTES) .withMetadataSizeLimit(4L * 1024 * 1024) .withAv1DecoderConfig(Av1DecoderConfig.DEFAULT.withFrameSizeLimit(MAX_PIXELS)) } } /** Sniff bytes, not extensions/MIME: sources and offline caches often omit both. */ internal fun isAvifSource(source: BufferedSource): Boolean { val peek = source.peek() if (!peek.request(16)) return false val boxSize = peek.readInt().toLong() and 0xffffffffL if (peek.readUtf8(4) != "ftyp" || boxSize < 16 || boxSize > 4096) return false val majorBrand = peek.readUtf8(4) peek.skip(4) // minor version is not a compatible brand if (majorBrand == "avif" || majorBrand == "avis") return true repeat(((boxSize - 16) / 4).toInt()) { if (!peek.request(4)) return false if (peek.readUtf8(4) in setOf("avif", "avis")) return true } return false }