From 0f01786cb66e10f58e5bd5194a00f52d267bd571 Mon Sep 17 00:00:00 2001 From: MrFr3di Date: Tue, 1 Sep 2026 09:11:06 +0500 Subject: [PATCH] test(playback): rebase LL-HLS characterization with attribution --- .../LlHlsByteRangeCharacterizationTest.kt | 301 ++++++++++++++++++ .../androidx-media-testdata-LICENSE-2.0.txt | 214 +++++++++++++ 2 files changed, 515 insertions(+) create mode 100644 player/media3/src/androidTest/kotlin/app/muxtv/player/media3/LlHlsByteRangeCharacterizationTest.kt create mode 100644 player/media3/src/androidTest/third_party/androidx-media-testdata-LICENSE-2.0.txt diff --git a/player/media3/src/androidTest/kotlin/app/muxtv/player/media3/LlHlsByteRangeCharacterizationTest.kt b/player/media3/src/androidTest/kotlin/app/muxtv/player/media3/LlHlsByteRangeCharacterizationTest.kt new file mode 100644 index 000000000..ea206954d --- /dev/null +++ b/player/media3/src/androidTest/kotlin/app/muxtv/player/media3/LlHlsByteRangeCharacterizationTest.kt @@ -0,0 +1,301 @@ +package app.muxtv.player.media3 + +import android.content.Context +import android.os.Handler +import android.os.HandlerThread +import android.util.Base64 +import androidx.annotation.OptIn as AndroidXOptIn +import androidx.media3.common.PlaybackException +import androidx.media3.common.Player +import androidx.media3.common.util.UnstableApi +import androidx.media3.exoplayer.ExoPlayer +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import app.muxtv.network.MuxTvHttpClients +import com.google.common.truth.Truth.assertThat +import java.io.Closeable +import java.util.Collections +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference +import mockwebserver3.Dispatcher +import mockwebserver3.MockResponse +import mockwebserver3.MockWebServer +import mockwebserver3.RecordedRequest +import okio.Buffer +import org.junit.Test +import org.junit.runner.RunWith + +/** + * Characterization evidence for androidx/media#3350 through MuxTV's production HLS construction. + * + * The origin is fully local and contains no provider data. The init fragment and bounded media + * bytes come from AndroidX Media3's Apache-2.0 CMAF test corpus (`audio_init.mp4` and the first + * 512 bytes of `audio_2.m4s`). The playlist exposes those 512 bytes as a trailing LL-HLS part. + * + * On Media3 versions affected by #3350, FragmentedMp4Extractor consumes the complete bounded + * DataSpec and asks for more input. HlsMediaChunk stores nextLoadPosition == DataSpec.length and + * retries the same chunk. The retry calls DataSpec.subrange(length), which attempts to create an + * illegal zero-length DataSpec and surfaces an unexpected IllegalArgumentException before another + * HTTP open. This test locks that existing upstream failure signature; it is not a workaround. + */ +@RunWith(AndroidJUnit4::class) +@AndroidXOptIn(UnstableApi::class) +class LlHlsByteRangeCharacterizationTest { + private val context: Context = ApplicationProvider.getApplicationContext() + + @Test + fun byteRangeLlHlsPart_retriesIntoIllegalZeroLengthSubrange() { + LlHlsOrigin.start().use { origin -> + PlayerHarness(context).use { harness -> + harness.post { + val request = PlaybackSessionRequest( + profileId = "profile-ll-hls-evidence", + mediaId = "channel-ll-hls-evidence", + variantId = "variant-ll-hls-evidence", + locator = origin.playlistUrl(), + insecureHttpApproved = true, + mimeType = "application/x-mpegURL", + ) + harness.player.setMediaSource( + PlaybackMediaSourceFactory(context, MuxTvHttpClients()).create(request), + ) + harness.player.prepare() + harness.player.play() + } + + val error = harness.awaitPlayerError(ERROR_TIMEOUT_SECONDS) { + "requests=${origin.requests()}" + } + val causes = causeChain(error) + val illegalArgument = causes.filterIsInstance() + .firstOrNull() + + assertThat(illegalArgument).isNotNull() + val stack = checkNotNull(illegalArgument).stackTrace + assertThat( + stack.any { + it.className == "androidx.media3.datasource.DataSpec" && + it.methodName == "subrange" + }, + ).isTrue() + assertThat( + stack.any { + it.className == "androidx.media3.exoplayer.hls.HlsMediaChunk" && + it.methodName == "feedDataToExtractor" + }, + ).isTrue() + + val partRequests = origin.requests().filter { it.contains("GET /audio_2.m4s") } + assertThat(partRequests).containsExactly("GET /audio_2.m4s range=bytes=0-511") + } + } + } + + private fun causeChain(error: Throwable): List { + val result = mutableListOf() + var current: Throwable? = error + while (current != null && result.size < MAX_CAUSE_DEPTH) { + result += current + current = current.cause + } + return result + } + + private class PlayerHarness(context: Context) : Closeable { + private val thread = HandlerThread("ll-hls-characterization").apply { start() } + private val handler = Handler(thread.looper) + private val playerError = AtomicReference() + val player: ExoPlayer + + init { + val playerRef = AtomicReference() + post { + playerRef.set( + ExoPlayer.Builder(context) + .setLooper(thread.looper) + .build() + .also { exoPlayer -> + exoPlayer.addListener( + object : Player.Listener { + override fun onPlayerError(error: PlaybackException) { + playerError.set(error) + } + }, + ) + }, + ) + } + player = checkNotNull(playerRef.get()) + } + + fun post(block: () -> Unit) { + val latch = CountDownLatch(1) + val failure = AtomicReference() + handler.post { + try { + block() + } catch (throwable: Throwable) { + failure.set(throwable) + } finally { + latch.countDown() + } + } + check(latch.await(OPERATION_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + "player-thread operation timed out" + } + failure.get()?.let { throw it } + } + + fun awaitPlayerError( + timeoutSeconds: Long, + diagnostics: () -> String, + ): PlaybackException { + val deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds) + while (System.nanoTime() < deadlineNanos) { + playerError.get()?.let { return it } + Thread.sleep(POLL_INTERVAL_MILLIS) + } + throw AssertionError( + "LL-HLS fixture did not produce a player error within the deadline; ${diagnostics()}", + ) + } + + override fun close() { + post { player.release() } + thread.quitSafely() + } + } + + private class LlHlsOrigin private constructor() : Closeable { + private val requests = Collections.synchronizedList(mutableListOf()) + private val initSegment = Base64.decode(INIT_SEGMENT_BASE64, Base64.DEFAULT) + private val boundedMediaPart = Base64.decode(BOUNDED_MEDIA_PART_BASE64, Base64.DEFAULT) + private val server = MockWebServer().also { mockServer -> + mockServer.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + val path = request.url.encodedPath + requests += "${request.method} $path range=${request.headers["Range"] ?: ""}" + return when (path) { + "/fixture.m3u8" -> textResponse(PLAYLIST_CONTENT_TYPE, PLAYLIST) + "/audio_init.mp4" -> bytesResponse(INIT_CONTENT_TYPE, initSegment) + "/audio_2.m4s" -> mediaPartResponse(request) + else -> MockResponse.Builder().code(404).build() + } + } + } + } + + private fun mediaPartResponse(request: RecordedRequest): MockResponse { + val range = request.headers["Range"] + if (range != EXPECTED_MEDIA_RANGE) { + return MockResponse.Builder() + .code(416) + .addHeader("Content-Range", "bytes */$MEDIA_RESOURCE_SIZE") + .build() + } + check(boundedMediaPart.size == BOUNDED_MEDIA_PART_SIZE) + return MockResponse.Builder() + .code(206) + .addHeader("Content-Type", PART_CONTENT_TYPE) + .addHeader("Accept-Ranges", "bytes") + .addHeader( + "Content-Range", + "bytes 0-${BOUNDED_MEDIA_PART_SIZE - 1}/$MEDIA_RESOURCE_SIZE", + ) + .addHeader("Content-Length", boundedMediaPart.size.toString()) + .body(Buffer().write(boundedMediaPart)) + .build() + } + + fun playlistUrl(): String = server.url("/fixture.m3u8").toString() + + fun requests(): List = synchronized(requests) { requests.toList() } + + override fun close() { + server.close() + } + + companion object { + fun start(): LlHlsOrigin = LlHlsOrigin().also { it.server.start() } + + private const val PLAYLIST_CONTENT_TYPE = "application/vnd.apple.mpegurl" + private const val INIT_CONTENT_TYPE = "audio/mp4" + private const val PART_CONTENT_TYPE = "audio/mp4" + private const val BOUNDED_MEDIA_PART_SIZE = 512 + private const val MEDIA_RESOURCE_SIZE = 3811 + private const val EXPECTED_MEDIA_RANGE = "bytes=0-511" + + private val PLAYLIST = """ + #EXTM3U + #EXT-X-VERSION:9 + #EXT-X-TARGETDURATION:1 + #EXT-X-MEDIA-SEQUENCE:1 + #EXT-X-MAP:URI="audio_init.mp4" + #EXT-X-PART-INF:PART-TARGET=0.255420 + #EXT-X-PART:URI="audio_2.m4s",DURATION=0.255420,INDEPENDENT=YES,BYTERANGE="512@0" + """.trimIndent() + "\n" + + // Exact androidx/media 1.10.1 libraries/test_data CMAF audio_init.mp4, blob + // 4d0cbdc5b0298a19f8eca80a5503e8d14b7c25c6. + private val INIT_SEGMENT_BASE64 = """ + AAAAJGZ0eXBtcDQxAAAAAGlzbzhp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RyZXgA + AAAAAAAAAQAAAAEAAAQAAAAAAAAAAAA= + """.trimIndent() + + // First 512 bytes of androidx/media 1.10.1 CMAF audio_2.m4s, blob + // 40111ff3c411240cd3ada1a7478f58d164a2011d. Decodes to exactly 512 bytes. + private val BOUNDED_MEDIA_PART_BASE64 = """ + AAAAJHN0eXBtcDQxAAAAAGlzbzhpc29tbXA0MWRhc2hjbWZzAAAALHNpZHgAAAAAAAAAAQAArEQA + ACwAAAAAAAAAAAEAAA6TAAAsAJAAAAAAAACobW9vZgAAABBtZmhkAAAAAAAAAAIAAACQdHJhZgAA + ABx0ZmhkAAIAKgAAAAEAAAABAAAEAAAAAAAAAAAQdGZkdAAAAAAAADAAAAAAQHRydW4AAAIBAAAA + CwAAALAAAAFhAAABKgAAAVcAAAFPAAABLgAAAU4AAAE8AAABOgAAATgAAAE9AAABSwAAABxzYmdw + AAAAAHJvbGwAAAABAAAACwAAAAEAAA3rbWRhdAD0OK6tQkKrP/w8f/prWs9p7e06/p7/47+euePX + ndSib1mudV4sqpA1NK0srSqXqN0kQkoivqShNM+38/Y2fsbSC4lVaVX9IMbOGHOGMkuqrlxJsEij + y74tgIsfFllniXzFvVJXDnZhEsFxMEWHTUbFEBYg5sH6LvTiDsTHE8dNl+bJTDydSVSRs97Wnq6t + 6FlusoGtt/ZWm7OvRX3TCJgxIBMfCos5yv8svil7031CEHyRWHwxdWzsUa5SNWNYE4UWpGm44qMQ + AwQ8VkErK2r1gFSQCw0X0OSvCo5pkMVo6rea0I8ixO70HdRWZApG9pwgShQ0ErDicqwRagrIjcI= + """.trimIndent() + + private fun textResponse(contentType: String, body: String): MockResponse = + MockResponse.Builder() + .code(200) + .addHeader("Content-Type", contentType) + .body(Buffer().writeUtf8(body)) + .build() + + private fun bytesResponse(contentType: String, body: ByteArray): MockResponse = + MockResponse.Builder() + .code(200) + .addHeader("Content-Type", contentType) + .addHeader("Content-Length", body.size.toString()) + .addHeader("Accept-Ranges", "bytes") + .body(Buffer().write(body)) + .build() + } + } + + private companion object { + const val ERROR_TIMEOUT_SECONDS = 20L + const val OPERATION_TIMEOUT_SECONDS = 30L + const val POLL_INTERVAL_MILLIS = 50L + const val MAX_CAUSE_DEPTH = 16 + } +} diff --git a/player/media3/src/androidTest/third_party/androidx-media-testdata-LICENSE-2.0.txt b/player/media3/src/androidTest/third_party/androidx-media-testdata-LICENSE-2.0.txt new file mode 100644 index 000000000..1678404ef --- /dev/null +++ b/player/media3/src/androidTest/third_party/androidx-media-testdata-LICENSE-2.0.txt @@ -0,0 +1,214 @@ +AndroidX Media test-data attribution + +MuxTV's LL-HLS characterization test incorporates bytes from the AndroidX Media test corpus at commit: +2bc207851df311340767e913931ca7b28cab1794 + +Source assets: +- libraries/test_data/src/test/assets/media/cmaf/multi-segment/audio_init.mp4 + blob 4d0cbdc5b0298a19f8eca80a5503e8d14b7c25c6 +- libraries/test_data/src/test/assets/media/cmaf/multi-segment/audio_2.m4s + blob 40111ff3c411240cd3ada1a7478f58d164a2011d (first 512 bytes only) + +These test-data bytes are redistributed under the AndroidX Media repository's Apache License 2.0. The license text is reproduced below without modification. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License.