Modern Apps git

← Modern-Apps.git

youpipe: port PipePipe #92 SABR rewrite (response decoder + streaming reader + segment collector)

Commit
b1117f2a939251f7ad89aa3b98e023e021ae7090
Author
vayun-mathur <[email protected]>
When
2026-08-16 17:22 UTC (3 months ago)
Parents
6c47b0d

Diff

youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/media/SabrMediaSegmentCollector.kt
diff --git a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/media/SabrMediaSegmentCollector.kt b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/media/SabrMediaSegmentCollector.ktnew file mode 100644index 0000000000..f89db2000a--- /dev/null+++ b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/media/SabrMediaSegmentCollector.kt@@ -0,0 +1,448 @@+package org.schabi.newpipe.extractor.services.youtube.sabrng.media++import org.brotli.dec.BrotliInputStream+import org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrResponse+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.generated.SabrMediaHeader+import org.schabi.newpipe.extractor.services.youtube.sabrng.protocol.SabrResponseDecoder+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.File+import java.io.FileOutputStream+import java.io.IOException+import java.io.InputStream+import java.io.OutputStream+import java.util.zip.GZIPInputStream++/** Assembles UMP MEDIA_HEADER / MEDIA / MEDIA_END parts into complete [SabrMediaSegment]s. */+object SabrMediaSegmentCollector {+    private const val MIN_PROGRESSIVE_SEGMENT_BYTES = 64 * 1024++    @JvmStatic+    @Throws(SabrProtocolException::class)+    fun collect(response: YoutubeSabrResponse): List<SabrMediaSegment> {+        val segments = ArrayList<SabrMediaSegment>()+        val openSegments = HashMap<Int, OpenSegment>()+        for (part in response.getParts()) {+            val partData = part.getRawData()+            when (part.getType()) {+                SabrResponseDecoder.MEDIA_HEADER -> {+                    val header = SabrMediaHeader.decode(partData)+                    openSegments[header.getHeaderId()] = OpenSegment(header)+                }+                SabrResponseDecoder.MEDIA -> {+                    if (partData.isNotEmpty()) {+                        val openSegment = openSegments[partData[0].toInt() and 0xff]+                        openSegment?.write(partData, 1, partData.size - 1)+                    }+                }+                SabrResponseDecoder.MEDIA_END -> {+                    if (partData.isNotEmpty()) {+                        val openSegment = openSegments.remove(partData[0].toInt() and 0xff)+                        if (openSegment != null) {+                            segments.add(openSegment.toSegment())+                        }+                    }+                }+                else -> {}+            }+        }+        return segments+    }++    /**+     * Incremental collector for the streaming path: feed MEDIA_HEADER / MEDIA / MEDIA_END parts as+     * they arrive and get each completed segment back from [onMediaEnd], so the caller never has to+     * retain all the MEDIA parts at once (that whole-body buffering was the 4K OOM).+     */+    class Incremental @JvmOverloads constructor(private val spoolDirectory: File? = null) {+        private val openSegments = HashMap<Int, OpenSegment>()++        @Throws(SabrProtocolException::class)+        fun onMediaHeader(partData: ByteArray): SabrMediaSegment? {+            val header = SabrMediaHeader.decode(partData)+            val current = OpenSegment(header, spoolDirectory)+            val previous = openSegments.put(header.getHeaderId(), current)+            previous?.abort()+            return current.getProgressiveSegment()+        }++        @Throws(SabrProtocolException::class)+        fun onMedia(partData: ByteArray) {+            if (partData.isNotEmpty()) {+                val openSegment = openSegments[partData[0].toInt() and 0xff]+                openSegment?.write(partData, 1, partData.size - 1)+            }+        }++        @Throws(SabrProtocolException::class)+        fun onMedia(headerId: Int, input: InputStream, count: Int) {+            val openSegment = openSegments[headerId]+            if (openSegment != null) {+                openSegment.write(input, count)+            } else {+                drain(input, count)+            }+        }++        @Throws(SabrProtocolException::class)+        fun onMediaEnd(partData: ByteArray): SabrMediaSegment? {+            if (partData.isNotEmpty()) {+                val openSegment = openSegments.remove(partData[0].toInt() and 0xff)+                if (openSegment != null) {+                    try {+                        return openSegment.toSegment()+                    } catch (e: SabrProtocolException) {+                        openSegment.abort()+                        throw e+                    }+                }+            }+            return null+        }++        fun abort() {+            for (segment in openSegments.values) {+                segment.abort()+            }+            openSegments.clear()+        }+    }++    private class OpenSegment @Throws(SabrProtocolException::class) constructor(+        private val header: SabrMediaHeader,+        spoolDirectory: File? = null+    ) {+        private val fixedData: ByteArray?+        private val dynamicData: ByteArrayOutputStream?+        private val file: File?+        private val fileOutput: OutputStream?+        private val progressiveSegment: SabrMediaSegment?+        private var length = 0+        private var fileOutputClosed = false++        init {+            val contentLength = header.getContentLength()+            if (spoolDirectory != null && header.getCompressionAlgorithm() <= 0 &&+                !header.isInitSegment()+            ) {+                if (contentLength > Int.MAX_VALUE) {+                    throw SabrProtocolException(+                        "SABR media segment too large: headerId=" + header.getHeaderId() ++                            ", length=" + contentLength+                    )+                }+                if (!spoolDirectory.exists() && !spoolDirectory.mkdirs()) {+                    throw SabrRecoverableException(+                        "Could not create SABR spool directory: $spoolDirectory"+                    )+                }+                try {+                    val spoolFile = File.createTempFile(+                        "sabr-" + header.getItag() + '-' + header.getSequenceNumber() + '-',+                        ".seg", spoolDirectory+                    )+                    file = spoolFile+                    fileOutput = FileOutputStream(spoolFile)+                    progressiveSegment = if (contentLength < MIN_PROGRESSIVE_SEGMENT_BYTES) {+                        null+                    } else {+                        SabrMediaSegment.InternalAccess.progressive(+                            header, spoolFile, contentLength.toInt()+                        )+                    }+                } catch (e: IOException) {+                    throw SabrRecoverableException("Could not open SABR spool file", e)+                }+                fixedData = null+                dynamicData = null+            } else if (contentLength >= 0) {+                if (contentLength > Int.MAX_VALUE) {+                    throw SabrProtocolException(+                        "SABR media segment too large: headerId=" + header.getHeaderId() ++                            ", length=" + contentLength+                    )+                }+                fixedData = ByteArray(contentLength.toInt())+                dynamicData = null+                file = null+                fileOutput = null+                progressiveSegment = null+            } else {+                fixedData = null+                dynamicData = ByteArrayOutputStream()+                file = null+                fileOutput = null+                progressiveSegment = null+            }+        }++        fun getProgressiveSegment(): SabrMediaSegment? = progressiveSegment++        @Throws(SabrProtocolException::class)+        fun write(bytes: ByteArray, offset: Int, count: Int) {+            if (count <= 0) {+                return+            }+            ensureLengthFits(count)+            ensureExpectedLengthNotExceeded(count)+            if (fixedData != null) {+                if (length + count > fixedData.size) {+                    throw SabrRecoverableException(+                        "SABR media length overflow: headerId=" + header.getHeaderId() ++                            ", expected=" + fixedData.size + ", actual>=" + (length + count)+                    )+                }+                System.arraycopy(bytes, offset, fixedData, length, count)+            } else if (fileOutput != null) {+                try {+                    fileOutput.write(bytes, offset, count)+                    length += count+                    if (progressiveSegment != null) {+                        SabrMediaSegment.InternalAccess.onBytesWritten(progressiveSegment, count)+                    }+                } catch (e: IOException) {+                    throw SabrRecoverableException("Could not write SABR spool file", e)+                }+            } else {+                dynamicData!!.write(bytes, offset, count)+            }+            if (fileOutput == null) {+                length += count+            }+        }++        @Throws(SabrProtocolException::class)+        fun write(input: InputStream, count: Int) {+            if (count <= 0) {+                return+            }+            ensureLengthFits(count)+            if (isExpectedLengthExceeded(count)) {+                drain(input, count)+                throw lengthOverflowException(count)+            }+            if (fixedData != null) {+                if (length + count > fixedData.size) {+                    drain(input, count)+                    throw SabrRecoverableException(+                        "SABR media length overflow: headerId=" + header.getHeaderId() ++                            ", expected=" + fixedData.size + ", actual>=" + (length + count)+                    )+                }+                readFully(input, fixedData, length, count)+            } else {+                val buffer = ByteArray(8192)+                var remaining = count+                while (remaining > 0) {+                    val read: Int = try {+                        input.read(buffer, 0, Math.min(buffer.size, remaining))+                    } catch (e: IOException) {+                        throw SabrRecoverableException("Could not read SABR media payload", e)+                    }+                    if (read < 0) {+                        throw SabrRecoverableException("Unexpected EOF in SABR media payload")+                    }+                    if (fileOutput != null) {+                        try {+                            fileOutput.write(buffer, 0, read)+                            length += read+                            if (progressiveSegment != null) {+                                SabrMediaSegment.InternalAccess.onBytesWritten(+                                    progressiveSegment, read+                                )+                            }+                        } catch (e: IOException) {+                            throw SabrRecoverableException("Could not write SABR spool file", e)+                        }+                    } else {+                        dynamicData!!.write(buffer, 0, read)+                    }+                    remaining -= read+                }+            }+            if (fileOutput == null) {+                length += count+            }+        }++        @Throws(SabrProtocolException::class)+        fun toSegment(): SabrMediaSegment {+            if (fileOutput != null) {+                closeFileOutput()+                if (header.getContentLength() >= 0 && length.toLong() != header.getContentLength()) {+                    throw SabrRecoverableException(+                        "SABR media length mismatch: headerId=" + header.getHeaderId() ++                            ", expected=" + header.getContentLength() + ", actual=" + length+                    )+                }+                if (progressiveSegment != null) {+                    SabrMediaSegment.InternalAccess.completeProgressive(progressiveSegment)+                    return progressiveSegment+                }+                return SabrMediaSegment.InternalAccess.fromFile(header, file!!, length)+            }+            val rawBytes: ByteArray = fixedData ?: dynamicData!!.toByteArray()+            if (header.getContentLength() >= 0 && length.toLong() != header.getContentLength()) {+                throw SabrRecoverableException(+                    "SABR media length mismatch: headerId=" + header.getHeaderId() ++                        ", expected=" + header.getContentLength() + ", actual=" + length+                )+            }+            return SabrMediaSegment.InternalAccess.fromBytes(+                header, maybeDecompress(header, rawBytes)+            )+        }++        @Throws(SabrProtocolException::class)+        private fun ensureLengthFits(count: Int) {+            if (length > Int.MAX_VALUE - count) {+                throw SabrProtocolException(+                    "SABR media segment too large: headerId=" + header.getHeaderId() ++                        ", length>" + Int.MAX_VALUE+                )+            }+        }++        @Throws(SabrProtocolException::class)+        private fun ensureExpectedLengthNotExceeded(count: Int) {+            if (isExpectedLengthExceeded(count)) {+                throw lengthOverflowException(count)+            }+        }++        private fun isExpectedLengthExceeded(count: Int): Boolean =+            header.getContentLength() >= 0 && length + count.toLong() > header.getContentLength()++        private fun lengthOverflowException(count: Int): SabrRecoverableException =+            SabrRecoverableException(+                "SABR media length overflow: headerId=" + header.getHeaderId() ++                    ", expected=" + header.getContentLength() + ", actual>=" + (length + count.toLong())+            )++        fun abort() {+            if (progressiveSegment != null) {+                SabrMediaSegment.InternalAccess.failProgressive(+                    progressiveSegment,+                    IOException("SABR media segment ended before MEDIA_END")+                )+            }+            try {+                closeFileOutput()+            } catch (ignored: SabrProtocolException) {+                // Best-effort cleanup after an already-failing segment.+            }+            if (file != null && file.exists() && !file.delete()) {+                file.deleteOnExit()+            }+        }++        @Throws(SabrProtocolException::class)+        private fun closeFileOutput() {+            if (fileOutput == null || fileOutputClosed) {+                return+            }+            try {+                fileOutput.close()+                fileOutputClosed = true+            } catch (e: IOException) {+                throw SabrRecoverableException("Could not close SABR spool file", e)+            }+        }++        companion object {+            @Throws(SabrProtocolException::class)+            private fun maybeDecompress(header: SabrMediaHeader, bytes: ByteArray): ByteArray {+                val compressionAlgorithm = header.getCompressionAlgorithm()+                if (compressionAlgorithm <= 0) {+                    return bytes+                }+                if (compressionAlgorithm == 1) {+                    return gunzip(bytes)+                }+                if (compressionAlgorithm == 2) {+                    return brotli(bytes)+                }+                throw SabrProtocolException(+                    "Unsupported SABR media compression: $compressionAlgorithm"+                )+            }++            @Throws(SabrProtocolException::class)+            private fun gunzip(bytes: ByteArray): ByteArray {+                try {+                    GZIPInputStream(ByteArrayInputStream(bytes)).use { input ->+                        ByteArrayOutputStream().use { output ->+                            val buffer = ByteArray(8192)+                            var read: Int+                            while (input.read(buffer).also { read = it } != -1) {+                                output.write(buffer, 0, read)+                            }+                            return output.toByteArray()+                        }+                    }+                } catch (e: IOException) {+                    throw SabrRecoverableException(+                        "Could not decompress gzip SABR media segment", e+                    )+                }+            }++            @Throws(SabrProtocolException::class)+            private fun brotli(bytes: ByteArray): ByteArray {+                try {+                    BrotliInputStream(ByteArrayInputStream(bytes)).use { input ->+                        ByteArrayOutputStream().use { output ->+                            val buffer = ByteArray(8192)+                            var read: Int+                            while (input.read(buffer).also { read = it } != -1) {+                                output.write(buffer, 0, read)+                            }+                            return output.toByteArray()+                        }+                    }+                } catch (e: IOException) {+                    throw SabrRecoverableException(+                        "Could not decompress brotli SABR media segment", e+                    )+                }+            }+        }+    }++    @Throws(SabrProtocolException::class)+    private fun readFully(input: InputStream, target: ByteArray, offset: Int, count: Int) {+        var current = offset+        var remaining = count+        while (remaining > 0) {+            val read: Int = try {+                input.read(target, current, remaining)+            } catch (e: IOException) {+                throw SabrRecoverableException("Could not read SABR media payload", e)+            }+            if (read < 0) {+                throw SabrRecoverableException("Unexpected EOF in SABR media payload")+            }+            current += read+            remaining -= read+        }+    }++    @Throws(SabrProtocolException::class)+    private fun drain(input: InputStream, count: Int) {+        val buffer = ByteArray(8192)+        var remaining = count+        while (remaining > 0) {+            val read: Int = try {+                input.read(buffer, 0, Math.min(buffer.size, remaining))+            } catch (e: IOException) {+                throw SabrRecoverableException("Could not drain SABR media payload", e)+            }+            if (read < 0) {+                throw SabrRecoverableException("Unexpected EOF in SABR media payload")+            }+            remaining -= read+        }+    }+}
youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/protocol/SabrResponseDecoder.kt
diff --git a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/protocol/SabrResponseDecoder.kt b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/protocol/SabrResponseDecoder.ktnew file mode 100644index 0000000000..9c05fde8fb--- /dev/null+++ b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/protocol/SabrResponseDecoder.kt@@ -0,0 +1,230 @@+package org.schabi.newpipe.extractor.services.youtube.sabrng.protocol++import org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrResponse+import org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrProtocolException+import org.schabi.newpipe.extractor.services.youtube.sabrng.generated.SabrFormatInitializationMetadata+import org.schabi.newpipe.extractor.services.youtube.sabrng.generated.SabrMediaHeader++/** Decodes UMP parts of a SABR response into structured control state on [YoutubeSabrResponse]. */+object SabrResponseDecoder {+    const val ONESIE_HEADER = 10+    const val ONESIE_DATA = 11+    const val ONESIE_ENCRYPTED_MEDIA = 12+    const val MEDIA_HEADER = 20+    const val MEDIA = 21+    const val MEDIA_END = 22+    const val CONFIG = 30+    const val LIVE_METADATA = 31+    const val HOSTNAME_CHANGE_HINT_DEPRECATED = 32+    const val LIVE_METADATA_PROMISE = 33+    const val LIVE_METADATA_PROMISE_CANCELLATION = 34+    const val NEXT_REQUEST_POLICY = 35+    const val USTREAMER_VIDEO_AND_FORMAT_METADATA = 36+    const val FORMAT_SELECTION_CONFIG = 37+    const val USTREAMER_SELECTED_MEDIA_STREAM = 38+    const val FORMAT_INITIALIZATION_METADATA = 42+    const val SABR_REDIRECT = 43+    const val SABR_ERROR = 44+    const val SABR_SEEK = 45+    const val RELOAD_PLAYER_RESPONSE = 46+    const val PLAYBACK_START_POLICY = 47+    const val ALLOWED_CACHED_FORMATS = 48+    const val START_BW_SAMPLING_HINT = 49+    const val PAUSE_BW_SAMPLING_HINT = 50+    const val SELECTABLE_FORMATS = 51+    const val REQUEST_IDENTIFIER = 52+    const val REQUEST_CANCELLATION_POLICY = 53+    const val ONESIE_PREFETCH_REJECTION = 54+    const val TIMELINE_CONTEXT = 55+    const val REQUEST_PIPELINING = 56+    const val SABR_CONTEXT_UPDATE = 57+    const val STREAM_PROTECTION_STATUS = 58+    const val SABR_CONTEXT_SENDING_POLICY = 59+    const val LAWNMOWER_POLICY = 60+    const val SABR_ACK = 61+    const val END_OF_TRACK = 62+    const val CACHE_LOAD_POLICY = 63+    const val LAWNMOWER_MESSAGING_POLICY = 64+    const val PREWARM_CONNECTION = 65+    const val PLAYBACK_DEBUG_INFO = 66+    const val SNACKBAR_MESSAGE = 67++    @JvmStatic+    @Throws(SabrProtocolException::class)+    fun decode(data: ByteArray): YoutubeSabrResponse = decodeParts(UmpReader.readAll(data))++    /**+     * Decode an already-parsed list of UMP parts. Used by the streaming path, which collects the+     * small control parts (everything except the big MEDIA payloads) and decodes them here, while+     * the MEDIA segments are assembled separately so the whole body is never held at once.+     */+    @JvmStatic+    @Throws(SabrProtocolException::class)+    fun decodeParts(parts: List<UmpReader.UmpPart>): YoutubeSabrResponse {+        val decoded = YoutubeSabrResponse()+        for (part in parts) {+            val partData = part.getRawData()+            decoded.addPart(part)+            if (part.getType() != MEDIA && part.getType() != MEDIA_END) {+                try {+                    decoded.addWireFieldSummary(part.getType(), SabrProto.summarizeFields(partData))+                } catch (ignored: SabrProtocolException) {+                    decoded.addWireFieldSummary(part.getType(), "opaqueBytes=" + partData.size)+                }+            }+            try {+                if (part.getType() == MEDIA_HEADER) {+                    decoded.addMediaHeader(SabrMediaHeader.decode(partData))+                    continue+                }+                if (part.getType() == MEDIA) {+                    if (partData.isNotEmpty()) {+                        decoded.addMediaBytes(partData[0].toInt() and 0xff, partData.size - 1L)+                    }+                    continue+                }+                if (part.getType() == MEDIA_END) {+                    if (partData.isNotEmpty()) decoded.addMediaEndHeaderId(partData[0].toInt() and 0xff)+                    continue+                }+                when (part.getType()) {+                    ONESIE_HEADER, ONESIE_DATA, ONESIE_ENCRYPTED_MEDIA ->+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    FORMAT_INITIALIZATION_METADATA -> {+                        val metadata = SabrFormatInitializationMetadata.decode(partData)+                        decoded.addFormatInitializationMetadata(metadata)+                        decoded.addGenericPartDescription(part.getType(), metadata.summarize())+                    }+                    MEDIA_HEADER -> decoded.addMediaHeader(SabrMediaHeader.decode(partData))+                    MEDIA -> if (partData.isNotEmpty()) {+                        decoded.addMediaBytes(partData[0].toInt() and 0xff, partData.size - 1L)+                    }+                    MEDIA_END -> if (partData.isNotEmpty()) {+                        decoded.addMediaEndHeaderId(partData[0].toInt() and 0xff)+                    }+                    LIVE_METADATA -> {+                        decoded.addLiveMetadata(partData)+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    }+                    NEXT_REQUEST_POLICY -> {+                        decodeNextRequestPolicy(partData, decoded)+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    }+                    SABR_REDIRECT -> {+                        decoded.setRedirectUrl(readString(partData, 1))+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    }+                    SABR_SEEK ->+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    SABR_ERROR -> {+                        val error = decodeError(partData)+                        decoded.setSabrError(error)+                        decoded.addGenericPartDescription(part.getType(), error)+                    }+                    RELOAD_PLAYER_RESPONSE -> {+                        decoded.setReloadRequested(true)+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    }+                    STREAM_PROTECTION_STATUS -> {+                        decodeStreamProtectionStatus(partData, decoded)+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    }+                    PLAYBACK_START_POLICY ->+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    SABR_CONTEXT_UPDATE -> {+                        decoded.addSabrContextUpdate(partData)+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    }+                    SABR_CONTEXT_SENDING_POLICY -> {+                        decoded.setSabrContextSendingPolicy(partData)+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    }+                    SNACKBAR_MESSAGE ->+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    FORMAT_SELECTION_CONFIG ->+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    PREWARM_CONNECTION ->+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    START_BW_SAMPLING_HINT, CONFIG, HOSTNAME_CHANGE_HINT_DEPRECATED,+                    LIVE_METADATA_PROMISE, LIVE_METADATA_PROMISE_CANCELLATION,+                    USTREAMER_VIDEO_AND_FORMAT_METADATA, USTREAMER_SELECTED_MEDIA_STREAM,+                    ALLOWED_CACHED_FORMATS, PAUSE_BW_SAMPLING_HINT, ONESIE_PREFETCH_REJECTION,+                    TIMELINE_CONTEXT, REQUEST_PIPELINING, LAWNMOWER_POLICY, SABR_ACK, END_OF_TRACK,+                    CACHE_LOAD_POLICY, LAWNMOWER_MESSAGING_POLICY, PLAYBACK_DEBUG_INFO ->+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    REQUEST_IDENTIFIER ->+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    REQUEST_CANCELLATION_POLICY ->+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    SELECTABLE_FORMATS ->+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    else -> {+                        decoded.addUnknownPartType(part.getType())+                        decoded.addGenericPartDescription(part.getType(), describeGenericMessage(partData))+                    }+                }+            } catch (e: SabrProtocolException) {+                // One malformed protobuf message must not discard valid MEDIA from the rest of the+                // UMP response. Ignore only that part and retain a bounded diagnostic.+                decoded.addMalformedPart(part.getType(), part.getSize(), e)+            }+        }+        return decoded+    }++    @Throws(SabrProtocolException::class)+    private fun decodeNextRequestPolicy(data: ByteArray, decoded: YoutubeSabrResponse) {+        decoded.setNextRequestPolicy(data)+        for (field in SabrProto.readFields(data)) {+            if (field.getNumber() == 4 && field.getWireType() == SabrProto.WIRE_VARINT) {+                decoded.setBackoffTimeMs(field.getVarint().toInt())+            }+        }+    }++    @Throws(SabrProtocolException::class)+    private fun decodeStreamProtectionStatus(data: ByteArray, decoded: YoutubeSabrResponse) {+        for (field in SabrProto.readFields(data)) {+            if (field.getNumber() == 1 && field.getWireType() == SabrProto.WIRE_VARINT) {+                decoded.setStreamProtectionStatus(field.getVarint().toInt())+            } else if (field.getNumber() == 2 && field.getWireType() == SabrProto.WIRE_VARINT) {+                decoded.setStreamProtectionMaxRetries(field.getVarint().toInt())+            }+        }+    }++    @Throws(SabrProtocolException::class)+    private fun readString(data: ByteArray, number: Int): String? {+        var value: String? = null+        for (field in SabrProto.readFields(data)) {+            if (field.getNumber() == number &&+                field.getWireType() == SabrProto.WIRE_LENGTH_DELIMITED+            ) {+                value = field.getString()+            }+        }+        return value+    }++    @Throws(SabrProtocolException::class)+    private fun decodeError(data: ByteArray): String {+        var type: String? = null+        var code = 0+        for (field in SabrProto.readFields(data)) {+            if (field.getNumber() == 1 && field.getWireType() == SabrProto.WIRE_LENGTH_DELIMITED) {+                type = field.getString()+            } else if (field.getNumber() == 2 && field.getWireType() == SabrProto.WIRE_VARINT) {+                code = field.getVarint().toInt()+            }+        }+        return "type=" + (type ?: "null") + ", code=" + code+    }++    private fun describeGenericMessage(data: ByteArray): String {+        return try {+            SabrProto.summarizeFields(data)+        } catch (e: Exception) {+            "undecodable(" + data.size + " bytes)"+        }+    }+}
youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/protocol/SabrStreamingResponseReader.kt
diff --git a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/protocol/SabrStreamingResponseReader.kt b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/protocol/SabrStreamingResponseReader.ktnew file mode 100644index 0000000000..b759286ac1--- /dev/null+++ b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/protocol/SabrStreamingResponseReader.kt@@ -0,0 +1,205 @@+package org.schabi.newpipe.extractor.services.youtube.sabrng.protocol++import org.schabi.newpipe.extractor.services.youtube.sabrng.YoutubeSabrResponse+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.generated.SabrMediaHeader+import org.schabi.newpipe.extractor.services.youtube.sabrng.media.SabrMediaSegment+import org.schabi.newpipe.extractor.services.youtube.sabrng.media.SabrMediaSegmentCollector+import java.io.ByteArrayOutputStream+import java.io.File+import java.io.IOException+import java.io.InputStream++/**+ * Streaming counterpart of [SabrResponseDecoder.decode]: parse the UMP envelope from a stream one+ * part at a time, assembling MEDIA segments on the fly (via [SabrMediaSegmentCollector.Incremental])+ * so the big MEDIA payloads are never all held at once. Only the small control parts are kept and+ * decoded into a [YoutubeSabrResponse].+ */+object SabrStreamingResponseReader {+    private const val MAX_CONTROL_PARTS = 512+    private const val MAX_CONTROL_PAYLOAD_BYTES = 512 * 1024L++    /** Receives one completed media segment as it becomes available. */+    fun interface SegmentConsumer {+        @Throws(SabrProtocolException::class)+        fun accept(segment: SabrMediaSegment)+    }++    @JvmStatic+    @Throws(SabrProtocolException::class, IOException::class)+    fun read(input: InputStream): Result = read(input, null)++    /**+     * Streams completed segments directly to [segmentConsumer]. When a consumer is supplied,+     * completed segments are not retained by the result, bounding the response reader to one open+     * segment instead of the sum of every segment in the response.+     */+    @JvmStatic+    @Throws(SabrProtocolException::class, IOException::class)+    fun read(input: InputStream, segmentConsumer: SegmentConsumer?): Result =+        read(input, segmentConsumer, null, null)++    @JvmStatic+    @Throws(SabrProtocolException::class, IOException::class)+    fun read(+        input: InputStream,+        segmentConsumer: SegmentConsumer?,+        segmentStartConsumer: SegmentConsumer?,+        spoolDirectory: File?+    ): Result {+        val controlParts = ArrayList<UmpReader.UmpPart>()+        val partSummaries = ArrayList<String>()+        val segments = ArrayList<SabrMediaSegment>()+        var segmentCount = 0+        var mediaPayloadBytes = 0L+        var mediaPartPayloadBytes = 0L+        var controlPayloadBytes = 0L+        var totalPayloadBytes = 0L+        var maxPartBytes = 0L+        var maxMediaPartPayloadBytes = 0L+        var maxSegmentBytes = 0L+        // headerId -> total media bytes seen, so the decoded response passes the same integrity+        // check (getIntegrityIssues -> "missing-media") as the buffered path WITHOUT the bytes.+        val mediaBytesByHeaderId = HashMap<Int, Long>()+        val collector = SabrMediaSegmentCollector.Incremental(spoolDirectory)+        try {+            UmpReader.readPayloadsUntil(input) { type, size, payloadStream ->+                YoutubeSabrResponse.addPartSummary(partSummaries, type, size)+                maxPartBytes = Math.max(maxPartBytes, size.toLong())+                totalPayloadBytes += size+                if (type != SabrResponseDecoder.MEDIA &&+                    (controlParts.size >= MAX_CONTROL_PARTS ||+                        controlPayloadBytes + size > MAX_CONTROL_PAYLOAD_BYTES)+                ) {+                    throw SabrProtocolException("SABR control response exceeded Host limit")+                }+                when (type) {+                    SabrResponseDecoder.MEDIA_HEADER -> {+                        val payload = readPayloadBytes(payloadStream, size)+                        controlPayloadBytes += payload.size+                        // small (just the header) -> keep so the decoder records it (observeHeader).+                        controlParts.add(UmpReader.UmpPart(type, payload.size, payload))+                        try {+                            val started = collector.onMediaHeader(payload)+                            if (started != null && segmentStartConsumer != null) {+                                segmentStartConsumer.accept(started)+                            }+                        } catch (ignored: SabrProtocolException) {+                            if (!isMalformedMediaHeader(payload)) {+                                throw ignored+                            }+                            // decodeParts records the malformed header. Following MEDIA is left+                            // without an open header so integrity recovery requests a clean batch.+                        }+                    }+                    SabrResponseDecoder.MEDIA -> {+                        mediaPartPayloadBytes += size+                        if (size > 0) {+                            val headerId = payloadStream.read()+                            if (headerId < 0) {+                                throw SabrRecoverableException(+                                    "Unexpected EOF while reading SABR media header id"+                                )+                            }+                            val mediaBytes = size - 1+                            // big payload -> assemble into the open segment, do NOT retain.+                            collector.onMedia(headerId, payloadStream, mediaBytes)+                            maxMediaPartPayloadBytes =+                                Math.max(maxMediaPartPayloadBytes, mediaBytes.toLong())+                            mediaPayloadBytes += mediaBytes+                            mediaBytesByHeaderId[headerId] =+                                (mediaBytesByHeaderId[headerId] ?: 0L) + mediaBytes+                        }+                    }+                    SabrResponseDecoder.MEDIA_END -> {+                        val payload = readPayloadBytes(payloadStream, size)+                        controlPayloadBytes += payload.size+                        val segment = collector.onMediaEnd(payload)+                        controlParts.add(UmpReader.UmpPart(type, payload.size, payload))+                        if (segment != null) {+                            segmentCount+++                            maxSegmentBytes = Math.max(maxSegmentBytes, segment.getLength().toLong())+                            if (segmentConsumer == null) {+                                segments.add(segment)+                            } else {+                                segmentConsumer.accept(segment)+                            }+                        }+                    }+                    else -> {+                        val payload = readPayloadBytes(payloadStream, size)+                        controlPayloadBytes += payload.size+                        controlParts.add(UmpReader.UmpPart(type, payload.size, payload))+                    }+                }+                true+            }+        } finally {+            // Any header left open after EOF, cancellation or failure must wake a growing-file+            // reader. Completed segments have already been removed from the collector.+            collector.abort()+        }+        val decoded = SabrResponseDecoder.decodeParts(controlParts)+        decoded.setPartSummaries(partSummaries)+        for ((key, value) in mediaBytesByHeaderId) {+            decoded.addMediaBytes(key, value)+        }+        return Result(+            decoded, segments, segmentCount, mediaPayloadBytes, mediaPartPayloadBytes,+            controlPayloadBytes, totalPayloadBytes, maxPartBytes, maxMediaPartPayloadBytes,+            maxSegmentBytes+        )+    }++    @Throws(IOException::class)+    private fun readPayloadBytes(input: InputStream, size: Int): ByteArray {+        val output = ByteArrayOutputStream(size)+        val buffer = ByteArray(8192)+        var remaining = size+        while (remaining > 0) {+            val read = input.read(buffer, 0, Math.min(buffer.size, remaining))+            if (read < 0) {+                throw IOException("Unexpected EOF while reading UMP part data")+            }+            output.write(buffer, 0, read)+            remaining -= read+        }+        return output.toByteArray()+    }++    private fun isMalformedMediaHeader(payload: ByteArray): Boolean {+        return try {+            SabrMediaHeader.decode(payload)+            false+        } catch (e: SabrProtocolException) {+            true+        }+    }++    /** The decoded control response plus the segments assembled while streaming. */+    class Result internal constructor(+        private val probeResult: YoutubeSabrResponse,+        private val segments: List<SabrMediaSegment>,+        private val segmentCount: Int,+        private val mediaPayloadBytes: Long,+        private val mediaPartPayloadBytes: Long,+        private val controlPayloadBytes: Long,+        private val totalPayloadBytes: Long,+        private val maxPartBytes: Long,+        private val maxMediaPartPayloadBytes: Long,+        private val maxSegmentBytes: Long+    ) {+        fun getProbeResult(): YoutubeSabrResponse = probeResult+        fun getSegments(): List<SabrMediaSegment> = segments+        fun getSegmentCount(): Int = segmentCount+        fun getMediaPayloadBytes(): Long = mediaPayloadBytes+        fun getMediaPartPayloadBytes(): Long = mediaPartPayloadBytes+        fun getControlPayloadBytes(): Long = controlPayloadBytes+        fun getTotalPayloadBytes(): Long = totalPayloadBytes+        fun getMaxPartBytes(): Long = maxPartBytes+        fun getMaxMediaPartPayloadBytes(): Long = maxMediaPartPayloadBytes+        fun getMaxSegmentBytes(): Long = maxSegmentBytes+    }+}