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,243 +20,132 @@ 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)
private fun createCollage(streams: List<InputStream>, size: Size): FetchResult? { val result = createBitmap(size, size)
val outputSize = size.collageSize()
val bitmaps = streams.mapNotNull { BitmapFactory.decodeStream(it) }
if (bitmaps.size != streams.size) {
return null
}
val cornerRadiusPx = outputSize * data.cornerRadiusRatio
val collageBitmap =
CollageGenerator.generate(
bitmaps,
CollageGenerator.Config(
outputSizePx = outputSize,
gapWidthPx = outputSize * ComposeCoverDefaults.GAP_RATIO,
cornerRadiusPx = cornerRadiusPx,
backgroundColor = data.backgroundColor,
zOrder = data.zOrder.validatedZOrder(),
),
)
return ImageFetchResult(
image = collageBitmap.toDrawable(context.resources).asImage(),
isSampled = true,
dataSource = DataSource.DISK,
)
}
private fun Size.collageSize(): Int {
val widthPx = width.pxOrElse { 512 }
val heightPx = height.pxOrElse { 512 }
return min(widthPx, heightPx).coerceAtLeast(1)
}
private object CollageGenerator {
data class Config(
val outputSizePx: Int,
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 {
if (sourceImages.size != 4) {
throw IllegalArgumentException("Collage requires exactly 4 images.")
}
val result = createBitmap(config.outputSizePx, config.outputSizePx)
val canvas = Canvas(result) val canvas = Canvas(result)
canvas.drawColor(backgroundColor)
canvas.drawColor(config.backgroundColor)
val gapPaint = val gapPaint =
Paint(Paint.ANTI_ALIAS_FLAG).apply { Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = config.backgroundColor color = backgroundColor
style = Paint.Style.FILL style = Paint.Style.FILL
} }
val imagePaint = val imagePaint =
Paint(Paint.ANTI_ALIAS_FLAG).apply { Paint(Paint.ANTI_ALIAS_FLAG).apply {
// Use the background color for the mask so anti-aliased edges blend // Use the background color for the mask so anti-aliased edges blend
// toward it, avoiding dark/light fringing artifacts // toward it, avoiding dark/light fringing artifacts
color = config.backgroundColor color = backgroundColor
} }
val totalSize = config.outputSizePx.toFloat() val coverSize = sizef * ComposeCoverDefaults.COVER_SIZE_PERCENT
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) val p0 = RectF(0f, 0f, coverSize, coverSize)
val p1 = RectF(totalSize - cardSize - inset, inset, totalSize - inset, inset + cardSize) val p1 = RectF(sizef - coverSize, 0f, sizef, coverSize)
val p2 = RectF(inset, totalSize - cardSize - inset, inset + cardSize, totalSize - inset) val p2 = RectF(0f, sizef - coverSize, coverSize, sizef)
val p3 = val p3 =
RectF( RectF(
totalSize - cardSize - inset, sizef - coverSize,
totalSize - cardSize - inset, sizef - coverSize,
totalSize - inset, sizef,
totalSize - inset, sizef,
) )
val positions = listOf(p0, p1, p2, p3) val positions = listOf(p0, p1, p2, p3)
// first we actually have to aggregate the geometry here so that
// our overlaps will actually work
val tiles = val tiles =
positions.mapIndexed { index, baseRect -> positions.mapIndexed { index, baseRect ->
// generate path-tiles for each cover
val isTop = index < 2 val isTop = index < 2
val isLeft = index % 2 == 0 val isLeft = index % 2 == 0
val isBottom = !isTop val isBottom = !isTop
val isRight = !isLeft val isRight = !isLeft
// inset base cover rect to prevent rounded corners from stacking in a way
// that leads weird "holes" and is instead more dynamic
// todo: refine this so we can do dynamic overlap?
val innerRect = RectF(baseRect) val innerRect = RectF(baseRect)
innerRect.left += if (isLeft) 0f else gapWidthPx innerRect.left += if (isLeft) 0f else gapWidthPx
innerRect.top += if (isTop) 0f else gapWidthPx innerRect.top += if (isTop) 0f else gapWidthPx
innerRect.right -= if (isRight) 0f else gapWidthPx innerRect.right -= if (isRight) 0f else gapWidthPx
innerRect.bottom -= if (isBottom) 0f else gapWidthPx innerRect.bottom -= if (isBottom) 0f else gapWidthPx
// set up the actual gap path
val gapRect = RectF(innerRect) val gapRect = RectF(innerRect)
gapRect.inset(-gapWidthPx, -gapWidthPx) 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 = val gapPath =
Path().apply { rounded(
addRoundRect(
gapRect, gapRect,
floatArrayOf( topLeft = if (!isTop && !isLeft) cornerRadiusPx else 0f,
gapTopLeft, topRight = if (!isTop && !isRight) cornerRadiusPx else 0f,
gapTopLeft, bottomRight = if (!isBottom && !isRight) cornerRadiusPx else 0f,
gapTopRight, bottomLeft = if (!isBottom && !isLeft) cornerRadiusPx else 0f
gapTopRight,
gapBottomRight,
gapBottomRight,
gapBottomLeft,
gapBottomLeft,
),
Path.Direction.CW,
) )
}
// then the inner mask
// adjust corner radii to make up for gap
val innerRadius = (cornerRadiusPx - gapWidthPx).coerceAtLeast(0f) val innerRadius = (cornerRadiusPx - gapWidthPx).coerceAtLeast(0f)
val topLeftRadius = if (!isTop && !isLeft) innerRadius else 0f val maskPath = rounded(
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, innerRect,
floatArrayOf( topLeft = if (!isTop && !isLeft) innerRadius else 0f,
topLeftRadius, topRight = if (!isTop && !isRight) innerRadius else 0f,
topLeftRadius, bottomRight = if (!isBottom && !isRight) innerRadius else 0f,
topRightRadius, bottomLeft = if (!isBottom && !isLeft) innerRadius else 0f
topRightRadius,
bottomRightRadius,
bottomRightRadius,
bottomLeftRadius,
bottomLeftRadius,
),
Path.Direction.CW,
) )
}
TileGeometry(innerRect, gapPath, maskPath) TileGeometry(innerRect, gapPath, maskPath)
} }
val zOrder = config.zOrder
for ((orderIndex, imageIndex) in zOrder.withIndex()) { for ((orderIndex, imageIndex) in zOrder.withIndex()) {
val bitmap = sourceImages[imageIndex] val bitmap = bitmaps[imageIndex]
val tile = tiles[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) val visiblePath = Path(tile.gapPath)
for (index in orderIndex + 1 until zOrder.size) { for (index in orderIndex + 1 until zOrder.size) {
visiblePath.op(tiles[zOrder[index]].gapPath, Path.Op.DIFFERENCE) visiblePath.op(tiles[zOrder[index]].gapPath, Path.Op.DIFFERENCE)
@@ -269,11 +158,11 @@ private constructor(
continue continue
} }
// draw adjusted gap
canvas.drawPath(visiblePath, gapPaint) canvas.drawPath(visiblePath, gapPaint)
if (tile.innerRect.width() > 0 && tile.innerRect.height() > 0) { // draw cover clipped to gap
val clipSave = canvas.save() canvas.withClip(visiblePath) {
canvas.clipPath(visiblePath)
val savedLayer = canvas.saveLayer(tile.innerRect, null) val savedLayer = canvas.saveLayer(tile.innerRect, null)
canvas.drawPath(tile.maskPath, imagePaint) canvas.drawPath(tile.maskPath, imagePaint)
@@ -282,37 +171,39 @@ private constructor(
imagePaint.xfermode = null imagePaint.xfermode = null
canvas.restoreToCount(savedLayer) canvas.restoreToCount(savedLayer)
canvas.restoreToCount(clipSave)
} }
} }
return result 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) 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)
}
}
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,7 +114,6 @@ 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)
@@ -126,7 +125,6 @@ private constructor(context: Context, private val data: SmatteringCoverCompositi
restoreToCount(savedLayer) restoreToCount(savedLayer)
} }
} }
}
return result return result
} }
@@ -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