Skip to content

StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.

fixed download speed test

David Nashashe368d7037326
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/InternetSpeedTestRunner.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/InternetSpeedTestRunner.kt
index 203298ed..0226a194 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/InternetSpeedTestRunner.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/InternetSpeedTestRunner.kt
@@ -12,6 +12,7 @@ import kotlinx.coroutines.withContext
import okhttp3.CacheControl
import okhttp3.OkHttpClient
import okhttp3.Request
+import okio.Buffer
import java.util.concurrent.TimeUnit
enum class InternetSpeedTestTransport {
@@ -38,7 +39,7 @@ sealed interface InternetSpeedTestResult {
@Singleton
class InternetSpeedTestRunner @Inject constructor(
@ApplicationContext private val context: Context,
- private val okHttpClient: OkHttpClient
+ private val downloadSpeedProbe: InternetDownloadSpeedProbe
) {
suspend fun run(): InternetSpeedTestResult = withContext(Dispatchers.IO) {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
@@ -52,56 +53,18 @@ class InternetSpeedTestRunner @Inject constructor(
val measuredAtMs = System.currentTimeMillis()
runCatching {
- val bytesToDownload = 4_000_000L
- val request = Request.Builder()
- .url("https://speed.cloudflare.com/__down?bytes=$bytesToDownload&seed=${SystemClock.elapsedRealtime()}")
- .cacheControl(CacheControl.Builder().noCache().noStore().build())
- .build()
- val startedAtNs = SystemClock.elapsedRealtimeNanos()
- okHttpClient.newCall(request).execute().use { response ->
- if (!response.isSuccessful) {
- error("Speed test failed with HTTP ${response.code}")
- }
- val body = response.body ?: error("Speed test returned no data")
- val bytesRead = body.source().use { source ->
- var total = 0L
- while (!source.exhausted()) {
- total += source.read(source.buffer, 8_192)
- .takeIf { it > 0 }
- ?: 0L
- }
- total
- }
- val elapsedSeconds = (SystemClock.elapsedRealtimeNanos() - startedAtNs)
- .coerceAtLeast(TimeUnit.MILLISECONDS.toNanos(1)) / 1_000_000_000.0
- val megabitsPerSecond = ((bytesRead * 8.0) / elapsedSeconds) / 1_000_000.0
- InternetSpeedTestResult.Success(
- InternetSpeedTestSnapshot(
- megabitsPerSecond = megabitsPerSecond,
- recommendedMaxVideoHeight = recommendMaxVideoHeight(megabitsPerSecond),
- measuredAtMs = measuredAtMs,
- transport = transport,
- isEstimated = false
- )
+ val megabitsPerSecond = downloadSpeedProbe.measureMegabitsPerSecond()
+ InternetSpeedTestResult.Success(
+ InternetSpeedTestSnapshot(
+ megabitsPerSecond = megabitsPerSecond,
+ recommendedMaxVideoHeight = recommendMaxVideoHeight(megabitsPerSecond),
+ measuredAtMs = measuredAtMs,
+ transport = transport,
+ isEstimated = false
)
- }
+ )
}.getOrElse {
- val fallbackMbps = capabilities.linkDownstreamBandwidthKbps
- .takeIf { it > 0 }
- ?.div(1000.0)
- if (fallbackMbps != null) {
- InternetSpeedTestResult.Success(
- InternetSpeedTestSnapshot(
- megabitsPerSecond = fallbackMbps,
- recommendedMaxVideoHeight = recommendMaxVideoHeight(fallbackMbps),
- measuredAtMs = measuredAtMs,
- transport = transport,
- isEstimated = true
- )
- )
- } else {
- InternetSpeedTestResult.Error(it.message ?: "Speed test failed")
- }
+ InternetSpeedTestResult.Error(it.message ?: "Speed test failed")
}
}
@@ -123,4 +86,58 @@ class InternetSpeedTestRunner @Inject constructor(
else -> InternetSpeedTestTransport.OTHER
}
}
-}
\ No newline at end of file
+}
+
+class InternetDownloadSpeedProbe @Inject constructor(
+ private val okHttpClient: OkHttpClient
+) {
+ private var urlFactory: (Long) -> String = { bytesToDownload ->
+ "https://speed.cloudflare.com/__down?bytes=$bytesToDownload&seed=${SystemClock.elapsedRealtime()}"
+ }
+ private var nanoTime: () -> Long = SystemClock::elapsedRealtimeNanos
+
+ internal constructor(
+ okHttpClient: OkHttpClient,
+ urlFactory: (Long) -> String,
+ nanoTime: () -> Long
+ ) : this(okHttpClient) {
+ this.urlFactory = urlFactory
+ this.nanoTime = nanoTime
+ }
+
+ fun measureMegabitsPerSecond(bytesToDownload: Long = DEFAULT_DOWNLOAD_BYTES): Double {
+ val request = Request.Builder()
+ .url(urlFactory(bytesToDownload))
+ .cacheControl(CacheControl.Builder().noCache().noStore().build())
+ .build()
+ val startedAtNs = nanoTime()
+ okHttpClient.newCall(request).execute().use { response ->
+ if (!response.isSuccessful) {
+ error("Speed test failed with HTTP ${response.code}")
+ }
+ val body = response.body ?: error("Speed test returned no data")
+ val bytesRead = body.source().use { source ->
+ val sink = Buffer()
+ var total = 0L
+ while (true) {
+ val read = source.read(sink, READ_CHUNK_BYTES)
+ if (read == -1L) break
+ total += read
+ sink.clear()
+ }
+ total
+ }
+ if (bytesRead <= 0L) {
+ error("Speed test returned no data")
+ }
+ val elapsedSeconds = (nanoTime() - startedAtNs)
+ .coerceAtLeast(TimeUnit.MILLISECONDS.toNanos(1)) / 1_000_000_000.0
+ return ((bytesRead * 8.0) / elapsedSeconds) / 1_000_000.0
+ }
+ }
+
+ private companion object {
+ const val DEFAULT_DOWNLOAD_BYTES = 8_000_000L
+ const val READ_CHUNK_BYTES = 16_384L
+ }
+}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/settings/InternetDownloadSpeedProbeTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/settings/InternetDownloadSpeedProbeTest.kt
new file mode 100644
index 00000000..15383b30
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/ui/screens/settings/InternetDownloadSpeedProbeTest.kt
@@ -0,0 +1,67 @@
+package com.streamvault.app.ui.screens.settings
+
+import com.google.common.truth.Truth.assertThat
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Protocol
+import okhttp3.Response
+import okhttp3.ResponseBody.Companion.toResponseBody
+import org.junit.Test
+
+class InternetDownloadSpeedProbeTest {
+ @Test
+ fun `measureMegabitsPerSecond measures bytes read over elapsed time`() {
+ var currentTimeNs = 0L
+ var requestedUrl: String? = null
+ val client = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ requestedUrl = chain.request().url.toString()
+ Response.Builder()
+ .request(chain.request())
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(ByteArray(1_000_000).toResponseBody("application/octet-stream".toMediaType()))
+ .build()
+ }
+ .build()
+ val probe = InternetDownloadSpeedProbe(
+ okHttpClient = client,
+ urlFactory = { bytes -> "https://example.test/speed?bytes=$bytes" },
+ nanoTime = {
+ val value = currentTimeNs
+ currentTimeNs += 1_000_000_000L
+ value
+ }
+ )
+
+ val result = probe.measureMegabitsPerSecond(bytesToDownload = 1_000_000L)
+
+ assertThat(result).isWithin(0.001).of(8.0)
+ assertThat(requestedUrl).isEqualTo("https://example.test/speed?bytes=1000000")
+ }
+
+ @Test
+ fun `measureMegabitsPerSecond fails instead of inventing a link speed estimate`() {
+ val client = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ Response.Builder()
+ .request(chain.request())
+ .protocol(Protocol.HTTP_1_1)
+ .code(503)
+ .message("Unavailable")
+ .body("".toResponseBody(null))
+ .build()
+ }
+ .build()
+ val probe = InternetDownloadSpeedProbe(
+ okHttpClient = client,
+ urlFactory = { "https://example.test/speed" },
+ nanoTime = { 0L }
+ )
+
+ val failure = runCatching { probe.measureMegabitsPerSecond() }.exceptionOrNull()
+
+ assertThat(failure).hasMessageThat().contains("HTTP 503")
+ }
+}
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 50cc37b3..a7f89490 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -29,6 +29,7 @@ All notable product changes are recorded in this document.
- Fixed provider onboarding URL handling so bare-host Xtream and Stalker server inputs resolve their protocol before validation and duplicate checks, allowing auto-detected `http://` or `https://` URLs to save correctly.
- Fixed default Stalker player requests to use MAG-style playback defaults, including `Lavf53.32.100` as the player User-Agent plus explicit `Accept`, `Connection`, and `Host` headers.
- Fixed Live TV favorites, recents, and custom-group ordered lists still collapsing SD/HD/FHD channel variants after grouped variants were disabled.
+- Fixed download speed test
### Added