package eu.friedcutlet.yokan.services.download internal const val MaxSplitImageBytes = 32L * 1024 * 1024 internal const val MaxSplitImagePixels = 24_000_000L internal const val MaxSplitTiles = 128 internal data class TallImageRegion(val top: Int, val height: Int) /** Keep page order and every pixel; refuse excessive allocations before decoding. */ internal fun tallImageRegions(width: Int, height: Int, maximumHeight: Int): List { val tileHeight = maximumHeight.coerceIn(1024, 8192) if (width <= 0 || height <= tileHeight || height.toLong() <= width.toLong() * 2 || width.toLong() * height > MaxSplitImagePixels) return emptyList() val count = (height.toLong() + tileHeight - 1) / tileHeight if (count > MaxSplitTiles) return emptyList() return List(count.toInt()) { index -> val top = index * tileHeight TallImageRegion(top, minOf(tileHeight, height - top)) } } /** Animated formats must retain their original frames, even when the first frame is tall. */ internal fun ByteArray.mayBeAnimatedImage(): Boolean { if (isGif()) return true if (size >= 21 && decodeToString(0, 4) == "RIFF" && decodeToString(8, 12) == "WEBP") { return decodeToString(12, 16) == "VP8X" && (this[20].toInt() and 2) != 0 } // APNG's animation control chunk precedes IDAT; inspect chunks, not incidental pixel bytes. if (size >= 8 && this[0] == 0x89.toByte() && decodeToString(1, 4) == "PNG") { var offset = 8 while (offset.toLong() + 12 <= size) { val length = (0..3).fold(0L) { value, i -> (value shl 8) or (this[offset + i].toLong() and 255) } val kind = decodeToString(offset + 4, offset + 8) if (kind == "acTL") return true if (kind == "IDAT" || length > size.toLong() - offset - 12) return false offset += length.toInt() + 12 } } return false } /** Emits one JPEG at a time, avoiding a chapter-sized list of decoded/encoded images. */ internal expect suspend fun splitTallImage( bytes: ByteArray, maximumHeight: Int, writeTile: suspend (index: Int, bytes: ByteArray) -> Unit, ): Boolean