Skip to content
Open
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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ the public-API contract.

Changes this fork carries on top of upstream.

- **A relayed remote HLS load now reports what its media took to arrive, without the origin's wait.**

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

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.

A host that judged the link from `networkThroughputMbps` on this route read AVPlayer's access log
on the loopback hop, which times a segment request from when it was sent. A transcode server
answers only once its encoder has written the segment, so a slow encode (or a burn-in, a source
read, a node starting) read as a slow link, and Silo learned it as the device's bandwidth limit
for a day. `LiveTelemetry.relayMediaReceivedBytes` and `relayMediaReceivingMs` now carry the
relay's own count: media bodies timed from their first byte to their last, bodies under 1 s
left out, overlapping time counted once.

- **A Matroska title on the frame grid no longer flashes a frame at segment starts.** AE#886 moves
each 23.976 (or 29.97, 59.94, ...) DTS onto its 1/24000 slot, or rescales it when the PTS is off
the grid, but a held packet's duration was still measured on the 1 ms source time base. Where
Expand Down
20 changes: 20 additions & 0 deletions Sources/AetherEngine/Diagnostics/LiveTelemetry.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low (docs). The doc block above these two properties has three problems:

  • Swift attaches it to relayMediaReceivedBytes alone, so relayMediaReceivingMs has no documentation of its own in Quick Help or DocC.
  • It says the bytes are "counted from each body's first byte to its last", but received(_:on:) leaves out the first chunk's bytes. docs/api.md says so; this comment doesn't.
  • The trust case mounts a relay only while EngineTLS.serverTrustEvaluator is set (prepareRemoteHLSStandIn probes systemTrustRefuses only then). Without it, a refused origin gets nil here, which the text doesn't say. The same wording is in the docs/api.md row.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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 EngineTLS.serverTrustEvaluator, here and in the docs/api.md row. PublicAPIDocumentationTests, DocumentedConstantsTests and Scripts/check-doc-links.py pass on macOS (Xcode 27.2).

public let audioBridgeLiveBytes: Int
public let rssMb: Int

Expand All @@ -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
) {
Expand All @@ -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
}
Expand Down
3 changes: 3 additions & 0 deletions Sources/AetherEngine/Diagnostics/LiveTelemetrySampler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,7 @@ final class LiveTelemetrySampler {
}

