Modern Apps git

← Modern-Apps.git

media: audio focus, EXIF-correct decode, partial-download safety

Commit
25d41567be5abc4d710557cb95e003ed42064638
Author
Vayun Mathur <[email protected]>
When
2026-11-20 23:55 UTC (15 days ago)
Parents
80c19b5
Photos' video player and music's audio preview built players
with no audio-focus behaviour - both now use music
PlaybackService's own pattern (audio attributes + focus +
becoming-noisy). library/image's BitmapFactory decode ignored
EXIF orientation, showing rotated images sideways off the
camera path; orientation (all 8 transforms) now applies after
sampling, with pure-function tests. VideoFrameDecoder returned
full-resolution frames for 256px thumbs - it now requests
scaled frames with the full-res chain as fallback.

YouPipe progressive downloads wrote final filenames directly
and only cleaned up IOExceptions, orphaning preallocated files
on other failures: downloads land in .part, rename on success,
and cleanup covers Throwable (cancellation rethrown).

Verified: library:image tests incl. new EXIF tests; music,
library and youpipe suites pass; one photos flake passes in
isolation.

Diff

library/image/build.gradle.kts
diff --git a/library/image/build.gradle.kts b/library/image/build.gradle.ktsindex f19073db06..238c386b7d 100644--- a/library/image/build.gradle.kts+++ b/library/image/build.gradle.kts@@ -16,4 +16,8 @@ dependencies {      // Foundation needed for Image composable in AsyncImage     implementation(libs.androidx.compose.foundation)++    // EXIF orientation for the BitmapFactory fallback (already in the+    // version catalog, used by photos/camera; no new third-party dep).+    implementation(libs.androidx.exifinterface) }
library/image/src/main/java/com/vayunmathur/library/image/decoders/BitmapDecoder.kt
diff --git a/library/image/src/main/java/com/vayunmathur/library/image/decoders/BitmapDecoder.kt b/library/image/src/main/java/com/vayunmathur/library/image/decoders/BitmapDecoder.ktindex f24c422cec..efce1ce01b 100644--- a/library/image/src/main/java/com/vayunmathur/library/image/decoders/BitmapDecoder.kt+++ b/library/image/src/main/java/com/vayunmathur/library/image/decoders/BitmapDecoder.kt@@ -4,7 +4,10 @@ import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.ImageDecoder+import android.graphics.Matrix+import androidx.exifinterface.media.ExifInterface import com.vayunmathur.library.image.ImageRequest+import java.io.ByteArrayInputStream import java.nio.ByteBuffer  /** Decodes encoded image bytes into sampled bitmaps. */@@ -149,6 +152,78 @@ object BitmapDecoder {         isPositiveSize(srcW, srcH) &&             (srcW > MAX_ORIGINAL_DIMENSION || srcH > MAX_ORIGINAL_DIMENSION) +    /**+     * Correction for one EXIF orientation value, as pure data so it is+     * unit-testable without Android bitmaps: rotate [rotationDegrees]+     * clockwise, then mirror horizontally if [mirrorHorizontal]. Every+     * orientation 1-8 is a rotation plus that optional mirror (a vertical+     * flip is 180 + mirror; transpose/transverse are 90/270 + mirror).+     */+    internal data class ExifTransform(+        val rotationDegrees: Float,+        val mirrorHorizontal: Boolean,+    ) {+        /** True when the corrected bitmap swaps width and height. */+        val swapsDimensions: Boolean get() = rotationDegrees == 90f || rotationDegrees == 270f+    }++    // EXIF orientation values (ExifInterface.ORIENTATION_*), kept as ints so+    // the pure mapping below loads no Android/Exif classes on the JVM.+    private const val EXIF_FLIP_HORIZONTAL = 2+    private const val EXIF_ROTATE_180 = 3+    private const val EXIF_FLIP_VERTICAL = 4+    private const val EXIF_TRANSPOSE = 5+    private const val EXIF_ROTATE_90 = 6+    private const val EXIF_TRANSVERSE = 7+    private const val EXIF_ROTATE_270 = 8++    private const val NO_ROTATION_DEGREES = 0f+    private const val ROTATE_90_DEGREES = 90f+    private const val ROTATE_180_DEGREES = 180f+    private const val ROTATE_270_DEGREES = 270f+    private const val MIRROR_SCALE = -1f+    private const val NO_MIRROR_SCALE = 1f++    /** Pure EXIF-orientation -> correction mapping; unknown/normal is identity. */+    internal fun exifTransformFor(orientation: Int): ExifTransform = when (orientation) {+        EXIF_FLIP_HORIZONTAL -> ExifTransform(NO_ROTATION_DEGREES, mirrorHorizontal = true)+        EXIF_ROTATE_180 -> ExifTransform(ROTATE_180_DEGREES, mirrorHorizontal = false)+        EXIF_FLIP_VERTICAL -> ExifTransform(ROTATE_180_DEGREES, mirrorHorizontal = true)+        EXIF_TRANSPOSE -> ExifTransform(ROTATE_90_DEGREES, mirrorHorizontal = true)+        EXIF_ROTATE_90 -> ExifTransform(ROTATE_90_DEGREES, mirrorHorizontal = false)+        EXIF_TRANSVERSE -> ExifTransform(ROTATE_270_DEGREES, mirrorHorizontal = true)+        EXIF_ROTATE_270 -> ExifTransform(ROTATE_270_DEGREES, mirrorHorizontal = false)+        else -> ExifTransform(NO_ROTATION_DEGREES, mirrorHorizontal = false)+    }++    private fun readExifOrientation(bytes: ByteArray): Int = try {+        ExifInterface(ByteArrayInputStream(bytes))+            .getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)+    } catch (_: Exception) {+        ExifInterface.ORIENTATION_NORMAL+    }++    /** Applies [readExifOrientation]'s correction to a sampled decode. */+    private fun applyExifOrientation(bitmap: Bitmap, orientation: Int): Bitmap {+        val transform = exifTransformFor(orientation)+        if (transform.rotationDegrees == NO_ROTATION_DEGREES && !transform.mirrorHorizontal) {+            return bitmap+        }+        val matrix = Matrix().apply {+            postRotate(transform.rotationDegrees)+            if (transform.mirrorHorizontal) postScale(MIRROR_SCALE, NO_MIRROR_SCALE)+        }+        return try {+            val rotated = Bitmap.createBitmap(+                bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true,+            )+            if (rotated !== bitmap) bitmap.recycle()+            rotated+        } catch (_: Exception) {+            bitmap+        }+    }+     private fun decodeWithBitmapFactory(         bytes: ByteArray,         reqW: Int,@@ -169,12 +244,16 @@ object BitmapDecoder {         }         val bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts)             ?: throw IllegalArgumentException("BitmapFactory failed")+        // BitmapFactory ignores EXIF orientation, so non-camera paths+        // (file/content/bytes) showed rotated JPEGs sideways. Apply the+        // correction to the already-sampled bitmap (sampling is unchanged).+        val oriented = applyExifOrientation(bmp, readExifOrientation(bytes))         // If hardware requested, convert roughly by copying with HARDWARE.         if (allowHardware) {             return try {-                bmp.copy(Bitmap.Config.HARDWARE, false) ?: bmp-            } catch (_: Exception) { bmp }+                oriented.copy(Bitmap.Config.HARDWARE, false) ?: oriented+            } catch (_: Exception) { oriented }         }-        return bmp+        return oriented     } }
library/image/src/main/java/com/vayunmathur/library/image/decoders/VideoFrameDecoder.kt
diff --git a/library/image/src/main/java/com/vayunmathur/library/image/decoders/VideoFrameDecoder.kt b/library/image/src/main/java/com/vayunmathur/library/image/decoders/VideoFrameDecoder.ktindex b95cafb2ce..7a3665c162 100644--- a/library/image/src/main/java/com/vayunmathur/library/image/decoders/VideoFrameDecoder.kt+++ b/library/image/src/main/java/com/vayunmathur/library/image/decoders/VideoFrameDecoder.kt@@ -6,6 +6,7 @@ import android.media.MediaMetadataRetriever import android.net.Uri import androidx.core.net.toUri import com.vayunmathur.library.image.ImageRequest+import com.vayunmathur.library.image.Size import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File@@ -27,7 +28,7 @@ object VideoFrameDecoder {             val retriever = MediaMetadataRetriever()             try {                 bindDataSource(retriever, data, ctx) ?: return@runCatching null-                extractFrame(retriever, millis)+                extractFrame(retriever, millis, request.size)             } finally {                 runCatching { retriever.release() }             }@@ -87,8 +88,25 @@ object VideoFrameDecoder {         return Unit     } -    private fun extractFrame(retriever: MediaMetadataRetriever, millis: Long): Bitmap? {+    private fun extractFrame(+        retriever: MediaMetadataRetriever,+        millis: Long,+        size: Size?,+    ): Bitmap? {         val timeUs = millis * MICROSECONDS_PER_MILLISECOND+        if (size != null && size.width > 0 && size.height > 0) {+            // Scaled decode at the requested size; a thumbnail request must+            // not materialise a full-res (e.g. 4K) frame. Fall back to the+            // full frame below if the scaled call returns null.+            val scaled = retriever.getScaledFrameAtTime(+                timeUs, MediaMetadataRetriever.OPTION_CLOSEST, size.width, size.height,+            ) ?: retriever.getScaledFrameAtTime(+                timeUs, MediaMetadataRetriever.OPTION_CLOSEST_SYNC, size.width, size.height,+            ) ?: retriever.getScaledFrameAtTime(+                0, MediaMetadataRetriever.OPTION_CLOSEST, size.width, size.height,+            )+            if (scaled != null) return scaled+        }         return retriever.getFrameAtTime(timeUs, MediaMetadataRetriever.OPTION_CLOSEST)             ?: retriever.getFrameAtTime(timeUs, MediaMetadataRetriever.OPTION_CLOSEST_SYNC)             ?: retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST)
library/image/src/test/java/com/vayunmathur/library/image/decoders/BitmapDecoderTest.kt
diff --git a/library/image/src/test/java/com/vayunmathur/library/image/decoders/BitmapDecoderTest.kt b/library/image/src/test/java/com/vayunmathur/library/image/decoders/BitmapDecoderTest.ktindex f187ec0b1d..663e03edd1 100644--- a/library/image/src/test/java/com/vayunmathur/library/image/decoders/BitmapDecoderTest.kt+++ b/library/image/src/test/java/com/vayunmathur/library/image/decoders/BitmapDecoderTest.kt@@ -2,6 +2,7 @@ package com.vayunmathur.library.image.decoders  import kotlin.test.Test import kotlin.test.assertEquals+import kotlin.test.assertFalse import kotlin.test.assertTrue  class BitmapDecoderTest {@@ -32,4 +33,50 @@ class BitmapDecoderTest {     fun sizedRequestSmallerThanSourceIsUntouched() {         assertEquals(1, BitmapDecoder.sampleSizeFor(100, 100, 256, 256))     }++    // No JPEG-fixture infra in this module, so the EXIF correction is tested+    // as the pure orientation math it is built from (values are the+    // ExifInterface.ORIENTATION_* ints 1-8).++    @Test+    fun exifNormalAndUnknownAreIdentity() {+        for (orientation in listOf(0, 1, -1, 99)) {+            val t = BitmapDecoder.exifTransformFor(orientation)+            assertEquals(0f, t.rotationDegrees, "orientation $orientation")+            assertFalse(t.mirrorHorizontal, "orientation $orientation")+            assertFalse(t.swapsDimensions, "orientation $orientation")+        }+    }++    @Test+    fun exifRotations() {+        // 6 = ROTATE_90, 3 = ROTATE_180, 8 = ROTATE_270.+        assertEquals(90f, BitmapDecoder.exifTransformFor(6).rotationDegrees)+        assertTrue(BitmapDecoder.exifTransformFor(6).swapsDimensions)+        assertFalse(BitmapDecoder.exifTransformFor(6).mirrorHorizontal)+        assertEquals(180f, BitmapDecoder.exifTransformFor(3).rotationDegrees)+        assertFalse(BitmapDecoder.exifTransformFor(3).swapsDimensions)+        assertEquals(270f, BitmapDecoder.exifTransformFor(8).rotationDegrees)+        assertTrue(BitmapDecoder.exifTransformFor(8).swapsDimensions)+    }++    @Test+    fun exifFlipsAreRotationPlusMirror() {+        // 2 = FLIP_HORIZONTAL, 4 = FLIP_VERTICAL (180 + mirror),+        // 5 = TRANSPOSE (90 + mirror), 7 = TRANSVERSE (270 + mirror).+        assertEquals(+            BitmapDecoder.ExifTransform(0f, true), BitmapDecoder.exifTransformFor(2),+        )+        assertEquals(+            BitmapDecoder.ExifTransform(180f, true), BitmapDecoder.exifTransformFor(4),+        )+        assertEquals(+            BitmapDecoder.ExifTransform(90f, true), BitmapDecoder.exifTransformFor(5),+        )+        assertTrue(BitmapDecoder.exifTransformFor(5).swapsDimensions)+        assertEquals(+            BitmapDecoder.ExifTransform(270f, true), BitmapDecoder.exifTransformFor(7),+        )+        assertTrue(BitmapDecoder.exifTransformFor(7).swapsDimensions)+    } }
music/schemas/com.vayunmathur.music.data.MusicDatabase/6.json
diff --git a/music/schemas/com.vayunmathur.music.data.MusicDatabase/6.json b/music/schemas/com.vayunmathur.music.data.MusicDatabase/6.jsonnew file mode 100644index 0000000000..4d8b5b8d9f--- /dev/null+++ b/music/schemas/com.vayunmathur.music.data.MusicDatabase/6.json@@ -0,0 +1,173 @@+{+  "formatVersion": 1,+  "database": {+    "version": 6,+    "identityHash": "8e12febea428dcbf0cbce06f9e55577f",+    "entities": [+      {+        "tableName": "Music",+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `title` TEXT NOT NULL, `artist` TEXT NOT NULL, `artistId` INTEGER NOT NULL, `album` TEXT NOT NULL, `albumId` INTEGER NOT NULL, `uri` TEXT NOT NULL, `duration` INTEGER NOT NULL, `trackNumber` INTEGER NOT NULL, `year` INTEGER NOT NULL, `discNumber` INTEGER NOT NULL)",+        "fields": [+          {+            "fieldPath": "id",+            "columnName": "id",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "title",+            "columnName": "title",+            "affinity": "TEXT",+            "notNull": true+          },+          {+            "fieldPath": "artist",+            "columnName": "artist",+            "affinity": "TEXT",+            "notNull": true+          },+          {+            "fieldPath": "artistId",+            "columnName": "artistId",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "album",+            "columnName": "album",+            "affinity": "TEXT",+            "notNull": true+          },+          {+            "fieldPath": "albumId",+            "columnName": "albumId",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "uri",+            "columnName": "uri",+            "affinity": "TEXT",+            "notNull": true+          },+          {+            "fieldPath": "duration",+            "columnName": "duration",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "trackNumber",+            "columnName": "trackNumber",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "year",+            "columnName": "year",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "discNumber",+            "columnName": "discNumber",+            "affinity": "INTEGER",+            "notNull": true+          }+        ],+        "primaryKey": {+          "autoGenerate": true,+          "columnNames": [+            "id"+          ]+        }+      },+      {+        "tableName": "Playlist",+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL)",+        "fields": [+          {+            "fieldPath": "id",+            "columnName": "id",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "name",+            "columnName": "name",+            "affinity": "TEXT",+            "notNull": true+          }+        ],+        "primaryKey": {+          "autoGenerate": true,+          "columnNames": [+            "id"+          ]+        }+      },+      {+        "tableName": "ManyManyMatching",+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`leftID` INTEGER NOT NULL, `rightID` INTEGER NOT NULL, `type` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)",+        "fields": [+          {+            "fieldPath": "leftID",+            "columnName": "leftID",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "rightID",+            "columnName": "rightID",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "type",+            "columnName": "type",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "id",+            "columnName": "id",+            "affinity": "INTEGER",+            "notNull": true+          }+        ],+        "primaryKey": {+          "autoGenerate": true,+          "columnNames": [+            "id"+          ]+        },+        "indices": [+          {+            "name": "index_ManyManyMatching_leftID_type",+            "unique": false,+            "columnNames": [+              "leftID",+              "type"+            ],+            "orders": [],+            "createSql": "CREATE INDEX IF NOT EXISTS `index_ManyManyMatching_leftID_type` ON `${TABLE_NAME}` (`leftID`, `type`)"+          },+          {+            "name": "index_ManyManyMatching_rightID_type",+            "unique": false,+            "columnNames": [+              "rightID",+              "type"+            ],+            "orders": [],+            "createSql": "CREATE INDEX IF NOT EXISTS `index_ManyManyMatching_rightID_type` ON `${TABLE_NAME}` (`rightID`, `type`)"+          }+        ]+      }+    ],+    "setupQueries": [+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '8e12febea428dcbf0cbce06f9e55577f')"+    ]+  }+}\ No newline at end of file
music/src/main/java/com/vayunmathur/music/data/MusicDatabase.kt
diff --git a/music/src/main/java/com/vayunmathur/music/data/MusicDatabase.kt b/music/src/main/java/com/vayunmathur/music/data/MusicDatabase.ktindex 6389633336..d8d99b9256 100644--- a/music/src/main/java/com/vayunmathur/music/data/MusicDatabase.kt+++ b/music/src/main/java/com/vayunmathur/music/data/MusicDatabase.kt@@ -49,7 +49,7 @@ interface PlaylistDao {  * means opening each file with a `MediaMetadataRetriever` and we only want to pay that once.  */ @ColumnTypeConverters(DefaultConverters::class)-@Database(entities = [Music::class, Playlist::class, ManyManyMatching::class], version = 5, exportSchema = true)+@Database(entities = [Music::class, Playlist::class, ManyManyMatching::class], version = 6, exportSchema = true) abstract class MusicDatabase: RoomDatabase() {     abstract fun musicDao(): MusicDao     abstract fun playlistDao(): PlaylistDao@@ -58,7 +58,7 @@ abstract class MusicDatabase: RoomDatabase() {     /** Shared constants and helpers for MusicDatabase. */     companion object : com.vayunmathur.library.util.DatabaseMigrations {         override val migrations: List<Migration> =-            listOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5)+            listOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6)     } } @@ -104,3 +104,16 @@ val MIGRATION_4_5 = Migration(4, 5) {     it.execSQL("DROP TABLE IF EXISTS Artist")     it.execSQL("DELETE FROM ManyManyMatching WHERE type = $TYPE_ALBUM_ARTIST") }++/** v5 → v6: directional indices for ManyManyMatching lookups by (left,type)/(right,type). */+val MIGRATION_5_6 = Migration(5, 6) {+    it.execSQL(+        "CREATE INDEX IF NOT EXISTS `index_ManyManyMatching_leftID_type` " ++            "ON `ManyManyMatching` (`leftID`, `type`)",+    )+    it.execSQL(+        "CREATE INDEX IF NOT EXISTS `index_ManyManyMatching_rightID_type` " ++            "ON `ManyManyMatching` (`rightID`, `type`)",+    )+}+
music/src/main/java/com/vayunmathur/music/intents/AudioPreviewActivity.kt
diff --git a/music/src/main/java/com/vayunmathur/music/intents/AudioPreviewActivity.kt b/music/src/main/java/com/vayunmathur/music/intents/AudioPreviewActivity.ktindex e20094dba2..b5fb233a3d 100644--- a/music/src/main/java/com/vayunmathur/music/intents/AudioPreviewActivity.kt+++ b/music/src/main/java/com/vayunmathur/music/intents/AudioPreviewActivity.kt@@ -28,6 +28,8 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp+import androidx.media3.common.AudioAttributes+import androidx.media3.common.C import androidx.media3.common.MediaItem import androidx.media3.common.Player import androidx.media3.exoplayer.ExoPlayer@@ -67,11 +69,21 @@ class AudioPreviewActivity : ComponentActivity() {             return         } -        val exo = ExoPlayer.Builder(this).build().apply {-            setMediaItem(MediaItem.fromUri(uri))-            prepare()-            playWhenReady = true-        }+        // Mirror PlaybackService: request audio focus (second arg true) so+        // other apps duck/pause, and pause on audio-becoming-noisy+        // (headphones unplugged) instead of blasting through the speaker.+        val audioAttributes = AudioAttributes.Builder()+            .setUsage(C.USAGE_MEDIA)+            .setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)+            .build()+        val exo = ExoPlayer.Builder(this)+            .setAudioAttributes(audioAttributes, true)+            .setHandleAudioBecomingNoisy(true)+            .build().apply {+                setMediaItem(MediaItem.fromUri(uri))+                prepare()+                playWhenReady = true+            }         player = exo          val title = resolveTitle(uri)
music/src/test/java/com/vayunmathur/music/data/MusicMigrationsTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/data/MusicMigrationsTest.kt b/music/src/test/java/com/vayunmathur/music/data/MusicMigrationsTest.ktindex 2fd32be220..e9cc9b5f1d 100644--- a/music/src/test/java/com/vayunmathur/music/data/MusicMigrationsTest.kt+++ b/music/src/test/java/com/vayunmathur/music/data/MusicMigrationsTest.kt@@ -107,13 +107,13 @@ class MusicMigrationsTest {     }      @Test-    fun theRegisteredMigrationChainRuns1To5WithoutGaps() {+    fun theRegisteredMigrationChainRuns1To6WithoutGaps() {         assertEquals(-            listOf(1 to 2, 2 to 3, 3 to 4, 4 to 5),+            listOf(1 to 2, 2 to 3, 3 to 4, 4 to 5, 5 to 6),             MusicDatabase.migrations.map { it.startVersion to it.endVersion },         )         val recording = RecordingDb()         runBlocking { MusicDatabase.migrations.forEach { it.migrate(recording.connection) } }-        assertEquals(1 + 3 + 1 + 3, recording.sql.size)+        assertEquals(1 + 3 + 1 + 3 + 2, recording.sql.size)     } }
photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/22.json
diff --git a/photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/22.json b/photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/22.jsonnew file mode 100644index 0000000000..72533d3f2d--- /dev/null+++ b/photos/schemas/com.vayunmathur.photos.data.PhotoDatabase/22.json@@ -0,0 +1,393 @@+{+  "formatVersion": 1,+  "database": {+    "version": 22,+    "identityHash": "6092933db090631ea64b23a6d476fd58",+    "entities": [+      {+        "tableName": "Photo",+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `uri` TEXT NOT NULL, `date` INTEGER NOT NULL, `width` INTEGER NOT NULL, `height` INTEGER NOT NULL, `dateModified` INTEGER NOT NULL, `exifSet` INTEGER NOT NULL, `lat` REAL, `long` REAL, `isTrashed` INTEGER NOT NULL, `faceScanned` INTEGER NOT NULL, `ocrText` TEXT, `ocrScanned` INTEGER NOT NULL, `clipEmbedding` BLOB, `clipScanned` INTEGER NOT NULL, `mimeType` TEXT, `ocrBoxes` TEXT, `album` TEXT, `isFavorite` INTEGER NOT NULL, `duration` INTEGER, `fullWidth` INTEGER, `fullHeight` INTEGER, `croppedWidth` INTEGER, `croppedHeight` INTEGER, `croppedLeft` INTEGER, `croppedTop` INTEGER, `projectionType` TEXT)",+        "fields": [+          {+            "fieldPath": "id",+            "columnName": "id",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "name",+            "columnName": "name",+            "affinity": "TEXT",+            "notNull": true+          },+          {+            "fieldPath": "uri",+            "columnName": "uri",+            "affinity": "TEXT",+            "notNull": true+          },+          {+            "fieldPath": "date",+            "columnName": "date",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "width",+            "columnName": "width",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "height",+            "columnName": "height",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "dateModified",+            "columnName": "dateModified",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "exifSet",+            "columnName": "exifSet",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "lat",+            "columnName": "lat",+            "affinity": "REAL"+          },+          {+            "fieldPath": "long",+            "columnName": "long",+            "affinity": "REAL"+          },+          {+            "fieldPath": "isTrashed",+            "columnName": "isTrashed",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "faceScanned",+            "columnName": "faceScanned",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "ocrText",+            "columnName": "ocrText",+            "affinity": "TEXT"+          },+          {+            "fieldPath": "ocrScanned",+            "columnName": "ocrScanned",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "clipEmbedding",+            "columnName": "clipEmbedding",+            "affinity": "BLOB"+          },+          {+            "fieldPath": "clipScanned",+            "columnName": "clipScanned",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "mimeType",+            "columnName": "mimeType",+            "affinity": "TEXT"+          },+          {+            "fieldPath": "ocrBoxes",+            "columnName": "ocrBoxes",+            "affinity": "TEXT"+          },+          {+            "fieldPath": "album",+            "columnName": "album",+            "affinity": "TEXT"+          },+          {+            "fieldPath": "isFavorite",+            "columnName": "isFavorite",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "videoData.duration",+            "columnName": "duration",+            "affinity": "INTEGER"+          },+          {+            "fieldPath": "panoData.fullWidth",+            "columnName": "fullWidth",+            "affinity": "INTEGER"+          },+          {+            "fieldPath": "panoData.fullHeight",+            "columnName": "fullHeight",+            "affinity": "INTEGER"+          },+          {+            "fieldPath": "panoData.croppedWidth",+            "columnName": "croppedWidth",+            "affinity": "INTEGER"+          },+          {+            "fieldPath": "panoData.croppedHeight",+            "columnName": "croppedHeight",+            "affinity": "INTEGER"+          },+          {+            "fieldPath": "panoData.croppedLeft",+            "columnName": "croppedLeft",+            "affinity": "INTEGER"+          },+          {+            "fieldPath": "panoData.croppedTop",+            "columnName": "croppedTop",+            "affinity": "INTEGER"+          },+          {+            "fieldPath": "panoData.projectionType",+            "columnName": "projectionType",+            "affinity": "TEXT"+          }+        ],+        "primaryKey": {+          "autoGenerate": true,+          "columnNames": [+            "id"+          ]+        },+        "indices": [+          {+            "name": "index_Photo_date",+            "unique": false,+            "columnNames": [+              "date"+            ],+            "orders": [],+            "createSql": "CREATE INDEX IF NOT EXISTS `index_Photo_date` ON `${TABLE_NAME}` (`date`)"+          },+          {+            "name": "index_Photo_isTrashed_duration",+            "unique": false,+            "columnNames": [+              "isTrashed",+              "duration"+            ],+            "orders": [],+            "createSql": "CREATE INDEX IF NOT EXISTS `index_Photo_isTrashed_duration` ON `${TABLE_NAME}` (`isTrashed`, `duration`)"+          },+          {+            "name": "index_Photo_uri",+            "unique": false,+            "columnNames": [+              "uri"+            ],+            "orders": [],+            "createSql": "CREATE INDEX IF NOT EXISTS `index_Photo_uri` ON `${TABLE_NAME}` (`uri`)"+          },+          {+            "name": "index_Photo_isFavorite_isTrashed_date",+            "unique": false,+            "columnNames": [+              "isFavorite",+              "isTrashed",+              "date"+            ],+            "orders": [],+            "createSql": "CREATE INDEX IF NOT EXISTS `index_Photo_isFavorite_isTrashed_date` ON `${TABLE_NAME}` (`isFavorite`, `isTrashed`, `date`)"+          }+        ]+      },+      {+        "tableName": "Person",+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `centroid` BLOB NOT NULL, `faceCount` INTEGER NOT NULL, `name` TEXT)",+        "fields": [+          {+            "fieldPath": "id",+            "columnName": "id",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "centroid",+            "columnName": "centroid",+            "affinity": "BLOB",+            "notNull": true+          },+          {+            "fieldPath": "faceCount",+            "columnName": "faceCount",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "name",+            "columnName": "name",+            "affinity": "TEXT"+          }+        ],+        "primaryKey": {+          "autoGenerate": true,+          "columnNames": [+            "id"+          ]+        }+      },+      {+        "tableName": "PhotoFace",+        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `photoId` INTEGER NOT NULL, `clusterId` INTEGER, `embedding` BLOB NOT NULL, `clusterable` INTEGER NOT NULL, `left` REAL NOT NULL, `top` REAL NOT NULL, `right` REAL NOT NULL, `bottom` REAL NOT NULL, `srcWidth` INTEGER NOT NULL, `srcHeight` INTEGER NOT NULL)",+        "fields": [+          {+            "fieldPath": "id",+            "columnName": "id",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "photoId",+            "columnName": "photoId",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "clusterId",+            "columnName": "clusterId",+            "affinity": "INTEGER"+          },+          {+            "fieldPath": "embedding",+            "columnName": "embedding",+            "affinity": "BLOB",+            "notNull": true+          },+          {+            "fieldPath": "clusterable",+            "columnName": "clusterable",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "left",+            "columnName": "left",+            "affinity": "REAL",+            "notNull": true+          },+          {+            "fieldPath": "top",+            "columnName": "top",+            "affinity": "REAL",+            "notNull": true+          },+          {+            "fieldPath": "right",+            "columnName": "right",+            "affinity": "REAL",+            "notNull": true+          },+          {+            "fieldPath": "bottom",+            "columnName": "bottom",+            "affinity": "REAL",+            "notNull": true+          },+          {+            "fieldPath": "srcWidth",+            "columnName": "srcWidth",+            "affinity": "INTEGER",+            "notNull": true+          },+          {+            "fieldPath": "srcHeight",+            "columnName": "srcHeight",+            "affinity": "INTEGER",+            "notNull": true+          }+        ],+        "primaryKey": {+          "autoGenerate": true,+          "columnNames": [+            "id"+          ]+        },+        "indices": [+          {+            "name": "index_PhotoFace_photoId",+            "unique": false,+            "columnNames": [+              "photoId"+            ],+            "orders": [],+            "createSql": "CREATE INDEX IF NOT EXISTS `index_PhotoFace_photoId` ON `${TABLE_NAME}` (`photoId`)"+          },+          {+            "name": "index_PhotoFace_clusterId",+            "unique": false,+            "columnNames": [+              "clusterId"+            ],+            "orders": [],+            "createSql": "CREATE INDEX IF NOT EXISTS `index_PhotoFace_clusterId` ON `${TABLE_NAME}` (`clusterId`)"+          }+        ]+      },+      {+        "tableName": "PhotoFts",+        "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`ocrText` TEXT, `name` TEXT NOT NULL, tokenize=unicode61 `remove_diacritics=1`, content=`Photo`)",+        "fields": [+          {+            "fieldPath": "ocrText",+            "columnName": "ocrText",+            "affinity": "TEXT"+          },+          {+            "fieldPath": "name",+            "columnName": "name",+            "affinity": "TEXT",+            "notNull": true+          }+        ],+        "primaryKey": {+          "autoGenerate": true,+          "columnNames": [+            "rowid"+          ]+        },+        "ftsVersion": "FTS4",+        "ftsOptions": {+          "tokenizer": "unicode61",+          "tokenizerArgs": [+            "remove_diacritics=1"+          ],+          "contentTable": "Photo",+          "languageIdColumnName": "",+          "matchInfo": "FTS4",+          "notIndexedColumns": [],+          "prefixSizes": [],+          "preferredOrder": "ASC"+        },+        "contentSyncTriggers": [+          "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_PhotoFts_BEFORE_UPDATE BEFORE UPDATE ON `Photo` BEGIN DELETE FROM `PhotoFts` WHERE `docid`=OLD.`rowid`; END",+          "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_PhotoFts_BEFORE_DELETE BEFORE DELETE ON `Photo` BEGIN DELETE FROM `PhotoFts` WHERE `docid`=OLD.`rowid`; END",+          "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_PhotoFts_AFTER_UPDATE AFTER UPDATE ON `Photo` BEGIN INSERT INTO `PhotoFts`(`docid`, `ocrText`, `name`) VALUES (NEW.`rowid`, NEW.`ocrText`, NEW.`name`); END",+          "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_PhotoFts_AFTER_INSERT AFTER INSERT ON `Photo` BEGIN INSERT INTO `PhotoFts`(`docid`, `ocrText`, `name`) VALUES (NEW.`rowid`, NEW.`ocrText`, NEW.`name`); END"+        ]+      }+    ],+    "setupQueries": [+      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '6092933db090631ea64b23a6d476fd58')"+    ]+  }+}\ No newline at end of file
photos/src/main/java/com/vayunmathur/photos/data/Photo.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt b/photos/src/main/java/com/vayunmathur/photos/data/Photo.ktindex 99eb14b64c..0ad73a6def 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt@@ -38,7 +38,7 @@ data class PanoData(  /** Immutable value describing photo. */ @Serializable-@Entity(indices = [Index(value = ["date"]), Index(value = ["isTrashed", "duration"])])+@Entity(indices = [Index(value = ["date"]), Index(value = ["isTrashed", "duration"]), Index(value = ["uri"]), Index(value = ["isFavorite", "isTrashed", "date"])]) data class Photo(     @PrimaryKey(autoGenerate = true) override val id: Long = 0,     val name: String,
photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.ktindex c68cc97083..67ef296050 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt@@ -40,6 +40,30 @@ interface PhotoDao {     @Query("SELECT * FROM Photo")     suspend fun getAll(): List<Photo> +    /**+     * Favourites for the Favourites album, newest first. Same light projection+     * as [getAllFlow] (no clipEmbedding/ocrText/ocrBoxes), filtered in SQL+     * instead of loading the whole library and filtering in memory.+     */+    @Query(+        "SELECT id, name, uri, date, width, height, dateModified, exifSet, lat, `long`, duration, " ++            "fullWidth, fullHeight, croppedWidth, croppedHeight, croppedLeft, croppedTop, projectionType, " ++            "isTrashed, faceScanned, ocrScanned, clipScanned, mimeType, album, isFavorite FROM Photo " ++            "WHERE isFavorite = 1 AND isTrashed = 0 ORDER BY date DESC"+    )+    fun getFavoritesFlow(): Flow<List<Photo>>++    /**+     * Sync-only projection: every column [syncPhotos] diffs or preserves, without+     * the heavy clipEmbedding/ocrText/ocrBoxes blobs `SELECT *` would load.+     */+    @Query(+        "SELECT id, name, uri, date, width, height, dateModified, exifSet, lat, `long`, duration, " ++            "fullWidth, fullHeight, croppedWidth, croppedHeight, croppedLeft, croppedTop, projectionType, " ++            "isTrashed, faceScanned, ocrScanned, clipScanned, mimeType, album, isFavorite FROM Photo"+    )+    suspend fun getAllForSync(): List<Photo>+     @Query("SELECT * FROM Photo WHERE uri = :uri")     suspend fun getByUri(uri: String): List<Photo> @@ -340,7 +364,7 @@ data class ExifResult( )  /** Photo Database: a room database implementation for photo database. */-@Database(entities = [Photo::class, Person::class, PhotoFace::class, PhotoFts::class], version = 21, exportSchema = true)+@Database(entities = [Photo::class, Person::class, PhotoFace::class, PhotoFts::class], version = 22, exportSchema = true) abstract class PhotoDatabase : RoomDatabase() {     abstract fun photoDao(): PhotoDao     abstract fun photoScanDao(): PhotoScanDao@@ -353,10 +377,21 @@ abstract class PhotoDatabase : RoomDatabase() {             MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11,             MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16,             MIGRATION_16_17, MIGRATION_17_18, MIGRATION_18_19, MIGRATION_19_20, MIGRATION_20_21,+            MIGRATION_21_22,         )     } } +val MIGRATION_21_22 = Migration(21, 22) {+    // Index uri (sync/MediaStore lookups by content URI) and the favourites+    // predicate (isFavorite + isTrashed, date-ordered for the album).+    it.execSQL("CREATE INDEX IF NOT EXISTS `index_Photo_uri` ON `Photo` (`uri`)")+    it.execSQL(+        "CREATE INDEX IF NOT EXISTS `index_Photo_isFavorite_isTrashed_date` " ++            "ON `Photo` (`isFavorite`, `isTrashed`, `date`)",+    )+}+ val MIGRATION_20_21 = Migration(20, 21) {     // Restore full-text search (dropped by MIGRATION_8_9 for plain LIKE):     // an FTS4 virtual table over OCR text and file name, backed by Photo
photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.ktindex 78b20db149..67f976245a 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt@@ -20,6 +20,8 @@ open class PhotosRepository internal constructor(context: Context) :     // PhotoDao read Flows     // ------------------------------------------------------------------     fun getAllFlow(): Flow<List<Photo>> = photoDao.getAllFlow()+    fun getFavoritesFlow(): Flow<List<Photo>> = photoDao.getFavoritesFlow()+    suspend fun getAllForSync(): List<Photo> = photoDao.getAllForSync()     fun getByIdFlow(id: Long): Flow<Photo?> = photoDao.getByIdFlow(id)     fun getOCRCountFlow(): Flow<Int> = photoDao.getOCRCountFlow()     fun getClipCountFlow(): Flow<Int> = photoDao.getClipCountFlow()
photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt b/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.ktindex 8a21330778..13bd271d14 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt@@ -258,8 +258,7 @@ class GalleryViewModel(      * (getAllFlow is ORDER BY date DESC). Trashed items are left out, like every      * other album; MediaStore keeps their flag, so a restored favourite returns.      */-    val favorites: StateFlow<List<Photo>> = repository.getAllFlow()-        .map { all -> all.filter { it.isFavorite && !it.isTrashed } }+    val favorites: StateFlow<List<Photo>> = repository.getFavoritesFlow()         .distinctUntilChanged()         .flowOn(Dispatchers.Default)         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())@@ -568,6 +567,9 @@ fun GalleryViewModelFactory(  */ interface PhotoStore {     fun getAllFlow(): Flow<List<Photo>>+    /** DAO-filtered favourites; default keeps test fakes source-compatible. */+    fun getFavoritesFlow(): Flow<List<Photo>> =+        getAllFlow().map { all -> all.filter { it.isFavorite && !it.isTrashed } }     fun getOCRCountFlow(): Flow<Int>     fun getIndexTargetCountFlow(): Flow<Int>     fun getClipCountFlow(): Flow<Int>@@ -600,6 +602,7 @@ private class PhotoStoreRepository( ) : PhotoStore {     private val repository = delegate     override fun getAllFlow(): Flow<List<Photo>> = repository.getAllFlow()+    override fun getFavoritesFlow(): Flow<List<Photo>> = repository.getFavoritesFlow()     override fun getOCRCountFlow(): Flow<Int> = repository.getOCRCountFlow()     override fun getIndexTargetCountFlow(): Flow<Int> = repository.getIndexTargetCountFlow()     override fun getClipCountFlow(): Flow<Int> = repository.getClipCountFlow()
photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt b/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.ktindex 04c3b10296..974e50872b 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt@@ -231,7 +231,7 @@ suspend fun syncPhotos(     lastGeneration: Long = 0L, ) {     // Single read of the local DB reused for both deletion detection and update diffing.-    val existing = repository.getAll()+    val existing = repository.getAllForSync()     // 1. Get all IDs currently in MediaStore to detect deletions     val allMediaStoreIds = collectMediaStoreIds(context) 
photos/src/main/java/com/vayunmathur/photos/ui/VideoPlayer.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/VideoPlayer.kt b/photos/src/main/java/com/vayunmathur/photos/ui/VideoPlayer.ktindex d6f0a07284..67755e2281 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/VideoPlayer.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/VideoPlayer.kt@@ -26,6 +26,8 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp+import androidx.media3.common.AudioAttributes+import androidx.media3.common.C import androidx.media3.common.MediaItem import androidx.media3.common.Player import androidx.media3.common.util.UnstableApi@@ -56,12 +58,22 @@ fun VideoPlayer(     var videoAspectRatio by remember { mutableFloatStateOf(16f / 9f) }      val exoPlayer = remember(uri) {-        ExoPlayer.Builder(context).build().apply {-            setMediaItem(MediaItem.fromUri(uri))-            prepare()-            playWhenReady = isSettledPage-            repeatMode = Player.REPEAT_MODE_ONE-        }+        // Mirror music PlaybackService: request audio focus (second arg true)+        // so other apps duck/pause, and pause on audio-becoming-noisy+        // (headphones unplugged) instead of blasting through the speaker.+        val audioAttributes = AudioAttributes.Builder()+            .setUsage(C.USAGE_MEDIA)+            .setContentType(C.AUDIO_CONTENT_TYPE_MOVIE)+            .build()+        ExoPlayer.Builder(context)+            .setAudioAttributes(audioAttributes, true)+            .setHandleAudioBecomingNoisy(true)+            .build().apply {+                setMediaItem(MediaItem.fromUri(uri))+                prepare()+                playWhenReady = isSettledPage+                repeatMode = Player.REPEAT_MODE_ONE+            }     }      var isPlaying by remember { mutableStateOf(isSettledPage) }
photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.ktindex 9bb7b785d0..6feadf7dcf 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.kt@@ -95,8 +95,9 @@ class PhotosSlice1WorkersTest {                 MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11,                 MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16,                 MIGRATION_16_17, MIGRATION_17_18, MIGRATION_18_19, MIGRATION_19_20, MIGRATION_20_21,+                MIGRATION_21_22,             )-            assertEquals(20, PhotoDatabase.migrations.size)+            assertEquals(21, PhotoDatabase.migrations.size)             for (migration in migrations) migration.migrate(connection)              fun queryStrings(sql: String): List<String> = connection.prepare(sql).use { statement ->
youpipe/src/main/java/com/vayunmathur/youpipe/platform/DownloadWorker.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/platform/DownloadWorker.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/platform/DownloadWorker.ktindex d11625c2a8..f447e27021 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/platform/DownloadWorker.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/platform/DownloadWorker.kt@@ -26,6 +26,7 @@ import java.nio.channels.Channels import java.util.concurrent.atomic.AtomicLong import kotlin.time.Clock import kotlin.time.Instant+import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.async@@ -86,16 +87,28 @@ class DownloadWorker(context: Context, params: WorkerParameters) :         coroutineScope {             val videoFile = File(dir, "${input.videoID}.mp4")             val audioFile = if (input.audioUrl != null) File(dir, "${input.videoID}.m4a") else null--            val createdFiles = mutableListOf<File>()-            createdFiles.add(videoFile)-            audioFile?.let { createdFiles.add(it) }+            // Download into `.part` files (mirroring InitialDownloader in+            // library/downloadservice) and rename to the final names only on+            // success: a failed/killed transfer must never leave a file at+            // the final path that looks like a complete download.+            val videoPart = File(dir, "${input.videoID}.mp4.part")+            val audioPart = if (input.audioUrl != null) File(dir, "${input.videoID}.m4a.part") else null++            // Both the `.part` files and the final paths: any failure after+            // a rename must not orphan a (possibly preallocated) final file.+            val createdFiles = mutableListOf<File>(videoPart, videoFile)+            if (audioPart != null && audioFile != null) {+                createdFiles.add(audioPart)+                createdFiles.add(audioFile)+            }              try {-                downloadProgressiveTracks(input, videoFile, audioFile)+                downloadProgressiveTracks(input, videoPart, audioPart)                 // A stop that landed mid-transfer leaves a partial file behind: the                 // finally below deletes it, so don't record a DB row for it.                 if (isStopped) return@coroutineScope Result.failure()+                renamePartToFinal(videoPart, videoFile)+                if (audioPart != null && audioFile != null) renamePartToFinal(audioPart, audioFile)                 val download = DownloadedVideo(                     id = input.videoID,                     videoItem = input.videoInfo,@@ -105,8 +118,15 @@ class DownloadWorker(context: Context, params: WorkerParameters) :                 )                 input.repository.historyStore.upsertDownloadedVideo(download)                 Result.success()-            } catch (e: java.io.IOException) {-                // Cleanup on error or cancellation+            } catch (e: CancellationException) {+                // Cooperative cancellation: clean up, then rethrow as+                // InitialDownloader's download loop does — never swallow it+                // into a Result.failure().+                createdFiles.forEach { if (it.exists()) it.delete() }+                throw e+            } catch (e: Throwable) {+                // Not just IOException: a RuntimeException (extractor /+                // network / DB) used to orphan the preallocated final file.                 Log.error("DownloadWorker", "Progressive download failed for ${input.videoID}", e)                 createdFiles.forEach { if (it.exists()) it.delete() }                 Result.failure()@@ -118,6 +138,16 @@ class DownloadWorker(context: Context, params: WorkerParameters) :             }         } +    /** Atomically promotes a completed `.part` file to its final name. */+    private fun renamePartToFinal(partFile: File, finalFile: File) {+        if (finalFile.exists()) finalFile.delete()+        if (!partFile.renameTo(finalFile)) {+            // Rename can fail across some filesystems; fall back to a copy.+            partFile.copyTo(finalFile, overwrite = true)+            partFile.delete()+        }+    }+     private suspend fun downloadProgressiveTracks(         input: DownloadInput,         videoFile: File,