youpipe: port PipePipe #92 SABR rewrite (media segment, UMP reader, request/response)
- Commit
6c47b0d2084b701d9b6853be3c4cfdb792c73b05- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-16 17:19 UTC (3 months ago)
- Parents
55ffd70
Diff
youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrRequest.kt
diff --git a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrRequest.kt b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrRequest.ktnew file mode 100644index 0000000000..79e81037c9--- /dev/null+++ b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrRequest.kt@@ -0,0 +1,112 @@+package org.schabi.newpipe.extractor.services.youtube.sabrng++/** Immutable description of one SABR transaction. */+class YoutubeSabrRequest private constructor(+ tracks: Collection<Track>,+ playbackState: PlaybackState,+ private val selectedTracks: Boolean+) {+ private val tracks: List<Track>+ private val playbackState: PlaybackState++ init {+ require(tracks.isNotEmpty()) { "SABR request must contain at least one track" }+ val copy = ArrayList<Track>(tracks.size)+ var audioFormat: YoutubeSabrInfo.Format? = null+ var videoFormat: YoutubeSabrInfo.Format? = null+ for (track in tracks) {+ when {+ track.getFormat().isAudio() -> {+ require(audioFormat == null) {+ "SABR request must not contain multiple audio tracks"+ }+ audioFormat = track.getFormat()+ }+ track.getFormat().isVideo() -> {+ require(videoFormat == null) {+ "SABR request must not contain multiple video tracks"+ }+ videoFormat = track.getFormat()+ }+ else -> throw IllegalArgumentException(+ "SABR request format has no track type: itag=" + track.getFormat().getItag()+ )+ }+ copy.add(track)+ }+ require(+ !(audioFormat != null && videoFormat != null &&+ audioFormat.getItag() == videoFormat.getItag())+ ) { "SABR audio/video formats must be distinct" }+ this.tracks = java.util.Collections.unmodifiableList(copy)+ this.playbackState = playbackState+ }++ internal fun getTracks(): List<Track> = tracks+ internal fun getPlaybackState(): PlaybackState = playbackState+ internal fun hasSelectedTracks(): Boolean = selectedTracks++ internal fun getAudioTrack(): Track? = tracks.firstOrNull { it.getFormat().isAudio() }+ internal fun getVideoTrack(): Track? = tracks.firstOrNull { it.getFormat().isVideo() }++ class Track private constructor(+ private val format: YoutubeSabrInfo.Format,+ private val timeline: YoutubeSabrFormatTimeline?,+ private val bufferedThrough: Int+ ) {+ init {+ require(bufferedThrough >= 0) {+ "SABR buffered-through sequence must not be negative"+ }+ }++ internal fun getFormat(): YoutubeSabrInfo.Format = format+ internal fun getTimeline(): YoutubeSabrFormatTimeline? = timeline+ internal fun getBufferedThrough(): Int = bufferedThrough++ companion object {+ @JvmStatic+ fun of(+ format: YoutubeSabrInfo.Format,+ timeline: YoutubeSabrFormatTimeline?,+ bufferedThrough: Int+ ): Track = Track(format, timeline, bufferedThrough)+ }+ }++ internal class PlaybackState(private val playerTimeMs: Long, private val playbackRate: Float) {+ fun getPlayerTimeMs(): Long = playerTimeMs+ fun getPlaybackRate(): Float = playbackRate+ }++ companion object {+ /**+ * Prepares format timelines around a playback position without declaring selected tracks.+ * Media returned alongside initialization segments may be retained by the caller.+ */+ @JvmStatic+ fun preparation(+ playerTimeMs: Long,+ preferredFormats: Collection<YoutubeSabrInfo.Format>+ ): YoutubeSabrRequest {+ require(playerTimeMs >= 0) { "SABR player time must not be negative" }+ val tracks = ArrayList<Track>(preferredFormats.size)+ for (format in preferredFormats) {+ tracks.add(Track.of(format, null, 0))+ }+ return YoutubeSabrRequest(tracks, PlaybackState(playerTimeMs, 1.0f), false)+ }++ /** Requests media for the active tracks in their preferred response order. */+ @JvmStatic+ fun playback(+ playerTimeMs: Long,+ playbackRate: Float,+ tracks: Collection<Track>+ ): YoutubeSabrRequest {+ require(playerTimeMs >= 0) { "SABR player time must not be negative" }+ require(playbackRate > 0) { "SABR playback rate must be positive" }+ return YoutubeSabrRequest(tracks, PlaybackState(playerTimeMs, playbackRate), true)+ }+ }+}
youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrResponse.kt
diff --git a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrResponse.kt b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrResponse.ktnew file mode 100644index 0000000000..9f5b667e3c--- /dev/null+++ b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/YoutubeSabrResponse.kt@@ -0,0 +1,278 @@+package org.schabi.newpipe.extractor.services.youtube.sabrng++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+import org.schabi.newpipe.extractor.services.youtube.sabrng.media.SabrMediaSegment+import org.schabi.newpipe.extractor.services.youtube.sabrng.protocol.UmpReader+import java.util.Collections++/** The complete HTTP, UMP control and media result of one SABR request. */+class YoutubeSabrResponse {+ private var info: YoutubeSabrInfo? = null+ private var segments: List<SabrMediaSegment> = emptyList()+ private var segmentCount = 0+ private var responseCode = 0+ private var contentType = ""+ private var responseBytes: Long = 0+ private var mediaPayloadBytes: Long = 0+ private var mediaPartPayloadBytes: Long = 0+ private var controlPayloadBytes: Long = 0+ private var totalPayloadBytes: Long = 0+ private var maxPartBytes: Long = 0+ private var maxMediaPartPayloadBytes: Long = 0+ private var maxSegmentBytes: Long = 0+ private var requestElapsedMs: Long = 0+ private var firstSegmentElapsedMs: Long = -1++ private val parts = ArrayList<UmpReader.UmpPart>()+ private val partSummaries = ArrayList<String>()+ private val wireFieldSummaries = ArrayList<String>()+ private val formatInitializationMetadata = ArrayList<SabrFormatInitializationMetadata>()+ private val mediaHeaders = ArrayList<SabrMediaHeader>()+ private val sabrContextUpdates = ArrayList<ByteArray>()+ private val liveMetadata = ArrayList<ByteArray>()+ private val mediaBytesByHeaderId = LinkedHashMap<Int, Long>()+ private val mediaEndHeaderIds = ArrayList<Int>()+ private val unknownPartTypes = ArrayList<Int>()+ private val malformedParts = ArrayList<String>()+ private val genericPartDescriptions = LinkedHashMap<Int, MutableList<String>>()+ private var redirectUrl: String? = null+ private var sabrError: String? = null+ private var nextRequestPolicy: ByteArray? = null+ private var sabrContextSendingPolicy: ByteArray? = null+ private var streamProtectionStatus = -1+ private var streamProtectionMaxRetries = -1+ private var backoffTimeMs = -1+ private var reloadRequested = false++ internal fun complete(+ requestInfo: YoutubeSabrInfo,+ responseSegments: List<SabrMediaSegment>,+ responseSegmentCount: Int,+ httpResponseCode: Int,+ responseContentType: String,+ rawResponseBytes: Long,+ rawMediaPayloadBytes: Long,+ rawMediaPartPayloadBytes: Long,+ rawControlPayloadBytes: Long,+ rawTotalPayloadBytes: Long,+ largestPartBytes: Long,+ largestMediaPartPayloadBytes: Long,+ largestSegmentBytes: Long,+ elapsedMs: Long,+ firstMediaElapsedMs: Long+ ) {+ info = requestInfo+ segments = responseSegments+ segmentCount = responseSegmentCount+ responseCode = httpResponseCode+ contentType = responseContentType+ responseBytes = rawResponseBytes+ mediaPayloadBytes = rawMediaPayloadBytes+ mediaPartPayloadBytes = rawMediaPartPayloadBytes+ controlPayloadBytes = rawControlPayloadBytes+ totalPayloadBytes = rawTotalPayloadBytes+ maxPartBytes = largestPartBytes+ maxMediaPartPayloadBytes = largestMediaPartPayloadBytes+ maxSegmentBytes = largestSegmentBytes+ requestElapsedMs = elapsedMs+ firstSegmentElapsedMs = firstMediaElapsedMs+ }++ fun addPart(part: UmpReader.UmpPart) {+ parts.add(part)+ addPartSummary(partSummaries, part.getType(), part.getSize())+ }++ fun setPartSummaries(summaries: List<String>) {+ partSummaries.clear()+ partSummaries.addAll(summaries)+ }++ fun addUnknownPartType(type: Int) {+ unknownPartTypes.add(type)+ }++ fun addWireFieldSummary(type: Int, summary: String) {+ wireFieldSummaries.add("$type={$summary}")+ }++ fun addGenericPartDescription(type: Int, description: String) {+ genericPartDescriptions.getOrPut(type) { ArrayList() }.add(description)+ }++ fun addMalformedPart(type: Int, size: Int, error: SabrProtocolException) {+ if (malformedParts.size >= MAX_MALFORMED_PARTS) return+ val message = error.message.toString()+ malformedParts.add(+ "$type:$size:" + if (message.length > MAX_MALFORMED_MESSAGE_CHARS) {+ message.substring(0, MAX_MALFORMED_MESSAGE_CHARS)+ } else {+ message+ }+ )+ }++ fun addFormatInitializationMetadata(value: SabrFormatInitializationMetadata) {+ formatInitializationMetadata.add(value)+ }++ fun addMediaHeader(value: SabrMediaHeader) {+ mediaHeaders.add(value)+ }++ fun addSabrContextUpdate(data: ByteArray) {+ sabrContextUpdates.add(data.clone())+ }++ fun addLiveMetadata(data: ByteArray) {+ liveMetadata.add(data.clone())+ }++ fun addMediaBytes(headerId: Int, bytes: Long) {+ mediaBytesByHeaderId[headerId] = (mediaBytesByHeaderId[headerId] ?: 0L) + bytes+ }++ fun addMediaEndHeaderId(headerId: Int) {+ mediaEndHeaderIds.add(headerId)+ }++ fun setRedirectUrl(value: String?) {+ redirectUrl = value+ }++ fun setSabrError(value: String?) {+ sabrError = value+ }++ fun setNextRequestPolicy(data: ByteArray) {+ nextRequestPolicy = data.clone()+ }++ fun setSabrContextSendingPolicy(data: ByteArray) {+ sabrContextSendingPolicy = data.clone()+ }++ fun setStreamProtectionStatus(value: Int) {+ streamProtectionStatus = value+ }++ fun setStreamProtectionMaxRetries(value: Int) {+ streamProtectionMaxRetries = value+ }++ fun setBackoffTimeMs(value: Int) {+ backoffTimeMs = value+ }++ fun setReloadRequested(value: Boolean) {+ reloadRequested = value+ }++ fun getInfo(): YoutubeSabrInfo = info!!+ fun getSegments(): List<SabrMediaSegment> = segments+ fun getSegmentCount(): Int = segmentCount+ fun getResponseCode(): Int = responseCode+ fun getContentType(): String = contentType+ fun getResponseBytes(): Long = responseBytes+ 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+ fun getRequestElapsedMs(): Long = requestElapsedMs+ fun getFirstSegmentElapsedMs(): Long = firstSegmentElapsedMs+ fun getParts(): List<UmpReader.UmpPart> = Collections.unmodifiableList(parts)+ fun getFormatInitializationMetadata(): List<SabrFormatInitializationMetadata> =+ Collections.unmodifiableList(formatInitializationMetadata)++ fun getMediaHeaders(): List<SabrMediaHeader> = Collections.unmodifiableList(mediaHeaders)+ fun getSabrContextUpdates(): List<ByteArray> = Collections.unmodifiableList(sabrContextUpdates)+ fun getLiveMetadata(): List<ByteArray> = Collections.unmodifiableList(liveMetadata)+ fun getRedirectUrl(): String? = redirectUrl+ fun getSabrError(): String? = sabrError+ fun getNextRequestPolicy(): ByteArray? = nextRequestPolicy?.clone()+ fun getSabrContextSendingPolicy(): ByteArray? = sabrContextSendingPolicy?.clone()+ fun getStreamProtectionStatus(): Int = streamProtectionStatus+ fun getStreamProtectionMaxRetries(): Int = streamProtectionMaxRetries+ fun getBackoffTimeMs(): Int = backoffTimeMs+ fun isReloadRequested(): Boolean = reloadRequested+ fun hasMedia(): Boolean = mediaHeaders.isNotEmpty() || mediaBytesByHeaderId.isNotEmpty()+ fun isNoMediaResponse(): Boolean = !hasMedia()+ fun isPolicyOnlyResponse(): Boolean = isNoMediaResponse() && nextRequestPolicy != null+ fun isAttestationRequired(): Boolean = streamProtectionStatus == ATTESTATION_REQUIRED+ fun isAttestationPending(): Boolean = streamProtectionStatus == ATTESTATION_PENDING++ fun getIntegrityIssues(): List<String> {+ val issues = ArrayList<String>()+ val headerIds = ArrayList<Int>()+ for (header in mediaHeaders) {+ if (headerIds.contains(header.getHeaderId())) {+ issues.add("duplicate-media-header:" + header.getHeaderId())+ }+ headerIds.add(header.getHeaderId())+ val bytes = mediaBytesByHeaderId[header.getHeaderId()]+ if (bytes == null) {+ issues.add("missing-media:" + header.getHeaderId())+ } else if (header.getContentLength() >= 0 && bytes != header.getContentLength()) {+ issues.add(+ "length-mismatch:" + header.getHeaderId() + ":expected=" ++ header.getContentLength() + ":actual=" + bytes+ )+ }+ if (!mediaEndHeaderIds.contains(header.getHeaderId())) {+ issues.add("missing-media-end:" + header.getHeaderId())+ }+ }+ for (id in mediaBytesByHeaderId.keys) {+ if (!headerIds.contains(id)) issues.add("media-without-header:$id")+ }+ for (id in mediaEndHeaderIds) {+ if (!headerIds.contains(id)) issues.add("media-end-without-header:$id")+ }+ return issues+ }++ fun summarizeForDiagnostics(): String =+ "parts=" + partSummaries + ", wireFields=" + wireFieldSummaries ++ ", controls=" + genericPartDescriptions + ", mediaHeaders=" + mediaHeaders.size ++ ", mediaBytes=" + mediaBytesByHeaderId + ", mediaEnds=" + mediaEndHeaderIds ++ ", integrity=" + getIntegrityIssues() + ", malformedParts=" + malformedParts ++ ", unknownParts=" + unknownPartTypes + ", protection=" ++ streamProtectionStatus + '/' + streamProtectionMaxRetries ++ ", backoffMs=" + backoffTimeMs + ", reload=" + reloadRequested++ fun summarizeNoMediaResponse(): String =+ "parts=" + parts.size + ", status=" + streamProtectionStatus ++ ", maxRetries=" + streamProtectionMaxRetries + ", backoffMs=" + backoffTimeMs ++ ", policy=" + (nextRequestPolicy != null) + ", reload=" + reloadRequested ++ ", redirect=" + (redirectUrl != null && redirectUrl!!.isNotEmpty()) ++ ", error=" + (sabrError ?: "null")++ companion object {+ const val ATTESTATION_PENDING = 2+ const val ATTESTATION_REQUIRED = 3+ private const val MAX_MALFORMED_PARTS = 16+ private const val MAX_MALFORMED_MESSAGE_CHARS = 256++ @JvmStatic+ fun addPartSummary(summaries: MutableList<String>, type: Int, size: Int) {+ val value = "$type:$size"+ if (summaries.isEmpty()) {+ summaries.add(value)+ return+ }+ val lastIndex = summaries.size - 1+ val last = summaries[lastIndex]+ when {+ last == value -> summaries[lastIndex] = value + "x2"+ last.startsWith(value + 'x') -> summaries[lastIndex] = value + 'x' ++ (last.substring(value.length + 1).toInt() + 1)+ else -> summaries.add(value)+ }+ }+ }+}
youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/media/SabrMediaSegment.kt
diff --git a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/media/SabrMediaSegment.kt b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/media/SabrMediaSegment.ktnew file mode 100644index 0000000000..0c1b73d8ea--- /dev/null+++ b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/media/SabrMediaSegment.kt@@ -0,0 +1,293 @@+package org.schabi.newpipe.extractor.services.youtube.sabrng.media++import org.schabi.newpipe.extractor.services.youtube.sabrng.generated.SabrMediaHeader+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.File+import java.io.FileInputStream+import java.io.IOException+import java.io.InputStream+import java.io.InterruptedIOException+import java.io.RandomAccessFile++/** One decoded SABR media (or initialization) segment, held in memory or spooled to disk. */+class SabrMediaSegment private constructor(+ private val header: SabrMediaHeader,+ private val data: ByteArray?,+ private val file: File?,+ private val length: Int,+ private val progressiveState: ProgressiveFileState?+) {+ internal constructor(header: SabrMediaHeader, data: ByteArray) :+ this(header, data, null, data.size, null)++ internal constructor(header: SabrMediaHeader, file: File, length: Int) :+ this(header, null, file, length, null)++ fun getHeader(): SabrMediaHeader = header++ /**+ * Read-only: callers must not mutate the returned array. Disk-backed segments are loaded only+ * for legacy callers; playback should use [openStream] to avoid pulling large media segments+ * back onto the Java heap.+ */+ fun getData(): ByteArray {+ data?.let { return it }+ try {+ openStream().use { input ->+ ByteArrayOutputStream(length).use { output ->+ val buffer = ByteArray(COPY_BUFFER_SIZE)+ var read: Int+ while (input.read(buffer).also { read = it } != -1) {+ output.write(buffer, 0, read)+ }+ return output.toByteArray()+ }+ }+ } catch (e: IOException) {+ throw IllegalStateException("Could not read disk-backed SABR media segment", e)+ }+ }++ @Throws(IOException::class)+ fun openStream(): InputStream {+ if (data != null) {+ return ByteArrayInputStream(data)+ }+ if (file == null) {+ throw IOException("SABR media segment has no backing data")+ }+ if (progressiveState != null) {+ progressiveState.throwIfFailed()+ try {+ return ProgressiveFileInputStream(file, progressiveState)+ } catch (e: IOException) {+ progressiveState.throwIfFailed()+ throw e+ }+ }+ return FileInputStream(file)+ }++ fun isDiskBacked(): Boolean = file != null++ fun isComplete(): Boolean = progressiveState == null || progressiveState.isComplete()++ fun hasFailed(): Boolean = progressiveState != null && progressiveState.hasFailed()++ internal fun onBytesWritten(count: Int) {+ progressiveState?.onBytesWritten(count)+ }++ internal fun completeProgressive() {+ progressiveState?.complete()+ }++ fun failProgressive(failure: IOException) {+ progressiveState?.fail(failure)+ }++ fun delete() {+ failProgressive(IOException("SABR media segment was discarded"))+ if (file != null && !file.delete() && file.exists()) {+ file.deleteOnExit()+ }+ }++ fun getLength(): Int = length++ internal fun getFile(): File? = file++ /** Internal bridge for media assembly implementations living in the media subpackage. */+ object InternalAccess {+ @JvmStatic+ fun fromBytes(header: SabrMediaHeader, data: ByteArray): SabrMediaSegment =+ SabrMediaSegment(header, data)++ @JvmStatic+ fun fromFile(header: SabrMediaHeader, file: File, length: Int): SabrMediaSegment =+ SabrMediaSegment(header, file, length)++ @JvmStatic+ fun progressive(header: SabrMediaHeader, file: File, length: Int): SabrMediaSegment =+ SabrMediaSegment(header, null, file, length, ProgressiveFileState(length))++ @JvmStatic+ fun onBytesWritten(segment: SabrMediaSegment, count: Int) = segment.onBytesWritten(count)++ @JvmStatic+ fun completeProgressive(segment: SabrMediaSegment) = segment.completeProgressive()++ @JvmStatic+ fun failProgressive(segment: SabrMediaSegment, failure: IOException) =+ segment.failProgressive(failure)+ }++ internal class ProgressiveFileState(private val expectedLength: Int) {+ private var bytesWritten = 0+ private var complete = false+ private var failure: IOException? = null++ @Synchronized+ fun onBytesWritten(count: Int) {+ if (count <= 0 || complete || failure != null) {+ return+ }+ bytesWritten += count+ (this as Object).notifyAll()+ }++ @Synchronized+ fun complete() {+ if (failure == null) {+ complete = true+ }+ (this as Object).notifyAll()+ }++ @Synchronized+ fun fail(exception: IOException) {+ if (!complete && failure == null) {+ failure = exception+ }+ (this as Object).notifyAll()+ }++ @Synchronized+ fun isComplete(): Boolean = complete++ @Synchronized+ fun hasFailed(): Boolean = failure != null++ @Synchronized+ @Throws(IOException::class)+ fun awaitAvailable(position: Long, reader: ProgressiveFileInputStream): Int {+ var readable = readableBytes(position)+ while (readable <= 0 && !complete && failure == null && !reader.closed) {+ try {+ (this as Object).wait()+ } catch (e: InterruptedException) {+ Thread.currentThread().interrupt()+ val interrupted = InterruptedIOException("Interrupted waiting for SABR media bytes")+ interrupted.initCause(e)+ throw interrupted+ }+ readable = readableBytes(position)+ }+ if (reader.closed) {+ throw InterruptedIOException("SABR media stream was closed")+ }+ failure?.let { throw it }+ return if (complete) Math.max(0, (bytesWritten - position).toInt()) else readable+ }++ @Synchronized+ @Throws(IOException::class)+ fun available(position: Long): Int {+ failure?.let { throw it }+ return if (complete) {+ Math.max(0, (bytesWritten - position).toInt())+ } else {+ readableBytes(position)+ }+ }++ private fun readableBytes(position: Long): Int {+ val available = Math.max(0, (bytesWritten - position).toInt())+ if (!complete && bytesWritten >= expectedLength && position + available >= expectedLength) {+ // Keep one byte unavailable until MEDIA_END validates the segment. Media3 knows the+ // declared DataSource length and may never issue a separate EOF read.+ return Math.max(0, available - 1)+ }+ return available+ }++ @Synchronized+ fun signalReaders() {+ (this as Object).notifyAll()+ }++ @Synchronized+ @Throws(IOException::class)+ fun throwIfFailed() {+ failure?.let { throw it }+ }+ }++ internal class ProgressiveFileInputStream @Throws(IOException::class) constructor(+ file: File,+ private val state: ProgressiveFileState+ ) : InputStream() {+ private val input: RandomAccessFile = RandomAccessFile(file, "r")+ private var position: Long = 0++ @Volatile+ var closed: Boolean = false+ private set++ @Throws(IOException::class)+ override fun read(): Int {+ val one = ByteArray(1)+ val read = read(one, 0, 1)+ return if (read < 0) -1 else one[0].toInt() and 0xff+ }++ @Throws(IOException::class)+ override fun read(bytes: ByteArray, offset: Int, count: Int): Int {+ if (closed) {+ throw IOException("SABR media stream is closed")+ }+ if (count == 0) {+ return 0+ }+ while (true) {+ val available = state.awaitAvailable(position, this)+ if (available <= 0) {+ return -1+ }+ input.seek(position)+ val read = input.read(bytes, offset, Math.min(count, available))+ if (read > 0) {+ position += read+ return read+ }+ }+ }++ @Throws(IOException::class)+ override fun skip(count: Long): Long {+ if (count <= 0) {+ return 0+ }+ val available = state.awaitAvailable(position, this)+ if (available <= 0) {+ return 0+ }+ val skipped = Math.min(count, available.toLong())+ position += skipped+ input.seek(position)+ return skipped+ }++ @Throws(IOException::class)+ override fun available(): Int {+ if (closed) {+ return 0+ }+ return state.available(position)+ }++ @Throws(IOException::class)+ override fun close() {+ if (!closed) {+ closed = true+ state.signalReaders()+ input.close()+ }+ }+ }++ companion object {+ private const val COPY_BUFFER_SIZE = 8192+ }+}
youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/protocol/UmpReader.kt
diff --git a/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/protocol/UmpReader.kt b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/protocol/UmpReader.ktnew file mode 100644index 0000000000..95bae766a3--- /dev/null+++ b/youpipe/extractor/src/main/kotlin/org/schabi/newpipe/extractor/services/youtube/sabrng/protocol/UmpReader.kt@@ -0,0 +1,254 @@+package org.schabi.newpipe.extractor.services.youtube.sabrng.protocol++import org.schabi.newpipe.extractor.services.youtube.sabrng.exception.SabrProtocolException+import java.io.EOFException+import java.io.IOException+import java.io.InputStream+import java.io.InterruptedIOException++/**+ * Reader for YouTube's UMP envelope. UMP uses its own compact integer format, not protobuf varints.+ */+object UmpReader {++ /** Receives one UMP part at a time (used by [readStreaming]). */+ fun interface PartConsumer {+ @Throws(SabrProtocolException::class, IOException::class)+ fun accept(type: Int, payload: ByteArray)+ }++ /** Receives one UMP part and returns false when the caller has enough data. */+ fun interface StoppablePartConsumer {+ @Throws(SabrProtocolException::class, IOException::class)+ fun accept(type: Int, payload: ByteArray): Boolean+ }++ /** Receives one UMP part payload as a bounded stream. The consumer may stop at part boundary. */+ fun interface StoppablePayloadConsumer {+ @Throws(SabrProtocolException::class, IOException::class)+ fun accept(type: Int, size: Int, payload: InputStream): Boolean+ }++ /**+ * Stream the UMP envelope: read one part (type, size, payload) at a time from [in] and hand it+ * to [consumer], so the whole response body is never held in memory at once. The stream is+ * consumed but NOT closed (caller owns it).+ */+ @JvmStatic+ @Throws(SabrProtocolException::class, IOException::class)+ fun readStreaming(input: InputStream, consumer: PartConsumer) {+ readStreamingUntil(input) { type, payload ->+ consumer.accept(type, payload)+ true+ }+ }++ /**+ * Like [readStreaming], but stops at a part boundary when [consumer] returns false. The caller+ * owns and closes the stream.+ */+ @JvmStatic+ @Throws(SabrProtocolException::class, IOException::class)+ fun readStreamingUntil(input: InputStream, consumer: StoppablePartConsumer) {+ readPayloadsUntil(input) { type, size, payload ->+ consumer.accept(type, readExactly(payload, size))+ }+ }++ /**+ * Stream the UMP envelope while exposing each payload as a bounded stream. This lets callers+ * consume large MEDIA parts without allocating one byte[] for the whole part.+ */+ @JvmStatic+ @Throws(SabrProtocolException::class, IOException::class)+ fun readPayloadsUntil(input: InputStream, consumer: StoppablePayloadConsumer) {+ while (true) {+ throwIfInterrupted()+ val first = input.read()+ if (first < 0) {+ return // clean EOF at a part boundary -> done+ }+ val type = readUmpInt(input, first)+ val size = readUmpInt(input, readByteOrThrow(input))+ if (type < 0 || size < 0) {+ throw SabrProtocolException("Invalid UMP part header")+ }+ val payload = BoundedInputStream(input, size)+ val keepGoing = consumer.accept(type, size, payload)+ payload.drain()+ if (!keepGoing) {+ return+ }+ }+ }++ // UMP compact int, given the already-read first byte. Mirrors Cursor.readUmpInt.+ @Throws(SabrProtocolException::class, IOException::class)+ private fun readUmpInt(input: InputStream, first: Int): Int {+ if (first < 0) {+ throw EOFException("Unexpected EOF in UMP integer")+ }+ if (first < 128) {+ return first+ }+ if (first < 192) {+ return (first and 0x3f) + 64 * readByteOrThrow(input)+ }+ if (first < 224) {+ return (first and 0x1f) + 32 * (readByteOrThrow(input) + 256 * readByteOrThrow(input))+ }+ if (first < 240) {+ return (first and 0x0f) + 16 * (readByteOrThrow(input) ++ 256 * (readByteOrThrow(input) + 256 * readByteOrThrow(input)))+ }+ return readByteOrThrow(input) + 256 * (readByteOrThrow(input) ++ 256 * (readByteOrThrow(input) + 256 * readByteOrThrow(input)))+ }++ @Throws(SabrProtocolException::class, IOException::class)+ private fun readByteOrThrow(input: InputStream): Int {+ throwIfInterrupted()+ val b = input.read()+ if (b < 0) {+ throw EOFException("Unexpected EOF in UMP integer")+ }+ return b+ }++ @Throws(SabrProtocolException::class, IOException::class)+ private fun readExactly(input: InputStream, length: Int): ByteArray {+ if (length < 0) {+ throw SabrProtocolException("Invalid UMP part length")+ }+ throwIfInterrupted()+ val result = ByteArray(length)+ var offset = 0+ while (offset < length) {+ throwIfInterrupted()+ val read = input.read(result, offset, length - offset)+ if (read < 0) {+ throw EOFException("Unexpected EOF while reading UMP part data")+ }+ offset += read+ }+ return result+ }++ @Throws(IOException::class)+ private fun throwIfInterrupted() {+ if (Thread.currentThread().isInterrupted) {+ throw InterruptedIOException("Interrupted while reading UMP stream")+ }+ }++ @JvmStatic+ @Throws(SabrProtocolException::class)+ fun readAll(data: ByteArray): List<UmpPart> {+ val cursor = Cursor(data)+ val parts = ArrayList<UmpPart>()+ while (!cursor.isDone()) {+ val type = cursor.readUmpInt()+ val size = cursor.readUmpInt()+ if (type < 0 || size < 0) {+ throw SabrProtocolException("Invalid UMP part header")+ }+ parts.add(UmpPart(type, size, cursor.readBytes(size)))+ }+ return parts+ }++ class UmpPart(private val type: Int, private val size: Int, private val data: ByteArray) {+ fun getType(): Int = type+ fun getSize(): Int = size+ fun getData(): ByteArray = data.clone()+ fun getRawData(): ByteArray = data+ }++ private class BoundedInputStream(+ private val source: InputStream,+ size: Int+ ) : InputStream() {+ private var remaining: Int = size++ @Throws(IOException::class)+ override fun read(): Int {+ throwIfInterrupted()+ if (remaining <= 0) {+ return -1+ }+ val value = source.read()+ if (value < 0) {+ throw EOFException("Unexpected EOF while reading UMP part data")+ }+ remaining--+ return value+ }++ @Throws(IOException::class)+ override fun read(buffer: ByteArray, offset: Int, length: Int): Int {+ throwIfInterrupted()+ if (remaining <= 0) {+ return -1+ }+ val read = source.read(buffer, offset, Math.min(length, remaining))+ if (read < 0) {+ throw EOFException("Unexpected EOF while reading UMP part data")+ }+ remaining -= read+ return read+ }++ @Throws(IOException::class)+ fun drain() {+ val buffer = ByteArray(8192)+ while (remaining > 0) {+ read(buffer, 0, Math.min(buffer.size, remaining))+ }+ }+ }++ private class Cursor(private val data: ByteArray) {+ private var offset = 0++ fun isDone(): Boolean = offset >= data.size++ @Throws(SabrProtocolException::class)+ fun readUmpInt(): Int {+ val first = readUnsignedByte()+ if (first < 128) {+ return first+ }+ if (first < 192) {+ return (first and 0x3f) + 64 * readUnsignedByte()+ }+ if (first < 224) {+ return (first and 0x1f) + 32 * (readUnsignedByte() + 256 * readUnsignedByte())+ }+ if (first < 240) {+ return (first and 0x0f) + 16 * (readUnsignedByte() ++ 256 * (readUnsignedByte() + 256 * readUnsignedByte()))+ }+ return readUnsignedByte() + 256 * (readUnsignedByte() ++ 256 * (readUnsignedByte() + 256 * readUnsignedByte()))+ }++ @Throws(SabrProtocolException::class)+ fun readBytes(length: Int): ByteArray {+ if (length < 0 || offset + length > data.size) {+ throw SabrProtocolException("Unexpected EOF while reading UMP part data")+ }+ val result = ByteArray(length)+ System.arraycopy(data, offset, result, 0, length)+ offset += length+ return result+ }++ @Throws(SabrProtocolException::class)+ private fun readUnsignedByte(): Int {+ if (offset >= data.size) {+ throw SabrProtocolException("Unexpected EOF in UMP integer")+ }+ return data[offset++].toInt() and 0xff+ }+ }+}