Initial commit: Foto Dup Finder 1.0.1
An Android duplicate-photo finder. Pure-Kotlin core (SHA-256 + dHash hashing, exact and perceptual union-find grouping, three sensitivity presets) with MediaStore access, a persistent SQLite hash index and a tiered ScanEngine behind a Jetpack Compose UI. No INTERNET permission, no ads, no analytics, no account. Ships versionCode 2 / versionName 1.0.1, carrying the scan-stall hardening (BoundedCall breaker) and verified against a 5,363-photo device library. 80 JVM unit tests, lint clean. Release paperwork is in docs/ (Play checklist, store listing, edge-case testing), the upload-ready Play graphics and screenshots in store-assets/, and the generators for those assets in tools/.
This commit is contained in:
@@ -0,0 +1,187 @@
|
||||
package de.softwareapp_hb.fotodup.finder.bench
|
||||
|
||||
import de.softwareapp_hb.fotodup.finder.core.PerceptualHash
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Models the two-stage cascade: a cheap binary hash proposes candidate pairs, and an
|
||||
* expensive verifier is only consulted for pairs that survive stage 1.
|
||||
*
|
||||
* The experiment answers two questions with numbers:
|
||||
* 1. can stage 1 run at a **loose** threshold (high recall) and have the verifier restore
|
||||
* precision, and
|
||||
* 2. how much of the library would the verifier actually have to touch?
|
||||
*/
|
||||
internal object CascadeBench {
|
||||
|
||||
private class PairRef(
|
||||
val a: Int,
|
||||
val b: Int,
|
||||
val stage1: Int,
|
||||
val positive: Boolean,
|
||||
)
|
||||
|
||||
private class Policy(
|
||||
val name: String,
|
||||
val tp: Int,
|
||||
val fp: Int,
|
||||
val fn: Int,
|
||||
/** Pairs stage 1 lets through — what the verifier would have to look at. */
|
||||
val stage1Candidates: Int,
|
||||
/** Of those, how many are not true duplicates (the verifier's extra load). */
|
||||
val falseCandidates: Int,
|
||||
) {
|
||||
val precision = if (tp + fp == 0) 1.0 else tp.toDouble() / (tp + fp)
|
||||
val recall = if (tp + fn == 0) 1.0 else tp.toDouble() / (tp + fn)
|
||||
val f1 = if (precision + recall == 0.0) 0.0 else 2 * precision * recall / (precision + recall)
|
||||
}
|
||||
|
||||
fun run(bases: List<Img>): String {
|
||||
val transforms = ImageLab.transforms
|
||||
val baseCount = bases.size
|
||||
val transformCount = transforms.size
|
||||
val imageCount = baseCount * (1 + transformCount)
|
||||
val report = StringBuilder()
|
||||
|
||||
// --- signatures: transforms are streamed, only signatures are retained --------
|
||||
val stage1 = LongArray(imageCount)
|
||||
val verifiers = listOf(ColourHistogramVerifier, ColourDHashVerifier)
|
||||
val signatures = Array(verifiers.size) { Array(imageCount) { LongArray(0) } }
|
||||
|
||||
fun sign(imageIndex: Int, img: Img) {
|
||||
stage1[imageIndex] = PerceptualHash.phashFromArgb(img.pixels, img.width, img.height)
|
||||
verifiers.forEachIndexed { v, verifier ->
|
||||
signatures[v][imageIndex] = verifier.signature(img)
|
||||
}
|
||||
}
|
||||
|
||||
bases.forEachIndexed { i, img -> sign(i, img) }
|
||||
transforms.forEachIndexed { t, transform ->
|
||||
bases.forEachIndexed { i, img ->
|
||||
sign(baseCount + i * transformCount + t, transform.apply(img))
|
||||
}
|
||||
}
|
||||
|
||||
// --- pairs (identical for every verifier) ------------------------------------
|
||||
val pairs = ArrayList<PairRef>()
|
||||
for (i in 0 until baseCount) {
|
||||
for (t in 0 until transformCount) {
|
||||
val copy = baseCount + i * transformCount + t
|
||||
pairs += PairRef(i, copy, PerceptualHash.hammingDistance(stage1[i], stage1[copy]), true)
|
||||
}
|
||||
}
|
||||
for (i in 0 until baseCount) {
|
||||
for (j in i + 1 until baseCount) {
|
||||
pairs += PairRef(i, j, PerceptualHash.hammingDistance(stage1[i], stage1[j]), false)
|
||||
}
|
||||
}
|
||||
val positivePairs = pairs.count { it.positive }
|
||||
|
||||
// The cheapest stage-1 setting that still yields no false positives, plus a looser
|
||||
// one — the loose setting is what a cascade would use to buy recall back.
|
||||
val negatives = pairs.filterNot { it.positive }.map { it.stage1 }
|
||||
// A dataset that already contains near-identical pairs can leave no threshold with zero
|
||||
// false pairs at all. That is a property of the *data*, not a failure, so fall back to the
|
||||
// strictest setting and say so rather than throwing.
|
||||
val tight = (0..64).lastOrNull { threshold -> negatives.none { it <= threshold } } ?: 0
|
||||
val loose = tight + 6
|
||||
val hasCleanThreshold = negatives.none { it <= tight }
|
||||
|
||||
report.appendLine(
|
||||
"images=$imageCount positive pairs=$positivePairs " +
|
||||
"negative pairs=${pairs.size - positivePairs}",
|
||||
)
|
||||
report.appendLine("stage 1 = pHash; tight threshold (no false positives) = $tight; loose = $loose")
|
||||
if (!hasCleanThreshold) {
|
||||
report.appendLine(
|
||||
"NOTE: no threshold has zero false pairs — this set contains genuine duplicates " +
|
||||
"that the harness treats as negatives, so precision numbers below are pessimistic.",
|
||||
)
|
||||
}
|
||||
report.appendLine()
|
||||
|
||||
for ((v, verifier) in verifiers.withIndex()) {
|
||||
val verified = DoubleArray(pairs.size) { p ->
|
||||
val ref = pairs[p]
|
||||
verifier.distance(signatures[v][ref.a], signatures[v][ref.b])
|
||||
}
|
||||
|
||||
fun evaluate(
|
||||
name: String,
|
||||
costFilter: (Int) -> Boolean,
|
||||
accept: (Int, Double) -> Boolean,
|
||||
): Policy {
|
||||
var tp = 0
|
||||
var fp = 0
|
||||
var fn = 0
|
||||
var candidates = 0
|
||||
var falseCandidates = 0
|
||||
pairs.forEachIndexed { p, ref ->
|
||||
if (costFilter(ref.stage1)) {
|
||||
candidates++
|
||||
if (!ref.positive) falseCandidates++
|
||||
}
|
||||
if (accept(ref.stage1, verified[p])) {
|
||||
if (ref.positive) tp++ else fp++
|
||||
} else if (ref.positive) {
|
||||
fn++
|
||||
}
|
||||
}
|
||||
return Policy(name, tp, fp, fn, candidates, falseCandidates)
|
||||
}
|
||||
|
||||
val tightOnly = evaluate("A) stage 1 only, thr $tight", { it <= tight }) { s, _ -> s <= tight }
|
||||
val looseOnly = evaluate("B) stage 1 only, thr $loose", { it <= loose }) { s, _ -> s <= loose }
|
||||
|
||||
val cascades = verifier.cutoffs().map { cutoff ->
|
||||
evaluate(
|
||||
"C) thr $loose + verifier <= %.2f".format(Locale.US, cutoff),
|
||||
{ it <= loose },
|
||||
) { s, d -> s <= loose && d <= cutoff }
|
||||
}
|
||||
val bestCascade = cascades.maxBy { it.f1 }
|
||||
|
||||
val verifierOnly = verifier.cutoffs().map { cutoff ->
|
||||
evaluate(
|
||||
"D) verifier alone <= %.2f".format(Locale.US, cutoff),
|
||||
{ true },
|
||||
) { _, d -> d <= cutoff }
|
||||
}
|
||||
val bestVerifierOnly = verifierOnly.maxBy { it.f1 }
|
||||
|
||||
report.appendLine("=== verifier: ${verifier.label} ===")
|
||||
report.appendLine(
|
||||
" policy prec recall F1 | st1 cands false cands",
|
||||
)
|
||||
listOf(tightOnly, looseOnly, bestCascade, bestVerifierOnly).forEach { policy ->
|
||||
report.appendLine(
|
||||
" %-38s %6.3f %6.3f %6.3f | %9d %11d".format(
|
||||
Locale.US, policy.name, policy.precision, policy.recall, policy.f1,
|
||||
policy.stage1Candidates, policy.falseCandidates,
|
||||
),
|
||||
)
|
||||
}
|
||||
report.appendLine()
|
||||
report.appendLine(
|
||||
" cascade sweep at stage-1 thr $loose (cutoff -> precision, recall, F1, false cands):",
|
||||
)
|
||||
verifier.cutoffs().forEachIndexed { index, cutoff ->
|
||||
val policy = cascades[index]
|
||||
report.appendLine(
|
||||
" %6.2f -> %6.3f %6.3f %6.3f %6d".format(
|
||||
Locale.US, cutoff, policy.precision, policy.recall, policy.f1,
|
||||
policy.falseCandidates,
|
||||
),
|
||||
)
|
||||
}
|
||||
report.appendLine()
|
||||
report.appendLine(
|
||||
" verdict: cascade(C) %.3f vs loose-only(B) %.3f vs tight-only(A) %.3f".format(
|
||||
Locale.US, bestCascade.f1, looseOnly.f1, tightOnly.f1,
|
||||
),
|
||||
)
|
||||
report.appendLine()
|
||||
}
|
||||
return report.toString()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package de.softwareapp_hb.fotodup.finder.bench
|
||||
|
||||
import de.softwareapp_hb.fotodup.finder.core.DuplicateGrouper
|
||||
import de.softwareapp_hb.fotodup.finder.core.DuplicatePolicy
|
||||
import de.softwareapp_hb.fotodup.finder.core.PhotoFingerprint
|
||||
import de.softwareapp_hb.fotodup.finder.core.RgbDHash
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
import java.util.Locale
|
||||
import kotlin.random.Random
|
||||
|
||||
/**
|
||||
* Times the grouping pass at realistic library sizes, including a large cluster of mutually
|
||||
* similar photos — the case that makes the banded candidate index behave quadratically.
|
||||
*
|
||||
* Opt-in:
|
||||
* ```
|
||||
* ./gradlew :app:testDebugUnitTest --tests '*GroupingScaleTest*' -DfotoScale=true --rerun-tasks
|
||||
* ```
|
||||
*/
|
||||
class GroupingScaleTest {
|
||||
|
||||
@Test
|
||||
fun `time the grouper at library scale`() {
|
||||
assumeTrue("set -DfotoScale=true to run", System.getProperty("fotoScale") == "true")
|
||||
|
||||
val librarySize = 5_363
|
||||
val report = StringBuilder()
|
||||
report.appendLine("library=$librarySize, BALANCED".format(Locale.US))
|
||||
|
||||
for (clusterSize in listOf(0, 10, 100, 500, 1_000, 2_500)) {
|
||||
val random = Random(7)
|
||||
val photos = ArrayList<PhotoFingerprint>(librarySize)
|
||||
repeat(librarySize - clusterSize) { index ->
|
||||
photos += PhotoFingerprint(
|
||||
id = index.toLong(),
|
||||
sizeBytes = 1_000,
|
||||
dateModifiedSeconds = 0,
|
||||
width = 100,
|
||||
height = 100,
|
||||
perceptualHash = random.nextLong(),
|
||||
rgbDHash = RgbDHash(random.nextLong(), random.nextLong(), random.nextLong()),
|
||||
)
|
||||
}
|
||||
// A cluster of mutually near-identical photos: all within a couple of bits, which is
|
||||
// exactly what a folder of dark screenshots or a repeated export looks like.
|
||||
repeat(clusterSize) { offset ->
|
||||
photos += PhotoFingerprint(
|
||||
id = (librarySize + offset).toLong(),
|
||||
sizeBytes = 1_000,
|
||||
dateModifiedSeconds = 0,
|
||||
width = 100,
|
||||
height = 100,
|
||||
perceptualHash = offset.toLong() and 0x3L,
|
||||
rgbDHash = RgbDHash(0L, 0L, 0L),
|
||||
)
|
||||
}
|
||||
|
||||
val started = System.nanoTime()
|
||||
val result = DuplicateGrouper.findGroupsDetailed(photos, DuplicatePolicy.BALANCED)
|
||||
val millis = (System.nanoTime() - started) / 1_000_000
|
||||
report.appendLine(
|
||||
" identical cluster of %5d -> %6d ms, candidate pairs=%d, groups=%d".format(
|
||||
Locale.US, clusterSize, millis, result.observedPairs, result.groups.size,
|
||||
),
|
||||
)
|
||||
}
|
||||
println(report)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package de.softwareapp_hb.fotodup.finder.bench
|
||||
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import javax.imageio.ImageIO
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
import kotlin.random.Random
|
||||
|
||||
/** A decoded image as packed ARGB pixels. */
|
||||
internal class Img(val pixels: IntArray, val width: Int, val height: Int)
|
||||
|
||||
/** A transformation applied to a base image to produce a "near duplicate". */
|
||||
internal class Transform(val label: String, val apply: (Img) -> Img)
|
||||
|
||||
/**
|
||||
* Image sources and the transformations a real photo library inflicts on a picture.
|
||||
*
|
||||
* Runs entirely on the JVM (headless AWT), so the benchmark needs no device and no sample
|
||||
* photos: it synthesises structured images, or loads a real folder when one is provided.
|
||||
*/
|
||||
internal object ImageLab {
|
||||
|
||||
/** Transformations a genuine duplicate should survive — plus one it will not. */
|
||||
val transforms: List<Transform> = listOf(
|
||||
Transform("resize 50%") { ImageOps.resample(it, it.width / 2, it.height / 2) },
|
||||
Transform("resize 200%") { ImageOps.resample(it, it.width * 2, it.height * 2) },
|
||||
Transform("resize 33%") { ImageOps.resample(it, it.width / 3, it.height / 3) },
|
||||
Transform("jpeg q85") { ImageOps.jpeg(it, 0.85f) },
|
||||
Transform("jpeg q45") { ImageOps.jpeg(it, 0.45f) },
|
||||
Transform("brightness +12%") { ImageOps.levels(it, gain = 1.12, gamma = 1.0) },
|
||||
Transform("brightness -12%") { ImageOps.levels(it, gain = 0.88, gamma = 1.0) },
|
||||
Transform("gamma 1.25") { ImageOps.levels(it, gain = 1.0, gamma = 1.25) },
|
||||
Transform("crop 90%") { ImageOps.crop(it, 0.9) },
|
||||
// Geometry the descriptors are not designed for — measured on purpose so the
|
||||
// limits are visible rather than assumed.
|
||||
Transform("shift x 5%") { ImageOps.shift(it, percentX = 5, percentY = 0) },
|
||||
Transform("shift y 5%") { ImageOps.shift(it, percentX = 0, percentY = 5) },
|
||||
Transform("rotate 2°") { ImageOps.rotate(it, 2.0) },
|
||||
Transform("rotate 5°") { ImageOps.rotate(it, 5.0) },
|
||||
Transform("rotate 10°") { ImageOps.rotate(it, 10.0) },
|
||||
Transform("rotate 90") { ImageOps.rotate90(it) },
|
||||
Transform("rotate 180") { ImageOps.rotate180(it) },
|
||||
Transform("flip horizontal") { ImageOps.flipHorizontal(it) },
|
||||
)
|
||||
|
||||
/**
|
||||
* Distinct, structured synthetic images.
|
||||
*
|
||||
* Deliberately *not* random noise: each has a gradient background plus solid blocks, so
|
||||
* different seeds genuinely look different. Pure noise would make the "negative" pairs
|
||||
* trivially separable and the numbers meaningless.
|
||||
*/
|
||||
fun syntheticBases(count: Int, width: Int = 320, height: Int = 240, seed: Int = 42): List<Img> =
|
||||
(0 until count).map { syntheticImage(seed + it, width, height) }
|
||||
|
||||
/**
|
||||
* Loads real images from [dir] (recursively).
|
||||
*
|
||||
* Only [maxImages] are decoded — chosen by a seeded shuffle so the subset is not biased by
|
||||
* filename order — because the harness holds every base image in memory. COCO photographs
|
||||
* are 640 px on the long edge, so ~1.2 MB each decoded.
|
||||
*/
|
||||
fun loadFrom(dir: File, maxImages: Int = DEFAULT_MAX_IMAGES, seed: Int = 42): List<Img> {
|
||||
require(dir.isDirectory) { "$dir is not a directory" }
|
||||
val files = dir.walkTopDown()
|
||||
.filter { it.isFile && it.extension.lowercase() in SUPPORTED }
|
||||
.sortedBy { it.absolutePath }
|
||||
.toList()
|
||||
val selected = if (files.size <= maxImages) {
|
||||
files
|
||||
} else {
|
||||
files.shuffled(Random(seed)).take(maxImages)
|
||||
}
|
||||
|
||||
// Two files with identical bytes are the same photo, not an unrelated pair. Datasets do
|
||||
// ship such duplicates (BSDS500 includes its bench folder twice), and a real folder the
|
||||
// user points at may too — but for *measuring* false positives they must go, otherwise
|
||||
// the harness counts genuine duplicates as negatives.
|
||||
val seen = HashSet<String>()
|
||||
val distinct = selected.filter { file ->
|
||||
val digest = runCatching {
|
||||
MessageDigest.getInstance("SHA-256").digest(file.readBytes())
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
}.getOrNull()
|
||||
digest == null || seen.add(digest)
|
||||
}
|
||||
|
||||
return distinct
|
||||
.mapNotNull { file -> runCatching { ImageIO.read(file) }.getOrNull() }
|
||||
.map { ImageOps.fromBufferedImage(it) }
|
||||
.filter { it.width >= 64 && it.height >= 64 }
|
||||
}
|
||||
|
||||
internal fun syntheticImage(seed: Int, width: Int, height: Int): Img {
|
||||
val rnd = Random(seed)
|
||||
val angle = rnd.nextDouble() * PI
|
||||
val cosA = cos(angle)
|
||||
val sinA = sin(angle)
|
||||
val from = randomColor(rnd)
|
||||
val to = randomColor(rnd)
|
||||
val diagonal = (width + height).toDouble()
|
||||
|
||||
val pixels = IntArray(width * height)
|
||||
for (y in 0 until height) {
|
||||
for (x in 0 until width) {
|
||||
val t = (((x * cosA + y * sinA) / diagonal) + 0.5).coerceIn(0.0, 1.0)
|
||||
pixels[y * width + x] = lerp(from, to, t)
|
||||
}
|
||||
}
|
||||
|
||||
repeat(3 + rnd.nextInt(6)) {
|
||||
val colour = randomColor(rnd)
|
||||
val w = 20 + rnd.nextInt(maxOf(1, width / 2))
|
||||
val h = 20 + rnd.nextInt(maxOf(1, height / 2))
|
||||
val x0 = rnd.nextInt(maxOf(1, width - w))
|
||||
val y0 = rnd.nextInt(maxOf(1, height - h))
|
||||
for (yy in y0 until minOf(y0 + h, height)) {
|
||||
for (xx in x0 until minOf(x0 + w, width)) {
|
||||
pixels[yy * width + xx] = colour
|
||||
}
|
||||
}
|
||||
}
|
||||
return Img(pixels, width, height)
|
||||
}
|
||||
|
||||
private fun randomColor(rnd: Random): Int {
|
||||
val r = 25 + rnd.nextInt(210)
|
||||
val g = 25 + rnd.nextInt(210)
|
||||
val b = 25 + rnd.nextInt(210)
|
||||
return (0xFF shl 24) or (r shl 16) or (g shl 8) or b
|
||||
}
|
||||
|
||||
private fun lerp(a: Int, b: Int, t: Double): Int {
|
||||
fun channel(shift: Int): Int {
|
||||
val ca = (a shr shift) and 0xFF
|
||||
val cb = (b shr shift) and 0xFF
|
||||
return (ca + (cb - ca) * t).toInt().coerceIn(0, 255)
|
||||
}
|
||||
return (0xFF shl 24) or (channel(16) shl 16) or (channel(8) shl 8) or channel(0)
|
||||
}
|
||||
|
||||
private val SUPPORTED = setOf("jpg", "jpeg", "png", "bmp")
|
||||
|
||||
/** Default cap on how many real photographs are decoded at once. */
|
||||
const val DEFAULT_MAX_IMAGES = 300
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package de.softwareapp_hb.fotodup.finder.bench
|
||||
|
||||
import java.awt.RenderingHints
|
||||
import java.awt.geom.AffineTransform
|
||||
import java.awt.image.BufferedImage
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import javax.imageio.IIOImage
|
||||
import javax.imageio.ImageIO
|
||||
import javax.imageio.ImageWriteParam
|
||||
import kotlin.math.pow
|
||||
|
||||
/**
|
||||
* Image operations backed by `java.awt` in headless mode.
|
||||
*
|
||||
* Used by the similarity benchmark to simulate what a real photo library does to a
|
||||
* picture: rescaling, JPEG re-encoding and tone changes.
|
||||
*/
|
||||
internal object ImageOps {
|
||||
|
||||
fun resample(img: Img, width: Int, height: Int): Img {
|
||||
val targetW = maxOf(1, width)
|
||||
val targetH = maxOf(1, height)
|
||||
val dst = BufferedImage(targetW, targetH, BufferedImage.TYPE_INT_RGB)
|
||||
val g = dst.createGraphics()
|
||||
g.setRenderingHint(
|
||||
RenderingHints.KEY_INTERPOLATION,
|
||||
RenderingHints.VALUE_INTERPOLATION_BILINEAR,
|
||||
)
|
||||
g.drawImage(toBufferedImage(img), 0, 0, targetW, targetH, null)
|
||||
g.dispose()
|
||||
return fromBufferedImage(dst)
|
||||
}
|
||||
|
||||
/** Re-encode through a real JPEG codec at the given quality. */
|
||||
fun jpeg(img: Img, quality: Float): Img {
|
||||
val bytes = ByteArrayOutputStream()
|
||||
val writer = ImageIO.getImageWritersByFormatName("jpeg").next()
|
||||
val param = writer.defaultWriteParam.apply {
|
||||
compressionMode = ImageWriteParam.MODE_EXPLICIT
|
||||
compressionQuality = quality
|
||||
}
|
||||
ImageIO.createImageOutputStream(bytes).use { stream ->
|
||||
writer.output = stream
|
||||
writer.write(null, IIOImage(toBufferedImage(img), null, null), param)
|
||||
}
|
||||
writer.dispose()
|
||||
val decoded = ImageIO.read(ByteArrayInputStream(bytes.toByteArray()))
|
||||
return fromBufferedImage(decoded)
|
||||
}
|
||||
|
||||
/** Brightness/gamma change through a 256-entry lookup table. */
|
||||
fun levels(img: Img, gain: Double, gamma: Double): Img {
|
||||
val lut = IntArray(256) { v ->
|
||||
((v / 255.0).pow(gamma) * gain * 255.0).toInt().coerceIn(0, 255)
|
||||
}
|
||||
val out = IntArray(img.pixels.size)
|
||||
for (i in img.pixels.indices) {
|
||||
val p = img.pixels[i]
|
||||
out[i] = (0xFF shl 24) or
|
||||
(lut[(p shr 16) and 0xFF] shl 16) or
|
||||
(lut[(p shr 8) and 0xFF] shl 8) or
|
||||
lut[p and 0xFF]
|
||||
}
|
||||
return Img(out, img.width, img.height)
|
||||
}
|
||||
|
||||
/** Centre crop to [ratio] of the original size. */
|
||||
fun crop(img: Img, ratio: Double): Img {
|
||||
val w = maxOf(1, (img.width * ratio).toInt())
|
||||
val h = maxOf(1, (img.height * ratio).toInt())
|
||||
val x0 = (img.width - w) / 2
|
||||
val y0 = (img.height - h) / 2
|
||||
val out = IntArray(w * h)
|
||||
for (y in 0 until h) {
|
||||
System.arraycopy(img.pixels, (y0 + y) * img.width + x0, out, y * w, w)
|
||||
}
|
||||
return Img(out, w, h)
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotates by [degrees] about the centre, keeping the original canvas — i.e. the
|
||||
* corners are clipped, which is what happens when a print is photographed slightly
|
||||
* crooked.
|
||||
*/
|
||||
fun rotate(img: Img, degrees: Double): Img {
|
||||
val dst = BufferedImage(img.width, img.height, BufferedImage.TYPE_INT_RGB)
|
||||
val g = dst.createGraphics()
|
||||
g.setRenderingHint(
|
||||
RenderingHints.KEY_INTERPOLATION,
|
||||
RenderingHints.VALUE_INTERPOLATION_BILINEAR,
|
||||
)
|
||||
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)
|
||||
val transform = AffineTransform()
|
||||
transform.rotate(Math.toRadians(degrees), img.width / 2.0, img.height / 2.0)
|
||||
g.drawImage(toBufferedImage(img), transform, null)
|
||||
g.dispose()
|
||||
return fromBufferedImage(dst)
|
||||
}
|
||||
|
||||
fun rotate90(img: Img): Img {
|
||||
val w = img.height
|
||||
val out = IntArray(w * img.width)
|
||||
for (y in 0 until img.height) {
|
||||
for (x in 0 until img.width) {
|
||||
out[x * w + (img.height - 1 - y)] = img.pixels[y * img.width + x]
|
||||
}
|
||||
}
|
||||
return Img(out, w, img.width)
|
||||
}
|
||||
|
||||
fun rotate180(img: Img): Img {
|
||||
val out = IntArray(img.pixels.size)
|
||||
val last = img.pixels.size - 1
|
||||
for (i in img.pixels.indices) out[i] = img.pixels[last - i]
|
||||
return Img(out, img.width, img.height)
|
||||
}
|
||||
|
||||
fun flipHorizontal(img: Img): Img {
|
||||
val out = IntArray(img.pixels.size)
|
||||
for (y in 0 until img.height) {
|
||||
val row = y * img.width
|
||||
for (x in 0 until img.width) out[row + x] = img.pixels[row + (img.width - 1 - x)]
|
||||
}
|
||||
return Img(out, img.width, img.height)
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates the image by a percentage of its own size, replicating the edge pixels.
|
||||
* Models a photo that is off-centre within a resaved/re-rendered frame.
|
||||
*/
|
||||
fun shift(img: Img, percentX: Int, percentY: Int): Img {
|
||||
val dx = img.width * percentX / 100
|
||||
val dy = img.height * percentY / 100
|
||||
val out = IntArray(img.pixels.size)
|
||||
for (y in 0 until img.height) {
|
||||
val sy = (y - dy).coerceIn(0, img.height - 1)
|
||||
for (x in 0 until img.width) {
|
||||
val sx = (x - dx).coerceIn(0, img.width - 1)
|
||||
out[y * img.width + x] = img.pixels[sy * img.width + sx]
|
||||
}
|
||||
}
|
||||
return Img(out, img.width, img.height)
|
||||
}
|
||||
|
||||
fun toBufferedImage(img: Img): BufferedImage {
|
||||
val bi = BufferedImage(img.width, img.height, BufferedImage.TYPE_INT_RGB)
|
||||
bi.setRGB(0, 0, img.width, img.height, img.pixels, 0, img.width)
|
||||
return bi
|
||||
}
|
||||
|
||||
fun fromBufferedImage(bi: BufferedImage): Img {
|
||||
val w = bi.width
|
||||
val h = bi.height
|
||||
val pixels = IntArray(w * h)
|
||||
bi.getRGB(0, 0, w, h, pixels, 0, w)
|
||||
return Img(pixels, w, h)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package de.softwareapp_hb.fotodup.finder.bench
|
||||
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Answers the cost question the all-duplicates benchmark could not:
|
||||
*
|
||||
* **how much of a realistic library would an expensive second stage have to touch?**
|
||||
*
|
||||
* The floor is the share of photos that genuinely have a near-duplicate — a verifier cannot
|
||||
* avoid those. Everything above that floor is what stage 1's false positives cost.
|
||||
*/
|
||||
internal object LibraryBench {
|
||||
|
||||
/** Slack added to the tight stage-1 threshold to produce the "loose" one. */
|
||||
private const val LOOSE_SLACK = 6
|
||||
|
||||
private class Candidate(val a: Int, val b: Int, val stage1: Int, val positive: Boolean)
|
||||
|
||||
private class Outcome(
|
||||
val name: String,
|
||||
val tp: Int,
|
||||
val fp: Int,
|
||||
val fn: Int,
|
||||
val candidatePairs: Int,
|
||||
val candidatePhotos: Int,
|
||||
) {
|
||||
val precision = if (tp + fp == 0) 1.0 else tp.toDouble() / (tp + fp)
|
||||
val recall = if (tp + fn == 0) 1.0 else tp.toDouble() / (tp + fn)
|
||||
val f1 = if (precision + recall == 0.0) 0.0 else 2 * precision * recall / (precision + recall)
|
||||
}
|
||||
|
||||
fun run(
|
||||
sceneCount: Int,
|
||||
density: Double,
|
||||
verifiers: List<Verifier>,
|
||||
seed: Int = 42,
|
||||
): String {
|
||||
val library = LibraryModel.build(sceneCount, density, seed, verifiers)
|
||||
val n = library.imageCount
|
||||
val text = StringBuilder()
|
||||
|
||||
// `LibraryModel.build` appends a duplicate copy immediately after its original, so a
|
||||
// duplicate pair is always (k, k+1). Skipping those is then an array lookup instead of
|
||||
// a hash-set probe on millions of pairs.
|
||||
val isDuplicateCopy = BooleanArray(n)
|
||||
library.duplicatePairs.forEach { pair ->
|
||||
require(pair[1] == pair[0] + 1) { "duplicate copies must be adjacent" }
|
||||
isDuplicateCopy[pair[1]] = true
|
||||
}
|
||||
fun isDuplicatePair(a: Int, b: Int) = b == a + 1 && isDuplicateCopy[b]
|
||||
|
||||
// Pass 1: exact negative-distance histogram — millions of pairs, no per-pair storage.
|
||||
val negativeHistogram = IntArray(65)
|
||||
for (a in 0 until n) {
|
||||
for (b in a + 1 until n) {
|
||||
if (isDuplicatePair(a, b)) continue
|
||||
negativeHistogram[library.stage1Distance(a, b)]++
|
||||
}
|
||||
}
|
||||
|
||||
fun falsePositivesUpTo(threshold: Int) = (0..threshold).sumOf { negativeHistogram[it] }
|
||||
val tight = (0..64).last { falsePositivesUpTo(it) == 0 }
|
||||
val loose = tight + LOOSE_SLACK
|
||||
val totalDuplicates = library.duplicatePairs.size
|
||||
val duplicatePhotos = totalDuplicates * 2
|
||||
|
||||
// Pass 2: only the pairs stage 1 proposes — a tiny fraction of the negative pairs.
|
||||
val candidates = ArrayList<Candidate>()
|
||||
for (a in 0 until n) {
|
||||
for (b in a + 1 until n) {
|
||||
if (isDuplicatePair(a, b)) continue
|
||||
val distance = library.stage1Distance(a, b)
|
||||
if (distance <= loose) {
|
||||
candidates += Candidate(a, b, distance, positive = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
library.duplicatePairs.forEach { pair ->
|
||||
val distance = library.stage1Distance(pair[0], pair[1])
|
||||
if (distance <= loose) {
|
||||
candidates += Candidate(pair[0], pair[1], distance, positive = true)
|
||||
}
|
||||
}
|
||||
|
||||
fun photosInPairs(threshold: Int): Int {
|
||||
val seen = HashSet<Int>()
|
||||
candidates.forEach { candidate ->
|
||||
if (candidate.stage1 <= threshold) {
|
||||
seen += candidate.a
|
||||
seen += candidate.b
|
||||
}
|
||||
}
|
||||
return seen.size
|
||||
}
|
||||
|
||||
text.appendLine(
|
||||
"scenes=$sceneCount duplicate rate=%.0f%% library images=%d duplicate pairs=%d".format(
|
||||
Locale.US, density * 100, n, totalDuplicates,
|
||||
),
|
||||
)
|
||||
text.appendLine(
|
||||
"photos genuinely in a duplicate pair: $duplicatePhotos " +
|
||||
"(%.1f%% of the library — the floor a verifier cannot go below)".format(
|
||||
Locale.US, 100.0 * duplicatePhotos / n,
|
||||
),
|
||||
)
|
||||
text.appendLine("stage 1 = pHash; tight=$tight (zero false positives); loose=$loose")
|
||||
text.appendLine()
|
||||
text.appendLine(
|
||||
"policy prec recall F1 | cand pairs stage-2 photos",
|
||||
)
|
||||
|
||||
fun line(outcome: Outcome) {
|
||||
text.appendLine(
|
||||
" %-38s %6.3f %6.3f %6.3f | %10d %6d (%.1f%% of library)".format(
|
||||
Locale.US, outcome.name, outcome.precision, outcome.recall, outcome.f1,
|
||||
outcome.candidatePairs, outcome.candidatePhotos,
|
||||
100.0 * outcome.candidatePhotos / n,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fun stage1Only(name: String, threshold: Int): Outcome {
|
||||
val missed = library.duplicatePairs.count {
|
||||
library.stage1Distance(it[0], it[1]) > threshold
|
||||
}
|
||||
val tp = totalDuplicates - missed
|
||||
val fp = falsePositivesUpTo(threshold)
|
||||
return Outcome(name, tp, fp, missed, tp + fp, photosInPairs(threshold))
|
||||
}
|
||||
|
||||
line(stage1Only("A) stage 1 only, thr $tight", tight))
|
||||
line(stage1Only("B) stage 1 only, thr $loose", loose))
|
||||
|
||||
// The verifier's cost is fixed by stage 1: it needs a signature for every photo that
|
||||
// appears in a pair stage 1 proposed. The cutoff only changes what it decides.
|
||||
val stage2Photos = photosInPairs(loose)
|
||||
|
||||
verifiers.forEachIndexed { v, verifier ->
|
||||
val best = verifier.cutoffs().map { cutoff ->
|
||||
var tp = 0
|
||||
var fp = 0
|
||||
candidates.forEach { candidate ->
|
||||
if (candidate.stage1 > loose) return@forEach
|
||||
val distance = verifier.distance(
|
||||
library.verifierSignatures[v][candidate.a],
|
||||
library.verifierSignatures[v][candidate.b],
|
||||
)
|
||||
if (distance <= cutoff) {
|
||||
if (candidate.positive) tp++ else fp++
|
||||
}
|
||||
}
|
||||
Outcome(
|
||||
name = "C) thr $loose + verifier <= %.2f".format(Locale.US, cutoff),
|
||||
tp = tp,
|
||||
fp = fp,
|
||||
fn = totalDuplicates - tp,
|
||||
candidatePairs = tp + fp,
|
||||
candidatePhotos = stage2Photos,
|
||||
)
|
||||
}.maxBy { it.f1 }
|
||||
line(best)
|
||||
text.appendLine(" ^ best cutoff for ${verifier.label}")
|
||||
}
|
||||
|
||||
text.appendLine()
|
||||
text.appendLine(
|
||||
"reading: a stage-2 verifier earns its place only if row C beats row B on recall",
|
||||
)
|
||||
text.appendLine(
|
||||
"without losing precision, and with a stage-2 photo count close to the floor above.",
|
||||
)
|
||||
text.appendLine(
|
||||
"false-positive candidate pairs at the loose threshold: ${candidates.count { !it.positive }}",
|
||||
)
|
||||
return text.toString()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package de.softwareapp_hb.fotodup.finder.bench
|
||||
|
||||
import de.softwareapp_hb.fotodup.finder.core.PerceptualHash
|
||||
import kotlin.random.Random
|
||||
|
||||
/**
|
||||
* A synthetic photo library — mostly unique photos plus a minority of near-duplicate copies
|
||||
* — described **only by signatures**.
|
||||
*
|
||||
* Images are generated, hashed and discarded immediately, so a library of a few thousand
|
||||
* photos costs a couple of megabytes instead of gigabytes of pixels.
|
||||
*/
|
||||
internal object LibraryModel {
|
||||
|
||||
const val WIDTH = 320
|
||||
const val HEIGHT = 240
|
||||
|
||||
/**
|
||||
* Transformations a real re-save or edit produces.
|
||||
*
|
||||
* Extreme geometry (90°/180°/mirror) is excluded: those are unusual duplicates and *no*
|
||||
* binary descriptor handles them, so including them would depress every number by the
|
||||
* same amount without telling us anything.
|
||||
*/
|
||||
val duplicateTransforms = ImageLab.transforms.filterNot {
|
||||
it.label in setOf("rotate 90", "rotate 180", "flip horizontal")
|
||||
}
|
||||
|
||||
class Library(
|
||||
val imageCount: Int,
|
||||
val stage1: LongArray,
|
||||
/** Ground-truth near-duplicate pairs, as image indices. */
|
||||
val duplicatePairs: List<IntArray>,
|
||||
/** The transform that produced each duplicate pair, aligned with [duplicatePairs]. */
|
||||
val duplicateLabels: List<String>,
|
||||
val verifierSignatures: List<Array<LongArray>>,
|
||||
) {
|
||||
fun stage1Distance(a: Int, b: Int): Int =
|
||||
PerceptualHash.hammingDistance(stage1[a], stage1[b])
|
||||
|
||||
/** Share of photo pairs that are actually duplicates, as a percentage. */
|
||||
val densityPercent: Double
|
||||
get() = 100.0 * duplicatePairs.size / imageCount
|
||||
}
|
||||
|
||||
fun build(
|
||||
sceneCount: Int,
|
||||
density: Double,
|
||||
seed: Int,
|
||||
verifiers: List<Verifier>,
|
||||
): Library {
|
||||
val random = Random(seed)
|
||||
val stage1 = ArrayList<Long>()
|
||||
val signatures = List(verifiers.size) { ArrayList<LongArray>() }
|
||||
val pairs = ArrayList<IntArray>()
|
||||
val labels = ArrayList<String>()
|
||||
|
||||
fun add(img: Img): Int {
|
||||
val index = stage1.size
|
||||
stage1 += PerceptualHash.phashFromArgb(img.pixels, img.width, img.height)
|
||||
verifiers.forEachIndexed { v, verifier -> signatures[v] += verifier.signature(img) }
|
||||
return index
|
||||
}
|
||||
|
||||
for (scene in 0 until sceneCount) {
|
||||
val original = ImageLab.syntheticImage(seed + scene, WIDTH, HEIGHT)
|
||||
val originalIndex = add(original)
|
||||
if (random.nextDouble() < density) {
|
||||
val transform = duplicateTransforms[random.nextInt(duplicateTransforms.size)]
|
||||
val copyIndex = add(transform.apply(original))
|
||||
pairs += intArrayOf(originalIndex, copyIndex)
|
||||
labels += transform.label
|
||||
}
|
||||
}
|
||||
|
||||
return Library(
|
||||
imageCount = stage1.size,
|
||||
stage1 = stage1.toLongArray(),
|
||||
duplicatePairs = pairs,
|
||||
duplicateLabels = labels,
|
||||
verifierSignatures = signatures.map { it.toTypedArray() },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package de.softwareapp_hb.fotodup.finder.bench
|
||||
|
||||
import de.softwareapp_hb.fotodup.finder.core.DuplicateGrouper
|
||||
import de.softwareapp_hb.fotodup.finder.core.DuplicatePolicy
|
||||
import de.softwareapp_hb.fotodup.finder.core.PerceptualHash
|
||||
import de.softwareapp_hb.fotodup.finder.core.PhotoFingerprint
|
||||
import de.softwareapp_hb.fotodup.finder.data.humanReadableBytes
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import javax.imageio.ImageIO
|
||||
|
||||
/**
|
||||
* Runs the app's **real** grouping logic against a folder of images, on the desktop.
|
||||
*
|
||||
* Only MediaStore, the SQLite index and the progress notification need Android — the duplicate
|
||||
* engine is pure Kotlin, so the algorithm can be exercised without a phone. Prepare a folder with:
|
||||
*
|
||||
* ```
|
||||
* python3 tools/normalise-for-local-grouping.py ~/fixtures/foto-dup-edge /tmp/fotonorm
|
||||
* ./gradlew :app:testDebugUnitTest --tests '*LocalGroupingTest*' -DfotoLocal.dir=/tmp/fotonorm
|
||||
* ```
|
||||
*
|
||||
* Faithful: hashing, the adaptive threshold, banded candidate generation, the pHash∧RGB
|
||||
* conjunction, union-find clustering and the resulting groups.
|
||||
* Not faithful: MediaStore's view of what is indexed, the provider's thumbnail decode, and the
|
||||
* SQLite cache.
|
||||
*/
|
||||
class LocalGroupingTest {
|
||||
|
||||
private class Row(
|
||||
val name: String,
|
||||
val sizeBytes: Long,
|
||||
val modifiedSeconds: Long,
|
||||
val sha256: String,
|
||||
val normalised: String?,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val error: String?,
|
||||
)
|
||||
|
||||
private class Pixels(val values: IntArray, val width: Int, val height: Int)
|
||||
|
||||
@Test
|
||||
fun `group a prepared folder`() {
|
||||
val dir = System.getProperty("fotoLocal.dir").orEmpty()
|
||||
assumeTrue("set -DfotoLocal.dir=<prepared folder>", dir.isNotBlank())
|
||||
val root = File(dir)
|
||||
val manifest = File(root, "manifest.tsv")
|
||||
assumeTrue("missing ${manifest.path}", manifest.isFile)
|
||||
|
||||
val rows = manifest.readLines().filter { it.isNotBlank() }.map { line ->
|
||||
val parts = line.split('\t')
|
||||
Row(
|
||||
name = parts[0],
|
||||
sizeBytes = parts[1].toLong(),
|
||||
modifiedSeconds = parts[2].toLong(),
|
||||
sha256 = parts[3],
|
||||
normalised = parts[4].ifBlank { null },
|
||||
width = parts[5].toInt(),
|
||||
height = parts[6].toInt(),
|
||||
error = parts.getOrNull(7)?.ifBlank { null },
|
||||
)
|
||||
}
|
||||
|
||||
val fingerprints = rows.mapIndexed { index, row ->
|
||||
val pixels = row.normalised?.let { readPixels(File(root, it)) }
|
||||
PhotoFingerprint(
|
||||
id = index.toLong(),
|
||||
sizeBytes = row.sizeBytes,
|
||||
dateModifiedSeconds = row.modifiedSeconds,
|
||||
width = row.width,
|
||||
height = row.height,
|
||||
contentHash = row.sha256,
|
||||
perceptualHash = pixels?.let {
|
||||
PerceptualHash.phashFromArgb(it.values, it.width, it.height)
|
||||
},
|
||||
rgbDHash = pixels?.let {
|
||||
PerceptualHash.rgbDHashFromArgb(it.values, it.width, it.height)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
val result = DuplicateGrouper.findGroupsDetailed(fingerprints, DuplicatePolicy.BALANCED)
|
||||
val nameOf = fingerprints.associate { it.id to rows[it.id.toInt()].name }
|
||||
val unreadable = rows.filter { it.error != null }
|
||||
|
||||
val report = StringBuilder()
|
||||
report.appendLine("images=${fingerprints.size} groups=${result.groups.size}")
|
||||
report.appendLine(
|
||||
"effective cut: pHash ≤ ${result.thresholds.phashDistance}, " +
|
||||
"RGB ≤ ${result.thresholds.rgbDistance}" +
|
||||
if (result.usedFallbackThreshold) " (fallback to the ceiling)" else " (fitted)",
|
||||
)
|
||||
report.appendLine("candidate pairs proposed by the band index: ${result.observedPairs}")
|
||||
report.appendLine("unreadable (${unreadable.size}): ${unreadable.joinToString { it.name }}")
|
||||
report.appendLine()
|
||||
if (result.groups.isEmpty()) report.appendLine(" (no duplicate groups)")
|
||||
result.groups.forEach { group ->
|
||||
report.appendLine(
|
||||
"${group.kind} — ${group.members.size} copies · " +
|
||||
"${humanReadableBytes(group.reclaimableBytes)} reclaimable",
|
||||
)
|
||||
group.members.forEach { member ->
|
||||
report.appendLine(
|
||||
" ${nameOf[member.id]} (${humanReadableBytes(member.sizeBytes)})",
|
||||
)
|
||||
}
|
||||
}
|
||||
println(report)
|
||||
}
|
||||
|
||||
private fun readPixels(file: File): Pixels? {
|
||||
val image = runCatching { ImageIO.read(file) }.getOrNull() ?: return null
|
||||
val width = image.width
|
||||
val height = image.height
|
||||
val values = IntArray(width * height)
|
||||
image.getRGB(0, 0, width, height, values, 0, width)
|
||||
return Pixels(values, width, height)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package de.softwareapp_hb.fotodup.finder.bench
|
||||
|
||||
import de.softwareapp_hb.fotodup.finder.core.PerceptualHash
|
||||
import java.util.Locale
|
||||
|
||||
/** A 64-bit descriptor under test. */
|
||||
internal enum class Descriptor(val label: String) {
|
||||
DHASH("dHash (current)") {
|
||||
override fun hash(img: Img): Long =
|
||||
PerceptualHash.fromArgb(img.pixels, img.width, img.height)
|
||||
},
|
||||
PHASH("pHash (DCT)") {
|
||||
override fun hash(img: Img): Long =
|
||||
PerceptualHash.phashFromArgb(img.pixels, img.width, img.height)
|
||||
},
|
||||
;
|
||||
|
||||
abstract fun hash(img: Img): Long
|
||||
}
|
||||
|
||||
/**
|
||||
* Measures how well each descriptor separates real near-duplicates (a base image vs a
|
||||
* transformed copy of itself) from unrelated images.
|
||||
*
|
||||
* Reports, per descriptor: hashing cost, the Hamming-distance distributions, a
|
||||
* precision/recall/F1 sweep over thresholds, and per-transform recall. That makes the
|
||||
* dHash-vs-pHash choice a measurement rather than an opinion.
|
||||
*/
|
||||
internal object SimilarityBench {
|
||||
|
||||
/** One operating point of the threshold sweep. */
|
||||
private class Point(val threshold: Int, val tp: Int, val fp: Int, val fn: Int) {
|
||||
val precision = if (tp + fp == 0) 1.0 else tp.toDouble() / (tp + fp)
|
||||
val recall = if (tp + fn == 0) 1.0 else tp.toDouble() / (tp + fn)
|
||||
val f1 = if (precision + recall == 0.0) 0.0 else 2 * precision * recall / (precision + recall)
|
||||
}
|
||||
|
||||
fun run(bases: List<Img>, thresholds: IntRange = 0..24): String {
|
||||
val report = StringBuilder()
|
||||
val transforms = ImageLab.transforms
|
||||
val positivePairs = bases.size * transforms.size
|
||||
val negativePairs = bases.size * (bases.size - 1) / 2
|
||||
|
||||
report.appendLine(
|
||||
"images=${bases.size} transforms=${transforms.size} " +
|
||||
"positive pairs=$positivePairs negative pairs=$negativePairs",
|
||||
)
|
||||
report.appendLine(
|
||||
"note: rotation and flip transforms are included on purpose — neither descriptor " +
|
||||
"is rotation invariant, so expect those rows to fail; see the per-transform table.",
|
||||
)
|
||||
report.appendLine()
|
||||
|
||||
val verdicts = mutableListOf<String>()
|
||||
|
||||
for (descriptor in Descriptor.entries) {
|
||||
// --- accuracy -----------------------------------------------------
|
||||
// Each transformed image is produced, hashed and discarded immediately, so
|
||||
// memory stays flat no matter how large the image set is.
|
||||
val baseHashes = bases.map { descriptor.hash(it) }
|
||||
val perTransform = ArrayList<IntArray>(transforms.size)
|
||||
transforms.forEach { transform ->
|
||||
val distances = IntArray(bases.size)
|
||||
bases.forEachIndexed { index, base ->
|
||||
val transformed = transform.apply(base)
|
||||
distances[index] = PerceptualHash.hammingDistance(
|
||||
baseHashes[index],
|
||||
descriptor.hash(transformed),
|
||||
)
|
||||
}
|
||||
perTransform += distances
|
||||
}
|
||||
|
||||
val positives = ArrayList<Int>(positivePairs)
|
||||
perTransform.forEach { distances -> distances.forEach { positives += it } }
|
||||
|
||||
val negatives = ArrayList<Int>(negativePairs)
|
||||
for (i in bases.indices) {
|
||||
for (j in i + 1 until bases.size) {
|
||||
negatives += PerceptualHash.hammingDistance(baseHashes[i], baseHashes[j])
|
||||
}
|
||||
}
|
||||
|
||||
// --- hash cost, measured on its own -------------------------------
|
||||
// Only the descriptor is inside the timed region: image transforms cost far
|
||||
// more than hashing and would otherwise drown the number we care about.
|
||||
repeat(3) { bases.forEach { descriptor.hash(it) } } // JIT warm-up
|
||||
val repeats = 5
|
||||
val timingStarted = System.nanoTime()
|
||||
repeat(repeats) { bases.forEach { descriptor.hash(it) } }
|
||||
val elapsedMs = (System.nanoTime() - timingStarted) / 1_000_000.0
|
||||
val timedImages = bases.size * repeats
|
||||
|
||||
report.appendLine("== ${descriptor.label} ==")
|
||||
report.appendLine(
|
||||
" hash cost %.3f ms/image (%.0f images/s; %d hashes in %.0f ms)".format(
|
||||
Locale.US,
|
||||
elapsedMs / timedImages,
|
||||
timedImages / (elapsedMs / 1000.0),
|
||||
timedImages,
|
||||
elapsedMs,
|
||||
),
|
||||
)
|
||||
report.appendLine(" duplicate distances: ${describe(positives)}")
|
||||
report.appendLine(" unrelated distances: ${describe(negatives)}")
|
||||
report.appendLine(" thr | TP FP FN | precision recall F1")
|
||||
|
||||
val sweep = thresholds.map { t ->
|
||||
Point(
|
||||
threshold = t,
|
||||
tp = positives.count { it <= t },
|
||||
fp = negatives.count { it <= t },
|
||||
fn = positives.count { it > t },
|
||||
)
|
||||
}
|
||||
sweep.forEach { point ->
|
||||
report.appendLine(
|
||||
" %3d | %4d %5d %5d | %9.3f %6.3f %6.3f".format(
|
||||
Locale.US, point.threshold, point.tp, point.fp, point.fn,
|
||||
point.precision, point.recall, point.f1,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
val bestF1 = sweep.maxBy { it.f1 }
|
||||
report.appendLine(
|
||||
" best F1 %.3f at threshold %d%s".format(
|
||||
Locale.US,
|
||||
bestF1.f1,
|
||||
bestF1.threshold,
|
||||
if (bestF1.threshold == thresholds.last) " (raise the upper bound!)" else "",
|
||||
),
|
||||
)
|
||||
|
||||
// The operating point that matters in production: the widest threshold that
|
||||
// still produces no false positives at all.
|
||||
val safe = sweep.lastOrNull { it.fp == 0 }
|
||||
val operatingThreshold = safe?.threshold ?: sweep.first().threshold
|
||||
report.appendLine(
|
||||
" zero false positives up to threshold $operatingThreshold " +
|
||||
"-> recall %.3f, F1 %.3f".format(Locale.US, safe?.recall ?: 0.0, safe?.f1 ?: 0.0),
|
||||
)
|
||||
verdicts += " %-16s thr %2d recall %.3f F1 %.3f (precision %.3f)".format(
|
||||
Locale.US, descriptor.label, operatingThreshold,
|
||||
safe?.recall ?: 0.0, safe?.f1 ?: 0.0, safe?.precision ?: 0.0,
|
||||
)
|
||||
|
||||
report.appendLine(" recall per transform at threshold $operatingThreshold:")
|
||||
transforms.forEachIndexed { index, transform ->
|
||||
val hits = perTransform[index].count { it <= operatingThreshold }
|
||||
report.appendLine(
|
||||
" %-16s %3d%%".format(Locale.US, transform.label, hits * 100 / bases.size),
|
||||
)
|
||||
}
|
||||
report.appendLine()
|
||||
}
|
||||
|
||||
report.appendLine("== verdict: best threshold with ZERO false positives ==")
|
||||
verdicts.forEach { report.appendLine(it) }
|
||||
return report.toString()
|
||||
}
|
||||
|
||||
private fun describe(values: List<Int>): String {
|
||||
if (values.isEmpty()) return "n/a"
|
||||
val sorted = values.sorted()
|
||||
fun percentile(q: Double) = sorted[((sorted.size - 1) * q).toInt()]
|
||||
return "min=${sorted.first()} p5=${percentile(0.05)} median=${percentile(0.5)} " +
|
||||
"p95=${percentile(0.95)} max=${sorted.last()}"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package de.softwareapp_hb.fotodup.finder.bench
|
||||
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Opt-in benchmark comparing the perceptual descriptors.
|
||||
*
|
||||
* It is skipped in a normal test run. To execute it:
|
||||
*
|
||||
* ```
|
||||
* # synthetic images
|
||||
* ./gradlew :app:testDebugUnitTest --tests '*SimilarityBenchmarkTest*' -DfotoBench=true
|
||||
*
|
||||
* # your own photos
|
||||
* ./gradlew :app:testDebugUnitTest --tests '*SimilarityBenchmarkTest*' \
|
||||
* -DfotoBench=true -DfotoBench.dir=/path/to/photos
|
||||
* ```
|
||||
*
|
||||
* The report is written to `app/build/reports/similarity-benchmark.txt`.
|
||||
*/
|
||||
class SimilarityBenchmarkTest {
|
||||
|
||||
@Test
|
||||
fun `compare dHash and pHash on transformed images`() {
|
||||
assumeTrue("set -DfotoBench=true to run", System.getProperty("fotoBench") == "true")
|
||||
|
||||
val dir = System.getProperty("fotoBench.dir").orEmpty()
|
||||
val bases = if (dir.isNotBlank()) {
|
||||
val max = System.getProperty("fotoBench.max")?.toIntOrNull() ?: ImageLab.DEFAULT_MAX_IMAGES
|
||||
val loaded = ImageLab.loadFrom(File(dir), maxImages = max)
|
||||
assumeTrue("fewer than 5 usable images in $dir", loaded.size >= 5)
|
||||
println("loaded ${loaded.size} real photographs from $dir")
|
||||
loaded
|
||||
} else {
|
||||
ImageLab.syntheticBases(count = System.getProperty("fotoBench.count")?.toIntOrNull() ?: 60)
|
||||
}
|
||||
|
||||
val report = SimilarityBench.run(bases)
|
||||
write("similarity-benchmark.txt", report)
|
||||
|
||||
val cascadeReport = CascadeBench.run(bases)
|
||||
write("cascade-benchmark.txt", cascadeReport)
|
||||
|
||||
val density = System.getProperty("fotoBench.density")?.toDoubleOrNull() ?: 0.15
|
||||
val scenes = System.getProperty("fotoBench.scenes")?.toIntOrNull() ?: 2500
|
||||
val libraryReport = LibraryBench.run(
|
||||
sceneCount = scenes,
|
||||
density = density,
|
||||
verifiers = listOf(ColourHistogramVerifier, ColourDHashVerifier),
|
||||
)
|
||||
write("library-benchmark.txt", libraryReport)
|
||||
}
|
||||
|
||||
private fun write(name: String, report: String) {
|
||||
val out = File("build/reports/$name")
|
||||
out.parentFile?.mkdirs()
|
||||
out.writeText(report)
|
||||
println(report)
|
||||
println("report written to ${out.absolutePath}")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package de.softwareapp_hb.fotodup.finder.bench
|
||||
|
||||
import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* A second-stage verifier: comparatively expensive per photo, but only ever run on photos
|
||||
* that already passed the cheap stage-1 filter.
|
||||
*
|
||||
* Signatures are `LongArray` so both packed binary hashes and quantised histograms fit the
|
||||
* same shape.
|
||||
*/
|
||||
internal interface Verifier {
|
||||
val label: String
|
||||
|
||||
fun signature(img: Img): LongArray
|
||||
|
||||
/** Distance between two signatures; the scale is verifier-specific. */
|
||||
fun distance(a: LongArray, b: LongArray): Double
|
||||
|
||||
/** Cutoffs to sweep, ordered from strict to loose. */
|
||||
fun cutoffs(): List<Double>
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalised 4x4x4 RGB histogram compared with L1 distance.
|
||||
*
|
||||
* This captures **colour only, with no spatial information** — which is exactly why it is
|
||||
* orthogonal to a grayscale structural hash and could catch hash collisions that share
|
||||
* structure but differ in colour.
|
||||
*/
|
||||
internal object ColourHistogramVerifier : Verifier {
|
||||
|
||||
override val label = "colour histogram 4x4x4 (L1)"
|
||||
|
||||
private const val BINS = 64
|
||||
private const val SCALE = 10_000L
|
||||
|
||||
override fun signature(img: Img): LongArray {
|
||||
val counts = IntArray(BINS)
|
||||
val pixels = img.pixels
|
||||
for (i in pixels.indices) {
|
||||
val p = pixels[i]
|
||||
val r = ((p shr 16) and 0xFF) shr 6
|
||||
val g = ((p shr 8) and 0xFF) shr 6
|
||||
val b = (p and 0xFF) shr 6
|
||||
counts[(r shl 4) or (g shl 2) or b]++
|
||||
}
|
||||
val total = pixels.size.coerceAtLeast(1)
|
||||
return LongArray(BINS) { (counts[it].toLong() * SCALE) / total }
|
||||
}
|
||||
|
||||
override fun distance(a: LongArray, b: LongArray): Double {
|
||||
var sum = 0L
|
||||
for (i in a.indices) sum += abs(a[i] - b[i])
|
||||
return sum.toDouble() / SCALE
|
||||
}
|
||||
|
||||
override fun cutoffs(): List<Double> =
|
||||
generateSequence(0.04) { it + 0.04 }.takeWhile { it <= 0.80 }.toList()
|
||||
}
|
||||
|
||||
/**
|
||||
* One 64-bit difference hash per RGB channel, compared by the sum of the three Hamming
|
||||
* distances. Structural, unlike the colour histogram, so a good cross-check on it.
|
||||
*/
|
||||
internal object ColourDHashVerifier : Verifier {
|
||||
|
||||
override val label = "RGB dHash 3x64 bit (Hamming sum)"
|
||||
|
||||
private const val GRID_WIDTH = 9
|
||||
private const val GRID_HEIGHT = 8
|
||||
|
||||
override fun signature(img: Img): LongArray = LongArray(3) { channel ->
|
||||
differenceHash(img, shift = when (channel) {
|
||||
0 -> 16
|
||||
1 -> 8
|
||||
else -> 0
|
||||
})
|
||||
}
|
||||
|
||||
override fun distance(a: LongArray, b: LongArray): Double {
|
||||
var sum = 0
|
||||
for (i in a.indices) sum += java.lang.Long.bitCount(a[i] xor b[i])
|
||||
return sum.toDouble()
|
||||
}
|
||||
|
||||
override fun cutoffs(): List<Double> =
|
||||
(0..60 step 3).map { it.toDouble() }
|
||||
|
||||
private fun differenceHash(img: Img, shift: Int): Long {
|
||||
val grid = IntArray(GRID_WIDTH * GRID_HEIGHT)
|
||||
for (y in 0 until GRID_HEIGHT) {
|
||||
val y0 = y * img.height / GRID_HEIGHT
|
||||
val y1 = maxOf(y0 + 1, (y + 1) * img.height / GRID_HEIGHT)
|
||||
for (x in 0 until GRID_WIDTH) {
|
||||
val x0 = x * img.width / GRID_WIDTH
|
||||
val x1 = maxOf(x0 + 1, (x + 1) * img.width / GRID_WIDTH)
|
||||
var sum = 0L
|
||||
var count = 0
|
||||
for (yy in y0 until minOf(y1, img.height)) {
|
||||
val row = yy * img.width
|
||||
for (xx in x0 until minOf(x1, img.width)) {
|
||||
sum += (img.pixels[row + xx] shr shift) and 0xFF
|
||||
count++
|
||||
}
|
||||
}
|
||||
grid[y * GRID_WIDTH + x] = if (count == 0) 0 else (sum / count).toInt()
|
||||
}
|
||||
}
|
||||
|
||||
var hash = 0L
|
||||
var bit = 0
|
||||
for (y in 0 until GRID_HEIGHT) {
|
||||
val row = y * GRID_WIDTH
|
||||
for (x in 0 until GRID_WIDTH - 1) {
|
||||
if (grid[row + x] > grid[row + x + 1]) hash = hash or (1L shl bit)
|
||||
bit++
|
||||
}
|
||||
}
|
||||
return hash
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import kotlin.math.exp
|
||||
|
||||
class AdaptiveThresholdTest {
|
||||
|
||||
private fun gaussianHistogram(
|
||||
population: Int,
|
||||
mean: Double,
|
||||
sd: Double,
|
||||
spike: IntArray = IntArray(0),
|
||||
): IntArray {
|
||||
val histogram = IntArray(65)
|
||||
for (d in 0..64) {
|
||||
val z = (d - mean) / sd
|
||||
val density = exp(-0.5 * z * z) / (sd * SQRT_TWO_PI)
|
||||
histogram[d] = (population * density).toInt()
|
||||
}
|
||||
spike.forEachIndexed { index, count ->
|
||||
if (index < histogram.size) histogram[index] += count
|
||||
}
|
||||
return histogram
|
||||
}
|
||||
|
||||
/** Rough shape of the unrelated-pair distances seen in the benchmark runs. */
|
||||
private fun unrelated(population: Int, spike: IntArray = IntArray(0)) =
|
||||
gaussianHistogram(population, mean = 32.0, sd = 8.0, spike = spike)
|
||||
|
||||
@Test
|
||||
fun `too little data falls back to the configured ceiling`() {
|
||||
val choice = AdaptiveThreshold.choose(unrelated(10), ceiling = 12, budget = 2.0)
|
||||
assertTrue(choice.usedFallback)
|
||||
assertEquals(12, choice.threshold)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a realistic library narrows the threshold below the ceiling`() {
|
||||
val choice = AdaptiveThreshold.choose(unrelated(2_000), ceiling = 12, budget = 2.0)
|
||||
assertTrue("expected no fallback but got one", !choice.usedFallback)
|
||||
assertTrue("expected a threshold below the ceiling, got ${choice.threshold}", choice.threshold < 12)
|
||||
assertTrue("expected a positive threshold, got ${choice.threshold}", choice.threshold > 0)
|
||||
assertTrue("expected the budget to hold, got ${choice.expectedFalsePairs}", choice.expectedFalsePairs <= 2.0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a bigger library gets a stricter threshold`() {
|
||||
val small = AdaptiveThreshold.choose(unrelated(2_000), ceiling = 18, budget = 2.0).threshold
|
||||
val large = AdaptiveThreshold.choose(unrelated(200_000), ceiling = 18, budget = 2.0).threshold
|
||||
assertTrue("expected $large < $small", large < small)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a huge library is as strict as possible`() {
|
||||
val choice = AdaptiveThreshold.choose(unrelated(50_000_000), ceiling = 18, budget = 2.0)
|
||||
assertEquals(0, choice.threshold)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `duplicate pairs at low distances barely shift the threshold`() {
|
||||
val spike = IntArray(6) { 200 } // a few hundred genuine duplicates at distances 0..5
|
||||
val without = AdaptiveThreshold.choose(unrelated(2_000), ceiling = 12, budget = 2.0)
|
||||
val with = AdaptiveThreshold.choose(unrelated(2_000, spike), ceiling = 12, budget = 2.0)
|
||||
// The fit itself only uses distances >= 20, so the spike does not change the estimated
|
||||
// distribution. It does inflate the pair population, which moves the threshold at most
|
||||
// one bit in the safe direction.
|
||||
assertTrue(
|
||||
"expected at most a one-bit shift, got ${without.threshold} -> ${with.threshold}",
|
||||
with.threshold <= without.threshold && without.threshold - with.threshold <= 1,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a smaller budget never allows a wider threshold`() {
|
||||
val generous = AdaptiveThreshold.choose(unrelated(50_000), ceiling = 18, budget = 5.0)
|
||||
val strict = AdaptiveThreshold.choose(unrelated(50_000), ceiling = 18, budget = 0.5)
|
||||
assertTrue(strict.threshold <= generous.threshold)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val SQRT_TWO_PI = 2.5066282746310002
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class ByteUtilsTest {
|
||||
|
||||
@Test
|
||||
fun `toHex encodes with leading zeroes`() {
|
||||
assertEquals("00", byteArrayOf(0).toHex())
|
||||
assertEquals("0f", byteArrayOf(0x0F).toHex())
|
||||
assertEquals("ff", byteArrayOf(0xFF.toByte()).toHex())
|
||||
assertEquals("0102ff", byteArrayOf(1, 2, 0xFF.toByte()).toHex())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `toBigEndianBytes is eight bytes long and ordered`() {
|
||||
val bytes = 0x0102030405060708L.toBigEndianBytes()
|
||||
assertEquals(8, bytes.size)
|
||||
assertEquals(listOf<Byte>(1, 2, 3, 4, 5, 6, 7, 8), bytes.toList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `toBigEndianBytes round trips the low values`() {
|
||||
assertEquals(listOf<Byte>(0, 0, 0, 0, 0, 0, 0, 42), 42L.toBigEndianBytes().toList())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class DecodeMathTest {
|
||||
|
||||
private fun isPowerOfTwo(value: Int) = value > 0 && Integer.bitCount(value) == 1
|
||||
|
||||
@Test
|
||||
fun `a typical camera photo is subsampled to about 100 px`() {
|
||||
// 4000x3000 -> 32 gives 125x93, the first power of two inside the ~2x target window.
|
||||
assertEquals(32, DecodeMath.sampleSizeFor(4000, 3000, target = 64))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `small images are barely subsampled`() {
|
||||
// 100 px on the long edge is already inside the ~2x target window, so no subsampling.
|
||||
assertEquals(1, DecodeMath.sampleSizeFor(100, 80, target = 64))
|
||||
// 128 is exactly 2x the target, so a single halving is what the rule asks for.
|
||||
assertEquals(2, DecodeMath.sampleSizeFor(128, 128, target = 64))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `zero and negative dimensions yield a usable sample`() {
|
||||
assertEquals(1, DecodeMath.sampleSizeFor(0, 0, target = 64))
|
||||
assertEquals(1, DecodeMath.sampleSizeFor(-5, -5, target = 64))
|
||||
assertEquals(1, DecodeMath.sampleSizeFor(4000, 3000, target = 0))
|
||||
}
|
||||
|
||||
/**
|
||||
* The decompression-bomb case: a crafted file declaring enormous dimensions must not overflow,
|
||||
* and must still produce a sample that decodes to something tiny.
|
||||
*/
|
||||
@Test
|
||||
fun `absurd dimensions do not overflow`() {
|
||||
val bomb = DecodeMath.sampleSizeFor(Int.MAX_VALUE, Int.MAX_VALUE, target = 64)
|
||||
assertTrue("expected a positive power of two but got $bomb", isPowerOfTwo(bomb))
|
||||
// 2^31 / 2^19 is still ~4000 px, well inside what a decoder will accept.
|
||||
assertTrue("sample should stay bounded but was $bomb", bomb <= 1 shl 20)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sample always decodes the declared dimensions to roughly the target`() {
|
||||
val cases = listOf(200 to 150, 640 to 480, 4000 to 3000, 12000 to 9000, 100_000 to 100_000)
|
||||
for ((width, height) in cases) {
|
||||
val sample = DecodeMath.sampleSizeFor(width, height, target = 64)
|
||||
assertTrue("not a power of two for $width x $height: $sample", isPowerOfTwo(sample))
|
||||
assertTrue(
|
||||
"decoded edge stayed too large for $width x $height: ${width / sample}",
|
||||
width / sample <= 256 || width > 100_000,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class DuplicateGroupTest {
|
||||
|
||||
private fun fp(id: Long, size: Long = 1_000, date: Long = 0) = PhotoFingerprint(
|
||||
id = id,
|
||||
sizeBytes = size,
|
||||
dateModifiedSeconds = date,
|
||||
width = 100,
|
||||
height = 100,
|
||||
contentHash = "content",
|
||||
)
|
||||
|
||||
private fun group(vararg members: PhotoFingerprint) = DuplicateGroup(
|
||||
id = "g",
|
||||
kind = GroupKind.EXACT,
|
||||
members = members.toList(),
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `suggested keep is the largest file`() {
|
||||
val g = group(fp(1, size = 100), fp(2, size = 300), fp(3, size = 200))
|
||||
assertEquals(2L, g.suggestedKeep()?.id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `suggested keep breaks ties by newest`() {
|
||||
val g = group(fp(1, size = 300, date = 10), fp(2, size = 300, date = 20))
|
||||
assertEquals(2L, g.suggestedKeep()?.id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `suggested removals exclude the keep`() {
|
||||
val g = group(fp(1, size = 100), fp(2, size = 300), fp(3, size = 200))
|
||||
assertEquals(setOf(1L, 3L), g.suggestedRemovals().map { it.id }.toSet())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `display order puts the keep first and leaves the rest untouched`() {
|
||||
val g = group(
|
||||
fp(1, size = 100, date = 30),
|
||||
fp(2, size = 300, date = 10),
|
||||
fp(3, size = 200, date = 20),
|
||||
)
|
||||
// id 2 is the largest, so it moves to the front; 1 and 3 keep their order.
|
||||
assertEquals(listOf(2L, 1L, 3L), g.displayOrder().map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `display order needs no reshuffle when the keep is already first`() {
|
||||
val g = group(fp(1, size = 300, date = 5), fp(2, size = 100, date = 9))
|
||||
assertEquals(listOf(1L, 2L), g.displayOrder().map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `empty group has no keep and an empty display order`() {
|
||||
val g = group()
|
||||
assertNull(g.suggestedKeep())
|
||||
assertEquals(emptyList<Long>(), g.displayOrder().map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `reclaimable bytes keep the largest copy`() {
|
||||
val g = group(fp(1, size = 100), fp(2, size = 300))
|
||||
assertEquals(100L, g.reclaimableBytes)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `without keeps the group while at least two copies remain`() {
|
||||
val g = group(fp(1), fp(2), fp(3))
|
||||
val remaining = g.without(setOf(1L))
|
||||
assertEquals(setOf(2L, 3L), remaining?.members?.map { it.id }?.toSet())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `without drops the group once fewer than two copies remain`() {
|
||||
val g = group(fp(1), fp(2), fp(3))
|
||||
assertNull(g.without(setOf(1L, 2L)))
|
||||
assertNull(g.without(setOf(1L, 2L, 3L)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `without with no ids returns the same group`() {
|
||||
val g = group(fp(1), fp(2))
|
||||
assertEquals(g, g.without(emptySet()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `without keeps the group id so list keys stay stable`() {
|
||||
val g = group(fp(1), fp(2), fp(3))
|
||||
assertEquals("g", g.without(setOf(1L))?.id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `display order after staging picks the best of what is left`() {
|
||||
val g = group(fp(1, size = 100), fp(2, size = 300), fp(3, size = 200))
|
||||
// Stage the largest copy: the next-largest of the survivors becomes BEST.
|
||||
val remaining = g.without(setOf(2L))
|
||||
assertEquals(listOf(3L, 1L), remaining?.displayOrder()?.map { it.id })
|
||||
assertEquals(3L, remaining?.suggestedKeep()?.id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `selected members are only the ticked ones`() {
|
||||
val g = group(fp(1), fp(2), fp(3))
|
||||
assertEquals(setOf(1L, 2L), g.selectedMembers(setOf(1L, 2L, 99L)).map { it.id }.toSet())
|
||||
assertEquals(emptyList<Long>(), g.selectedMembers(emptySet()).map { it.id })
|
||||
}
|
||||
|
||||
/**
|
||||
* The reported bug: a group of BEST + DUP1 + DUP2 showed "Remove 2 duplicates" even after
|
||||
* DUP2 was unticked, because the count came from the *suggestion* rather than the selection.
|
||||
*/
|
||||
@Test
|
||||
fun `unticking a copy reduces the row removal count`() {
|
||||
val g = group(
|
||||
fp(1, size = 300), // BEST
|
||||
fp(2, size = 100), // DUP1
|
||||
fp(3, size = 100), // DUP2
|
||||
)
|
||||
|
||||
// Right after a scan everything but BEST is ticked: the row offers to remove 2.
|
||||
val ticked = g.suggestedRemovals().map { it.id }.toSet()
|
||||
assertEquals(setOf(2L, 3L), ticked)
|
||||
assertEquals(2, g.selectedMembers(ticked).size)
|
||||
|
||||
// Unticking DUP2 must immediately read as 1.
|
||||
val afterUntick = ticked - 3L
|
||||
assertEquals(1, g.selectedMembers(afterUntick).size)
|
||||
assertEquals(listOf(2L), g.selectedMembers(afterUntick).map { it.id })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class DuplicateGrouperTest {
|
||||
|
||||
private fun fp(
|
||||
id: Long,
|
||||
size: Long = 1_000,
|
||||
contentHash: String? = null,
|
||||
perceptualHash: Long? = null,
|
||||
// Derived from the pHash by default so existing tests keep their meaning; tests for the
|
||||
// colour gate pass an explicit value.
|
||||
rgbDHash: RgbDHash? = perceptualHash?.let { RgbDHash(it, it, it) },
|
||||
width: Int = 0,
|
||||
height: Int = 0,
|
||||
date: Long = 0,
|
||||
) = PhotoFingerprint(
|
||||
id = id,
|
||||
sizeBytes = size,
|
||||
dateModifiedSeconds = date,
|
||||
width = width,
|
||||
height = height,
|
||||
contentHash = contentHash,
|
||||
perceptualHash = perceptualHash,
|
||||
rgbDHash = rgbDHash,
|
||||
)
|
||||
|
||||
/**
|
||||
* The `solid-*.png` fixtures are flat colour, so every one of them hashes to exactly the same
|
||||
* perceptual fingerprint. They must therefore come back as a *single* group, not split.
|
||||
*/
|
||||
@Test
|
||||
fun `many photos with identical perceptual hashes form one group`() {
|
||||
val photos = (1L..8L).map {
|
||||
fp(it, perceptualHash = 1L, rgbDHash = RgbDHash(0L, 0L, 0L))
|
||||
}
|
||||
val groups = DuplicateGrouper.findGroups(photos, DuplicatePolicy.BALANCED)
|
||||
assertEquals(1, groups.size)
|
||||
assertEquals(8, groups.single().members.size)
|
||||
}
|
||||
|
||||
/** Same, but large enough that the adaptive threshold actually runs instead of falling back. */
|
||||
@Test
|
||||
fun `identical hashes stay together even when the adaptive fit runs`() {
|
||||
// 400 flat photos + 400 unrelated ones: the 400 identical pairs dominate the low end of
|
||||
// the candidate histogram, which must not split them apart.
|
||||
val clones = (1L..400L).map { fp(it, perceptualHash = 1L, rgbDHash = RgbDHash(0L, 0L, 0L)) }
|
||||
val others = (1L..400L).map {
|
||||
fp(1_000L + it, perceptualHash = 0x0F0F0F0F0F0F0F0FL, rgbDHash = RgbDHash(it, it, it))
|
||||
}
|
||||
val groups = DuplicateGrouper.findGroups(clones + others, DuplicatePolicy.BALANCED)
|
||||
val biggest = groups.maxBy { it.members.size }
|
||||
assertEquals(400, biggest.members.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `exact duplicates are grouped`() {
|
||||
val groups = DuplicateGrouper.findGroups(
|
||||
listOf(
|
||||
fp(1, contentHash = "h1"),
|
||||
fp(2, contentHash = "h1"),
|
||||
fp(3, contentHash = "h1"),
|
||||
fp(4, contentHash = "h2"),
|
||||
),
|
||||
DuplicatePolicy.EXACT_ONLY,
|
||||
)
|
||||
|
||||
assertEquals(1, groups.size)
|
||||
val group = groups.single()
|
||||
assertEquals(GroupKind.EXACT, group.kind)
|
||||
assertEquals(setOf(1L, 2L, 3L), group.members.map { it.id }.toSet())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unique photos produce no groups`() {
|
||||
val groups = DuplicateGrouper.findGroups(
|
||||
listOf(fp(1, contentHash = "a"), fp(2, contentHash = "b")),
|
||||
DuplicatePolicy.EXACT_ONLY,
|
||||
)
|
||||
assertTrue(groups.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `perceptually close photos are grouped`() {
|
||||
val groups = DuplicateGrouper.findGroups(
|
||||
listOf(fp(1, perceptualHash = 0L), fp(2, perceptualHash = 0b11L)),
|
||||
DuplicatePolicy.BALANCED,
|
||||
)
|
||||
assertEquals(1, groups.size)
|
||||
assertEquals(GroupKind.PERCEPTUAL, groups.single().kind)
|
||||
assertEquals(setOf(1L, 2L), groups.single().members.map { it.id }.toSet())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a pHash beyond the balanced ceiling is not grouped`() {
|
||||
// Bits 0..19 differ => distance 20, above BALANCED's pHash ceiling of 12.
|
||||
val groups = DuplicateGrouper.findGroups(
|
||||
listOf(fp(1, perceptualHash = 0L), fp(2, perceptualHash = 0b11111111111111111111L)),
|
||||
DuplicatePolicy.BALANCED,
|
||||
)
|
||||
assertTrue(groups.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a pHash within the balanced ceiling is grouped`() {
|
||||
// Distance 10 is inside BALANCED's ceiling of 12.
|
||||
val groups = DuplicateGrouper.findGroups(
|
||||
listOf(fp(1, perceptualHash = 0L), fp(2, perceptualHash = 0b1111111111L)),
|
||||
DuplicatePolicy.BALANCED,
|
||||
)
|
||||
assertEquals(1, groups.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `differing colour structure blocks a near duplicate`() {
|
||||
// Identical luminance structure, but the colour hashes are 64 bits apart on every
|
||||
// channel — beyond the RGB ceiling, so this must not be reported as a duplicate.
|
||||
val groups = DuplicateGrouper.findGroups(
|
||||
listOf(
|
||||
fp(1, perceptualHash = 0L, rgbDHash = RgbDHash(0L, 0L, 0L)),
|
||||
fp(2, perceptualHash = 0L, rgbDHash = RgbDHash(-1L, -1L, -1L)),
|
||||
),
|
||||
DuplicatePolicy.BALANCED,
|
||||
)
|
||||
assertTrue(groups.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `aggressive policy groups a distance ten pair`() {
|
||||
val groups = DuplicateGrouper.findGroups(
|
||||
listOf(fp(1, perceptualHash = 0L), fp(2, perceptualHash = 0b1111111111L)),
|
||||
DuplicatePolicy.AGGRESSIVE,
|
||||
)
|
||||
assertEquals(1, groups.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `exact only policy ignores perceptual hashes`() {
|
||||
val groups = DuplicateGrouper.findGroups(
|
||||
listOf(fp(1, perceptualHash = 0L), fp(2, perceptualHash = 0L)),
|
||||
DuplicatePolicy.EXACT_ONLY,
|
||||
)
|
||||
assertTrue(groups.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `transitive similarity forms one cluster`() {
|
||||
// 0 ~ 7 (distance 3), 7 ~ 63 (distance 3), 0 ~ 63 (distance 6).
|
||||
val groups = DuplicateGrouper.findGroups(
|
||||
listOf(fp(1, perceptualHash = 0L), fp(2, perceptualHash = 7L), fp(3, perceptualHash = 63L)),
|
||||
DuplicatePolicy.BALANCED,
|
||||
)
|
||||
assertEquals(1, groups.size)
|
||||
assertEquals(setOf(1L, 2L, 3L), groups.single().members.map { it.id }.toSet())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `exact matches are not repeated in the perceptual pass`() {
|
||||
val groups = DuplicateGrouper.findGroups(
|
||||
listOf(
|
||||
fp(1, contentHash = "same", perceptualHash = 0L),
|
||||
fp(2, contentHash = "same", perceptualHash = 0L),
|
||||
fp(3, contentHash = "other", perceptualHash = 0L),
|
||||
),
|
||||
DuplicatePolicy.BALANCED,
|
||||
)
|
||||
// One exact group of {1,2}; photo 3 differs in content and has no peer left.
|
||||
assertEquals(1, groups.size)
|
||||
assertEquals(GroupKind.EXACT, groups.single().kind)
|
||||
assertEquals(setOf(1L, 2L), groups.single().members.map { it.id }.toSet())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `different aspect ratios are not grouped`() {
|
||||
val groups = DuplicateGrouper.findGroups(
|
||||
listOf(
|
||||
fp(1, perceptualHash = 0L, width = 100, height = 100), // 1.0
|
||||
fp(2, perceptualHash = 0L, width = 300, height = 100), // 3.0
|
||||
),
|
||||
DuplicatePolicy.BALANCED,
|
||||
)
|
||||
assertTrue(groups.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unknown dimensions do not block grouping`() {
|
||||
val groups = DuplicateGrouper.findGroups(
|
||||
listOf(fp(1, perceptualHash = 0L), fp(2, perceptualHash = 0L)),
|
||||
DuplicatePolicy.BALANCED,
|
||||
)
|
||||
assertEquals(1, groups.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `reclaimable bytes keep the largest copy`() {
|
||||
val groups = DuplicateGrouper.findGroups(
|
||||
listOf(
|
||||
fp(1, size = 100, contentHash = "h"),
|
||||
fp(2, size = 300, contentHash = "h"),
|
||||
),
|
||||
DuplicatePolicy.EXACT_ONLY,
|
||||
)
|
||||
val group = groups.single()
|
||||
assertEquals(400, group.totalBytes)
|
||||
assertEquals(300, group.largestBytes)
|
||||
assertEquals(100, group.reclaimableBytes)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `members are ordered newest first`() {
|
||||
val groups = DuplicateGrouper.findGroups(
|
||||
listOf(
|
||||
fp(1, contentHash = "h", date = 10),
|
||||
fp(2, contentHash = "h", date = 20),
|
||||
),
|
||||
DuplicatePolicy.EXACT_ONLY,
|
||||
)
|
||||
assertEquals(listOf(2L, 1L), groups.single().members.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `groups are sorted by reclaimable bytes descending`() {
|
||||
val groups = DuplicateGrouper.findGroups(
|
||||
listOf(
|
||||
fp(1, size = 100, contentHash = "small"),
|
||||
fp(2, size = 100, contentHash = "small"),
|
||||
fp(3, size = 5_000, contentHash = "big"),
|
||||
fp(4, size = 5_000, contentHash = "big"),
|
||||
),
|
||||
DuplicatePolicy.EXACT_ONLY,
|
||||
)
|
||||
assertEquals(2, groups.size)
|
||||
assertEquals("big", groups.first().id.removePrefix("exact:"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.InputStream
|
||||
|
||||
class HashingTest {
|
||||
|
||||
@Test
|
||||
fun `sha256 matches the well known empty vector`() {
|
||||
assertEquals(
|
||||
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
Hashing.sha256(ByteArray(0)),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sha256 matches the well known abc vector`() {
|
||||
assertEquals(
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
|
||||
Hashing.sha256("abc".toByteArray(Charsets.UTF_8)),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `streaming sha256 equals in-memory sha256`() {
|
||||
val data = ByteArray(200_000) { (it % 251).toByte() }
|
||||
assertEquals(Hashing.sha256(data), Hashing.sha256(ByteArrayInputStream(data)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `quick signature is stable for identical input`() {
|
||||
val a = Hashing.quickSignature(size = 3, head = "abc".toByteArray(), tail = "xyz".toByteArray())
|
||||
val b = Hashing.quickSignature(size = 3, head = "abc".toByteArray(), tail = "xyz".toByteArray())
|
||||
assertEquals(a, b)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `quick signature changes with size, head and tail`() {
|
||||
val base = Hashing.quickSignature(100, "AAAA".toByteArray(), "ZZZZ".toByteArray())
|
||||
assertNotEquals(base, Hashing.quickSignature(101, "AAAA".toByteArray(), "ZZZZ".toByteArray()))
|
||||
assertNotEquals(base, Hashing.quickSignature(100, "BBBB".toByteArray(), "ZZZZ".toByteArray()))
|
||||
assertNotEquals(base, Hashing.quickSignature(100, "AAAA".toByteArray(), "YYYY".toByteArray()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `quick signature works without a tail`() {
|
||||
val a = Hashing.quickSignature(100, "AAAA".toByteArray())
|
||||
assertEquals("quick signature should be deterministic", a, Hashing.quickSignature(100, "AAAA".toByteArray()))
|
||||
assertNotEquals(a, Hashing.quickSignature(100, "BBBB".toByteArray()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `readAtMost returns fewer bytes at end of stream`() {
|
||||
assertArrayEquals(byteArrayOf(1, 2, 3), ByteArrayInputStream(byteArrayOf(1, 2, 3)).readAtMost(8))
|
||||
assertEquals(0, ByteArrayInputStream(byteArrayOf(1)).readAtMost(0).size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `readAtMost stops at the requested length`() {
|
||||
val stream = ByteArrayInputStream(byteArrayOf(1, 2, 3, 4, 5))
|
||||
assertArrayEquals(byteArrayOf(1, 2), stream.readAtMost(2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `readAtMost stops when the stream keeps reporting no data`() {
|
||||
// A non-blocking pipe-backed descriptor can return 0 for ever. The loop must treat that as
|
||||
// the end rather than spinning; the watchdog makes a regression fail instead of hanging.
|
||||
val stream = object : InputStream() {
|
||||
override fun read(): Int = 0
|
||||
override fun read(b: ByteArray, off: Int, len: Int): Int = 0
|
||||
}
|
||||
var result: ByteArray? = null
|
||||
val worker = Thread { result = stream.readAtMost(16) }.apply {
|
||||
isDaemon = true
|
||||
start()
|
||||
}
|
||||
worker.join(2_000)
|
||||
assertTrue("readAtMost did not terminate", !worker.isAlive)
|
||||
assertEquals(0, result!!.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sha256 stops when the stream keeps reporting no data`() {
|
||||
val stream = object : InputStream() {
|
||||
override fun read(): Int = 0
|
||||
override fun read(b: ByteArray, off: Int, len: Int): Int = 0
|
||||
}
|
||||
var digest: String? = null
|
||||
val worker = Thread { digest = Hashing.sha256(stream) }.apply {
|
||||
isDaemon = true
|
||||
start()
|
||||
}
|
||||
worker.join(2_000)
|
||||
assertTrue("sha256 did not terminate", !worker.isAlive)
|
||||
// Nothing was readable, so it hashes the empty input.
|
||||
assertEquals(Hashing.sha256(ByteArray(0)), digest)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package de.softwareapp_hb.fotodup.finder.core
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class PerceptualHashTest {
|
||||
|
||||
private fun gray(v: Int): Int {
|
||||
val c = v.coerceIn(0, 255)
|
||||
return (0xFF shl 24) or (c shl 16) or (c shl 8) or c
|
||||
}
|
||||
|
||||
private fun image(width: Int, height: Int, luma: (x: Int, y: Int) -> Int): IntArray {
|
||||
val pixels = IntArray(width * height)
|
||||
for (y in 0 until height) {
|
||||
for (x in 0 until width) {
|
||||
pixels[y * width + x] = gray(luma(x, y))
|
||||
}
|
||||
}
|
||||
return pixels
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hamming distance basics`() {
|
||||
assertEquals(0, PerceptualHash.hammingDistance(0L, 0L))
|
||||
assertNotEquals(0, PerceptualHash.hammingDistance(0L, 1L))
|
||||
// 0L xor -1L has all 64 bits set.
|
||||
assertEquals(64, PerceptualHash.hammingDistance(0L, -1L))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `uniform image has an empty hash`() {
|
||||
val pixels = image(PerceptualHash.GRID_WIDTH, PerceptualHash.GRID_HEIGHT) { _, _ -> 128 }
|
||||
assertEquals(0L, PerceptualHash.fromArgb(pixels, PerceptualHash.GRID_WIDTH, PerceptualHash.GRID_HEIGHT))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `strictly decreasing luminance sets every bit`() {
|
||||
// 9x8 image where each pixel is brighter than the one on its right.
|
||||
val pixels = image(PerceptualHash.GRID_WIDTH, PerceptualHash.GRID_HEIGHT) { x, _ -> 250 - x * 20 }
|
||||
val hash = PerceptualHash.fromArgb(pixels, PerceptualHash.GRID_WIDTH, PerceptualHash.GRID_HEIGHT)
|
||||
assertEquals(-1L, hash)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `increasing luminance clears every bit and is far from the inverse`() {
|
||||
val width = PerceptualHash.GRID_WIDTH
|
||||
val height = PerceptualHash.GRID_HEIGHT
|
||||
val decreasing = PerceptualHash.fromArgb(image(width, height) { x, _ -> 250 - x * 20 }, width, height)
|
||||
val increasing = PerceptualHash.fromArgb(image(width, height) { x, _ -> 10 + x * 20 }, width, height)
|
||||
assertEquals(0L, increasing)
|
||||
assertEquals(64, PerceptualHash.hammingDistance(decreasing, increasing))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromLumaGrid sets the expected bits`() {
|
||||
// Row-major 9x8 grid, all rows identical: bright for x<=4, dark afterwards.
|
||||
val luma = IntArray(PerceptualHash.GRID_WIDTH * PerceptualHash.GRID_HEIGHT) { index ->
|
||||
val x = index % PerceptualHash.GRID_WIDTH
|
||||
if (x <= 4) 200 else 0
|
||||
}
|
||||
val expected = (0 until 8).fold(0L) { acc, row -> acc or (1L shl (row * 8 + 4)) }
|
||||
assertEquals(expected, PerceptualHash.fromLumaGrid(luma))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromLumaGrid rejects the wrong grid size`() {
|
||||
try {
|
||||
PerceptualHash.fromLumaGrid(IntArray(10))
|
||||
throw AssertionError("expected IllegalArgumentException")
|
||||
} catch (expected: IllegalArgumentException) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `similar images stay close`() {
|
||||
val width = 64
|
||||
val height = 64
|
||||
val base = image(width, height) { x, _ -> x * 4 }
|
||||
// Same image with a subtle brightness bump on the left half.
|
||||
val tweaked = image(width, height) { x, _ -> (x * 4 + if (x < 32) 6 else 0) }
|
||||
val distance = PerceptualHash.hammingDistance(
|
||||
PerceptualHash.fromArgb(base, width, height),
|
||||
PerceptualHash.fromArgb(tweaked, width, height),
|
||||
)
|
||||
assertTrue("expected a small distance but was $distance", distance <= 6)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `luminance uses Rec 601 weights`() {
|
||||
assertEquals(255, PerceptualHash.luminance(gray(255)))
|
||||
assertEquals(0, PerceptualHash.luminance(gray(0)))
|
||||
// Pure green is much brighter than pure blue for the human eye.
|
||||
val green = (0xFF shl 24) or (0x00 shl 16) or (0xFF shl 8) or 0x00
|
||||
val blue = (0xFF shl 24) or (0x00 shl 16) or (0x00 shl 8) or 0xFF
|
||||
assertTrue(PerceptualHash.luminance(green) > PerceptualHash.luminance(blue))
|
||||
}
|
||||
|
||||
// --- pHash (DCT) --------------------------------------------------------
|
||||
|
||||
/** Structured 32x32 test image; r=g=b so the luminance is exact, not rounded. */
|
||||
private fun pattern(offset: Int) = image(32, 32) { x, y -> offset + (x * 3 + y * 5) % 60 }
|
||||
|
||||
@Test
|
||||
fun `phash is deterministic`() {
|
||||
val pixels = pattern(30)
|
||||
assertEquals(
|
||||
PerceptualHash.phashFromArgb(pixels, 32, 32),
|
||||
PerceptualHash.phashFromArgb(pixels, 32, 32),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A uniform brightness offset changes only the DC coefficient, so the AC coefficients
|
||||
* — and therefore the median and every bit — are unchanged. This is the robustness
|
||||
* that motivated the descriptor.
|
||||
*/
|
||||
@Test
|
||||
fun `phash ignores a uniform brightness offset`() {
|
||||
assertEquals(
|
||||
PerceptualHash.phashFromArgb(pattern(offset = 40), 32, 32),
|
||||
PerceptualHash.phashFromArgb(pattern(offset = 80), 32, 32),
|
||||
)
|
||||
}
|
||||
|
||||
/** Likewise a gain scales every coefficient equally, preserving the comparison. */
|
||||
@Test
|
||||
fun `phash ignores a uniform brightness gain`() {
|
||||
val base = pattern(offset = 40).copyOf()
|
||||
val doubled = IntArray(base.size) { i ->
|
||||
val p = base[i]
|
||||
val v = ((p and 0xFF) * 2).coerceAtMost(255)
|
||||
(0xFF shl 24) or (v shl 16) or (v shl 8) or v
|
||||
}
|
||||
assertEquals(
|
||||
PerceptualHash.phashFromArgb(base, 32, 32),
|
||||
PerceptualHash.phashFromArgb(doubled, 32, 32),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `phash separates structurally opposite images`() {
|
||||
val increasing = image(32, 32) { x, _ -> x * 6 }
|
||||
val decreasing = image(32, 32) { x, _ -> 250 - x * 6 }
|
||||
val distance = PerceptualHash.hammingDistance(
|
||||
PerceptualHash.phashFromArgb(increasing, 32, 32),
|
||||
PerceptualHash.phashFromArgb(decreasing, 32, 32),
|
||||
)
|
||||
assertTrue("expected a large distance but was $distance", distance >= 30)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `phash rejects the wrong grid size`() {
|
||||
try {
|
||||
PerceptualHash.phashFromLumaGrid(IntArray(10))
|
||||
throw AssertionError("expected IllegalArgumentException")
|
||||
} catch (expected: IllegalArgumentException) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package de.softwareapp_hb.fotodup.finder.data
|
||||
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import kotlin.system.measureTimeMillis
|
||||
|
||||
/**
|
||||
* The regression behind the device hang: a `ContentResolver` call that never returns used to
|
||||
* freeze the whole scan, because a coroutine timeout cannot interrupt a thread parked in a
|
||||
* binder transaction. These tests pin the behaviour that fixes it — the caller gives up, the
|
||||
* scan keeps moving.
|
||||
*/
|
||||
class BoundedCallTest {
|
||||
|
||||
@Before
|
||||
fun resetStallState() {
|
||||
// The singleton is shared across tests in this JVM; a stall triggered by one test must
|
||||
// not leak into the next.
|
||||
BoundedCall.resetForTest()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `returns the result of a call that finishes in time`() {
|
||||
assertEquals("42", BoundedCall.orNull(5_000) { "42" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `returns null when the call throws`() {
|
||||
val result: String? = BoundedCall.orNull(5_000) { throw IllegalStateException("boom") }
|
||||
assertNull(result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `abandons a call stuck for ever instead of waiting for it`() {
|
||||
// Stands in for a provider call parked in a binder transaction: it would never finish.
|
||||
val parkedForever = CountDownLatch(1)
|
||||
var result: String? = "sentinel"
|
||||
val elapsed = measureTimeMillis {
|
||||
result = BoundedCall.orNull(200) {
|
||||
parkedForever.await()
|
||||
"too late"
|
||||
}
|
||||
}
|
||||
assertNull("a call that overran must count as no result", result)
|
||||
assertTrue("gave up only after ${elapsed}ms", elapsed < 5_000)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `never waits longer than the deadline plus a small margin`() {
|
||||
val parkedForever = CountDownLatch(1)
|
||||
val elapsed = measureTimeMillis { BoundedCall.orNull(200) { parkedForever.await(); null } }
|
||||
assertTrue("returned after ${elapsed}ms", elapsed in 150..3_000)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `propagates cancellation so cancelling a scan still works`() {
|
||||
assertThrows(CancellationException::class.java) {
|
||||
BoundedCall.orNull(5_000) { throw CancellationException("cancelled") }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `caps the threads parked in a stalled provider instead of one per file`() {
|
||||
val parkedForever = CountDownLatch(1)
|
||||
// 50 photos that would each park a thread for the full deadline: 50 x 50 ms = 2.5 s.
|
||||
val elapsed = measureTimeMillis {
|
||||
repeat(50) {
|
||||
assertNull(BoundedCall.orNull(50) { parkedForever.await(); null })
|
||||
}
|
||||
}
|
||||
assertTrue("50 blocking calls took ${elapsed}ms", elapsed < 1_500)
|
||||
assertTrue("parked ${BoundedCall.parkedCount()} threads", BoundedCall.parkedCount() <= 6)
|
||||
assertTrue("the breaker should be open", BoundedCall.isStalled())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `recovers once the provider answers again`() {
|
||||
val parkedForever = CountDownLatch(1)
|
||||
repeat(3) { assertNull(BoundedCall.orNull(100) { parkedForever.await(); null }) }
|
||||
assertTrue("the breaker should have tripped", BoundedCall.isStalled())
|
||||
|
||||
val refused = measureTimeMillis {
|
||||
assertNull(BoundedCall.orNull(100) { parkedForever.await(); null })
|
||||
}
|
||||
assertTrue("a stalled provider must be refused immediately, took ${refused}ms", refused < 50)
|
||||
|
||||
// The provider comes back; the cooldown must elapse before a probe is admitted.
|
||||
parkedForever.countDown()
|
||||
var recovered: String? = null
|
||||
val deadline = System.currentTimeMillis() + 8_000
|
||||
while (recovered == null && System.currentTimeMillis() < deadline) {
|
||||
Thread.sleep(100)
|
||||
recovered = BoundedCall.orNull(2_000) { "ok" }
|
||||
}
|
||||
assertEquals("the call must succeed once the provider answers again", "ok", recovered)
|
||||
assertEquals("no thread should be counted as parked", 0, BoundedCall.parkedCount())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package de.softwareapp_hb.fotodup.finder.domain
|
||||
|
||||
import android.app.Application
|
||||
import de.softwareapp_hb.fotodup.finder.core.DuplicatePolicy
|
||||
import de.softwareapp_hb.fotodup.finder.core.GroupKind
|
||||
import de.softwareapp_hb.fotodup.finder.data.BoundedCall
|
||||
import de.softwareapp_hb.fotodup.finder.data.MediaStorePhotoSource
|
||||
import de.softwareapp_hb.fotodup.finder.data.PhotoHasher
|
||||
import de.softwareapp_hb.fotodup.finder.data.PhotoIndexStore
|
||||
import de.softwareapp_hb.fotodup.finder.testutil.FakeMediaStoreProvider
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.awt.image.BufferedImage
|
||||
import java.io.File
|
||||
import javax.imageio.IIOImage
|
||||
import javax.imageio.ImageIO
|
||||
import javax.imageio.ImageWriteParam
|
||||
|
||||
/**
|
||||
* Runs the **real** scan pipeline on the JVM: the MediaStore query, head/tail signatures, SHA-256,
|
||||
* the decoded thumbnail, the SQLite index and the grouper — against [FakeMediaStoreProvider].
|
||||
*
|
||||
* What it can prove: the query and projection handling, the head/tail read, the exact-duplicate
|
||||
* path over genuine bytes, the index, the unreadable-file reporting, and that the pipeline runs
|
||||
* to completion instead of stalling (which is what froze on a device).
|
||||
*
|
||||
* What it cannot: perceptual hashing. Robolectric's `ShadowBitmapFactory` does not decode real
|
||||
* pixel data, so any assertion about near-duplicates has to come from the image-based harness in
|
||||
* `bench/` or from a device.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [36], application = Application::class)
|
||||
class ScanEngineEndToEndTest {
|
||||
|
||||
private lateinit var library: File
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
library = File(context.cacheDir, "library").apply {
|
||||
deleteRecursively()
|
||||
mkdirs()
|
||||
}
|
||||
context.getDatabasePath("photo_index.db").delete()
|
||||
// The provider-call breaker is a process-wide singleton; a stall from another test must
|
||||
// not decide whether this scan is allowed to talk to the (fake) provider.
|
||||
BoundedCall.resetForTest()
|
||||
FakeMediaStoreProvider.install()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `finds exact and near duplicates and survives unreadable files`() {
|
||||
val scene = saveJpeg("scene.jpg", quality = 0.90f, tint = 0)
|
||||
// A byte-identical copy: only the exact-duplicate path can catch this.
|
||||
val copy = File(library, "scene-copy.jpg").apply { writeBytes(scene.readBytes()) }
|
||||
// The same scene re-encoded twice: different bytes, so only the perceptual path can match.
|
||||
val low = saveJpeg("scene-low.jpg", quality = 0.55f, tint = 0)
|
||||
val low2 = saveJpeg("scene-low2.jpg", quality = 0.50f, tint = 0)
|
||||
// An unrelated photo.
|
||||
val other = saveJpeg("other.jpg", quality = 0.90f, tint = 96)
|
||||
// Non-empty but undecodable, so MediaStore reports it and the hasher must give up.
|
||||
val garbage = File(library, "garbage.jpg").apply {
|
||||
writeBytes(ByteArray(4_096) { (it % 251).toByte() })
|
||||
}
|
||||
|
||||
addPhoto(1, scene)
|
||||
addPhoto(2, copy)
|
||||
addPhoto(3, low)
|
||||
addPhoto(4, low2)
|
||||
addPhoto(5, other)
|
||||
addPhoto(6, garbage)
|
||||
|
||||
val result = runScan()
|
||||
|
||||
assertEquals("every library entry should be seen", 6, result.photoCount)
|
||||
|
||||
// The exact-duplicate path is fully exercised here: real bytes off disk, read through
|
||||
// ContentResolver, head/tail signature, then a full SHA-256.
|
||||
val exact = result.groups.filter { it.kind == GroupKind.EXACT }
|
||||
assertEquals("the byte-identical copy is one exact group", 1, exact.size)
|
||||
assertEquals(setOf(1L, 2L), exact.single().members.map { it.id }.toSet())
|
||||
|
||||
// Robolectric's ShadowBitmapFactory does not decode real pixel data, so every perceptual
|
||||
// fingerprint comes back null and all six files are reported as unreadable. That is a
|
||||
// limitation of the shadow, not of the app. What this test proves is the I/O half of the
|
||||
// scan — the MediaStore query, the head/tail read, the exact path, the index and the
|
||||
// reporting of unreadable files — and above all that it runs to completion rather than
|
||||
// stalling, which is what froze on a device.
|
||||
assertEquals("undecodable files must be reported, not dropped", 6, result.unreadableCount)
|
||||
|
||||
// A second run must agree; it takes the cached path through the SQLite index.
|
||||
val again = runScan()
|
||||
assertEquals(result.groups.size, again.groups.size)
|
||||
assertEquals(result.reclaimableBytes, again.reclaimableBytes)
|
||||
assertEquals(result.unreadableCount, again.unreadableCount)
|
||||
}
|
||||
|
||||
/**
|
||||
* The release blocker: on a real device the scan appeared frozen with the phase label still
|
||||
* showing, while every worker was parked in a provider read (MediaProvider restarting, FUSE
|
||||
* blocked). A provider call that never returns must be *abandoned*, never waited on.
|
||||
*/
|
||||
@Test
|
||||
fun `a provider read that blocks for ever cannot freeze the scan`() {
|
||||
val scene = saveJpeg("scene.jpg", quality = 0.90f, tint = 0)
|
||||
// Byte-identical copies, so every one of them is read for the signature phase.
|
||||
val copy = File(library, "scene-copy.jpg").apply { writeBytes(scene.readBytes()) }
|
||||
val stuck = File(library, "stuck.jpg").apply { writeBytes(scene.readBytes()) }
|
||||
|
||||
addPhoto(1, scene)
|
||||
addPhoto(2, copy)
|
||||
addPhoto(3, stuck)
|
||||
|
||||
// Media id 3 never answers; the scan must still run to completion.
|
||||
FakeMediaStoreProvider.blockReads(3)
|
||||
val result = try {
|
||||
runScan(providerTimeoutMs = 250L)
|
||||
} finally {
|
||||
FakeMediaStoreProvider.releaseBlockedReads()
|
||||
}
|
||||
|
||||
assertEquals("every library entry should be seen", 3, result.photoCount)
|
||||
val exact = result.groups.filter { it.kind == GroupKind.EXACT }
|
||||
assertEquals("the readable identical copies still group", 1, exact.size)
|
||||
assertEquals(
|
||||
"the blocked copy is reported as unreadable, not silently dropped",
|
||||
3,
|
||||
result.unreadableCount,
|
||||
)
|
||||
}
|
||||
|
||||
private fun runScan(providerTimeoutMs: Long = 10_000L): ScanResult = runBlocking {
|
||||
val context = RuntimeEnvironment.getApplication()
|
||||
val engine = ScanEngine(
|
||||
source = MediaStorePhotoSource(context),
|
||||
hasher = PhotoHasher(context, providerTimeoutMs),
|
||||
index = PhotoIndexStore(context),
|
||||
)
|
||||
var finished: ScanResult? = null
|
||||
engine.scan(DuplicatePolicy.BALANCED).collect { progress ->
|
||||
when (progress) {
|
||||
is ScanProgress.Finished -> finished = progress.result
|
||||
is ScanProgress.Failed -> throw AssertionError("scan failed: ${progress.message}")
|
||||
is ScanProgress.Working -> Unit
|
||||
}
|
||||
}
|
||||
requireNotNull(finished) { "the scan produced no result" }
|
||||
}
|
||||
|
||||
private fun addPhoto(id: Long, file: File, width: Int = 160, height: Int = 120) {
|
||||
FakeMediaStoreProvider.addFile(
|
||||
id = id,
|
||||
file = file,
|
||||
width = width,
|
||||
height = height,
|
||||
modifiedSeconds = 1_700_000_000L + id,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A deterministic textured JPEG: solid colour blocks with hard edges.
|
||||
*
|
||||
* Deliberately not a smooth gradient — on a smooth ramp the per-channel difference hash is
|
||||
* decided by compression noise rather than by structure, so two qualities can diverge. Real
|
||||
* photographs have edges, which is what the descriptor is meant to key on.
|
||||
*/
|
||||
private fun saveJpeg(name: String, quality: Float, tint: Int): File {
|
||||
val width = 160
|
||||
val height = 120
|
||||
val image = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
|
||||
val random = kotlin.random.Random(42 + tint)
|
||||
for (blockY in 0 until 6) {
|
||||
for (blockX in 0 until 8) {
|
||||
val colour = java.awt.Color(
|
||||
random.nextInt(60, 250),
|
||||
random.nextInt(60, 250),
|
||||
random.nextInt(60, 250),
|
||||
).rgb
|
||||
for (y in blockY * height / 6 until (blockY + 1) * height / 6) {
|
||||
for (x in blockX * width / 8 until (blockX + 1) * width / 8) {
|
||||
image.setRGB(x, y, colour)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val file = File(library, name)
|
||||
val writer = ImageIO.getImageWritersByFormatName("jpeg").next()
|
||||
val param = writer.defaultWriteParam.apply {
|
||||
compressionMode = ImageWriteParam.MODE_EXPLICIT
|
||||
compressionQuality = quality
|
||||
}
|
||||
ImageIO.createImageOutputStream(file).use { output ->
|
||||
writer.output = output
|
||||
writer.write(null, IIOImage(image, null, null), param)
|
||||
}
|
||||
writer.dispose()
|
||||
return file
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package de.softwareapp_hb.fotodup.finder.testutil
|
||||
|
||||
import android.content.ContentProvider
|
||||
import android.content.ContentValues
|
||||
import android.database.Cursor
|
||||
import android.database.MatrixCursor
|
||||
import android.net.Uri
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.provider.MediaStore
|
||||
import org.robolectric.Robolectric
|
||||
import java.io.File
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.CountDownLatch
|
||||
|
||||
/**
|
||||
* A stand-in for the system media provider, so the *real* scan pipeline can run on the JVM.
|
||||
*
|
||||
* Registering this under the MediaStore authority means `MediaStorePhotoSource` queries it, and
|
||||
* `ContentResolver.openFileDescriptor` reaches [openFile] — so `PhotoHasher` reads genuine files
|
||||
* through the same code path a phone would exercise.
|
||||
*
|
||||
* The query answers with exactly the columns the caller asked for, so the source under test can
|
||||
* request whatever projection it likes without this fake having to be kept in step.
|
||||
*/
|
||||
class FakeMediaStoreProvider : ContentProvider() {
|
||||
|
||||
class Entry(
|
||||
val id: Long,
|
||||
val file: File,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val modifiedSeconds: Long,
|
||||
val relativePath: String = "DCIM/",
|
||||
)
|
||||
|
||||
override fun onCreate(): Boolean = true
|
||||
|
||||
override fun query(
|
||||
uri: Uri,
|
||||
projection: Array<out String>?,
|
||||
selection: String?,
|
||||
selectionArgs: Array<out String>?,
|
||||
sortOrder: String?,
|
||||
): Cursor {
|
||||
val columns = projection?.toList()
|
||||
?: listOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.SIZE)
|
||||
val cursor = MatrixCursor(columns.toTypedArray())
|
||||
media.forEach { entry -> cursor.addRow(columns.map { valueFor(it, entry) }) }
|
||||
return cursor
|
||||
}
|
||||
|
||||
override fun getType(uri: Uri): String = "image/jpeg"
|
||||
|
||||
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor {
|
||||
val id = uri.lastPathSegment?.toLongOrNull() ?: error("no media id in $uri")
|
||||
// Stands in for a wedged provider/FUSE daemon: the call never returns until the test
|
||||
// releases it. Used to prove the scan survives a provider call that blocks for ever.
|
||||
blockedReads[id]?.await()
|
||||
val entry = media.firstOrNull { it.id == id } ?: error("unknown media id $id")
|
||||
return ParcelFileDescriptor.open(entry.file, ParcelFileDescriptor.MODE_READ_ONLY)
|
||||
}
|
||||
|
||||
override fun insert(uri: Uri, values: ContentValues?): Uri? =
|
||||
throw UnsupportedOperationException("the fake library is read-only")
|
||||
|
||||
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int =
|
||||
throw UnsupportedOperationException("the fake library is read-only")
|
||||
|
||||
override fun update(
|
||||
uri: Uri,
|
||||
values: ContentValues?,
|
||||
selection: String?,
|
||||
selectionArgs: Array<out String>?,
|
||||
): Int = throw UnsupportedOperationException("the fake library is read-only")
|
||||
|
||||
private fun valueFor(column: String, entry: Entry): Any? = when (column) {
|
||||
MediaStore.Images.Media._ID -> entry.id
|
||||
MediaStore.Images.Media.DISPLAY_NAME -> entry.file.name
|
||||
MediaStore.Images.Media.SIZE -> entry.file.length()
|
||||
MediaStore.Images.Media.DATE_MODIFIED -> entry.modifiedSeconds
|
||||
MediaStore.Images.Media.WIDTH -> entry.width
|
||||
MediaStore.Images.Media.HEIGHT -> entry.height
|
||||
MediaStore.Images.Media.MIME_TYPE -> "image/jpeg"
|
||||
MediaStore.Images.Media.RELATIVE_PATH -> entry.relativePath
|
||||
else -> null
|
||||
}
|
||||
|
||||
companion object {
|
||||
val media: MutableList<Entry> = mutableListOf()
|
||||
|
||||
/** Media ids whose [openFile] blocks until [releaseBlockedReads] is called. */
|
||||
private val blockedReads: MutableMap<Long, CountDownLatch> = ConcurrentHashMap()
|
||||
|
||||
/** Registers the provider under the MediaStore authority and clears the library. */
|
||||
fun install(): FakeMediaStoreProvider {
|
||||
media.clear()
|
||||
blockedReads.clear()
|
||||
return Robolectric.buildContentProvider(FakeMediaStoreProvider::class.java)
|
||||
.create(MediaStore.AUTHORITY)
|
||||
.get()
|
||||
}
|
||||
|
||||
/** Makes every read of media [id] block, simulating a provider that never answers. */
|
||||
fun blockReads(id: Long) {
|
||||
blockedReads[id] = CountDownLatch(1)
|
||||
}
|
||||
|
||||
/** Lets every blocked read finish, so a test can tear down cleanly. */
|
||||
fun releaseBlockedReads() {
|
||||
blockedReads.values.forEach(CountDownLatch::countDown)
|
||||
blockedReads.clear()
|
||||
}
|
||||
|
||||
/** Adds [file] to the fake library, deriving the reported size from the file itself. */
|
||||
fun addFile(id: Long, file: File, width: Int, height: Int, modifiedSeconds: Long = 0L) {
|
||||
media += Entry(id, file, width, height, modifiedSeconds)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user