Add file and volume snapshot codecs

This commit is contained in:
jay
2026-11-14 06:06:05 -05:00
parent b380a412d2
commit f3cfa995c3
8 changed files with 539 additions and 29 deletions
@@ -0,0 +1,63 @@
/*
* Copyright (c) 2026 Auxio Project
* ValueVolumes.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.fs.path
import android.content.Context
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Volume
/** Value-backed internal volume. The display name is not part of its stable identity. */
internal data class InternalVolumeValue(
override val mediaStoreName: String?,
override val components: Components?,
val displayName: String,
) : Volume.Internal {
override fun resolveName(context: Context) = displayName
override fun equals(other: Any?) =
other is InternalVolumeValue &&
mediaStoreName == other.mediaStoreName &&
components == other.components
override fun hashCode() =
31 * (mediaStoreName?.hashCode() ?: 0) + (components?.hashCode() ?: 0)
}
/** Value-backed external volume. The display name is not part of its stable identity. */
internal data class ExternalVolumeValue(
override val id: String?,
override val mediaStoreName: String?,
override val components: Components?,
val displayName: String,
) : Volume.External {
override fun resolveName(context: Context) = displayName
override fun equals(other: Any?) =
other is ExternalVolumeValue &&
id == other.id &&
mediaStoreName == other.mediaStoreName &&
components == other.components
override fun hashCode(): Int {
var result = id?.hashCode() ?: 0
result = 31 * result + (mediaStoreName?.hashCode() ?: 0)
result = 31 * result + (components?.hashCode() ?: 0)
return result
}
}
@@ -42,43 +42,41 @@ internal interface VolumeManager {
companion object { companion object {
fun from(context: Context): VolumeManager = fun from(context: Context): VolumeManager =
VolumeManagerImpl(context.getSystemService(StorageManager::class.java)) VolumeManagerImpl(
context.getSystemService(StorageManager::class.java),
context.applicationContext,
)
} }
} }
private class VolumeManagerImpl(private val storageManager: StorageManager) : VolumeManager { private class VolumeManagerImpl(
private val storageManager: StorageManager,
private val context: Context,
) : VolumeManager {
override fun getInternalVolume(): Volume.Internal = override fun getInternalVolume(): Volume.Internal =
InternalVolumeImpl(storageManager.primaryStorageVolume) storageManager.primaryStorageVolume.toInternalValue(context)
override fun getVolumes() = override fun getVolumes(): List<Volume> =
storageManager.storageVolumesCompat.map { storageManager.storageVolumesCompat.map {
if (it.isInternalCompat) { if (it.isInternalCompat) {
InternalVolumeImpl(it) it.toInternalValue(context)
} else { } else {
ExternalVolumeImpl(it) it.toExternalValue(context)
} }
} }
private data class InternalVolumeImpl(val storageVolume: StorageVolume) : Volume.Internal {
override val mediaStoreName
get() = storageVolume.mediaStoreVolumeNameCompat
override val components
get() = storageVolume.directoryCompat?.let(Components.Companion::parseUnix)
override fun resolveName(context: Context) = storageVolume.getDescriptionCompat(context)
}
private data class ExternalVolumeImpl(val storageVolume: StorageVolume) : Volume.External {
override val id
get() = storageVolume.uuidCompat
override val mediaStoreName
get() = storageVolume.mediaStoreVolumeNameCompat
override val components
get() = storageVolume.directoryCompat?.let(Components.Companion::parseUnix)
override fun resolveName(context: Context) = storageVolume.getDescriptionCompat(context)
}
} }
private fun StorageVolume.toInternalValue(context: Context) =
InternalVolumeValue(
mediaStoreName = mediaStoreVolumeNameCompat,
components = directoryCompat?.let(Components.Companion::parseUnix),
displayName = getDescriptionCompat(context),
)
private fun StorageVolume.toExternalValue(context: Context) =
ExternalVolumeValue(
id = uuidCompat,
mediaStoreName = mediaStoreVolumeNameCompat,
components = directoryCompat?.let(Components.Companion::parseUnix),
displayName = getDescriptionCompat(context),
)
@@ -18,6 +18,7 @@
package org.oxycblt.musikr.snapshot package org.oxycblt.musikr.snapshot
import android.net.Uri
import java.io.DataInputStream import java.io.DataInputStream
import java.io.DataOutputStream import java.io.DataOutputStream
import java.io.IOException import java.io.IOException
@@ -27,6 +28,12 @@ import java.nio.ByteBuffer
import java.nio.charset.CodingErrorAction import java.nio.charset.CodingErrorAction
import java.util.UUID import java.util.UUID
import org.oxycblt.musikr.Music import org.oxycblt.musikr.Music
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Format
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.Volume
import org.oxycblt.musikr.fs.path.ExternalVolumeValue
import org.oxycblt.musikr.fs.path.InternalVolumeValue
import org.oxycblt.musikr.tag.Date import org.oxycblt.musikr.tag.Date
import org.oxycblt.musikr.tag.Disc import org.oxycblt.musikr.tag.Disc
import org.oxycblt.musikr.tag.ReleaseType import org.oxycblt.musikr.tag.ReleaseType
@@ -36,10 +43,20 @@ object LibrarySnapshotCodec {
const val MAGIC = "AUXSNAP" const val MAGIC = "AUXSNAP"
private const val SCHEMA_VERSION = 1 private const val SCHEMA_VERSION = 1
private const val MAX_STRING_BYTES = 1024 * 1024 private const val MAX_STRING_BYTES = 1024 * 1024
private const val MAX_FORMAT_DEPTH = 8
private val MAGIC_BYTES = MAGIC.toByteArray(Charsets.US_ASCII) private val MAGIC_BYTES = MAGIC.toByteArray(Charsets.US_ASCII)
data class Header(val magic: String, val schemaVersion: Int) data class Header(val magic: String, val schemaVersion: Int)
data class FileProperties(
val uri: Uri,
val path: Path,
val format: Format,
val size: Long,
val modifiedMs: Long,
val addedMs: Long,
)
fun writeHeader(output: OutputStream) { fun writeHeader(output: OutputStream) {
val dataOutput = DataOutputStream(output) val dataOutput = DataOutputStream(output)
dataOutput.write(MAGIC_BYTES) dataOutput.write(MAGIC_BYTES)
@@ -283,4 +300,137 @@ object LibrarySnapshotCodec {
else -> throw IOException("Invalid snapshot MusicBrainz ID marker: $marker") else -> throw IOException("Invalid snapshot MusicBrainz ID marker: $marker")
} }
} }
fun writePath(output: OutputStream, value: Path) {
when (val volume = value.volume) {
is InternalVolumeValue -> {
writeInt(output, 0)
writeNullableString(output, volume.mediaStoreName)
writeNullableString(output, volume.components?.unixString)
writeString(output, volume.displayName)
}
is ExternalVolumeValue -> {
writeInt(output, 1)
writeNullableString(output, volume.id)
writeNullableString(output, volume.mediaStoreName)
writeNullableString(output, volume.components?.unixString)
writeString(output, volume.displayName)
}
else -> throw IOException("Unsupported snapshot path volume")
}
writeString(output, value.components.unixString)
}
fun readPath(input: InputStream): Path {
val volume: Volume =
when (readInt(input)) {
0 -> {
val mediaStoreName = readNullableString(input)
val components = readNullableComponents(input)
InternalVolumeValue(mediaStoreName, components, readString(input))
}
1 -> {
val id = readNullableString(input)
val mediaStoreName = readNullableString(input)
val components = readNullableComponents(input)
ExternalVolumeValue(id, mediaStoreName, components, readString(input))
}
else -> throw IOException("Invalid snapshot path volume")
}
return Path(volume, Components.parseUnix(readString(input)))
}
private fun readNullableComponents(input: InputStream): Components? {
return readNullableString(input)?.let { Components.parseUnix(it) }
}
fun writeUri(output: OutputStream, value: Uri) {
writeString(output, value.toString())
}
fun readUri(input: InputStream): Uri {
return Uri.parse(readString(input))
}
fun writeFormat(output: OutputStream, value: Format) {
writeFormat(output, value, depth = 0)
}
private fun writeFormat(output: OutputStream, value: Format, depth: Int) {
require(depth <= MAX_FORMAT_DEPTH) { "Snapshot format nesting exceeds depth limit" }
when (value) {
Format.MPEG3 -> writeInt(output, 0)
is Format.MPEG4 -> {
writeInt(output, 1)
writeNullableFormat(output, value.containing, depth + 1)
}
Format.AAC -> writeInt(output, 2)
Format.ALAC -> writeInt(output, 3)
is Format.Ogg -> {
writeInt(output, 4)
writeNullableFormat(output, value.containing, depth + 1)
}
Format.Opus -> writeInt(output, 5)
Format.Vorbis -> writeInt(output, 6)
Format.FLAC -> writeInt(output, 7)
Format.Wav -> writeInt(output, 8)
is Format.Unknown -> {
writeInt(output, 9)
writeString(output, value.mimeType)
}
}
}
private fun writeNullableFormat(output: OutputStream, value: Format?, depth: Int) {
writeBoolean(output, value != null)
if (value != null) {
writeFormat(output, value, depth)
}
}
fun readFormat(input: InputStream): Format {
return readFormat(input, depth = 0)
}
private fun readFormat(input: InputStream, depth: Int): Format {
if (depth > MAX_FORMAT_DEPTH) {
throw IOException("Snapshot format nesting exceeds depth limit")
}
return when (readInt(input)) {
0 -> Format.MPEG3
1 -> Format.MPEG4(readNullableFormat(input, depth + 1))
2 -> Format.AAC
3 -> Format.ALAC
4 -> Format.Ogg(readNullableFormat(input, depth + 1))
5 -> Format.Opus
6 -> Format.Vorbis
7 -> Format.FLAC
8 -> Format.Wav
9 -> Format.Unknown(readString(input))
else -> throw IOException("Invalid snapshot audio format")
}
}
private fun readNullableFormat(input: InputStream, depth: Int): Format? {
return if (readBoolean(input)) readFormat(input, depth) else null
}
fun writeFileProperties(output: OutputStream, value: FileProperties) {
writeUri(output, value.uri)
writePath(output, value.path)
writeFormat(output, value.format)
writeLong(output, value.size)
writeLong(output, value.modifiedMs)
writeLong(output, value.addedMs)
}
fun readFileProperties(input: InputStream): FileProperties {
val uri = readUri(input)
val path = readPath(input)
val format = readFormat(input)
val size = readLong(input)
val modifiedMs = readLong(input)
val addedMs = readLong(input)
return FileProperties(uri, path, format, size, modifiedMs, addedMs)
}
} }
@@ -0,0 +1,52 @@
/*
* Copyright (c) 2026 Auxio Project
* ValueVolumesTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.fs.path
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
import org.oxycblt.musikr.fs.Components
class ValueVolumesTest {
@Test
fun internalValue_equalityUsesStableIdentityNotDisplayName() {
val components = Components.parseUnix("/storage/emulated/0")
val value = InternalVolumeValue("external_primary", components, "Phone")
val relabelled = InternalVolumeValue("external_primary", components, "Internal storage")
val different = InternalVolumeValue("different", components, "Phone")
assertEquals(value, relabelled)
assertEquals(value.hashCode(), relabelled.hashCode())
assertNotEquals(value, different)
}
@Test
fun externalValue_equalityIncludesVolumeIdNotDisplayName() {
val components = Components.parseUnix("/storage/7AFE-060A")
val value = ExternalVolumeValue("7AFE-060A", "7afe-060a", components, "SD card")
val relabelled =
ExternalVolumeValue("7AFE-060A", "7afe-060a", components, "Walkman card")
val different =
ExternalVolumeValue("FFFFFFFF-FFFF", "7afe-060a", components, "SD card")
assertEquals(value, relabelled)
assertEquals(value.hashCode(), relabelled.hashCode())
assertNotEquals(value, different)
}
}
@@ -29,6 +29,10 @@ import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows import org.junit.Assert.assertThrows
import org.junit.Test import org.junit.Test
import org.oxycblt.musikr.Music import org.oxycblt.musikr.Music
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.ExternalVolumeValue
import org.oxycblt.musikr.fs.path.InternalVolumeValue
import org.oxycblt.musikr.tag.Date import org.oxycblt.musikr.tag.Date
import org.oxycblt.musikr.tag.Disc import org.oxycblt.musikr.tag.Disc
import org.oxycblt.musikr.tag.ReleaseType import org.oxycblt.musikr.tag.ReleaseType
@@ -355,4 +359,81 @@ class LibrarySnapshotCodecTest {
assertEquals(values, decoded) assertEquals(values, decoded)
} }
@Test
fun path_roundTrip_preservesSharedVolumesAndComponents() {
val paths =
listOf(
Path(
InternalVolumeValue(
"external_primary",
Components.parseUnix("/storage/emulated/0"),
"Phone",
),
Components.parseUnix("Library/A/song.mp3"),
),
Path(
ExternalVolumeValue(
"7AFE-060A",
"7afe-060a",
Components.parseUnix("/storage/7AFE-060A"),
"SD card",
),
Components.parseUnix("Development/Music/song.mp3"),
),
)
val output = ByteArrayOutputStream()
paths.forEach { LibrarySnapshotCodec.writePath(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = paths.map { LibrarySnapshotCodec.readPath(input) }
assertEquals(paths, decoded)
assertEquals("Phone", (decoded[0].volume as InternalVolumeValue).displayName)
assertEquals("SD card", (decoded[1].volume as ExternalVolumeValue).displayName)
}
@Test
fun domainCodecs_invalidEncodings_throwIOException() {
val invalidText = ByteArrayOutputStream()
LibrarySnapshotCodec.writeString(invalidText, "not-a-domain-value")
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readUid(ByteArrayInputStream(invalidText.toByteArray()))
}
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readDate(ByteArrayInputStream(invalidText.toByteArray()))
}
fun taggedInput(): ByteArrayInputStream {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeInt(output, 99)
return ByteArrayInputStream(output.toByteArray())
}
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readReleaseType(taggedInput())
}
assertThrows(IOException::class.java) { LibrarySnapshotCodec.readPath(taggedInput()) }
assertThrows(IOException::class.java) { LibrarySnapshotCodec.readFormat(taggedInput()) }
val invalidRefinement = ByteArrayOutputStream()
LibrarySnapshotCodec.writeInt(invalidRefinement, 0)
LibrarySnapshotCodec.writeNullableString(invalidRefinement, "SYNCHRONIZED")
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readReleaseType(
ByteArrayInputStream(invalidRefinement.toByteArray())
)
}
val excessiveNesting = ByteArrayOutputStream()
repeat(10) {
LibrarySnapshotCodec.writeInt(excessiveNesting, 1)
LibrarySnapshotCodec.writeBoolean(excessiveNesting, true)
}
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readFormat(
ByteArrayInputStream(excessiveNesting.toByteArray())
)
}
}
} }
@@ -0,0 +1,65 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotFileCodecTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import android.net.Uri
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Format
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.ExternalVolumeValue
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotFileCodecTest {
@Test
fun fileProperties_roundTrip_preservesIdentitySizeAndTimestamps() {
val value =
LibrarySnapshotCodec.FileProperties(
uri = Uri.parse("content://media/7AFE-060A/audio/media/42"),
path =
Path(
ExternalVolumeValue(
"7AFE-060A",
"7afe-060a",
Components.parseUnix("/storage/7AFE-060A"),
"SD card",
),
Components.parseUnix("Development/Music/Library/song.ogg"),
),
format = Format.Ogg(Format.Opus),
size = 17_130_325L,
modifiedMs = 1_794_589_521_000L,
addedMs = 1_794_619_280_000L,
)
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeFileProperties(output, value)
val decoded =
LibrarySnapshotCodec.readFileProperties(ByteArrayInputStream(output.toByteArray()))
assertEquals(value, decoded)
}
}
@@ -0,0 +1,58 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotFormatCodecTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.fs.Format
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotFormatCodecTest {
@Test
fun format_roundTrip_preservesEveryVariant() {
val values =
listOf(
Format.MPEG3,
Format.MPEG4(Format.AAC),
Format.MPEG4(null),
Format.AAC,
Format.ALAC,
Format.Ogg(Format.Vorbis),
Format.Ogg(null),
Format.Opus,
Format.Vorbis,
Format.FLAC,
Format.Wav,
Format.Unknown("audio/x-custom"),
)
val output = ByteArrayOutputStream()
values.forEach { LibrarySnapshotCodec.writeFormat(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = values.map { LibrarySnapshotCodec.readFormat(input) }
assertEquals(values, decoded)
}
}
@@ -0,0 +1,43 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotUriCodecTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import android.net.Uri
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotUriCodecTest {
@Test
fun uri_roundTrip_preservesCanonicalText() {
val uri = Uri.parse("content://org.oxycblt.auxio/Library/初音%20ミク.mp3")
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeUri(output, uri)
val decoded = LibrarySnapshotCodec.readUri(ByteArrayInputStream(output.toByteArray()))
assertEquals(uri, decoded)
}
}