image: fully deslop composition fetchers

This commit is contained in:
Alexander Capehart
2026-04-23 08:44:04 -06:00
parent 8ca5a22255
commit c8a9537878
5 changed files with 153 additions and 281 deletions
@@ -387,13 +387,12 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
// For artists we both engage in circle cropping but also arrange them // For artists we both engage in circle cropping but also arrange them
// in a "smattering" of random rotation/tilt to give the feeling of a messy // in a "smattering" of random rotation/tilt to give the feeling of a messy
// stack of vinyl. // stack of vinyl.
val uidSeed = artist.uid.toString().hashCode()
bindImpl( bindImpl(
{ size -> { size ->
SmatteringCoverComposition( SmatteringCoverComposition(
artist.covers, artist.covers,
responsiveCornerRatio(size), responsiveCornerRatio(size),
uidSeed, artist.uid.toString().hashCode(),
backgroundColor(), backgroundColor(),
) )
}, },
@@ -415,8 +414,8 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
{ size -> { size ->
GalleryCoverCollection( GalleryCoverCollection(
genre.covers, genre.covers,
genre.uid.toString().hashCode(),
responsiveCornerRatio(size), responsiveCornerRatio(size),
seededZOrder(genre.uid.toString().hashCode()),
backgroundColor(), backgroundColor(),
) )
}, },
@@ -553,22 +552,6 @@ constructor(context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr
return cornerRadius / minSize return cornerRadius / minSize
} }
private fun seededZOrder(uidSeed: Int): List<Int> {
val order = mutableListOf(0, 1, 2, 3)
order.shuffle(Random(uidSeed.toLong()))
return order
}
private fun seededFanAngle(uidSeed: Int): Float {
val random = Random(uidSeed.toLong())
return random.nextFloat() * 10f + 5f // 5-15 degrees
}
private fun seededTiltAngle(uidSeed: Int): Float {
val random = Random(uidSeed.toLong())
return random.nextFloat() * 20f - 10f // -10 to +10 degrees
}
private fun backgroundColor(): Int = context.getColorCompat(R.color.sel_cover_bg).defaultColor private fun backgroundColor(): Int = context.getColorCompat(R.color.sel_cover_bg).defaultColor
private fun resolveSize(): Size? { private fun resolveSize(): Size? {
@@ -24,8 +24,8 @@ import android.graphics.Canvas
import android.graphics.Paint import android.graphics.Paint
import android.graphics.Rect import android.graphics.Rect
import android.graphics.RectF import android.graphics.RectF
import android.graphics.Bitmap
import androidx.core.graphics.drawable.toDrawable import androidx.core.graphics.drawable.toDrawable
import coil3.Bitmap
import coil3.asImage import coil3.asImage
import coil3.decode.DataSource import coil3.decode.DataSource
import coil3.fetch.FetchResult import coil3.fetch.FetchResult
@@ -20,299 +20,190 @@ package org.oxycblt.auxio.image.coil
import android.content.Context import android.content.Context
import android.graphics.Bitmap import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas import android.graphics.Canvas
import android.graphics.Paint import android.graphics.Paint
import android.graphics.Path import android.graphics.Path
import android.graphics.PorterDuff import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode import android.graphics.PorterDuffXfermode
import android.graphics.Rect
import android.graphics.RectF import android.graphics.RectF
import androidx.annotation.ColorInt import androidx.annotation.ColorInt
import androidx.core.graphics.createBitmap import androidx.core.graphics.createBitmap
import androidx.core.graphics.drawable.toDrawable import androidx.core.graphics.withClip
import coil3.ImageLoader import coil3.ImageLoader
import coil3.asImage
import coil3.decode.DataSource
import coil3.decode.ImageSource
import coil3.fetch.FetchResult
import coil3.fetch.Fetcher import coil3.fetch.Fetcher
import coil3.fetch.ImageFetchResult
import coil3.fetch.SourceFetchResult
import coil3.key.Keyer as CoilKeyer
import coil3.request.Options import coil3.request.Options
import coil3.size.Size import coil3.size.Size
import coil3.size.pxOrElse import org.oxycblt.musikr.covers.CoverCollection
import java.io.InputStream
import javax.inject.Inject import javax.inject.Inject
import kotlin.math.max import kotlin.math.max
import kotlin.math.min import kotlin.math.min
import kotlinx.coroutines.Dispatchers import kotlin.random.Random
import kotlinx.coroutines.flow.asFlow import coil3.key.Keyer as CoilKeyer
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.withContext
import okio.FileSystem
import okio.buffer
import okio.source
import org.oxycblt.musikr.covers.CoverCollection
data class GalleryCoverCollection( data class GalleryCoverCollection(
val covers: CoverCollection, override val covers: CoverCollection,
override val seed: Int,
val cornerRadiusRatio: Float, val cornerRadiusRatio: Float,
val zOrder: List<Int>,
@ColorInt val backgroundColor: Int, @ColorInt val backgroundColor: Int,
) ) : CoverComposition
class GalleryComposeFetcher class GalleryComposeFetcher
private constructor( private constructor(
private val context: Context, context: Context,
private val data: GalleryCoverCollection, private val data: GalleryCoverCollection,
private val size: Size, size: Size,
) : Fetcher { ) : CoverCompositionFetcher(context, data, size) {
override suspend fun fetch(): FetchResult? {
val streams = data.covers.covers.asFlow().mapNotNull { it.open() }.take(4).toList()
if (streams.size == 4) {
return createCollage(streams, size).also {
withContext(Dispatchers.IO) { streams.forEach(InputStream::close) }
}
}
val first = streams.firstOrNull() ?: return null override fun compose(bitmaps: List<Bitmap>, size: Int, random: Random): Bitmap {
val sizef = size.toFloat()
withContext(Dispatchers.IO) { val cornerRadiusPx =
for (i in 1 until streams.size) { min(sizef * data.cornerRadiusRatio, sizef * ComposeCoverDefaults.MAX_CORNER_RATIO)
streams[i].close() val gapWidthPx = max(
} sizef * ComposeCoverDefaults.GAP_RATIO,
} cornerRadiusPx * ComposeCoverDefaults.MIN_GAP_CORNER_RATIO,
return SourceFetchResult(
source = ImageSource(first.source().buffer(), FileSystem.SYSTEM, null),
mimeType = null,
dataSource = DataSource.DISK,
) )
} val backgroundColor = data.backgroundColor
val zOrder = seededZOrder(bitmaps.size, random)
val result = createBitmap(size, size)
val canvas = Canvas(result)
canvas.drawColor(backgroundColor)
private fun createCollage(streams: List<InputStream>, size: Size): FetchResult? { val gapPaint =
val outputSize = size.collageSize() Paint(Paint.ANTI_ALIAS_FLAG).apply {
val bitmaps = streams.mapNotNull { BitmapFactory.decodeStream(it) } color = backgroundColor
if (bitmaps.size != streams.size) { style = Paint.Style.FILL
return null }
} val imagePaint =
val cornerRadiusPx = outputSize * data.cornerRadiusRatio Paint(Paint.ANTI_ALIAS_FLAG).apply {
val collageBitmap = // Use the background color for the mask so anti-aliased edges blend
CollageGenerator.generate( // toward it, avoiding dark/light fringing artifacts
bitmaps, color = backgroundColor
CollageGenerator.Config( }
outputSizePx = outputSize,
gapWidthPx = outputSize * ComposeCoverDefaults.GAP_RATIO, val coverSize = sizef * ComposeCoverDefaults.COVER_SIZE_PERCENT
cornerRadiusPx = cornerRadiusPx,
backgroundColor = data.backgroundColor, val p0 = RectF(0f, 0f, coverSize, coverSize)
zOrder = data.zOrder.validatedZOrder(), val p1 = RectF(sizef - coverSize, 0f, sizef, coverSize)
), val p2 = RectF(0f, sizef - coverSize, coverSize, sizef)
val p3 =
RectF(
sizef - coverSize,
sizef - coverSize,
sizef,
sizef,
) )
return ImageFetchResult( val positions = listOf(p0, p1, p2, p3)
image = collageBitmap.toDrawable(context.resources).asImage(), // first we actually have to aggregate the geometry here so that
isSampled = true, // our overlaps will actually work
dataSource = DataSource.DISK, val tiles =
) positions.mapIndexed { index, baseRect ->
} // generate path-tiles for each cover
val isTop = index < 2
val isLeft = index % 2 == 0
val isBottom = !isTop
val isRight = !isLeft
private fun Size.collageSize(): Int { // inset base cover rect to prevent rounded corners from stacking in a way
val widthPx = width.pxOrElse { 512 } // that leads weird "holes" and is instead more dynamic
val heightPx = height.pxOrElse { 512 } // todo: refine this so we can do dynamic overlap?
return min(widthPx, heightPx).coerceAtLeast(1) val innerRect = RectF(baseRect)
} innerRect.left += if (isLeft) 0f else gapWidthPx
innerRect.top += if (isTop) 0f else gapWidthPx
innerRect.right -= if (isRight) 0f else gapWidthPx
innerRect.bottom -= if (isBottom) 0f else gapWidthPx
private object CollageGenerator { // set up the actual gap path
data class Config( val gapRect = RectF(innerRect)
val outputSizePx: Int, gapRect.inset(-gapWidthPx, -gapWidthPx)
val gapWidthPx: Float,
val cornerRadiusPx: Float,
@ColorInt val backgroundColor: Int,
val zOrder: List<Int> = listOf(0, 1, 2, 3),
)
fun generate(sourceImages: List<Bitmap>, config: Config): Bitmap { val gapPath =
if (sourceImages.size != 4) { rounded(
throw IllegalArgumentException("Collage requires exactly 4 images.") gapRect,
} topLeft = if (!isTop && !isLeft) cornerRadiusPx else 0f,
topRight = if (!isTop && !isRight) cornerRadiusPx else 0f,
val result = createBitmap(config.outputSizePx, config.outputSizePx) bottomRight = if (!isBottom && !isRight) cornerRadiusPx else 0f,
val canvas = Canvas(result) bottomLeft = if (!isBottom && !isLeft) cornerRadiusPx else 0f
canvas.drawColor(config.backgroundColor)
val gapPaint =
Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = config.backgroundColor
style = Paint.Style.FILL
}
val imagePaint =
Paint(Paint.ANTI_ALIAS_FLAG).apply {
// Use the background color for the mask so anti-aliased edges blend
// toward it, avoiding dark/light fringing artifacts
color = config.backgroundColor
}
val totalSize = config.outputSizePx.toFloat()
val cardSize = totalSize * ComposeCoverDefaults.COVER_SIZE_PERCENT
val inset = 0f
val cornerRadiusPx =
if (config.cornerRadiusPx > 0f) {
min(config.cornerRadiusPx, totalSize * ComposeCoverDefaults.MAX_CORNER_RATIO)
} else {
0f
}
val gapWidthPx =
if (cornerRadiusPx > 0f) {
max(
config.gapWidthPx,
cornerRadiusPx * ComposeCoverDefaults.MIN_GAP_CORNER_RATIO,
) )
} else {
config.gapWidthPx
}
val p0 = RectF(inset, inset, inset + cardSize, inset + cardSize) // then the inner mask
val p1 = RectF(totalSize - cardSize - inset, inset, totalSize - inset, inset + cardSize) // adjust corner radii to make up for gap
val p2 = RectF(inset, totalSize - cardSize - inset, inset + cardSize, totalSize - inset) val innerRadius = (cornerRadiusPx - gapWidthPx).coerceAtLeast(0f)
val p3 = val maskPath = rounded(
RectF( innerRect,
totalSize - cardSize - inset, topLeft = if (!isTop && !isLeft) innerRadius else 0f,
totalSize - cardSize - inset, topRight = if (!isTop && !isRight) innerRadius else 0f,
totalSize - inset, bottomRight = if (!isBottom && !isRight) innerRadius else 0f,
totalSize - inset, bottomLeft = if (!isBottom && !isLeft) innerRadius else 0f
) )
val positions = listOf(p0, p1, p2, p3) TileGeometry(innerRect, gapPath, maskPath)
val tiles = }
positions.mapIndexed { index, baseRect ->
val isTop = index < 2
val isLeft = index % 2 == 0
val isBottom = !isTop
val isRight = !isLeft
val innerRect = RectF(baseRect)
innerRect.left += if (isLeft) 0f else gapWidthPx
innerRect.top += if (isTop) 0f else gapWidthPx
innerRect.right -= if (isRight) 0f else gapWidthPx
innerRect.bottom -= if (isBottom) 0f else gapWidthPx
val gapRect = RectF(innerRect)
gapRect.inset(-gapWidthPx, -gapWidthPx)
val gapRadius = cornerRadiusPx
val gapTopLeft = if (!isTop && !isLeft) gapRadius else 0f
val gapTopRight = if (!isTop && !isRight) gapRadius else 0f
val gapBottomRight = if (!isBottom && !isRight) gapRadius else 0f
val gapBottomLeft = if (!isBottom && !isLeft) gapRadius else 0f
val gapPath =
Path().apply {
addRoundRect(
gapRect,
floatArrayOf(
gapTopLeft,
gapTopLeft,
gapTopRight,
gapTopRight,
gapBottomRight,
gapBottomRight,
gapBottomLeft,
gapBottomLeft,
),
Path.Direction.CW,
)
}
val innerRadius = (cornerRadiusPx - gapWidthPx).coerceAtLeast(0f)
val topLeftRadius = if (!isTop && !isLeft) innerRadius else 0f
val topRightRadius = if (!isTop && !isRight) innerRadius else 0f
val bottomRightRadius = if (!isBottom && !isRight) innerRadius else 0f
val bottomLeftRadius = if (!isBottom && !isLeft) innerRadius else 0f
val maskPath =
Path().apply {
addRoundRect(
innerRect,
floatArrayOf(
topLeftRadius,
topLeftRadius,
topRightRadius,
topRightRadius,
bottomRightRadius,
bottomRightRadius,
bottomLeftRadius,
bottomLeftRadius,
),
Path.Direction.CW,
)
}
TileGeometry(innerRect, gapPath, maskPath)
}
val zOrder = config.zOrder
for ((orderIndex, imageIndex) in zOrder.withIndex()) {
val bitmap = sourceImages[imageIndex]
val tile = tiles[imageIndex]
val visiblePath = Path(tile.gapPath)
for (index in orderIndex + 1 until zOrder.size) {
visiblePath.op(tiles[zOrder[index]].gapPath, Path.Op.DIFFERENCE)
if (visiblePath.isEmpty) {
break
}
}
for ((orderIndex, imageIndex) in zOrder.withIndex()) {
val bitmap = bitmaps[imageIndex]
val tile = tiles[imageIndex]
// we actually go and difference our gap with the others so we know
// what parts of the path are actually going to be visible after
// the inset
val visiblePath = Path(tile.gapPath)
for (index in orderIndex + 1 until zOrder.size) {
visiblePath.op(tiles[zOrder[index]].gapPath, Path.Op.DIFFERENCE)
if (visiblePath.isEmpty) { if (visiblePath.isEmpty) {
continue break
}
canvas.drawPath(visiblePath, gapPaint)
if (tile.innerRect.width() > 0 && tile.innerRect.height() > 0) {
val clipSave = canvas.save()
canvas.clipPath(visiblePath)
val savedLayer = canvas.saveLayer(tile.innerRect, null)
canvas.drawPath(tile.maskPath, imagePaint)
imagePaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
drawBitmapCover(canvas, bitmap, tile.innerRect, imagePaint)
imagePaint.xfermode = null
canvas.restoreToCount(savedLayer)
canvas.restoreToCount(clipSave)
} }
} }
return result if (visiblePath.isEmpty) {
} continue
private data class TileGeometry(val innerRect: RectF, val gapPath: Path, val maskPath: Path)
private fun drawBitmapCover(canvas: Canvas, bitmap: Bitmap, dest: RectF, paint: Paint) {
val bitmapRatio = bitmap.width.toFloat() / bitmap.height.toFloat()
val destRatio = dest.width() / dest.height()
val srcRect = Rect(0, 0, bitmap.width, bitmap.height)
if (bitmapRatio > destRatio) {
val newWidth = (bitmap.height * destRatio).toInt()
val xOffset = (bitmap.width - newWidth) / 2
srcRect.left = xOffset
srcRect.right = xOffset + newWidth
} else {
val newHeight = (bitmap.width / destRatio).toInt()
val yOffset = (bitmap.height - newHeight) / 2
srcRect.top = yOffset
srcRect.bottom = yOffset + newHeight
} }
canvas.drawBitmap(bitmap, srcRect, dest, paint) // draw adjusted gap
canvas.drawPath(visiblePath, gapPaint)
// draw cover clipped to gap
canvas.withClip(visiblePath) {
val savedLayer = canvas.saveLayer(tile.innerRect, null)
canvas.drawPath(tile.maskPath, imagePaint)
imagePaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
drawBitmapCover(canvas, bitmap, tile.innerRect, imagePaint)
imagePaint.xfermode = null
canvas.restoreToCount(savedLayer)
}
} }
return result
} }
private fun rounded(
rect: RectF,
topLeft: Float,
topRight: Float,
bottomRight: Float,
bottomLeft: Float
) =
Path().apply {
addRoundRect(
rect,
floatArrayOf(
topLeft,
topLeft,
topRight,
topRight,
bottomRight,
bottomRight,
bottomLeft,
bottomLeft,
),
Path.Direction.CW,
)
}
private data class TileGeometry(val innerRect: RectF, val gapPath: Path, val maskPath: Path)
class Factory @Inject constructor() : Fetcher.Factory<GalleryCoverCollection> { class Factory @Inject constructor() : Fetcher.Factory<GalleryCoverCollection> {
override fun create( override fun create(
data: GalleryCoverCollection, data: GalleryCoverCollection,
@@ -324,7 +215,7 @@ private constructor(
class Keyer @Inject constructor() : CoilKeyer<GalleryCoverCollection> { class Keyer @Inject constructor() : CoilKeyer<GalleryCoverCollection> {
override fun key(data: GalleryCoverCollection, options: Options): String { override fun key(data: GalleryCoverCollection, options: Options): String {
val config = val config =
"${data.cornerRadiusRatio}.${data.zOrder.joinToString(".")}.${data.backgroundColor}" "${data.cornerRadiusRatio}.${data.seed}.${data.backgroundColor}"
return "g:${data.covers.hashCode()}.${options.size.width}.${options.size.height}.$config" return "g:${data.covers.hashCode()}.${options.size.width}.${options.size.height}.$config"
} }
} }
@@ -65,7 +65,7 @@ private constructor(context: Context, private val data: SmatteringCoverCompositi
val innerRadius = (cornerRadius - gapWidth).coerceAtLeast(0f) val innerRadius = (cornerRadius - gapWidth).coerceAtLeast(0f)
val fanAngle = seededFanAngle(random) val fanAngle = seededFanAngle(random)
val tiltAngle = seededTiltAngle(random) val tiltAngle = seededTiltAngle(random)
val zOrder = seededZOrder(data.seed, random) val zOrder = seededZOrder(bitmaps.size, random)
val result = createBitmap(size, size) val result = createBitmap(size, size)
val canvas = Canvas(result) val canvas = Canvas(result)
canvas.drawColor(data.backgroundColor) canvas.drawColor(data.backgroundColor)
@@ -114,17 +114,15 @@ private constructor(context: Context, private val data: SmatteringCoverCompositi
canvas.withRotation(rotation, centerX, centerY) { canvas.withRotation(rotation, centerX, centerY) {
drawPath(gapPath, gapPaint) drawPath(gapPath, gapPaint)
if (innerRect.width() > 0 && innerRect.height() > 0) { val savedLayer = saveLayer(innerRect, null)
val savedLayer = saveLayer(innerRect, null) val maskPath = rounded(innerRect, innerRadius)
val maskPath = rounded(innerRect, innerRadius) drawPath(maskPath, imagePaint)
drawPath(maskPath, imagePaint)
imagePaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN) imagePaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
drawBitmapCover(this, bitmap, innerRect, imagePaint) drawBitmapCover(this, bitmap, innerRect, imagePaint)
imagePaint.xfermode = null imagePaint.xfermode = null
restoreToCount(savedLayer) restoreToCount(savedLayer)
}
} }
} }
@@ -77,7 +77,7 @@ private constructor(context: Context, val data: StackCoverComposition, size: Siz
sizef * ComposeCoverDefaults.GAP_RATIO, sizef * ComposeCoverDefaults.GAP_RATIO,
cornerRadius * ComposeCoverDefaults.MIN_GAP_CORNER_RATIO, cornerRadius * ComposeCoverDefaults.MIN_GAP_CORNER_RATIO,
) )
val zOrder = seededZOrder(data.seed, random) val zOrder = seededZOrder(bitmaps.size, random)
val result = createBitmap(size, size) val result = createBitmap(size, size)
val canvas = Canvas(result) val canvas = Canvas(result)
canvas.drawColor(data.backgroundColor) canvas.drawColor(data.backgroundColor)
@@ -89,7 +89,7 @@ private constructor(context: Context, val data: StackCoverComposition, size: Siz
// this is a hard-coded constant derived when i was deslopping gpt output knowing // this is a hard-coded constant derived when i was deslopping gpt output knowing
// that we will always have 4 covers. specifically its the simplification of // that we will always have 4 covers. specifically its the simplification of
// (lastIndex - 1) = (3 - 1) = 2. // (lastIndex - 1) = (3 - 1) = 2.
// without this the covers just zoom around. very wired. // without this i can only fit at most 2ish covers in
// this is why i dont want raw unreviewed ai slop in the codebase btw. lesson learned // this is why i dont want raw unreviewed ai slop in the codebase btw. lesson learned
val maxStep = visibleSize / 2 val maxStep = visibleSize / 2
// re-adjust our corner radius by the actual width of the gap // re-adjust our corner radius by the actual width of the gap