Modern Apps git

← Modern-Apps.git

youpipe: #92 SABR flip - extractor emits sabrng + ViewModel/PlaybackService/downloads on sabrng bridge (old bridge dormant)

Commit
b262d922e34fb5b3eb191397b18487d188b685e8
Author
vayun-mathur <[email protected]>
When
2026-08-16 18:11 UTC (3 months ago)
Parents
3f66a52

Diff

youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.kt
diff --git a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.kt b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.ktindex eee6dd6891..128398da58 100644--- a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.kt+++ b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.kt@@ -48,9 +48,8 @@ import org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.getTex import org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.prepareDesktopJsonBuilder import org.schabi.newpipe.extractor.services.youtube.YoutubeStreamHelper import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeChannelLinkHandlerFactory-import org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrClientProfile-import org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrFormat-import org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrProbe+import org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrInfo+import org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrNgInfoBuilder import org.schabi.newpipe.extractor.stream.AudioStream import org.schabi.newpipe.extractor.stream.DeliveryMethod import org.schabi.newpipe.extractor.stream.Description@@ -269,35 +268,6 @@ class YoutubeStreamExtractor(                 throw ParsingException("Could not parse \"$accessibilityText\" as a long", e)             }         }--        @Throws(ParsingException::class)-        private fun buildSabrItagItem(format: YoutubeSabrFormat): ItagItem? {-            val mimeType = format.mimeType ?: ""-            val codec = if (mimeType.contains("codecs")) {-                // mimeType like video/mp4; codecs="avc1..."-                val parts = mimeType.split("\"")-                if (parts.size > 1) parts[1] else ""-            } else ""-            val webm = mimeType.contains("webm")-            val itagItem: ItagItem = if (format.isAudio) {-                val mediaFormat = if (webm) {-                    if (codec.contains("opus")) MediaFormat.WEBMA_OPUS else MediaFormat.WEBMA-                } else MediaFormat.M4A-                ItagItem(format.itag, ItagItem.ItagType.AUDIO, mediaFormat, kotlin.math.max(format.bitrate, 0))-            } else {-                val mediaFormat = if (webm) MediaFormat.WEBM else MediaFormat.MPEG_4-                val resolution = if (format.height > 0) "${format.height}p" else ""-                val item = ItagItem(format.itag, ItagItem.ItagType.VIDEO_ONLY, mediaFormat, resolution)-                item.width = format.width-                item.height = format.height-                item-            }-            itagItem.bitrate = format.bitrate-            itagItem.codec = codec-            itagItem.contentLength = format.contentLength-            itagItem.approxDurationMs = format.approxDurationMs-            return itagItem-        }     }      private var playerResponse: JsonObject? = null@@ -1026,10 +996,9 @@ class YoutubeStreamExtractor(         } catch (e: Exception) {             return         }-        val sabrInfo: org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrInfo = try {-            YoutubeSabrProbe.fetchSabrInfo(+        val sabrInfo: YoutubeSabrInfo = try {+            YoutubeSabrNgInfoBuilder.fetchSabrInfo(                 videoId,-                YoutubeSabrClientProfile.WEB,                 getExtractorLocalization(),                 getExtractorContentCountry()             )@@ -1037,53 +1006,30 @@ class YoutubeStreamExtractor(             ExtractorLogger.d("YoutubeSabr", "SABR fetch failed for {}: {}", videoId, e)             return         }-        if (sabrInfo.getFormats().isEmpty() && sabrInfo.serverAbrStreamingUrl.isNullOrEmpty()) {-            // still check formats via getFormats for compatibility-        }-        // Use getter for java compatibility + kotlin property both exist-        val formats = try {-            sabrInfo.getFormats()-        } catch (e: Exception) {-            // fallback to property via reflection not needed; try formats list directly via internal?-            emptyList<YoutubeSabrFormat>()-        }-        // Also try direct access if getFormats empty: use YoutubeSabrInfo's internal formats? But we also have property via earlier version?-        // We'll just use formats above; if empty and actual list available via extension, keep empty logic.--        val actualFormats = if (formats.isNotEmpty()) formats else {-            // Try to get via property if kotlin class exposes getFormats-            try {-                // SabrInfo was just converted, it has getFormats()-                sabrInfo.getFormats()-            } catch (_: Exception) {-                emptyList()-            }-        }-+        val actualFormats = sabrInfo.getFormats()         if (actualFormats.isEmpty()) {             ExtractorLogger.d("YoutubeSabr", "SABR fetch returned no info/formats for {}", videoId)-            // still continue to allow serverAbrStreamingUrl check         }-        val serverAbrStreamingUrl = sabrInfo.serverAbrStreamingUrl ?: ""+        val serverAbrStreamingUrl = sabrInfo.getServerAbrStreamingUrl() ?: ""         var av1Count = 0         for (format in actualFormats) {             try {-                val itagItem = buildSabrItagItem(format) ?: continue-                val idStr = format.itag.toString()+                val itagItem = format.toItagItem()+                val idStr = format.getItag().toString() -                if (format.isAudio) {+                if (format.isAudio()) {                     val builder = AudioStream.Builder()                         .setContent(serverAbrStreamingUrl, false)                         .setMediaFormat(itagItem.mediaFormat)-                        .setAverageBitrate(format.bitrate)+                        .setAverageBitrate(format.getBitrate())                         .setItagItem(itagItem)                         .setDeliveryMethod(DeliveryMethod.SABR)                         .setDeliveryMethodInfo(sabrInfo)                     var streamId = idStr-                    val trackId = format.audioTrackId+                    val trackId = format.getAudioTrackId()                     if (!trackId.isNullOrEmpty()) {                         val langPart = trackId.split(".")[0]-                        val displayName = format.audioTrackDisplayName+                        val displayName = format.getAudioTrackDisplayName()                         builder.setAudioTrackId(trackId)                             .setAudioTrackName(displayName ?: langPart)                             .setAudioLocale(Locale(langPart.split("-")[0]))@@ -1094,14 +1040,12 @@ class YoutubeStreamExtractor(                     if (sabrAudioStreams.none { audioStreamId == it.getId() }) {                         sabrAudioStreams.add(stream)                     }-                } else if (format.isVideo) {+                } else if (format.isVideo()) {                     val codec = itagItem.codec                     if (codec != null && codec.contains("av01")) {                         av1Count++                     }-                    val qualityLabel = format.qualityLabel-                    val resolution = if (!qualityLabel.isNullOrEmpty()) qualityLabel-                    else if (format.height > 0) "${format.height}p" else ""+                    val resolution = if (format.getHeight() > 0) "${format.getHeight()}p" else ""                     val stream = VideoStream.Builder()                         .setId(idStr)                         .setContent(serverAbrStreamingUrl, false)
youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.ktindex d4f3a1e1d3..79cb678e3a 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.kt@@ -12,13 +12,13 @@ import androidx.work.WorkerParameters import com.vayunmathur.youpipe.data.DownloadedVideo import com.vayunmathur.youpipe.data.SubscriptionRepository import com.vayunmathur.youpipe.ui.VideoInfo-import com.vayunmathur.youpipe.util.sabr.SabrDownloadHelper+import com.vayunmathur.youpipe.util.sabr.SabrNgDownloadHelper import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.NetworkDataStream import org.schabi.newpipe.extractor.ServiceList import org.schabi.newpipe.extractor.stream.DeliveryMethod import org.schabi.newpipe.extractor.stream.Stream-import org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrInfo+import org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrInfo import java.io.BufferedOutputStream import java.io.File import java.io.RandomAccessFile@@ -170,11 +170,12 @@ class DownloadWorker(context: Context, params: WorkerParameters) :                 }?.getDeliveryMethodInfo() as? YoutubeSabrInfo                     ?: throw IllegalStateException("No SABR info available for $youtubeId") -                SabrDownloadHelper.download(+                SabrNgDownloadHelper.download(                     context = applicationContext,                     videoId = youtubeId,                     videoItag = videoItag,                     audioItag = audioItag,+                    audioTrackId = null,                     info = info,                     workDir = workDir,                     outputFile = outputFile,
youpipe/src/main/java/com/vayunmathur/youpipe/util/PlaybackService.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/PlaybackService.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/PlaybackService.ktindex 74bbc87d29..b8c611841a 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/PlaybackService.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/PlaybackService.kt@@ -20,8 +20,11 @@ import androidx.media3.session.MediaSession import androidx.media3.session.MediaSessionService import com.google.common.util.concurrent.Futures import com.google.common.util.concurrent.ListenableFuture-import com.vayunmathur.youpipe.util.sabr.SabrDashMediaSource-import com.vayunmathur.youpipe.util.sabr.SabrSessionStore+import com.vayunmathur.youpipe.util.sabr.LocalDomPoTokenProvider+import com.vayunmathur.youpipe.util.sabr.SabrNgDashMediaSource+import com.vayunmathur.youpipe.util.sabr.SabrNgSessionStore+import org.schabi.newpipe.extractor.localization.Localization+import org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrInfo import org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.isAndroidStreamingUrl import org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.isIosStreamingUrl import org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.isVisionOsStreamingUrl@@ -104,12 +107,27 @@ class PlaybackService : MediaSessionService() {                             }                         } catch (_: Exception) {}                     }-                    val info = SabrSessionStore.getExtractorInfo(videoId)+                    val info = SabrNgSessionStore.getExtractorInfo(videoId)+                        ?: throw RuntimeException("No SABR info available for $videoId")                     val sabrSource = try {-                        val spec = SabrSessionStore.createSourceSpec(-                            videoId, vitag, audioItag, audioTrackIdOverride, info+                        val poToken = LocalDomPoTokenProvider.shared(applicationContext)+                            .getPoTokenBytes(videoId, info.getVisitorData())+                        val spec = SabrNgSessionStore.createSourceSpec(+                            videoId, vitag, audioItag, audioTrackIdOverride, info, poToken,+                            Localization("en", "US")+                        )+                        val onAttestationFailure: () -> YoutubeSabrInfo? = {+                            val fresh = LocalDomPoTokenProvider.shared(applicationContext)+                                .getPoTokenBytes(videoId, info.getVisitorData(), true)+                            YoutubeSabrInfo(+                                info.getVideoId(), info.getCpn(), info.getClientVersion(),+                                info.getVisitorData(), info.getServerAbrStreamingUrl(),+                                info.getVideoPlaybackUstreamerConfig(), info.getFormats(), fresh+                            )+                        }+                        SabrNgDashMediaSource(+                            this@PlaybackService, mediaItem, spec, onAttestationFailure                         )-                        SabrDashMediaSource(this@PlaybackService, mediaItem, spec)                     } catch (e: Exception) {                         throw RuntimeException("Failed to create SABR media source for $videoId", e)                     }
youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeViewModel.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeViewModel.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeViewModel.ktindex 438ee01bd9..e67b60e033 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeViewModel.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/YouPipeViewModel.kt@@ -775,11 +775,11 @@ class YouPipeViewModel(                         if (sabrVideoOnly.isNotEmpty()) {                             sabrVideoOnly.firstOrNull {                                 it.getDeliveryMethodInfo() is-                                    org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrInfo+                                    org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrInfo                             }?.let {                                 val sabrInfo = it.getDeliveryMethodInfo() as-                                    org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrInfo-                                com.vayunmathur.youpipe.util.sabr.SabrSessionStore.putExtractorInfo(+                                    org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrInfo+                                com.vayunmathur.youpipe.util.sabr.SabrNgSessionStore.putExtractorInfo(                                     videoId, sabrInfo                                 )                             }
youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrNgDownloadHelper.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrNgDownloadHelper.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrNgDownloadHelper.ktnew file mode 100644index 0000000000..c812f970f8--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/sabr/SabrNgDownloadHelper.kt@@ -0,0 +1,98 @@+package com.vayunmathur.youpipe.util.sabr++import android.content.Context+import android.util.Log+import org.schabi.newpipe.extractor.localization.Localization+import org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrFormatTimeline+import org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrInfo+import java.io.File+import java.io.FileOutputStream+import java.io.IOException++/**+ * Session-based ([SabrNgSession]) SABR downloader: drives `requestOnce` to fetch the selected+ * audio+video formats to two temporary files (init segment followed by all media segments) and+ * muxes them into a single mp4 via [SabrFfmpegMuxer]. Replaces the old `SabrDownloadHelper`, which+ * drove the legacy SABR session API.+ */+internal object SabrNgDownloadHelper {+    private const val TAG = "SabrNgDownloadHelper"+    private const val SEGMENT_TIMEOUT_MS = 30_000L+    private val DOWNLOAD_LOCALIZATION = Localization("en", "US")++    @Throws(IOException::class)+    fun download(+        context: Context,+        videoId: String,+        videoItag: Int,+        audioItag: Int,+        audioTrackId: String?,+        info: YoutubeSabrInfo,+        workDir: File,+        outputFile: File,+        onProgress: (Double) -> Unit,+    ) {+        if (!workDir.exists() && !workDir.mkdirs()) {+            throw IOException("Could not create SABR download directory: $workDir")+        }+        val poToken = LocalDomPoTokenProvider.shared(context.applicationContext)+            .getPoTokenBytes(videoId, info.getVisitorData())+        val spec = SabrNgSessionStore.createSourceSpec(+            videoId, videoItag, audioItag, audioTrackId, info, poToken, DOWNLOAD_LOCALIZATION+        )+        val audioFile = File(workDir, "sabr-audio-$videoId-${spec.audioFormat.getItag()}.media")+        val videoFile = File(workDir, "sabr-video-$videoId-${spec.videoFormat.getItag()}.media")+        val spoolDir = File(workDir, "spool").apply { mkdirs() }+        val session = SabrNgSession(spec, spoolDir, onAttestationFailure = null)++        val totalSegments =+            (spec.audioTimeline.getEndSequence() + spec.videoTimeline.getEndSequence())+                .coerceAtLeast(1)+        var written = 0+        val progress = { onProgress((written.toDouble() / totalSegments).coerceIn(0.0, 1.0)) }+        try {+            session.start()+            writeTrack(session, spec.audioFormat.getItag(), spec.audioTimeline, audioFile) {+                written+++                progress()+            }+            writeTrack(session, spec.videoFormat.getItag(), spec.videoTimeline, videoFile) {+                written+++                progress()+            }+            SabrFfmpegMuxer.mux(videoFile, audioFile, outputFile)+            onProgress(1.0)+        } catch (e: Exception) {+            Log.e(TAG, "SABR download failed for $videoId", e)+            if (outputFile.exists()) {+                outputFile.delete()+            }+            if (e is IOException) throw e+            throw IOException("SABR download failed: ${e.message ?: e.javaClass.simpleName}", e)+        } finally {+            session.stop()+            audioFile.delete()+            videoFile.delete()+            spoolDir.deleteRecursively()+        }+    }++    @Throws(IOException::class)+    private fun writeTrack(+        session: SabrNgSession,+        itag: Int,+        timeline: YoutubeSabrFormatTimeline,+        file: File,+        onSegment: () -> Unit,+    ) {+        FileOutputStream(file).use { out ->+            session.getInitialization(itag)?.let { out.write(it) }+            for (sequence in 1..timeline.getEndSequence()) {+                val segment = session.getMediaSegment(itag, sequence, SEGMENT_TIMEOUT_MS)+                    ?: throw IOException("Missing SABR segment itag=$itag seq=$sequence")+                segment.openStream().use { it.copyTo(out) }+                onSegment()+            }+        }+    }+}