diff --git a/bench/browser/page/media.ts b/bench/browser/page/media.ts index 6b8da1dce82..79c2f4a86d5 100644 --- a/bench/browser/page/media.ts +++ b/bench/browser/page/media.ts @@ -1,5 +1,5 @@ /** Publish a synthetic picture with @moq/publish and watch it with @moq/watch through the relay. */ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import * as Moq from "@moq/net"; import * as Publish from "@moq/publish"; import * as Watch from "@moq/watch"; @@ -70,7 +70,7 @@ async function publish(config: Media): Promise { codec: config.codec, frameRate: config.fps, maxPixels: config.width * config.height, - join: Milli(config.keyframe_ms), + join: Duration.millis(config.keyframe_ms), maxBitrate: config.bitrate, }, }); diff --git a/bench/browser/page/stats.ts b/bench/browser/page/stats.ts index 35890deb2bd..3283a20b746 100644 --- a/bench/browser/page/stats.ts +++ b/bench/browser/page/stats.ts @@ -6,7 +6,7 @@ * receive shape's publisher dials once with `Moq.Connection.connect`, which runs no loop, so it * adds the same delivery work to every variant without sampling of its own. */ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import * as Moq from "@moq/net"; import { Session } from "@moq/qmux"; import { check, payload } from "../fixture.ts"; @@ -177,7 +177,7 @@ async function receive(config: Sampling): Promise { const request = origin.follow(Moq.Path.from(`${config.path}/live`)); cleanup.push(() => request.close()); const broadcast = await active(request); - const subscriber = broadcast.track("data").subscribe({ delay: { max: Milli(1000) } }); + const subscriber = broadcast.track("data").subscribe({ delay: { max: Duration.millis(1000) } }); cleanup.push(() => subscriber.close()); const reader = received.push(0) - 1; readers.push( diff --git a/bench/browser/page/transport.ts b/bench/browser/page/transport.ts index d188ee28dc2..0fa732feff5 100644 --- a/bench/browser/page/transport.ts +++ b/bench/browser/page/transport.ts @@ -1,5 +1,5 @@ /** Publisher and consumer roles for the @moq/net stream path over a real WebTransport session. */ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import * as Moq from "@moq/net"; import { check, payload } from "../fixture.ts"; import { longTasks, nextTask } from "./observe.ts"; @@ -35,7 +35,10 @@ async function publish(config: Transport): Promise { const publication = origin.route(Moq.Path.from(config.path), { hidden: true }); const producer = publication.broadcast; // Retention covers the whole run, so a slow consumer cannot lose a group to eviction. - const track = producer.createTrack("data", { timescale: Moq.Time.Timescale.MILLI, maxAge: Milli(600_000) }); + const track = producer.createTrack("data", { + timescale: Moq.Time.Timescale.MILLI, + maxAge: Duration.millis(600_000), + }); const demand = track.demand().wanted; publication.announce(); const connection = await Moq.Connection.connect({ @@ -92,7 +95,9 @@ async function consume(config: Transport): Promise { if (!broadcast) throw new Error("consume before prepare"); const groups = Math.ceil(config.frames / config.group); const start = performance.now(); - const subscriber = broadcast.track("data").subscribe({ delay: { max: Milli(600_000) }, order: "ascending" }); + const subscriber = broadcast + .track("data") + .subscribe({ delay: { max: Duration.millis(600_000) }, order: "ascending" }); cleanup.push(() => subscriber.close()); let frames = 0; let bytes = 0; diff --git a/demo/carla/web/src/player.ts b/demo/carla/web/src/player.ts index a0d389658f0..988da952457 100644 --- a/demo/carla/web/src/player.ts +++ b/demo/carla/web/src/player.ts @@ -10,7 +10,7 @@ * @module */ -import { Milli, Nano } from "@moq/clock"; +import { Duration } from "@moq/clock"; import * as Moq from "@moq/net"; import { COLLISION_ALERT_MS, collisionAge, collisionLabel, diverged, divergence } from "./feedback.ts"; import { drawDivergence, drawDriveHud, drawGuide } from "./guides.ts"; @@ -720,7 +720,7 @@ export function mount(root: ShadowRoot, connection: Moq.Connection, origin: Moq. frame = requestAnimationFrame(tick); } signals.cleanup(() => cancelAnimationFrame(frame)); - signals.interval(step, Nano.fromMilli(Milli(250))); + signals.interval(step, Duration.millis(250)); // --- Wheel status chip + calibration dialog. --- let calibration: Calibration | undefined; @@ -1118,7 +1118,7 @@ export function mount(root: ShadowRoot, connection: Moq.Connection, origin: Moq. // A collision's age is wall clock, not a status field, so it needs its own // tick: without one the callout would freeze on a truck that stops moving // and therefore stops changing its snapshot. - this.#signals.interval(() => this.#renderCollision(this.truck.status.peek()), Nano.fromMilli(Milli(1000))); + this.#signals.interval(() => this.#renderCollision(this.truck.status.peek()), Duration.millis(1000)); // Repaint on layout/resize (the initial effect run happens before layout, // so the overlay has zero size until the first observation fires). diff --git a/demo/carla/web/src/truck.ts b/demo/carla/web/src/truck.ts index f88f9c26ad4..aecdbfbc5d1 100644 --- a/demo/carla/web/src/truck.ts +++ b/demo/carla/web/src/truck.ts @@ -9,7 +9,7 @@ * * @module */ -import { Milli, Nano } from "@moq/clock"; +import { Duration } from "@moq/clock"; import * as Json from "@moq/json"; import * as Moq from "@moq/net"; import * as Watch from "@moq/watch"; @@ -44,7 +44,7 @@ interface Command { /** A driver session: pending until the truck accepts, `null` once the dial or the session failed. */ type Session = Moq.Signals.Signal; -const CONTROL_HEARTBEAT = Milli(250); +const CONTROL_HEARTBEAT = Duration.millis(250); const MAX_PENDING_ACKS = 64; const encoder = new TextEncoder(); const decoder = new TextDecoder(); @@ -120,7 +120,7 @@ export class Truck { this.#signals.run(this.#runActive.bind(this)); this.#signals.run(this.#runControlLease.bind(this)); this.#signals.run(this.#runRespawn.bind(this)); - this.#signals.interval(() => this.#heartbeat(), Nano.fromMilli(CONTROL_HEARTBEAT)); + this.#signals.interval(() => this.#heartbeat(), CONTROL_HEARTBEAT); // Video pipeline. this.broadcast = new Watch.Broadcast({ @@ -313,11 +313,11 @@ export class Truck { #timestamps(): { label: string; ts: number }[] { const entries: { label: string; ts: number }[] = []; const received = this.sync.out.timestamp.peek(); - if (received != null) entries.push({ label: "received", ts: received }); + if (received != null) entries.push({ label: "received", ts: received.asMillis() }); const decoded = this.videoDecoder.out.timestamp.peek(); - if (decoded != null) entries.push({ label: "decoded", ts: decoded }); + if (decoded != null) entries.push({ label: "decoded", ts: decoded.asMillis() }); const rendered = this.videoRenderer.out.timestamp.peek(); - if (rendered != null) entries.push({ label: "rendered", ts: rendered }); + if (rendered != null) entries.push({ label: "rendered", ts: rendered.asMillis() }); return entries; } diff --git a/demo/web/src/index.ts b/demo/web/src/index.ts index c5128d3a9e9..812d9fdd959 100644 --- a/demo/web/src/index.ts +++ b/demo/web/src/index.ts @@ -17,7 +17,7 @@ */ import "./highlight"; -import { Milli, Nano, now } from "@moq/clock"; +import { Duration, now } from "@moq/clock"; import * as Json from "@moq/json"; import "@moq/watch/element"; // defines import "@moq/watch/ui"; // defines @@ -509,58 +509,55 @@ viz.run((effect) => { // Sample the active tile's byte/frame counters and push per-second rates. let prevWatch: MoqWatch | undefined; -let prev = { frames: 0, videoBytes: 0, audioBytes: 0, when: Nano.toMilli(Nano(now())) }; -viz.interval( - () => { - const watch = activeWatch.peek(); - const at = Nano.toMilli(Nano(now())); - - // Reset baselines when switching tiles (or when idle) so the first sample - // isn't a huge spike from the counter difference. - if (watch !== prevWatch || !watch) { - prevWatch = watch; - const video = watch?.video.out.stats.peek(); - const audio = watch?.audio.out.stats.peek(); - prev = { - frames: video?.frameCount ?? 0, - videoBytes: video?.bytesReceived ?? 0, - audioBytes: audio?.bytesReceived ?? 0, - when: at, - }; - for (const g of allGraphs) g.push(undefined); - return; - } +let prev = { frames: 0, videoBytes: 0, audioBytes: 0, when: now() }; +viz.interval(() => { + const watch = activeWatch.peek(); + const at = now(); + + // Reset baselines when switching tiles (or when idle) so the first sample + // isn't a huge spike from the counter difference. + if (watch !== prevWatch || !watch) { + prevWatch = watch; + const video = watch?.video.out.stats.peek(); + const audio = watch?.audio.out.stats.peek(); + prev = { + frames: video?.frameCount ?? 0, + videoBytes: video?.bytesReceived ?? 0, + audioBytes: audio?.bytesReceived ?? 0, + when: at, + }; + for (const g of allGraphs) g.push(undefined); + return; + } - const v = watch.video.out.stats.peek(); - const a = watch.audio.out.stats.peek(); - const videoBytes = v?.bytesReceived ?? 0; - const audioBytes = a?.bytesReceived ?? 0; - const frames = v?.frameCount ?? 0; - const elapsed = at - prev.when; - - const perSec = (delta: number) => (delta >= 0 ? (delta * 1000) / elapsed : undefined); - let videoBitrate: number | undefined; - let audioBitrate: number | undefined; - let throughput: number | undefined; - let fps: number | undefined; - if (elapsed > 0) { - videoBitrate = perSec((videoBytes - prev.videoBytes) * 8); - audioBitrate = perSec((audioBytes - prev.audioBytes) * 8); - throughput = perSec((videoBytes - prev.videoBytes + audioBytes - prev.audioBytes) * 8); - fps = perSec(frames - prev.frames); - } - videoBitrateGraph.push(videoBitrate); - audioBitrateGraph.push(audioBitrate); - fpsGraph.push(fps); - throughputGraph.push(throughput); - - const rtt = watch.connection.probe.peek()?.rtt as unknown as number | undefined; - rttGraph.push(rtt && rtt > 0 ? rtt : undefined); - - prev = { frames, videoBytes, audioBytes, when: at }; - }, - Nano.fromMilli(Milli(250)), -); + const v = watch.video.out.stats.peek(); + const a = watch.audio.out.stats.peek(); + const videoBytes = v?.bytesReceived ?? 0; + const audioBytes = a?.bytesReceived ?? 0; + const frames = v?.frameCount ?? 0; + const elapsed = at.since(prev.when).asMillis(); + + const perSec = (delta: number) => (delta >= 0 ? (delta * 1000) / elapsed : undefined); + let videoBitrate: number | undefined; + let audioBitrate: number | undefined; + let throughput: number | undefined; + let fps: number | undefined; + if (elapsed > 0) { + videoBitrate = perSec((videoBytes - prev.videoBytes) * 8); + audioBitrate = perSec((audioBytes - prev.audioBytes) * 8); + throughput = perSec((videoBytes - prev.videoBytes + audioBytes - prev.audioBytes) * 8); + fps = perSec(frames - prev.frames); + } + videoBitrateGraph.push(videoBitrate); + audioBitrateGraph.push(audioBitrate); + fpsGraph.push(fps); + throughputGraph.push(throughput); + + const rtt = watch.connection.probe.peek()?.rtt?.asMillis(); + rttGraph.push(rtt && rtt > 0 ? rtt : undefined); + + prev = { frames, videoBytes, audioBytes, when: at }; +}, Duration.millis(250)); // Rebuild the buffer visualization whenever the active tile changes; it binds to // one element and runs its own animation loop until its child effect closes. diff --git a/demo/web/src/publish.ts b/demo/web/src/publish.ts index 75ac86ded9b..632a080b007 100644 --- a/demo/web/src/publish.ts +++ b/demo/web/src/publish.ts @@ -19,7 +19,7 @@ import "./highlight"; import * as Json from "@moq/json"; import "@moq/publish/element"; // defines import "@moq/publish/ui"; // defines -import { Milli, Nano, now } from "@moq/clock"; +import { Duration, now } from "@moq/clock"; import { type Audio, Net, Signals, Source, type Video } from "@moq/publish"; import type MoqPublish from "@moq/publish/element"; import MoqPublishSupport from "@moq/publish/support/element"; @@ -142,7 +142,7 @@ function encoderConfig(effect: Signals.Effect, target: VideoTarget): Video.Confi codec: effect.get(codec), maxPixels: target.width && target.height ? target.width * target.height : undefined, maxBitrate: br != null ? br * 1000 : undefined, - join: kf != null ? Milli(kf) : undefined, + join: kf != null ? Duration.millis(kf) : undefined, frameRate: target.frameRate, }; } @@ -200,7 +200,7 @@ ui.run((effect) => { const config: Audio.OpusConfig = { mime: "opus", ...(bitrate != null ? { bitrate: bitrate * 1000 } : {}), - ...(frameDuration != null ? { frameDuration: Milli(frameDuration) } : {}), + ...(frameDuration != null ? { frameDuration: Duration.millis(frameDuration) } : {}), ...(complexity != null ? { complexity } : {}), ...(packetLoss != null ? { packetlossperc: packetLoss } : {}), useinbandfec: effect.get(opusFec), @@ -408,7 +408,7 @@ meta.run((effect) => { // A day-long cache so a viewer joining long after the last edit still replays the value. const track = net.createTrack(META_TRACK, { timescale: Net.Time.Timescale.MILLI, - maxAge: Milli(86_400_000), + maxAge: Duration.millis(86_400_000), }); effect.cleanup(() => { track.finish(); @@ -488,28 +488,25 @@ viz.run((effect) => { }); let prevFrames = 0; -let prevWhen = Nano.toMilli(Nano(now())); -viz.interval( - () => { - const at = Nano.toMilli(Nano(now())); - const elapsed = at - prevWhen; - captureGraph.push(elapsed > 0 ? ((frames - prevFrames) * 1000) / elapsed : undefined); - prevFrames = frames; - prevWhen = at; - - const rtt = publish.connection.probe.peek()?.rtt as unknown as number | undefined; - rttGraph.push(rtt && rtt > 0 ? rtt : undefined); - - void publish.connection.stats().then( - (stats) => { - const up = stats?.estimatedSendRate; - uploadGraph.push(up && up > 0 ? up : undefined); - }, - () => uploadGraph.push(undefined), - ); - }, - Nano.fromMilli(Milli(250)), -); +let prevWhen = now(); +viz.interval(() => { + const at = now(); + const elapsed = at.since(prevWhen).asMillis(); + captureGraph.push(elapsed > 0 ? ((frames - prevFrames) * 1000) / elapsed : undefined); + prevFrames = frames; + prevWhen = at; + + const rtt = publish.connection.probe.peek()?.rtt?.asMillis(); + rttGraph.push(rtt && rtt > 0 ? rtt : undefined); + + void publish.connection.stats().then( + (stats) => { + const up = stats?.estimatedSendRate; + uploadGraph.push(up && up > 0 ? up : undefined); + }, + () => uploadGraph.push(undefined), + ); +}, Duration.millis(250)); // Vite re-evaluates this module on hot reload, dropping the references to the // module-scoped effects above. Close them on dispose so they don't get garbage diff --git a/demo/web/src/stats.ts b/demo/web/src/stats.ts index 26a3feaff26..65cdeac1fa5 100644 --- a/demo/web/src/stats.ts +++ b/demo/web/src/stats.ts @@ -23,7 +23,7 @@ */ import "./highlight"; -import { Milli, Nano, wall } from "@moq/clock"; +import { Duration, wall } from "@moq/clock"; import { Net, Signals } from "@moq/hang"; import * as Json from "@moq/json"; @@ -33,7 +33,7 @@ const RELAY_URL = import.meta.env.VITE_RELAY_URL ?? "http://localhost:4443"; const STATS_PREFIX = ".stats/node"; // Rolling history window for the charts. -const SAMPLE = Nano.fromMilli(Milli(1000)); +const SAMPLE = Duration.millis(1000); const MAX_SAMPLES = 90; const $ = (id: string): T => { @@ -354,7 +354,7 @@ sampler.run((effect) => { effect.interval(() => { const all = nodeStats.peek(); const nodes = Object.keys(all).sort(); - const t = wall(); + const t = wall().asUnixMillis(); const agg: Sample = { t, diff --git a/demo/web/src/viz.ts b/demo/web/src/viz.ts index f43f613534e..ef8fb136c94 100644 --- a/demo/web/src/viz.ts +++ b/demo/web/src/viz.ts @@ -9,6 +9,7 @@ * to change the delay. */ +import { Duration } from "@moq/clock"; import type { BufferedRanges, Signals } from "@moq/watch"; import type MoqWatch from "@moq/watch/element"; @@ -153,7 +154,7 @@ const BUFFER_MAX = 4000; // window shown, in milliseconds function drawRanges( canvas: HTMLCanvasElement, ranges: BufferedRanges, - timestamp: number | undefined, + timestamp: Duration | undefined, stalled: boolean, ) { const ctx = canvas.getContext("2d"); @@ -173,11 +174,12 @@ function drawRanges( ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, width, height); if (timestamp === undefined) return; + const playhead = timestamp.asMillis(); for (let i = 0; i < ranges.length; i++) { const range = ranges[i]; - const startMs = range.start - timestamp; - const endMs = range.end - timestamp; + const startMs = range.start.asMillis() - playhead; + const endMs = range.end.asMillis() - playhead; const visibleStart = Math.max(0, startMs); const visibleEnd = Math.min(endMs, BUFFER_MAX); if (visibleEnd <= visibleStart) continue; @@ -256,10 +258,9 @@ export function bufferBars(parent: Signals.Effect, watch: MoqWatch): HTMLElement root.append(viz, legend); - // Set the playback delay. Cast bypasses the branded ms type. + // Set the playback delay, in milliseconds. const setDelay = (ms: number) => { - const clamped = Math.max(0, Math.min(BUFFER_MAX, ms)); - watch.delay = clamped as unknown as typeof watch.delay; + watch.delay = Duration.millis(Math.max(0, Math.min(BUFFER_MAX, ms))); }; const setFromX = (clientX: number) => { @@ -290,12 +291,12 @@ export function bufferBars(parent: Signals.Effect, watch: MoqWatch): HTMLElement : 0; if (delta === 0) return; e.preventDefault(); - setDelay(watch.sync.out.delay.peek() + delta); + setDelay(watch.sync.out.delay.peek().asMillis() + delta); }); // Position the target line from the resolved delay (the live buffer in ms). parent.run((effect) => { - const delay = effect.get(watch.sync.out.delay); + const delay = effect.get(watch.sync.out.delay).asMillis(); const pct = Math.max(0, Math.min(1, delay / BUFFER_MAX)) * 100; target.style.left = `${pct}%`; targetLabel.textContent = `${Math.round(delay)}ms`; diff --git a/doc/lib/js/clock.md b/doc/lib/js/clock.md index 418be7bb7bd..bdd71e56350 100644 --- a/doc/lib/js/clock.md +++ b/doc/lib/js/clock.md @@ -17,33 +17,38 @@ bun add @moq/clock ``` ```ts -import { Manual, Milli, Nano, now, sleep } from "@moq/clock"; +import { Duration, Manual, now, sleep } from "@moq/clock"; const clock = new Manual(); const installed = clock.install(); try { const start = now(); - const pending = sleep(Nano.fromMilli(Milli(10))); - await clock.advance(Nano.fromMilli(Milli(10))); + const pending = sleep(Duration.millis(10)); + await clock.advance(Duration.millis(10)); await pending; - console.log(now() - start); // 10,000,000 nanoseconds + console.log(now().since(start).asMillis()); // 10 } finally { installed.close(); } ``` -`Instant` counts nanoseconds from its clock's origin: the realm's performance -time origin on the host, so DOM timestamps convert by unit, or zero for a -`Manual` clock. `Nano`, `Micro`, -`Milli`, and `Second` brand duration units; convert a duration to nanoseconds -before passing it to a timer. Number nanoseconds are exact for roughly 104 +`Duration`, `Instant`, and `Wall` are immutable objects that mirror Rust's +`Duration` and `kio::clock`'s `Instant` and `Wall`. Build a duration with a unit +(`Duration.millis(5)`) and read it with one (`asMillis()`); compare with +`lt`, `ge`, and friends. None of them converts to a number: arithmetic, `<`, +and `JSON.stringify` throw a `TypeError`, so a unit mistake can't hide behind a +cast. A template string prints one with its unit. + +`Instant` counts from its clock's origin: the realm's performance time origin +on the host, so a DOM timestamp `t` is `Instant.ZERO.add(Duration.millis(t))`, +or zero for a `Manual` clock. Its nanoseconds are exact for roughly 104 days, then gradually lose sub-microsecond precision. Compare instants only from the same clock. Rust and JS each own their origin: no instant may cross that boundary until the backend explicitly shares one. -`Wall` is a separate branded number of milliseconds since the Unix epoch. -Use it for dates, rather than measuring elapsed time. A Rust wall-time -boundary must convert its units explicitly. A new `Manual` starts at instant +`Wall` is wall-clock time, separate from monotonic time: `Wall.unixMillis(ms)` +builds one from Unix milliseconds and `asUnixMillis()` reads them back exactly. Use it for dates, rather than +measuring elapsed time. A new `Manual` starts at instant zero and 2025-01-01 UTC. `await advance()` moves both readings through each due timer deadline, draining tasks between deadlines, including timers those tasks re-arm before the target. `yieldNow()` waits for a later host task, giving the @@ -84,7 +89,7 @@ workspace dependencies reach `@moq/clock` loads a preload fails a workspace that doesn't. The preload fails a test when a timer it armed through `@moq/clock` fires on the host clock, so a test can't prove that nothing happened by waiting in real time; lint bans the native timers in test files. A -timer already due when armed, such as `sleep(0)`, or a `timeout()` whose +timer already due when armed, such as `sleep(Duration.ZERO)`, or a `timeout()` whose operation settles first never waits, and a timer firing after its test ended fails nothing. A test on real sockets, devices, or processes calls `hostTime()` from `@moq/clock/test` first; without the preload it does nothing. diff --git a/doc/lib/js/hang.md b/doc/lib/js/hang.md index 12c96199ed9..ab9f35a116b 100644 --- a/doc/lib/js/hang.md +++ b/doc/lib/js/hang.md @@ -28,15 +28,15 @@ or building a custom player. A catalog's `media` section may carry a `clock` that maps PTS zero to wall time. `Catalog.wallClockTime(clock, pts, ptsTimescale)` turns a frame's timestamp -into a `Date`. A `Container.Legacy` timestamp is microseconds, so pass -`1_000_000`. +into a `Date`. It takes integer ticks at a timescale, so pass a frame's +`Duration` timestamp as whole microseconds with `1_000_000`. ```ts for await (const root of Catalog.watch(broadcast)) { const clock = root.media?.clock; if (!clock) continue; // the publisher exposes no clock // `frame` comes from your own `Container.Legacy` consumer. - const captured = Catalog.wallClockTime(clock, frame.timestamp, 1_000_000); + const captured = Catalog.wallClockTime(clock, Math.floor(frame.timestamp.asMicros()), 1_000_000); } ``` diff --git a/doc/lib/js/net.md b/doc/lib/js/net.md index 5dd1fe8cc98..cffb5956f93 100644 --- a/doc/lib/js/net.md +++ b/doc/lib/js/net.md @@ -52,8 +52,9 @@ route.announce(); - **One track per name.** Concurrent subscriptions share one request and producer. `createTrack` on a name with a request still queued answers it. The application owns sequence numbers: the broadcast keeps nothing of an ended track, so a track that replaces it, created or requested, starts at 0. A name always means the same content, so the replacement continues past its predecessor's groups by writing its first group with an explicit sequence. Sequences are `bigint`, so every ID the wire carries fits, past 2^53 included: `track.createGroup(5n)`, `{ absolute: 10n }`. Frame indices and relative anchors stay `number`. - **Serve history on request.** `track.requests()` opens a handle that serves the groups readers miss: ones their ranges name below the newest group written that the cache no longer holds, or never did. Each run of misses arrives as a `Track.Fill` from `await requests.requestedFill()`, shared by every reader missing it. `accept(sequence)` it into the cache and write the group's frames as first published, `dropGroups(start, end)` what the source lacks (sequences are `bigint`), and serve `wanted()` until it is `undefined`: a reader that leaves or narrows stops wanting its groups. `close()` the fill when done; whatever is still wanted is named dropped. A `fetchGroup` of an uncached group asks the handle at once, even for a group not written yet, which a live write then answers; with no handle open it fails with `NotFound`, as in Rust, and a reader's miss is given up. A reader only asks for what its `delay.max` still wants, so a reader at the live edge never asks. This serves lite FETCH, single-group IETF FETCH, and lite-07 ranged subscriptions from the same track, as Rust's `requests()` does. - **Timing is per track, with no default.** A track that declares a `timescale` carries a `timestamp` on every frame; one without is [untimed](/concept/moq-lite#subscriptions) and its frames carry none. Omitting it means untimed, as in Rust. Nothing stamps a frame for you: the publisher passes the timestamp, and the `Timed` type (`{ value, at }`) carries one into the `@moq/json` producers. +- **Durations and instants are `Clock` types.** Every duration (`maxAge`, `delay`, timeouts, RTT) is a `Clock.Duration` and every monotonic time a `Clock.Instant`, from [`@moq/clock`](./clock), which `@moq/net` re-exports as `Clock`: `maxAge: Moq.Clock.Duration.secs(30)`. Neither converts to a number implicitly; read one with an explicit unit, such as `asMillis()`. The wire still carries whole milliseconds, rounded up. Frame timestamps stay `Time.Timestamp`, a tick count at the track's timescale. - **A subscription's `delay` is a `Track.Delay { min, max }`, as in Rust.** Staleness is `delay.max`: it counts from a group's successor, by media time and by wall clock, whichever reaches it first. `delay.min` is the target latency, carried on moq-lite 07; a peer that cannot carry it leaves it `null` (not stated). Passing the old `maxAge` or `maxDelay` key throws a `TypeError` naming `delay.max`. The publisher's own staleness bound is the separate `Track.Info.maxAge`, which caps `delay.max` and fetches. -- **Authored tracks default to a zero `maxAge`.** `createTrack` and `accept` take a `Track.InfoInit`: an omitted `maxAge` is zero, so readers get only the live edge; `null` sets no publisher limit, and a number is that bound, as `Info::default()` and `with_max_age(None)` do in Rust. A track whose readers reach back for superseded groups (history, a fetch, a range from an absolute start) sets one explicitly; media takes `@moq/hang`'s 30-second `Container.MAX_AGE`. `maxAge` is how long a superseded group stays fresh, never the newest group, so a track that writes one snapshot stays readable to a late joiner. A received `Track.Info` uses `null` for none (`maxAge`, `timescale`, `refresh`), so it serves onward unchanged. +- **Authored tracks default to a zero `maxAge`.** `createTrack` and `accept` take a `Track.InfoInit`: an omitted `maxAge` is zero, so readers get only the live edge; `null` sets no publisher limit, and a `Clock.Duration` is that bound, as `Info::default()` and `with_max_age(None)` do in Rust. A track whose readers reach back for superseded groups (history, a fetch, a range from an absolute start) sets one explicitly; media takes `@moq/hang`'s 30-second `Container.MAX_AGE`. `maxAge` is how long a superseded group stays fresh, never the newest group, so a track that writes one snapshot stays readable to a late joiner. A received `Track.Info` uses `null` for none (`maxAge`, `timescale`, `refresh`), so it serves onward unchanged. - **The cache keeps an idle group for 30 seconds.** A track evicts a group nothing has written for 30 seconds, matching the Rust cache's default expiry; a live track's newest group is exempt until a newer one arrives, unless it failed. Neither `Track.Info.maxAge` nor `delay.max` changes that window: they only decide which cached groups a reader still receives. - **Subscription defaults.** `Track.Subscription.default()` returns the default subscription, whose zero `delay.max` skips a superseded group at once; calling `subscribe()` with no options means the same. An omitted `delay` field means the same zero; `max: null` sets no subscriber limit. - **A subscription asks for `ranges`.** Each [range](/concept/moq-lite#subscriptions) starts and ends at an `absolute` group, one `relative` to the latest, or the group containing a `time` (a `Timestamp`), and a reader reads only its own ranges. A read whose ranges all end finishes once every group in them is handed out, dropped, or skipped, as in Rust. A time anchor needs a timed track and `moq-lite-07-wip` over a session. Passing the old `groups` key throws a `TypeError` naming `ranges`; `withRange` only narrows reads locally. diff --git a/doc/lib/js/publish.md b/doc/lib/js/publish.md index e84d9c676e7..181d4261079 100644 --- a/doc/lib/js/publish.md +++ b/doc/lib/js/publish.md @@ -118,8 +118,8 @@ puts every frame in its own group, and zero is refused. A longer join lets a relay keep fewer streams, at the cost of coarser loss: a viewer that falls behind skips a whole group. Frames still forward as they are encoded. -Timestamps are `@moq/clock`'s `now()` in microseconds, so every source shares one -timeline. The catalog's `media.clock` maps it to wall time. Stamp your own tracks +Timestamps are `@moq/clock`'s `now()` since its origin, a `Duration`, so every +source shares one timeline. The catalog's `media.clock` maps it to wall time. Stamp your own tracks (e.g. text cues) on the same timeline to stay in sync. ## Custom tracks diff --git a/doc/lib/js/signals.md b/doc/lib/js/signals.md index 1bb3f8aa560..1da5d379198 100644 --- a/doc/lib/js/signals.md +++ b/doc/lib/js/signals.md @@ -21,14 +21,14 @@ the rest. | `Derived` | A cheap mapped view with no lifecycle. | ```ts -import { Milli, Nano } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Effect, Signal } from "@moq/signals"; const volume = new Signal(1); const effect = new Effect((effect) => { const v = effect.get(volume); // read AND subscribe; peek() reads without subscribing - effect.interval(() => console.log(v), Nano.fromMilli(Milli(1000))); // cancelled on rerun or close + effect.interval(() => console.log(v), Duration.secs(1)); // cancelled on rerun or close effect.cleanup(() => console.log("bye")); }); @@ -39,8 +39,8 @@ effect.close(); // permanent The rules that differ from other signal libraries: - **Nothing is tracked implicitly.** `effect.get(signal)` subscribes; `signal.peek()` doesn't. -- **Writes coalesce per microtask** and only notify on a real change (deep for plain objects, identity for class instances). -- **Effects own their resources.** `effect.timer`, `interval`, `animate`, `event`, `spawn`, and `run` (a nested effect) all clean up on rerun or close, so never call `setTimeout` or `addEventListener` inside one directly. Timers take `Nano` durations and run on the [`@moq/clock`](./clock) clock, so a `Manual` clock drives them in tests. +- **Writes coalesce per microtask** and only notify on a real change (deep for plain objects, identity for class instances except clock values, which compare by value). +- **Effects own their resources.** `effect.timer`, `interval`, `animate`, `event`, `spawn`, and `run` (a nested effect) all clean up on rerun or close, so never call `setTimeout` or `addEventListener` inside one directly. Timers take a `Duration` and run on the [`@moq/clock`](./clock) clock, so a `Manual` clock drives them in tests. - **Teardown runs last-in, first-out**, like `DisposableStack`. - **Race with `race`, not `Promise.race`.** `Promise.race` leaves a listener on every loser, so racing a long-lived promise once per frame grows the heap. `race([...])` and `effect.race(promise)` drop their listeners when they settle. - **Misuse warns in every build**, with the effect's creation stack: effects that tracked nothing, or were garbage-collected without `close()`. diff --git a/doc/lib/js/watch.md b/doc/lib/js/watch.md index 7efb5225cb7..6917d677175 100644 --- a/doc/lib/js/watch.md +++ b/doc/lib/js/watch.md @@ -255,7 +255,9 @@ response emitted in one burst with future timestamps, wants the opposite. Set `delay`, since playback only skips ahead once media sits more than `delay + lookahead` past the playhead. -Durations need a unit; a bare number is rejected. Audio holds the lookahead +Durations need a unit; a bare number is rejected. From script, the `delay` and +`lookahead` properties take a `Duration` from `@moq/clock`, such as +`el.delay = Duration.millis(300)`. Audio holds the lookahead as encoded frames, so a large one is cheap; video waits as decoded pictures, which hold decoder memory, so a long video lookahead is not. The first video frame shows as a poster at once, and playback starts once every enabled track diff --git a/js/AGENTS.md b/js/AGENTS.md index 04250d88153..a548b99cdd9 100644 --- a/js/AGENTS.md +++ b/js/AGENTS.md @@ -4,7 +4,7 @@ The `/js` Bun workspace, published as `@moq/`. Run recipes via `just js `@moq/signals` is the reactive core; read `signals/src/index.ts` before touching reactive code. -- `Signal` equality is deep for plain data but identity for class instances; `set(v, true)` forces a notify. +- `Signal` equality is deep for plain data but identity for class instances, except clock values (by value); `set(v, true)` forces a notify. - `Computed` is `undefined` until its first run and after `close()`. Close standalone ones; `effect.computed()` closes with its parent. - An `Effect` rerun waits for every `effect.spawn` task from the previous run to settle, so register `effect.cleanup` unconditionally. - Use the scoped helpers (`effect.interval`, `timer`, `event`, `subscribe`, ...) over raw timers and listeners, and nested `effect.run` over one giant effect. diff --git a/js/auth/src/cli.test.ts b/js/auth/src/cli.test.ts index 4247c676dd3..05170250fdb 100644 --- a/js/auth/src/cli.test.ts +++ b/js/auth/src/cli.test.ts @@ -81,9 +81,9 @@ describe("sign", () => { /** The `exp` `args` write, with the wall seconds bracketing the subprocess that wrote it. */ function bracketed(...args: string[]) { - const before = Math.floor(wall() / 1000); + const before = Math.floor(wall().asUnixMillis() / 1000); const value = exp(...args) ?? 0; - const after = Math.floor(wall() / 1000); + const after = Math.floor(wall().asUnixMillis() / 1000); return { before, value, after }; } diff --git a/js/auth/src/cli.ts b/js/auth/src/cli.ts index 469c38078ec..58d2c4e6bef 100755 --- a/js/auth/src/cli.ts +++ b/js/auth/src/cli.ts @@ -90,7 +90,7 @@ program const exp = options.unbounded ? undefined - : (options.expires ?? Math.floor(wall() / 1000) + (options.ttl ?? 3600)); + : (options.expires ?? Math.floor(wall().asUnixMillis() / 1000) + (options.ttl ?? 3600)); const claims = ClaimsSchema.parse({ root: options.root, ...(options.publish && { publish: options.publish }), diff --git a/js/auth/src/key.test.ts b/js/auth/src/key.test.ts index 0ef5749f111..e197a919d2c 100644 --- a/js/auth/src/key.test.ts +++ b/js/auth/src/key.test.ts @@ -25,8 +25,8 @@ const testClaims = { root: "test-path", publish: ["test-pub/**"], subscribe: ["test-sub/**"], - exp: Math.floor((wall() + 60 * 1000) / 1000), // 1 minute from now in seconds - iat: Math.floor(wall() / 1000), // now in seconds + exp: Math.floor(wall().asUnixMillis() / 1000 + 60), // 1 minute from now in seconds + iat: Math.floor(wall().asUnixMillis() / 1000), // now in seconds }; type AsymmetricAlgorithm = Exclude; @@ -56,7 +56,7 @@ async function generateAsymmetricKeyPair( test("verify refuses unsafe signed payloads without dropping their restrictions", async () => { const clock = new Manual(); - clock.stepWall(Wall(1_000_000)); + clock.stepWall(Wall.unixMillis(1_000_000)); const installed = clock.install(); try { const key = Key.parse(encodeJwk(testKey)); @@ -283,7 +283,7 @@ test("verify - invalid token format", async () => { test("verify - expired token", async () => { const expiredClaims = { ...testClaims, - exp: Math.floor((wall() - 60 * 1000) / 1000), // 1 minute ago in seconds + exp: Math.floor(wall().asUnixMillis() / 1000 - 60), // 1 minute ago in seconds }; const key = Key.parse(encodeJwk(testKey)); @@ -332,8 +332,8 @@ test("round-trip - sign and verify", async () => { root: "test-path", publish: ["test-pub/**"], subscribe: ["test-sub/**"], - exp: Math.floor((wall() + 60 * 1000) / 1000), - iat: Math.floor(wall() / 1000), + exp: Math.floor(wall().asUnixMillis() / 1000 + 60), + iat: Math.floor(wall().asUnixMillis() / 1000), }; const token = await Key.sign(key, originalClaims); @@ -883,7 +883,7 @@ async function signRaw(payload: Record): Promise { // might narrow the grant, and a misspelled `root` would widen it to everything. test("verify - only registered claims", async () => { const key = Key.parse(encodeJwk(testKey)); - const now = Math.floor(wall() / 1000); + const now = Math.floor(wall().asUnixMillis() / 1000); const token = await signRaw({ root: "room", publish: ["**"], iss: "api", sub: "alice", jti: "1", iat: now }); const claims = await Key.verify(key, token); @@ -902,7 +902,7 @@ test("verify - only registered claims", async () => { test("verify - enforces not before", async () => { const key = Key.parse(encodeJwk(testKey)); - const now = Math.floor(wall() / 1000); + const now = Math.floor(wall().asUnixMillis() / 1000); expect((await Key.verify(key, await signRaw({ publish: ["**"], nbf: now - 60 }))).nbf).toBe(now - 60); await expect(Key.verify(key, await signRaw({ publish: ["**"], nbf: now + 3600 }))).rejects.toThrow(); }); diff --git a/js/auth/src/key.ts b/js/auth/src/key.ts index 4a7b2b00bca..7033e9f8daa 100644 --- a/js/auth/src/key.ts +++ b/js/auth/src/key.ts @@ -244,7 +244,7 @@ async function verify(key: PublicKey | SymmetricKey, token: string): Promise now) throw new Error("Token is not yet valid"); ensureClaimsWithinScope(key, claims); diff --git a/js/clock/README.md b/js/clock/README.md index 561634a60f6..b1a0fe6edbc 100644 --- a/js/clock/README.md +++ b/js/clock/README.md @@ -4,15 +4,15 @@ Logical monotonic time, wall time, and timers from one clock per JavaScript real Use `Manual` to test time without replacing the host's timers. ```ts -import { Manual, Milli, Nano, now, sleep } from "@moq/clock"; +import { Duration, Instant, Manual, now, sleep } from "@moq/clock"; const clock = new Manual(); const installed = clock.install(); try { - const pending = sleep(Nano.fromMilli(Milli(10))); - await clock.advance(Nano.fromMilli(Milli(10))); + const pending = sleep(Duration.millis(10)); + await clock.advance(Duration.millis(10)); await pending; - console.log(now()); // 10,000,000 nanoseconds + console.log(now().since(Instant.ZERO).asMillis()); // 10 } finally { installed.close(); } diff --git a/js/clock/api/index.api.md b/js/clock/api/index.api.md index aed81dc35be..25e1144a7ab 100644 --- a/js/clock/api/index.api.md +++ b/js/clock/api/index.api.md @@ -1,6 +1,39 @@ # `@moq/clock` ```ts +export class Duration { + static readonly ZERO: Duration; + [Symbol.toPrimitive](hint: string): string; + absDiff(other: Duration): Duration; + add(other: Duration): Duration; + asMicros(): number; + asMillis(): number; + asNanos(): number; + asSecs(): number; + clamp(lo: Duration, hi: Duration): Duration; + cmp(other: Duration): -1 | 0 | 1; + div(divisor: number): Duration; + divDuration(other: Duration): number; + eq(other: Duration): boolean; + ge(other: Duration): boolean; + gt(other: Duration): boolean; + isZero(): boolean; + le(other: Duration): boolean; + lt(other: Duration): boolean; + max(other: Duration): Duration; + static micros(value: number): Duration; + static millis(value: number): Duration; + min(other: Duration): Duration; + mul(factor: number): Duration; + static nanos(value: number): Duration; + saturatingSub(other: Duration): Duration; + static secs(value: number): Duration; + sub(other: Duration): Duration; + toJSON(): never; + toString(): string; + valueOf(): never; +} + export class Elapsed extends Error { constructor(); } @@ -9,21 +42,29 @@ export interface Installed { close(): void; } -export const Instant: ((value: number) => Instant) & { - add: (at: Instant, duration: Nano) => Instant; - durationSince: (at: Instant, earlier: Instant) => Nano; - sub: (at: Instant, duration: Nano) => Instant; - zero: Instant; -}; - -export type Instant = number & { - readonly _brand: "clock-instant"; -}; +export class Instant { + static readonly ZERO: Instant; + [Symbol.toPrimitive](hint: string): string; + add(duration: Duration): Instant; + cmp(other: Instant): -1 | 0 | 1; + eq(other: Instant): boolean; + ge(other: Instant): boolean; + gt(other: Instant): boolean; + le(other: Instant): boolean; + lt(other: Instant): boolean; + max(other: Instant): Instant; + min(other: Instant): Instant; + since(earlier: Instant): Duration; + sub(duration: Duration): Instant; + toJSON(): never; + toString(): string; + valueOf(): never; +} export class Interval { - constructor(period: Nano); + constructor(period: Duration); close(): void; - period(): Nano; + period(): Duration; setMissedTickBehavior(behavior: MissedTickBehavior): void; tick(): Promise; } @@ -31,44 +72,16 @@ export class Interval { export class Manual { constructor(); static readonly WALL_START: Wall; - advance(duration: Nano): Promise; + advance(duration: Duration): Promise; drive(work: PromiseLike): Promise; fire(): Promise; install(): Installed; - jump(duration: Nano): void; + jump(duration: Duration): void; now(): Instant; stepWall(wall: Wall): void; wall(): Wall; } -export const Micro: ((value: number) => Micro) & { - fromMilli: (value: Milli) => Micro; - fromNano: (value: Nano) => Micro; - fromSecond: (value: Second) => Micro; - toMilli: (value: Micro) => Milli; - toNano: (value: Micro) => Nano; - toSecond: (value: Micro) => Second; - zero: Micro; -}; - -export type Micro = number & { - readonly _brand: "clock-micro"; -}; - -export const Milli: ((value: number) => Milli) & { - fromMicro: (value: Micro) => Milli; - fromNano: (value: Nano) => Milli; - fromSecond: (value: Second) => Milli; - toMicro: (value: Milli) => Micro; - toNano: (value: Milli) => Nano; - toSecond: (value: Milli) => Second; - zero: Milli; -}; - -export type Milli = number & { - readonly _brand: "clock-milli"; -}; - export const MissedTickBehavior: { readonly Burst: "burst"; readonly Delay: "delay"; @@ -77,52 +90,32 @@ export const MissedTickBehavior: { export type MissedTickBehavior = typeof MissedTickBehavior[keyof typeof MissedTickBehavior]; -export const Nano: ((value: number) => Nano) & { - fromMicro: (value: Micro) => Nano; - fromMilli: (value: Milli) => Nano; - fromSecond: (value: Second) => Nano; - toMicro: (value: Nano) => Micro; - toMilli: (value: Nano) => Milli; - toSecond: (value: Nano) => Second; - zero: Nano; -}; - -export type Nano = number & { - readonly _brand: "clock-nano"; -}; - -export const Second: ((value: number) => Second) & { - fromMicro: (value: Micro) => Second; - fromMilli: (value: Milli) => Second; - fromNano: (value: Nano) => Second; - toMicro: (value: Second) => Micro; - toMilli: (value: Second) => Milli; - toNano: (value: Second) => Nano; - zero: Second; -}; - -export type Second = number & { - readonly _brand: "clock-second"; -}; - -export const Wall: ((unixMillis: number) => Wall) & { - UNIX_EPOCH: Wall; - add: (at: Wall, duration: Nano) => Wall; - durationSince: (at: Wall, earlier: Wall) => Nano; - sub: (at: Wall, duration: Nano) => Wall; -}; - -export type Wall = number & { - readonly _brand: "clock-wall"; -}; +export class Wall { + static readonly UNIX_EPOCH: Wall; + [Symbol.toPrimitive](hint: string): string; + add(duration: Duration): Wall; + asUnixMillis(): number; + cmp(other: Wall): -1 | 0 | 1; + eq(other: Wall): boolean; + ge(other: Wall): boolean; + gt(other: Wall): boolean; + le(other: Wall): boolean; + lt(other: Wall): boolean; + since(earlier: Wall): Duration; + sub(duration: Duration): Wall; + toJSON(): never; + toString(): string; + static unixMillis(millis: number): Wall; + valueOf(): never; +} -export function interval(period: Nano): Interval; +export function interval(period: Duration): Interval; export function now(): Instant; export function origin(): Wall; -export function sleep(duration: Nano, options?: { +export function sleep(duration: Duration, options?: { ref?: boolean; signal?: AbortSignal; }): Promise; @@ -132,9 +125,9 @@ export function sleepUntil(at: Instant, options?: { signal?: AbortSignal; }): Promise; -export function timeout(duration: Nano, operation: PromiseLike): Promise; +export function timeout(duration: Duration, operation: PromiseLike): Promise; -export function timeoutSignal(duration: Nano, options?: { +export function timeoutSignal(duration: Duration, options?: { ref?: boolean; signal?: AbortSignal; }): AbortSignal; diff --git a/js/clock/bench/timers.ts b/js/clock/bench/timers.ts index 36ce4e7e18f..d8803805130 100644 --- a/js/clock/bench/timers.ts +++ b/js/clock/bench/timers.ts @@ -1,5 +1,5 @@ // Sweep armed timers x timers made ready, with independent and shared abort scopes. -import { Manual, Nano, sleep } from "../src/index.ts"; +import { Duration, Manual, sleep } from "../src/index.ts"; console.log("mode,scope,armed,ready,arm_us,advance_us,cancel_us"); for (const mode of ["jump", "advance"]) { @@ -14,13 +14,13 @@ for (const mode of ["jump", "advance"]) { try { const start = performance.now(); const timers = Array.from({ length: armed }, (_, index) => - sleep(Nano(index < ready ? index + 1 : armed + 1), { + sleep(Duration.nanos(index < ready ? index + 1 : armed + 1), { signal: aborts[index % aborts.length].signal, }).catch(() => {}), ); const armedAt = performance.now(); - if (mode === "jump") clock.jump(Nano(ready)); - else await clock.advance(Nano(ready)); + if (mode === "jump") clock.jump(Duration.nanos(ready)); + else await clock.advance(Duration.nanos(ready)); const advancedAt = performance.now(); for (const abort of aborts) abort.abort(); const cancelledAt = performance.now(); diff --git a/js/clock/src/guard.test.ts b/js/clock/src/guard.test.ts index 45878ddcbf0..464558baf7e 100644 --- a/js/clock/src/guard.test.ts +++ b/js/clock/src/guard.test.ts @@ -8,10 +8,10 @@ const src = import.meta.dir; // Each case runs as its own test under the real preload, since the guard fails a test from a host callback. const fixture = ` import { test } from "bun:test"; -import { Milli, Nano, sleep, timeout, yieldNow } from "${join(src, "index.ts")}"; +import { Duration, sleep, timeout, yieldNow } from "${join(src, "index.ts")}"; import { hostTime } from "${join(src, "test.ts")}"; -const ms = (n) => Nano.fromMilli(Milli(n)); +const ms = (n) => Duration.millis(n); test("waits 50ms on the real clock", async () => { await sleep(ms(50)); @@ -23,7 +23,7 @@ test("a watchdog on progress that settles first", async () => { await timeout(ms(1000), Promise.resolve(1)); }); test("a sleep already due", async () => { - await sleep(Nano(0)); + await sleep(Duration.ZERO); }); test("opted out with hostTime", async () => { hostTime(); // the case under test diff --git a/js/clock/src/index.test.ts b/js/clock/src/index.test.ts index b5c7f919fe2..ef58eacf02c 100644 --- a/js/clock/src/index.test.ts +++ b/js/clock/src/index.test.ts @@ -2,18 +2,15 @@ import { afterEach, expect, test } from "bun:test"; // biome-ignore lint/style/noRestrictedImports: a host task that bypasses the installed Manual clock. import { setTimeout as hostTimeout } from "node:timers/promises"; import { + Duration, Elapsed, type Installed, Instant, interval, Manual, - Micro, - Milli, MissedTickBehavior, - Nano, now, origin, - Second, sleep, sleepUntil, timeout, @@ -33,100 +30,151 @@ function manual(): Manual { installs.push(clock.install()); return clock; } -const ns = Nano.fromMilli; - -test("units convert without permitting instant or wall time as durations", () => { - expect(Nano.fromSecond(Second(1))).toBe(1_000_000_000); - expect(Micro.fromMilli(Milli(2))).toBe(2000); - expect(Milli.fromNano(Nano(1_500_000))).toBe(1.5); - expect(Second.fromMicro(Micro(2_000_000))).toBe(2); - expect(() => Nano(-1)).toThrow(RangeError); - expect(() => Milli(Number.POSITIVE_INFINITY)).toThrow(RangeError); - expect(() => Instant(Number.NaN)).toThrow(RangeError); +// Read an instant or wall time as a plain number for assertions. +const ns = (at: Instant): number => at.since(Instant.ZERO).asNanos(); +const ms = (at: Wall): number => at.asUnixMillis(); +const instant = (nanos: number): Instant => Instant.ZERO.add(Duration.nanos(nanos)); +const unix = (millis: number): Wall => Wall.unixMillis(millis); +const START = ms(Manual.WALL_START); + +test("durations convert units and refuse to become numbers", () => { + expect(Duration.secs(1).asNanos()).toBe(1_000_000_000); + expect(Duration.millis(2).asMicros()).toBe(2000); + expect(Duration.nanos(1_500_000).asMillis()).toBe(1.5); + expect(Duration.micros(2_000_000).asSecs()).toBe(2); + expect(() => Duration.nanos(-1)).toThrow(RangeError); + expect(() => Duration.millis(Number.POSITIVE_INFINITY)).toThrow(RangeError); + expect(() => instant(Number.NaN)).toThrow(RangeError); + expect(() => Duration.millis(1).sub(Duration.millis(2))).toThrow(RangeError); + expect(() => Instant.ZERO.sub(Duration.nanos(1))).toThrow(RangeError); + expect(Duration.millis(1).saturatingSub(Duration.millis(2)).isZero()).toBe(true); + expect(instant(5).since(instant(9)).isZero()).toBe(true); + expect(`${Duration.micros(1500)}`).toBe("1.5ms"); + const loose: unknown = Duration.millis(1); + expect(() => (loose as number) + 1).toThrow(TypeError); + expect(() => (loose as number) < 2).toThrow(TypeError); + expect(() => JSON.stringify({ loose })).toThrow(TypeError); + expect(() => (instant(1) as unknown as number) * 2).toThrow(TypeError); + expect(() => JSON.stringify(Wall.UNIX_EPOCH)).toThrow(TypeError); if (false as boolean) { // @ts-expect-error instants are not durations - void sleep(Instant.zero); + void sleep(Instant.ZERO); // @ts-expect-error wall time is not monotonic time void sleepUntil(Wall.UNIX_EPOCH); - // @ts-expect-error milliseconds must be converted to nanoseconds - void sleep(Milli(1)); + // @ts-expect-error a duration is not a number + void sleep(5); + // @ts-expect-error a duration does not convert to a number + void (Duration.millis(1) as number); } }); +test("durations keep a whole count of any unit exact past 2^53 ns", () => { + // Microseconds since the Unix epoch, as a legacy container timestamp carries them. + for (const micros of [1_735_689_600_000_016, 4_102_444_800_123_457, Number.MAX_SAFE_INTEGER]) { + expect(Duration.micros(micros).asMicros()).toBe(micros); + } + for (const millis of [1_735_689_600_017, Number.MAX_SAFE_INTEGER]) { + expect(Duration.millis(millis).asMillis()).toBe(millis); + } + const epoch = Duration.micros(1_735_689_600_000_016); + expect(epoch.add(Duration.micros(1)).asMicros()).toBe(1_735_689_600_000_017); + expect(epoch.sub(Duration.micros(17)).asMicros()).toBe(1_735_689_599_999_999); + expect(epoch.add(Duration.nanos(1)).gt(epoch)).toBe(true); + expect(Duration.micros(1500)).toEqual(Duration.millis(1.5)); + expect(Duration.secs(1).sub(Duration.nanos(1)).asNanos()).toBe(999_999_999); + expect(Duration.millis(250).mul(4)).toEqual(Duration.secs(1)); + expect(Duration.secs(1).div(4)).toEqual(Duration.millis(250)); + expect(() => Duration.micros(1).sub(Duration.micros(2))).toThrow(RangeError); + // A unit with no exact binary form rounds to whole nanoseconds, so it orders as it converts. + expect(Duration.secs(1.1)).toEqual(Duration.millis(1100)); + expect(Duration.millis(3300).divDuration(Duration.secs(1.1))).toBe(3); + expect(Duration.millis(3300).sub(Duration.secs(1.1).mul(3)).isZero()).toBe(true); + expect(Duration.nanos(0.4).isZero()).toBe(true); +}); + +test("wall time round-trips Unix milliseconds exactly", () => { + // Past 2^53 ns, a detour through a Duration since the epoch would round. + for (const millis of [0, 1_735_689_600_001, 4_102_444_800_123, Number.MAX_SAFE_INTEGER]) { + expect(Wall.unixMillis(millis).asUnixMillis()).toBe(millis); + } + expect(() => Wall.unixMillis(-1)).toThrow(RangeError); + expect(() => Wall.unixMillis(Number.NaN)).toThrow(RangeError); +}); + test("manual reads and wall corrections share a clock without inventing elapsed time", () => { const clock = manual(); - expect(now()).toBe(0); - expect(wall()).toBe(Manual.WALL_START); - clock.jump(ns(Milli(5))); - expect(now()).toBe(5_000_000); - expect(wall()).toBe(Manual.WALL_START + 5); - clock.stepWall(Wall(Manual.WALL_START - 1000)); - expect(now()).toBe(5_000_000); - clock.stepWall(Wall(Manual.WALL_START + 1000)); - clock.jump(ns(Milli(1))); - expect(clock.now()).toBe(6_000_000); - expect(clock.wall()).toBe(Manual.WALL_START + 1001); - expect(origin()).toBe(Manual.WALL_START + 1000 - 5); + expect(ns(now())).toBe(0); + expect(ms(wall())).toBe(START); + clock.jump(Duration.millis(5)); + expect(ns(now())).toBe(5_000_000); + expect(ms(wall())).toBe(START + 5); + clock.stepWall(unix(START - 1000)); + expect(ns(now())).toBe(5_000_000); + clock.stepWall(unix(START + 1000)); + clock.jump(Duration.millis(1)); + expect(ns(clock.now())).toBe(6_000_000); + expect(ms(clock.wall())).toBe(START + 1001); + expect(ms(origin())).toBe(START + 1000 - 5); }); test("many small advances move wall time by their combined duration", () => { const clock = new Manual(); - for (let i = 0; i < 10_000; i++) clock.jump(Nano(100)); - expect(clock.now()).toBe(1_000_000); - expect(clock.wall()).toBe(Manual.WALL_START + 1); + for (let i = 0; i < 10_000; i++) clock.jump(Duration.nanos(100)); + expect(ns(clock.now())).toBe(1_000_000); + expect(ms(clock.wall())).toBe(START + 1); }); test("installation restores nested and out-of-order scopes without reviving them", () => { const outer = manual(); - outer.jump(Nano(4)); + outer.jump(Duration.nanos(4)); const inner = manual(); - inner.jump(Nano(8)); - expect(now()).toBe(8); + inner.jump(Duration.nanos(8)); + expect(ns(now())).toBe(8); installs[0].close(); - expect(now()).toBe(8); + expect(ns(now())).toBe(8); installs[1].close(); - const restored = now(); + const restored = ns(now()); installs[1].close(); - expect(now()).toBeGreaterThanOrEqual(restored); - expect(now()).not.toBe(4); + expect(ns(now())).toBeGreaterThanOrEqual(restored); + expect(ns(now())).not.toBe(4); }); test("deadlines fire in time then arming order and reached deadlines fire without advance", async () => { const clock = manual(); const order: number[] = []; - void sleepUntil(Instant(10)).then(() => order.push(2)); - void sleepUntil(Instant(5)).then(() => order.push(1)); - void sleepUntil(Instant(10)).then(() => order.push(3)); - await clock.advance(Nano(10)); + void sleepUntil(instant(10)).then(() => order.push(2)); + void sleepUntil(instant(5)).then(() => order.push(1)); + void sleepUntil(instant(10)).then(() => order.push(3)); + await clock.advance(Duration.nanos(10)); expect(order).toEqual([1, 2, 3]); - await sleepUntil(Instant(1)); - await sleep(Nano.zero); + await sleepUntil(instant(1)); + await sleep(Duration.ZERO); }); test("advance drains arbitrarily deep microtasks and newly due timers", async () => { const clock = manual(); let done = false; void (async () => { - await sleep(Nano(5)); + await sleep(Duration.nanos(5)); for (let i = 0; i < 1000; i++) await Promise.resolve(); - await sleep(Nano.zero); + await sleep(Duration.ZERO); done = true; })(); - await clock.advance(Nano(5)); + await clock.advance(Duration.nanos(5)); expect(done).toBe(true); }); for (const driver of ["advance", "fire"] as const) { test(`${driver} waits out a chain of host-task yields before moving time`, async () => { const clock = manual(); - void sleep(Nano(10)); + void sleep(Duration.nanos(10)); const seen: number[] = []; void (async () => { for (let i = 0; i < 3; i++) await yieldNow(); - seen.push(now()); + seen.push(ns(now())); })(); - if (driver === "advance") await clock.advance(Nano(10)); - else expect(await clock.fire()).toBe(10); + if (driver === "advance") await clock.advance(Duration.nanos(10)); + else expect(ns(await clock.fire())).toBe(10); expect(seen).toEqual([0]); }); } @@ -134,66 +182,66 @@ for (const driver of ["advance", "fire"] as const) { test("a sleep stays on its creation clock and abort releases it", async () => { const first = manual(); let done = false; - const pending = sleep(Nano(10)).then(() => { + const pending = sleep(Duration.nanos(10)).then(() => { done = true; }); const second = manual(); - await second.advance(Nano(10)); + await second.advance(Duration.nanos(10)); expect(done).toBe(false); - await first.advance(Nano(10)); + await first.advance(Duration.nanos(10)); await pending; const abort = new AbortController(); - const cancelled = sleep(Nano(100), { signal: abort.signal }).catch((error: unknown) => error); + const cancelled = sleep(Duration.nanos(100), { signal: abort.signal }).catch((error: unknown) => error); abort.abort(); expect(await cancelled).toHaveProperty("name", "AbortError"); - await second.advance(Nano(100)); - await expect(sleep(Nano.zero, { signal: abort.signal })).rejects.toHaveProperty("name", "AbortError"); + await second.advance(Duration.nanos(100)); + await expect(sleep(Duration.ZERO, { signal: abort.signal })).rejects.toHaveProperty("name", "AbortError"); }); test("timeouts prefer ready work, propagate rejection, and expire on the manual deadline", async () => { const clock = manual(); - expect(await timeout(Nano.zero, Promise.resolve(7))).toBe(7); + expect(await timeout(Duration.ZERO, Promise.resolve(7))).toBe(7); const failure = new Error("operation failed"); - await expect(timeout(Nano(10), Promise.reject(failure))).rejects.toBe(failure); - const pending = timeout(Nano(10), new Promise(() => {})).catch((error: unknown) => error); - await clock.advance(Nano(9)); - await clock.advance(Nano(1)); + await expect(timeout(Duration.nanos(10), Promise.reject(failure))).rejects.toBe(failure); + const pending = timeout(Duration.nanos(10), new Promise(() => {})).catch((error: unknown) => error); + await clock.advance(Duration.nanos(9)); + await clock.advance(Duration.nanos(1)); expect(await pending).toBeInstanceOf(Elapsed); }); test("a timeout signal aborts at the manual deadline unless its parent aborts first", async () => { const clock = manual(); - const signal = timeoutSignal(Nano(10)); - await clock.advance(Nano(9)); + const signal = timeoutSignal(Duration.nanos(10)); + await clock.advance(Duration.nanos(9)); expect(signal.aborted).toBe(false); - await clock.advance(Nano(1)); + await clock.advance(Duration.nanos(1)); expect(signal.reason).toHaveProperty("name", "TimeoutError"); const parent = new AbortController(); - const child = timeoutSignal(Nano(10), { signal: parent.signal }); + const child = timeoutSignal(Duration.nanos(10), { signal: parent.signal }); parent.abort("closed"); expect(child.reason).toBe("closed"); - await clock.advance(Nano(10)); + await clock.advance(Duration.nanos(10)); expect(child.reason).toBe("closed"); const late = new AbortController(); - const fired = timeoutSignal(Nano(10), { signal: late.signal }); - clock.jump(Nano(10)); + const fired = timeoutSignal(Duration.nanos(10), { signal: late.signal }); + clock.jump(Duration.nanos(10)); late.abort("closed"); expect(fired.reason).toHaveProperty("name", "TimeoutError"); }); test("interval burst delivers every missed scheduled tick", async () => { const clock = manual(); - const ticks = interval(Nano(10)); + const ticks = interval(Duration.nanos(10)); try { - expect(await ticks.tick()).toBe(0); - clock.jump(Nano(35)); - expect(await ticks.tick()).toBe(10); - expect(await ticks.tick()).toBe(20); - expect(await ticks.tick()).toBe(30); + expect(ns(await ticks.tick())).toBe(0); + clock.jump(Duration.nanos(35)); + expect(ns(await ticks.tick())).toBe(10); + expect(ns(await ticks.tick())).toBe(20); + expect(ns(await ticks.tick())).toBe(30); const next = ticks.tick(); - await clock.advance(Nano(5)); - expect(await next).toBe(40); - expect(ticks.period()).toBe(10); + await clock.advance(Duration.nanos(5)); + expect(ns(await next)).toBe(40); + expect(ticks.period().asNanos()).toBe(10); } finally { ticks.close(); } @@ -202,15 +250,15 @@ test("interval burst delivers every missed scheduled tick", async () => { for (const behavior of [MissedTickBehavior.Delay, MissedTickBehavior.Skip]) { test(`interval ${behavior} resumes after a missed tick`, async () => { const clock = manual(); - const ticks = interval(Nano(10)); + const ticks = interval(Duration.nanos(10)); ticks.setMissedTickBehavior(behavior); try { - expect(await ticks.tick()).toBe(0); - clock.jump(Nano(35)); - expect(await ticks.tick()).toBe(10); + expect(ns(await ticks.tick())).toBe(0); + clock.jump(Duration.nanos(35)); + expect(ns(await ticks.tick())).toBe(10); const next = ticks.tick(); - await clock.advance(Nano(behavior === MissedTickBehavior.Delay ? 10 : 5)); - expect(await next).toBe(behavior === MissedTickBehavior.Delay ? 45 : 40); + await clock.advance(Duration.nanos(behavior === MissedTickBehavior.Delay ? 10 : 5)); + expect(ns(await next)).toBe(behavior === MissedTickBehavior.Delay ? 45 : 40); } finally { ticks.close(); } @@ -219,8 +267,8 @@ for (const behavior of [MissedTickBehavior.Delay, MissedTickBehavior.Skip]) { test("an interval cancels pending ticks, refuses concurrent ticks and stays closed", async () => { manual(); - expect(() => interval(Nano.zero)).toThrow(RangeError); - const ticks = interval(Nano(10)); + expect(() => interval(Duration.ZERO)).toThrow(RangeError); + const ticks = interval(Duration.nanos(10)); await ticks.tick(); const pending = ticks.tick().catch((error: unknown) => error); await expect(ticks.tick()).rejects.toThrow("already pending"); @@ -234,21 +282,21 @@ test("the host clock counts from the performance time origin", () => { // biome-ignore lint/style/noRestrictedGlobals: checks the host backend against the global it wraps. const host = performance; const before = host.now(); - const at = Nano.toMilli(Instant.durationSince(now(), Instant.zero)); + const at = now().since(Instant.ZERO).asMillis(); expect(at).toBeGreaterThanOrEqual(before); expect(at).toBeLessThanOrEqual(host.now()); - expect(origin()).toBe(host.timeOrigin); + expect(ms(origin())).toBe(host.timeOrigin); }); test("an unreferenced sleep still completes on the host", async () => { hostTime(); // tests the host backend itself - await sleep(Nano.fromMilli(Milli(1)), { ref: false }); + await sleep(Duration.millis(1), { ref: false }); }); test("manual installation leaves the host's own timers real", async () => { manual(); await hostTimeout(0); - expect(now()).toBe(0); + expect(ns(now())).toBe(0); }); test("many cancelled and live timers retain deadline and arming order", async () => { @@ -261,7 +309,7 @@ test("many cancelled and live timers retain deadline and arming order", async () aborts.push(abort); const at = 1 + ((index * 73) % 17); if (index % 3 !== 0) expected.push({ at, index }); - return sleepUntil(Instant(at), { signal: abort.signal }).then( + return sleepUntil(instant(at), { signal: abort.signal }).then( () => { fired.push(index); }, @@ -269,7 +317,7 @@ test("many cancelled and live timers retain deadline and arming order", async () ); }); for (let index = aborts.length - 1; index >= 0; index--) if (index % 3 === 0) aborts[index].abort(); - await clock.advance(Nano(17)); + await clock.advance(Duration.nanos(17)); await Promise.all(pending); expect(fired).toEqual(expected.sort((a, b) => a.at - b.at || a.index - b.index).map(({ index }) => index)); }); @@ -277,62 +325,62 @@ test("many cancelled and live timers retain deadline and arming order", async () test("fire advances exactly to the earliest deadline and runs only what is due", async () => { const clock = manual(); const order: number[] = []; - void sleepUntil(Instant(30)).then(() => order.push(30)); - void sleepUntil(Instant(10)).then(() => order.push(1)); - void sleepUntil(Instant(20)).then(() => order.push(20)); - void sleepUntil(Instant(10)).then(() => order.push(2)); - clock.jump(Nano(3)); - expect(await clock.fire()).toBe(10); - expect(now()).toBe(10); + void sleepUntil(instant(30)).then(() => order.push(30)); + void sleepUntil(instant(10)).then(() => order.push(1)); + void sleepUntil(instant(20)).then(() => order.push(20)); + void sleepUntil(instant(10)).then(() => order.push(2)); + clock.jump(Duration.nanos(3)); + expect(ns(await clock.fire())).toBe(10); + expect(ns(now())).toBe(10); expect(order).toEqual([1, 2]); - expect(await clock.fire()).toBe(20); - expect(await clock.fire()).toBe(30); + expect(ns(await clock.fire())).toBe(20); + expect(ns(await clock.fire())).toBe(30); expect(order).toEqual([1, 2, 20, 30]); }); test("fire picks an earlier timer that a pending microtask chain arms", async () => { const clock = manual(); - void sleepUntil(Instant(100)); - void Promise.resolve().then(() => sleepUntil(Instant(10))); - expect(await clock.fire()).toBe(10); + void sleepUntil(instant(100)); + void Promise.resolve().then(() => sleepUntil(instant(10))); + expect(ns(await clock.fire())).toBe(10); }); test("fire waits, without a timer, until a later host task arms one", async () => { const clock = manual(); const abort = new AbortController(); - void sleep(Nano(5), { signal: abort.signal }).catch(() => {}); + void sleep(Duration.nanos(5), { signal: abort.signal }).catch(() => {}); abort.abort(); let fired: number | undefined; const pending = clock.fire().then((at) => { - fired = at; + fired = ns(at); }); await hostTimeout(0); await hostTimeout(0); expect(fired).toBeUndefined(); await expect(clock.fire()).rejects.toThrow("already pending"); - void sleep(Nano(7)); + void sleep(Duration.nanos(7)); await pending; expect(fired).toBe(7); }); test("fire resolves when a later host task arms an already-due timer", async () => { const clock = manual(); - clock.jump(Nano(4)); + clock.jump(Duration.nanos(4)); let woke = false; const pending = clock.fire(); await hostTimeout(0); - void sleep(Nano(0)).then(() => { + void sleep(Duration.nanos(0)).then(() => { woke = true; }); - expect(await pending).toBe(4); + expect(ns(await pending)).toBe(4); expect(woke).toBe(true); }); test("fire stops at an already-due timer a pending microtask chain arms", async () => { const clock = manual(); - void sleepUntil(Instant(100)); - void Promise.resolve().then(() => sleep(Nano(0))); - expect(await clock.fire()).toBe(0); + void sleepUntil(instant(100)); + void Promise.resolve().then(() => sleep(Duration.nanos(0))); + expect(ns(await clock.fire())).toBe(0); }); test("advance steps through deadlines armed by earlier timers and stops at its target", async () => { @@ -340,14 +388,14 @@ test("advance steps through deadlines armed by earlier timers and stops at its t const at: number[] = []; void (async () => { for (let i = 0; i < 4; i++) { - await sleep(Nano(10)); - at.push(now()); + await sleep(Duration.nanos(10)); + at.push(ns(now())); } })(); - await clock.advance(Nano(30)); + await clock.advance(Duration.nanos(30)); expect(at).toEqual([10, 20, 30]); - expect(now()).toBe(30); - expect(await clock.fire()).toBe(40); + expect(ns(now())).toBe(30); + expect(ns(await clock.fire())).toBe(40); expect(at).toEqual([10, 20, 30, 40]); }); @@ -355,56 +403,56 @@ test("advance drains one timer's tasks before firing the next at the same deadli const clock = manual(); const abort = new AbortController(); const order: string[] = []; - void sleep(Nano(10)).then(() => { + void sleep(Duration.nanos(10)).then(() => { order.push("first"); abort.abort(); }); - void sleep(Nano(10), { signal: abort.signal }).then( + void sleep(Duration.nanos(10), { signal: abort.signal }).then( () => order.push("second"), () => order.push("cancelled"), ); - await clock.advance(Nano(10)); + await clock.advance(Duration.nanos(10)); expect(order).toEqual(["first", "cancelled"]); }); test("a timer armed while draining joins existing timers at the same deadline", async () => { const clock = manual(); const order: string[] = []; - void sleep(Nano(10)).then(() => { + void sleep(Duration.nanos(10)).then(() => { order.push("first"); - void sleepUntil(Instant(10)).then(() => order.push("new")); + void sleepUntil(instant(10)).then(() => order.push("new")); }); - void sleep(Nano(10)).then(() => order.push("second")); - await clock.advance(Nano(10)); + void sleep(Duration.nanos(10)).then(() => order.push("second")); + await clock.advance(Duration.nanos(10)); expect(order).toEqual(["first", "second", "new"]); }); test("a past deadline armed while draining observes the current instant", async () => { const clock = manual(); const at: number[] = []; - void sleep(Nano(10)).then(async () => { - at.push(now()); - await sleepUntil(Instant(3)); - at.push(now()); + void sleep(Duration.nanos(10)).then(async () => { + at.push(ns(now())); + await sleepUntil(instant(3)); + at.push(ns(now())); }); - await clock.advance(Nano(10)); + await clock.advance(Duration.nanos(10)); expect(at).toEqual([10, 10]); - expect(clock.now()).toBe(10); + expect(ns(clock.now())).toBe(10); }); test("drive fires each deadline its work waits on and stops when the work settles", async () => { const clock = manual(); let late = false; - void sleepUntil(Instant(100)).then(() => { + void sleepUntil(instant(100)).then(() => { late = true; }); const work = (async () => { - await sleep(Nano(10)); - await sleep(Nano(20)); + await sleep(Duration.nanos(10)); + await sleep(Duration.nanos(20)); return now(); })(); - expect(await clock.drive(work)).toBe(30); - expect(clock.now()).toBe(30); + expect(ns(await clock.drive(work))).toBe(30); + expect(ns(clock.now())).toBe(30); await hostTimeout(0); expect(late).toBe(false); }); @@ -413,13 +461,13 @@ test("drive settles with its work's rejection at the deadline that caused it", a const clock = manual(); const err = await clock .drive( - sleep(Nano(10)).then(() => { + sleep(Duration.nanos(10)).then(() => { throw new Error("boom"); }), ) .catch((e: unknown) => e); expect(err).toEqual(new Error("boom")); - expect(clock.now()).toBe(10); + expect(ns(clock.now())).toBe(10); }); for (const settles of ["before any timer", "on a later host task"] as const) { @@ -428,13 +476,13 @@ for (const settles of ["before any timer", "on a later host task"] as const) { const work = settles === "before any timer" ? Promise.resolve(1) : hostTimeout(0).then(() => 1); expect(await clock.drive(work)).toBe(1); const fired: number[] = []; - void sleep(ns(Milli(60_000))).then(() => fired.push(now())); - void sleep(ns(Milli(70_000))).then(() => fired.push(now())); + void sleep(Duration.millis(60_000)).then(() => fired.push(ns(now()))); + void sleep(Duration.millis(70_000)).then(() => fired.push(ns(now()))); await hostTimeout(0); expect(fired).toEqual([]); - expect(clock.now()).toBe(0); - expect(await clock.fire()).toBe(ns(Milli(60_000))); - expect(fired).toEqual([ns(Milli(60_000))]); + expect(ns(clock.now())).toBe(0); + expect(ns(await clock.fire())).toBe(60_000_000_000); + expect(fired).toEqual([60_000_000_000]); }); } @@ -446,64 +494,68 @@ for (const driver of ["advance", "fire", "drive"] as const) { release = resolve; }); const pending = - driver === "advance" ? clock.advance(Nano(10)) : driver === "fire" ? clock.fire() : clock.drive(work); + driver === "advance" + ? clock.advance(Duration.nanos(10)) + : driver === "fire" + ? clock.fire() + : clock.drive(work); try { - await expect(clock.advance(Nano(100))).rejects.toThrow("already pending"); - expect(() => clock.jump(Nano(100))).toThrow("already pending"); + await expect(clock.advance(Duration.nanos(100))).rejects.toThrow("already pending"); + expect(() => clock.jump(Duration.nanos(100))).toThrow("already pending"); await expect(clock.fire()).rejects.toThrow("already pending"); expect(await clock.drive(Promise.resolve()).catch((e: unknown) => e)).toEqual( new Error("time driver already pending"), ); - expect(clock.now()).toBe(0); + expect(ns(clock.now())).toBe(0); } finally { // Let fire and drive finish even if an assertion fails before they have a timer. - void sleepUntil(Instant(10)).then(release); + void sleepUntil(instant(10)).then(release); await pending; } - expect(clock.now()).toBe(10); - clock.jump(Nano(1)); - await clock.advance(Nano(1)); - void sleep(Nano(1)); - expect(await clock.fire()).toBe(13); + expect(ns(clock.now())).toBe(10); + clock.jump(Duration.nanos(1)); + await clock.advance(Duration.nanos(1)); + void sleep(Duration.nanos(1)); + expect(ns(await clock.fire())).toBe(13); }); } test("a timer callback cannot move time beyond the active advance target", async () => { const clock = manual(); const at: number[] = []; - const callback = sleep(Nano(5)).then(async () => { - await expect(clock.advance(Nano(100))).rejects.toThrow("already pending"); - expect(() => clock.jump(Nano(100))).toThrow("already pending"); + const callback = sleep(Duration.nanos(5)).then(async () => { + await expect(clock.advance(Duration.nanos(100))).rejects.toThrow("already pending"); + expect(() => clock.jump(Duration.nanos(100))).toThrow("already pending"); await expect(clock.fire()).rejects.toThrow("already pending"); - await sleepUntil(Instant(7)); - at.push(now()); + await sleepUntil(instant(7)); + at.push(ns(now())); }); - await clock.advance(Nano(10)); + await clock.advance(Duration.nanos(10)); await callback; expect(at).toEqual([7]); - expect(clock.now()).toBe(10); + expect(ns(clock.now())).toBe(10); }); test("fire returns the first deadline reached when a host task arms an earlier timer", async () => { const clock = manual(); const at: number[] = []; - void sleepUntil(Instant(10)).then(() => at.push(now())); + void sleepUntil(instant(10)).then(() => at.push(ns(now()))); const pending = clock.fire(); const channel = new MessageChannel(); try { channel.port1.onmessage = () => { channel.port1.close(); channel.port2.close(); - void sleepUntil(Instant(5)).then(() => at.push(now())); + void sleepUntil(instant(5)).then(() => at.push(ns(now()))); }; channel.port2.postMessage(null); - const fired = await pending; + const fired = ns(await pending); // A host may run the task before selection or during the drain after firing. // Either way fire must stop where it first observed a timer becoming ready. - expect(fired).toBe(at[0]); + expect(fired).toBe(at[0]); expect(at.every((value) => value === fired)).toBe(true); if (fired < 10) { - expect(await clock.fire()).toBe(10); + expect(ns(await clock.fire())).toBe(10); expect(at).toEqual([5, 10]); } } finally { diff --git a/js/clock/src/index.ts b/js/clock/src/index.ts index eba82207464..7c6927d55f7 100644 --- a/js/clock/src/index.ts +++ b/js/clock/src/index.ts @@ -6,7 +6,7 @@ */ import { backend } from "./ambient.ts"; -import { Wall } from "./types.ts"; +import { type Wall, wallOf } from "./types.ts"; export type { Installed } from "./ambient.ts"; export { Manual } from "./manual.ts"; @@ -22,17 +22,14 @@ export { timeoutSignal, yieldNow, } from "./timer.ts"; -export { Instant, Micro, Milli, Nano, Second, Wall } from "./types.ts"; +export { Duration, Instant, Wall } from "./types.ts"; -/** Read the installed clock's wall time in Unix milliseconds. */ +/** Read the installed clock's wall time. */ export function wall(): Wall { - return Wall(backend().wall()); + return wallOf(backend().wall()); } -/** - * Read the installed clock's wall time at instant zero, in Unix milliseconds. - * Rust's `kio::clock::origin()` pairs a nanosecond `Wall` with an instant instead. - */ +/** Read the installed clock's wall time at `Instant.ZERO`. */ export function origin(): Wall { - return Wall(backend().origin()); + return wallOf(backend().origin()); } diff --git a/js/clock/src/manual.ts b/js/clock/src/manual.ts index f742edf2b2e..b63c664aeb5 100644 --- a/js/clock/src/manual.ts +++ b/js/clock/src/manual.ts @@ -1,7 +1,7 @@ import { type Installed, install } from "./ambient.ts"; import type { Backend } from "./backend.ts"; import { drain, host } from "./host.ts"; -import { Instant, Nano, Wall } from "./types.ts"; +import { type Duration, type Instant, instantOf, type Wall, wallMillis, wallOf } from "./types.ts"; type Timer = { at: number; order: number; index: number; ready: () => void }; @@ -11,11 +11,12 @@ type Timer = { at: number; order: number; index: number; ready: () => void }; */ export class Manual { /** The reproducible starting wall time, 2025-01-01T00:00:00Z. */ - static readonly WALL_START = Wall(1_735_689_600_000); - #now = Instant.zero; + static readonly WALL_START: Wall = wallOf(1_735_689_600_000); + // Nanoseconds since the origin. + #now = 0; // Wall time is derived from an anchor so tiny advances don't vanish into an epoch-sized float. - #wallAnchor = Manual.WALL_START; - #wallAnchorAt = Instant.zero; + #wallAnchor = wallMillis(Manual.WALL_START); + #wallAnchorAt = 0; #timers: Timer[] = []; #order = 0; #revision = 0; @@ -26,8 +27,8 @@ export class Manual { #armed?: () => void; #backend: Backend = { now: () => this.#now, - wall: () => this.wall(), - origin: () => this.#wallAnchor - Nano.toMilli(Nano(this.#wallAnchorAt)), + wall: () => this.#wall(), + origin: () => this.#wallAnchor - this.#wallAnchorAt / 1_000_000, arm: (at, ready) => { const timer = { at, order: this.#order++, index: this.#timers.length, ready }; this.#timers.push(timer); @@ -57,20 +58,24 @@ export class Manual { /** Read this clock's instant without installing it. */ now(): Instant { - return this.#now; + return instantOf(this.#now); } /** Read this clock's wall time without installing it. */ wall(): Wall { - return Wall.add(this.#wallAnchor, Instant.durationSince(this.#now, this.#wallAnchorAt)); + return wallOf(this.#wall()); + } + + #wall(): number { + return this.#wallAnchor + (this.#now - this.#wallAnchorAt) / 1_000_000; } /** Jump forward without draining tasks, firing due timers late as a stalled event loop would. */ - jump(duration: Nano): void { + jump(duration: Duration): void { if (this.#driving) throw new Error("time driver already pending"); this.#driving = true; try { - this.#now = Instant.add(this.#now, duration); + this.#now += duration.asNanos(); this.#fire(); } finally { this.#driving = false; @@ -78,11 +83,11 @@ export class Manual { } /** Advance through each due deadline, draining tasks and pending yields before continuing to the target. */ - async advance(duration: Nano): Promise { + async advance(duration: Duration): Promise { if (this.#driving) throw new Error("time driver already pending"); this.#driving = true; try { - await this.#advance(Instant.add(this.#now, duration)); + await this.#advance(this.#now + duration.asNanos()); } finally { this.#driving = false; } @@ -97,7 +102,7 @@ export class Manual { this.#driving = true; try { await this.#advance(); - return this.#now; + return instantOf(this.#now); } finally { this.#driving = false; } @@ -131,12 +136,12 @@ export class Manual { /** Set wall time forward or backward without passing monotonic time. */ stepWall(wall: Wall): void { - this.#wallAnchor = Wall(wall); + this.#wallAnchor = wallMillis(wall); this.#wallAnchorAt = this.#now; } // Without a target, advances to the earliest deadline unless `stop` holds first. - async #advance(target?: Instant, stop?: () => boolean): Promise { + async #advance(target?: number, stop?: () => boolean): Promise { const fired = this.#fired; // Reached timers armed while draining join the heap once a target is chosen. this.#advancing = target !== undefined; @@ -158,12 +163,12 @@ export class Manual { this.#armed = undefined; continue; } - target = Instant(Math.max(this.#now, at)); + target = Math.max(this.#now, at); this.#advancing = true; } const first = this.#timers[0]; if (first !== undefined && first.at <= target) { - this.#now = Instant(Math.max(this.#now, first.at)); + this.#now = Math.max(this.#now, first.at); this.#ready(first); } else if (this.#now < target) { this.#now = target; diff --git a/js/clock/src/timer.ts b/js/clock/src/timer.ts index 2d800783e89..0bbc8e2ed4f 100644 --- a/js/clock/src/timer.ts +++ b/js/clock/src/timer.ts @@ -1,6 +1,6 @@ import { backend } from "./ambient.ts"; import type { Backend } from "./backend.ts"; -import { Instant, type Nano } from "./types.ts"; +import { type Duration, type Instant, instantNanos, instantOf } from "./types.ts"; function aborted(): DOMException { return new DOMException("timer closed", "AbortError"); @@ -9,7 +9,7 @@ function aborted(): DOMException { // `ref: false` lets a Node or Bun process exit while only this timer is pending; browsers ignore it. type Options = { signal?: AbortSignal; ref?: boolean }; -function wait(clock: Backend, at: Instant, options: Options = {}): { promise: Promise; cancel: () => void } { +function wait(clock: Backend, at: number, options: Options = {}): { promise: Promise; cancel: () => void } { const { signal, ref = true } = options; let cancel = () => {}; const promise = new Promise((resolve, reject) => { @@ -35,18 +35,18 @@ function wait(clock: Backend, at: Instant, options: Options = {}): { promise: Pr /** Read the installed clock's monotonic instant. */ export function now(): Instant { - return Instant(backend().now()); + return instantOf(backend().now()); } /** Complete when the installed clock reaches an instant, or reject on abort; `ref: false` won't hold the process open. */ export function sleepUntil(at: Instant, options?: { signal?: AbortSignal; ref?: boolean }): Promise { - return wait(backend(), Instant(at), options).promise; + return wait(backend(), instantNanos(at), options).promise; } /** Complete after a duration on the installed clock, or reject on abort; `ref: false` won't hold the process open. */ -export function sleep(duration: Nano, options?: { signal?: AbortSignal; ref?: boolean }): Promise { +export function sleep(duration: Duration, options?: { signal?: AbortSignal; ref?: boolean }): Promise { const clock = backend(); - return wait(clock, Instant.add(Instant(clock.now()), duration), options).promise; + return wait(clock, clock.now() + duration.asNanos(), options).promise; } /** Complete in a later host task, giving the host's other work a turn; a `Manual` clock won't advance past it. */ @@ -65,9 +65,9 @@ export class Elapsed extends Error { } /** Resolve an operation within a duration, preferring an already-ready operation. */ -export function timeout(duration: Nano, operation: PromiseLike): Promise { +export function timeout(duration: Duration, operation: PromiseLike): Promise { const clock = backend(); - const timer = wait(clock, Instant.add(Instant(clock.now()), duration)); + const timer = wait(clock, clock.now() + duration.asNanos()); return new Promise((resolve, reject) => { let done = false; const finish = (ok: boolean, value: unknown) => { @@ -89,7 +89,7 @@ export function timeout(duration: Nano, operation: PromiseLike): Promise {}; disarm = clock.arm( - Instant.add(Instant(clock.now()), duration), + clock.now() + duration.asNanos(), () => { parent?.removeEventListener("abort", abort); controller.abort(new DOMException("signal timed out", "TimeoutError")); @@ -131,16 +131,15 @@ export type MissedTickBehavior = (typeof MissedTickBehavior)[keyof typeof Missed /** An owned repeating timer, bound to the clock it was created on. */ export class Interval { #clock = backend(); - #next = Instant(this.#clock.now()); - #period: Nano; + #next = this.#clock.now(); + #period: Duration; #missed: MissedTickBehavior = MissedTickBehavior.Burst; #abort = new AbortController(); #pending = false; /** Start a positive-period interval whose first tick is ready at once. */ - constructor(period: Nano) { - Instant.add(Instant.zero, period); - if (period === 0) throw new RangeError("interval period must be positive"); + constructor(period: Duration) { + if (period.isZero()) throw new RangeError("interval period must be positive"); this.#period = period; } @@ -152,19 +151,20 @@ export class Interval { await wait(this.#clock, this.#next, { signal: this.#abort.signal }).promise; const scheduled = this.#next; const now = this.#clock.now(); - let next = Instant.add(scheduled, this.#period); + const period = this.#period.asNanos(); + let next = scheduled + period; if (next <= now) { switch (this.#missed) { case MissedTickBehavior.Delay: - next = Instant(now + this.#period); + next = now + period; break; case MissedTickBehavior.Skip: - next = Instant(now + this.#period - ((now - scheduled) % this.#period)); + next = now + period - ((now - scheduled) % period); break; } } this.#next = next; - return scheduled; + return instantOf(scheduled); } finally { this.#pending = false; } @@ -177,7 +177,7 @@ export class Interval { } /** Return the time between ticks. */ - period(): Nano { + period(): Duration { return this.#period; } @@ -188,6 +188,6 @@ export class Interval { } /** Tick every positive period on the installed clock, starting at once. */ -export function interval(period: Nano): Interval { +export function interval(period: Duration): Interval { return new Interval(period); } diff --git a/js/clock/src/types.ts b/js/clock/src/types.ts index e78e40d48ec..0a2df100315 100644 --- a/js/clock/src/types.ts +++ b/js/clock/src/types.ts @@ -1,82 +1,443 @@ -function checked(value: number): number { - if (!Number.isFinite(value) || value < 0) throw new RangeError(`invalid time: ${value}`); +function checked(value: number, what: string): number { + if (!Number.isFinite(value) || value < 0) throw new RangeError(`invalid ${what}: ${value}`); return value; } -/** A nonnegative duration in nanoseconds. */ -export type Nano = number & { readonly _brand: "clock-nano" }; - -/** Brand nanoseconds or convert another duration unit. */ -export const Nano = Object.assign((value: number): Nano => checked(value) as Nano, { - zero: 0 as Nano, - fromMicro: (value: Micro): Nano => Nano(value * 1_000), - toMicro: (value: Nano): Micro => Micro(value / 1_000), - fromMilli: (value: Milli): Nano => Nano(value * 1_000_000), - toMilli: (value: Nano): Milli => Milli(value / 1_000_000), - fromSecond: (value: Second): Nano => Nano(value * 1_000_000_000), - toSecond: (value: Nano): Second => Second(value / 1_000_000_000), -}); - -/** A nonnegative duration in microseconds. */ -export type Micro = number & { readonly _brand: "clock-micro" }; - -/** Brand microseconds or convert another duration unit. */ -export const Micro = Object.assign((value: number): Micro => checked(value) as Micro, { - zero: 0 as Micro, - fromNano: (value: Nano): Micro => Micro(value / 1_000), - toNano: (value: Micro): Nano => Nano(value * 1_000), - fromMilli: (value: Milli): Micro => Micro(value * 1_000), - toMilli: (value: Micro): Milli => Milli(value / 1_000), - fromSecond: (value: Second): Micro => Micro(value * 1_000_000), - toSecond: (value: Micro): Second => Second(value / 1_000_000), -}); - -/** A nonnegative duration in milliseconds. */ -export type Milli = number & { readonly _brand: "clock-milli" }; - -/** Brand milliseconds or convert another duration unit. */ -export const Milli = Object.assign((value: number): Milli => checked(value) as Milli, { - zero: 0 as Milli, - fromNano: (value: Nano): Milli => Milli(value / 1_000_000), - toNano: (value: Milli): Nano => Nano(value * 1_000_000), - fromMicro: (value: Micro): Milli => Milli(value / 1_000), - toMicro: (value: Milli): Micro => Micro(value * 1_000), - fromSecond: (value: Second): Milli => Milli(value * 1_000), - toSecond: (value: Milli): Second => Second(value / 1_000), -}); - -/** A nonnegative duration in seconds. */ -export type Second = number & { readonly _brand: "clock-second" }; - -/** Brand seconds or convert another duration unit. */ -export const Second = Object.assign((value: number): Second => checked(value) as Second, { - zero: 0 as Second, - fromNano: (value: Nano): Second => Second(value / 1_000_000_000), - toNano: (value: Second): Nano => Nano(value * 1_000_000_000), - fromMicro: (value: Micro): Second => Second(value / 1_000_000), - toMicro: (value: Second): Micro => Micro(value * 1_000_000), - fromMilli: (value: Milli): Second => Second(value / 1_000), - toMilli: (value: Second): Milli => Milli(value * 1_000), -}); - -/** Nanoseconds since this clock's origin, separate from durations and wall time. */ -export type Instant = number & { readonly _brand: "clock-instant" }; - -/** Brand a logical instant or do arithmetic on its own clock's coordinates. */ -export const Instant = Object.assign((value: number): Instant => checked(value) as Instant, { - zero: 0 as Instant, - add: (at: Instant, duration: Nano): Instant => Instant(at + Nano(duration)), - sub: (at: Instant, duration: Nano): Instant => Instant(at - Nano(duration)), - durationSince: (at: Instant, earlier: Instant): Nano => Nano(Math.max(0, at - earlier)), -}); - -/** Milliseconds since the Unix epoch, separate from monotonic time. */ -export type Wall = number & { readonly _brand: "clock-wall" }; - -/** Brand Unix milliseconds or move wall time by a duration. */ -export const Wall = Object.assign((unixMillis: number): Wall => checked(unixMillis) as Wall, { - UNIX_EPOCH: 0 as Wall, - add: (at: Wall, duration: Nano): Wall => Wall(at + Nano.toMilli(duration)), - sub: (at: Wall, duration: Nano): Wall => Wall(at - Nano.toMilli(duration)), - durationSince: (at: Wall, earlier: Wall): Nano => Nano.fromMilli(Milli(Math.max(0, at - earlier))), -}); +function refuse(what: string): never { + throw new TypeError(`a ${what} is not a number; read it with an explicit unit`); +} + +// Values live under a symbol rather than a `#private` field so test matchers such as `toEqual` +// compare them by value; a private field is invisible to them, so every pair would match. +/** @internal */ +export const VALUE: unique symbol = Symbol("clock value"); +/** @internal */ +export const NANOS: unique symbol = Symbol("clock nanos"); + +// Package-private bridges for backends that count in plain numbers. +/** @internal */ +export let instantOf: (nanos: number) => Instant; +/** @internal */ +export let instantNanos: (at: Instant) => number; +/** @internal */ +export let wallOf: (unixMillis: number) => Wall; +/** @internal */ +export let wallMillis: (at: Wall) => number; + +const NANOS_PER_SEC = 1_000_000_000; + +/** + * A nonnegative span of time, mirroring Rust's `std::time::Duration`. + * + * Build one with a unit (`Duration.millis(5)`) and read it with one (`asMillis()`). It never + * converts to a number implicitly: arithmetic, `<`, and `JSON.stringify` throw. + * + * Whole seconds and the whole nanoseconds past them are held apart, as Rust holds them, so a + * whole number of any unit converts back exactly, such as microseconds since the Unix epoch. + * A value finer than a nanosecond rounds to the nearest one. + */ +export class Duration { + /** No time at all. */ + static readonly ZERO: Duration = new Duration(0, 0); + + /** @internal Whole seconds. */ + readonly [VALUE]: number; + /** @internal Whole nanoseconds past the whole seconds, in `[0, 1e9)`. */ + readonly [NANOS]: number; + declare private readonly kind: "duration"; + + private constructor(secs: number, nanos: number) { + this[VALUE] = secs; + this[NANOS] = nanos; + } + + // `value` units of which `perSec` make a second, split without rounding a whole count. + static #unit(value: number, perSec: number): Duration { + checked(value, "duration"); + let secs = Math.floor(value / perSec); + let rest = value - secs * perSec; + if (rest < 0) { + secs -= 1; + rest += perSec; + } else if (rest >= perSec) { + secs += 1; + rest -= perSec; + } + let nanos = Math.round(rest * (NANOS_PER_SEC / perSec)); + if (nanos >= NANOS_PER_SEC) { + secs += 1; + nanos -= NANOS_PER_SEC; + } + if (!Number.isFinite(secs)) throw new RangeError(`invalid duration: ${value}`); + return new Duration(secs, nanos); + } + + // Whole seconds plus any nanoseconds, possibly out of range or fractional seconds, rounded to + // whole nanoseconds as Rust's are, so a value's conversions agree with its ordering. + static #carry(secs: number, nanos: number): Duration { + let whole = Math.floor(secs); + let rest = Math.round((secs - whole) * NANOS_PER_SEC + nanos); + const carry = Math.floor(rest / NANOS_PER_SEC); + whole += carry; + rest -= carry * NANOS_PER_SEC; + if (rest >= NANOS_PER_SEC) { + whole += 1; + rest -= NANOS_PER_SEC; + } else if (rest < 0) { + whole -= 1; + rest += NANOS_PER_SEC; + } + if (!Number.isFinite(whole) || !Number.isFinite(rest) || whole < 0) { + throw new RangeError(`invalid duration: ${secs}s + ${nanos}ns`); + } + return new Duration(whole, rest); + } + + /** A duration of `value` nanoseconds, rounded to a whole one; throws a `RangeError` unless finite and nonnegative. */ + static nanos(value: number): Duration { + return Duration.#unit(value, NANOS_PER_SEC); + } + + /** A duration of `value` microseconds; throws a `RangeError` unless finite and nonnegative. */ + static micros(value: number): Duration { + return Duration.#unit(value, 1_000_000); + } + + /** A duration of `value` milliseconds; throws a `RangeError` unless finite and nonnegative. */ + static millis(value: number): Duration { + return Duration.#unit(value, 1_000); + } + + /** A duration of `value` seconds; throws a `RangeError` unless finite and nonnegative. */ + static secs(value: number): Duration { + return Duration.#unit(value, 1); + } + + /** The duration in nanoseconds; past 2^53 ns (about 104 days) it rounds. */ + asNanos(): number { + return this[VALUE] * NANOS_PER_SEC + this[NANOS]; + } + + /** The duration in microseconds, possibly fractional. */ + asMicros(): number { + return this[VALUE] * 1_000_000 + this[NANOS] / 1_000; + } + + /** The duration in milliseconds, possibly fractional. */ + asMillis(): number { + return this[VALUE] * 1_000 + this[NANOS] / 1_000_000; + } + + /** The duration in seconds, possibly fractional. */ + asSecs(): number { + return this[VALUE] + this[NANOS] / NANOS_PER_SEC; + } + + /** Whether this is no time at all. */ + isZero(): boolean { + return this[VALUE] === 0 && this[NANOS] === 0; + } + + /** The sum of both durations. */ + add(other: Duration): Duration { + return Duration.#carry(this[VALUE] + other[VALUE], this[NANOS] + other[NANOS]); + } + + /** This duration minus `other`; throws a `RangeError` if `other` is longer. */ + sub(other: Duration): Duration { + if (this.lt(other)) throw new RangeError(`invalid duration: ${this} - ${other}`); + return Duration.#carry(this[VALUE] - other[VALUE], this[NANOS] - other[NANOS]); + } + + /** This duration minus `other`, or zero if `other` is longer. */ + saturatingSub(other: Duration): Duration { + return this.gt(other) ? this.sub(other) : Duration.ZERO; + } + + /** This duration scaled by a finite, nonnegative factor. */ + mul(factor: number): Duration { + checked(factor, "factor"); + return Duration.#carry(this[VALUE] * factor, this[NANOS] * factor); + } + + /** This duration divided by a finite, positive divisor. */ + div(divisor: number): Duration { + if (!(divisor > 0) || !Number.isFinite(divisor)) throw new RangeError(`invalid divisor: ${divisor}`); + return Duration.#carry(this[VALUE] / divisor, this[NANOS] / divisor); + } + + /** How many times `other` fits in this duration, possibly fractional; throws a `RangeError` if `other` is zero. */ + divDuration(other: Duration): number { + if (other.isZero()) throw new RangeError("division by a zero duration"); + return this.asNanos() / other.asNanos(); + } + + /** The distance between both durations, whichever is longer. */ + absDiff(other: Duration): Duration { + return this.ge(other) ? this.sub(other) : other.sub(this); + } + + /** Whether both durations are the same length. */ + eq(other: Duration): boolean { + return this[VALUE] === other[VALUE] && this[NANOS] === other[NANOS]; + } + + /** -1, 0, or 1 as this is less than, equal to, or greater than `other`, for sorting. */ + cmp(other: Duration): -1 | 0 | 1 { + if (this[VALUE] !== other[VALUE]) return this[VALUE] < other[VALUE] ? -1 : 1; + return this[NANOS] < other[NANOS] ? -1 : this[NANOS] > other[NANOS] ? 1 : 0; + } + + /** Whether this duration is shorter than `other`. */ + lt(other: Duration): boolean { + return this.cmp(other) < 0; + } + + /** Whether this duration is at most `other`. */ + le(other: Duration): boolean { + return this.cmp(other) <= 0; + } + + /** Whether this duration is longer than `other`. */ + gt(other: Duration): boolean { + return this.cmp(other) > 0; + } + + /** Whether this duration is at least `other`. */ + ge(other: Duration): boolean { + return this.cmp(other) >= 0; + } + + /** The shorter of both durations. */ + min(other: Duration): Duration { + return other.lt(this) ? other : this; + } + + /** The longer of both durations. */ + max(other: Duration): Duration { + return other.gt(this) ? other : this; + } + + /** This duration limited to `[lo, hi]`. */ + clamp(lo: Duration, hi: Duration): Duration { + return this.max(lo).min(hi); + } + + /** The duration in milliseconds with a unit, such as `1.5ms`. */ + toString(): string { + return `${this.asMillis()}ms`; + } + + /** Refuses: a duration has no unitless number. */ + valueOf(): never { + return refuse("Duration"); + } + + /** Refuses: serialize a number with an explicit unit instead. */ + toJSON(): never { + return refuse("Duration"); + } + + [Symbol.toPrimitive](hint: string): string { + if (hint === "string") return this.toString(); + return refuse("Duration"); + } +} + +/** + * A point on the installed clock's monotonic timeline, mirroring `kio::clock::Instant`. + * + * Instants are only comparable within one clock. The host clock's origin is the realm's + * performance time origin, so a DOM timestamp `t` is `Instant.ZERO.add(Duration.millis(t))`. + */ +export class Instant { + /** The clock's origin. */ + static readonly ZERO: Instant = new Instant(0); + + /** @internal Nanoseconds since the origin. */ + readonly [VALUE]: number; + declare private readonly kind: "instant"; + + private constructor(nanos: number) { + this[VALUE] = nanos; + } + + static { + instantOf = (nanos) => new Instant(checked(nanos, "instant")); + instantNanos = (at) => at[VALUE]; + } + + /** This instant moved forward by `duration`. */ + add(duration: Duration): Instant { + return new Instant(checked(this[VALUE] + duration.asNanos(), "instant")); + } + + /** This instant moved back by `duration`; throws a `RangeError` before the clock's origin. */ + sub(duration: Duration): Instant { + return new Instant(checked(this[VALUE] - duration.asNanos(), "instant")); + } + + /** The time from `earlier` to this instant, zero if `earlier` is later. */ + since(earlier: Instant): Duration { + return this[VALUE] > earlier[VALUE] ? Duration.nanos(this[VALUE] - earlier[VALUE]) : Duration.ZERO; + } + + /** Whether both are the same instant. */ + eq(other: Instant): boolean { + return this[VALUE] === other[VALUE]; + } + + /** -1, 0, or 1 as this is less than, equal to, or greater than `other`, for sorting. */ + cmp(other: Instant): -1 | 0 | 1 { + return this[VALUE] < other[VALUE] ? -1 : this[VALUE] > other[VALUE] ? 1 : 0; + } + + /** Whether this instant is before `other`. */ + lt(other: Instant): boolean { + return this[VALUE] < other[VALUE]; + } + + /** Whether this instant is at or before `other`. */ + le(other: Instant): boolean { + return this[VALUE] <= other[VALUE]; + } + + /** Whether this instant is after `other`. */ + gt(other: Instant): boolean { + return this[VALUE] > other[VALUE]; + } + + /** Whether this instant is at or after `other`. */ + ge(other: Instant): boolean { + return this[VALUE] >= other[VALUE]; + } + + /** The earlier of both instants. */ + min(other: Instant): Instant { + return other[VALUE] < this[VALUE] ? other : this; + } + + /** The later of both instants. */ + max(other: Instant): Instant { + return other[VALUE] > this[VALUE] ? other : this; + } + + /** The time since the origin with a unit, such as `Instant(1.5ms)`. */ + toString(): string { + return `Instant(${this[VALUE] / 1_000_000}ms)`; + } + + /** Refuses: an instant has no unitless number. */ + valueOf(): never { + return refuse("Instant"); + } + + /** Refuses: an instant is meaningless outside its clock. */ + toJSON(): never { + return refuse("Instant"); + } + + [Symbol.toPrimitive](hint: string): string { + if (hint === "string") return this.toString(); + return refuse("Instant"); + } +} + +/** + * A point in wall-clock time, separate from monotonic time, mirroring `kio::clock::Wall`. + * + * Convert Unix milliseconds exactly with `Wall.unixMillis(ms)` and back with `asUnixMillis()`. + */ +export class Wall { + /** 1970-01-01T00:00:00Z. */ + static readonly UNIX_EPOCH: Wall = new Wall(0); + + /** @internal Unix milliseconds, since Unix nanoseconds pass 2^53. */ + readonly [VALUE]: number; + declare private readonly kind: "wall"; + + private constructor(millis: number) { + this[VALUE] = millis; + } + + static { + wallOf = (millis) => new Wall(checked(millis, "wall time")); + wallMillis = (at) => at[VALUE]; + } + + /** The time `millis` Unix milliseconds after the epoch; throws a `RangeError` unless finite and nonnegative. */ + static unixMillis(millis: number): Wall { + return new Wall(checked(millis, "wall time")); + } + + /** The time in Unix milliseconds, possibly fractional, as stored rather than rounded to a nanosecond. */ + asUnixMillis(): number { + return this[VALUE]; + } + + /** This time moved forward by `duration`. */ + add(duration: Duration): Wall { + return new Wall(checked(this[VALUE] + duration.asMillis(), "wall time")); + } + + /** This time moved back by `duration`; throws a `RangeError` before the Unix epoch. */ + sub(duration: Duration): Wall { + return new Wall(checked(this[VALUE] - duration.asMillis(), "wall time")); + } + + /** The time from `earlier` to this one, zero if `earlier` is later. */ + since(earlier: Wall): Duration { + return this[VALUE] > earlier[VALUE] ? Duration.millis(this[VALUE] - earlier[VALUE]) : Duration.ZERO; + } + + /** Whether both are the same time. */ + eq(other: Wall): boolean { + return this[VALUE] === other[VALUE]; + } + + /** -1, 0, or 1 as this is less than, equal to, or greater than `other`, for sorting. */ + cmp(other: Wall): -1 | 0 | 1 { + return this[VALUE] < other[VALUE] ? -1 : this[VALUE] > other[VALUE] ? 1 : 0; + } + + /** Whether this time is before `other`. */ + lt(other: Wall): boolean { + return this[VALUE] < other[VALUE]; + } + + /** Whether this time is at or before `other`. */ + le(other: Wall): boolean { + return this[VALUE] <= other[VALUE]; + } + + /** Whether this time is after `other`. */ + gt(other: Wall): boolean { + return this[VALUE] > other[VALUE]; + } + + /** Whether this time is at or after `other`. */ + ge(other: Wall): boolean { + return this[VALUE] >= other[VALUE]; + } + + /** The time as an ISO 8601 string, or Unix milliseconds past `Date`'s range. */ + toString(): string { + // biome-ignore lint/style/noRestrictedGlobals: formats a time, never reads the host clock. + return this[VALUE] <= 8.64e15 ? new Date(this[VALUE]).toISOString() : `Wall(${this[VALUE]}ms)`; + } + + /** Refuses: a wall time has no unitless number. */ + valueOf(): never { + return refuse("Wall"); + } + + /** Refuses: serialize `asUnixMillis()` instead. */ + toJSON(): never { + return refuse("Wall"); + } + + [Symbol.toPrimitive](hint: string): string { + if (hint === "string") return this.toString(); + return refuse("Wall"); + } +} diff --git a/js/crypto/bench/pump.ts b/js/crypto/bench/pump.ts index 63f65ebef74..9d04ecf1921 100644 --- a/js/crypto/bench/pump.ts +++ b/js/crypto/bench/pump.ts @@ -1,6 +1,6 @@ // Sweep protected frame size x writes in flight through the serial pump, then open every frame. // Bun's WebCrypto stands in for the browser's, so compare runs on the same runtime. -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Broadcast, Time } from "@moq/net"; import { Credential } from "../src/e2ee/index.ts"; @@ -29,7 +29,7 @@ for (const bytes of [160, 1_160, 16_384, 262_144]) { }); const consumer = credential .consume(generation.epoch) - .consume(net.subscribe({ delay: { max: Milli(60_000) } }), "video"); + .consume(net.subscribe({ delay: { max: Duration.millis(60_000) } }), "video"); const producer = await generation.produce(net, "video"); const sealStart = performance.now(); diff --git a/js/crypto/src/e2ee/e2ee.test.ts b/js/crypto/src/e2ee/e2ee.test.ts index 24e601f0147..2198307956e 100644 --- a/js/crypto/src/e2ee/e2ee.test.ts +++ b/js/crypto/src/e2ee/e2ee.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Broadcast, Datagram as NetDatagram, @@ -50,7 +50,7 @@ function netTrack(name: string, timed = true): NetTrack.Producer { } function subscribe(net: NetTrack.Producer): NetTrack.Subscriber { - return net.subscribe({ delay: { max: Milli(60_000) } }); + return net.subscribe({ delay: { max: Duration.millis(60_000) } }); } interface Pair { @@ -253,7 +253,7 @@ test("a broadcast speaks semantic names and puts physical names on the wire", as const consumer = await new Protected.Consumer( net.consume(), generation.credential.consume(generation.epoch), - ).subscribe("video", { delay: { max: Milli(60_000) } }); + ).subscribe("video", { delay: { max: Duration.millis(60_000) } }); const group = video.appendGroup(); await group.writeFrame(ms(1), text("frame")); group.finish(); diff --git a/js/crypto/src/e2ee/transport.test.ts b/js/crypto/src/e2ee/transport.test.ts index 6cd4d85bbad..b5f6e537e2b 100644 --- a/js/crypto/src/e2ee/transport.test.ts +++ b/js/crypto/src/e2ee/transport.test.ts @@ -1,6 +1,6 @@ // Protected tracks over real moq-lite and MoQ Transport sessions: relays forward ciphertext. import { expect, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { type Broadcast, Connection, Origin, type Path, Time } from "@moq/net"; // The in-memory WebTransport pair @moq/net tests with; not part of its published surface. import { createMockTransportPair } from "../../../net/src/mock.ts"; @@ -81,7 +81,7 @@ for (const [name, protocol, routed, timed] of transports) { expect(Epoch.of(remote)).toBe(routed ? generation.epoch : undefined); const epoch = Epoch.of(remote) ?? generation.epoch; const consumer = await new Protected.Consumer(remote, cred.consume(epoch)).subscribe("video", { - delay: { max: Milli(60_000) }, + delay: { max: Duration.millis(60_000) }, }); const received = await consumer.recvGroup(); diff --git a/js/crypto/src/sign/sign.test.ts b/js/crypto/src/sign/sign.test.ts index 19edae28b62..8eaf8448b1a 100644 --- a/js/crypto/src/sign/sign.test.ts +++ b/js/crypto/src/sign/sign.test.ts @@ -1,6 +1,6 @@ // Signed tracks over a real moq-lite session: the subscriber delivers only what verifies. import { expect, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { type Broadcast, Connection, Error as NetError, Origin, Path, Time } from "@moq/net"; // The in-memory WebTransport pair @moq/net tests with; not part of its published surface. import { createMockTransportPair } from "../../../net/src/mock.ts"; @@ -14,7 +14,7 @@ import * as Track from "./track.ts"; const encoder = new TextEncoder(); const decoder = new TextDecoder(); const url = new URL("https://localhost:4443/test"); -const subscription = { delay: { max: Milli(60_000) } }; +const subscription = { delay: { max: Duration.millis(60_000) } }; async function session() { const pair = createMockTransportPair("moq-lite-07-wip"); diff --git a/js/hang/api/container.api.md b/js/hang/api/container.api.md index f2e81f7f2cb..0e16dbd15d8 100644 --- a/js/hang/api/container.api.md +++ b/js/hang/api/container.api.md @@ -3,15 +3,13 @@ ```ts import { AudioConfig } from "@moq/hang/catalog"; import { Format as Format_1 } from "@moq/hang/container"; -import { Micro } from "@moq/clock"; -import { Milli } from "@moq/clock"; import { Net } from "@moq/hang"; import { Signals } from "@moq/hang"; import { VideoConfig } from "@moq/hang/catalog"; export interface BufferedRange { - end: Milli; - start: Milli; + end: Net.Clock.Duration; + start: Net.Clock.Duration; } export type BufferedRanges = BufferedRange[]; @@ -21,27 +19,27 @@ export class Consumer { readonly buffered: Signals.Getter; close(): void; next(): Promise; - readonly spread: Signals.Getter; + readonly spread: Signals.Getter; } export interface ConsumerProps { delay?: Signals.GetterInit; format: Format; predecessor?: Consumer; - warmup?: Milli; + warmup?: Net.Clock.Duration; } export interface Format { decode(payload: Uint8Array, timestamp: Net.Time.Timestamp | undefined): Frame[]; - end?(frame: Frame): Micro | undefined; + end?(frame: Frame): Net.Clock.Duration | undefined; readonly kind?: "audio" | "video" | "data"; } export interface Frame { - duration?: Micro; + duration?: Net.Clock.Duration; keyframe: boolean; payload: Uint8Array; - timestamp: Micro; + timestamp: Net.Clock.Duration; } export namespace Legacy { @@ -50,48 +48,48 @@ export namespace Legacy { export class Format implements Format_1 { constructor(config: AudioConfig | VideoConfig | "audio" | "video" | "data"); decode(frame: Uint8Array): Frame[]; - end(frame: Frame): Micro | undefined; - finishGroup(group: Net.Group.Producer, end?: Micro): void; + end(frame: Frame): Net.Clock.Duration | undefined; + finishGroup(group: Net.Group.Producer, end?: Net.Clock.Duration): void; readonly kind: "audio" | "video" | "data"; } export { Frame }; export class Producer { constructor(track: Net.Track.Producer, format: Legacy.Format); close(err?: Error): void; - discontinuity(end?: Micro): void; - encode(data: Uint8Array | Legacy.Source, timestamp: Micro, keyframe: boolean): void; + discontinuity(endpoint?: Net.Clock.Duration): void; + encode(data: Uint8Array | Legacy.Source, pts: Net.Clock.Duration, keyframe: boolean): void; } export interface Source { byteLength: number; copyTo(buffer: Uint8Array): void; } - export function encodeFrame(source: Uint8Array | Legacy.Source, timestamp: Micro): Uint8Array; + export function encodeFrame(source: Uint8Array | Legacy.Source, timestamp: Net.Clock.Duration): Uint8Array; } export * as Loc from "@moq/loc"; -export const MAX_AGE: Milli; +export const MAX_AGE: Net.Clock.Duration; export type Read = { frame: ReceivedFrame; group: bigint; kind: "frame"; } | { - duration: Micro; + duration: Net.Clock.Duration; kind: "gap"; - timestamp: Micro; + timestamp: Net.Clock.Duration; } | { - end: Micro; + end: Net.Clock.Duration; group: bigint; kind: "end"; }; export interface ReceivedFrame extends Frame { - arrival: Milli; + arrival: Net.Clock.Instant; } export type TrackInfoOptions = { - maxAge?: Milli | null; + maxAge?: Net.Clock.Duration | null; priority: number; }; diff --git a/js/hang/bench/buffered.ts b/js/hang/bench/buffered.ts index 4573bacf5fa..20aa8ce9431 100644 --- a/js/hang/bench/buffered.ts +++ b/js/hang/bench/buffered.ts @@ -1,12 +1,12 @@ /** Sweep buffered groups, frames per group, publishers and players through the container consumer. */ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { type Group, Time, Track, Varint } from "@moq/net"; import { Signal } from "@moq/signals"; import { Consumer } from "../src/container/consumer.ts"; import { Format } from "../src/container/legacy.ts"; // Far past every fixture's span, so only the burst case skips anything. -const HOLD = Milli(1_000_000_000); +const HOLD = Duration.millis(1_000_000_000); // One group per second at 30 fps. const FRAME_US = 33_333; const GROUP_US = 1_000_000; @@ -82,7 +82,11 @@ async function drain(player: Player, expected: number[]): Promise { gaps++; continue; } - if (read.kind !== "frame" || read.frame.timestamp !== want || read.frame.payload[0] !== PAYLOAD[0]) + if ( + read.kind !== "frame" || + read.frame.timestamp.asMicros() !== want || + read.frame.payload[0] !== PAYLOAD[0] + ) throw new Error("frame missing or reordered"); break; } @@ -91,7 +95,9 @@ async function drain(player: Player, expected: number[]): Promise { } function ranges(player: Player): string { - return JSON.stringify(player.consumer.buffered.peek()); + return JSON.stringify( + player.consumer.buffered.peek().map((r) => ({ start: r.start.asMillis(), end: r.end.asMillis() })), + ); } /** Return elapsed ns, the measured operations, gaps and warnings for one case. */ @@ -129,7 +135,7 @@ async function measure( const reads = players.map((player) => player.consumer.next()); for (const source of sources) source.writeFrame(wire(i, frame)); for (const read of await Promise.all(reads)) - if (read?.kind !== "frame" || read.frame.timestamp !== timestamp(i, frame)) + if (read?.kind !== "frame" || read.frame.timestamp.asMicros() !== timestamp(i, frame)) throw new Error("frame missing or reordered"); } for (const source of sources) source.finish(); @@ -161,7 +167,7 @@ async function measure( if (scenario === "burst") { // The budget drops to nothing, so the next arrival makes every older group too stale to keep. - delay.set({ max: Milli.zero }); + delay.set({ max: Duration.ZERO }); start = performance.now(); const sources = tracks.map((track) => track.createGroup(BigInt(groups))); await arrive(sources, players, groups, 0); @@ -173,7 +179,7 @@ async function measure( if (player.received.slice(0, groups).some((group) => !group.isClosed)) throw new Error("skipped group left open"); const read = await player.consumer.next(); - if (read?.kind !== "frame" || read.frame.timestamp !== timestamp(groups, 0)) + if (read?.kind !== "frame" || read.frame.timestamp.asMicros() !== timestamp(groups, 0)) throw new Error("newest frame missing"); } return { ns: elapsed, ops: groups * players.length, gaps, warnings }; diff --git a/js/hang/bench/jitter.ts b/js/hang/bench/jitter.ts index 35da4373424..2adf4b7a7ed 100644 --- a/js/hang/bench/jitter.ts +++ b/js/hang/bench/jitter.ts @@ -1,7 +1,6 @@ // Sweep the jitter estimator's held history against in-order and reordered frames, the per-frame // cost a publisher controls through its timestamp rate. -import type { Milli } from "@moq/clock"; import { Jitter } from "../src/container/jitter.ts"; const FRAMES = 100_000; @@ -13,16 +12,16 @@ for (const held of [64, 512, 4096, 8192]) { // Spaced so `held` frames fit inside the two-second window. const step = 2000 / held; let media = 0; - for (let i = 0; i < held; i++, media += step) jitter.observe(media as Milli, media as Milli); + for (let i = 0; i < held; i++, media += step) jitter.observe(media, media); const started = performance.now(); for (let i = 0; i < FRAMES; i++) { if (order === "in") { - jitter.observe(media as Milli, media as Milli); + jitter.observe(media, media); media += step; } else { // Just behind the newest, so the reference covers almost the whole history. - jitter.observe(media as Milli, (media - 2 * step) as Milli); + jitter.observe(media, media - 2 * step); } } const ns = ((performance.now() - started) * 1e6) / FRAMES; diff --git a/js/hang/bench/slow-group.ts b/js/hang/bench/slow-group.ts index a082161bba1..4004d48f30d 100644 --- a/js/hang/bench/slow-group.ts +++ b/js/hang/bench/slow-group.ts @@ -1,6 +1,6 @@ // Measure warning traffic and catch-up time over the groups a slow consumer skips. -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Time, Track, Varint } from "@moq/net"; import { Signal } from "@moq/signals"; import { Consumer } from "../src/container/consumer.ts"; @@ -9,8 +9,8 @@ import { Format } from "../src/container/legacy.ts"; console.log("groups,warnings,bytes,catchup_ms"); for (const count of [1, 16, 256, 1024]) { const track = new Track.Producer("tone"); - const delay = new Signal({ max: Milli(30_000) }); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const delay = new Signal({ max: Duration.millis(30_000) }); + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), delay, }); @@ -19,7 +19,7 @@ for (const count of [1, 16, 256, 1024]) { group.writeFrame({ payload: Varint.encode(Number(sequence) * 1000), timestamp: Time.Timestamp.now() }); }; const buffered = async (timestamp: number) => { - while (consumer.buffered.peek().at(-1)?.end !== timestamp) await consumer.buffered.changed(); + while (consumer.buffered.peek().at(-1)?.end.asMillis() !== timestamp) await consumer.buffered.changed(); }; let warnings = 0; let bytes = 0; @@ -31,7 +31,7 @@ for (const count of [1, 16, 256, 1024]) { try { for (let i = 0n; i < BigInt(count); i++) write(i); await buffered(count - 1); - delay.set({ max: Milli.zero }); + delay.set({ max: Duration.ZERO }); const started = performance.now(); write(BigInt(count)); await buffered(count); diff --git a/js/hang/src/cmaf/format.test.ts b/js/hang/src/cmaf/format.test.ts index ffbeccf15f4..8eada5dd01c 100644 --- a/js/hang/src/cmaf/format.test.ts +++ b/js/hang/src/cmaf/format.test.ts @@ -1,5 +1,4 @@ import { expect, test } from "bun:test"; -import type { Micro } from "@moq/clock"; import { Time } from "@moq/net"; import type { InitSegment } from "./decode.ts"; import { Format } from "./format.ts"; @@ -75,7 +74,7 @@ test("CmafFormat times samples from the frame timestamp", () => { ]); const frames = new Format(INIT).decode(segment, Time.Timestamp.fromMillis(10_000)); - expect(frames.map((f) => f.timestamp)).toEqual([10_000_000, 10_066_667, 10_033_333] as Micro[]); + expect(frames.map((f) => f.timestamp.asMicros())).toEqual([10_000_000, 10_066_667, 10_033_333]); }); // A fragment can open on a sample that presents after a later one (open-GOP leading pictures, @@ -87,7 +86,7 @@ test("CmafFormat anchors the earliest presentation time", () => { ]); const frames = new Format(INIT).decode(segment, Time.Timestamp.fromMillis(5_000)); - expect(frames.map((f) => f.timestamp)).toEqual([5_033_333, 5_000_000] as Micro[]); + expect(frames.map((f) => f.timestamp.asMicros())).toEqual([5_033_333, 5_000_000]); }); // Runs continue one decode timeline, so the anchor is the earliest sample across all of them. @@ -95,7 +94,7 @@ test("CmafFormat anchors the earliest sample across runs", () => { const segment = fragment(0, [[3000, 6000]], [[3000, 0]]); const frames = new Format(INIT).decode(segment, at(3000)); - expect(frames.map((f) => f.timestamp)).toEqual([66_667, 33_333] as Micro[]); + expect(frames.map((f) => f.timestamp.asMicros())).toEqual([66_667, 33_333]); }); // An untimed track's frames carry no broadcast time, so their samples present at `tfdt`. @@ -107,7 +106,7 @@ test("CmafFormat times an untimed fragment from its tfdt", () => { ]); const frames = new Format(INIT).decode(segment, undefined); - expect(frames.map((f) => f.timestamp)).toEqual([1_033_333, 1_100_000, 1_066_667] as Micro[]); + expect(frames.map((f) => f.timestamp.asMicros())).toEqual([1_033_333, 1_100_000, 1_066_667]); }); // Samples are read front to back, so a run that skips bytes is refused rather than sliced wrong. diff --git a/js/hang/src/cmaf/format.ts b/js/hang/src/cmaf/format.ts index 34a474cad00..97641c70540 100644 --- a/js/hang/src/cmaf/format.ts +++ b/js/hang/src/cmaf/format.ts @@ -1,4 +1,4 @@ -import type { Micro } from "@moq/clock"; +import { Duration } from "@moq/clock"; import type { Time } from "@moq/net"; import type { Format as ContainerFormat } from "../container/format"; import type { Frame } from "../container/types"; @@ -17,9 +17,9 @@ export class Format implements ContainerFormat { decode(payload: Uint8Array, timestamp: Time.Timestamp | undefined): Frame[] { return decodeDataSegment(payload, this.#init, timestamp).map((s) => ({ payload: s.data, - timestamp: s.timestamp as Micro, + timestamp: Duration.micros(s.timestamp), keyframe: s.keyframe, - duration: s.duration as Micro, + duration: Duration.micros(s.duration), })); } } diff --git a/js/hang/src/container/consumer.backpressure.test.ts b/js/hang/src/container/consumer.backpressure.test.ts index 35711904f8e..8c64f0bffd5 100644 --- a/js/hang/src/container/consumer.backpressure.test.ts +++ b/js/hang/src/container/consumer.backpressure.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Elapsed, Manual, type Micro, Milli, Nano, timeout } from "@moq/clock"; +import { Duration, Elapsed, Instant, Manual, timeout } from "@moq/clock"; import { Time, Track } from "@moq/net"; import { Consumer, type Read } from "./consumer.ts"; import { encodeFrame, Format } from "./legacy.ts"; @@ -22,7 +22,7 @@ const PAYLOAD = new Uint8Array([0xde, 0xad]); const flush = () => new Promise((resolve) => setImmediate(resolve)); function write(group: { writeFrame(frame: { payload: Uint8Array; timestamp: Time.Timestamp }): void }, ts: number) { - group.writeFrame({ payload: encodeFrame(PAYLOAD, ts as Micro), timestamp: Time.Timestamp.now() }); + group.writeFrame({ payload: encodeFrame(PAYLOAD, Duration.micros(ts)), timestamp: Time.Timestamp.now() }); } // The most frames the consumer may hold: past the max buffer, one more wire frame. Each held frame @@ -47,7 +47,7 @@ async function readAll(consumer: Consumer, format: Counting, bounded?: number): } function timestamps(reads: Read[]): number[] { - return reads.flatMap((read) => (read.kind === "frame" ? [read.frame.timestamp] : [])); + return reads.flatMap((read) => (read.kind === "frame" ? [read.frame.timestamp.asMicros()] : [])); } test("Consumer holds frames sharing a timestamp within the max buffer", async () => { @@ -55,9 +55,9 @@ test("Consumer holds frames sharing a timestamp within the max buffer", async () const maxBuffer = 4096; const format = new Counting("data"); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format, - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, maxBuffer, }); try { @@ -90,9 +90,9 @@ test("Consumer holds many groups within the max buffer and reaches the live edge const maxBuffer = 8192; const format = new Counting("data"); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format, - delay: { max: Milli(100) }, + delay: { max: Duration.millis(100) }, maxBuffer, }); try { @@ -125,9 +125,9 @@ test("Consumer skips a stalled group once group overhead alone fills the max buf const warn = spyOn(console, "warn").mockImplementation(() => {}); const format = new Counting("data"); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format, - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, // Two groups' overhead, so nothing past the stalled head would decode without its successor leading. maxBuffer: 512, }); @@ -138,9 +138,9 @@ test("Consumer skips a stalled group once group overhead alone fills the max buf write(next, 10_000); next.finish(); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 0 } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(0) } }); expect(await consumer.next()).toMatchObject({ kind: "gap" }); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 10_000 } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(10_000) } }); } finally { consumer.close(); track.close(); @@ -152,9 +152,9 @@ test("Consumer reaches a readable group past a stalled successor once group over const warn = spyOn(console, "warn").mockImplementation(() => {}); const format = new Counting("data"); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format, - delay: { max: Milli.zero }, + delay: { max: Duration.ZERO }, // Three groups' overhead: the readable group cannot decode until the stalled ones are moved past. maxBuffer: 768, }); @@ -167,10 +167,10 @@ test("Consumer reaches a readable group past a stalled successor once group over write(readable, 20_000); readable.finish(); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 0 } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(0) } }); expect(await consumer.next()).toMatchObject({ kind: "gap" }); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 10_000 } }); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 20_000 } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(10_000) } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(20_000) } }); } finally { consumer.close(); track.close(); @@ -181,9 +181,9 @@ test("Consumer reaches a readable group past a stalled successor once group over test("Consumer admits reads completing together one at a time against the max buffer", async () => { const format = new Counting("data"); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format, - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, maxBuffer: 4096, }); try { @@ -193,7 +193,7 @@ test("Consumer admits reads completing together one at a time against the max bu await flush(); const large = new Uint8Array(2_000); for (const group of groups) { - group.writeFrame({ payload: encodeFrame(large, 0 as Micro), timestamp: Time.Timestamp.now() }); + group.writeFrame({ payload: encodeFrame(large, Duration.micros(0)), timestamp: Time.Timestamp.now() }); } await flush(); @@ -216,9 +216,9 @@ class Header extends Format { test("Consumer charges a small view of a large wire frame the wire frame", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Header("data"), - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, maxBuffer: 16 * 1024, }); try { @@ -228,7 +228,7 @@ test("Consumer charges a small view of a large wire frame the wire frame", async const padding = new Uint8Array(60_000); for (let i = 0; i < 8; i++) { padded.writeFrame({ - payload: encodeFrame(padding, (10_000 + i) as Micro), + payload: encodeFrame(padding, Duration.micros(10_000 + i)), timestamp: Time.Timestamp.now(), }); } @@ -236,10 +236,16 @@ test("Consumer charges a small view of a large wire frame the wire frame", async // The padded frames fill the max buffer behind the stalled group, which moves the cursor on to them. // Charging only the one byte views, the buffer never fills and the reader waits on the stall. - expect(await within(consumer.next())).toMatchObject({ kind: "frame", frame: { timestamp: 0 } }); + expect(await within(consumer.next())).toMatchObject({ + kind: "frame", + frame: { timestamp: Duration.micros(0) }, + }); expect(await within(consumer.next())).toMatchObject({ kind: "gap" }); for (let i = 0; i < 8; i++) { - expect(await within(consumer.next())).toMatchObject({ kind: "frame", frame: { timestamp: 10_000 + i } }); + expect(await within(consumer.next())).toMatchObject({ + kind: "frame", + frame: { timestamp: Duration.micros(10_000 + i) }, + }); } } finally { consumer.close(); @@ -252,24 +258,30 @@ test("Consumer stamps frames the max buffer held back with when they landed, not const clock = new Manual(); const installed = clock.install(); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, // One group's overhead and one frame: the second frame waits in the transport until the first is read. maxBuffer: 300, }); try { const group = track.createGroup(0n); write(group, 0); - await clock.advance(Nano.fromMilli(Milli(250))); + await clock.advance(Duration.millis(250)); write(group, 10_000); group.finish(); track.finish(); // The reader is slow: nothing is read until well after both frames landed. - await clock.advance(Nano.fromMilli(Milli(750))); + await clock.advance(Duration.millis(750)); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 0, arrival: 0 } }); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 10_000, arrival: 250 } }); + expect(await consumer.next()).toMatchObject({ + kind: "frame", + frame: { timestamp: Duration.micros(0), arrival: Instant.ZERO }, + }); + expect(await consumer.next()).toMatchObject({ + kind: "frame", + frame: { timestamp: Duration.micros(10_000), arrival: Instant.ZERO.add(Duration.millis(250)) }, + }); } finally { consumer.close(); track.close(); @@ -281,9 +293,9 @@ test("Consumer expires a hole behind a full max buffer from when the group past const clock = new Manual(); const installed = clock.install(); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(500) }, + delay: { max: Duration.millis(500) }, // Two groups' overhead: group 3 waits in the transport until groups 0 and 1 are read. maxBuffer: 512, }); @@ -297,7 +309,7 @@ test("Consumer expires a hole behind a full max buffer from when the group past marker.writeFrame({ payload: new Uint8Array(), timestamp: Time.Timestamp.now() }); marker.finish(); // The reader is slow: the hole before group 3 expired before anything is read. - await clock.advance(Nano.fromMilli(Milli(1_000))); + await clock.advance(Duration.millis(1_000)); expect(await within(consumer.next())).toMatchObject({ kind: "frame", group: 0n }); expect(await within(consumer.next())).toMatchObject({ kind: "frame", group: 1n }); @@ -314,9 +326,9 @@ for (const maxBuffer of [0, 256]) { test(`Consumer moves past a stalled group with a ${maxBuffer} byte max buffer`, async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, // No more than one group's overhead: the successor is pulled anyway, so the head can be skipped. maxBuffer, }); @@ -327,9 +339,12 @@ for (const maxBuffer of [0, 256]) { write(next, 10_000); next.finish(); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 0 } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(0) } }); expect(await consumer.next()).toMatchObject({ kind: "gap" }); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 10_000 } }); + expect(await consumer.next()).toMatchObject({ + kind: "frame", + frame: { timestamp: Duration.micros(10_000) }, + }); } finally { consumer.close(); track.close(); @@ -341,9 +356,9 @@ for (const maxBuffer of [0, 256]) { test("Consumer moves past a stalled backlog group below the cursor once the max buffer is full", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, // Two groups' overhead: the backlog group and the active one leave no room for the newer group. maxBuffer: 512, }); @@ -358,7 +373,11 @@ test("Consumer moves past a stalled backlog group below the cursor once the max newer.finish(); expect(await consumer.next()).toMatchObject({ kind: "gap" }); - expect(await consumer.next()).toMatchObject({ kind: "frame", group: 4n, frame: { timestamp: 40_000 } }); + expect(await consumer.next()).toMatchObject({ + kind: "frame", + group: 4n, + frame: { timestamp: Duration.micros(40_000) }, + }); } finally { consumer.close(); track.close(); @@ -369,9 +388,9 @@ test("Consumer moves past a stalled backlog group below the cursor once the max test("Consumer reads what a promoted head already holds before skipping it under pressure", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, maxBuffer: 1024, }); try { @@ -385,15 +404,19 @@ test("Consumer reads what a promoted head already holds before skipping it under const later = track.createGroup(2n); const early = Time.Timestamp.now(); later.writeFrame({ - payload: encodeFrame(new Uint8Array(2_000), 20_000 as Micro), + payload: encodeFrame(new Uint8Array(2_000), Duration.micros(20_000)), timestamp: Time.Timestamp.now(), }); await flush(); - between.writeFrame({ payload: encodeFrame(PAYLOAD, 10_000 as Micro), timestamp: early }); + between.writeFrame({ payload: encodeFrame(PAYLOAD, Duration.micros(10_000)), timestamp: early }); // Group 0 is skipped, but group 1 is read once promoted rather than skipped before its task runs. expect(await consumer.next()).toMatchObject({ kind: "gap" }); - expect(await consumer.next()).toMatchObject({ kind: "frame", group: 1n, frame: { timestamp: 10_000 } }); + expect(await consumer.next()).toMatchObject({ + kind: "frame", + group: 1n, + frame: { timestamp: Duration.micros(10_000) }, + }); } finally { consumer.close(); track.close(); @@ -404,7 +427,7 @@ test("Consumer reads what a promoted head already holds before skipping it under // Settle `promise` within a second, so a reader that hangs fails the test instead of timing it out. async function within(promise: Promise): Promise { try { - return await timeout(Nano.fromMilli(Milli(1_000)), promise); + return await timeout(Duration.millis(1_000), promise); } catch (error) { if (error instanceof Elapsed) throw new Error("the reader hung"); throw error; @@ -414,9 +437,9 @@ async function within(promise: Promise): Promise { test("Consumer raises a malformed frame in a head promoted under pressure", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, maxBuffer: 1024, }); try { @@ -429,7 +452,7 @@ test("Consumer raises a malformed frame in a head promoted under pressure", asyn const later = track.createGroup(2n); const early = Time.Timestamp.now(); later.writeFrame({ - payload: encodeFrame(new Uint8Array(2_000), 20_000 as Micro), + payload: encodeFrame(new Uint8Array(2_000), Duration.micros(20_000)), timestamp: Time.Timestamp.now(), }); await flush(); @@ -447,9 +470,9 @@ test("Consumer raises a malformed frame in a head promoted under pressure", asyn test("Consumer raises a malformed group an age skip passes after the track finished", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(500) }, + delay: { max: Duration.millis(500) }, }); try { const first = track.createGroup(0n); @@ -478,9 +501,9 @@ test("Consumer raises a malformed group an age skip passes after the track finis test("Consumer reads a finished marker group's end before skipping under pressure", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, maxBuffer: 1024, }); try { @@ -493,7 +516,7 @@ test("Consumer reads a finished marker group's end before skipping under pressur const later = track.createGroup(2n); const early = Time.Timestamp.now(); later.writeFrame({ - payload: encodeFrame(new Uint8Array(2_000), 20_000 as Micro), + payload: encodeFrame(new Uint8Array(2_000), Duration.micros(20_000)), timestamp: Time.Timestamp.now(), }); await flush(); @@ -503,7 +526,11 @@ test("Consumer reads a finished marker group's end before skipping under pressur // Group 0 is skipped, and group 1 declares its end before group 2 is read. expect(await within(consumer.next())).toMatchObject({ kind: "gap" }); expect(await within(consumer.next())).toMatchObject({ kind: "end", group: 1n }); - expect(await within(consumer.next())).toMatchObject({ kind: "frame", group: 2n, frame: { timestamp: 20_000 } }); + expect(await within(consumer.next())).toMatchObject({ + kind: "frame", + group: 2n, + frame: { timestamp: Duration.micros(20_000) }, + }); } finally { consumer.close(); track.close(); @@ -514,9 +541,9 @@ test("Consumer reads a finished marker group's end before skipping under pressur test("Consumer reads a group whose frame fails to read as cut short while the reader waits", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, }); try { const stalled = track.createGroup(0n); @@ -530,7 +557,7 @@ test("Consumer reads a group whose frame fails to read as cut short while the re // slice that will not inflate does. The read that takes it fails the group. const pending = within(consumer.next()); await flush(); - const payload = encodeFrame(PAYLOAD, 5_000 as Micro); + const payload = encodeFrame(PAYLOAD, Duration.micros(5_000)); let armed = false; stalled.writeFrame({ get payload() { @@ -542,7 +569,11 @@ test("Consumer reads a group whose frame fails to read as cut short while the re armed = true; expect(await pending).toMatchObject({ kind: "gap" }); - expect(await within(consumer.next())).toMatchObject({ kind: "frame", group: 1n, frame: { timestamp: 10_000 } }); + expect(await within(consumer.next())).toMatchObject({ + kind: "frame", + group: 1n, + frame: { timestamp: Duration.micros(10_000) }, + }); } finally { consumer.close(); track.close(); diff --git a/js/hang/src/container/consumer.holes.test.ts b/js/hang/src/container/consumer.holes.test.ts index fd68adc5d6c..b6d76bccba1 100644 --- a/js/hang/src/container/consumer.holes.test.ts +++ b/js/hang/src/container/consumer.holes.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Manual, Micro, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { Time, Track } from "@moq/net"; import { Consumer, type Read } from "./consumer.ts"; import { encodeFrame, Format } from "./legacy.ts"; @@ -10,9 +10,9 @@ test.each([0, 100])("a sequence hole before a paused data marker expires at %sms const clock = new Manual(); const installed = clock.install(); const track = new Track.Producer("data"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(budget) }, + delay: { max: Duration.millis(budget) }, }); const results: Read[] = []; const reading = (async () => { @@ -24,7 +24,10 @@ test.each([0, 100])("a sequence hole before a paused data marker expires at %sms })(); try { const first = track.createGroup(0n); - first.writeFrame({ payload: encodeFrame(new Uint8Array([1]), Micro(10_000)), timestamp: Time.Timestamp.now() }); + first.writeFrame({ + payload: encodeFrame(new Uint8Array([1]), Duration.micros(10_000)), + timestamp: Time.Timestamp.now(), + }); first.finish(); await flush(); expect(results).toHaveLength(1); @@ -34,13 +37,13 @@ test.each([0, 100])("a sequence hole before a paused data marker expires at %sms await flush(); if (budget > 0) { expect(results).toHaveLength(1); - await clock.advance(Nano.fromMilli(Milli(budget - 1))); + await clock.advance(Duration.millis(budget - 1)); expect(results).toHaveLength(1); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); } expect(results.slice(1)).toEqual([ - { kind: "gap", timestamp: Micro(10_000), duration: Micro.zero }, - { kind: "end", group: 2n, end: Micro(10_000) }, + { kind: "gap", timestamp: Duration.micros(10_000), duration: Duration.ZERO }, + { kind: "end", group: 2n, end: Duration.micros(10_000) }, ]); } finally { consumer.close(); @@ -58,9 +61,9 @@ test("a filled hole cancels its timer and the next hole gets a fresh budget", as const clock = new Manual(); const installed = clock.install(); const track = new Track.Producer("data"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(100) }, + delay: { max: Duration.millis(100) }, }); const results: Read[] = []; const reading = (async () => { @@ -73,7 +76,10 @@ test("a filled hole cancels its timer and the next hole gets a fresh budget", as const write = (sequence: bigint, timestamp?: number) => { const group = track.createGroup(sequence); group.writeFrame({ - payload: timestamp === undefined ? new Uint8Array() : encodeFrame(new Uint8Array([1]), Micro(timestamp)), + payload: + timestamp === undefined + ? new Uint8Array() + : encodeFrame(new Uint8Array([1]), Duration.micros(timestamp)), timestamp: Time.Timestamp.fromMicros(timestamp ?? 20_000), }); group.finish(); @@ -83,18 +89,18 @@ test("a filled hole cancels its timer and the next hole gets a fresh budget", as await flush(); write(2n, 20_000); await flush(); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); write(1n, 10_000); await flush(); expect(results.map((read) => read.kind)).toEqual(["frame", "frame", "frame"]); write(4n); await flush(); - await clock.advance(Nano.fromMilli(Milli(99))); + await clock.advance(Duration.millis(99)); expect(results).toHaveLength(3); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); expect(results.slice(3)).toEqual([ - { kind: "gap", timestamp: Micro(20_000), duration: Micro.zero }, - { kind: "end", group: 4n, end: Micro(20_000) }, + { kind: "gap", timestamp: Duration.micros(20_000), duration: Duration.ZERO }, + { kind: "end", group: 4n, end: Duration.micros(20_000) }, ]); } finally { consumer.close(); @@ -112,9 +118,9 @@ test("the holes a stalled source left behind share one budget", async () => { const clock = new Manual(); const installed = clock.install(); const track = new Track.Producer("data"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(100) }, + delay: { max: Duration.millis(100) }, }); const results: Read[] = []; const reading = (async () => { @@ -127,7 +133,7 @@ test("the holes a stalled source left behind share one budget", async () => { const write = (sequence: bigint) => { const group = track.createGroup(sequence); group.writeFrame({ - payload: encodeFrame(new Uint8Array([1]), Micro(Number(sequence) * 10_000)), + payload: encodeFrame(new Uint8Array([1]), Duration.micros(Number(sequence) * 10_000)), timestamp: Time.Timestamp.fromMicros(Number(sequence) * 10_000), }); group.finish(); @@ -138,7 +144,7 @@ test("the holes a stalled source left behind share one budget", async () => { for (const sequence of [2n, 4n, 6n]) write(sequence); await flush(); expect(results).toHaveLength(1); - await clock.advance(Nano.fromMilli(Milli(100))); + await clock.advance(Duration.millis(100)); expect(results.map((read) => read.kind)).toEqual(["frame", "gap", "frame", "gap", "frame", "gap", "frame"]); } finally { consumer.close(); @@ -156,9 +162,9 @@ test("a hole is late from the earliest arrival past it", async () => { const clock = new Manual(); const installed = clock.install(); const track = new Track.Producer("data"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(100) }, + delay: { max: Duration.millis(100) }, }); const results: Read[] = []; const reading = (async () => { @@ -171,7 +177,7 @@ test("a hole is late from the earliest arrival past it", async () => { const write = (sequence: bigint) => { const group = track.createGroup(sequence); group.writeFrame({ - payload: encodeFrame(new Uint8Array([1]), Micro(Number(sequence) * 10_000)), + payload: encodeFrame(new Uint8Array([1]), Duration.micros(Number(sequence) * 10_000)), timestamp: Time.Timestamp.fromMicros(Number(sequence) * 10_000), }); group.finish(); @@ -181,11 +187,11 @@ test("a hole is late from the earliest arrival past it", async () => { await flush(); write(4n); await flush(); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); write(2n); await flush(); expect(results).toHaveLength(1); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); expect(results.map((read) => read.kind)).toEqual(["frame", "gap", "frame", "gap", "frame"]); } finally { consumer.close(); @@ -212,17 +218,20 @@ test("a hole in a drained backlog is late from the earliest arrival past it, not group.finish(); }; const first = track.createGroup(0n); - first.writeFrame({ payload: encodeFrame(new Uint8Array([1]), Micro(0)), timestamp: Time.Timestamp.fromMicros(0) }); + first.writeFrame({ + payload: encodeFrame(new Uint8Array([1]), Duration.micros(0)), + timestamp: Time.Timestamp.fromMicros(0), + }); first.finish(); marker(5n); - await clock.advance(Nano.fromMilli(Milli(900))); + await clock.advance(Duration.millis(900)); marker(3n); - await clock.advance(Nano.fromMilli(Milli(100))); + await clock.advance(Duration.millis(100)); // Joined now, the backlog drains in sequence order: group 3 before group 5, which landed first. - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(500) }, + delay: { max: Duration.millis(500) }, }); const results: Read[] = []; const reading = (async () => { @@ -260,9 +269,9 @@ test.each([true, false])("the head after a declared end is waited for (arrives: const clock = new Manual(); const installed = clock.install(); const track = new Track.Producer("audio"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("audio"), - delay: { max: Milli(300) }, + delay: { max: Duration.millis(300) }, }); const results: Read[] = []; const reading = (async () => { @@ -276,8 +285,8 @@ test.each([true, false])("the head after a declared end is waited for (arrives: const group = track.createGroup(sequence); for (const [timestamp, payload = new Uint8Array([1])] of frames) { group.writeFrame({ - payload: encodeFrame(payload, Micro(timestamp)), - timestamp: Time.Timestamp.fromMicros(Micro(timestamp)), + payload: encodeFrame(payload, Duration.micros(timestamp)), + timestamp: Time.Timestamp.fromMicros(timestamp), }); } group.finish(); @@ -285,17 +294,21 @@ test.each([true, false])("the head after a declared end is waited for (arrives: const frame = (group: bigint, timestamp: number) => ({ kind: "frame" as const, group, - frame: expect.objectContaining({ timestamp }), + frame: expect.objectContaining({ timestamp: Duration.micros(timestamp) }), }); try { write(0n, [0]); // The end, then the stopped encoder's final packet, as a native publisher writes them. write(1n, [60_000, new Uint8Array()], [40_000]); await flush(); - expect(results).toEqual([frame(0n, 0), { kind: "end", group: 1n, end: Micro(60_000) }, frame(1n, 40_000)]); + expect(results).toEqual([ + frame(0n, 0), + { kind: "end", group: 1n, end: Duration.micros(60_000) }, + frame(1n, 40_000), + ]); write(3n, [60_060_000]); await flush(); - await clock.advance(Nano.fromMilli(Milli(299))); + await clock.advance(Duration.millis(299)); expect(results).toHaveLength(3); if (arrives) { write(2n, [60_000_000]); @@ -305,14 +318,14 @@ test.each([true, false])("the head after a declared end is waited for (arrives: write(5n, [61_000_000], [61_300_000]); await flush(); expect(results.slice(5)).toEqual([ - { kind: "gap", timestamp: Micro(60_060_000), duration: Micro(940_000) }, + { kind: "gap", timestamp: Duration.micros(60_060_000), duration: Duration.micros(940_000) }, frame(5n, 61_000_000), frame(5n, 61_300_000), ]); } else { - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); expect(results.slice(3)).toEqual([ - { kind: "gap", timestamp: Micro(60_000), duration: Micro(60_000_000) }, + { kind: "gap", timestamp: Duration.micros(60_000), duration: Duration.micros(60_000_000) }, frame(3n, 60_060_000), ]); } @@ -336,9 +349,9 @@ test("a newest-first flush past a hole delivers the groups landing behind its ne const clock = new Manual(); const installed = clock.install(); const track = new Track.Producer("audio"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("audio"), - delay: { max: Milli(80) }, + delay: { max: Duration.millis(80) }, }); const results: Read[] = []; const reading = (async () => { @@ -352,7 +365,7 @@ test("a newest-first flush past a hole delivers the groups landing behind its ne const sent = Time.Timestamp.now(); const write = (sequence: number) => { const group = track.createGroup(BigInt(sequence)); - const timestamp = Micro(sequence * 20_000); + const timestamp = Duration.micros(sequence * 20_000); group.writeFrame({ payload: encodeFrame(new Uint8Array([1]), timestamp), timestamp: sent }); group.finish(); }; @@ -367,7 +380,7 @@ test("a newest-first flush past a hole delivers the groups landing behind its ne [0, 1, 2, 3, 4, 5, 6, 7].map((sequence) => ({ kind: "frame", group: BigInt(sequence), - frame: expect.objectContaining({ timestamp: Micro(sequence * 20_000) }), + frame: expect.objectContaining({ timestamp: Duration.micros(sequence * 20_000) }), })), ); } finally { diff --git a/js/hang/src/container/consumer.nonsequential.test.ts b/js/hang/src/container/consumer.nonsequential.test.ts index c0240f07f64..7fed8b3bcbd 100644 --- a/js/hang/src/container/consumer.nonsequential.test.ts +++ b/js/hang/src/container/consumer.nonsequential.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; -import { type Installed, Manual, type Micro, Milli, Nano } from "@moq/clock"; +import { Duration, type Installed, Manual } from "@moq/clock"; import { type Group, Time, Track, Varint } from "@moq/net"; import { Consumer } from "./consumer.ts"; import { Format as LegacyFormat } from "./legacy.ts"; @@ -19,7 +19,7 @@ afterEach(() => { /** Flush the consumer's readers without moving time, then return what `read` settled with, or "pending". */ async function poll(read: Promise): Promise { - const flushed = clock.advance(Nano.zero); + const flushed = clock.advance(Duration.ZERO); try { return await Promise.race([read, flushed.then(() => "pending" as const)]); } finally { @@ -35,7 +35,7 @@ async function nextFrame(consumer: Consumer) { } } -function encodeLegacyFrame(timestamp: Micro, payload: Uint8Array): Uint8Array { +function encodeLegacyFrame(timestamp: number, payload: Uint8Array): Uint8Array { const tsBytes = Varint.encode(timestamp); const data = new Uint8Array(tsBytes.byteLength + payload.byteLength); data.set(tsBytes, 0); @@ -58,13 +58,13 @@ test("Consumer waits on a non-sequential hang group because it has no per-frame const track = new Track.Producer("test"); const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("data"), - delay: { max: 5000 as Milli }, + delay: { max: Duration.millis(5000) }, }); // Group A at a large sequence, completed so the cursor advances past it. const a = track.createGroup(1_000_000n); a.writeFrame({ - payload: encodeLegacyFrame(0 as Micro, new Uint8Array([0x01])), + payload: encodeLegacyFrame(0, new Uint8Array([0x01])), timestamp: Time.Timestamp.now(), }); a.finish(); @@ -81,13 +81,13 @@ test("Consumer waits on a non-sequential hang group because it has no per-frame // could still be coming. We cannot tell, so B must NOT surface yet. const b = track.createGroup(1_090_000n); b.writeFrame({ - payload: encodeLegacyFrame(1_000_000 as Micro, new Uint8Array([0x02])), + payload: encodeLegacyFrame(1_000_000, new Uint8Array([0x02])), timestamp: Time.Timestamp.now(), }); // Within the max delay budget (5s), the parked next() stays parked: no duration means no proof of // contiguity, so the consumer waits instead of eagerly delivering across the gap. - await clock.advance(Nano.fromMilli(Milli(4_999))); + await clock.advance(Duration.millis(4_999)); expect(await poll(pending)).toBe("pending"); consumer.close(); @@ -100,12 +100,12 @@ test("Consumer reads on without a gap past a group it skipped", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("audio"), - delay: { max: 500 as Milli }, + delay: { max: Duration.millis(500) }, }); const write = (group: Group.Producer, timestamps: number[]) => { for (const timestamp of timestamps) { group.writeFrame({ - payload: encodeLegacyFrame(timestamp as Micro, new Uint8Array([0x01])), + payload: encodeLegacyFrame(timestamp, new Uint8Array([0x01])), timestamp: Time.Timestamp.now(), }); } @@ -120,12 +120,12 @@ test("Consumer reads on without a gap past a group it skipped", async () => { // frame and leaves only the skipped group's end to show the timeline goes on. first.finish(); const empty = track.createGroup(1n); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); const last = track.createGroup(20n); write(last, [400_000, 1_000_000]); last.finish(); empty.finish(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); const next = await poll(consumer.next()); expect(next).toMatchObject({ kind: "frame", group: 20n }); diff --git a/js/hang/src/container/consumer.outoforder.test.ts b/js/hang/src/container/consumer.outoforder.test.ts index 6146646b002..74330cec692 100644 --- a/js/hang/src/container/consumer.outoforder.test.ts +++ b/js/hang/src/container/consumer.outoforder.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; -import { type Installed, Manual, Micro, Milli, Nano } from "@moq/clock"; +import { Duration, type Installed, Manual } from "@moq/clock"; import { type Group, Time, Track, Varint } from "@moq/net"; import { Consumer } from "./consumer.ts"; import { Format as LegacyFormat } from "./legacy.ts"; @@ -19,7 +19,7 @@ afterEach(() => { /** Flush the consumer's readers without moving time, then return what `read` settled with, or "pending". */ async function poll(read: Promise): Promise { - const flushed = clock.advance(Nano.zero); + const flushed = clock.advance(Duration.ZERO); try { return await Promise.race([read, flushed.then(() => "pending" as const)]); } finally { @@ -35,7 +35,7 @@ async function nextFrame(consumer: Consumer) { } } -function encodeLegacyFrame(timestamp: Micro, payload: Uint8Array): Uint8Array { +function encodeLegacyFrame(timestamp: number, payload: Uint8Array): Uint8Array { const tsBytes = Varint.encode(timestamp); const data = new Uint8Array(tsBytes.byteLength + payload.byteLength); data.set(tsBytes, 0); @@ -46,7 +46,7 @@ function encodeLegacyFrame(timestamp: Micro, payload: Uint8Array): Uint8Array { /** Write one frame into an open group: `millis` on the timeline, tagged `tag`. */ function publishFrame(group: Group.Producer, millis: number, tag: number) { group.writeFrame({ - payload: encodeLegacyFrame(Micro.fromMilli(millis as Milli), new Uint8Array([tag])), + payload: encodeLegacyFrame(millis * 1000, new Uint8Array([tag])), timestamp: Time.Timestamp.fromMillis(millis), }); } @@ -75,16 +75,19 @@ async function drain(consumer: Consumer): Promise<[bigint, number | undefined][] // the budget. A group below that floor is never delivered and adds no gap. Mirrors Rust's // `startup_at_the_publishers_start_over_a_newer_first_arrival`. test("the head of the window arriving after the live edge is delivered first", async () => { - const track = new Track.Producer("test").accept({ timescale: Time.Timescale.MILLI, maxAge: Milli(30_000) }); + const track = new Track.Producer("test").accept({ + timescale: Time.Timescale.MILLI, + maxAge: Duration.millis(30_000), + }); const consumer = new Consumer( - track.subscribe({ delay: { max: Milli(5000) }, ranges: [{ start: { absolute: 1n } }] }), - { format: new LegacyFormat("data"), delay: { max: 5000 as Milli } }, + track.subscribe({ delay: { max: Duration.millis(5000) }, ranges: [{ start: { absolute: 1n } }] }), + { format: new LegacyFormat("data"), delay: { max: Duration.millis(5000) } }, ); // The live edge lands first, and delivery waits for the floor rather than starting there. publish(track, 3n, 30); const waiting = consumer.next(); - await clock.advance(Nano.fromMilli(Milli(4_999))); + await clock.advance(Duration.millis(4_999)); expect(await poll(waiting)).toBe("pending"); // The window's head follows, and a reordered group below the floor with it. @@ -106,10 +109,13 @@ test("the head of the window arriving after the live edge is delivered first", a // loop consumes faster than the network delivers). Removing it at that instant silently truncates // its tail, so removal must wait for the group to finish. test("a head group still downloading is not truncated", async () => { - const track = new Track.Producer("test").accept({ timescale: Time.Timescale.MILLI, maxAge: Milli(30_000) }); + const track = new Track.Producer("test").accept({ + timescale: Time.Timescale.MILLI, + maxAge: Duration.millis(30_000), + }); const consumer = new Consumer( - track.subscribe({ delay: { max: Milli(5000) }, ranges: [{ start: { absolute: 1n } }] }), - { format: new LegacyFormat("data"), delay: { max: 5000 as Milli } }, + track.subscribe({ delay: { max: Duration.millis(5000) }, ranges: [{ start: { absolute: 1n } }] }), + { format: new LegacyFormat("data"), delay: { max: Duration.millis(5000) } }, ); // The live edge group arrives first (still open), and the head after it, one frame at a time. @@ -141,13 +147,16 @@ test("a head group still downloading is not truncated", async () => { // budget, or forever on an open track, for groups it never gets. Mirrors Rust's // `an_excluded_gap_between_ranges_does_not_stall`. test("an excluded gap between ranges does not stall", async () => { - const track = new Track.Producer("test").accept({ timescale: Time.Timescale.MILLI, maxAge: Milli(30_000) }); + const track = new Track.Producer("test").accept({ + timescale: Time.Timescale.MILLI, + maxAge: Duration.millis(30_000), + }); const consumer = new Consumer( track.subscribe({ - delay: { max: Milli(10_000) }, + delay: { max: Duration.millis(10_000) }, ranges: [{ start: { absolute: 0n }, end: { absolute: 1n } }, { start: { absolute: 10n } }], }), - { format: new LegacyFormat("data"), delay: { max: 10_000 as Milli } }, + { format: new LegacyFormat("data"), delay: { max: Duration.millis(10_000) } }, ); for (const sequence of [0n, 5n, 10n]) publish(track, sequence, Number(sequence) * 100); @@ -162,13 +171,22 @@ test("an excluded gap between ranges does not stall", async () => { // which counts a newest group that held no frame yet, rather than wait under the budget for a group // below it that never comes. Mirrors Rust's `a_resolved_relative_floor_rises_to_the_publishers_start`. test("a resolved relative floor rises to the publisher's start", async () => { - const track = new Track.Producer("test").accept({ timescale: Time.Timescale.MILLI, maxAge: Milli(30_000) }); + const track = new Track.Producer("test").accept({ + timescale: Time.Timescale.MILLI, + maxAge: Duration.millis(30_000), + }); for (const sequence of [0n, 1n, 2n, 3n, 4n]) publish(track, sequence, Number(sequence) * 100); - const subscriber = track.subscribe({ delay: { max: Milli(10_000) }, ranges: [{ start: { relative: 0n } }] }); + const subscriber = track.subscribe({ + delay: { max: Duration.millis(10_000) }, + ranges: [{ start: { relative: 0n } }], + }); expect(subscriber.floor()).toBe(4n); // A session declares the publisher's start; a local track has none, so stand in for it. subscriber.start = async () => 5n; - const consumer = new Consumer(subscriber, { format: new LegacyFormat("data"), delay: { max: 10_000 as Milli } }); + const consumer = new Consumer(subscriber, { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(10_000) }, + }); publish(track, 5n, 500); expect(await drain(consumer)).toEqual([[5n, 5]]); diff --git a/js/hang/src/container/consumer.rewind.test.ts b/js/hang/src/container/consumer.rewind.test.ts index a22d310bbe7..dbd8b143254 100644 --- a/js/hang/src/container/consumer.rewind.test.ts +++ b/js/hang/src/container/consumer.rewind.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; -import { type Installed, Manual, Micro, Milli, Nano } from "@moq/clock"; +import { Duration, type Installed, Manual } from "@moq/clock"; import { Time, Track } from "@moq/net"; import { Consumer } from "./consumer"; import { encodeFrame, Format, Producer } from "./legacy"; @@ -8,16 +8,16 @@ import { encodeFrame, Format, Producer } from "./legacy"; let installed: Installed; beforeEach(() => { const clock = new Manual(); - clock.jump(Nano.fromMilli(Milli(200))); + clock.jump(Duration.millis(200)); installed = clock.install(); }); afterEach(() => installed.close()); function setup() { const track = new Track.Producer("rewind"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("video"), - delay: { max: Milli(30_000) }, + delay: { max: Duration.millis(30_000) }, }); return { track, consumer }; } @@ -26,14 +26,14 @@ function group(track: Track.Producer, timestamps: number[], end?: number) { const group = track.appendGroup(); for (const timestamp of timestamps) { group.writeFrame({ - timestamp: Time.Timestamp.fromMicros(Micro(timestamp)), - payload: encodeFrame(new Uint8Array([1]), Micro(timestamp)), + timestamp: Time.Timestamp.fromMicros(timestamp), + payload: encodeFrame(new Uint8Array([1]), Duration.micros(timestamp)), }); } if (end !== undefined) { group.writeFrame({ - timestamp: Time.Timestamp.fromMicros(Micro(end)), - payload: encodeFrame(new Uint8Array(), Micro(end)), + timestamp: Time.Timestamp.fromMicros(end), + payload: encodeFrame(new Uint8Array(), Duration.micros(end)), }); } group.finish(); @@ -52,10 +52,10 @@ test("Consumer accepts a resuming keyframe before the estimated group end", asyn // A cut estimates the final 33ms frame's end at 66ms. Playback consumes that // marker before the encoder resumes at 50ms, so the end cannot be a floor. group(track, [0, 33_000], 66_000); - expect((await frame(consumer))?.frame?.timestamp).toBe(Micro(0)); - expect((await frame(consumer))?.frame?.timestamp).toBe(Micro(33_000)); + expect((await frame(consumer))?.frame?.timestamp.asMicros()).toBe(0); + expect((await frame(consumer))?.frame?.timestamp.asMicros()).toBe(33_000); group(track, [50_000]); - expect((await frame(consumer))?.frame?.timestamp).toBe(Micro(50_000)); + expect((await frame(consumer))?.frame?.timestamp.asMicros()).toBe(50_000); } finally { consumer.close(); track.finish(); @@ -68,11 +68,11 @@ for (const start of [16_000, 0]) { const { track, consumer } = setup(); const producer = new Producer(track, new Format("video")); try { - producer.encode(new Uint8Array([1]), Micro(0), true); - producer.encode(new Uint8Array([1]), Micro(33_000), false); + producer.encode(new Uint8Array([1]), Duration.micros(0), true); + producer.encode(new Uint8Array([1]), Duration.micros(33_000), false); expect((await frame(consumer))?.group).toBe(0n); await frame(consumer); - producer.encode(new Uint8Array([1]), Micro(start), true); + producer.encode(new Uint8Array([1]), Duration.micros(start), true); expect((await frame(consumer))?.group).toBe(1n); } finally { consumer.close(); @@ -88,8 +88,8 @@ test("Consumer accepts leading pictures below the previous group's content", asy await frame(consumer); await frame(consumer); group(track, [200_000, 150_000]); - expect((await frame(consumer))?.frame?.timestamp).toBe(Micro(200_000)); - expect((await frame(consumer))?.frame?.timestamp).toBe(Micro(150_000)); + expect((await frame(consumer))?.frame?.timestamp.asMicros()).toBe(200_000); + expect((await frame(consumer))?.frame?.timestamp.asMicros()).toBe(150_000); } finally { consumer.close(); track.finish(); @@ -104,13 +104,13 @@ test("Consumer rejects a later frame below the previous group start", async () = await frame(consumer); const current = track.appendGroup(); current.writeFrame({ - timestamp: Time.Timestamp.fromMicros(Micro(200_000)), - payload: encodeFrame(new Uint8Array([1]), Micro(200_000)), + timestamp: Time.Timestamp.fromMicros(200_000), + payload: encodeFrame(new Uint8Array([1]), Duration.micros(200_000)), }); await frame(consumer); current.writeFrame({ - timestamp: Time.Timestamp.fromMicros(Micro(99_000)), - payload: encodeFrame(new Uint8Array([1]), Micro(99_000)), + timestamp: Time.Timestamp.fromMicros(99_000), + payload: encodeFrame(new Uint8Array([1]), Duration.micros(99_000)), }); await expect(frame(consumer)).rejects.toThrow("below"); } finally { @@ -124,13 +124,13 @@ test("Producer refuses a rewind before closing the current group", () => { const track = new Track.Producer("rewind"); const producer = new Producer(track, new Format("video")); try { - producer.encode(new Uint8Array([1]), Micro(100_000), true); - expect(() => producer.encode(new Uint8Array([1]), Micro(99_000), true)).toThrow("below"); + producer.encode(new Uint8Array([1]), Duration.micros(100_000), true); + expect(() => producer.encode(new Uint8Array([1]), Duration.micros(99_000), true)).toThrow("below"); // The refused keyframe must not close the group and strand its delta frames. - producer.encode(new Uint8Array([1]), Micro(110_000), false); - producer.encode(new Uint8Array([1]), Micro(200_000), true); - producer.encode(new Uint8Array([1]), Micro(150_000), false); - expect(() => producer.encode(new Uint8Array([1]), Micro(99_000), false)).toThrow("below"); + producer.encode(new Uint8Array([1]), Duration.micros(110_000), false); + producer.encode(new Uint8Array([1]), Duration.micros(200_000), true); + producer.encode(new Uint8Array([1]), Duration.micros(150_000), false); + expect(() => producer.encode(new Uint8Array([1]), Duration.micros(99_000), false)).toThrow("below"); } finally { producer.close(); } diff --git a/js/hang/src/container/consumer.skips.test.ts b/js/hang/src/container/consumer.skips.test.ts index b5f61390881..9b9e6e1b253 100644 --- a/js/hang/src/container/consumer.skips.test.ts +++ b/js/hang/src/container/consumer.skips.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Time, Track, Varint } from "@moq/net"; import { Signal } from "@moq/signals"; import { Consumer } from "./consumer.ts"; @@ -11,8 +11,8 @@ for (const count of [1, 16, 256]) { test(`Consumer summarizes ${count} skipped groups once per catch-up`, async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("tone"); - const delay = new Signal({ max: Milli(30_000) }); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const delay = new Signal({ max: Duration.millis(30_000) }); + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), delay, }); @@ -22,19 +22,19 @@ for (const count of [1, 16, 256]) { return group; }; const buffered = async (timestamp: number) => { - while (consumer.buffered.peek().at(-1)?.end !== timestamp) await consumer.buffered.changed(); + while (consumer.buffered.peek().at(-1)?.end.asMillis() !== timestamp) await consumer.buffered.changed(); }; try { // Sparse sequence numbers make the count differ from the sequence range. for (let i = 0; i < count; i++) write(BigInt(i) * 2n, i * 1000); await buffered(count - 1); expect(warn).not.toHaveBeenCalled(); - delay.set({ max: Milli.zero }); + delay.set({ max: Duration.ZERO }); const newest = write(BigInt(count) * 2n, count * 1000); await buffered(count); expect(warn).toHaveBeenCalledTimes(1); expect(warn).toHaveBeenLastCalledWith(`skipping slow groups: track=tone 0 -> ${count * 2} count=${count}`); - expect(consumer.buffered.peek()[0]?.start).toBe(Milli(count)); + expect(consumer.buffered.peek()[0]?.start).toEqual(Duration.millis(count)); // The retained group is still delivered, and another catch-up reports separately. expect(await consumer.next()).toMatchObject({ kind: "frame", group: BigInt(count) * 2n }); newest.writeFrame({ payload: Varint.encode(count * 1000), timestamp: Time.Timestamp.now() }); @@ -61,9 +61,9 @@ for (const open of [true, false]) { test(`a buffered backlog starts within the budget (sixth group ${open ? "open" : "finished"})`, async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("backlog"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(1500) }, + delay: { max: Duration.millis(1500) }, }); const frame = (micros: number) => ({ payload: Varint.encode(micros), timestamp: Time.Timestamp.now() }); try { @@ -75,13 +75,13 @@ for (const open of [true, false]) { const last = track.createGroup(5n); last.writeFrame(frame(5_000_000)); if (!open) last.finish(); - while (consumer.buffered.peek().at(-1)?.end !== 5000) await consumer.buffered.changed(); + while (consumer.buffered.peek().at(-1)?.end.asMillis() !== 5000) await consumer.buffered.changed(); const read: number[] = []; for (let i = 0; i < 11; i++) { const next = await consumer.next(); if (next?.kind !== "frame") throw new Error(`unexpected read: ${JSON.stringify(next)}`); - read.push(next.frame.timestamp); + read.push(next.frame.timestamp.asMicros()); } const expected = [...Array.from({ length: 10 }, (_, f) => 4_000_000 + f * 100_000), 5_000_000]; expect(read).toEqual(expected); @@ -101,9 +101,9 @@ for (const open of [true, false]) { test("a backlog start waits on a successor without frames", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("backlog"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(1500) }, + delay: { max: Duration.millis(1500) }, }); const frame = (micros: number) => ({ payload: Varint.encode(micros), timestamp: Time.Timestamp.now() }); const frames = (g: bigint) => Array.from({ length: 10 }, (_, f) => Number(g) * 1_000_000 + f * 100_000); @@ -112,7 +112,7 @@ test("a backlog start waits on a successor without frames", async () => { for (let i = 0; i < n; i++) { const next = await consumer.next(); if (next?.kind !== "frame") throw new Error(`unexpected read: ${JSON.stringify(next)}`); - read.push(next.frame.timestamp); + read.push(next.frame.timestamp.asMicros()); } }; try { @@ -127,7 +127,7 @@ test("a backlog start waits on a successor without frames", async () => { const last = track.createGroup(5n); last.writeFrame(frame(5_000_000)); last.finish(); - while (consumer.buffered.peek().at(-1)?.end !== 5000) await consumer.buffered.changed(); + while (consumer.buffered.peek().at(-1)?.end.asMillis() !== 5000) await consumer.buffered.changed(); await readN(10); for (const micros of frames(4n)) fifth.writeFrame({ payload: Varint.encode(micros), timestamp: sent }); @@ -145,8 +145,8 @@ test("a backlog start waits on a successor without frames", async () => { test("Consumer measures each skip's span over every group left, not just the new oldest", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("tone"); - const delay = new Signal({ max: Milli(30_000) }); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const delay = new Signal({ max: Duration.millis(30_000) }); + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), delay, }); @@ -155,7 +155,7 @@ test("Consumer measures each skip's span over every group left, not just the new group.writeFrame({ payload: Varint.encode(timestamp), timestamp: Time.Timestamp.now() }); }; const buffered = async (timestamp: number) => { - while (consumer.buffered.peek().at(-1)?.end !== timestamp) await consumer.buffered.changed(); + while (consumer.buffered.peek().at(-1)?.end.asMillis() !== timestamp) await consumer.buffered.changed(); }; try { // Group 2 starts below group 1, so the span after skipping group 0 still reaches back to it. @@ -169,13 +169,13 @@ test("Consumer measures each skip's span over every group left, not just the new await buffered(12); // Before the first read, the span alone ages a group out: once reading began, its successor's // start bounds it instead, which the span always reaches past. - delay.set({ max: Milli(5) }); + delay.set({ max: Duration.millis(5) }); write(4n, 13_000); await buffered(13); expect(warn).toHaveBeenLastCalledWith("skipping slow groups: track=tone 0 -> 3 count=3"); expect(consumer.buffered.peek()).toEqual([ - { start: Milli(12), end: Milli(12) }, - { start: Milli(13), end: Milli(13) }, + { start: Duration.millis(12), end: Duration.millis(12) }, + { start: Duration.millis(13), end: Duration.millis(13) }, ]); // Joining mid-track is not a gap: nothing was read before it. expect(await consumer.next()).toMatchObject({ kind: "frame", group: 3n }); @@ -193,9 +193,9 @@ test("Consumer measures each skip's span over every group left, not just the new test("a blocking group is kept until its successor starts a budget behind the newest", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("tone"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(150) }, + delay: { max: Duration.millis(150) }, }); const sent = Time.Timestamp.now(); const write = (sequence: bigint, timestamp: number) => { @@ -232,9 +232,9 @@ test("a blocking group is kept until its successor starts a budget behind the ne test("a blocking group ages out past an unstamped successor", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("tone"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(150) }, + delay: { max: Duration.millis(150) }, }); const sent = Time.Timestamp.now(); try { diff --git a/js/hang/src/container/consumer.startup.test.ts b/js/hang/src/container/consumer.startup.test.ts index 8b9d3935caf..1a7b486249c 100644 --- a/js/hang/src/container/consumer.startup.test.ts +++ b/js/hang/src/container/consumer.startup.test.ts @@ -1,5 +1,5 @@ import { expect, onTestFinished, spyOn, test } from "bun:test"; -import { Manual, Micro, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { type Group, Error as NetError, StreamCode, Time, Track } from "@moq/net"; import { Consumer, type Read } from "./consumer.ts"; import { encodeFrame, Format } from "./legacy.ts"; @@ -8,11 +8,11 @@ function setup(maxDelay = 100) { const clock = new Manual(); const installed = clock.install(); // Drain the in-memory readers and their continuations without moving time. - const flush = () => clock.advance(Nano.zero); + const flush = () => clock.advance(Duration.ZERO); const track = new Track.Producer("video"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("video"), - delay: { max: Milli(maxDelay) }, + delay: { max: Duration.millis(maxDelay) }, }); const results: Read[] = []; const warn = spyOn(console, "warn").mockImplementation(() => {}); @@ -40,9 +40,9 @@ function setup(maxDelay = 100) { // Each item as "gap <µs>+<µs>", "@<µs>" for a frame, or "end @<µs>". function items(results: Read[]): string[] { return results.map((read) => { - if (read.kind === "gap") return `gap ${read.timestamp}+${read.duration}`; - if (read.kind === "end") return `end ${read.group}@${read.end}`; - return `${read.group}@${read.frame.timestamp}`; + if (read.kind === "gap") return `gap ${read.timestamp.asMicros()}+${read.duration.asMicros()}`; + if (read.kind === "end") return `end ${read.group}@${read.end.asMicros()}`; + return `${read.group}@${read.frame.timestamp.asMicros()}`; }); } @@ -52,7 +52,7 @@ function frames(results: Read[]) { function write(group: Group.Producer, timestamp: number, marker = false) { group.writeFrame({ - payload: encodeFrame(marker ? new Uint8Array() : new Uint8Array([1]), Micro(timestamp)), + payload: encodeFrame(marker ? new Uint8Array() : new Uint8Array([1]), Duration.micros(timestamp)), timestamp: Time.Timestamp.now(), }); } diff --git a/js/hang/src/container/consumer.test.ts b/js/hang/src/container/consumer.test.ts index 30bf5525266..e13fe20d41d 100644 --- a/js/hang/src/container/consumer.test.ts +++ b/js/hang/src/container/consumer.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; import { readFileSync } from "node:fs"; -import { type Installed, Manual, type Micro, Milli, Nano } from "@moq/clock"; +import { Duration, type Installed, Manual } from "@moq/clock"; import { Format as LocFormat } from "@moq/loc"; import { type Group, Error as NetError, SessionCode, StreamCode, Time, Track, Varint } from "@moq/net"; import { decodeInitSegment, type InitSegment } from "../cmaf/decode.ts"; @@ -24,7 +24,7 @@ const TEST_INIT: InitSegment = { defaultSampleFlags: 0, }; -function encodeLegacyFrame(timestamp: Micro, payload: Uint8Array): Uint8Array { +function encodeLegacyFrame(timestamp: number, payload: Uint8Array): Uint8Array { const tsBytes = Varint.encode(timestamp); const data = new Uint8Array(tsBytes.byteLength + payload.byteLength); data.set(tsBytes, 0); @@ -33,13 +33,13 @@ function encodeLegacyFrame(timestamp: Micro, payload: Uint8Array): Uint8Array { } /** A LOC frame carrying only the timestamp property (0x10). */ -function encodeLocFrame(timestamp: Micro, payload: Uint8Array): Uint8Array { +function encodeLocFrame(timestamp: number, payload: Uint8Array): Uint8Array { const props = new Uint8Array([...Varint.encode(0x10), ...Varint.encode(timestamp)]); return new Uint8Array([...Varint.encode(props.byteLength), ...props, ...payload]); } /** Write each group of `[timestamp, payload]` LOC frames to `track`, then close it. */ -function writeLoc(track: Track.Producer, groups: [Micro, number[]][][]) { +function writeLoc(track: Track.Producer, groups: [number, number[]][][]) { for (const frames of groups) { const group = track.appendGroup(); for (const [timestamp, payload] of frames) { @@ -62,12 +62,14 @@ function at(ticks: number): Time.Timestamp { // Fixed cadence keeps timing-only tests independent of CMAF parsing. const timedLegacy: ContainerFormat = { decode(payload) { - return new LegacyFormat("video").decode(payload).map((frame) => ({ ...frame, duration: 33_333 as Micro })); + return new LegacyFormat("video") + .decode(payload) + .map((frame) => ({ ...frame, duration: Duration.micros(33_333) })); }, }; /** A one-byte legacy frame at the test track timestamp. */ function timedFrame(data: number, timestamp: number, _sequence: number): Group.Frame { - const payload = encodeLegacyFrame(Math.round((timestamp / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([data])); + const payload = encodeLegacyFrame(Math.round((timestamp / TIMESCALE) * 1_000_000), new Uint8Array([data])); return { payload, timestamp: at(timestamp) }; } @@ -84,7 +86,7 @@ afterEach(() => { /** Let the consumer's group readers drain what's been written, without moving time. */ function flush(): Promise { - return clock.advance(Nano.zero); + return clock.advance(Duration.ZERO); } /** Flush, then return what `read` settled with, or "pending" if it is still waiting. */ @@ -102,7 +104,7 @@ async function poll(read: Promise): Promise { // These tests write every group up front and only then read, so they ask for history // rather than the live edge. function replay(track: Track.Producer): Track.Subscriber { - return track.subscribe({ delay: { max: Milli(30_000) } }); + return track.subscribe({ delay: { max: Duration.millis(30_000) } }); } // --- LegacyFormat --- @@ -110,30 +112,30 @@ function replay(track: Track.Producer): Track.Subscriber { test("LegacyFormat decodes a valid frame", () => { const format = new LegacyFormat("data"); const payload = new Uint8Array([0xde, 0xad]); - const timestamp = 1000 as Micro; + const timestamp = 1000; const frame = encodeLegacyFrame(timestamp, payload); const result = format.decode(frame); expect(result).toHaveLength(1); - expect(result[0].timestamp).toBe(timestamp); + expect(result[0].timestamp.asMicros()).toBe(timestamp); expect(result[0].payload).toEqual(payload); expect(result[0].keyframe).toBe(false); }); test("LegacyFormat preserves a duration marker", () => { const format = new LegacyFormat("video"); - const frame = encodeLegacyFrame(1000 as Micro, new Uint8Array()); + const frame = encodeLegacyFrame(1000, new Uint8Array()); const [marker] = format.decode(frame); - expect(marker.timestamp).toBe(1000 as Micro); + expect(marker.timestamp.asMicros()).toBe(1000); expect(marker.payload).toHaveLength(0); - expect(format.end(marker)).toBe(1000 as Micro); + expect(format.end(marker)).toEqual(Duration.micros(1000)); }); test("LegacyFormat always returns keyframe: false", () => { const format = new LegacyFormat("data"); - const frame = encodeLegacyFrame(0 as Micro, new Uint8Array([0x01])); + const frame = encodeLegacyFrame(0, new Uint8Array([0x01])); const [decoded] = format.decode(frame); expect(decoded.keyframe).toBe(false); @@ -141,7 +143,7 @@ test("LegacyFormat always returns keyframe: false", () => { test("LegacyFormat always returns exactly one frame", () => { const format = new LegacyFormat("data"); - const frame = encodeLegacyFrame(5000 as Micro, new Uint8Array([0x01, 0x02, 0x03])); + const frame = encodeLegacyFrame(5000, new Uint8Array([0x01, 0x02, 0x03])); const result = format.decode(frame); expect(result).toHaveLength(1); @@ -155,65 +157,67 @@ test("LegacyFormat decodes no frame from a data track's empty object and throws test("Legacy Producer refuses a group below the previous group start", () => { const track = new Track.Producer("test"); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([1]), 20_000 as Micro, true); - producer.encode(new Uint8Array([1]), 33_000 as Micro, false); - expect(() => producer.encode(new Uint8Array([1]), 16_000 as Micro, true)).toThrow("below the previous group start"); + producer.encode(new Uint8Array([1]), Duration.micros(20_000), true); + producer.encode(new Uint8Array([1]), Duration.micros(33_000), false); + expect(() => producer.encode(new Uint8Array([1]), Duration.micros(16_000), true)).toThrow( + "below the previous group start", + ); producer.close(); }); test("Legacy Producer accepts B-frames within a group", () => { const track = new Track.Producer("test"); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([1]), 0 as Micro, true); - producer.encode(new Uint8Array([1]), 66_000 as Micro, false); - producer.encode(new Uint8Array([1]), 33_000 as Micro, false); + producer.encode(new Uint8Array([1]), Duration.micros(0), true); + producer.encode(new Uint8Array([1]), Duration.micros(66_000), false); + producer.encode(new Uint8Array([1]), Duration.micros(33_000), false); producer.close(); }); test("Legacy Producer accepts open-GOP leading pictures above the previous group", () => { const track = new Track.Producer("test"); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([1]), 0 as Micro, true); - producer.encode(new Uint8Array([1]), 33_000 as Micro, false); - producer.encode(new Uint8Array([1]), 66_000 as Micro, true); - producer.encode(new Uint8Array([1]), 50_000 as Micro, false); + producer.encode(new Uint8Array([1]), Duration.micros(0), true); + producer.encode(new Uint8Array([1]), Duration.micros(33_000), false); + producer.encode(new Uint8Array([1]), Duration.micros(66_000), true); + producer.encode(new Uint8Array([1]), Duration.micros(50_000), false); producer.close(); }); test("Legacy Producer writes a duration marker at the next keyframe", async () => { const track = new Track.Producer("test"); - const subscriber = track.subscribe({ delay: { max: Milli(30_000) } }); + const subscriber = track.subscribe({ delay: { max: Duration.millis(30_000) } }); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([0xde, 0xad]), 0 as Micro, true); - producer.encode(new Uint8Array([0xbe, 0xef]), 10_000 as Micro, false); - producer.encode(new Uint8Array([0xca, 0xfe]), 20_000 as Micro, true); + producer.encode(new Uint8Array([0xde, 0xad]), Duration.micros(0), true); + producer.encode(new Uint8Array([0xbe, 0xef]), Duration.micros(10_000), false); + producer.encode(new Uint8Array([0xca, 0xfe]), Duration.micros(20_000), true); producer.close(); const group = await subscriber.recvGroup(); expect(group).toBeDefined(); - const frames: { timestamp: Micro; size: number }[] = []; + const frames: { timestamp: number; size: number }[] = []; for (;;) { const frame = await group?.readFrame(); if (!frame) break; const [timestamp, payload] = Varint.decode(frame.payload); - frames.push({ timestamp: timestamp as Micro, size: payload.byteLength }); + frames.push({ timestamp: timestamp, size: payload.byteLength }); } expect(frames).toEqual([ - { timestamp: 0 as Micro, size: 2 }, - { timestamp: 10_000 as Micro, size: 2 }, - { timestamp: 20_000 as Micro, size: 0 }, + { timestamp: 0, size: 2 }, + { timestamp: 10_000, size: 2 }, + { timestamp: 20_000, size: 0 }, ]); }); test("Legacy Producer omits a reordered group's presentation endpoint marker", async () => { const track = new Track.Producer("test"); - const subscriber = track.subscribe({ delay: { max: Milli(30_000) } }); + const subscriber = track.subscribe({ delay: { max: Duration.millis(30_000) } }); const producer = new LegacyProducer(track, new LegacyFormat("video")); for (const [index, timestamp] of [0, 120_000, 40_000, 80_000].entries()) { - producer.encode(new Uint8Array([1]), timestamp as Micro, index === 0); + producer.encode(new Uint8Array([1]), Duration.micros(timestamp), index === 0); } - producer.encode(new Uint8Array([1]), 160_000 as Micro, true); - producer.discontinuity(200_000 as Micro); + producer.encode(new Uint8Array([1]), Duration.micros(160_000), true); + producer.discontinuity(Duration.micros(200_000)); producer.close(); const group = await subscriber.recvGroup(); expect(group).toBeDefined(); @@ -233,10 +237,10 @@ test("Legacy Producer omits a reordered group's presentation endpoint marker", a test("Legacy Producer estimates the tail from the current cadence", async () => { const track = new Track.Producer("test"); - const subscriber = track.subscribe({ delay: { max: Milli(30_000) } }); + const subscriber = track.subscribe({ delay: { max: Duration.millis(30_000) } }); const producer = new LegacyProducer(track, new LegacyFormat("video")); for (const [index, timestamp] of [0, 16_000, 32_000, 65_000, 98_000].entries()) { - producer.encode(new Uint8Array([1]), timestamp as Micro, index === 0); + producer.encode(new Uint8Array([1]), Duration.micros(timestamp), index === 0); } producer.close(); const group = await subscriber.recvGroup(); @@ -253,12 +257,12 @@ test("Legacy Producer estimates the tail from the current cadence", async () => test("Legacy Producer rejects a backwards discontinuity without closing the group", async () => { const track = new Track.Producer("test"); - const subscriber = track.subscribe({ delay: { max: Milli(30_000) } }); + const subscriber = track.subscribe({ delay: { max: Duration.millis(30_000) } }); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([1]), 20_000 as Micro, true); - expect(() => producer.discontinuity(10_000 as Micro)).toThrow(); - producer.encode(new Uint8Array([2]), 30_000 as Micro, false); - producer.discontinuity(35_000 as Micro); + producer.encode(new Uint8Array([1]), Duration.micros(20_000), true); + expect(() => producer.discontinuity(Duration.micros(10_000))).toThrow(); + producer.encode(new Uint8Array([2]), Duration.micros(30_000), false); + producer.discontinuity(Duration.micros(35_000)); producer.close(); const group = await subscriber.recvGroup(); const timestamps = []; @@ -272,11 +276,11 @@ test("Legacy Producer rejects a backwards discontinuity without closing the grou test("Legacy Producer keeps the cadence after rejecting a backwards discontinuity", async () => { const track = new Track.Producer("test"); - const subscriber = track.subscribe({ delay: { max: Milli(30_000) } }); + const subscriber = track.subscribe({ delay: { max: Duration.millis(30_000) } }); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([1]), 20_000 as Micro, true); - producer.encode(new Uint8Array([2]), 30_000 as Micro, false); - expect(() => producer.discontinuity(10_000 as Micro)).toThrow(); + producer.encode(new Uint8Array([1]), Duration.micros(20_000), true); + producer.encode(new Uint8Array([2]), Duration.micros(30_000), false); + expect(() => producer.discontinuity(Duration.micros(10_000))).toThrow(); producer.close(); const group = await subscriber.recvGroup(); const timestamps = []; @@ -291,9 +295,11 @@ test("Legacy Producer keeps the cadence after rejecting a backwards discontinuit test("Legacy Producer refuses a keyframe that rewinds the timeline", () => { const track = new Track.Producer("test"); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([1]), 20_000 as Micro, true); - producer.encode(new Uint8Array([2]), 30_000 as Micro, false); - expect(() => producer.encode(new Uint8Array([3]), 0 as Micro, true)).toThrow("below the previous group start"); + producer.encode(new Uint8Array([1]), Duration.micros(20_000), true); + producer.encode(new Uint8Array([2]), Duration.micros(30_000), false); + expect(() => producer.encode(new Uint8Array([3]), Duration.micros(0), true)).toThrow( + "below the previous group start", + ); producer.close(); }); @@ -319,11 +325,11 @@ test("Legacy Producer discontinuity marks the break with one empty frame at the const track = new Track.Producer("test"); const subscriber = replay(track); const producer = new LegacyProducer(track, new LegacyFormat("audio")); - producer.encode(new Uint8Array([1]), 0 as Micro, true); - producer.encode(new Uint8Array([1]), 20_000 as Micro, true); + producer.encode(new Uint8Array([1]), Duration.micros(0), true); + producer.encode(new Uint8Array([1]), Duration.micros(20_000), true); producer.discontinuity(); producer.discontinuity(); // nothing new to mark - producer.encode(new Uint8Array([1]), 5_000_000 as Micro, true); + producer.encode(new Uint8Array([1]), Duration.micros(5_000_000), true); producer.close(); expect(await readGroups(subscriber, 3n)).toEqual([ @@ -338,8 +344,8 @@ test("Legacy Producer discontinuity marks the break at the caller's end", async const track = new Track.Producer("test"); const subscriber = replay(track); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([1]), 0 as Micro, true); - producer.discontinuity(33_000 as Micro); + producer.encode(new Uint8Array([1]), Duration.micros(0), true); + producer.discontinuity(Duration.micros(33_000)); producer.close(); expect(await readGroups(subscriber, 1n)).toEqual([ @@ -359,11 +365,11 @@ test("Legacy Producer discontinuity writes no end estimated from the cadence", a const subscriber = replay(track); const producer = new LegacyProducer(track, new LegacyFormat("video")); for (const [index, timestamp] of [0, 33_000, 66_000].entries()) { - producer.encode(new Uint8Array([1]), timestamp as Micro, index === 0); + producer.encode(new Uint8Array([1]), Duration.micros(timestamp), index === 0); } producer.discontinuity(); // The capture swap resumes sooner than one frame later: no end past it, so no rewind. - producer.encode(new Uint8Array([1]), 80_000 as Micro, true); + producer.encode(new Uint8Array([1]), Duration.micros(80_000), true); producer.close(); expect(await readGroups(subscriber, 2n)).toEqual([ @@ -392,13 +398,16 @@ test("Legacy Producer discontinuity on a data track reads as an end at the edge" const track = new Track.Producer("data"); const subscriber = replay(track); const producer = new LegacyProducer(track, new LegacyFormat("data")); - producer.encode(new Uint8Array([1]), 0 as Micro, true); - producer.encode(new Uint8Array(), 20_000 as Micro, true); + producer.encode(new Uint8Array([1]), Duration.micros(0), true); + producer.encode(new Uint8Array(), Duration.micros(20_000), true); producer.discontinuity(); - producer.encode(new Uint8Array([1]), 5_000_000 as Micro, true); + producer.encode(new Uint8Array([1]), Duration.micros(5_000_000), true); producer.close(); - const consumer = new Consumer(subscriber, { format: new LegacyFormat("data"), delay: { max: 30_000 as Milli } }); + const consumer = new Consumer(subscriber, { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(30_000) }, + }); const items: string[] = []; for (let read = await consumer.next(); read; read = await consumer.next()) items.push(describe(read)); expect(items).toEqual(["0", "20000", "end 20000", "5000000"]); @@ -410,11 +419,11 @@ test("Legacy Producer discontinuity on a data track reads as an end at the edge" // A data track's marker is alone in its group, so one sharing it is refused rather than read as // a break or dropped in silence. test("Consumer refuses a data marker that shares its group", async () => { - for (const second of [new Uint8Array(), encodeLegacyFrame(10_000 as Micro, new Uint8Array([1]))]) { + for (const second of [new Uint8Array(), encodeLegacyFrame(10_000, new Uint8Array([1]))]) { const track = new Track.Producer("data"); const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), - delay: { max: 500 as Milli }, + delay: { max: Duration.millis(500) }, }); try { const group = track.appendGroup(); @@ -436,13 +445,13 @@ test("Consumer refuses a data marker that shares its group", async () => { test("Legacy Producer discontinuity keeps pre-pause media from reading as live", async () => { const track = new Track.Producer("test"); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([1]), 0 as Micro, true); - producer.encode(new Uint8Array([1]), 33_000 as Micro, false); + producer.encode(new Uint8Array([1]), Duration.micros(0), true); + producer.encode(new Uint8Array([1]), Duration.micros(33_000), false); producer.discontinuity(); - producer.encode(new Uint8Array([1]), 5_000_000 as Micro, true); + producer.encode(new Uint8Array([1]), Duration.micros(5_000_000), true); producer.close(); - const subscriber = track.subscribe({ delay: { max: Milli(1_000) } }); + const subscriber = track.subscribe({ delay: { max: Duration.millis(1_000) } }); expect((await readGroups(subscriber, 2n)).map(([sequence]) => sequence)).toEqual([1n, 2n]); }); @@ -462,7 +471,7 @@ test("CmafFormat decodes a valid keyframe segment", () => { expect(result).toHaveLength(1); expect(result[0].payload).toEqual(new Uint8Array([0xca, 0xfe])); - expect(result[0].timestamp).toBe(0 as Micro); + expect(result[0].timestamp.asMicros()).toBe(0); expect(result[0].keyframe).toBe(true); }); @@ -504,7 +513,7 @@ test("CmafFormat converts timescale units to microseconds", () => { const segment = fragment("oneSecond"); const result = format.decode(segment, at(TIMESCALE)); - expect(result[0].timestamp).toBe(1_000_000 as Micro); + expect(result[0].timestamp.asMicros()).toBe(1_000_000); }); test("CmafFormat throws on corrupt segment", () => { @@ -514,7 +523,7 @@ test("CmafFormat throws on corrupt segment", () => { // --- Consumer --- -function encodeLegacy(timestamp: Micro): Uint8Array { +function encodeLegacy(timestamp: number): Uint8Array { const tsBytes = Varint.encode(timestamp); const payload = new Uint8Array([0xde, 0xad]); const data = new Uint8Array(tsBytes.byteLength + payload.byteLength); @@ -527,8 +536,8 @@ function encodeLegacy(timestamp: Micro): Uint8Array { function writeGroupWithLegacyFrames( track: Track.Producer, sequence: bigint, - timestamps: Micro[], - stamp: (ts: Micro) => Time.Timestamp = (ts) => Time.Timestamp.fromMicros(ts), + timestamps: number[], + stamp: (ts: number) => Time.Timestamp = (ts) => Time.Timestamp.fromMicros(ts), ) { const group = track.createGroup(sequence); for (const ts of timestamps) { @@ -537,7 +546,7 @@ function writeGroupWithLegacyFrames( group.finish(); } -function writeMarkerGroup(track: Track.Producer, sequence: bigint, timestamp: Micro) { +function writeMarkerGroup(track: Track.Producer, sequence: bigint, timestamp: number) { const group = track.createGroup(sequence); group.writeFrame({ payload: encodeLegacyFrame(timestamp, new Uint8Array()), @@ -547,13 +556,17 @@ function writeMarkerGroup(track: Track.Producer, sequence: bigint, timestamp: Mi } /** Read every frame deliverable without moving time, leaving the read that waits pending. */ -async function drainFrames(consumer: Consumer): Promise<{ timestamp: Micro; group: bigint; keyframe: boolean }[]> { - const frames: { timestamp: Micro; group: bigint; keyframe: boolean }[] = []; +async function drainFrames(consumer: Consumer): Promise<{ timestamp: number; group: bigint; keyframe: boolean }[]> { + const frames: { timestamp: number; group: bigint; keyframe: boolean }[] = []; for (;;) { const result = await poll(consumer.next()); if (result === "pending" || result === undefined) break; if (result.kind === "frame") { - frames.push({ timestamp: result.frame.timestamp, group: result.group, keyframe: result.frame.keyframe }); + frames.push({ + timestamp: result.frame.timestamp.asMicros(), + group: result.group, + keyframe: result.frame.keyframe, + }); } } return frames; @@ -561,9 +574,9 @@ async function drainFrames(consumer: Consumer): Promise<{ timestamp: Micro; grou /** An item as "gap <µs>+<µs>", a frame's µs, or "end <µs>". */ function describe(read: Read): string { - if (read.kind === "gap") return `gap ${read.timestamp}+${read.duration}`; - if (read.kind === "end") return `end ${read.end}`; - return `${read.frame.timestamp}`; + if (read.kind === "gap") return `gap ${read.timestamp.asMicros()}+${read.duration.asMicros()}`; + if (read.kind === "end") return `end ${read.end.asMicros()}`; + return `${read.frame.timestamp.asMicros()}`; } /** The frame a read carries, failing on anything else. */ @@ -575,24 +588,30 @@ function frameOf(read: Read | string | undefined): Frame { test("Consumer delivers frames from a single group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(500) }, + }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro, 33_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); track.finish(); track.close(); const frames = await drainFrames(consumer); expect(frames).toHaveLength(2); - expect(frames[0].timestamp).toBe(0 as Micro); - expect(frames[1].timestamp).toBe(33_000 as Micro); + expect(frames[0].timestamp).toBe(0); + expect(frames[1].timestamp).toBe(33_000); consumer.close(); }); test("Consumer forces keyframe true at index 0", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(500) }, + }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro, 33_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); track.finish(); track.close(); @@ -607,15 +626,15 @@ test("Consumer index spans MoQ frames for keyframe detection", async () => { const multiFormat: ContainerFormat = { decode(_frame: Uint8Array): Frame[] { return [ - { payload: new Uint8Array([1]), timestamp: 0 as Micro, keyframe: false }, - { payload: new Uint8Array([2]), timestamp: 33_000 as Micro, keyframe: false }, - { payload: new Uint8Array([3]), timestamp: 66_000 as Micro, keyframe: false }, + { payload: new Uint8Array([1]), timestamp: Duration.micros(0), keyframe: false }, + { payload: new Uint8Array([2]), timestamp: Duration.micros(33_000), keyframe: false }, + { payload: new Uint8Array([3]), timestamp: Duration.micros(66_000), keyframe: false }, ]; }, }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: multiFormat, delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: multiFormat, delay: { max: Duration.millis(500) } }); const group = track.createGroup(0n); group.writeFrame({ payload: new Uint8Array([0x01]), timestamp: Time.Timestamp.now() }); // first MoQ frame → 3 samples @@ -643,12 +662,12 @@ for (const [where, payloads] of [ const failingFormat: ContainerFormat = { decode(frame: Uint8Array): Frame[] { if (frame[0] === 0xff) throw new Error("malformed"); - return [{ payload: frame, timestamp: frame[0] as Micro, keyframe: false }]; + return [{ payload: frame, timestamp: Duration.micros(frame[0]), keyframe: false }]; }, }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: failingFormat, delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: failingFormat, delay: { max: Duration.millis(500) } }); const g0 = track.createGroup(0n); for (const byte of payloads) @@ -667,7 +686,7 @@ for (const [where, payloads] of [ for (;;) { const result = await consumer.next(); if (!result) return result; - if (result.kind === "frame") frames.push(result.frame.timestamp); + if (result.kind === "frame") frames.push(result.frame.timestamp.asMicros()); } }; await expect(read()).rejects.toThrow("malformed"); @@ -679,10 +698,13 @@ for (const [where, payloads] of [ // Errors come in delivery order, so a decode error waits behind the items ahead of it, a gap included. test("Consumer delivers everything ahead of a decode error", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 10_000 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(10_000) }, + }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); - writeGroupWithLegacyFrames(track, 2n, [100_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); + writeGroupWithLegacyFrames(track, 2n, [100_000]); const malformed = track.createGroup(3n); // A truncated timestamp varint. malformed.writeFrame({ payload: new Uint8Array([0x80]), timestamp: Time.Timestamp.fromMicros(200_000) }); @@ -708,7 +730,7 @@ test("Consumer keeps the first of several decode errors", async () => { }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: failingFormat, delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: failingFormat, delay: { max: Duration.millis(500) } }); for (const sequence of [0n, 1n]) { const group = track.createGroup(sequence); @@ -734,12 +756,12 @@ test("Consumer releases its open groups when an error ends it", async () => { decode(frame: Uint8Array): Frame[] { if (frame[0] === 0xff) throw new Error("malformed"); if (frame[0] === 0x01) resolveOpen(); - return [{ payload: frame, timestamp: frame[0] as Micro, keyframe: false }]; + return [{ payload: frame, timestamp: Duration.micros(frame[0]), keyframe: false }]; }, }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: failingFormat, delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: failingFormat, delay: { max: Duration.millis(500) } }); const malformed = track.createGroup(0n); malformed.writeFrame({ payload: new Uint8Array([0xff]), timestamp: Time.Timestamp.now() }); @@ -771,19 +793,19 @@ test("Consumer keeps frames decoded before a group reset (truncated GoP)", async }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format, delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format, delay: { max: Duration.millis(500) } }); const g0 = track.createGroup(0n); for (const timestamp of [1, 2]) { g0.writeFrame({ - payload: encodeLegacyFrame(timestamp as Micro, new Uint8Array([1])), + payload: encodeLegacyFrame(timestamp, new Uint8Array([1])), timestamp: Time.Timestamp.fromMicros(timestamp), }); } await decoded; g0.abort(new NetError.Stream(StreamCode.Cancel)); - writeGroupWithLegacyFrames(track, 1n, [4 as Micro]); + writeGroupWithLegacyFrames(track, 1n, [4]); track.finish(); track.close(); @@ -795,7 +817,10 @@ test("Consumer keeps frames decoded before a group reset (truncated GoP)", async test("Consumer close returns undefined from next()", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(500) }, + }); const promise = consumer.next(); consumer.close(); @@ -806,7 +831,10 @@ test("Consumer close returns undefined from next()", async () => { test("Consumer throws on concurrent next() calls", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(500) }, + }); // First call blocks waiting for data void consumer.next(); @@ -819,12 +847,15 @@ test("Consumer throws on concurrent next() calls", async () => { test("Consumer skips groups via PTS-span when over the max delay", async () => { const track = new Track.Producer("test"); // Zero max delay = skip everything that's not the latest - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 0 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(0) }, + }); // Write groups with increasing timestamps. With a 0 max delay, any PTS span > 0 triggers skip. - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); - writeGroupWithLegacyFrames(track, 1n, [100_000 as Micro]); - writeGroupWithLegacyFrames(track, 2n, [200_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); + writeGroupWithLegacyFrames(track, 1n, [100_000]); + writeGroupWithLegacyFrames(track, 2n, [200_000]); track.finish(); track.close(); @@ -839,29 +870,29 @@ test("Consumer measures arrivals as they land", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("audio"), - delay: { max: 5000 as Milli }, + delay: { max: Duration.millis(5000) }, }); const next = new Track.Producer("next"); try { // Nothing observed yet: the cold-start estimate. - expect(consumer.spread.peek()).toBe(100 as Milli); + expect(consumer.spread.peek()).toEqual(Duration.millis(100)); // Groups arriving exactly as fast as their media, across four resample intervals. Nothing is // late, so the evidence pulls the estimate down from the cold start. for (let i = 0; i < 5; i++) { - writeGroupWithLegacyFrames(track, BigInt(i), [(i * 520_000) as Micro]); - await clock.advance(Nano.fromMilli(Milli(520))); + writeGroupWithLegacyFrames(track, BigInt(i), [i * 520_000]); + await clock.advance(Duration.millis(520)); } - expect(consumer.spread.peek()).toBeLessThan(100 as Milli); + expect(consumer.spread.peek().asMillis()).toBeLessThan(100); // A replacement on the same path continues the estimate rather than restarting cold. const replacement = new Consumer(next.subscribe(), { format: new LegacyFormat("audio"), - delay: { max: 5000 as Milli }, + delay: { max: Duration.millis(5000) }, predecessor: consumer, }); - expect(replacement.spread.peek()).toBe(consumer.spread.peek()); + expect(replacement.spread.peek()).toEqual(consumer.spread.peek()); replacement.close(); } finally { track.finish(); @@ -876,7 +907,7 @@ test("Consumer does not relax its measurement across a declared silence", async // Two identical paths, except that one publisher declares its silence and the other just stops. const declared = new Track.Producer("declared"); const undeclared = new Track.Producer("undeclared"); - const options = { format: new LegacyFormat("audio"), delay: { max: 5000 as Milli } }; + const options = { format: new LegacyFormat("audio"), delay: { max: Duration.millis(5000) } }; const quiet = new Consumer(declared.subscribe(), options); const lapsed = new Consumer(undeclared.subscribe(), options); const producers = [new LegacyProducer(declared, options.format), new LegacyProducer(undeclared, options.format)]; @@ -884,9 +915,9 @@ test("Consumer does not relax its measurement across a declared silence", async let media = 0; const send = async (count: number) => { for (let i = 0; i < count; i++) { - for (const producer of producers) producer.encode(payload, (media * 1000) as Micro, true); + for (const producer of producers) producer.encode(payload, Duration.micros(media * 1000), true); media += 520; - await clock.advance(Nano.fromMilli(Milli(520))); + await clock.advance(Duration.millis(520)); } }; @@ -894,16 +925,16 @@ test("Consumer does not relax its measurement across a declared silence", async // Arrivals exactly as fast as their media until the cold-start prior is spent. await send(40); const settled = quiet.spread.peek(); - expect(lapsed.spread.peek()).toBe(settled); + expect(lapsed.spread.peek()).toEqual(settled); // A minute of silence on both, declared on one. producers[0].discontinuity(); media += 60_000; - await clock.advance(Nano.fromMilli(Milli(60_000))); + await clock.advance(Duration.millis(60_000)); await send(2); - expect(quiet.spread.peek()).toBe(settled); - expect(lapsed.spread.peek()).toBeGreaterThan(settled); + expect(quiet.spread.peek()).toEqual(settled); + expect(lapsed.spread.peek().gt(settled)).toBe(true); } finally { for (const track of [declared, undeclared]) { track.finish(); @@ -918,11 +949,14 @@ test("Consumer does not relax its measurement across a declared silence", async test("Consumer delivers groups in sequence order regardless of arrival order", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(500) }, + }); - writeGroupWithLegacyFrames(track, 2n, [60_000 as Micro]); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); - writeGroupWithLegacyFrames(track, 1n, [30_000 as Micro]); + writeGroupWithLegacyFrames(track, 2n, [60_000]); + writeGroupWithLegacyFrames(track, 0n, [0]); + writeGroupWithLegacyFrames(track, 1n, [30_000]); track.finish(); track.close(); @@ -940,15 +974,18 @@ test("Consumer delivers groups in sequence order regardless of arrival order", a // group arriving there is never delivered and adds no gap. Mirrors Rust's consumer. test("Consumer drops a group that arrives below the cursor", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(500) }, + }); // Group 5 arrives first, and delivery starts there: the track reports no start. - writeGroupWithLegacyFrames(track, 5n, [100_000 as Micro]); + writeGroupWithLegacyFrames(track, 5n, [100_000]); expect((await nextFrame(consumer))?.group).toBe(5n); // Group 3 lands behind the cursor, and group 6 ahead of it. - writeGroupWithLegacyFrames(track, 3n, [0 as Micro]); - writeGroupWithLegacyFrames(track, 6n, [200_000 as Micro]); + writeGroupWithLegacyFrames(track, 3n, [0]); + writeGroupWithLegacyFrames(track, 6n, [200_000]); track.finish(); track.close(); @@ -966,10 +1003,13 @@ test("Consumer drops a group that arrives below the cursor", async () => { test("Consumer next() yields no gap before the first frame", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(500) }, + }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro, 33_000 as Micro]); - writeGroupWithLegacyFrames(track, 1n, [66_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); + writeGroupWithLegacyFrames(track, 1n, [66_000]); track.finish(); track.close(); @@ -988,16 +1028,23 @@ test("Consumer next() yields no gap before the first frame", async () => { test("Consumer reads nothing after close, even the frame a gap was returned ahead of", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 0 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(0) }, + }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(0); // Group 1 never arrives, so group 2's frame is deferred behind a gap. - writeGroupWithLegacyFrames(track, 2n, [100_000 as Micro]); + writeGroupWithLegacyFrames(track, 2n, [100_000]); await flush(); - expect(await consumer.next()).toEqual({ kind: "gap", timestamp: 0 as Micro, duration: 100_000 as Micro }); + expect(await consumer.next()).toEqual({ + kind: "gap", + timestamp: Duration.micros(0), + duration: Duration.micros(100_000), + }); consumer.close(); expect(await consumer.next()).toBeUndefined(); @@ -1009,16 +1056,16 @@ test("Consumer keeps a trailing duration marker internal", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("video"), - delay: { max: 500 as Milli }, + delay: { max: Duration.millis(500) }, }); const group = track.createGroup(0n); group.writeFrame({ - payload: encodeLegacyFrame(0 as Micro, new Uint8Array([0xde, 0xad])), + payload: encodeLegacyFrame(0, new Uint8Array([0xde, 0xad])), timestamp: Time.Timestamp.now(), }); group.writeFrame({ - payload: encodeLegacyFrame(33_000 as Micro, new Uint8Array()), + payload: encodeLegacyFrame(33_000, new Uint8Array()), timestamp: Time.Timestamp.now(), }); group.finish(); @@ -1039,23 +1086,23 @@ test("Consumer reads a leading marker as an end and keeps the first media keyfra const track = new Track.Producer("test"); const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("video"), - delay: { max: 500 as Milli }, + delay: { max: Duration.millis(500) }, }); const group = track.createGroup(0n); group.writeFrame({ - payload: encodeLegacyFrame(20_000 as Micro, new Uint8Array()), + payload: encodeLegacyFrame(20_000, new Uint8Array()), timestamp: Time.Timestamp.now(), }); group.writeFrame({ - payload: encodeLegacyFrame(20_000 as Micro, new Uint8Array([0xde, 0xad])), + payload: encodeLegacyFrame(20_000, new Uint8Array([0xde, 0xad])), timestamp: Time.Timestamp.now(), }); group.finish(); track.finish(); track.close(); - expect(await consumer.next()).toEqual({ kind: "end", group: 0n, end: 20_000 as Micro }); + expect(await consumer.next()).toEqual({ kind: "end", group: 0n, end: Duration.micros(20_000) }); const media = frameOf(await consumer.next()); expect(media.payload).toEqual(new Uint8Array([0xde, 0xad])); expect(media.keyframe).toBe(true); @@ -1067,13 +1114,16 @@ test("Consumer reads an empty LOC payload as the frame's duration", async () => const track = new Track.Producer("test"); writeLoc(track, [ [ - [0 as Micro, [0xde, 0xad]], - [33_000 as Micro, []], - [66_000 as Micro, []], + [0, [0xde, 0xad]], + [33_000, []], + [66_000, []], ], ]); - const consumer = new Consumer(replay(track), { format: new LocFormat("video"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LocFormat("video"), + delay: { max: Duration.millis(500) }, + }); await flush(); const media = frameOf(await consumer.next()); expect(media.payload).toEqual(new Uint8Array([0xde, 0xad])); @@ -1086,17 +1136,20 @@ test("Consumer passes over LOC duration markers", async () => { const track = new Track.Producer("test"); writeLoc(track, [ [ - [0 as Micro, [0xde, 0xad]], - [10_000 as Micro, [0xbe, 0xef]], - [20_000 as Micro, []], + [0, [0xde, 0xad]], + [10_000, [0xbe, 0xef]], + [20_000, []], ], [ - [20_000 as Micro, [0xca, 0xfe]], - [30_000 as Micro, []], + [20_000, [0xca, 0xfe]], + [30_000, []], ], ]); - const consumer = new Consumer(replay(track), { format: new LocFormat("video"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LocFormat("video"), + delay: { max: Duration.millis(500) }, + }); await flush(); const first = frameOf(await consumer.next()); expect(first.payload).toEqual(new Uint8Array([0xde, 0xad])); @@ -1114,13 +1167,13 @@ test("Consumer preserves empty Legacy and LOC data frames", async () => { const track = new Track.Producer("data"); if (kind === "legacy") { const producer = new LegacyProducer(track, new LegacyFormat("data")); - producer.encode(new Uint8Array(), 0 as Micro, true); + producer.encode(new Uint8Array(), Duration.micros(0), true); producer.close(); } else { - writeLoc(track, [[[0 as Micro, []]]]); + writeLoc(track, [[[0, []]]]); } const format = kind === "legacy" ? new LegacyFormat("data") : new LocFormat(); - const consumer = new Consumer(replay(track), { format, delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format, delay: { max: Duration.millis(500) } }); const frame = frameOf(await consumer.next()); expect(frame.payload).toEqual(new Uint8Array()); expect(frame.keyframe).toBe(true); @@ -1144,13 +1197,16 @@ const wallClock = () => Time.Timestamp.now(); test("Consumer aborts a group below the previous group start", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 30_000 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(30_000) }, + }); - writeGroupWithLegacyFrames(track, 0n, [10_000_000 as Micro], wallClock); - writeGroupWithLegacyFrames(track, 1n, [0 as Micro, 100_000 as Micro], wallClock); + writeGroupWithLegacyFrames(track, 0n, [10_000_000], wallClock); + writeGroupWithLegacyFrames(track, 1n, [0, 100_000], wallClock); await flush(); - expect((await nextFrame(consumer))?.frame?.timestamp).toBe(10_000_000 as Micro); + expect((await nextFrame(consumer))?.frame?.timestamp.asMicros()).toBe(10_000_000); await expect(nextFrame(consumer)).rejects.toThrow("below the previous group start"); consumer.close(); @@ -1159,18 +1215,21 @@ test("Consumer aborts a group below the previous group start", async () => { // A later group's rewind does not mask an earlier group's decode error. test("Consumer throws the first error in delivery order", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 30_000 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(30_000) }, + }); - writeGroupWithLegacyFrames(track, 0n, [10_000_000 as Micro], wallClock); + writeGroupWithLegacyFrames(track, 0n, [10_000_000], wallClock); const malformed = track.createGroup(1n); // A truncated timestamp varint. malformed.writeFrame({ payload: new Uint8Array([0x80]), timestamp: wallClock() }); malformed.finish(); - writeGroupWithLegacyFrames(track, 2n, [0 as Micro, 100_000 as Micro], wallClock); + writeGroupWithLegacyFrames(track, 2n, [0, 100_000], wallClock); track.finish(); track.close(); - expect((await nextFrame(consumer))?.frame?.timestamp).toBe(10_000_000 as Micro); + expect((await nextFrame(consumer))?.frame?.timestamp.asMicros()).toBe(10_000_000); await expect(nextFrame(consumer)).rejects.toThrow("buffer too short"); consumer.close(); }); @@ -1187,7 +1246,11 @@ test("Consumer checks a whole decoded batch before a skip drops its group", asyn decode(frame: Uint8Array): Frame[] { const timestamps = JSON.parse(new TextDecoder().decode(frame)) as number[]; for (const timestamp of timestamps) decoded.get(timestamp)?.(); - return timestamps.map((timestamp) => ({ payload: frame, timestamp: timestamp as Micro, keyframe: true })); + return timestamps.map((timestamp) => ({ + payload: frame, + timestamp: Duration.micros(timestamp), + keyframe: true, + })); }, }; const write = (sequence: bigint, timestamps: number[]) => { @@ -1201,10 +1264,10 @@ test("Consumer checks a whole decoded batch before a skip drops its group", asyn }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: batchFormat, delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: batchFormat, delay: { max: Duration.millis(500) } }); write(0n, [1_000_000]).finish(); - expect((await nextFrame(consumer))?.frame?.timestamp).toBe(1_000_000 as Micro); + expect((await nextFrame(consumer))?.frame?.timestamp.asMicros()).toBe(1_000_000); // Its first sample is fine; the second rewinds below the delivered group's start. write(2n, [2_000_000, 0]).finish(); @@ -1226,15 +1289,18 @@ test("Consumer checks a whole decoded batch before a skip drops its group", asyn test("Consumer aborts a rewind carried by a later arrival", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 30_000 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(30_000) }, + }); - writeGroupWithLegacyFrames(track, 0n, [10_000_000 as Micro], wallClock); + writeGroupWithLegacyFrames(track, 0n, [10_000_000], wallClock); await flush(); - expect((await nextFrame(consumer))?.frame?.timestamp).toBe(10_000_000 as Micro); + expect((await nextFrame(consumer))?.frame?.timestamp.asMicros()).toBe(10_000_000); const pending = nextFrame(consumer); await flush(); - writeGroupWithLegacyFrames(track, 1n, [0 as Micro, 100_000 as Micro], wallClock); + writeGroupWithLegacyFrames(track, 1n, [0, 100_000], wallClock); await expect(pending).rejects.toThrow("below the previous group start"); @@ -1245,20 +1311,23 @@ test("Consumer aborts a rewind carried by a later arrival", async () => { // rewind, so the detector compares against the previous group's start. test("Consumer treats B-frame reordering within a group as continuous", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 30_000 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(30_000) }, + }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro, 66_000 as Micro, 33_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0, 66_000, 33_000]); await flush(); for (const timestamp of [0, 66_000, 33_000]) { - expect(frameOf(await consumer.next()).timestamp).toBe(timestamp as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(timestamp); } // The cursor is now on group 1, whose own frames reorder the same way. - writeGroupWithLegacyFrames(track, 1n, [100_000 as Micro, 166_000 as Micro, 133_000 as Micro]); + writeGroupWithLegacyFrames(track, 1n, [100_000, 166_000, 133_000]); await flush(); for (const timestamp of [100_000, 166_000, 133_000]) { // Read directly: a gap here would fail the frame check. - expect(frameOf(await consumer.next()).timestamp).toBe(timestamp as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(timestamp); } consumer.close(); @@ -1266,13 +1335,16 @@ test("Consumer treats B-frame reordering within a group as continuous", async () test("Consumer accepts open-GOP leading pictures above the previous group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 30_000 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(30_000) }, + }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro, 33_000 as Micro]); - writeGroupWithLegacyFrames(track, 1n, [66_000 as Micro, 50_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); + writeGroupWithLegacyFrames(track, 1n, [66_000, 50_000]); await flush(); for (const timestamp of [0, 33_000, 66_000, 50_000]) { - expect(frameOf(await consumer.next()).timestamp).toBe(timestamp as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(timestamp); } consumer.close(); @@ -1282,18 +1354,21 @@ test("Consumer accepts open-GOP leading pictures above the previous group", asyn // the max delay loses nothing. test("Consumer reads no gap when retiring a fully delivered group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 150 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(150) }, + }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(0); - writeGroupWithLegacyFrames(track, 1n, [100_000 as Micro]); - writeGroupWithLegacyFrames(track, 2n, [200_000 as Micro]); + writeGroupWithLegacyFrames(track, 1n, [100_000]); + writeGroupWithLegacyFrames(track, 2n, [200_000]); await flush(); // Read directly: a gap here would fail the frame check. - expect(frameOf(await consumer.next()).timestamp).toBe(100_000 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(100_000); consumer.close(); }); @@ -1301,23 +1376,26 @@ test("Consumer reads no gap when retiring a fully delivered group", async () => // An unread trailing endpoint carries no media, so retiring its group loses nothing. test("Consumer reads no gap when retiring a group holding only its endpoint", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("video"), delay: { max: 150 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("video"), + delay: { max: Duration.millis(150) }, + }); const group = track.createGroup(0n); - group.writeFrame({ payload: encodeLegacy(0 as Micro), timestamp: Time.Timestamp.fromMicros(0) }); + group.writeFrame({ payload: encodeLegacy(0), timestamp: Time.Timestamp.fromMicros(0) }); group.writeFrame({ - payload: encodeLegacyFrame(33_000 as Micro, new Uint8Array()), + payload: encodeLegacyFrame(33_000, new Uint8Array()), timestamp: Time.Timestamp.fromMicros(33_000), }); group.finish(); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(0); - writeGroupWithLegacyFrames(track, 1n, [100_000 as Micro]); - writeGroupWithLegacyFrames(track, 2n, [200_000 as Micro]); + writeGroupWithLegacyFrames(track, 1n, [100_000]); + writeGroupWithLegacyFrames(track, 2n, [200_000]); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(100_000 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(100_000); consumer.close(); }); @@ -1326,21 +1404,28 @@ test("Consumer reads no gap when retiring a group holding only its endpoint", as // next group is adjacent. test("Consumer reads a gap when retiring a truncated group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 150 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(150) }, + }); const group = track.createGroup(0n); - group.writeFrame({ payload: encodeLegacy(0 as Micro), timestamp: Time.Timestamp.fromMicros(0) }); + group.writeFrame({ payload: encodeLegacy(0), timestamp: Time.Timestamp.fromMicros(0) }); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(0); group.abort(new NetError.Stream(StreamCode.Cancel)); - writeGroupWithLegacyFrames(track, 1n, [100_000 as Micro]); - writeGroupWithLegacyFrames(track, 2n, [200_000 as Micro]); + writeGroupWithLegacyFrames(track, 1n, [100_000]); + writeGroupWithLegacyFrames(track, 2n, [200_000]); await flush(); // Legacy carries no duration, so the gap starts at the last frame read. - expect(await consumer.next()).toEqual({ kind: "gap", timestamp: 0 as Micro, duration: 100_000 as Micro }); - expect(frameOf(await consumer.next()).timestamp).toBe(100_000 as Micro); + expect(await consumer.next()).toEqual({ + kind: "gap", + timestamp: Duration.micros(0), + duration: Duration.micros(100_000), + }); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(100_000); consumer.close(); }); @@ -1348,21 +1433,28 @@ test("Consumer reads a gap when retiring a truncated group", async () => { // An open group may still have a tail in flight, so adjacency proves nothing when it is retired. test("Consumer reads a gap when retiring an open group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 150 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(150) }, + }); const group = track.createGroup(0n); - group.writeFrame({ payload: encodeLegacy(0 as Micro), timestamp: Time.Timestamp.fromMicros(0) }); + group.writeFrame({ payload: encodeLegacy(0), timestamp: Time.Timestamp.fromMicros(0) }); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(0); // Group 1 starts a whole budget behind the newest content, so the open group is retired. - writeGroupWithLegacyFrames(track, 1n, [100_000 as Micro]); - writeGroupWithLegacyFrames(track, 2n, [250_000 as Micro]); + writeGroupWithLegacyFrames(track, 1n, [100_000]); + writeGroupWithLegacyFrames(track, 2n, [250_000]); await flush(); // Legacy carries no duration, so the gap starts at the last frame read. - expect(await consumer.next()).toEqual({ kind: "gap", timestamp: 0 as Micro, duration: 100_000 as Micro }); - expect(frameOf(await consumer.next()).timestamp).toBe(100_000 as Micro); + expect(await consumer.next()).toEqual({ + kind: "gap", + timestamp: Duration.micros(0), + duration: Duration.micros(100_000), + }); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(100_000); group.finish(); consumer.close(); @@ -1372,19 +1464,22 @@ test("Consumer reads a gap when retiring an open group", async () => { test("Consumer buffered signal updates as frames arrive", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(500) }, + }); expect(consumer.buffered.peek()).toEqual([]); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro, 33_000 as Micro]); - writeGroupWithLegacyFrames(track, 1n, [66_000 as Micro, 99_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); + writeGroupWithLegacyFrames(track, 1n, [66_000, 99_000]); await flush(); const ranges = consumer.buffered.peek(); expect(ranges.length).toBe(1); - expect(ranges[0].start).toBe(0 as Milli); - expect((ranges[0].end as number) >= 66).toBeTruthy(); + expect(ranges[0].start).toEqual(Duration.millis(0)); + expect(ranges[0].end.asMillis()).toBeGreaterThanOrEqual(66); track.finish(); track.close(); @@ -1395,14 +1490,17 @@ test("Consumer buffered signal updates as frames arrive", async () => { test("Consumer recovers from gap in group sequence numbers", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 100 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(100) }, + }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro, 20_000 as Micro]); - writeGroupWithLegacyFrames(track, 1n, [40_000 as Micro, 60_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0, 20_000]); + writeGroupWithLegacyFrames(track, 1n, [40_000, 60_000]); // Skip group 2 - writeGroupWithLegacyFrames(track, 3n, [120_000 as Micro, 140_000 as Micro]); - writeGroupWithLegacyFrames(track, 4n, [160_000 as Micro, 180_000 as Micro]); - writeGroupWithLegacyFrames(track, 5n, [200_000 as Micro, 220_000 as Micro]); + writeGroupWithLegacyFrames(track, 3n, [120_000, 140_000]); + writeGroupWithLegacyFrames(track, 4n, [160_000, 180_000]); + writeGroupWithLegacyFrames(track, 5n, [200_000, 220_000]); track.finish(); track.close(); @@ -1421,12 +1519,12 @@ test("Consumer handles empty decode result without deadlock", async () => { decode(_frame: Uint8Array): Frame[] { callCount++; if (callCount === 1) return []; // empty result - return [{ payload: new Uint8Array([1]), timestamp: 33_000 as Micro, keyframe: false }]; + return [{ payload: new Uint8Array([1]), timestamp: Duration.micros(33_000), keyframe: false }]; }, }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: emptyThenValid, delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: emptyThenValid, delay: { max: Duration.millis(500) } }); const group = track.createGroup(0n); group.writeFrame({ payload: new Uint8Array([0x01]), timestamp: Time.Timestamp.now() }); // empty decode @@ -1448,11 +1546,11 @@ test("Consumer handles empty decode result without deadlock", async () => { test("Consumer preserves empty media from formats without endpoint markers", async () => { const format: ContainerFormat = { decode(): Frame[] { - return [{ payload: new Uint8Array(), timestamp: 0 as Micro, keyframe: false }]; + return [{ payload: new Uint8Array(), timestamp: Duration.micros(0), keyframe: false }]; }, }; const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe(), { format, delay: { max: 500 as Milli } }); + const consumer = new Consumer(track.subscribe(), { format, delay: { max: Duration.millis(500) } }); const group = track.createGroup(0n); group.writeFrame({ payload: new Uint8Array([1]), timestamp: Time.Timestamp.now() }); group.finish(); @@ -1469,7 +1567,7 @@ test("Consumer with CmafFormat delivers correct timestamps", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new CmafFormat(TEST_INIT), - delay: { max: 500 as Milli }, + delay: { max: Duration.millis(500) }, }); const group = track.createGroup(0n); @@ -1489,8 +1587,8 @@ test("Consumer with CmafFormat delivers correct timestamps", async () => { expect(frames).toHaveLength(2); expect(frames[0].keyframe).toBe(true); // index 0 override expect(frames[1].keyframe).toBe(false); // trusts format - expect(frames[0].timestamp).toBe(0 as Micro); - expect(frames[1].timestamp).toBe(33_333 as Micro); // 3000/90000 * 1_000_000 + expect(frames[0].timestamp).toBe(0); + expect(frames[1].timestamp).toBe(33_333); // 3000/90000 * 1_000_000 consumer.close(); }); @@ -1498,7 +1596,7 @@ test("Consumer with CmafFormat times an untimed track from tfdt", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new CmafFormat(TEST_INIT), - delay: { max: 500 as Milli }, + delay: { max: Duration.millis(500) }, }); const group = track.createGroup(0n); @@ -1509,7 +1607,7 @@ test("Consumer with CmafFormat times an untimed track from tfdt", async () => { track.close(); const frames = await drainFrames(consumer); - expect(frames.map((f) => f.timestamp)).toEqual([1_000_000, 1_033_333] as Micro[]); + expect(frames.map((f) => f.timestamp)).toEqual([1_000_000, 1_033_333]); consumer.close(); }); @@ -1519,7 +1617,7 @@ test("CmafFormat decodes the per-sample duration", () => { const [frame] = format.decode(segment, at(0)); // 3000 ticks / 90000 timescale * 1_000_000 = 33333µs - expect(frame.duration).toBe(33_333 as Micro); + expect(frame.duration?.asMicros()).toBe(33_333); }); // --- Duration skipping --- @@ -1530,8 +1628,8 @@ const durationFormat: ContainerFormat = { return [ { payload: frame, - timestamp: (frame[0] * 1000) as Micro, - duration: 33_000 as Micro, + timestamp: Duration.micros(frame[0] * 1000), + duration: Duration.micros(33_000), keyframe: false, }, ]; @@ -1541,7 +1639,7 @@ const durationFormat: ContainerFormat = { test("Consumer duration-skips a stalled group once it is covered", async () => { const track = new Track.Producer("test"); // Latency dwarfs the gap, so only duration coverage can trigger the skip. - const consumer = new Consumer(replay(track), { format: durationFormat, delay: { max: 10_000 as Milli } }); + const consumer = new Consumer(replay(track), { format: durationFormat, delay: { max: Duration.millis(10_000) } }); // Group.Producer 0: one frame at ts=0 lasting 33ms, never closed (stalled). const g0 = track.createGroup(0n); @@ -1568,8 +1666,8 @@ test("Consumer does not duration-skip when the gap is not covered", async () => return [ { payload: frame, - timestamp: (frame[0] * 1000) as Micro, - duration: 10_000 as Micro, + timestamp: Duration.micros(frame[0] * 1000), + duration: Duration.micros(10_000), keyframe: false, }, ]; @@ -1577,7 +1675,7 @@ test("Consumer does not duration-skip when the gap is not covered", async () => }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: shortFormat, delay: { max: 10_000 as Milli } }); + const consumer = new Consumer(replay(track), { format: shortFormat, delay: { max: Duration.millis(10_000) } }); // Group.Producer 0 stays open and later receives a second frame; nothing covers the gap, // so that late frame must survive rather than being skipped. @@ -1610,13 +1708,13 @@ test("Consumer delivers a PTS-contiguous next group whose sequence jumped (Legac const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: timedLegacy, - delay: { max: 500 as Milli }, + delay: { max: Duration.millis(500) }, }); // Group A (seq 1_000_000): one 3000-tick sample, so its content ends at 33_333µs (3000/90000 * 1e6). const a = track.createGroup(1_000_000n); a.writeFrame({ - payload: encodeLegacyFrame(Math.round((0 / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([0x01])), + payload: encodeLegacyFrame(Math.round((0 / TIMESCALE) * 1_000_000) as number, new Uint8Array([0x01])), timestamp: at(0), }); a.finish(); @@ -1631,7 +1729,7 @@ test("Consumer delivers a PTS-contiguous next group whose sequence jumped (Legac // tolerance, so the timeline is unbroken and B must deliver immediately even while still open. const b = track.createGroup(1_090_000n); b.writeFrame({ - payload: encodeLegacyFrame(Math.round((3045 / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([0x02])), + payload: encodeLegacyFrame(Math.round((3045 / TIMESCALE) * 1_000_000) as number, new Uint8Array([0x02])), timestamp: at(3045), }); @@ -1649,13 +1747,13 @@ test("Consumer waits on a PTS gap instead of skipping to a later buffered group const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: timedLegacy, - delay: { max: 10_000 as Milli }, + delay: { max: Duration.millis(10_000) }, }); // Group A (seq 1_000_000): content ends at 33_333µs. const a = track.createGroup(1_000_000n); a.writeFrame({ - payload: encodeLegacyFrame(Math.round((0 / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([0x01])), + payload: encodeLegacyFrame(Math.round((0 / TIMESCALE) * 1_000_000) as number, new Uint8Array([0x01])), timestamp: at(0), }); a.finish(); @@ -1668,19 +1766,19 @@ test("Consumer waits on a PTS gap instead of skipping to a later buffered group // gap. An intermediate group may still be in transit, so C must NOT be delivered yet. const c = track.createGroup(1_090_000n); c.writeFrame({ - payload: encodeLegacyFrame(Math.round((90_000 / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([0x03])), + payload: encodeLegacyFrame(Math.round((90_000 / TIMESCALE) * 1_000_000) as number, new Uint8Array([0x03])), timestamp: at(90_000), }); // Held until the max delay runs out: the gap is not eagerly skipped. - await clock.advance(Nano.fromMilli(Milli(9_999))); + await clock.advance(Duration.millis(9_999)); expect(await poll(pending)).toBe("pending"); // The missing group B arrives, contiguous with A (first PTS 3000 ticks = 33_333µs = A.end); it // continues the timeline, so delivery resumes with B's frame. const b = track.createGroup(1_045_000n); b.writeFrame({ - payload: encodeLegacyFrame(Math.round((3000 / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([0x02])), + payload: encodeLegacyFrame(Math.round((3000 / TIMESCALE) * 1_000_000) as number, new Uint8Array([0x02])), timestamp: at(3000), }); @@ -1698,7 +1796,7 @@ test("Consumer delivers a contiguous group after one that completed out of order const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: timedLegacy, - delay: { max: 10_000 as Milli }, + delay: { max: Duration.millis(10_000) }, }); // A (seq 1_000_000) stays open so it remains the active group. @@ -1741,7 +1839,7 @@ test("Consumer plays the head once a waited-out gap exceeds the budget (Legacy)" const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: timedLegacy, - delay: { max: 100 as Milli }, + delay: { max: Duration.millis(100) }, }); // A (seq 1000): one frame, ends at 3000 ticks (33_333µs). @@ -1765,7 +1863,7 @@ test("Consumer plays the head once a waited-out gap exceeds the budget (Legacy)" // The missing group's span was never delivered, so a gap from A's end to B comes first. const result = await poll(pending); - expect(result).toEqual({ kind: "gap", timestamp: 33_333 as Micro, duration: 966_667 as Micro }); + expect(result).toEqual({ kind: "gap", timestamp: Duration.micros(33_333), duration: Duration.micros(966_667) }); expect(frameOf(await consumer.next()).payload).toEqual(new Uint8Array([0x02])); consumer.close(); @@ -1776,7 +1874,7 @@ test("Consumer waits on a gap within the budget, then plays the head once it exc const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: timedLegacy, - delay: { max: 100 as Milli }, + delay: { max: Duration.millis(100) }, }); // A (seq 1000): one frame, ends at 3000 ticks (33_333µs). @@ -1791,7 +1889,7 @@ test("Consumer waits on a gap within the budget, then plays the head once it exc // Waited out until just short of the budget. const pending = consumer.next(); - await clock.advance(Nano.fromMilli(Milli(99))); + await clock.advance(Duration.millis(99)); expect(await poll(pending)).toBe("pending"); // B alone grows past the budget (up to 12_000 ticks, 100ms past A's end and beyond). @@ -1801,7 +1899,7 @@ test("Consumer waits on a gap within the budget, then plays the head once it exc } const result = await poll(pending); - expect(result).toEqual({ kind: "gap", timestamp: 33_333 as Micro, duration: 33_334 as Micro }); + expect(result).toEqual({ kind: "gap", timestamp: Duration.micros(33_333), duration: Duration.micros(33_334) }); expect(frameOf(await consumer.next()).payload).toEqual(new Uint8Array([0x02])); consumer.close(); @@ -1814,111 +1912,137 @@ test("Consumer waits on a gap within the budget, then plays the head once it exc // adjacency doesn't rule out a group the max delay check dropped on the way past. test("Consumer yields no gap while nothing is dropped", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 100 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(100) }, + }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro, 33_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); - expect(frameOf(await consumer.next()).timestamp).toBe(33_000 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(0); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(33_000); - writeGroupWithLegacyFrames(track, 1n, [66_000 as Micro]); + writeGroupWithLegacyFrames(track, 1n, [66_000]); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(66_000 as Micro); // group 1 continues group 0 + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(66_000); // group 1 continues group 0 consumer.close(); }); test("Consumer reads a marker group as an end, not a gap", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 2_000 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(2_000) }, + }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); - writeMarkerGroup(track, 1n, 0 as Micro); - writeGroupWithLegacyFrames(track, 2n, [1_000_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); + writeMarkerGroup(track, 1n, 0); + writeGroupWithLegacyFrames(track, 2n, [1_000_000]); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); - expect(await consumer.next()).toEqual({ kind: "end", group: 1n, end: 0 as Micro }); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(0); + expect(await consumer.next()).toEqual({ kind: "end", group: 1n, end: Duration.micros(0) }); // A declared stop loses nothing, so no gap follows it. - expect(frameOf(await consumer.next()).timestamp).toBe(1_000_000 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(1_000_000); consumer.close(); }); test("Consumer empty groups mean nothing", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 2_000 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(2_000) }, + }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); const empty = track.createGroup(1n); empty.finish(); - writeGroupWithLegacyFrames(track, 2n, [1_000 as Micro]); + writeGroupWithLegacyFrames(track, 2n, [1_000]); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); - expect(frameOf(await consumer.next()).timestamp).toBe(1_000 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(0); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(1_000); consumer.close(); }); test("Consumer reads a latency skip as one gap", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 0 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(0) }, + }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); await flush(); - expect((await nextFrame(consumer))?.frame?.timestamp).toBe(0 as Micro); + expect((await nextFrame(consumer))?.frame?.timestamp.asMicros()).toBe(0); - writeGroupWithLegacyFrames(track, 2n, [100_000 as Micro]); + writeGroupWithLegacyFrames(track, 2n, [100_000]); await flush(); - expect(await consumer.next()).toEqual({ kind: "gap", timestamp: 0 as Micro, duration: 100_000 as Micro }); - expect(frameOf(await consumer.next()).timestamp).toBe(100_000 as Micro); + expect(await consumer.next()).toEqual({ + kind: "gap", + timestamp: Duration.micros(0), + duration: Duration.micros(100_000), + }); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(100_000); consumer.close(); }); test("Consumer reads a timestamp hole as a gap", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 0 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(0) }, + }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); await flush(); - expect((await nextFrame(consumer))?.frame?.timestamp).toBe(0 as Micro); + expect((await nextFrame(consumer))?.frame?.timestamp.asMicros()).toBe(0); - writeGroupWithLegacyFrames(track, 3n, [1_000_000 as Micro]); + writeGroupWithLegacyFrames(track, 3n, [1_000_000]); await flush(); expect(await consumer.next()).toEqual({ kind: "gap", - timestamp: 0 as Micro, - duration: 1_000_000 as Micro, + timestamp: Duration.ZERO, + duration: Duration.micros(1_000_000), }); - expect(frameOf(await consumer.next()).timestamp).toBe(1_000_000 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(1_000_000); consumer.close(); }); test("Consumer reads a shed marker group as a gap", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 0 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(0) }, + }); const group0 = track.createGroup(0n); group0.writeFrame({ - payload: encodeLegacy(0 as Micro), + payload: encodeLegacy(0), timestamp: Time.Timestamp.fromMicros(0), }); await flush(); - expect((await nextFrame(consumer))?.frame?.timestamp).toBe(0 as Micro); + expect((await nextFrame(consumer))?.frame?.timestamp.asMicros()).toBe(0); - writeMarkerGroup(track, 1n, 0 as Micro); - writeGroupWithLegacyFrames(track, 2n, [500 as Micro]); + writeMarkerGroup(track, 1n, 0); + writeGroupWithLegacyFrames(track, 2n, [500]); await flush(); // The zero budget sheds the marker unread, and what it declared is lost with it. - expect(await consumer.next()).toEqual({ kind: "gap", timestamp: 0 as Micro, duration: 500 as Micro }); - expect(frameOf(await consumer.next()).timestamp).toBe(500 as Micro); + expect(await consumer.next()).toEqual({ + kind: "gap", + timestamp: Duration.micros(0), + duration: Duration.micros(500), + }); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(500); group0.finish(); consumer.close(); @@ -1929,7 +2053,7 @@ test("Consumer yields no gap across a PTS-contiguous group id jump (Legacy)", as const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: timedLegacy, - delay: { max: 10_000 as Milli }, + delay: { max: Duration.millis(10_000) }, }); const a = track.createGroup(1_000_000n); @@ -1951,11 +2075,11 @@ test("a live video frame is delivered before its duration marker arrives", async const track = new Track.Producer("test"); const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("video"), - delay: { max: 500 as Milli }, + delay: { max: Duration.millis(500) }, }); const group = track.appendGroup(); group.writeFrame({ - payload: encodeLegacyFrame(0 as Micro, new Uint8Array([1])), + payload: encodeLegacyFrame(0, new Uint8Array([1])), timestamp: Time.Timestamp.now(), }); let delivered = false; @@ -1965,9 +2089,9 @@ test("a live video frame is delivered before its duration marker arrives", async }); await flush(); expect(delivered).toBe(true); - expect(frameOf(await read).timestamp).toBe(0 as Micro); + expect(frameOf(await read).timestamp.asMicros()).toBe(0); group.writeFrame({ - payload: encodeLegacyFrame(15_000 as Micro, new Uint8Array()), + payload: encodeLegacyFrame(15_000, new Uint8Array()), timestamp: Time.Timestamp.now(), }); group.finish(); @@ -1984,8 +2108,8 @@ test("audio discontinuity writes no duration marker", async () => { const track = new Track.Producer("test"); const subscriber = track.subscribe(); const producer = new LegacyProducer(track, new LegacyFormat("audio")); - producer.encode(new Uint8Array([1]), 0 as Micro, true); - producer.discontinuity(15_000 as Micro); + producer.encode(new Uint8Array([1]), Duration.micros(0), true); + producer.discontinuity(Duration.micros(15_000)); const group = await subscriber.recvGroup(); expect(await group?.readFrame()).toBeDefined(); expect(await group?.readFrame()).toBeUndefined(); @@ -1995,12 +2119,15 @@ test("audio discontinuity writes no duration marker", async () => { for (const code of [StreamCode.Cancel, StreamCode.Internal, StreamCode.Old, StreamCode.Evicted, StreamCode(1234)]) { test(`Consumer preserves frames and continues after group reset ${code}`, async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 0 as Milli } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(0) }, + }); const error = spyOn(console, "error").mockImplementation(() => {}); try { const group = track.appendGroup(); group.writeFrame({ - payload: encodeLegacyFrame(0 as Micro, new Uint8Array([1])), + payload: encodeLegacyFrame(0, new Uint8Array([1])), timestamp: Time.Timestamp.now(), }); await flush(); @@ -2009,15 +2136,15 @@ for (const code of [StreamCode.Cancel, StreamCode.Internal, StreamCode.Old, Stre expect(frameOf(await nextFrame(consumer)).payload).toEqual(new Uint8Array([1])); const next = track.appendGroup(); next.writeFrame({ - payload: encodeLegacyFrame(1 as Micro, new Uint8Array([2])), + payload: encodeLegacyFrame(1, new Uint8Array([2])), timestamp: Time.Timestamp.now(), }); next.finish(); // The reset cut the group's tail. expect(await consumer.next()).toEqual({ kind: "gap", - timestamp: 0 as Micro, - duration: 1 as Micro, + timestamp: Duration.ZERO, + duration: Duration.micros(1), }); const resumed = frameOf(await consumer.next()); expect(resumed.payload).toEqual(new Uint8Array([2])); @@ -2087,12 +2214,12 @@ for (const end of [ const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), - delay: { max: 10_000 as Milli }, + delay: { max: Duration.millis(10_000) }, }); try { - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); expect(await nextFrame(consumer)).toMatchObject({ group: 0n }); - writeGroupWithLegacyFrames(track, 2n, [1_000_000 as Micro]); + writeGroupWithLegacyFrames(track, 2n, [1_000_000]); await flush(); const pending = consumer.next(); if (end) track.abort(end); @@ -2103,8 +2230,16 @@ for (const end of [ const resumed = await poll(pending); expect(resumed).not.toBe("pending"); if (resumed === "pending") return; - expect(resumed).toEqual({ kind: "gap", timestamp: 0 as Micro, duration: 1_000_000 as Micro }); - expect(await consumer.next()).toMatchObject({ kind: "frame", group: 2n, frame: { timestamp: 1_000_000 } }); + expect(resumed).toEqual({ + kind: "gap", + timestamp: Duration.micros(0), + duration: Duration.micros(1_000_000), + }); + expect(await consumer.next()).toMatchObject({ + kind: "frame", + group: 2n, + frame: { timestamp: Duration.micros(1_000_000) }, + }); if (end) await expect(consumer.next()).rejects.toBe(end); else expect(await consumer.next()).toBeUndefined(); } finally { diff --git a/js/hang/src/container/consumer.ts b/js/hang/src/container/consumer.ts index dcb4913d254..245273eff7a 100644 --- a/js/hang/src/container/consumer.ts +++ b/js/hang/src/container/consumer.ts @@ -1,4 +1,4 @@ -import { Instant, Micro, Milli, Nano, now } from "@moq/clock"; +import { Duration, Instant, now } from "@moq/clock"; import type * as Moq from "@moq/net"; import { Effect, type Getter, type GetterInit, getter, Once, Signal } from "@moq/signals"; import type { Format } from "./format"; @@ -58,7 +58,7 @@ export interface ConsumerProps { * covers the reach and tolerates the warmup, so the media leading up to the start is not dropped * as stale. After that, the max delay alone governs it. */ - warmup?: Milli; + warmup?: Duration; /** * The consumer this one replaces on the same path, such as the previous rendition. * @@ -81,13 +81,13 @@ export type Read = * per-frame duration that is the last frame's timestamp, one frame early. `duration` runs to * where the next item resumes, so it also covers any declared pause in between. */ - | { kind: "gap"; timestamp: Micro; duration: Micro } + | { kind: "gap"; timestamp: Duration; duration: Duration } /** * The publisher declared that its media stops at `end`: it paused, switched source, or finished. * Frames that follow from the same `group` are the stopped encoder's final packets (an audio * codec's drain), whose output at or past `end` is padding. The next group starts fresh. */ - | { kind: "end"; group: bigint; end: Micro }; + | { kind: "end"; group: bigint; end: Duration }; // The default max buffer: one group at the transport's size cap. Mirrors Rust's. const DEFAULT_MAX_BUFFER = 32 * 1024 * 1024; @@ -107,10 +107,11 @@ interface Group { empty: boolean; // no wire frame was published; empty groups mean nothing media: boolean; // a decodable (non-marker) frame was buffered bare?: boolean; // a data track's marker group: one object with no bytes - start?: Micro; // First decoded timestamp - minMedia?: Micro; // Lowest decodable timestamp - latest?: Micro; // The timestamp of the latest known frame - end?: Micro; // The furthest presentation point so far, i.e. max(timestamp + duration) + // Timestamps in microseconds, kept as numbers since every frame updates them. + start?: number; // First decoded timestamp + minMedia?: number; // Lowest decodable timestamp + latest?: number; // The timestamp of the latest known frame + end?: number; // The furthest presentation point so far, i.e. max(timestamp + duration) fault?: Error; // The payload that failed to decode, an error after the buffered frames are delivered. index: number; // Media frames decoded so far: the first is a keyframe by protocol invariant charged: number; // What this group holds against the max buffer @@ -128,7 +129,7 @@ interface Spans { // to microseconds independently, so a genuinely contiguous boundary can be off by ~1µs (seen on 48kHz // audio). A real missing group spans ~one group duration (orders of magnitude larger), so 1ms cleanly // separates rounding noise from an actual gap. -const CONTIGUITY_TOLERANCE = Micro.fromMilli(1 as Milli); +const CONTIGUITY_TOLERANCE = 1000; /** * True when `nextStart` continues the timeline that ends at `end`: it lands at or before `end`, @@ -139,7 +140,7 @@ const CONTIGUITY_TOLERANCE = Micro.fromMilli(1 as Milli); * timeline, a start past `end` beyond the tolerance is a gap. Group starts are validated * separately; an overlapping endpoint is not a rewind. */ -function ptsContiguous(end: Micro | undefined, nextStart: Micro | undefined): boolean { +function ptsContiguous(end: number | undefined, nextStart: number | undefined): boolean { return end !== undefined && nextStart !== undefined && nextStart <= end + CONTIGUITY_TOLERANCE; } @@ -152,13 +153,14 @@ function ptsContiguous(end: Micro | undefined, nextStart: Micro | undefined): bo function continues(prev: Group, next: Group | undefined): next is Group { if (next === undefined) return false; return ( - next.consumer.sequence === prev.consumer.sequence + 1n || ptsContiguous(prev.end, next.frames.at(0)?.timestamp) + next.consumer.sequence === prev.consumer.sequence + 1n || + ptsContiguous(prev.end, next.frames.at(0)?.timestamp.asMicros()) ); } // The max delay in microseconds, infinite when unlimited. function maxMicros(delay: Moq.Track.Delay): number { - return delay.max === null ? Number.POSITIVE_INFINITY : Micro.fromMilli(delay.max ?? Milli.zero); + return delay.max === null ? Number.POSITIVE_INFINITY : (delay.max?.asMicros() ?? 0); } /** @@ -173,7 +175,7 @@ export class Consumer { #delay: Getter; #maxBuffer: number; // How much further than the min delay the start reaches, and the age skip tolerates while warming. - #warmup: Milli; + #warmup: Duration; // The start may still wait for a group covering the reach, until that wait ends for good. #starting = true; // When the newest group had landed as the first one arrived, once the start waits. @@ -182,7 +184,7 @@ export class Consumer { #target?: number; // Where the warming ends: the warmup past the first frame read, or past the start's target when // that is later. Undefined before the first frame. - #warmed?: Micro; + #warmed?: number; // What the buffered groups hold, against the max buffer. #used = 0; // Group watchers and the track loop parked on a full max buffer. @@ -197,7 +199,7 @@ export class Consumer { // Presentation end (max PTS + duration) of the group we most recently advanced past, so next()'s // promotion guard can tell a timeline-continuous next group from one sitting after a gap. // Written only by #pass, which every move past a group goes through. - #presentedEnd?: Micro; + #presentedEnd?: number; // Group of the last media frame next() returned, so an endpoint after it reads as that frame's // duration rather than a declared stop. #mediaGroup?: bigint; @@ -205,13 +207,13 @@ export class Consumer { #lost = false; // The furthest presentation point read so far: max(timestamp + duration), endpoints included. // Undefined until the first item, so a loss before it is no gap. - #edge?: Micro; + #edge?: number; // The item a gap was returned ahead of. #next?: Read; // The first media timestamp of the latest delivered group, and its predecessor's start. // Endpoints and later frames can overlap the next group without moving this floor. - #start?: { group: bigint; timestamp: Micro }; - #floor?: Micro; + #start?: { group: bigint; timestamp: number }; + #floor?: number; // The error that ended the reader, the first in delivery order: a decode failure or a rewind. #error?: Error; @@ -223,14 +225,14 @@ export class Consumer { readonly buffered: Getter = this.#buffered; #jitter: Jitter; - #spread: Signal; + #spread: Signal; /** * How much buffer late arrivals need, measured as frames come off the transport. * * The measured term of doc/concept/audio-jitter.md, excluding the codec frame and any advertised * floor. Starts at the predecessor's estimate, or the cold-start estimate without one. */ - readonly spread: Getter; + readonly spread: Getter; // The newest group opened by a declared end, until a later group's first frame tells the jitter // estimator the silence is over. Not at the marker itself: the stopped encoder's final packets may // follow it in its own group, and they belong to the speech before the silence. @@ -246,9 +248,9 @@ export class Consumer { this.#format = props.format; this.#delay = getter(props.delay ?? {}); this.#maxBuffer = props.maxBuffer ?? DEFAULT_MAX_BUFFER; - this.#warmup = props.warmup ?? Milli.zero; + this.#warmup = props.warmup ?? Duration.ZERO; this.#jitter = props.predecessor ? props.predecessor.#jitter.fork() : new Jitter(); - this.#spread = new Signal(this.#jitter.measured); + this.#spread = new Signal(Duration.millis(this.#jitter.measured)); this.spread = this.#spread; this.#signals.spawn(this.#run.bind(this)); @@ -321,8 +323,8 @@ export class Consumer { // Each group is late from the earliest arrival among it and the groups past it. A drained // backlog comes in sequence order, not arrival order, so an arrival can lower those below it. const next = this.#groups.at(index); - if (next && next.late < group.late) group.late = next.late; - for (let i = index - 1; i >= 0 && this.#groups[i].late > group.late; i--) + if (next?.late.lt(group.late)) group.late = next.late; + for (let i = index - 1; i >= 0 && this.#groups[i].late.gt(group.late); i--) this.#groups[i].late = group.late; this.#groups.splice(index, 0, group); // Group overhead alone can fill the max buffer, past which next() moves on from a stalled head. @@ -424,7 +426,8 @@ export class Consumer { group.empty = false; // When the frame landed, not when it was decoded: a frame the max buffer left in the transport // would otherwise count the consumer's own wait as network jitter. - const arrival = Nano.toMilli(Nano(wire.arrived ?? now())); + const arrival = wire.arrived ?? now(); + const arrived = arrival.since(Instant.ZERO).asMillis(); // A malformed payload is not loss: it ends the reader where it sits, rather than truncating the group. let decoded: Frame[]; @@ -459,8 +462,9 @@ export class Consumer { this.#jitter.end(); this.#declared = undefined; } - this.#jitter.observe(arrival, Milli.fromMicro(sample.timestamp)); - this.#spread.set(this.#jitter.measured); + this.#jitter.observe(arrived, sample.timestamp.asMillis()); + const spread = this.#jitter.measured; + if (spread !== this.#spread.peek().asMillis()) this.#spread.set(Duration.millis(spread)); } else if (!group.media) { // Only a marker ahead of any media declares an end; one after it is a frame's endpoint. this.#declare(group); @@ -480,26 +484,27 @@ export class Consumer { duration: sample.duration, }; + const at = frame.timestamp.asMicros(); if (!marker) { group.index++; group.media = true; - if (group.minMedia === undefined || frame.timestamp < group.minMedia) { - group.minMedia = frame.timestamp; + if (group.minMedia === undefined || at < group.minMedia) { + group.minMedia = at; } } - group.start ??= frame.timestamp; + group.start ??= at; group.frames.push(frame); const cost = FRAME_COST + frame.payload.byteLength; group.costs.push(cost); this.#charge(group, cost); views += frame.payload.byteLength; - if (group.latest === undefined || frame.timestamp > group.latest) { - group.latest = frame.timestamp; + if (group.latest === undefined || at > group.latest) { + group.latest = at; } - const end = (frame.timestamp + (frame.duration ?? 0)) as Micro; + const end = at + (frame.duration?.asMicros() ?? 0); if (group.end === undefined || end > group.end) { group.end = end; } @@ -554,7 +559,7 @@ export class Consumer { for (const group of this.#groups) { if (group.latest === undefined) continue; - const frame = group.frames.at(0)?.timestamp ?? group.latest; + const frame = group.frames.at(0)?.timestamp.asMicros() ?? group.latest; if (min === undefined || frame < min) min = frame; if (max === undefined || group.latest > max) max = group.latest; } @@ -599,7 +604,7 @@ export class Consumer { this.#pass(first, this.#groups[0]?.consumer.sequence); const next = this.#groups[0]; - const nextStart = next?.frames.at(0)?.timestamp ?? next?.end; + const nextStart = next?.frames.at(0)?.timestamp.asMicros() ?? next?.end; const marker = !first.empty && !first.media; // Unread media is thrown away, and `first.end` counts it, so contiguity alone would hide it. // A trailing endpoint carries no media, so leaving it unread discards nothing. @@ -640,7 +645,7 @@ export class Consumer { for (let i = count - 1; i >= 0; i--) { const group = this.#groups[i]; if (group.latest !== undefined) { - const frame = group.frames.at(0)?.timestamp ?? group.latest; + const frame = group.frames.at(0)?.timestamp.asMicros() ?? group.latest; if (min === undefined || frame < min) min = frame; if (max === undefined || group.latest > max) max = group.latest; } @@ -662,7 +667,7 @@ export class Consumer { if (this.#ended(active) !== undefined || active.frames.length > 0 || active.end === undefined) return false; const next = this.#groups[1]; - const nextStart = next?.frames.at(0)?.timestamp; + const nextStart = next?.frames.at(0)?.timestamp.asMicros(); if (!next || nextStart === undefined || active.end < nextStart) return false; this.#groups.shift(); @@ -696,7 +701,7 @@ export class Consumer { ); // Still open, so its tail is lost unless the next group picks up where it ended, which nothing // proves before its start is read. A marker group stops the timeline, so moving past one loses it. - const nextStart = next.frames.at(0)?.timestamp; + const nextStart = next.frames.at(0)?.timestamp.asMicros(); const marker = !head.empty && !head.media; if (marker || !ptsContiguous(head.end ?? this.#presentedEnd, nextStart)) this.#lost = true; this.#pass(head, next.consumer.sequence); @@ -850,13 +855,13 @@ export class Consumer { this.#hole = head.late; // Joining at the first arrival leaves no hole to wait for; a floor does. const startup = this.#start === undefined && !this.#floored; - const contiguous = ptsContiguous(this.#presentedEnd, head.frames.at(0)?.timestamp); + const contiguous = ptsContiguous(this.#presentedEnd, head.frames.at(0)?.timestamp.asMicros()); const empty = head.empty && head.consumer.done; const maxDelay = maxMicros(this.#delay.peek()); const bound = this.#groups.find((group) => group.start !== undefined)?.start; const edge = this.#liveEdge(); const aged = bound !== undefined && edge !== undefined && edge - bound >= maxDelay; - const elapsed = Instant.durationSince(now(), this.#hole) >= maxDelay * 1000; + const elapsed = now().since(this.#hole).asMicros() >= maxDelay; // The ranges ask for nothing in between, so nothing there is owed. const next = this.#track.nextInRange(this.#active); const excluded = next === undefined || next >= head.consumer.sequence; @@ -893,7 +898,7 @@ export class Consumer { this.#updateBuffered(); // A trailing endpoint is the last frame's duration: it moves the edge, nothing else. if (seq === this.#mediaGroup) { - this.#advance(end); + this.#advance(end.asMicros()); continue; } return this.#emit({ kind: "end", group: seq, end }); @@ -901,14 +906,13 @@ export class Consumer { this.#mediaGroup = seq; // A group covering the target began before it, so the reader warms until the target too. - this.#warmed ??= Micro( - Math.max(frame.timestamp, this.#target ?? frame.timestamp) + Micro.fromMilli(this.#warmup), - ); + const at = frame.timestamp.asMicros(); + this.#warmed ??= Math.max(at, this.#target ?? at) + this.#warmup.asMicros(); if (this.#start === undefined || seq > this.#start.group) { this.#floor = this.#start?.timestamp; - this.#start = { group: seq, timestamp: frame.timestamp }; + this.#start = { group: seq, timestamp: at }; } - if (this.#floor !== undefined && frame.timestamp < this.#floor) { + if (this.#floor !== undefined && at < this.#floor) { this.#abort(new Error("frame timestamp is below the previous group start")); throw this.#error; } @@ -947,7 +951,7 @@ export class Consumer { // A data track's marker carries no timestamp, so it ends where this reader got to. // Before the first item there is nothing to end. if (head.bare && !truncated && this.#edge !== undefined) { - return this.#emit({ kind: "end", group: seq, end: this.#edge }); + return this.#emit({ kind: "end", group: seq, end: Duration.micros(this.#edge) }); } continue; } @@ -976,8 +980,7 @@ export class Consumer { // The start waits out its reach, and a hole the max delay, which an unlimited one never does. const budget = starting === undefined ? maxMicros(delay) : this.#reach(delay); if (!Number.isFinite(budget)) return; - const elapsed = Instant.durationSince(now(), since); - effect.timer(() => this.#notify?.(), Nano(Math.max(0, budget * 1000 - elapsed))); + effect.timer(() => this.#notify?.(), Duration.micros(budget).saturatingSub(now().since(since))); }); } @@ -999,7 +1002,7 @@ export class Consumer { // How far behind the live edge the start reaches, in microseconds: the min delay plus the warmup. // The publisher serves nothing older than the max delay, so a min delay past it reaches no further. #reach(delay: Moq.Track.Delay): number { - return Math.min(Micro.fromMilli(delay.min ?? Milli.zero), maxMicros(delay)) + Micro.fromMilli(this.#warmup); + return Math.min(delay.min?.asMicros() ?? 0, maxMicros(delay)) + this.#warmup.asMicros(); } // While the start still waits for a group covering the live edge less the min delay and the @@ -1023,7 +1026,7 @@ export class Consumer { // Nothing earlier can arrive or be held. const lowest = this.#groups[0].consumer.sequence === 0n; // Wall time: the newest group landed a whole reach ago. - const elapsed = Instant.durationSince(now(), this.#anchor) >= reach * 1000; + const elapsed = now().since(this.#anchor).asMicros() >= reach; if (ended || this.#full() || target === undefined || covered || lowest || elapsed) { this.#started(); this.#target = target; @@ -1062,7 +1065,7 @@ export class Consumer { // the max delay, plus the warmup while the reader warms. #ageBudget(): number { const maxDelay = maxMicros(this.#delay.peek()); - return this.#warming() ? maxDelay + Micro.fromMilli(this.#warmup) : maxDelay; + return this.#warming() ? maxDelay + this.#warmup.asMicros() : maxDelay; } // The reader has not yet read past the start's target and the warmup past its first frame. @@ -1072,20 +1075,20 @@ export class Consumer { // Return `read`, or a gap ahead of it when media went missing after an earlier item. #emit(read: Exclude): Read { - const resume = read.kind === "frame" ? read.frame.timestamp : read.end; + const resume = (read.kind === "frame" ? read.frame.timestamp : read.end).asMicros(); const edge = this.#edge; const lost = this.#lost; this.#lost = false; - this.#advance(read.kind === "frame" ? Micro(resume + (read.frame.duration ?? Micro.zero)) : resume); + this.#advance(read.kind === "frame" ? resume + (read.frame.duration?.asMicros() ?? 0) : resume); if (!lost || edge === undefined) return read; // A next group may start before the edge (an overlapping endpoint), so the span bottoms out at zero. - const timestamp = Micro(Math.min(edge, resume)); + const timestamp = Math.min(edge, resume); this.#next = read; - return { kind: "gap", timestamp, duration: Micro(resume - timestamp) }; + return { kind: "gap", timestamp: Duration.micros(timestamp), duration: Duration.micros(resume - timestamp) }; } - #advance(end: Micro): void { + #advance(end: number): void { if (this.#edge === undefined || end > this.#edge) this.#edge = end; } @@ -1093,24 +1096,27 @@ export class Consumer { const ranges: BufferedRanges = []; let prev: Group | undefined; + // The open range, its end in microseconds: only the merged ranges become Durations, not + // every group on every update. + let start: Duration | undefined; + let end = 0; for (const group of this.#groups) { const first = group.frames.at(0); if (!first || group.latest === undefined) continue; - const start = Milli.fromMicro(first.timestamp); - const end = Milli.fromMicro(group.latest); - - const last = ranges.at(-1); const contiguous = prev?.consumer.done && prev.consumer.sequence + 1n === group.consumer.sequence; - if (last && (last.end >= start || contiguous)) { - last.end = Milli(Math.max(last.end, end)); + if (start !== undefined && (end >= first.timestamp.asMicros() || contiguous)) { + end = Math.max(end, group.latest); } else { - ranges.push({ start, end }); + if (start !== undefined) ranges.push({ start, end: Duration.micros(end) }); + start = first.timestamp; + end = group.latest; } prev = group; } + if (start !== undefined) ranges.push({ start, end: Duration.micros(end) }); this.#buffered.set(ranges); } diff --git a/js/hang/src/container/consumer.warmup.test.ts b/js/hang/src/container/consumer.warmup.test.ts index ec3f3b3f2b1..d35d7668473 100644 --- a/js/hang/src/container/consumer.warmup.test.ts +++ b/js/hang/src/container/consumer.warmup.test.ts @@ -1,5 +1,5 @@ import { expect, onTestFinished, spyOn, test } from "bun:test"; -import { Manual, Micro, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { type Group, Time, Track } from "@moq/net"; import { Consumer, type Read } from "./consumer.ts"; import { encodeFrame, Format } from "./legacy.ts"; @@ -11,14 +11,17 @@ function setup(delay = BUDGET, warmup = 0, min = delay, max: number | null = del const clock = new Manual(); const installed = clock.install(); // Drain the in-memory readers and their continuations without moving time. - const flush = () => clock.advance(Nano.zero); + const flush = () => clock.advance(Duration.ZERO); const track = new Track.Producer("video"); // A null max delay sets no subscriber limit; an omitted one is zero. - const consumer = new Consumer(track.subscribe({ delay: { max: max === null ? null : Milli(max + warmup) } }), { - format: new Format("video"), - delay: { min: Milli(min), max: max === null ? null : Milli(max) }, - warmup: Milli(warmup), - }); + const consumer = new Consumer( + track.subscribe({ delay: { max: max === null ? null : Duration.millis(max + warmup) } }), + { + format: new Format("video"), + delay: { min: Duration.millis(min), max: max === null ? null : Duration.millis(max) }, + warmup: Duration.millis(warmup), + }, + ); const results: Read[] = []; const warn = spyOn(console, "warn").mockImplementation(() => {}); const reading = (async () => { @@ -44,12 +47,14 @@ function setup(delay = BUDGET, warmup = 0, min = delay, max: number | null = del // Each frame as "@<µs>". function frames(results: Read[]): string[] { - return results.flatMap((read) => (read.kind === "frame" ? [`${read.group}@${read.frame.timestamp}`] : [])); + return results.flatMap((read) => + read.kind === "frame" ? [`${read.group}@${read.frame.timestamp.asMicros()}`] : [], + ); } function write(group: Group.Producer, timestamp: number) { group.writeFrame({ - payload: encodeFrame(new Uint8Array([1]), Micro(timestamp)), + payload: encodeFrame(new Uint8Array([1]), Duration.micros(timestamp)), timestamp: Time.Timestamp.now(), }); } @@ -99,10 +104,10 @@ test("a quiet track starts within one reach", async () => { const { clock, track, results, flush } = setup(200, 300); group(track, 5n, [5_000_000]); await flush(); - await clock.advance(Nano.fromMilli(Milli(BUDGET - 50))); + await clock.advance(Duration.millis(BUDGET - 50)); expect(frames(results)).toEqual([]); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); expect(frames(results)).toEqual(["5@5000000"]); }); @@ -145,10 +150,10 @@ test("a min delay past the max delay reaches only the max delay", async () => { const { clock, track, results, flush } = setup(200, 0, 2_000); group(track, 5n, [5_000_000]); await flush(); - await clock.advance(Nano.fromMilli(Milli(150))); + await clock.advance(Duration.millis(150)); expect(frames(results)).toEqual([]); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); expect(frames(results)).toEqual(["5@5000000"]); }); diff --git a/js/hang/src/container/format.ts b/js/hang/src/container/format.ts index 57ef80c22f1..16ce122a8d9 100644 --- a/js/hang/src/container/format.ts +++ b/js/hang/src/container/format.ts @@ -1,4 +1,4 @@ -import type { Micro } from "@moq/clock"; +import type { Duration } from "@moq/clock"; import type { Time } from "@moq/net"; import type { Frame } from "./types"; @@ -9,5 +9,5 @@ export interface Format { /** Parse one MoQ frame's payload, given its moq-net timestamp (absent on an untimed track), into decoded media frames. On a data track no frames means the discontinuity marker, so a format returns none only for an object with no bytes. */ decode(payload: Uint8Array, timestamp: Time.Timestamp | undefined): Frame[]; /** Return the endpoint timestamp carried by empty-payload metadata. */ - end?(frame: Frame): Micro | undefined; + end?(frame: Frame): Duration | undefined; } diff --git a/js/hang/src/container/jitter.test.ts b/js/hang/src/container/jitter.test.ts index c346af8d378..4f7d32d2cf5 100644 --- a/js/hang/src/container/jitter.test.ts +++ b/js/hang/src/container/jitter.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it } from "bun:test"; import { readdirSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import type { Milli } from "@moq/clock"; import { type Entry, History, Jitter } from "./jitter"; // The conformance corpus beside doc/concept/audio-jitter.md, read directly so this is graded @@ -57,7 +56,7 @@ describe("audio jitter conformance", () => { let current: number | undefined; for (let i = 0; i < c.arrival.length; i++) { if (ends.has(i)) jitter.end(); - jitter.observe(c.arrival[i] as Milli, c.media[i] as Milli); + jitter.observe(c.arrival[i], c.media[i]); const value = target(jitter, c); const listed = expected.get(i); if (listed !== undefined) { @@ -74,18 +73,18 @@ describe("audio jitter conformance", () => { describe("Jitter", () => { it("starts at the prior's 95th percentile", () => { - expect(new Jitter().measured).toBe(100 as Milli); + expect(new Jitter().measured).toBe(100); }); it("is not moved by a stale frame ahead of the live edge", () => { // The #3517 regression: one frame from a stale group, then the live edge 14.5s of media later, // then evenly paced audio with no real jitter. The jump must not read as a delay or a frame. const jitter = new Jitter(); - jitter.observe(0 as Milli, 0 as Milli); + jitter.observe(0, 0); for (let i = 0; i < 500; i++) { - jitter.observe((10 + i * 20) as Milli, (14_500 + i * 20) as Milli); + jitter.observe(10 + i * 20, 14_500 + i * 20); } - expect(jitter.measured).toBe(20 as Milli); + expect(jitter.measured).toBe(20); }); it("ignores an end before any observation", () => { @@ -93,9 +92,9 @@ describe("Jitter", () => { // excuse the first unexplained gap. const jitter = new Jitter(); jitter.end(); - for (let i = 0; i < 500; i++) jitter.observe((50 + i * 20) as Milli, (i * 20) as Milli); + for (let i = 0; i < 500; i++) jitter.observe(50 + i * 20, i * 20); const settled = jitter.measured; - jitter.observe((50 + 500 * 20 + 30_000) as Milli, (500 * 20 + 30_000) as Milli); + jitter.observe(50 + 500 * 20 + 30_000, 500 * 20 + 30_000); expect(jitter.measured).toBeGreaterThan(settled); }); @@ -104,8 +103,8 @@ describe("Jitter", () => { const near = new Jitter(); const far = new Jitter(); for (let i = 0; i < 500; i++) { - near.observe((10 + i * 20) as Milli, (i * 20) as Milli); - far.observe((2000 + i * 20) as Milli, (i * 20) as Milli); + near.observe(10 + i * 20, i * 20); + far.observe(2000 + i * 20, i * 20); } expect(far.measured).toBe(near.measured); }); @@ -114,18 +113,17 @@ describe("Jitter", () => { // A path where every tenth frame lands 300ms late. const warm = new Jitter(); for (let i = 0; i < 500; i++) { - warm.observe((i * 20 + (i % 10 === 0 ? 300 : 0)) as Milli, (i * 20) as Milli); + warm.observe(i * 20 + (i % 10 === 0 ? 300 : 0), i * 20); } const learned = warm.measured; - expect(learned).toBeGreaterThan(100 as Milli); + expect(learned).toBeGreaterThan(100); const fork = warm.fork(); expect(fork.measured).toBe(learned); // The replacement opens with a backlog: older media arriving at once, long after the warm // track's frames. Measured against the warm track's arrivals it would read as seconds late. - for (let i = 0; i < 100; i++) - fork.observe((20_000 + Math.floor(i / 50) * 1000) as Milli, (8000 + i * 20) as Milli); + for (let i = 0; i < 100; i++) fork.observe(20_000 + Math.floor(i / 50) * 1000, 8000 + i * 20); expect(fork.measured).toBeLessThanOrEqual(learned); expect(warm.measured).toBe(learned); }); diff --git a/js/hang/src/container/jitter.ts b/js/hang/src/container/jitter.ts index 257beda9c2d..2074a4adfd5 100644 --- a/js/hang/src/container/jitter.ts +++ b/js/hang/src/container/jitter.ts @@ -1,5 +1,3 @@ -import type { Milli } from "@moq/clock"; - // Implements the estimator in doc/concept/audio-jitter.md, which is normative. The design and // every constant come from WebRTC NetEq's underrun optimizer; this is written from the document, // not from NetEq's source. @@ -68,8 +66,8 @@ export class Jitter { /** How much of the histogram is still the prior's rather than evidence. */ #prior = 1; - /** Fold one frame in: `arrival` on the receiver's monotonic clock, `media` its timestamp. */ - observe(arrival: Milli, media: Milli): void { + /** Fold one frame in, in milliseconds: `arrival` on the receiver's monotonic clock, `media` its timestamp. */ + observe(arrival: number, media: number): void { // A reordered frame is measured but never joins the window: it arrived after a newer frame, // so it can never be the fastest, and a later frame must not be measured against it. if (media > this.#newest) { @@ -140,14 +138,14 @@ export class Jitter { return fork; } - /** The measured term: the upper edge of the bucket holding the 95th percentile. */ - get measured(): Milli { + /** The measured term in milliseconds: the upper edge of the bucket holding the 95th percentile. */ + get measured(): number { let cumulative = 0; for (let i = 0; i < BUCKETS; i++) { cumulative += this.#histogram[i]; - if (cumulative > QUANTILE) return ((i + 1) * BUCKET) as Milli; + if (cumulative > QUANTILE) return (i + 1) * BUCKET; } - return (BUCKETS * BUCKET) as Milli; + return BUCKETS * BUCKET; } // Evidence decays by `FORGET` and the prior holds the rest, of which an observation takes up to diff --git a/js/hang/src/container/legacy.ts b/js/hang/src/container/legacy.ts index dd2bc91c7cf..0853c53bc65 100644 --- a/js/hang/src/container/legacy.ts +++ b/js/hang/src/container/legacy.ts @@ -3,7 +3,7 @@ import { Time } from "@moq/net"; export type { BufferedRange, BufferedRanges, Frame } from "./types"; -import type { Micro } from "@moq/clock"; +import { Duration } from "@moq/clock"; import type { AudioConfig, VideoConfig } from "../catalog"; import type { Format as ContainerFormat } from "./format"; import type { Frame } from "./types"; @@ -19,13 +19,16 @@ export class Format implements ContainerFormat { } /** Write the final video frame's end timestamp before the group closes. */ - finishGroup(group: Moq.Group.Producer, end?: Micro) { + finishGroup(group: Moq.Group.Producer, end?: Duration) { if (this.kind !== "video" || end === undefined) return; - group.writeFrame({ payload: encodeFrame(new Uint8Array(), end), timestamp: Time.Timestamp.fromMicros(end) }); + group.writeFrame({ + payload: encodeFrame(new Uint8Array(), end), + timestamp: Time.Timestamp.fromMicros(micros(end)), + }); } /** Return the video-frame or audio-source endpoint for an empty codec payload. */ - end(frame: Frame): Micro | undefined { + end(frame: Frame): Duration | undefined { return this.kind !== "data" && frame.payload.byteLength === 0 ? frame.timestamp : undefined; } @@ -33,7 +36,7 @@ export class Format implements ContainerFormat { decode(frame: Uint8Array): Frame[] { if (this.kind === "data" && frame.byteLength === 0) return []; const [timestamp, data] = Moq.Varint.decode(frame); - return [{ payload: data, timestamp: timestamp as Micro, keyframe: false }]; + return [{ payload: data, timestamp: Duration.micros(timestamp), keyframe: false }]; } } @@ -46,8 +49,8 @@ export interface Source { } /** Encode a frame as a timestamp varint followed by the payload bytes. */ -export function encodeFrame(source: Uint8Array | Source, timestamp: Micro): Uint8Array { - const timestampBytes = Moq.Varint.encode(timestamp); +export function encodeFrame(source: Uint8Array | Source, timestamp: Duration): Uint8Array { + const timestampBytes = Moq.Varint.encode(micros(timestamp)); const data = new Uint8Array(timestampBytes.byteLength + source.byteLength); data.set(timestampBytes, 0); @@ -60,22 +63,28 @@ export function encodeFrame(source: Uint8Array | Source, timestamp: Micro): Uint return data; } +// The wire carries whole microseconds, rounded down as moq-net's timestamps are. +function micros(timestamp: Duration): number { + return Math.floor(timestamp.asMicros()); +} + /** Writes legacy-container frames into a MoQ track, starting a new group on each keyframe. */ export class Producer { #track: Moq.Track.Producer; #format: Format; - #previous?: Micro; + // Timestamps in whole microseconds. + #previous?: number; #reordered = false; #group?: Moq.Group.Producer; // The newest timestamp written in the current group, which estimates its end. - #end?: Micro; + #end?: number; // Furthest timestamp in finished groups, used only for discontinuity markers. - #liveEdge?: Micro; + #liveEdge?: number; // The current group start and the previous group start, which bounds its frames. - #start?: Micro; - #floor?: Micro; + #start?: number; + #floor?: number; // Gap between consecutive timestamps, used to close the last group when no successor exists. - #interval?: Micro; + #interval?: number; // A discontinuity's marker is the newest group, so another one would say nothing new. #marked = false; @@ -86,7 +95,8 @@ export class Producer { } /** Encode and append a frame; a keyframe starts a new group. Throws if the first frame is not a keyframe, a group start goes backwards, or a frame is below the previous group start. */ - encode(data: Uint8Array | Source, timestamp: Micro, keyframe: boolean) { + encode(data: Uint8Array | Source, pts: Duration, keyframe: boolean) { + const timestamp = micros(pts); const floor = keyframe ? this.#start : this.#floor; if (floor !== undefined && timestamp < floor) { throw new Error("frame timestamp is below the previous group start"); @@ -104,13 +114,13 @@ export class Producer { } this.#group?.writeFrame({ - payload: encodeFrame(data, timestamp), + payload: encodeFrame(data, pts), timestamp: Time.Timestamp.fromMicros(timestamp), }); this.#reordered ||= this.#previous !== undefined && timestamp < this.#previous; if (this.#previous !== undefined && timestamp > this.#previous) { - const delta = (timestamp - this.#previous) as Micro; + const delta = timestamp - this.#previous; this.#interval = delta; } this.#previous = timestamp; @@ -132,7 +142,8 @@ export class Producer { * object with no bytes at all. No marker is written until a frame follows the last one. Throws if * `end` precedes the last video frame. */ - discontinuity(end?: Micro) { + discontinuity(endpoint?: Duration) { + const end = endpoint === undefined ? undefined : micros(endpoint); // Nothing is measured across the break, so a missing end has no cadence to estimate from. // An explicit end keeps the cadence until #close validates it, in case it throws. if (end === undefined) this.#interval = undefined; @@ -143,16 +154,19 @@ export class Producer { const group = this.#track.appendGroup(); group.writeFrame({ - payload: this.#format.kind === "data" ? new Uint8Array() : encodeFrame(new Uint8Array(), timestamp), + payload: + this.#format.kind === "data" + ? new Uint8Array() + : encodeFrame(new Uint8Array(), Duration.micros(timestamp)), timestamp: Time.Timestamp.fromMicros(timestamp), }); group.finish(); - this.#liveEdge = this.#liveEdge === undefined ? timestamp : (Math.max(this.#liveEdge, timestamp) as Micro); + this.#liveEdge = this.#liveEdge === undefined ? timestamp : Math.max(this.#liveEdge, timestamp); this.#marked = true; } // Flush and close the current group at the supplied or estimated end timestamp. - #close(end?: Micro) { + #close(end?: number) { if (!this.#group) return; if ( this.#format.kind === "video" && @@ -163,16 +177,13 @@ export class Producer { ) { throw new Error("video group endpoint precedes its last frame"); } - end ??= - this.#end !== undefined && this.#interval !== undefined - ? ((this.#end + this.#interval) as Micro) - : undefined; + end ??= this.#end !== undefined && this.#interval !== undefined ? this.#end + this.#interval : undefined; // A presentation endpoint cannot bound the decode-order tail after reordering. - this.#format.finishGroup(this.#group, this.#reordered ? undefined : end); + this.#format.finishGroup(this.#group, this.#reordered || end === undefined ? undefined : Duration.micros(end)); this.#group.finish(); this.#group = undefined; if (this.#end !== undefined) { - this.#liveEdge = this.#liveEdge === undefined ? this.#end : (Math.max(this.#liveEdge, this.#end) as Micro); + this.#liveEdge = this.#liveEdge === undefined ? this.#end : Math.max(this.#liveEdge, this.#end); } this.#end = undefined; this.#previous = undefined; diff --git a/js/hang/src/container/track.test.ts b/js/hang/src/container/track.test.ts index 4ad411bbf6b..d1d1953505a 100644 --- a/js/hang/src/container/track.test.ts +++ b/js/hang/src/container/track.test.ts @@ -1,20 +1,20 @@ import { expect, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Time, Track } from "@moq/net"; import { MAX_AGE, trackInfo } from "./track"; test("trackInfo declares the media max age, null is unlimited, and a value is kept", async () => { - expect(MAX_AGE).toBe(Milli(30_000)); + expect(MAX_AGE).toEqual(Duration.millis(30_000)); const omitted = trackInfo({ priority: 1 }); expect(omitted).toEqual({ timescale: Time.Timescale.MICRO, maxAge: MAX_AGE, priority: 1 }); expect(trackInfo({ priority: 1, maxAge: undefined }).maxAge).toBe(MAX_AGE); expect(trackInfo({ priority: 1, maxAge: null }).maxAge).toBeNull(); - expect(trackInfo({ priority: 1, maxAge: Milli(5000) }).maxAge).toBe(Milli(5000)); + expect(trackInfo({ priority: 1, maxAge: Duration.millis(5000) }).maxAge).toEqual(Duration.millis(5000)); // What a producer accepting each commits. - const committed = async (maxAge?: Milli | null) => + const committed = async (maxAge?: Duration | null) => (await new Track.Producer("media").accept(trackInfo({ priority: 1, maxAge })).info()).maxAge; - expect(await committed()).toBe(Milli(30_000)); + expect(await committed()).toEqual(Duration.millis(30_000)); expect(await committed(null)).toBeNull(); - expect(await committed(Milli(5000))).toBe(Milli(5000)); + expect(await committed(Duration.millis(5000))).toEqual(Duration.millis(5000)); }); diff --git a/js/hang/src/container/track.ts b/js/hang/src/container/track.ts index be03b97e7da..59e0ad90eab 100644 --- a/js/hang/src/container/track.ts +++ b/js/hang/src/container/track.ts @@ -7,7 +7,7 @@ * @module */ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Time, type Track } from "@moq/net"; /** @@ -19,7 +19,7 @@ import { Time, type Track } from "@moq/net"; * target durations behind live, and a recorder absorbs reordering. `@moq/net`'s default of zero * would leave those addressing groups that are already stale. */ -export const MAX_AGE = Milli(30_000); +export const MAX_AGE = Duration.millis(30_000); /** * Track properties for a track carrying media frames, for `Request.accept`. @@ -58,5 +58,5 @@ export type TrackInfoOptions = { * and lowering it does not reduce latency: it only shortens how far back a fetch can reach. * It keeps no bytes either; the cache decides how long a group's payload stays held. */ - maxAge?: Milli | null; + maxAge?: Duration | null; }; diff --git a/js/hang/src/container/types.ts b/js/hang/src/container/types.ts index e6d7edd3f4c..69eb6e42bf6 100644 --- a/js/hang/src/container/types.ts +++ b/js/hang/src/container/types.ts @@ -1,11 +1,11 @@ -import { type Micro, Milli } from "@moq/clock"; +import type { Duration, Instant } from "@moq/clock"; /** A decoded media frame: codec payload plus its presentation timestamp and keyframe flag. */ export interface Frame { /** The codec bitstream payload. */ payload: Uint8Array; - /** Presentation timestamp in microseconds. */ - timestamp: Micro; + /** Presentation timestamp: how far into the media timeline this frame starts. */ + timestamp: Duration; /** Whether this frame opens a group, or is a video keyframe. Audio carries it only on a group start. */ keyframe: boolean; @@ -16,21 +16,21 @@ export interface Frame { * so it can advance to a newer group as soon as the gap is covered instead of * waiting out the max delay budget. */ - duration?: Micro; + duration?: Duration; } /** A media frame carrying its local transport ingress time. */ export interface ReceivedFrame extends Frame { - /** Monotonic ingress time in milliseconds, before reordering or decoder backpressure. */ - arrival: Milli; + /** When the frame came off the transport, before reordering or decoder backpressure. */ + arrival: Instant; } -/** A contiguous span of buffered media, in milliseconds. */ +/** A contiguous span of buffered media, on the presentation timeline. */ export interface BufferedRange { - /** Start of the range in milliseconds. */ - start: Milli; - /** End of the range in milliseconds. */ - end: Milli; + /** Start of the range. */ + start: Duration; + /** End of the range. */ + end: Duration; } /** An ordered list of buffered time ranges. */ @@ -42,12 +42,12 @@ export function mergeBufferedRanges(a: BufferedRanges, b: BufferedRanges): Buffe if (b.length === 0) return a; const result: BufferedRanges = []; - const all = [...a, ...b].sort((x, y) => x.start - y.start); + const all = [...a, ...b].sort((x, y) => x.start.cmp(y.start)); for (const range of all) { const last = result.at(-1); - if (last && last.end >= range.start) { - last.end = Milli(Math.max(last.end, range.end)); + if (last?.end.ge(range.start)) { + last.end = last.end.max(range.end); } else { result.push({ ...range }); } diff --git a/js/json/src/snapshot/consumer.ts b/js/json/src/snapshot/consumer.ts index 492c2f5339a..957192bda69 100644 --- a/js/json/src/snapshot/consumer.ts +++ b/js/json/src/snapshot/consumer.ts @@ -1,4 +1,4 @@ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import type { Timed } from "@moq/net"; import * as Moq from "@moq/net"; @@ -43,7 +43,7 @@ export class Consumer { .subscribe({ ...Moq.Track.Subscription.default(), priority: config.priority ?? 0, - delay: { max: Milli.zero }, + delay: { max: Duration.ZERO }, }) .ordered(); this.#decoder = new Decoder(config); diff --git a/js/json/src/snapshot/snapshot.test.ts b/js/json/src/snapshot/snapshot.test.ts index 5efd87ea9bb..76142215667 100644 --- a/js/json/src/snapshot/snapshot.test.ts +++ b/js/json/src/snapshot/snapshot.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { Error as NetError, StreamCode, Time, Track } from "@moq/net"; import { hooks } from "../../../net/src/internal.ts"; import { Consumer } from "./consumer.ts"; @@ -10,7 +10,7 @@ type Value = Record; // These tests inspect complete finished timelines through raw ordered reads, so request a // replay window instead of the transport's live-edge default. A snapshot consumer ignores it. -const REPLAY_LATENCY = Milli(30_000); +const REPLAY_LATENCY = Duration.millis(30_000); // Reconstruct every state a consumer reading `track` yields from `next()`, in order. async function drain(track: Track.Producer | Consumer): Promise { @@ -195,7 +195,7 @@ test("next skips every superseded group, whatever budget another reader asks for for (let n = 1; n <= 3; n++) producer.update({ value: { n }, at: Time.Timestamp.fromMillis(n * 1_000) }); producer.finish(); - for (const max of [Milli.zero, Milli(500), REPLAY_LATENCY, null]) { + for (const max of [Duration.ZERO, Duration.millis(500), REPLAY_LATENCY, null]) { const other = track.subscribe({ delay: { max } }); expect(await drain(track)).toEqual([{ n: 3 }]); other.close(); @@ -210,7 +210,7 @@ test("reads skip a group the subscription still owes", async () => { const clock = new Manual(); const installed = clock.install(); try { - for (const max of [Milli.zero, Milli(1_000), null]) { + for (const max of [Duration.ZERO, Duration.millis(1_000), null]) { const track = new Track.Producer("test").accept({}); hooks.receiveTrack(track); const other = track.subscribe({ delay: { max } }); @@ -226,7 +226,7 @@ test("reads skip a group the subscription still owes", async () => { expect((await latest.latest())?.value).toEqual({ n: 0 }); expect((await next.next())?.value).toEqual({ n: 0 }); const reads = [latest.latest(), next.next()]; - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); put(2n); expect((await Promise.all(reads)).map((state) => state?.value)).toEqual([{ n: 2 }, { n: 2 }]); diff --git a/js/json/src/stream/stream.test.ts b/js/json/src/stream/stream.test.ts index e657afe6cd4..70f05ef37b8 100644 --- a/js/json/src/stream/stream.test.ts +++ b/js/json/src/stream/stream.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { StreamCode, Time, Track } from "@moq/net"; import * as z from "zod/mini"; import { Consumer, Producer, Rolled } from "./index.ts"; @@ -99,7 +99,7 @@ test("a second group is reported while the first is still open", async () => { // Ask for a replay window, so the first group is delivered rather than skipped by the // subscriber's default max delay budget once a newer group exists. - const consumer = new Consumer({ track: track.subscribe({ delay: { max: Milli(30_000) } }) }); + const consumer = new Consumer({ track: track.subscribe({ delay: { max: Duration.millis(30_000) } }) }); expect((await consumer.next())?.value).toEqual({ n: 0 }); await expect(consumer.next()).rejects.toBeInstanceOf(Rolled); diff --git a/js/json/src/window/window.test.ts b/js/json/src/window/window.test.ts index 902034a2433..10cc0bfdca8 100644 --- a/js/json/src/window/window.test.ts +++ b/js/json/src/window/window.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Milli, yieldNow } from "@moq/clock"; +import { Duration, yieldNow } from "@moq/clock"; import { Error as NetError, StreamCode, Time, type Timed, Track } from "@moq/net"; import { Consumer } from "./consumer.ts"; import { Decoder, Encoder, type Event, Producer, type Span } from "./index.ts"; @@ -212,7 +212,7 @@ test("compressed round-trip across rolls", async () => { // The frame count and first-frame timestamp of each group in a finished track. async function groups(track: Track.Producer): Promise<[number, number | undefined][]> { - const ordered = track.subscribe({ delay: { max: Milli(30_000) } }).ordered(); + const ordered = track.subscribe({ delay: { max: Duration.millis(30_000) } }).ordered(); const out: [number, number | undefined][] = []; for (let group = await ordered.nextGroup(); group; group = await ordered.nextGroup()) { const first = await group.readFrame(); diff --git a/js/loc/api/index.api.md b/js/loc/api/index.api.md index 3d7e3df62a0..d360f331898 100644 --- a/js/loc/api/index.api.md +++ b/js/loc/api/index.api.md @@ -1,18 +1,18 @@ # `@moq/loc` ```ts -import { Micro } from "@moq/clock"; +import { Duration } from "@moq/clock"; export class Format { constructor(kind?: "audio" | "video" | "data"); decode(frame: Uint8Array): Frame[]; - end(frame: Frame): Micro | undefined; + end(frame: Frame): Duration | undefined; readonly kind: "audio" | "video" | "data"; } export interface Frame { keyframe: boolean; payload: Uint8Array; - timestamp: Micro; + timestamp: Duration; } ``` diff --git a/js/loc/src/index.test.ts b/js/loc/src/index.test.ts index 3c68644ebf7..19121102bb3 100644 --- a/js/loc/src/index.test.ts +++ b/js/loc/src/index.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import type { Micro } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Varint } from "@moq/net"; import { Format } from "./index.ts"; @@ -33,7 +33,7 @@ test("Format treats an empty payload as a duration marker", () => { const fmt = new Format("video"); const [decoded] = fmt.decode(frame); expect(decoded.payload.byteLength).toBe(0); - expect(fmt.end(decoded)).toBe(33_000 as Micro); + expect(fmt.end(decoded)).toEqual(Duration.micros(33_000)); }); test("Format preserves empty data payloads", () => { @@ -57,7 +57,7 @@ test("Format decodes timestamp at default microseconds timescale", () => { const fmt = new Format(); const [decoded] = fmt.decode(frame); - expect(decoded.timestamp).toBe(12_345 as Micro); + expect(decoded.timestamp).toEqual(Duration.micros(12_345)); expect(decoded.payload).toEqual(payload); expect(decoded.keyframe).toBe(false); }); @@ -75,7 +75,7 @@ test("Format honors per-frame timescale property", () => { const fmt = new Format(); const [decoded] = fmt.decode(frame); - expect(decoded.timestamp).toBe(2_000_000 as Micro); + expect(decoded.timestamp).toEqual(Duration.micros(2_000_000)); }); test("Format skips unknown odd-typed properties", () => { @@ -93,7 +93,7 @@ test("Format skips unknown odd-typed properties", () => { const fmt = new Format(); const [decoded] = fmt.decode(frame); - expect(decoded.timestamp).toBe(10 as Micro); + expect(decoded.timestamp).toEqual(Duration.micros(10)); expect(decoded.payload).toEqual(payload); }); @@ -136,7 +136,7 @@ test("Format decodes the draft-03 timestamp property", () => { const fmt = new Format(); const [decoded] = fmt.decode(frame); - expect(decoded.timestamp).toBe(4242 as Micro); + expect(decoded.timestamp).toEqual(Duration.micros(4242)); expect(decoded.payload).toEqual(payload); }); @@ -148,7 +148,7 @@ test("Format skips an unknown property whose value needs all 62 bits", () => { Varint.encode(1_000), ); const [decoded] = new Format().decode(buildFrame(props, new Uint8Array([1]))); - expect(decoded.timestamp).toBe(1_000 as Micro); + expect(decoded.timestamp).toEqual(Duration.micros(1_000)); }); test("Format rejects a timestamp past 2^53 - 1 instead of rounding", () => { diff --git a/js/loc/src/index.ts b/js/loc/src/index.ts index bb954622062..56c1a955430 100644 --- a/js/loc/src/index.ts +++ b/js/loc/src/index.ts @@ -5,15 +5,15 @@ * @module */ -import type { Micro } from "@moq/clock"; +import { Duration } from "@moq/clock"; import * as Moq from "@moq/net"; /** A decoded LOC frame: the codec bitstream plus its timing metadata. */ export interface Frame { /** The codec bitstream payload, with the LOC property block stripped. */ payload: Uint8Array; - /** Presentation timestamp in microseconds. */ - timestamp: Micro; + /** Presentation timestamp, rounded to whole microseconds. */ + timestamp: Duration; /** True if this frame can be decoded without any preceding frames. */ keyframe: boolean; } @@ -47,7 +47,7 @@ export class Format { } /** Return the video-frame or audio-source endpoint for an empty codec payload. */ - end(frame: Frame): Micro | undefined { + end(frame: Frame): Duration | undefined { return this.kind !== "data" && frame.payload.byteLength === 0 ? frame.timestamp : undefined; } @@ -100,7 +100,7 @@ export class Format { } const activeTimescale = timescale ?? DEFAULT_TIMESCALE; - const micros = Math.round((timestamp * DEFAULT_TIMESCALE) / activeTimescale) as Micro; + const micros = Duration.micros(Math.round((timestamp * DEFAULT_TIMESCALE) / activeTimescale)); return [{ payload, timestamp: micros, keyframe: false }]; } diff --git a/js/moq-boy/src/game.ts b/js/moq-boy/src/game.ts index 115618b1fad..71dd55a7224 100644 --- a/js/moq-boy/src/game.ts +++ b/js/moq-boy/src/game.ts @@ -6,7 +6,7 @@ * * @module */ -import { Nano, Second } from "@moq/clock"; +import { Duration } from "@moq/clock"; import * as Json from "@moq/json"; import * as Moq from "@moq/net"; import * as Watch from "@moq/watch"; @@ -37,7 +37,7 @@ interface Command { } // Close the session to the emulator after 60s of no input. -const FEEDBACK_IDLE = Nano.fromSecond(Second(60)); +const FEEDBACK_IDLE = Duration.secs(60); // Game Boy native resolution. const GB_WIDTH = 160; @@ -225,15 +225,15 @@ export class Game { this.#command.set({ cmd, timestamps: this.#timestamps() }, true); } - /** Collect media timestamps at each pipeline stage for latency measurement. */ + /** Collect media timestamps, in milliseconds, at each pipeline stage for latency measurement. */ #timestamps(): { label: string; ts: number }[] { const entries: { label: string; ts: number }[] = []; const received = this.sync.out.timestamp.peek(); - if (received != null) entries.push({ label: "received", ts: received }); + if (received != null) entries.push({ label: "received", ts: received.asMillis() }); const decoded = this.videoDecoder.out.timestamp.peek(); - if (decoded != null) entries.push({ label: "decoded", ts: decoded }); + if (decoded != null) entries.push({ label: "decoded", ts: decoded.asMillis() }); const rendered = this.videoRenderer.out.timestamp.peek(); - if (rendered != null) entries.push({ label: "rendered", ts: rendered }); + if (rendered != null) entries.push({ label: "rendered", ts: rendered.asMillis() }); return entries; } diff --git a/js/moq-boy/src/ui/components/StatsPanel.tsx b/js/moq-boy/src/ui/components/StatsPanel.tsx index 0c131798135..29ce4dda8a2 100644 --- a/js/moq-boy/src/ui/components/StatsPanel.tsx +++ b/js/moq-boy/src/ui/components/StatsPanel.tsx @@ -1,4 +1,4 @@ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { createAccessor } from "@moq/signals/solid"; import { For, Show } from "solid-js"; import { useGameUI } from "../hooks/use-boy-ui"; @@ -12,7 +12,7 @@ export default function StatsPanel() { const onDelayInput = (e: Event) => { const el = e.currentTarget as HTMLInputElement; - game.delay.set(Milli(Number.parseInt(el.value, 10))); + game.delay.set(Duration.millis(Number.parseInt(el.value, 10))); }; const location = () => ctx.status()?.location; @@ -47,13 +47,13 @@ export default function StatsPanel() {