Skip to content

Commit 44aa140

Browse files
committed
Merge remote master
2 parents 0d54ee5 + 7a08b57 commit 44aa140

5 files changed

Lines changed: 172 additions & 44 deletions

File tree

‎app/src/main/java/app/gyrolet/mpvrx/domain/thumbnail/EmbeddedArtworkCandidates.kt‎

Lines changed: 43 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,19 @@ object EmbeddedArtworkCandidates {
2121
private val artworkExtensions = listOf("jpg", "jpeg", "png", "webp")
2222
private val genericArtworkNames = listOf("cover", "folder", "poster", "thumbnail")
2323

24+
/** Local audio folder cover.mp4; opaque and remote URIs are not guessed. */
25+
fun audioFolderMotionPath(path: String?): String? {
26+
if (path.isNullOrBlank() || path.isRemoteOrOpaqueUri()) return null
27+
val parsed = Uri.parse(path)
28+
val localPath = when (parsed.scheme?.lowercase()) {
29+
null, "" -> path
30+
"file" -> parsed.path
31+
else -> null
32+
} ?: return null
33+
val folder = File(localPath).parentFile ?: return null
34+
return File(folder, "cover.mp4").takeIf { it.isFile && it.canRead() }?.let { Uri.fromFile(it).toString() }
35+
}
36+
2437
fun forVideoPath(path: String): List<String> {
2538
if (path.isBlank() || path.isRemoteOrOpaqueUri()) return emptyList()
2639
val normalizedPath = path.replace('\\', '/')
@@ -128,21 +141,36 @@ internal object EmbeddedArtworkResolver {
128141
?.let(EmbeddedArtworkCandidates::forVideoPath)
129142
?.asSequence()
130143
?.map(::File)
131-
?.firstNotNullOfOrNull { candidate ->
132-
candidate
133-
.takeIf { it.isFile && it.canRead() }
134-
?.let { file ->
135-
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
136-
BitmapFactory.decodeFile(file.path, bounds)
137-
BitmapFactory.decodeFile(
138-
file.path,
139-
BitmapFactory.Options().apply {
140-
inSampleSize = calculateThumbnailSampleSize(bounds.outWidth, bounds.outHeight, maxSize)
141-
inPreferredConfig = Bitmap.Config.ARGB_8888
142-
},
143-
)
144-
}
145-
}
144+
?.firstNotNullOfOrNull { decodeArtworkFile(it, maxSize) }
145+
146+
/** Audio-folder cover.jpg is preferred after embedded artwork. */
147+
fun decodeAudioSidecar(audioPath: String?, maxSize: Int = MAX_THUMBNAIL_SIZE): Bitmap? {
148+
if (audioPath.isNullOrBlank()) return null
149+
val parsed = Uri.parse(audioPath)
150+
val localPath = when (parsed.scheme?.lowercase()) {
151+
null, "" -> audioPath
152+
"file" -> parsed.path
153+
else -> null
154+
} ?: return decodeSidecar(audioPath, maxSize)
155+
val cover = File(localPath).parentFile?.let { File(it, "cover.jpg") }
156+
return decodeArtworkFile(cover, maxSize) ?: decodeSidecar(audioPath, maxSize)
157+
}
158+
159+
private fun decodeArtworkFile(file: File?, maxSize: Int): Bitmap? =
160+
file?.takeIf { it.isFile && it.canRead() }?.let {
161+
runCatching {
162+
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
163+
BitmapFactory.decodeFile(it.path, bounds)
164+
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return@runCatching null
165+
BitmapFactory.decodeFile(
166+
it.path,
167+
BitmapFactory.Options().apply {
168+
inSampleSize = calculateThumbnailSampleSize(bounds.outWidth, bounds.outHeight, maxSize)
169+
inPreferredConfig = Bitmap.Config.ARGB_8888
170+
},
171+
)
172+
}.getOrNull()
173+
}
146174

147175
fun decodeRetrieverArtwork(
148176
retriever: MediaMetadataRetriever,

‎app/src/main/java/app/gyrolet/mpvrx/domain/thumbnail/ThumbnailRepository.kt‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -821,16 +821,18 @@ class ThumbnailRepository(
821821
}
822822
}
823823
}.getOrNull()
824-
return (
825-
retrieverArtwork
826-
?: EmbeddedArtworkResolver.decodeContainerOrSidecar(
827-
videoPath = canonicalPath,
828-
context = context,
829-
videoUri = video.uri,
830-
displayName = video.displayName,
831-
maxSize = maxSize,
832-
)
833-
)?.scaleToThumbnailMax(maxSize)
824+
val sidecarArtwork = if (isAudioArtwork(video)) {
825+
EmbeddedArtworkResolver.decodeAudioSidecar(canonicalPath, maxSize)
826+
} else {
827+
EmbeddedArtworkResolver.decodeContainerOrSidecar(
828+
videoPath = canonicalPath,
829+
context = context,
830+
videoUri = video.uri,
831+
displayName = video.displayName,
832+
maxSize = maxSize,
833+
)
834+
}
835+
return (retrieverArtwork ?: sidecarArtwork)?.scaleToThumbnailMax(maxSize)
834836
}
835837

836838
private suspend fun generateWithFastThumbnails(

‎app/src/main/java/app/gyrolet/mpvrx/ui/player/controls/AudioPlayerControls.kt‎

Lines changed: 62 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,7 @@ private data class AudioPresentationMetadata(
247247
val artwork: Bitmap?,
248248
val artist: String?,
249249
val motionArtwork: ByteArray? = null,
250+
val folderMotionArtworkUri: String? = null,
250251
)
251252

252253
/**
@@ -301,8 +302,19 @@ private object AudioPresentationMetadataCache {
301302
synchronized(cache) { cache.get(key) }?.let { return@withContext it }
302303

303304
// An old native retriever may still be unwinding; Android artwork must not wait for it.
304-
if (isLocalArtworkSource(pathOrUri) && generator != app.gyrolet.mpvrx.preferences.ThumbnailGenerator.Native) {
305-
return@withContext AudioPresentationMetadata(artwork = repository.getArtwork(pathOrUri), artist = null)
305+
val localFolderMotion = app.gyrolet.mpvrx.domain.thumbnail.EmbeddedArtworkCandidates
306+
.audioFolderMotionPath(pathOrUri)
307+
if (
308+
isLocalArtworkSource(pathOrUri) &&
309+
generator != app.gyrolet.mpvrx.preferences.ThumbnailGenerator.Native &&
310+
generator != app.gyrolet.mpvrx.preferences.ThumbnailGenerator.MediaStore &&
311+
!pathOrUri.startsWith("content://", ignoreCase = true) &&
312+
localFolderMotion == null
313+
) {
314+
return@withContext AudioPresentationMetadata(
315+
artwork = repository.getArtwork(pathOrUri),
316+
artist = null,
317+
)
306318
}
307319
loadMutex.withLock {
308320
synchronized(cache) { cache.get(key) }?.let { return@withLock it }
@@ -340,22 +352,42 @@ private object AudioPresentationMetadataCache {
340352
}
341353
}
342354

343-
val pictureBytes = if (explicitArtwork == null) retriever?.embeddedPicture else null
355+
// Priority: embedded artwork, folder cover.jpg, then animated folder cover.mp4.
356+
val pictureBytes = retriever?.embeddedPicture
357+
val embeddedArtwork = retriever?.let {
358+
EmbeddedArtworkResolver.decodeRetrieverArtwork(it, pictureBytes)
359+
}
360+
val sidecarArtwork = if (embeddedArtwork == null) {
361+
EmbeddedArtworkResolver.decodeAudioSidecar(cleanPath ?: pathOrUri)
362+
} else null
363+
// Keep a still image underneath while a selected motion cover buffers.
364+
val folderMotion = if (embeddedArtwork == null && sidecarArtwork == null) {
365+
app.gyrolet.mpvrx.domain.thumbnail.EmbeddedArtworkCandidates
366+
.audioFolderMotionPath(cleanPath ?: pathOrUri)
367+
} else null
344368
AudioPresentationMetadata(
345-
artwork = explicitArtwork ?: retriever?.let { EmbeddedArtworkResolver.decodeEmbeddedArtwork(cleanPath ?: pathOrUri, it, pictureBytes) },
369+
artwork = embeddedArtwork ?: sidecarArtwork ?: explicitArtwork,
346370
artist = retriever?.let {
347371
it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)
348372
?: it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST)
349373
?: it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_AUTHOR)
350374
?: it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_COMPOSER)
351375
},
352376
motionArtwork = EmbeddedMotionArtwork.animatedBytes(pictureBytes),
377+
folderMotionArtworkUri = folderMotion,
353378
)
354379
} catch (_: Exception) {
355380
val fallbackArtwork = explicitArtwork ?: if (cleanPath != null && !isNetworkStream) {
356381
EmbeddedArtworkResolver.decodeSidecar(cleanPath)
357382
} else null
358-
AudioPresentationMetadata(artwork = fallbackArtwork, artist = null)
383+
AudioPresentationMetadata(
384+
artwork = fallbackArtwork,
385+
artist = null,
386+
folderMotionArtworkUri = if (fallbackArtwork == null) {
387+
localFolderMotion
388+
?: app.gyrolet.mpvrx.domain.thumbnail.EmbeddedArtworkCandidates.audioFolderMotionPath(cleanPath ?: pathOrUri)
389+
} else null,
390+
)
359391
} finally {
360392
runCatching { retriever?.release() }
361393
}
@@ -663,6 +695,7 @@ private fun CoverArtCardImage(
663695
artworkUrl: String? = null,
664696
contentScale: ContentScale = ContentScale.Crop,
665697
motionArtwork: ByteArray? = null,
698+
localMotionArtworkUri: String? = null,
666699
isPlaying: Boolean = false,
667700
remoteMotionQuery: MotionArtworkQuery? = null,
668701
remoteMotionSurface: MotionArtworkSurface = MotionArtworkSurface.COVER,
@@ -694,21 +727,14 @@ private fun CoverArtCardImage(
694727
val animatedDrawable = rememberMotionArtworkDrawable(motionArtwork)
695728

696729
Box(modifier.fillMaxSize()) {
697-
if (animatedDrawable != null) {
698-
MotionArtworkImage(
699-
drawable = animatedDrawable,
700-
isPlaying = isPlaying,
701-
fit = contentScale == ContentScale.Fit,
702-
modifier = Modifier.fillMaxSize(),
703-
)
704-
} else if (imageBitmap != null) {
730+
if (imageBitmap != null) {
705731
Image(
706732
bitmap = imageBitmap,
707733
contentDescription = null,
708734
contentScale = contentScale,
709735
modifier = Modifier.fillMaxSize(),
710736
)
711-
} else {
737+
} else if (animatedDrawable == null && localMotionArtworkUri == null) {
712738
Box(
713739
modifier = Modifier.fillMaxSize(),
714740
contentAlignment = Alignment.Center,
@@ -721,6 +747,22 @@ private fun CoverArtCardImage(
721747
)
722748
}
723749
}
750+
// Motion layers sit above the still cover; until the first decoded frame, the
751+
// embedded/folder artwork underneath remains visible.
752+
if (animatedDrawable != null) {
753+
MotionArtworkImage(
754+
drawable = animatedDrawable,
755+
isPlaying = isPlaying,
756+
fit = contentScale == ContentScale.Fit,
757+
modifier = Modifier.fillMaxSize(),
758+
)
759+
} else if (localMotionArtworkUri != null) {
760+
LocalFolderMotionArtworkVideo(
761+
uri = localMotionArtworkUri,
762+
isPlaying = isPlaying,
763+
modifier = Modifier.fillMaxSize(),
764+
)
765+
}
724766
if (remoteMotionQuery != null && animatedDrawable == null) {
725767
RemoteMotionArtwork(
726768
query = remoteMotionQuery,
@@ -753,6 +795,7 @@ private fun ImmersiveArtworkBackground(
753795
bitmap: Bitmap?,
754796
artworkUrl: String?,
755797
motionArtwork: ByteArray?,
798+
localMotionArtworkUri: String?,
756799
remoteMotionQuery: MotionArtworkQuery?,
757800
isPlaying: Boolean,
758801
landscape: Boolean,
@@ -834,6 +877,7 @@ private fun ImmersiveArtworkBackground(
834877
bitmap = bitmap,
835878
artworkUrl = artworkUrl,
836879
motionArtwork = motionArtwork.takeUnless { reducedMotion },
880+
localMotionArtworkUri = localMotionArtworkUri.takeUnless { reducedMotion },
837881
remoteMotionQuery = remoteMotionQuery.takeUnless { reducedMotion },
838882
// Landscape keeps the square side-by-side cover, where a portrait Canvas would be cropped away.
839883
remoteMotionSurface = if (landscape) MotionArtworkSurface.COVER else MotionArtworkSurface.BACKGROUND,
@@ -1387,7 +1431,8 @@ fun AudioPlayerControls(
13871431
val stableInsets = WindowInsets.systemBarsIgnoringVisibility.union(WindowInsets.displayCutout)
13881432
val showImmersiveArtwork = !isTablet && immersiveArtworkEnabled && !showVisualizer && !showInPlaceLyrics &&
13891433
(albumArtBitmap != null || !currentArtworkUri.isNullOrBlank() ||
1390-
currentAudioPresentation?.motionArtwork != null || motionQuery != null)
1434+
currentAudioPresentation?.motionArtwork != null ||
1435+
currentAudioPresentation?.folderMotionArtworkUri != null || motionQuery != null)
13911436
// PlayerActivity uses light status-bar icons; the in-app player follows the app's bar style.
13921437
val useLightImmersiveHeaderContent =
13931438
if (showImmersiveArtwork && inAppSheet != null) {
@@ -1459,6 +1504,7 @@ fun AudioPlayerControls(
14591504
bitmap = activeCoverOverride ?: albumArtBitmap,
14601505
artworkUrl = currentArtworkUri?.takeUnless { isLocalArtworkSource(currentMediaSource) },
14611506
motionArtwork = currentAudioPresentation?.motionArtwork?.takeIf { activeCoverOverride == null },
1507+
localMotionArtworkUri = currentAudioPresentation?.folderMotionArtworkUri?.takeIf { activeCoverOverride == null },
14621508
remoteMotionQuery = motionQuery?.takeIf { activeCoverOverride == null },
14631509
isPlaying = isPlaying,
14641510
landscape = !isPortrait,
@@ -1828,6 +1874,7 @@ fun AudioPlayerControls(
18281874
artworkUrl = currentArtworkUri?.takeUnless { isLocalArtworkSource(currentMediaSource) },
18291875
contentScale = if (isAudiobook) ContentScale.Fit else ContentScale.Crop,
18301876
motionArtwork = currentAudioPresentation?.motionArtwork?.takeIf { activeCoverOverride == null },
1877+
localMotionArtworkUri = currentAudioPresentation?.folderMotionArtworkUri?.takeIf { activeCoverOverride == null },
18311878
isPlaying = isPlaying,
18321879
remoteMotionQuery = motionQuery?.takeIf {
18331880
activeCoverOverride == null && !showVisualizer && !showInPlaceLyrics

‎app/src/main/java/app/gyrolet/mpvrx/ui/player/controls/RemoteMotionArtwork.kt‎

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import androidx.media3.common.PlaybackException
3232
import androidx.media3.common.Player
3333
import androidx.media3.common.VideoSize
3434
import androidx.media3.common.util.UnstableApi
35+
import androidx.media3.datasource.DefaultDataSource
3536
import androidx.media3.datasource.DefaultHttpDataSource
3637
import androidx.media3.exoplayer.DefaultLoadControl
3738
import androidx.media3.exoplayer.ExoPlayer
@@ -162,12 +163,46 @@ private fun MotionArtworkVideo(
162163
}
163164
}
164165

166+
/** Local folder cover.mp4, looped silently and scoped to the visible player lifecycle. */
167+
@Composable
168+
internal fun LocalFolderMotionArtworkVideo(
169+
uri: String,
170+
isPlaying: Boolean,
171+
modifier: Modifier = Modifier,
172+
) {
173+
val lifecycleOwner = LocalLifecycleOwner.current
174+
val lifecycleState by lifecycleOwner.lifecycle.currentStateAsState()
175+
if (lifecycleState.isAtLeast(Lifecycle.State.STARTED)) {
176+
key(uri) {
177+
var firstFrame by remember { mutableStateOf(false) }
178+
AndroidView(
179+
modifier = modifier,
180+
factory = { context ->
181+
MotionArtworkTextureView(
182+
context = context,
183+
rendition = MotionArtworkRendition(uri, hls = false),
184+
source = null,
185+
portrait = false,
186+
onFrameReady = { firstFrame = it },
187+
onFailure = { Log.w("MotionArtworkVideo", "Local folder cover.mp4 could not be played") },
188+
)
189+
},
190+
update = { view ->
191+
view.alpha = if (firstFrame) 1f else 0f
192+
view.setPlaying(isPlaying)
193+
},
194+
onRelease = { view -> view.releasePlayer() },
195+
)
196+
}
197+
}
198+
}
199+
165200
/** HLS/MP4 artwork with audio tracks disabled; no audio focus, media session or video disk cache. */
166201
@OptIn(UnstableApi::class)
167202
private class MotionArtworkTextureView(
168203
context: Context,
169204
private val rendition: MotionArtworkRendition,
170-
private val source: MotionArtworkSource,
205+
private val source: MotionArtworkSource?,
171206
private val portrait: Boolean,
172207
private val onFrameReady: (Boolean) -> Unit,
173208
private val onFailure: () -> Unit,
@@ -202,7 +237,7 @@ private class MotionArtworkTextureView(
202237
http.setDefaultRequestProperties(mapOf("Referer" to "https://music.apple.com/", "Origin" to "https://music.apple.com"))
203238
}
204239
val current = ExoPlayer.Builder(context.applicationContext)
205-
.setMediaSourceFactory(DefaultMediaSourceFactory(http))
240+
.setMediaSourceFactory(DefaultMediaSourceFactory(DefaultDataSource.Factory(context.applicationContext, http)))
206241
.setLoadControl(DefaultLoadControl.Builder().setBufferDurationsMs(2_000, 8_000, 500, 1_000).build())
207242
.setAudioAttributes(AudioAttributes.DEFAULT, false)
208243
.setHandleAudioBecomingNoisy(false)

‎app/src/main/java/app/gyrolet/mpvrx/utils/media/LyricsUtils.kt‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,13 @@ object LyricsUtils {
3737
var isSynced = false
3838

3939
lyricsText.lines().forEach { rawLine ->
40-
val line = rawLine.trim()
40+
// Embedded tags sometimes prefix each lyric with a vocalist channel (for example "v1:").
41+
// Treat that as metadata, and leave online/user-edited lyrics untouched.
42+
val line = if (sourceType == LyricsSourceType.EMBEDDED) {
43+
stripEmbeddedVocalistPrefix(rawLine.trim())
44+
} else {
45+
rawLine.trim()
46+
}
4147
if (line.isEmpty() || LRC_METADATA_PATTERN.matcher(line).matches()) return@forEach
4248

4349
val lineMatcher = LRC_LINE_REGEX.matcher(line)
@@ -46,7 +52,9 @@ object LyricsUtils {
4652
val minutes = lineMatcher.group(1)?.toLong() ?: 0
4753
val seconds = lineMatcher.group(2)?.toLong() ?: 0
4854
val fraction = fractionToMillis(lineMatcher.group(3))
49-
val rawText = lineMatcher.group(4)?.trim() ?: ""
55+
val rawText = (lineMatcher.group(4) ?: "").let { text ->
56+
if (sourceType == LyricsSourceType.EMBEDDED) stripEmbeddedVocalistPrefix(text) else text.trim()
57+
}
5058

5159
val lineTimestamp = (minutes * 60 * 1000 + seconds * 1000 + fraction).toInt()
5260

@@ -144,6 +152,14 @@ object LyricsUtils {
144152
}
145153
}
146154

155+
/**
156+
* Removes leading embedded vocal-track labels such as "v1:", "V2 :" or
157+
* repeated channel labels. Only a numeric v-channel token at line start is
158+
* accepted, so ordinary lyric text and mid-line occurrences are preserved.
159+
*/
160+
private fun stripEmbeddedVocalistPrefix(text: String): String =
161+
text.replace(Regex("^(?:v\\d+\\s*:\\s*)+", RegexOption.IGNORE_CASE), "").trim()
162+
147163
/** Converts LRC tenths, centiseconds, or milliseconds to milliseconds. */
148164
private fun fractionToMillis(fraction: String?): Long =
149165
when (fraction?.length) {

0 commit comments

Comments
 (0)