Yokan / rebuild
Course 1 8624561

TallImageSplitter.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/TallImageSplitter.kt

implementation47 lines
1package eu.friedcutlet.yokan.services.download23internal const val MaxSplitImageBytes = 32L * 1024 * 10244internal const val MaxSplitImagePixels = 24_000_000L5internal const val MaxSplitTiles = 12867internal data class TallImageRegion(val top: Int, val height: Int)89/** Keep page order and every pixel; refuse excessive allocations before decoding. */10internal fun tallImageRegions(width: Int, height: Int, maximumHeight: Int): List<TallImageRegion> {11    val tileHeight = maximumHeight.coerceIn(1024, 8192)12    if (width <= 0 || height <= tileHeight || height.toLong() <= width.toLong() * 2 ||13        width.toLong() * height > MaxSplitImagePixels) return emptyList()14    val count = (height.toLong() + tileHeight - 1) / tileHeight15    if (count > MaxSplitTiles) return emptyList()16    return List(count.toInt()) { index ->17        val top = index * tileHeight18        TallImageRegion(top, minOf(tileHeight, height - top))19    }20}2122/** Animated formats must retain their original frames, even when the first frame is tall. */23internal fun ByteArray.mayBeAnimatedImage(): Boolean {24    if (isGif()) return true25    if (size >= 21 && decodeToString(0, 4) == "RIFF" && decodeToString(8, 12) == "WEBP") {26        return decodeToString(12, 16) == "VP8X" && (this[20].toInt() and 2) != 027    }28    // APNG's animation control chunk precedes IDAT; inspect chunks, not incidental pixel bytes.29    if (size >= 8 && this[0] == 0x89.toByte() && decodeToString(1, 4) == "PNG") {30        var offset = 831        while (offset.toLong() + 12 <= size) {32            val length = (0..3).fold(0L) { value, i -> (value shl 8) or (this[offset + i].toLong() and 255) }33            val kind = decodeToString(offset + 4, offset + 8)34            if (kind == "acTL") return true35            if (kind == "IDAT" || length > size.toLong() - offset - 12) return false36            offset += length.toInt() + 1237        }38    }39    return false40}4142/** Emits one JPEG at a time, avoiding a chapter-sized list of decoded/encoded images. */43internal expect suspend fun splitTallImage(44    bytes: ByteArray,45    maximumHeight: Int,46    writeTile: suspend (index: Int, bytes: ByteArray) -> Unit,47): Boolean48

Search chapters, reference and source filenames.