Repository navigation
feat(hls): time relayed media bodies from first byte to last #30
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -94,6 +94,22 @@ public struct LiveTelemetry: Equatable, Sendable { | |
| /// Bytes pulled from the SOURCE in the session, across every demuxer it has had. The origin-side | ||
| /// counterpart to `networkTransferredBytes`, and the one that is about the same link on both paths. | ||
| public let demuxerBytesFetched: Int64 | ||
| /// Silo fork: on a relayed remote HLS load (`LoadOptions.httpRequestAuthorization`, or an origin the | ||
| /// system's trust refuses while `EngineTLS.serverTrustEvaluator` is set), the bytes of the media | ||
| /// bodies the relay received from the origin after each body's first chunk, as a running total for | ||
| /// the relay. The first chunk arrives before anything times it, so its bytes stay out. A body that | ||
| /// arrived in under 1 s, a subtitle rendition and a playlist do not count. nil without a relay; a | ||
| /// new load's relay starts again from 0. `relayMediaReceivingMs` is the time they took. | ||
| public let relayMediaReceivedBytes: Int64? | ||
| /// Silo fork: the milliseconds the bodies in `relayMediaReceivedBytes` spent arriving, each timed | ||
| /// from its first byte to its last, with time in which several were arriving counted once. The time | ||
| /// an origin takes to produce a segment before it answers is not in it, where | ||
| /// `networkThroughputMbps` (AVPlayer's access log on the loopback hop) reads that wait as transfer | ||
| /// time. The quotient of the two totals is a lower bound on the link's rate while it delivered. The | ||
| /// quotient of a difference between two readings is not: a body that reaches 1 s adds all its | ||
| /// bytes at once, while time it shared with a body counted earlier is already in the earlier | ||
| /// reading. | ||
| public let relayMediaReceivingMs: Int64? | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Low (docs). The doc block above these two properties has three problems:
Repair: give each property its own comment, say the first chunk's bytes stay out, and add the evaluator condition in both places. I'm fixing this in a commit on this branch. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 7d22c5f. Each property now has its own doc comment. The bytes comment says the first chunk stays out, and the trust case names |
||
| public let audioBridgeLiveBytes: Int | ||
| public let rssMb: Int | ||
|
|
||
|
|
@@ -120,6 +136,8 @@ public struct LiveTelemetry: Equatable, Sendable { | |
| serverBytesSentLifetime: Int64, | ||
| serverRequestCount: Int, | ||
| demuxerBytesFetched: Int64, | ||
| relayMediaReceivedBytes: Int64? = nil, | ||
| relayMediaReceivingMs: Int64? = nil, | ||
| audioBridgeLiveBytes: Int, | ||
| rssMb: Int | ||
| ) { | ||
|
|
@@ -145,6 +163,8 @@ public struct LiveTelemetry: Equatable, Sendable { | |
| self.serverBytesSentLifetime = serverBytesSentLifetime | ||
| self.serverRequestCount = serverRequestCount | ||
| self.demuxerBytesFetched = demuxerBytesFetched | ||
| self.relayMediaReceivedBytes = relayMediaReceivedBytes | ||
| self.relayMediaReceivingMs = relayMediaReceivingMs | ||
| self.audioBridgeLiveBytes = audioBridgeLiveBytes | ||
| self.rssMb = rssMb | ||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| import Foundation | ||
|
|
||
| /// Silo fork: how long a relay's media bodies spent arriving, and what arrived, counted only while | ||
| /// bytes were arriving. `LiveTelemetry.relayMediaReceivedBytes` / `relayMediaReceivingMs` publish it. | ||
| /// | ||
| /// On the native remote HLS route AVPlayer reads from the relay on 127.0.0.1, and its access log times | ||
| /// each request from when it was sent. An origin that produces a segment before it answers (an | ||
| /// encoder slower than real time, subtitle burn-in, a source read, a transcode node starting) holds | ||
| /// that request silent for seconds and then delivers the body at the link's full rate, so the access | ||
| /// log's `observedBitrate` reads the origin's work as a slow link. Here a body is timed from its first | ||
| /// byte to its last instead, on the relay's own URLSession, so the wait before the first byte never | ||
| /// counts. | ||
| /// | ||
| /// A body that arrives in under `minimumReceivingMs` does not count, in bytes or in time: a short body | ||
| /// on a warm connection, such as one HLS segment, arrives at the connection's burst rate, which can be | ||
| /// twice what the link sustains. The bytes of a body's first chunk do not count either, because they | ||
| /// arrived before anything timed them. Time in which several bodies were arriving counts once. These | ||
| /// three rules are Silo Android's `PlaybackThroughputMeter`'s. A pause inside a body does count, which | ||
| /// keeps the rate a lower bound. Unlike Android's windowed `takeKbps`, these are running totals, so a | ||
| /// host that diffs two readings can see a body that reached 1 s add its bytes without the time it | ||
| /// shared with a body counted before the earlier reading. | ||
| final class RelayTransferMeter: @unchecked Sendable { | ||
| struct Totals: Equatable, Sendable { | ||
| var bytes: Int64 = 0 | ||
| var receivingMs: Int64 = 0 | ||
| } | ||
|
|
||
| /// A body that receives for less than this does not count. | ||
| static let minimumReceivingMs: Int64 = 1_000 | ||
|
|
||
| /// One body being received. Its fields are the meter's, read and written under its lock. | ||
| final class Transfer { | ||
| fileprivate var firstMs: Int64? | ||
| fileprivate var lastMs: Int64 = 0 | ||
| /// Bytes after the first chunk. | ||
| fileprivate var bytes: Int64 = 0 | ||
| /// How far this body is already counted, once it is. | ||
| fileprivate var countedThroughMs: Int64? | ||
| fileprivate var countedBytes: Int64 = 0 | ||
| } | ||
|
|
||
| private let clock: @Sendable () -> Int64 | ||
| private let lock = NSLock() | ||
| private var counted = Totals() | ||
| /// The spans already counted, merged, oldest first. Only recent ones can overlap a new span, so | ||
| /// the list is trimmed to `coverageMemoryMs` behind the latest end. | ||
| private var covered: [(start: Int64, end: Int64)] = [] | ||
| private static let coverageMemoryMs: Int64 = 600_000 | ||
|
|
||
| init(clock: @escaping @Sendable () -> Int64 = RelayTransferMeter.uptimeMs) { | ||
| self.clock = clock | ||
| } | ||
|
|
||
| static func uptimeMs() -> Int64 { | ||
| Int64(DispatchTime.now().uptimeNanoseconds / 1_000_000) | ||
| } | ||
|
|
||
| func begin() -> Transfer { Transfer() } | ||
|
|
||
| /// Whether a response's body is media the player plays from, and so timed. A playlist is not, by | ||
| /// the same test the relay rewrites it by (a long VOD playlist can be served as `audio/mpegurl`). | ||
| /// A subtitle rendition is not either: a server extracting a track streams it for as long as the | ||
| /// extract takes, so its arrival says how fast the server works, not how fast the link is. | ||
| static func timesBody(url: URL, status: Int, contentType: String?) -> Bool { | ||
| guard (200..<300).contains(status), | ||
| !HLSOriginRelay.looksLikePlaylist(url: url, contentType: contentType) | ||
| else { return false } | ||
| let path = url.path.lowercased() | ||
| if subtitleSuffixes.contains(where: { path.hasSuffix($0) }) { return false } | ||
| let type = (contentType ?? "application/octet-stream") | ||
| .split(separator: ";").first.map { $0.trimmingCharacters(in: .whitespaces).lowercased() } ?? "" | ||
| return type.hasPrefix("video/") || type.hasPrefix("audio/") | ||
| || type == "application/mp4" || type == "application/octet-stream" | ||
|
Rhainland marked this conversation as resolved.
Resolved
|
||
| } | ||
|
|
||
| private static let subtitleSuffixes = [".vtt", ".webvtt", ".srt", ".ttml"] | ||
|
|
||
| /// `bytes` of a body arrived now. Called on the session's delegate queue as each chunk lands. | ||
| func received(_ bytes: Int, on transfer: Transfer) { | ||
| guard bytes > 0 else { return } | ||
| let now = clock() | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| guard let first = transfer.firstMs else { | ||
| transfer.firstMs = now | ||
| transfer.lastMs = now | ||
| return | ||
| } | ||
| transfer.bytes += Int64(bytes) | ||
| transfer.lastMs = max(transfer.lastMs, now) | ||
| guard transfer.lastMs - first >= Self.minimumReceivingMs else { return } | ||
| let from = transfer.countedThroughMs ?? first | ||
| counted.receivingMs += cover(from: from, to: transfer.lastMs) | ||
| counted.bytes += transfer.bytes - transfer.countedBytes | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Low (contract). The quotient of the running totals is a lower bound. The quotient of a difference between two readings is not. Trigger: one body has been counted through t=1000 ms, and a host reads the totals at that point. A second body began at 1 ms and reaches the 1 s minimum at 1001 ms. Impact: Silo Apple's Repair: I'm narrowing the parity comment and documenting the limit on the field and in There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Documented in 7d22c5f. The parity note now names the three rules shared with Android and says these are running totals, unlike its windowed |
||
| transfer.countedThroughMs = transfer.lastMs | ||
| transfer.countedBytes = transfer.bytes | ||
| } | ||
|
|
||
| /// Everything counted so far on this relay. | ||
| var totals: Totals { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| return counted | ||
| } | ||
|
|
||
| /// Adds `start...end` to the covered spans and returns how much of it was not covered yet. | ||
| private func cover(from start: Int64, to end: Int64) -> Int64 { | ||
| guard end > start else { return 0 } | ||
| var added = end - start | ||
| var merged = (start: start, end: end) | ||
| var kept: [(start: Int64, end: Int64)] = [] | ||
| kept.reserveCapacity(covered.count + 1) | ||
| for span in covered { | ||
| if span.end < merged.start || span.start > merged.end { | ||
| kept.append(span) | ||
| continue | ||
| } | ||
| added -= min(span.end, end) - max(span.start, start) | ||
| merged = (min(merged.start, span.start), max(merged.end, span.end)) | ||
| } | ||
| kept.append(merged) | ||
| kept.sort { $0.start < $1.start } | ||
| let horizon = (kept.last?.end ?? end) - Self.coverageMemoryMs | ||
| covered = kept.filter { $0.end >= horizon } | ||
| return max(0, added) | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Limit the claim about origin wait time.
If the origin pauses after sending the first chunk, the receiving time includes that pause. A host could therefore still interpret production time as a slow link. State that the timing excludes the wait before the first byte, but includes pauses within the body.