Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 70 additions & 22 deletions .github/workflows/discord-app-release.yml
Original file line number Diff line number Diff line change
@@ -1,44 +1,92 @@
# For app repos (TypeType-Android, TypeType-IOS, TypeType-TV, TypeType-tvOS).
# Pre-releases (-beta.N, -rc.N) go to #🧪・releases-rc, stable releases go to #🚀・releases-main,
# with the release notes. Needs the secrets DISCORD_WEBHOOK_RC and DISCORD_WEBHOOK_MAIN.
#
# A release published by hand fires `release`. A release created by a build workflow with GITHUB_TOKEN never fires
# `release` (GitHub does not start workflows from GITHUB_TOKEN events), so `workflow_run` catches those: when a build
# that ran a release/publish job succeeds, the releases whose tag points at the commit it built are posted.
# `workflow_dispatch` posts one tag by hand.
name: Discord release notify

on:
release:
types: [published]
workflow_run:
workflows: ["iOS", "Android", "Android Beta", "Release"]
types: [completed]
workflow_dispatch:
inputs:
tag:
description: Release tag to post
required: true

permissions:
contents: read
actions: read

jobs:
notify:
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
steps:
- name: Find the releases to post
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
EVENT: ${{ github.event_name }}
RELEASE_TAG: ${{ github.event.release.tag_name }}
INPUT_TAG: ${{ inputs.tag }}
RUN_ID: ${{ github.event.workflow_run.id }}
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
run: |
set -euo pipefail
: > tags.txt
case "$EVENT" in
release) echo "$RELEASE_TAG" > tags.txt ;;
workflow_dispatch) echo "$INPUT_TAG" > tags.txt ;;
workflow_run)
ran=$(gh api "repos/$REPO/actions/runs/$RUN_ID/jobs" \
--jq '[.jobs[] | select((.name | test("release|publish"; "i")) and .conclusion == "success")] | length')
[ "$ran" -gt 0 ] || { echo "no release job ran"; exit 0; }
for tag in $(gh api "repos/$REPO/releases?per_page=10" \
--jq '.[] | select(.draft == false and .author.login == "github-actions[bot]") | .tag_name'); do
sha=$(gh api "repos/$REPO/commits/$tag" --jq .sha)
[ "$sha" = "$HEAD_SHA" ] && echo "$tag" >> tags.txt
done
;;
esac
cat tags.txt

