Modern Apps git

← Modern-Apps.git

youpipe: port PipePipe #92 SABR rewrite (session driver, request helper, diagnostics)

Commit
5b1394ffe29d57f95d3c9531625d2499984ef684
Author
vayun-mathur <[email protected]>
When
2026-08-16 17:27 UTC (3 months ago)
Parents
b1117f2

Diff

youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrRequestHelper.kt
diff --git a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrRequestHelper.kt b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrRequestHelper.ktnew file mode 100644index 0000000000..af8218943a--- /dev/null+++ b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrRequestHelper.kt@@ -0,0 +1,470 @@+package org.schabi.newpipe.extractor.services.youtube.sabrng++import org.schabi.newpipe.extractor.NewPipe+import org.schabi.newpipe.extractor.downloader.StreamingResponse+import org.schabi.newpipe.extractor.exceptions.ExtractionException+import org.schabi.newpipe.extractor.localization.Localization+import org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrProtocolException+import org.schabi.newpipe.extractor.services.youtube.sabrng.protocol.SabrProto+import org.schabi.newpipe.extractor.services.youtube.sabrng.protocol.SabrStreamingResponseReader+import java.io.File+import java.io.FilterInputStream+import java.io.IOException+import java.io.InputStream+import java.util.Base64+import java.util.concurrent.TimeUnit++/** Builds and sends session-based SABR requests and decodes their UMP responses. */+object YoutubeSabrRequestHelper {+    private const val MWEB_CLIENT_ID = 2+    private const val MAX_INITIALIZATION_BYTES = 4 * 1024 * 1024+    private const val MWEB_USER_AGENT =+        "Mozilla/5.0 (iPad; CPU OS 16_7_10 like Mac OS X) AppleWebKit/605.1.15 " ++            "(KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1,gzip(gfe)"+    val MWEB_LOCALIZATION = Localization("en", "US")++    @JvmStatic+    @Throws(IOException::class)+    fun fetchInitializationData(+        format: YoutubeSabrInfo.Format,+        poToken: ByteArray,+        timeoutMs: Long+    ): ByteArray {+        val initializationUrl = format.getInitializationUrl()+        val start = format.getInitRangeStart()+        val end = format.getInitRangeEnd()+        if (initializationUrl.isNullOrEmpty() || start < 0 || end < start ||+            end - start >= MAX_INITIALIZATION_BYTES+        ) {+            throw IOException(+                "Invalid SABR initialization range: itag=" + format.getItag() ++                    ", start=" + start + ", end=" + end+            )+        }+        if (poToken.isEmpty()) {+            throw IOException(+                "Missing PO token for SABR initialization range: itag=" + format.getItag()+            )+        }+        val url = appendQueryParameterIfMissing(+            initializationUrl, "pot",+            Base64.getUrlEncoder().withoutPadding().encodeToString(poToken)+        )+        val length = (end - start + 1).toInt()+        val headers: Map<String, List<String>> = mapOf("Range" to listOf("bytes=$start-$end"))+        try {+            val response = if (timeoutMs > 0) {+                NewPipe.getDownloader().getStreaming(url, headers, MWEB_LOCALIZATION, timeoutMs)+            } else {+                NewPipe.getDownloader().getStreaming(url, headers, MWEB_LOCALIZATION)+            }+            response.use {+                if (it.responseCode() != 206 && !(it.responseCode() == 200 && start == 0L)) {+                    throw IOException(+                        "SABR initialization range failed: itag=" + format.getItag() ++                            ", status=" + it.responseCode()+                    )+                }+                return readExactly(it.body(), length)+            }+        } catch (error: ExtractionException) {+            throw IOException("SABR initialization range failed: itag=" + format.getItag(), error)+        }+    }++    @Throws(IOException::class, ExtractionException::class)+    internal fun post(+        info: YoutubeSabrInfo,+        request: YoutubeSabrRequest,+        session: YoutubeSabrSession,+        serverAbrStreamingUrl: String,+        requestNumber: Int,+        segmentConsumer: SabrStreamingResponseReader.SegmentConsumer?,+        segmentStartConsumer: SabrStreamingResponseReader.SegmentConsumer?,+        segmentSpoolDirectory: File?+    ): YoutubeSabrResponse {+        val requestBody = buildMediaRequest(info, request, session, requestNumber > 0)+        val requestStartNs = System.nanoTime()+        var firstSegmentElapsedMs = -1L+        val timedConsumer: SabrStreamingResponseReader.SegmentConsumer? =+            if (segmentConsumer == null) {+                null+            } else {+                SabrStreamingResponseReader.SegmentConsumer { segment ->+                    if (firstSegmentElapsedMs < 0) {+                        firstSegmentElapsedMs = elapsedMs(requestStartNs)+                    }+                    segmentConsumer.accept(segment)+                }+            }+        val timedStartConsumer: SabrStreamingResponseReader.SegmentConsumer? =+            if (segmentStartConsumer == null) {+                null+            } else {+                SabrStreamingResponseReader.SegmentConsumer { segment ->+                    if (firstSegmentElapsedMs < 0) {+                        firstSegmentElapsedMs = elapsedMs(requestStartNs)+                    }+                    segmentStartConsumer.accept(segment)+                }+            }+        NewPipe.getDownloader().postStreaming(+            withSessionParameters(serverAbrStreamingUrl, info.getCpn(), requestNumber),+            buildRequestHeaders(), requestBody, MWEB_LOCALIZATION+        ).use { response ->+            val contentType = response.getHeader("Content-Type")+            if (contentType == null ||+                !contentType.lowercase().contains("application/vnd.yt-ump")+            ) {+                throw SabrProtocolException(+                    "Expected UMP response, got content type: " + contentType ++                        ", status=" + response.responseCode()+                )+            }+            val body = CountingInputStream(response.body())+            val streamed = SabrStreamingResponseReader.read(+                body, timedConsumer, timedStartConsumer, segmentSpoolDirectory+            )+            val result = streamed.getProbeResult()+            result.complete(+                info, streamed.getSegments(), streamed.getSegmentCount(),+                response.responseCode(), contentType, body.getCount(),+                streamed.getMediaPayloadBytes(), streamed.getMediaPartPayloadBytes(),+                streamed.getControlPayloadBytes(), streamed.getTotalPayloadBytes(),+                streamed.getMaxPartBytes(), streamed.getMaxMediaPartPayloadBytes(),+                streamed.getMaxSegmentBytes(), elapsedMs(requestStartNs), firstSegmentElapsedMs+            )+            return result+        }+    }++    @Throws(SabrProtocolException::class)+    private fun buildMediaRequest(+        info: YoutubeSabrInfo,+        sabrRequest: YoutubeSabrRequest,+        session: YoutubeSabrSession,+        followUp: Boolean+    ): ByteArray {+        val ustreamerConfig = info.getVideoPlaybackUstreamerConfig()+        if (ustreamerConfig.isNullOrEmpty()) {+            throw SabrProtocolException("Missing video playback ustreamer config")+        }+        val playbackState = sabrRequest.getPlaybackState()+        val audioTrack = sabrRequest.getAudioTrack()+        val videoTrack = sabrRequest.getVideoTrack()+        val audioFormat = audioTrack?.getFormat()+        val videoFormat = videoTrack?.getFormat()+        val playerTimeMs = playbackState.getPlayerTimeMs()+        val playbackRate = playbackState.getPlaybackRate()+        val bufferedRanges = ArrayList<ByteArray>()+        if (sabrRequest.hasSelectedTracks()) {+            for (track in sabrRequest.getTracks()) {+                addBufferedRange(bufferedRanges, track)+            }+        }+        val includePlaybackState = followUp || playerTimeMs > 0 || bufferedRanges.isNotEmpty()+        val includeSelectedTracks = includePlaybackState && sabrRequest.hasSelectedTracks()+        val trackMode = if (audioTrack != null && videoTrack == null) {+            1+        } else if (videoTrack != null && audioTrack == null) {+            2+        } else {+            0+        }+        val request = SabrProto.Writer()+        request.writeMessage(+            1,+            buildClientAbrState(+                audioFormat, videoFormat, playerTimeMs, followUp || includePlaybackState,+                trackMode, session.getBandwidthEstimate(), playbackRate+            )+        )+        if (includePlaybackState) {+            if (includeSelectedTracks) {+                for (track in sabrRequest.getTracks()) {+                    request.writeMessage(2, SabrProto.formatId(track.getFormat()))+                }+            }+            for (range in bufferedRanges) {+                request.writeMessage(3, range)+            }+            request.writeUInt64(4, playerTimeMs)+        }+        request.writeBytes(5, decodeBase64(ustreamerConfig))+        writePreferredFormats(request, audioFormat, videoFormat)+        request.writeMessage(19, buildStreamerContext(info, session))+        return request.toByteArray()+    }++    private fun buildClientAbrState(+        audioFormat: YoutubeSabrInfo.Format?,+        videoFormat: YoutubeSabrInfo.Format?,+        playerTimeMs: Long,+        includeFollowUpState: Boolean,+        enabledTrackTypesBitfield: Int,+        requestedBandwidthEstimate: Long,+        playbackRate: Float+    ): ByteArray {+        val state = SabrProto.Writer()+        if (includeFollowUpState && videoFormat != null) {+            state.writeInt32(18, Math.max(videoFormat.getWidth(), 640))+            state.writeInt32(19, Math.max(videoFormat.getHeight(), 360))+        }+        if (videoFormat != null) {+            state.writeInt32(21, Math.max(videoFormat.getHeight(), 360))+        }+        if (includeFollowUpState) {+            val bandwidthEstimate = if (requestedBandwidthEstimate > 0) {+                requestedBandwidthEstimate+            } else {+                activeBitrateEstimate(audioFormat, videoFormat)+            }+            if (bandwidthEstimate > 0) {+                state.writeUInt64(23, bandwidthEstimate)+            }+        }+        state.writeInt32(34, 1)+        state.writeFloat(35, if (playbackRate > 0) playbackRate else 1.0f)+        if (enabledTrackTypesBitfield != 0) {+            state.writeInt32(40, enabledTrackTypesBitfield)+        }+        if (audioFormat != null && audioFormat.isDrc()) {+            state.writeBool(46, true)+        }+        state.writeUInt64(28, playerTimeMs)+        if (audioFormat != null) {+            state.writeStringIfNotEmpty(69, audioFormat.getAudioTrackId())+        }+        return state.toByteArray()+    }++    private fun activeBitrateEstimate(+        audioFormat: YoutubeSabrInfo.Format?,+        videoFormat: YoutubeSabrInfo.Format?+    ): Long {+        var bitrate = 0L+        if (audioFormat != null) {+            if (audioFormat.getBitrate() <= 0) return -1+            bitrate += audioFormat.getBitrate()+        }+        if (videoFormat != null) {+            if (videoFormat.getBitrate() <= 0) return -1+            bitrate += videoFormat.getBitrate()+        }+        return if (bitrate > 0) bitrate * 2L else -1+    }++    private fun writePreferredFormats(+        request: SabrProto.Writer,+        audioFormat: YoutubeSabrInfo.Format?,+        videoFormat: YoutubeSabrInfo.Format?+    ) {+        if (audioFormat != null) {+            request.writeMessage(16, SabrProto.formatId(audioFormat))+        }+        if (videoFormat != null) {+            request.writeMessage(17, SabrProto.formatId(videoFormat))+        }+    }++    private fun buildStreamerContext(+        info: YoutubeSabrInfo,+        session: YoutubeSabrSession+    ): ByteArray {+        val context = SabrProto.Writer()+        context.writeMessage(1, buildClientInfo(info))+        val poToken = session.getRawPoToken()+        if (poToken != null && poToken.isNotEmpty()) {+            context.writeBytes(2, poToken)+        }+        val playbackCookie = session.getRawPlaybackCookie()+        if (playbackCookie != null && playbackCookie.isNotEmpty()) {+            context.writeBytes(3, playbackCookie)+        }+        for ((key, value) in session.getActiveSabrContexts()) {+            val sabrContext = SabrProto.Writer()+            sabrContext.writeInt32(1, key)+            sabrContext.writeBytes(2, value)+            context.writeMessage(5, sabrContext.toByteArray())+        }+        for (type in session.getUnsentSabrContextTypes()) {+            context.writeInt32(6, type)+        }+        return context.toByteArray()+    }++    private fun addBufferedRange(ranges: MutableList<ByteArray>, track: YoutubeSabrRequest.Track) {+        val timeline = track.getTimeline()+        val bufferedThrough = track.getBufferedThrough()+        if (timeline == null || bufferedThrough <= 0) {+            return+        }+        val endSequence = Math.min(bufferedThrough, timeline.getEndSequence())+        if (endSequence <= 0) {+            return+        }+        val format = track.getFormat()+        ranges.add(+            buildBufferedRange(+                format.getItag(), format.getLastModified(), format.getXtags(), 0,+                Math.max(0, timeline.getEndMs(endSequence)), 1, endSequence, 1000+            )+        )+    }++    private fun buildClientInfo(info: YoutubeSabrInfo): ByteArray {+        val client = SabrProto.Writer()+        client.writeInt32(16, MWEB_CLIENT_ID)+        client.writeStringIfNotEmpty(17, info.getClientVersion())+        client.writeStringIfNotEmpty(21, "en-US")+        client.writeStringIfNotEmpty(22, "US")+        return client.toByteArray()+    }++    private fun buildBufferedRange(+        itag: Int,+        lastModified: Long,+        xtags: String?,+        startTimeMs: Long,+        durationMs: Long,+        startSegmentIndex: Int,+        endSegmentIndex: Int,+        timescale: Int+    ): ByteArray {+        val format = SabrProto.Writer()+        format.writeInt32(1, itag)+        if (lastModified > 0) {+            format.writeUInt64(2, lastModified)+        }+        format.writeStringIfNotEmpty(3, xtags)++        val timeRange = SabrProto.Writer()+        timeRange.writeUInt64(1, startTimeMs)+        timeRange.writeUInt64(2, durationMs)+        timeRange.writeInt32(3, timescale)++        val range = SabrProto.Writer()+        range.writeMessage(1, format.toByteArray())+        range.writeUInt64(2, startTimeMs)+        range.writeUInt64(3, durationMs)+        range.writeInt32(4, startSegmentIndex)+        range.writeInt32(5, endSegmentIndex)+        range.writeMessage(6, timeRange.toByteArray())+        return range.toByteArray()+    }++    private fun buildRequestHeaders(): Map<String, List<String>> = mapOf(+        "Content-Type" to listOf("application/x-protobuf"),+        "Accept" to listOf("application/vnd.yt-ump"),+        "Accept-Encoding" to listOf("identity"),+        "User-Agent" to listOf(MWEB_USER_AGENT)+    )++    private fun withSessionParameters(url: String, cpn: String, requestNumber: Int): String {+        var result = appendQueryParameterIfMissing(url, "alr", "yes")+        result = appendQueryParameterIfMissing(result, "cpn", cpn)+        return setQueryParameter(result, "rn", requestNumber.toString())+    }++    private fun appendQueryParameterIfMissing(url: String, name: String, value: String): String {+        if (url.matches(Regex(".*(?:[?&])" + name + "=[^&]*.*"))) {+            return url+        }+        return url + (if (url.contains("?")) '&' else '?') + name + '=' + value+    }++    private fun setQueryParameter(url: String, name: String, value: String): String {+        val fragmentIndex = url.indexOf('#')+        val baseUrl = if (fragmentIndex < 0) url else url.substring(0, fragmentIndex)+        val fragment = if (fragmentIndex < 0) "" else url.substring(fragmentIndex)+        val queryIndex = baseUrl.indexOf('?')+        val path = if (queryIndex < 0) baseUrl else baseUrl.substring(0, queryIndex)+        val query = if (queryIndex < 0) "" else baseUrl.substring(queryIndex + 1)+        val result = StringBuilder(path).append('?')+        var wroteParameter = false+        for (parameter in query.split("&")) {+            if (parameter.isEmpty()) {+                continue+            }+            val equalsIndex = parameter.indexOf('=')+            val parameterName = if (equalsIndex < 0) parameter else parameter.substring(0, equalsIndex)+            if (parameterName == name) {+                continue+            }+            if (wroteParameter) {+                result.append('&')+            }+            result.append(parameter)+            wroteParameter = true+        }+        if (wroteParameter) {+            result.append('&')+        }+        return result.append(name).append('=').append(value).append(fragment).toString()+    }++    @Throws(SabrProtocolException::class)+    private fun decodeBase64(value: String): ByteArray {+        return try {+            Base64.getDecoder().decode(padBase64(value))+        } catch (first: IllegalArgumentException) {+            try {+                Base64.getUrlDecoder().decode(padBase64(value))+            } catch (second: IllegalArgumentException) {+                throw SabrProtocolException("Could not decode base64 ustreamer config", second)+            }+        }+    }++    private fun padBase64(value: String): String {+        val padding = (4 - value.length % 4) % 4+        val builder = StringBuilder(value)+        for (i in 0 until padding) {+            builder.append('=')+        }+        return builder.toString()+    }++    private fun elapsedMs(startNs: Long): Long =+        Math.max(0L, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs))++    @Throws(IOException::class)+    private fun readExactly(input: InputStream, length: Int): ByteArray {+        val data = ByteArray(length)+        var offset = 0+        while (offset < length) {+            val read = input.read(data, offset, length - offset)+            if (read < 0) {+                throw IOException(+                    "Truncated SABR initialization range: expected=$length, actual=$offset"+                )+            }+            offset += read+        }+        return data+    }++    private class CountingInputStream(input: InputStream) : FilterInputStream(input) {+        private var count: Long = 0++        @Throws(IOException::class)+        override fun read(): Int {+            val value = super.read()+            if (value >= 0) {+                count+++            }+            return value+        }++        @Throws(IOException::class)+        override fun read(buffer: ByteArray, offset: Int, length: Int): Int {+            val read = super.read(buffer, offset, length)+            if (read > 0) {+                count += read+            }+            return read+        }++        fun getCount(): Long = count+    }+}
youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSession.kt
diff --git a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSession.kt b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSession.ktnew file mode 100644index 0000000000..da787d9db5--- /dev/null+++ b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSession.kt@@ -0,0 +1,521 @@+package org.schabi.newpipe.extractor.services.youtube.sabrng++import org.schabi.newpipe.extractor.exceptions.ExtractionException+import org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrAttestationException+import org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrProtocolException+import org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrRecoverableException+import org.schabi.newpipe.extractor.services.youtube.sabrng.media.SabrMediaSegment+import org.schabi.newpipe.extractor.services.youtube.sabrng.protocol.SabrProto+import org.schabi.newpipe.extractor.services.youtube.sabrng.protocol.SabrStreamingResponseReader+import java.io.File+import java.io.IOException+import java.net.URI+import java.util.Collections++/**+ * Drives the session-based SABR protocol: builds requests, sends them via+ * [YoutubeSabrRequestHelper], ingests control/attestation/protection state, handles redirects,+ * backoff and bounded recovery, and forwards media segments to a consumer.+ */+class YoutubeSabrSession @JvmOverloads constructor(+    private val info: YoutubeSabrInfo,+    private val segmentSpoolDirectory: File? = null+) {+    private var serverAbrStreamingUrl: String+    private var requestNumber = 0+    private var redirectCount = 0+    private var consecutiveIntegrityFailures = 0+    private var consecutiveAttestationPendingResponses = 0+    private var playbackCookie: ByteArray? = null+    private val sabrContexts = LinkedHashMap<Int, ByteArray>()+    private val activeSabrContextTypes = LinkedHashSet<Int>()+    private var live = false+    private var postLiveDvr = false+    private var liveHeadSequenceNumber: Long = -1+    private var liveHeadTimeMs: Long = -1+    private var bandwidthEstimate: Long = -1++    @Volatile+    private var backoffDeadlineNs: Long = 0+    private var poToken: ByteArray? = null++    private val diagnostics = YoutubeSabrSessionDiagnostics()++    init {+        val url = info.getServerAbrStreamingUrl()+        require(!url.isNullOrEmpty()) { "Missing SABR streaming URL" }+        serverAbrStreamingUrl = url+    }++    @Throws(IOException::class, ExtractionException::class)+    private fun fetchNextResponse(+        request: YoutubeSabrRequest,+        segmentConsumer: SabrStreamingResponseReader.SegmentConsumer?+    ): YoutubeSabrResponse {+        val playbackState = request.getPlaybackState()+        val audioTrack = request.getAudioTrack()+        val videoTrack = request.getVideoTrack()+        addDiagnosticEvent(+            "request n=" + requestNumber ++                " playerMs=" + playbackState.getPlayerTimeMs() ++                " audioThrough=" + (audioTrack?.getBufferedThrough() ?: 0) ++                " videoThrough=" + (videoTrack?.getBufferedThrough() ?: 0) ++                " selectedTracks=" + request.hasSelectedTracks() ++                " poTokenBytes=" + (poToken?.size ?: -1)+        )+        val timedConsumer = segmentConsumer+        val startedConsumer = SabrStreamingResponseReader.SegmentConsumer { }+        val result: YoutubeSabrResponse+        try {+            result = YoutubeSabrRequestHelper.post(+                info, request, this, serverAbrStreamingUrl, requestNumber, timedConsumer,+                startedConsumer, segmentSpoolDirectory+            )+        } catch (e: IOException) {+            addDiagnosticEvent(+                "request_failed n=" + requestNumber + " type=" + e.javaClass.simpleName ++                    " message=" + e.message.toString()+            )+            throw e+        } catch (e: ExtractionException) {+            addDiagnosticEvent(+                "request_failed n=" + requestNumber + " type=" + e.javaClass.simpleName ++                    " message=" + e.message.toString()+            )+            throw e+        }+        addDiagnosticEvent(+            "response n=" + requestNumber ++                " http=" + result.getResponseCode() ++                " contentType=" + result.getContentType() ++                " segments=" + (+                    if (result.getSegments().isEmpty()) {+                        "count=" + result.getSegmentCount()+                    } else {+                        summarizeSegments(result.getSegments())+                    }+                    ) ++                " decoded={" + result.summarizeForDiagnostics() + '}'+        )+        if (result.getBackoffTimeMs() > MAX_BACKOFF_MS) {+            throw SabrProtocolException("SABR backoff exceeds limit: " + result.getBackoffTimeMs() + "ms")+        }+        updateBackoff(result.getBackoffTimeMs())+        diagnostics.recordResponse(result, requestNumber)+        updateBandwidthEstimate(result.getResponseBytes(), result.getRequestElapsedMs())+        requestNumber+++        return result+    }++    @Synchronized+    @Throws(IOException::class, ExtractionException::class)+    fun requestOnce(+        request: YoutubeSabrRequest,+        consumer: SabrStreamingResponseReader.SegmentConsumer+    ): RequestResult {+        val backoffRemainingMs = getBackoffRemainingMs()+        if (backoffRemainingMs > 0) {+            return RequestResult(0, Math.min(Int.MAX_VALUE.toLong(), backoffRemainingMs).toInt(), true)+        }+        val result = fetchAndProcessResponse(request, consumer)+            ?: return RequestResult(+                0, Math.min(Int.MAX_VALUE.toLong(), getBackoffRemainingMs()).toInt(), false+            )+        return RequestResult(result.getSegmentCount(), result.getBackoffTimeMs(), false)+    }++    class RequestResult internal constructor(+        private val segmentCount: Int,+        private val backoffMs: Int,+        private val deferred: Boolean+    ) {+        fun getSegmentCount(): Int = segmentCount+        fun getBackoffMs(): Int = backoffMs++        /** True when no HTTP request was sent because this session is still backing off. */+        fun isDeferred(): Boolean = deferred+    }++    /** Remaining server-requested delay before another transaction may start. */+    fun getBackoffRemainingMs(): Long {+        val remainingNs = backoffDeadlineNs - System.nanoTime()+        return if (remainingNs <= 0) 0 else Math.max(1, remainingNs / 1_000_000L)+    }++    private fun updateBackoff(backoffMs: Int) {+        backoffDeadlineNs = if (backoffMs <= 0) 0 else System.nanoTime() + backoffMs * 1_000_000L+    }++    @Throws(IOException::class, ExtractionException::class)+    private fun fetchAndProcessResponse(+        request: YoutubeSabrRequest,+        segmentConsumer: SabrStreamingResponseReader.SegmentConsumer+    ): YoutubeSabrResponse? {+        val result: YoutubeSabrResponse+        try {+            result = fetchNextResponse(request, segmentConsumer)+        } catch (e: SabrRecoverableException) {+            if (recoverFromStreamingMediaException(e)) {+                return null+            }+            throw e+        }+        val decoded = result+        val integrityIssues = decoded.getIntegrityIssues()+        if (integrityIssues.isNotEmpty()) {+            if (isRecoverableIncompleteMediaResponse(integrityIssues)) {+                if (recoverFromIncompleteMediaResponse()) {+                    return null+                }+                throw SabrProtocolException("SABR media integrity issue: $integrityIssues")+            }+            throw SabrProtocolException("SABR media integrity issue: $integrityIssues")+        }+        consecutiveIntegrityFailures = 0+        handleControlResponse(result)+        return result+    }++    @Throws(SabrProtocolException::class)+    private fun handleControlResponse(result: YoutubeSabrResponse) {+        val decoded = result+        if (decoded.isAttestationPending() && decoded.isNoMediaResponse()) {+            consecutiveAttestationPendingResponses+++            addDiagnosticEvent(+                "attestation_pending_no_media count=$consecutiveAttestationPendingResponses"+            )+            if (consecutiveAttestationPendingResponses >= MAX_CONSECUTIVE_ATTESTATION_PENDING_RESPONSES) {+                throw SabrAttestationException(+                    "SABR attestation remained pending without media for " ++                        consecutiveAttestationPendingResponses + " consecutive responses: " ++                        decoded.summarizeNoMediaResponse()+                )+            }+        } else {+            consecutiveAttestationPendingResponses = 0+        }+        ingestControl(decoded)++        val redirectUrl = decoded.getRedirectUrl()+        if (!redirectUrl.isNullOrEmpty()) {+            if (++redirectCount > MAX_REDIRECTS_PER_SESSION) {+                throw SabrProtocolException("SABR redirect limit exceeded: redirects=$redirectCount")+            }+            validateRedirectUrl(redirectUrl)+            serverAbrStreamingUrl = redirectUrl+        }++        if (decoded.getSabrError() != null) {+            throw SabrProtocolException("SABR error: " + decoded.getSabrError())+        }+        if (decoded.isAttestationRequired()) {+            throw SabrAttestationException(+                "SABR attestation required: " + decoded.summarizeNoMediaResponse()+            )+        }+        if (decoded.isReloadRequested()) {+            throw SabrProtocolException(+                "SABR requested player reload: " + decoded.summarizeNoMediaResponse()+            )+        }++        if (result.getSegmentCount() > 0) {+            redirectCount = 0+        }+    }++    private fun ingestControl(response: YoutubeSabrResponse) {+        val nextRequestPolicy = response.getNextRequestPolicy()+        if (nextRequestPolicy != null) {+            ingestNextRequestPolicy(nextRequestPolicy)+        }+        for (update in response.getSabrContextUpdates()) {+            ingestContextUpdate(update)+        }+        val sendingPolicy = response.getSabrContextSendingPolicy()+        if (sendingPolicy != null) {+            ingestContextSendingPolicy(sendingPolicy)+        }+        for (metadata in response.getLiveMetadata()) {+            ingestLiveMetadata(metadata)+        }+    }++    private fun ingestNextRequestPolicy(data: ByteArray) {+        try {+            for (field in SabrProto.readFields(data)) {+                if (field.getNumber() == 7) {+                    playbackCookie = field.getBytes()+                }+            }+        } catch (ignored: SabrProtocolException) {+            // The response decoder already records malformed control parts.+        }+    }++    private fun ingestLiveMetadata(data: ByteArray) {+        val live = true+        var postLiveDvr = false+        var liveHeadSequenceNumber: Long = -1+        var liveHeadTimeMs: Long = -1+        try {+            for (field in SabrProto.readFields(data)) {+                when (field.getNumber()) {+                    3 -> liveHeadSequenceNumber = field.getVarint()+                    4 -> liveHeadTimeMs = field.getVarint()+                    8 -> postLiveDvr = field.getVarint() != 0L+                    else -> {}+                }+            }+        } catch (ignored: SabrProtocolException) {+            return+        }+        this.live = live+        this.postLiveDvr = postLiveDvr+        if (liveHeadSequenceNumber >= 0) this.liveHeadSequenceNumber = liveHeadSequenceNumber+        if (liveHeadTimeMs >= 0) this.liveHeadTimeMs = liveHeadTimeMs+    }++    private fun ingestContextUpdate(data: ByteArray) {+        var type = -1+        var value: ByteArray? = null+        var sendByDefault = false+        var writePolicy = -1+        try {+            for (field in SabrProto.readFields(data)) {+                when (field.getNumber()) {+                    1 -> type = field.getVarint().toInt()+                    3 -> value = field.getBytes()+                    4 -> sendByDefault = field.getVarint() != 0L+                    5 -> writePolicy = field.getVarint().toInt()+                    else -> {}+                }+            }+        } catch (ignored: SabrProtocolException) {+            return+        }+        if (type < 0 || value == null || value.isEmpty() ||+            writePolicy == 2 && sabrContexts.containsKey(type)+        ) {+            return+        }+        sabrContexts[type] = value+        if (sendByDefault) {+            activeSabrContextTypes.add(type)+        }+    }++    private fun ingestContextSendingPolicy(data: ByteArray) {+        try {+            for (field in SabrProto.readFields(data)) {+                val values: List<Long> = when (field.getWireType()) {+                    SabrProto.WIRE_VARINT -> Collections.singletonList(field.getVarint())+                    SabrProto.WIRE_LENGTH_DELIMITED -> SabrProto.readPackedVarints(field.getBytes())+                    else -> emptyList()+                }+                for (value in values) {+                    val type = value.toInt()+                    when (field.getNumber()) {+                        1 -> activeSabrContextTypes.add(type)+                        2 -> activeSabrContextTypes.remove(type)+                        3 -> {+                            sabrContexts.remove(type)+                            activeSabrContextTypes.remove(type)+                        }+                    }+                }+            }+        } catch (ignored: SabrProtocolException) {+            // The response decoder already records malformed control parts.+        }+    }++    internal fun getRawPlaybackCookie(): ByteArray? = playbackCookie++    @Synchronized+    fun clearPlaybackCookie() {+        playbackCookie = null+    }++    internal fun getActiveSabrContexts(): Map<Int, ByteArray> {+        val active = LinkedHashMap<Int, ByteArray>()+        for (type in activeSabrContextTypes) {+            val value = sabrContexts[type]+            if (value != null) active[type] = value+        }+        return active+    }++    internal fun getUnsentSabrContextTypes(): Collection<Int> {+        val unsent = ArrayList<Int>()+        for (type in sabrContexts.keys) {+            if (!activeSabrContextTypes.contains(type)) unsent.add(type)+        }+        return unsent+    }++    /** True once the server has reported this is a live stream (foundation for live support). */+    fun isLive(): Boolean = live++    /** Latest segment the live edge has reached, or -1 if unknown / not live. */+    fun getLiveHeadSequenceNumber(): Long = liveHeadSequenceNumber++    fun isPostLiveDvr(): Boolean = postLiveDvr++    fun getLiveHeadTimeMs(): Long = liveHeadTimeMs++    fun getRequestNumber(): Int = requestNumber++    @Synchronized+    fun setPoToken(value: ByteArray?) {+        poToken = value?.clone()+    }++    internal fun getRawPoToken(): ByteArray? = poToken++    internal fun getBandwidthEstimate(): Long = bandwidthEstimate++    private fun updateBandwidthEstimate(responseBytes: Long, elapsedMs: Long) {+        if (responseBytes <= 0 || elapsedMs <= 0) return+        val sample = responseBytes * 8_000L / elapsedMs+        bandwidthEstimate = if (bandwidthEstimate <= 0) sample else (bandwidthEstimate * 3 + sample) / 4+    }++    private fun matchesFormat(format: YoutubeSabrInfo.Format, segment: SabrMediaSegment): Boolean {+        if (segment.getHeader().getItag() != format.getItag()) return false+        val headerXtags = segment.getHeader().getXtags()+        if (headerXtags != null) return headerXtags == format.getXtags()+        var sameItagFormats = 0+        for (candidate in info.getFormats()) {+            if (candidate.getItag() == format.getItag()) sameItagFormats+++        }+        return sameItagFormats == 1+    }++    @Throws(IOException::class, ExtractionException::class)+    private fun recoverFromStreamingMediaException(error: SabrRecoverableException): Boolean {+        addDiagnosticEvent(+            "streaming_integrity_recoverable type=" + error.javaClass.simpleName ++                " message=" + error.message+        )+        return recoverFromIncompleteMediaResponse()+    }++    @Throws(IOException::class, ExtractionException::class)+    private fun recoverFromIncompleteMediaResponse(): Boolean {+        consecutiveIntegrityFailures+++        return consecutiveIntegrityFailures < MAX_INCOMPLETE_MEDIA_RESPONSES+    }++    @Synchronized+    fun addDiagnosticEvent(event: String) {+        diagnostics.addEvent(event)+    }++    @Synchronized+    fun getDiagnosticTrace(): String = diagnostics.getTrace()++    /** Raw bytes consumed from all SABR HTTP response bodies in this session. */+    fun getTotalResponseBytes(): Long = diagnostics.getTotalResponseBytes()+    fun getMaxResponseBytes(): Long = diagnostics.getMaxResponseBytes()+    fun getMaxUmpPartBytes(): Long = diagnostics.getMaxUmpPartBytes()+    fun getMaxMediaPartPayloadBytes(): Long = diagnostics.getMaxMediaPartPayloadBytes()+    fun getMaxSegmentBytes(): Long = diagnostics.getMaxSegmentBytes()+    fun getMaxSegmentsPerResponse(): Int = diagnostics.getMaxSegmentsPerResponse()+    fun getMaxStreamProtectionStatus(): Int = diagnostics.getMaxStreamProtectionStatus()++    fun getMemoryDiagnosticSummary(): String = diagnostics.getMemorySummary(requestNumber)++    fun setTraceEnabled(traceEnabled: Boolean) {+        diagnostics.setTraceEnabled(traceEnabled)+    }++    fun getTraceSnapshot(): TraceSnapshot = diagnostics.snapshot(requestNumber)++    class TraceSnapshot internal constructor(+        private val responseBytes: Long,+        private val mediaPayloadBytes: Long,+        private val controlPayloadBytes: Long,+        private val umpOverheadBytes: Long,+        private val discardedBytes: Long,+        private val requestNumber: Int,+        segments: List<String>,+        discards: List<String>,+        responses: List<String>+    ) {+        private val segments: List<String> = Collections.unmodifiableList(segments)+        private val discards: List<String> = Collections.unmodifiableList(discards)+        private val responses: List<String> = Collections.unmodifiableList(responses)++        fun getResponseBytes(): Long = responseBytes+        fun getMediaPayloadBytes(): Long = mediaPayloadBytes+        fun getControlPayloadBytes(): Long = controlPayloadBytes+        fun getUmpOverheadBytes(): Long = umpOverheadBytes+        fun getDiscardedBytes(): Long = discardedBytes+        fun getRequestNumber(): Int = requestNumber+        fun getSegments(): List<String> = segments+        fun getDiscards(): List<String> = discards+        fun getResponses(): List<String> = responses+    }++    companion object {+        private const val MAX_REDIRECTS_PER_SESSION = 3+        private const val MAX_INCOMPLETE_MEDIA_RESPONSES = 3+        private const val MAX_CONSECUTIVE_ATTESTATION_PENDING_RESPONSES = 3+        private const val MAX_BACKOFF_MS = 30_000++        private fun isRecoverableIncompleteMediaResponse(integrityIssues: List<String>): Boolean {+            if (integrityIssues.isEmpty()) {+                return false+            }+            for (issue in integrityIssues) {+                if (!issue.startsWith("length-mismatch:") &&+                    !issue.startsWith("missing-media-end:") &&+                    !issue.startsWith("missing-media:") &&+                    !issue.startsWith("media-without-header:") &&+                    !issue.startsWith("media-end-without-header:")+                ) {+                    return false+                }+            }+            return true+        }++        @Throws(SabrProtocolException::class)+        private fun validateRedirectUrl(redirectUrl: String) {+            try {+                val uri = URI.create(redirectUrl)+                val host = uri.host+                if (!"https".equals(uri.scheme, ignoreCase = true) || host == null ||+                    !(host == "googlevideo.com" || host.endsWith(".googlevideo.com"))+                ) {+                    throw SabrProtocolException("SABR redirect escaped the GoogleVideo Host")+                }+            } catch (error: IllegalArgumentException) {+                throw SabrProtocolException("Malformed SABR redirect URL", error)+            }+        }++        private fun summarizeSegments(segments: List<SabrMediaSegment>): String {+            if (segments.isEmpty()) {+                return "[]"+            }+            val summary = StringBuilder("[")+            for (i in segments.indices) {+                if (i > 0) {+                    summary.append(',')+                }+                val segment = segments[i]+                summary.append(segment.getHeader().getItag()).append(':')+                summary.append(+                    if (segment.getHeader().isInitSegment()) {+                        "init"+                    } else {+                        segment.getHeader().getSequenceNumber()+                    }+                )+            }+            return summary.append(']').toString()+        }+    }+}
youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSessionDiagnostics.kt
diff --git a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSessionDiagnostics.kt b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSessionDiagnostics.ktnew file mode 100644index 0000000000..2f9efa6a17--- /dev/null+++ b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrSessionDiagnostics.kt@@ -0,0 +1,134 @@+package org.schabi.newpipe.extractor.services.youtube.sabrng++import java.util.ArrayDeque+import java.util.concurrent.atomic.AtomicInteger++/** Observability state for a SABR session; it does not participate in requests. */+internal class YoutubeSabrSessionDiagnostics {+    private val diagnosticEvents = ArrayDeque<String>()+    private var diagnosticChars = 0++    @Volatile+    private var totalResponseBytes: Long = 0++    @Volatile+    private var maxResponseBytes: Long = 0++    @Volatile+    private var maxUmpPartBytes: Long = 0++    @Volatile+    private var maxMediaPartPayloadBytes: Long = 0++    @Volatile+    private var maxSegmentBytes: Long = 0++    @Volatile+    private var maxSegmentsPerResponse: Int = 0++    private val maxStreamProtectionStatus = AtomicInteger(-1)++    @Volatile+    private var traceEnabled = false++    private val traceLock = Any()+    private var traceResponseBytes: Long = 0+    private var traceMediaPayloadBytes: Long = 0+    private var traceControlPayloadBytes: Long = 0+    private var traceUmpOverheadBytes: Long = 0+    private val traceResponses = ArrayDeque<String>()++    @Synchronized+    fun addEvent(event: String) {+        val bounded = if (event.length > MAX_DIAGNOSTIC_CHARS) {+            event.substring(0, MAX_DIAGNOSTIC_CHARS)+        } else {+            event+        }+        while (diagnosticEvents.isNotEmpty() &&+            diagnosticChars + bounded.length > MAX_DIAGNOSTIC_CHARS+        ) {+            diagnosticChars -= diagnosticEvents.removeFirst().length+        }+        diagnosticEvents.addLast(bounded)+        diagnosticChars += bounded.length+    }++    @Synchronized+    fun getTrace(): String = diagnosticEvents.joinToString(" | ")++    fun recordResponse(result: YoutubeSabrResponse, requestNumber: Int) {+        totalResponseBytes += result.getResponseBytes()+        maxResponseBytes = Math.max(maxResponseBytes, result.getResponseBytes())+        maxUmpPartBytes = Math.max(maxUmpPartBytes, result.getMaxPartBytes())+        maxMediaPartPayloadBytes =+            Math.max(maxMediaPartPayloadBytes, result.getMaxMediaPartPayloadBytes())+        maxSegmentBytes = Math.max(maxSegmentBytes, result.getMaxSegmentBytes())+        maxSegmentsPerResponse = Math.max(maxSegmentsPerResponse, result.getSegmentCount())+        maxStreamProtectionStatus.accumulateAndGet(result.getStreamProtectionStatus()) { a, b ->+            Math.max(a, b)+        }+        if (!traceEnabled) {+            return+        }+        val umpOverheadBytes = Math.max(0, result.getResponseBytes() - result.getTotalPayloadBytes())+        synchronized(traceLock) {+            traceResponseBytes += result.getResponseBytes()+            traceMediaPayloadBytes += result.getMediaPayloadBytes()+            traceControlPayloadBytes += result.getControlPayloadBytes()+            traceUmpOverheadBytes += umpOverheadBytes+            addBoundedTraceEvent(+                traceResponses,+                "request=" + requestNumber ++                    ",elapsedMs=" + result.getRequestElapsedMs() ++                    ",firstSegmentMs=" + result.getFirstSegmentElapsedMs() ++                    ",bytes=" + result.getResponseBytes() ++                    ",mediaBytes=" + result.getMediaPayloadBytes() ++                    ",segments=" + result.getSegmentCount()+            )+        }+    }++    fun setTraceEnabled(enabled: Boolean) {+        traceEnabled = enabled+    }++    fun getTotalResponseBytes(): Long = totalResponseBytes+    fun getMaxResponseBytes(): Long = maxResponseBytes+    fun getMaxUmpPartBytes(): Long = maxUmpPartBytes+    fun getMaxMediaPartPayloadBytes(): Long = maxMediaPartPayloadBytes+    fun getMaxSegmentBytes(): Long = maxSegmentBytes+    fun getMaxSegmentsPerResponse(): Int = maxSegmentsPerResponse+    fun getMaxStreamProtectionStatus(): Int = maxStreamProtectionStatus.get()++    fun getMemorySummary(requestNumber: Int): String =+        "requestNumber=" + requestNumber ++            ", totalResponseBytes=" + totalResponseBytes ++            ", maxResponseBytes=" + maxResponseBytes ++            ", maxUmpPartBytes=" + maxUmpPartBytes ++            ", maxMediaPartPayloadBytes=" + maxMediaPartPayloadBytes ++            ", maxSegmentBytes=" + maxSegmentBytes ++            ", maxSegmentsPerResponse=" + maxSegmentsPerResponse++    fun snapshot(requestNumber: Int): YoutubeSabrSession.TraceSnapshot {+        synchronized(traceLock) {+            return YoutubeSabrSession.TraceSnapshot(+                traceResponseBytes, traceMediaPayloadBytes, traceControlPayloadBytes,+                traceUmpOverheadBytes, 0, requestNumber, emptyList(), emptyList(),+                ArrayList(traceResponses)+            )+        }+    }++    companion object {+        private const val MAX_DIAGNOSTIC_CHARS = 32 * 1024+        private const val MAX_TRACE_EVENTS = 1024++        private fun addBoundedTraceEvent(events: ArrayDeque<String>, value: String) {+            if (events.size >= MAX_TRACE_EVENTS) {+                events.removeFirst()+            }+            events.addLast(value)+        }+    }+}