Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Player rework #202

Merged
merged 7 commits into from
Jan 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions app/proguard-rules.pro
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,10 @@
-dontwarn org.openjsse.javax.net.ssl.SSLSocket
-dontwarn org.openjsse.net.ssl.OpenJSSE
-dontwarn org.slf4j.impl.StaticLoggerBinder

## Rules for NewPipeExtractor
-keep class org.schabi.newpipe.extractor.timeago.patterns.** { *; }
-keep class org.mozilla.javascript.** { *; }
-keep class org.mozilla.classfile.ClassFileWriter
-dontwarn org.mozilla.javascript.JavaToJSONConverters
-dontwarn org.mozilla.javascript.tools.**
47 changes: 19 additions & 28 deletions app/src/main/java/com/dd3boh/outertune/playback/DownloadUtil.kt
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import java.util.concurrent.Executor
import javax.inject.Inject
import javax.inject.Singleton
import com.dd3boh.outertune.extensions.getLikeAutoDownload
import com.dd3boh.outertune.utils.YTPlayerUtils

@Singleton
class DownloadUtil @Inject constructor(
Expand All @@ -65,35 +66,20 @@ class DownloadUtil @Inject constructor(
throw PlaybackException("Local song are non-downloadable", null, PlaybackException.ERROR_CODE_UNSPECIFIED)
}

songUrlCache[mediaId]?.takeIf { it.second < System.currentTimeMillis() }?.let {
songUrlCache[mediaId]?.takeIf { it.second > System.currentTimeMillis() }?.let {
return@Factory dataSpec.withUri(it.first.toUri())
}

val playedFormat = runBlocking(Dispatchers.IO) { database.format(mediaId).first() }
val playerResponse = runBlocking(Dispatchers.IO) {
YouTube.player(mediaId, registerPlayback = false)
val playbackData = runBlocking(Dispatchers.IO) {
YTPlayerUtils.playerResponseForPlayback(
mediaId,
playedFormat = playedFormat,
audioQuality = audioQuality,
connectivityManager = connectivityManager,
)
}.getOrThrow()
if (playerResponse.playabilityStatus.status != "OK") {
throw PlaybackException(playerResponse.playabilityStatus.reason, null, PlaybackException.ERROR_CODE_REMOTE_ERROR)
}

val format =
if (playedFormat != null) {
playerResponse.streamingData?.adaptiveFormats?.find { it.itag == playedFormat.itag }
} else {
playerResponse.streamingData?.adaptiveFormats
?.filter { it.isAudio }
?.maxByOrNull {
it.bitrate * when (audioQuality) {
AudioQuality.AUTO -> if (connectivityManager.isActiveNetworkMetered) -1 else 1
AudioQuality.HIGH -> 1
AudioQuality.LOW -> -1
} + (if (it.mimeType.startsWith("audio/webm")) 10240 else 0) // prefer opus stream
}
}!!.let {
// Specify range to avoid YouTube's throttling
it.copy(url = "${it.url}&range=0-${it.contentLength ?: 10000000}")
}
val format = playbackData.format

database.query {
upsert(
Expand All @@ -105,14 +91,19 @@ class DownloadUtil @Inject constructor(
bitrate = format.bitrate,
sampleRate = format.audioSampleRate,
contentLength = format.contentLength!!,
loudnessDb = playerResponse.playerConfig?.audioConfig?.loudnessDb,
playbackUrl = playerResponse.playbackTracking?.videostatsPlaybackUrl?.baseUrl
loudnessDb = playbackData.audioConfig?.loudnessDb,
playbackUrl = playbackData.playbackTracking?.videostatsPlaybackUrl?.baseUrl
)
)
}

songUrlCache[mediaId] = format.url!! to playerResponse.streamingData!!.expiresInSeconds * 1000L
dataSpec.withUri(format.url!!.toUri())
val streamUrl = playbackData.streamUrl.let {
// Specify range to avoid YouTube's throttling
"${it}&range=0-${format.contentLength ?: 10000000}"
}

songUrlCache[mediaId] = streamUrl to System.currentTimeMillis() + (playbackData.streamExpiresInSeconds * 1000L)
dataSpec.withUri(streamUrl.toUri())
}
val downloadNotificationHelper = DownloadNotificationHelper(context, ExoDownloadService.CHANNEL_ID)
val downloadManager: DownloadManager = DownloadManager(context, databaseProvider, downloadCache, dataSourceFactory, Executor(Runnable::run)).apply {
Expand Down
73 changes: 28 additions & 45 deletions app/src/main/java/com/dd3boh/outertune/playback/MusicService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ import com.dd3boh.outertune.playback.queues.ListQueue
import com.dd3boh.outertune.playback.queues.Queue
import com.dd3boh.outertune.playback.queues.YouTubeQueue
import com.dd3boh.outertune.utils.CoilBitmapLoader
import com.dd3boh.outertune.utils.YTPlayerUtils
import com.dd3boh.outertune.utils.dataStore
import com.dd3boh.outertune.utils.enumPreference
import com.dd3boh.outertune.utils.get
Expand All @@ -101,7 +102,6 @@ import com.google.common.util.concurrent.MoreExecutors
import com.zionhuang.innertube.YouTube
import com.zionhuang.innertube.models.SongItem
import com.zionhuang.innertube.models.WatchEndpoint
import com.zionhuang.innertube.models.response.PlayerResponse
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
Expand Down Expand Up @@ -447,22 +447,16 @@ class MusicService : MediaLibraryService(),
)
}

private suspend fun recoverSong(mediaId: String, playerResponse: PlayerResponse? = null) {
var playbackUrl = database.format(mediaId).first()?.playbackUrl

if (playbackUrl == null) {
playbackUrl = if (playerResponse?.playbackTracking?.videostatsPlaybackUrl?.baseUrl == null)
YouTube.player(mediaId, registerPlayback = false).getOrNull()?.playbackTracking
?.videostatsPlaybackUrl?.baseUrl!!
else
playerResponse.playbackTracking?.videostatsPlaybackUrl?.baseUrl
}
private suspend fun recoverSong(mediaId: String, playbackData: YTPlayerUtils.PlaybackData? = null) {
val playbackUrl = database.format(mediaId).first()?.playbackUrl
?: playbackData?.playbackTracking?.videostatsPlaybackUrl?.baseUrl
?: YTPlayerUtils.playerResponseForMetadata(mediaId).getOrNull()?.playbackTracking?.videostatsPlaybackUrl?.baseUrl

playbackUrl?.let {
try { YouTube.registerPlayback(queuePlaylistId, playbackUrl) }
catch (exception: UnknownHostException) {
reportException(exception)
}
YouTube.registerPlayback(queuePlaylistId, playbackUrl)
.onFailure {
reportException(it)
}
}

val song = database.song(mediaId).first()
Expand All @@ -471,7 +465,7 @@ class MusicService : MediaLibraryService(),
} ?: return
val duration = song?.song?.duration?.takeIf { it != -1 }
?: mediaMetadata.duration.takeIf { it != -1 }
?: (playerResponse ?: YouTube.player(mediaId, registerPlayback = false).getOrNull())?.videoDetails?.lengthSeconds?.toInt()
?: (playbackData?.videoDetails ?: YTPlayerUtils.playerResponseForMetadata(mediaId).getOrNull()?.videoDetails)?.lengthSeconds?.toInt()
?: -1
database.query {
if (song == null) insert(mediaMetadata.copy(duration = duration))
Expand Down Expand Up @@ -682,18 +676,25 @@ class MusicService : MediaLibraryService(),
return@Factory dataSpec
}

songUrlCache[mediaId]?.takeIf { it.second < System.currentTimeMillis() }?.let {
songUrlCache[mediaId]?.takeIf { it.second > System.currentTimeMillis() }?.let {
scope.launch(Dispatchers.IO) { recoverSong(mediaId) }
return@Factory dataSpec.withUri(it.first.toUri())
}

// Check whether format exists so that users from older version can view format details
// There may be inconsistent between the downloaded file and the displayed info if user change audio quality frequently
val playedFormat = runBlocking(Dispatchers.IO) { database.format(mediaId).first() }
val playerResponse = runBlocking(Dispatchers.IO) {
YouTube.player(mediaId, registerPlayback = false)
val playbackData = runBlocking(Dispatchers.IO) {
YTPlayerUtils.playerResponseForPlayback(
mediaId,
playedFormat = playedFormat,
audioQuality = audioQuality,
connectivityManager = connectivityManager,
)
}.getOrElse { throwable ->
when (throwable) {
is PlaybackException -> throw throwable

is ConnectException, is UnknownHostException -> {
throw PlaybackException(getString(R.string.error_no_internet), throwable, PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED)
}
Expand All @@ -705,27 +706,7 @@ class MusicService : MediaLibraryService(),
else -> throw PlaybackException(getString(R.string.error_unknown), throwable, PlaybackException.ERROR_CODE_REMOTE_ERROR)
}
}
if (playerResponse.playabilityStatus.status != "OK") {
throw PlaybackException(playerResponse.playabilityStatus.reason, null, PlaybackException.ERROR_CODE_REMOTE_ERROR)
}

val format =
if (playedFormat != null) {
playerResponse.streamingData?.adaptiveFormats?.find {
// Use itag to identify previously played format
it.itag == playedFormat.itag
}
} else {
playerResponse.streamingData?.adaptiveFormats
?.filter { it.isAudio }
?.maxByOrNull {
it.bitrate * when (audioQuality) {
AudioQuality.AUTO -> if (connectivityManager.isActiveNetworkMetered) -1 else 1
AudioQuality.HIGH -> 1
AudioQuality.LOW -> -1
} + (if (it.mimeType.startsWith("audio/webm")) 10240 else 0) // prefer opus stream
}
} ?: throw PlaybackException(getString(R.string.error_no_stream), null, ERROR_CODE_NO_STREAM)
val format = playbackData.format

database.query {
upsert(
Expand All @@ -737,15 +718,17 @@ class MusicService : MediaLibraryService(),
bitrate = format.bitrate,
sampleRate = format.audioSampleRate,
contentLength = format.contentLength!!,
loudnessDb = playerResponse.playerConfig?.audioConfig?.loudnessDb,
playbackUrl = playerResponse.playbackTracking?.videostatsPlaybackUrl?.baseUrl!!
loudnessDb = playbackData.audioConfig?.loudnessDb,
playbackUrl = playbackData.playbackTracking?.videostatsPlaybackUrl?.baseUrl
)
)
}
scope.launch(Dispatchers.IO) { recoverSong(mediaId, playerResponse) }
scope.launch(Dispatchers.IO) { recoverSong(mediaId, playbackData) }

val streamUrl = playbackData.streamUrl

songUrlCache[mediaId] = format.url!! to playerResponse.streamingData!!.expiresInSeconds * 1000L
dataSpec.withUri(format.url!!.toUri()).subrange(dataSpec.uriPositionOffset, CHUNK_LENGTH)
songUrlCache[mediaId] = streamUrl to System.currentTimeMillis() + (playbackData.streamExpiresInSeconds * 1000L)
dataSpec.withUri(streamUrl.toUri()).subrange(dataSpec.uriPositionOffset, CHUNK_LENGTH)
}
}

Expand Down
Loading
Loading