let softwareCache = engine.softwarePacketCacheSnapshot
let relayTransfer = engine.remoteHLSSubtitleProxy?.server.relay?.mediaTransferTotals
let snapshot = LiveTelemetry(
instantBitrateMbps: instantBitrateMbps,
averageBitrateMbps: averageBitrateMbps,
Expand All @@ -452,6 +453,8 @@ final class LiveTelemetrySampler {
serverBytesSentLifetime: engine.serverBytesSentLifetime,
serverRequestCount: engine.serverRequestCount,
demuxerBytesFetched: demuxerBytes,
relayMediaReceivedBytes: relayTransfer?.bytes,
relayMediaReceivingMs: relayTransfer?.receivingMs,
audioBridgeLiveBytes: engine.audioBridgeLiveBytes,
rssMb: AetherEngine.residentMemoryMB()
)
Expand Down
28 changes: 25 additions & 3 deletions Sources/AetherEngine/Network/HLSOriginRelay.swift
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,13 @@ final class HLSOriginRelay: @unchecked Sendable {
private let heldBodyLimit: Int
private let pendingLimit: Int

/// Silo fork: times the media bodies this relay receives from the origin, from their first byte to
/// their last (`RelayTransferMeter`).
private let transferMeter = RelayTransferMeter()

/// What the media bodies this relay received took to arrive, counted only while they were arriving.
var mediaTransferTotals: RelayTransferMeter.Totals { transferMeter.totals }

/// Audit NET-107: fetches cut off because the consumer fell `pendingLimit` bytes behind. Diagnostics and tests.
var cappedFetchCount: Int {
stateLock.lock(); defer { stateLock.unlock() }
Expand Down Expand Up @@ -437,7 +444,7 @@ final class HLSOriginRelay: @unchecked Sendable {
}
}

private static func looksLikePlaylist(url: URL, contentType: String?) -> Bool {
static func looksLikePlaylist(url: URL, contentType: String?) -> Bool {
if let type = contentType?.lowercased(), type.contains("mpegurl") || type.contains("m3u") {
return true
}
Expand Down Expand Up @@ -673,7 +680,9 @@ final class HLSOriginRelay: @unchecked Sendable {
for: origin, label: "relay", timeout: slotWait)
defer { OriginRequestBudget.shared.release(ticket) }

let pump = UpstreamPump(hardCapBytes: pendingLimit) { [weak self] in
// A sidecar relay's bodies and a body read whole for the engine are not media the player streams.
let pump = UpstreamPump(hardCapBytes: pendingLimit,
transferMeter: rawResources || forceHold ? nil : transferMeter) { [weak self] in
guard let self else { return }
self.stateLock.lock()
self._cappedFetchCount += 1
Expand Down Expand Up @@ -868,9 +877,14 @@ private final class UpstreamPump: NSObject, URLSessionDataDelegate, @unchecked S

private let hardCapBytes: Int
private let onCapped: @Sendable () -> Void
private let transferMeter: RelayTransferMeter?
/// Set from the response head when the body is media, before its first byte; read on the same
/// delegate queue.
private var timedTransfer: RelayTransferMeter.Transfer?

init(hardCapBytes: Int, onCapped: @escaping @Sendable () -> Void) {
init(hardCapBytes: Int, transferMeter: RelayTransferMeter? = nil, onCapped: @escaping @Sendable () -> Void) {
self.hardCapBytes = hardCapBytes
self.transferMeter = transferMeter
self.onCapped = onCapped
}

Expand Down Expand Up @@ -970,6 +984,11 @@ private final class UpstreamPump: NSObject, URLSessionDataDelegate, @unchecked S
completionHandler(.cancel)
return
}
if let transferMeter, let url = http.url,
RelayTransferMeter.timesBody(url: url, status: http.statusCode,
contentType: http.value(forHTTPHeaderField: "Content-Type")) {
timedTransfer = transferMeter.begin()
}
condition.lock()
head = http
condition.broadcast()
Expand All @@ -978,6 +997,9 @@ private final class UpstreamPump: NSObject, URLSessionDataDelegate, @unchecked S
}

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
// Timed as it lands, before anything else happens to it: an arrival is a fact about the link
// whether or not the consumer is still there to take it.
if let timedTransfer { transferMeter?.received(data.count, on: timedTransfer) }
condition.lock()
var stop = consumerGaveUp || capped
var newlyCapped = false
Expand Down
127 changes: 127 additions & 0 deletions Sources/AetherEngine/Network/RelayTransferMeter.swift
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"
Comment thread
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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. cover adds only the 1 ms not already covered, but this line adds all of that body's bytes, so the next delta is about a second's worth of bytes over 1 ms.

Impact: Silo Apple's RelayPlanThroughput diffs readings per plan, so a plan that starts while two bodies overlap can read faster than the link. The effect is bounded and needs concurrent bodies. Silo's transcode HLS muxes audio into the video segments, so I don't expect it often there. Android's windowed takeKbps keeps an open request's whole span in the window that counts it, so it doesn't do this. The doc comment at line 18 says the two clients "report the same quantity", which overstates the parity.

Repair: I'm narrowing the parity comment and documenting the limit on the field and in docs/api.md in a commit on this branch. Changing the accounting itself is a maintainer decision.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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 takeKbps. relayMediaReceivingMs and the docs/api.md row say a difference between two readings is not a lower bound, and why. The accounting itself is unchanged; that stays a maintainer decision.

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)
}
}
5 changes: 5 additions & 0 deletions Tests/AetherEngineTests/DocumentedConstantsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ final class DocumentedConstantsTests: XCTestCase {
assertDocumented("Quarantine is bounded to 96 MiB and 10,000 packets", try documentation())
}

func testRelayMediaTimingMinimumMatchesDocumentation() throws {
XCTAssertEqual(RelayTransferMeter.minimumReceivingMs, 1_000)
assertDocumented("Bodies that arrived in under 1 s", try documentation())
}

func testAuthorizedResourceDeadlineMatchesDocumentation() throws {
XCTAssertEqual(HTTPRequestAuthorization.resourceTransferTimeout, 20)
assertDocumented("**20 second** deadline", try documentation())
Expand Down
Loading