- name: Post to Discord
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
WEBHOOK_RC: ${{ secrets.DISCORD_WEBHOOK_RC }}
WEBHOOK_MAIN: ${{ secrets.DISCORD_WEBHOOK_MAIN }}
PRERELEASE: ${{ github.event.release.prerelease }}
TAG: ${{ github.event.release.tag_name }}
RNAME: ${{ github.event.release.name }}
URL: ${{ github.event.release.html_url }}
BODY: ${{ github.event.release.body }}
REPO: ${{ github.repository }}
run: |
set -euo pipefail
if [ "$PRERELEASE" = "true" ]; then
WEBHOOK="$WEBHOOK_RC"; BOT="The Lab TV"; EMOJI="🧪"; COLOR=15105570; INTRO="Beta build, might break, have fun (・ω・)"
else
WEBHOOK="$WEBHOOK_MAIN"; BOT="Rocket TV"; EMOJI="🚀"; COLOR=5763719; INTRO="New release (。•̀ᴗ-)✧"
fi
[ -n "$WEBHOOK" ] || { echo "webhook secret not set"; exit 0; }
TITLE="${EMOJI} ${RNAME:-${REPO#*/} ${TAG}}"
jq -n \
--arg title "$TITLE" \
--arg url "$URL" \
--arg desc "$(printf '%s\n\n%s' "$INTRO" "${BODY:-}" | cut -c1-3900)" \
--argjson color "$COLOR" \
--arg bot "$BOT" \
'{username: $bot, embeds: [{title: $title, url: $url, description: $desc, color: $color}]}' \
> payload.json
curl -fsS -H "Content-Type: application/json" -d @payload.json "$WEBHOOK"
while read -r TAG; do
[ -n "$TAG" ] || continue
gh api "repos/$REPO/releases/tags/$TAG" > release.json
PRERELEASE=$(jq -r .prerelease release.json)
RNAME=$(jq -r '.name // ""' release.json)
URL=$(jq -r .html_url release.json)
BODY=$(jq -r '.body // ""' release.json)
if [ "$PRERELEASE" = "true" ]; then
WEBHOOK="$WEBHOOK_RC"; BOT="The Lab TV"; EMOJI="🧪"; COLOR=15105570; INTRO="Beta build, might break, have fun (・ω・)"
else
WEBHOOK="$WEBHOOK_MAIN"; BOT="Rocket TV"; EMOJI="🚀"; COLOR=5763719; INTRO="New release (。•̀ᴗ-)✧"
fi
[ -n "$WEBHOOK" ] || { echo "webhook secret not set"; exit 0; }
TITLE="${EMOJI} ${RNAME:-${REPO#*/} ${TAG}}"
jq -n \
--arg title "$TITLE" \
--arg url "$URL" \
--arg desc "$(printf '%s\n\n%s' "$INTRO" "${BODY:-}" | cut -c1-3900)" \
--argjson color "$COLOR" \
--arg bot "$BOT" \
'{username: $bot, embeds: [{title: $title, url: $url, description: $desc, color: $color}]}' \
> payload.json
curl -fsS -H "Content-Type: application/json" -d @payload.json "$WEBHOOK"
echo "posted $TAG"
done < tags.txt
4 changes: 2 additions & 2 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ android {

defaultConfig {
applicationId = "dev.typetype.android"
versionCode = 11126
versionName = "1.15.0-beta.1"
versionCode = 11127
versionName = "1.15.0-beta.2"
}

signingConfigs {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,40 @@ fun normalizePlaybackQuality(value: String): String {
return "${height}p"
}

// The speed each size needs to start and keep playing: about one and a half times what YouTube sends for it.
// Same table as the web player, so Auto picks the same size on both for the same connection.
private val SPEED_NEEDED_BITS_PER_SECOND = listOf(
2160 to 25_000_000L,
1440 to 13_000_000L,
1080 to 6_500_000L,
720 to 3_500_000L,
480 to 1_800_000L,
)
private const val SLOWEST_AUTO_HEIGHT = 360

fun speedQualityHeight(measuredBitsPerSecond: Long?): Int? {
if (measuredBitsPerSecond == null || measuredBitsPerSecond <= 0L) return null
return SPEED_NEEDED_BITS_PER_SECOND.firstOrNull { (_, needed) -> measuredBitsPerSecond >= needed }?.first
?: SLOWEST_AUTO_HEIGHT
}

fun effectivePlaybackQualityCap(
defaultQuality: String,
mobileDataQuality: String,
isMetered: Boolean,
measuredBitsPerSecond: Long? = null,
): String {
val normalizedDefault = normalizePlaybackQuality(defaultQuality)
if (!isMetered) return normalizedDefault.capHeightLabel()
val normalizedMobile = normalizePlaybackQuality(mobileDataQuality)
return "${minOf(normalizedDefault.capHeight(), normalizedMobile.capHeight())}p"
val speedHeight = speedQualityHeight(measuredBitsPerSecond)
?.takeIf { normalizedDefault == "auto" }
?: Int.MAX_VALUE
val wanted = if (isMetered) {
minOf(normalizedDefault.capHeight(), normalizePlaybackQuality(mobileDataQuality).capHeight())
} else {
normalizedDefault.capHeight()
}
return "${minOf(wanted, speedHeight)}p"
}

private fun String.capHeight(): Int =
if (this == "auto") 2160 else substringBefore('p').toIntOrNull() ?: 1080

private fun String.capHeightLabel(): String =
if (this == "auto") "2160p" else this
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package dev.typetype.android.domain.stream

import kotlin.math.abs

private val VIDEO_TIERS = listOf(144, 240, 360, 480, 720, 1080, 1440, 2160, 4320)

// The quality a picture is named after, as YouTube names it: a wide film in 3840x1608 is 2160p, 2048x858 is 1080p
// and a vertical 1080x1920 is 1080p. Raw heights would show a wide 4K film as 1608p and let a 1080p cap pick the
// 1440p picture.
fun videoTier(width: Int, height: Int): Int {
if (width <= 0 || height <= 0) return height.coerceAtLeast(0)
val wide = width.toLong() * 9L > height.toLong() * 16L
val lines = if (wide) width * 9 / 16 else minOf(width, height)
return VIDEO_TIERS.minBy { abs(it - lines) }
}

val StreamVideoSource.qualityTier: Int
get() = videoTier(width, height)
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,37 @@ class PlaybackQualityTest {
fun `quality names accept hdr suffixes`() {
assertEquals("1440p", normalizePlaybackQuality("1440p HDR"))
}

@Test
fun `auto follows the measured speed`() {
assertEquals("1080p", autoCap(measured = 8_000_000L))
assertEquals("720p", autoCap(measured = 4_000_000L))
assertEquals("360p", autoCap(measured = 900_000L))
assertEquals("2160p", autoCap(measured = 40_000_000L))
}

@Test
fun `auto keeps the screen cap until a speed is measured`() {
assertEquals("2160p", autoCap(measured = null))
assertEquals("2160p", autoCap(measured = 0L))
}

@Test
fun `a chosen quality ignores the measured speed`() {
assertEquals(
"1440p",
effectivePlaybackQualityCap("1440p", "1080p", isMetered = false, measuredBitsPerSecond = 2_000_000L),
)
}

@Test
fun `the mobile cap still applies under a fast measured speed`() {
assertEquals(
"720p",
effectivePlaybackQualityCap("auto", "720p", isMetered = true, measuredBitsPerSecond = 40_000_000L),
)
}

private fun autoCap(measured: Long?): String =
effectivePlaybackQualityCap("auto", "1080p", isMetered = false, measuredBitsPerSecond = measured)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package dev.typetype.android.domain.stream

import org.junit.Assert.assertEquals
import org.junit.Test

class VideoTierTest {
@Test
fun `a wide film is named after its width`() {
assertEquals(2160, videoTier(3840, 1608))
assertEquals(1440, videoTier(2560, 1072))
assertEquals(1080, videoTier(2048, 858))
assertEquals(1080, videoTier(1920, 804))
assertEquals(720, videoTier(1280, 536))
assertEquals(480, videoTier(854, 358))
}

@Test
fun `a standard or tall picture is named after its short side`() {
assertEquals(2160, videoTier(3840, 2160))
assertEquals(1080, videoTier(1080, 1920))
assertEquals(1080, videoTier(1440, 1080))
assertEquals(720, videoTier(960, 720))
}

@Test
fun `an unknown width keeps the height`() {
assertEquals(1080, videoTier(0, 1080))
assertEquals(0, videoTier(0, 0))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import dev.typetype.android.domain.preferences.RECOMMENDED_CODEC_KEY
import dev.typetype.android.domain.preferences.VP9_CODEC_KEY
import dev.typetype.android.domain.stream.StreamAudioSource
import dev.typetype.android.domain.stream.StreamVideoSource
import dev.typetype.android.domain.stream.qualityTier

internal fun List<StreamVideoSource>.pickVideo(
quality: String,
Expand Down Expand Up @@ -36,11 +37,11 @@ internal fun List<StreamVideoSource>.pickVideo(
}
if (targetHeight == null) return codecCandidates.maxWithOrNull(comparator)?.source
return codecCandidates
.filter { it.source.height <= targetHeight }
.filter { it.source.qualityTier <= targetHeight }
.maxWithOrNull(comparator)
?.source
?: codecCandidates.minWithOrNull(
compareBy<VideoCandidate> { it.source.height }
compareBy<VideoCandidate> { it.source.qualityTier }
.thenByDescending { it.decoder.rank }
.thenByDescending { it.source.codecReliability() },
)?.source
Expand Down Expand Up @@ -109,18 +110,18 @@ private data class VideoCandidate(
)

private val recommendedVideoComparator = compareBy<VideoCandidate> { it.decoder.rank }
.thenBy { it.source.height }
.thenBy { it.source.qualityTier }
.thenBy { it.smartCodecPriority() }
.thenBy { it.source.fps }
.thenBy { it.source.bitrate ?: 0 }

private val qualityFirstComparator = compareBy<VideoCandidate> { it.source.height }
private val qualityFirstComparator = compareBy<VideoCandidate> { it.source.qualityTier }
.thenBy { it.decoder.rank }
.thenBy { it.source.codecReliability() }
.thenBy { it.source.fps }
.thenBy { it.source.bitrate ?: 0 }

private val videoQualityComparator = compareBy<StreamVideoSource> { it.height }
private val videoQualityComparator = compareBy<StreamVideoSource> { it.qualityTier }
.thenBy { it.width }
.thenBy { it.bitrate ?: 0 }

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package dev.typetype.android.services

import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.annotation.OptIn
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.upstream.BandwidthMeter
import androidx.media3.exoplayer.upstream.DefaultBandwidthMeter
import dagger.hilt.android.qualifiers.ApplicationContext
import dev.typetype.android.data.network.PlaybackNetworkMonitor
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
@OptIn(UnstableApi::class)
class PlaybackBandwidthEstimate @Inject constructor(
@ApplicationContext context: Context,
private val networkMonitor: PlaybackNetworkMonitor,
) {
private val measured = MeasuredBandwidth()

// ExoPlayer reports every media transfer, SABR included, to this process-wide meter.
private val listener = BandwidthMeter.EventListener { elapsedMs, bytesTransferred, bitrateEstimate ->
measured.add(networkMonitor.snapshot().generation, elapsedMs.toLong(), bytesTransferred, bitrateEstimate)
}

init {
DefaultBandwidthMeter.getSingletonInstance(context)
.addEventListener(Handler(Looper.getMainLooper()), listener)
}

fun bitsPerSecond(): Long? = measured.bitsPerSecond(networkMonitor.snapshot().generation)
}

// DefaultBandwidthMeter keeps announcing its starting guess from the network type until it has seen 2 s or
// 512 KiB of transfers; only estimates past that point are measurements of this connection.
internal class MeasuredBandwidth {
private var networkGeneration = -1L
private var elapsedMs = 0L
private var bytes = 0L
private var estimate: Long? = null

@Synchronized
fun add(generation: Long, sampleElapsedMs: Long, sampleBytes: Long, bitrateEstimate: Long) {
if (generation != networkGeneration) {
networkGeneration = generation
elapsedMs = 0L
bytes = 0L
estimate = null
}
if (sampleElapsedMs <= 0L || sampleBytes <= 0L) return
elapsedMs += sampleElapsedMs
bytes += sampleBytes
if (elapsedMs >= MEASURED_AFTER_MS || bytes >= MEASURED_AFTER_BYTES) {
estimate = bitrateEstimate.takeIf { it > 0L }
}
}

@Synchronized
fun bitsPerSecond(generation: Long): Long? = estimate.takeIf { generation == networkGeneration }

private companion object {
const val MEASURED_AFTER_MS = 2_000L
const val MEASURED_AFTER_BYTES = 512L * 1024L
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class PlaybackQueueItemResolver @Inject constructor(
private val networkMonitor: PlaybackNetworkMonitor,
private val sabrPlaybackRepository: SabrPlaybackRepository,
private val codecSupport: DevicePlaybackCodecSupport,
private val bandwidthEstimate: PlaybackBandwidthEstimate,
) {

suspend fun resolve(videoUrl: String): Result<MediaItem> = captureQueueResult {
Expand All @@ -35,6 +36,7 @@ class PlaybackQueueItemResolver @Inject constructor(
defaultQuality = preferences.playerDefaultQuality,
mobileDataQuality = preferences.playerMobileDataQuality,
isMetered = networkMonitor.snapshot().isMetered,
measuredBitsPerSecond = bandwidthEstimate.bitsPerSecond(),
)
val stream = streamRepository.loadPlaybackStream(videoUrl).getOrThrow()
val selectedAudioKey = stream.initialAudioKey(
Expand Down
Loading