Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

YouTube videos say why they are not the official one, and stop stalling

Lelonio78552ee5f3a1
diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/ChunkedDataSource.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/ChunkedDataSource.kt
new file mode 100644
index 0000000..22d3d6d
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/ChunkedDataSource.kt
@@ -0,0 +1,115 @@
+package dev.lelonio.square.backend.youtube
+
+import android.net.Uri
+import androidx.media3.common.C
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.datasource.DataSource
+import androidx.media3.datasource.DataSpec
+import androidx.media3.datasource.TransferListener
+
+/**
+ * A YouTube stream fetched a piece at a time, read as one.
+ *
+ * YouTube lets a single long request run for a few seconds and then holds it
+ * back: a video played for seven seconds and stood still for ten. Here each
+ * piece is a request of its own, too short to be held back, and the next is
+ * asked for as soon as one runs out — below the player, which sees one stream
+ * and its end only where the file really ends.
+ */
+@UnstableApi
+class ChunkedDataSource(private val upstream: DataSource) : DataSource {
+
+ class Factory(private val upstream: DataSource.Factory) : DataSource.Factory {
+ override fun createDataSource() = ChunkedDataSource(upstream.createDataSource())
+ }
+
+ private var spec: DataSpec? = null
+ private var chunked = false
+ /** Where the next piece starts, from the start of the file. */
+ private var position = 0L
+ /** Bytes still wanted in all, or unset for "to the end". */
+ private var remaining = C.LENGTH_UNSET.toLong()
+ private var pieceLeft = 0L
+ private var opened = false
+
+ override fun addTransferListener(transferListener: TransferListener) =
+ upstream.addTransferListener(transferListener)
+
+ override fun open(dataSpec: DataSpec): Long {
+ spec = dataSpec
+ chunked = dataSpec.uri.scheme == "https" && dataSpec.uri.host.orEmpty().endsWith("googlevideo.com")
+ if (!chunked) {
+ opened = true
+ return upstream.open(dataSpec)
+ }
+ position = dataSpec.position
+ remaining = dataSpec.length
+ val first = openPiece()
+ // The whole of what is left, where the server said how big the file is.
+ val total = upstream.responseHeaders["Content-Range"]?.firstOrNull()
+ ?.substringAfter('/')?.toLongOrNull()
+ return when {
+ remaining != C.LENGTH_UNSET.toLong() -> remaining
+ total != null -> total - dataSpec.position
+ else -> if (first < CHUNK_BYTES) first else C.LENGTH_UNSET.toLong()
+ }
+ }
+
+ private fun openPiece(): Long {
+ val wanted = if (remaining == C.LENGTH_UNSET.toLong()) CHUNK_BYTES else minOf(CHUNK_BYTES, remaining)
+ val piece = spec!!.buildUpon().setPosition(position).setLength(wanted).build()
+ val length = upstream.open(piece)
+ opened = true
+ pieceLeft = if (length == C.LENGTH_UNSET.toLong()) wanted else length
+ return pieceLeft
+ }
+
+ override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
+ if (length == 0) return 0
+ if (!chunked) return upstream.read(buffer, offset, length)
+ while (true) {
+ if (remaining == 0L) return C.RESULT_END_OF_INPUT
+ if (!opened) {
+ // The next piece. Asked past the end, the server says 416.
+ val next = try {
+ openPiece()
+ } catch (e: androidx.media3.datasource.HttpDataSource.InvalidResponseCodeException) {
+ if (e.responseCode == 416) return C.RESULT_END_OF_INPUT
+ throw e
+ }
+ if (next == 0L) return C.RESULT_END_OF_INPUT
+ }
+ val read = upstream.read(buffer, offset, minOf(length.toLong(), pieceLeft).toInt())
+ if (read == C.RESULT_END_OF_INPUT) {
+ // Shorter than asked for: the file ends inside this piece.
+ if (pieceLeft > 0) return C.RESULT_END_OF_INPUT
+ upstream.close()
+ opened = false
+ continue
+ }
+ position += read
+ pieceLeft -= read
+ if (remaining != C.LENGTH_UNSET.toLong()) remaining -= read
+ if (pieceLeft == 0L) {
+ upstream.close()
+ opened = false
+ }
+ return read
+ }
+ }
+
+ override fun getUri(): Uri? = upstream.uri ?: spec?.uri
+
+ override fun getResponseHeaders(): Map<String, List<String>> = upstream.responseHeaders
+
+ override fun close() {
+ if (opened) upstream.close()
+ opened = false
+ spec = null
+ }
+
+ private companion object {
+ /** Half a megabyte: a few seconds of 1080p, a minute of sound. */
+ const val CHUNK_BYTES = 512L * 1024
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt
index c5925cc..de64582 100644
--- a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt
@@ -44,9 +44,11 @@ object YouTubePlayerFactory {
val dataSources = ResolvingDataSource.Factory(
// Files as well as the network: a kept song resolves to one on the
// phone, which an HTTP source cannot open.
- androidx.media3.datasource.DefaultDataSource.Factory(
- host.context,
- DefaultHttpDataSource.Factory(),
+ ChunkedDataSource.Factory(
+ androidx.media3.datasource.DefaultDataSource.Factory(
+ host.context,
+ DefaultHttpDataSource.Factory(),
+ ),
),
YouTubeStreamResolver(host.context.applicationContext),
)
@@ -130,6 +132,16 @@ object YouTubePlayerFactory {
android.util.Log.w(TAG, "params speed=${parameters.speed} pitch=${parameters.pitch}")
}
+ override fun onLoadError(
+ eventTime: androidx.media3.exoplayer.analytics.AnalyticsListener.EventTime,
+ loadEventInfo: androidx.media3.exoplayer.source.LoadEventInfo,
+ mediaLoadData: androidx.media3.exoplayer.source.MediaLoadData,
+ error: java.io.IOException,
+ wasCanceled: Boolean,
+ ) {
+ android.util.Log.w(TAG, "load error ${loadEventInfo.uri.host}: ${error.message}")
+ }
+
override fun onAudioSinkError(
eventTime: androidx.media3.exoplayer.analytics.AnalyticsListener.EventTime,
audioSinkError: Exception,
@@ -390,7 +402,19 @@ object YouTubeStreams {
val chosen = runCatching { OfficialVideos.forSong(songId, song) }.getOrNull()
?.let { id ->
runCatching { id to info(id) }
- .onFailure { android.util.Log.i("SquareYTVideo", "official video $id unplayable: ${it.message}") }
+ .onFailure {
+ android.util.Log.i("SquareYTVideo", "official video $id unplayable: ${it.message}")
+ // Said under the picture, so the cover standing in for
+ // the video is not mistaken for a bug.
+ YouTubeVideoMode.markUnavailable(
+ songId,
+ if (it is org.schabi.newpipe.extractor.exceptions.AgeRestrictedContentException) {
+ YouTubeVideoMode.Unavailable.AGE_RESTRICTED
+ } else {
+ YouTubeVideoMode.Unavailable.OTHER
+ },
+ )
+ }
.getOrNull()
}
?: (songId to song)
diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeVideoMode.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeVideoMode.kt
index fb4cfe5..3337423 100644
--- a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeVideoMode.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeVideoMode.kt
@@ -78,6 +78,18 @@ object YouTubeVideoMode {
var byItem = false
private set
+ /** Why a song's official video could not be shown in its place. */
+ enum class Unavailable { AGE_RESTRICTED, OTHER }
+
+ private val _unavailable = MutableStateFlow<Map<String, Unavailable>>(emptyMap())
+
+ /** By video id of the song: the songs showing their own upload instead of their video. */
+ val unavailable: StateFlow<Map<String, Unavailable>> = _unavailable.asStateFlow()
+
+ fun markUnavailable(songId: String, reason: Unavailable) {
+ _unavailable.value = _unavailable.value + (songId to reason)
+ }
+
/** Set when the listener asked for the video playing to be sound alone. */
@Volatile
private var audioOnly = false
diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
index 5194a95..a3636ef 100644
--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
@@ -490,6 +490,7 @@ fun SquareApp(
val positionMs = if (remote != null) remotePosition else localPosition
val queueSource = rememberQueue(player)
val videoOn by YouTubeVideoMode.enabled.collectAsStateWithLifecycle()
+ val videoUnavailable by YouTubeVideoMode.unavailable.collectAsStateWithLifecycle()
// Video keeps playing when the app leaves the foreground, surface or no
// surface. Switching back to the audio-only stream would be tidier, but the
@@ -3085,6 +3086,18 @@ fun SquareApp(
}
?.let { { YouTubeVideoMode.toggle(it) } },
videoOn = videoOn || spotifyVideoOn,
+ videoNotice = playback.mediaId
+ ?.takeIf { it.startsWith(dev.lelonio.square.backend.youtube.YouTubeBackend.TRACK_PREFIX) }
+ ?.let { videoUnavailable[dev.lelonio.square.backend.youtube.YouTubeBackend.videoIdOfUri(it)] }
+ ?.let { reason ->
+ stringResource(
+ if (reason == YouTubeVideoMode.Unavailable.AGE_RESTRICTED) {
+ R.string.video_age_restricted
+ } else {
+ R.string.video_unavailable
+ },
+ )
+ },
videoPlayer = player,
videoAttachKey = spotifyVideoGeneration,
)
diff --git a/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt b/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt
index 458555a..be22720 100644
--- a/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt
@@ -39,6 +39,7 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.shape.CircleShape
@@ -355,6 +356,8 @@ fun PlayerScreen(
onWatchVideo: (() -> Unit)? = null,
/** Showing the picture right now. */
videoOn: Boolean = false,
+ /** Why the picture is not the song's official video, when it is not. */
+ videoNotice: String? = null,
/** The player to hang the video surface off; null when there is no video. */
videoPlayer: Player? = null,
/** Changes when the session starts playing a new video; see VideoStage. */
@@ -1005,7 +1008,12 @@ fun PlayerScreen(
// keeps drawing the one it is leaving, and
// the controller it holds is gone the moment
// the activity stops.
- Box(contentAlignment = Alignment.Center) {
+ // Gives up height to the button under it rather
+ // than taking the whole stage and squashing it.
+ Box(
+ Modifier.weight(1f, fill = false),
+ contentAlignment = Alignment.Center,
+ ) {
videoPlayer?.let {
VideoStage(
it,
@@ -1020,12 +1028,21 @@ fun PlayerScreen(
Row(
Modifier
.fillMaxWidth()
- .padding(top = 10.dp, end = 4.dp),
- horizontalArrangement = Arrangement.End,
+ .padding(top = 10.dp, start = 4.dp, end = 4.dp),
+ horizontalArrangement = Arrangement.spacedBy(10.dp),
+ verticalAlignment = Alignment.CenterVertically,
) {
+ Text(
+ videoNotice.orEmpty(),
+ style = MaterialTheme.typography.bodySmall,
+ color = Color.White.copy(alpha = 0.8f),
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f),
+ )
Box(
Modifier
- .size(36.dp)
+ .requiredSize(36.dp)
.clip(CircleShape)
.background(Color.Black.copy(alpha = 0.35f))
.pressable(onClick = {
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index 6934bfa..b48b95f 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -475,4 +475,6 @@
<string name="subscribers_count">%s Abonnenten</string>
<string name="exit_full_screen">Vollbild beenden</string>
<string name="rotate_video">Ins Vollbild drehen</string>
+ <string name="video_age_restricted">Das offizielle Video ist altersbeschränkt und erfordert eine YouTube-Anmeldung: Das Video des Songs wird gezeigt.</string>
+ <string name="video_unavailable">Das offizielle Video kann nicht abgespielt werden: Das Video des Songs wird gezeigt.</string>
</resources>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 9f2f0d2..797806c 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -481,4 +481,6 @@
<string name="subscribers_count">%s suscriptores</string>
<string name="exit_full_screen">Salir de pantalla completa</string>
<string name="rotate_video">Girar a pantalla completa</string>
+ <string name="video_age_restricted">El vídeo oficial tiene restricción de edad y requiere iniciar sesión en YouTube: se muestra el vídeo de la canción.</string>
+ <string name="video_unavailable">El vídeo oficial no se puede reproducir: se muestra el vídeo de la canción.</string>
</resources>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index 26cdab9..882f197 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -475,4 +475,6 @@
<string name="subscribers_count">%s abonnés</string>
<string name="exit_full_screen">Quitter le plein écran</string>
<string name="rotate_video">Pivoter en plein écran</string>
+ <string name="video_age_restricted">La vidéo officielle est soumise à une limite d\'âge et nécessite une connexion à YouTube : affichage de la vidéo du titre.</string>
+ <string name="video_unavailable">La vidéo officielle ne peut pas être lue : affichage de la vidéo du titre.</string>
</resources>
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index 7312736..1d7837b 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -490,4 +490,6 @@
<string name="subscribers_count">%s सब्सक्राइबर</string>
<string name="exit_full_screen">फ़ुल स्क्रीन से बाहर निकलें</string>
<string name="rotate_video">फ़ुल स्क्रीन के लिए घुमाएँ</string>
+ <string name="video_age_restricted">आधिकारिक वीडियो आयु-प्रतिबंधित है और YouTube साइन-इन चाहिए: गाने का वीडियो दिखाया जा रहा है।</string>
+ <string name="video_unavailable">आधिकारिक वीडियो नहीं चल सकता: गाने का वीडियो दिखाया जा रहा है।</string>
</resources>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index ca19901..1355ac8 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -476,4 +476,6 @@
<string name="subscribers_count">%s iscritti</string>
<string name="exit_full_screen">Esci da schermo intero</string>
<string name="rotate_video">Ruota a schermo intero</string>
+ <string name="video_age_restricted">Il video ufficiale è vietato ai minori e richiede l\'accesso a YouTube: mostro il video del brano.</string>
+ <string name="video_unavailable">Il video ufficiale non può essere riprodotto: mostro il video del brano.</string>
</resources>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index 5797e8e..b317f81 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -475,4 +475,6 @@
<string name="subscribers_count">%s inscritos</string>
<string name="exit_full_screen">Sair da tela cheia</string>
<string name="rotate_video">Girar para tela cheia</string>
+ <string name="video_age_restricted">O vídeo oficial tem restrição de idade e exige login no YouTube: mostrando o vídeo da música.</string>
+ <string name="video_unavailable">O vídeo oficial não pode ser reproduzido: mostrando o vídeo da música.</string>
</resources>
diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml
index a03e914..e02c6f1 100644
--- a/app/src/main/res/values-ru/strings.xml
+++ b/app/src/main/res/values-ru/strings.xml
@@ -502,4 +502,6 @@
<string name="subscribers_count">%s подписчиков</string>
<string name="exit_full_screen">Выйти из полноэкранного режима</string>
<string name="rotate_video">Повернуть на весь экран</string>
+ <string name="video_age_restricted">Официальное видео с возрастным ограничением и требует входа в YouTube: показано видео трека.</string>
+ <string name="video_unavailable">Официальное видео недоступно: показано видео трека.</string>
</resources>
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index 9fe6eb0..67ba4bf 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -488,4 +488,6 @@
<string name="subscribers_count">%s abone</string>
<string name="exit_full_screen">Tam ekrandan çık</string>
<string name="rotate_video">Tam ekran için döndür</string>
+ <string name="video_age_restricted">Resmi video yaş kısıtlamalı ve YouTube girişi gerektiriyor: şarkının kendi videosu gösteriliyor.</string>
+ <string name="video_unavailable">Resmi video oynatılamıyor: şarkının kendi videosu gösteriliyor.</string>
</resources>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 682fc12..c38e8cb 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -502,4 +502,6 @@
<string name="subscribers_count">%s subscribers</string>
<string name="exit_full_screen">Exit full screen</string>
<string name="rotate_video">Rotate to full screen</string>
+ <string name="video_age_restricted">The official video is age-restricted and needs a YouTube sign-in: showing the song\'s own video.</string>
+ <string name="video_unavailable">The official video can\'t be played: showing the song\'s own video.</string>
</resources>