package eu.friedcutlet.yokan.services.download import eu.friedcutlet.yokan.database.einkScaledSize import org.jetbrains.skia.ColorAlphaType import org.jetbrains.skia.ColorType import org.jetbrains.skia.EncodedImageFormat import org.jetbrains.skia.FilterMipmap import org.jetbrains.skia.FilterMode import org.jetbrains.skia.Image import org.jetbrains.skia.ImageInfo import org.jetbrains.skia.MipmapMode import org.jetbrains.skia.Rect import org.jetbrains.skia.Surface internal actual fun transcodeEinkPage(bytes: ByteArray, maxShortSide: Int): ByteArray? { if (bytes.isGif()) return null // Skia objects are not AutoCloseable on every target, so they are closed explicitly. val image = runCatching { Image.makeFromEncoded(bytes) }.getOrNull() ?: return null val encoded: ByteArray? = try { val (width, height) = einkScaledSize(image.width, image.height, maxShortSide) // A GRAY_8 target converts to luminance while drawing and encodes a single-channel JPEG. val surface = Surface.makeRaster(ImageInfo(width, height, ColorType.GRAY_8, ColorAlphaType.OPAQUE)) try { surface.canvas.clear(org.jetbrains.skia.Color.WHITE) surface.canvas.drawImageRect( image, Rect.makeWH(image.width.toFloat(), image.height.toFloat()), Rect.makeWH(width.toFloat(), height.toFloat()), FilterMipmap(FilterMode.LINEAR, MipmapMode.LINEAR), null, true, ) val snapshot = surface.makeImageSnapshot() try { snapshot.encodeToData(EncodedImageFormat.JPEG, EinkJpegQuality)?.bytes } finally { snapshot.close() } } finally { surface.close() } } catch (_: Exception) { null } finally { image.close() } return encoded?.takeIf { it.isNotEmpty() && it.size < bytes.size } }