From 40062de1054de93346f04969bc3025a0b02c8058 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 07:05:39 -0800 Subject: [PATCH 1/6] chore(quest): claim quest/m2/ffi-open-selectors.md Quest-Claim: 8dd71fc87cd06542 From 917bf4379a19f88e94fad6dcd768f1c638cf95e0 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 07:18:21 -0800 Subject: [PATCH 2/6] feat(ffi)!: binding selectors can grow, and a null max age means unlimited Co-Authored-By: Claude Opus 5.5 --- cpp/moq/bench/main.cpp | 1 + dart/moq/lib/json.dart | 4 +- dart/moq/lib/src/aliases.dart | 35 +- dart/moq/lib/src/surface.dart | 29 +- dart/moq/lib/video.dart | 4 +- dart/moq/test/moq_test.dart | 50 +- dart/moq_ffi/lib/src/moq.dart | 452 ++++++++++++++---- demo/carla/sim/moq_carla_sim/publish.py | 2 +- demo/carla/sim/tests/conftest.py | 2 +- doc/lib/cpp/index.md | 6 +- doc/lib/dart/index.md | 7 +- doc/lib/go/index.md | 4 +- doc/lib/kt/index.md | 7 +- doc/lib/py/index.md | 6 +- doc/lib/swift/index.md | 7 +- go/wrapper/README.md | 3 +- go/wrapper/json/json_test.go | 6 +- go/wrapper/moq_test.go | 2 +- go/wrapper/records.go | 15 +- go/wrapper/server.go | 2 + go/wrapper/subscribe.go | 42 +- go/wrapper/subscribe_internal_test.go | 26 - go/wrapper/types.go | 34 +- go/wrapper/video/video.go | 4 +- .../kotlin/dev/moq/Aliases.kt | 7 +- .../kotlin/dev/moq/json/Tracks.kt | 8 +- .../kotlin/dev/moq/video/Video.kt | 24 +- .../kotlin/dev/moq/SmokeTest.kt | 27 +- kt/moq/src/jvmTest/kotlin/dev/moq/FfiBench.kt | 2 +- py/moq-rs/README.md | 2 +- py/moq-rs/moq/__init__.py | 4 - py/moq-rs/moq/_records.py | 35 +- py/moq-rs/moq/json.py | 2 +- py/moq-rs/moq/types.py | 8 +- py/moq-rs/tests/test_local.py | 38 +- rs/moq-ffi/AGENTS.md | 9 + rs/moq-ffi/src/bench.rs | 3 +- rs/moq-ffi/src/producer.rs | 100 ++-- rs/moq-ffi/src/server.rs | 48 +- rs/moq-ffi/src/socket.rs | 2 +- rs/moq-ffi/src/test.rs | 40 +- rs/moq-ffi/src/video.rs | 57 ++- swift/README.md | 4 +- swift/Sources/Moq/Aliases.swift | 8 +- swift/Sources/Moq/Json.swift | 6 +- swift/Sources/Moq/Video.swift | 24 +- swift/Tests/MoqTests/FfiBench.swift | 2 +- swift/Tests/MoqTests/SmokeTests.swift | 23 +- 48 files changed, 723 insertions(+), 510 deletions(-) delete mode 100644 go/wrapper/subscribe_internal_test.go diff --git a/cpp/moq/bench/main.cpp b/cpp/moq/bench/main.cpp index e8a6c01aeda..205575f12b0 100644 --- a/cpp/moq/bench/main.cpp +++ b/cpp/moq/bench/main.cpp @@ -104,6 +104,7 @@ void throughput(Case c, double budget, std::vector &results) std::vector> tracks; std::vector> consumers; moq::TrackInfo info; + info.max_age = std::chrono::nanoseconds::zero(); info.timescale = 1000000; for (int p = 0; p < c.publishers; ++p) { auto track = ok(broadcast->publish_track(std::to_string(p), info)); diff --git a/dart/moq/lib/json.dart b/dart/moq/lib/json.dart index 9815f246709..480ad9ab675 100644 --- a/dart/moq/lib/json.dart +++ b/dart/moq/lib/json.dart @@ -4,7 +4,7 @@ /// snapshot and stream producers also advertise it in the broadcast's catalog, /// which has no window mode), and a consumer takes over a `TrackConsumer` that /// has not read a group yet. Values cross as JSON strings. Compression is the -/// track's: publish JSON with `MoqTrackInfo(compression: MoqCompression.deflate)`, and a consumer +/// track's: publish JSON with `TrackInfo(compression: Compression.deflate())`, and a consumer /// reads it with no option of its own. Every write (a snapshot update, a stream /// append, a window push or pop) takes a timestamp on the broadcast clock, the /// epoch every track in the broadcast shares, so the track needs a timescale; @@ -18,7 +18,7 @@ /// broadcast: broadcast, /// track: broadcast.publishTrack( /// name: 'status', -/// info: MoqTrackInfo(timescale: 1000, compression: MoqCompression.deflate), +/// info: TrackInfo(timescale: 1000, compression: Compression.deflate()), /// ), /// config: moq_json.SnapshotConfig(), /// ); diff --git a/dart/moq/lib/src/aliases.dart b/dart/moq/lib/src/aliases.dart index efc7afef0e6..e1b38ef6932 100644 --- a/dart/moq/lib/src/aliases.dart +++ b/dart/moq/lib/src/aliases.dart @@ -3,11 +3,12 @@ import 'package:moq_ffi/moq_ffi.dart'; // Re-export the UniFFI types without their `Moq` prefix, so consumers spell // them the way the Rust API does. These are type aliases, not wrappers: the // values are the exact same objects, so every generated method applies -// unchanged and the prefixed names stay valid. `Delay`, `Subscription`, and -// `Timestamp` are extension types instead, which are the same objects too but -// add constructors: an omitted delay bound is the zero moq-net defaults to, -// where the generated record leaves it null, and a timestamp is built either -// scaled or [Timestamp.unscaled], as in Rust. +// unchanged and the prefixed names stay valid. `Delay`, `Subscription`, +// `TrackInfo`, and `Timestamp` are extension types instead, which are the same +// objects too but add constructors: an omitted delay bound or max age is the +// zero moq-net defaults to, where the generated record leaves it null (no +// limit), and a timestamp is built either scaled or [Timestamp.unscaled], as in +// Rust. // // Four types are deliberately not aliased, because the unprefixed name is // already taken where this package is used: @@ -216,8 +217,30 @@ typedef Position = MoqPosition; /// Options for fetching one past group by sequence. typedef FetchGroupOptions = MoqFetchGroupOptions; +/// How a track's frames are compressed on the wire: `Compression.deflate()`, or null in +/// [TrackInfo] for none. Compare a received one by `name()`. +typedef Compression = MoqCompression; + /// Delivery settings for a raw track: priority, ordering, latency budget, and timescale. -typedef TrackInfo = MoqTrackInfo; +extension type TrackInfo._(MoqTrackInfo _info) implements MoqTrackInfo { + /// `maxAge` is how long a superseded group stays fresh, defaulting to zero, moq-net's + /// default, which serves only the live edge. An explicit null sets no publisher limit. + TrackInfo({ + int priority = 0, + Duration? maxAge = Duration.zero, + int? refresh, + int? timescale, + MoqCompression? compression, + }) : this._( + MoqTrackInfo( + priority: priority, + maxAge: maxAge, + refresh: refresh, + timescale: timescale, + compression: compression, + ), + ); +} /// Divides one connection's send estimate among the tracks sharing it. typedef Allocator = MoqAllocator; diff --git a/dart/moq/lib/src/surface.dart b/dart/moq/lib/src/surface.dart index fb9f55faaeb..9461118502b 100644 --- a/dart/moq/lib/src/surface.dart +++ b/dart/moq/lib/src/surface.dart @@ -1,28 +1,11 @@ import 'package:moq_ffi/moq_ffi.dart'; -/// The platform image backing a `DecodedFrame`, when `DecoderOutput` asked for one. -/// -/// Switch on it with a default case, since new platforms add kinds. -abstract class Surface { - const Surface._(); -} +/// The platform image backing a `DecodedFrame`, when `DecoderOutput` asked for one: a +/// [PixelBuffer] on macOS and iOS, or an [UnknownSurface] for a kind this version cannot name yet. +typedef Surface = MoqVideoSurface; /// A borrowed `CVPixelBufferRef` address (macOS and iOS), valid while its `DecodedFrame` lives. -final class PixelBuffer extends Surface { - /// The address of the `CVPixelBufferRef`. - final int pointer; +typedef PixelBuffer = PixelBufferMoqVideoSurface; - const PixelBuffer._(this.pointer) : super._(); -} - -/// A surface kind this version of the package does not know yet. -final class UnknownSurface extends Surface { - const UnknownSurface._() : super._(); -} - -/// Maps a generated surface to [Surface], so a variant this package predates is an [UnknownSurface]. -Surface? surfaceFrom(MoqVideoSurface? surface) => switch (surface) { - null => null, - PixelBufferMoqVideoSurface(:final pointer) => PixelBuffer._(pointer), - _ => const UnknownSurface._(), -}; +/// A surface kind this version of the package cannot name yet. +typedef UnknownSurface = UnknownMoqVideoSurface; diff --git a/dart/moq/lib/video.dart b/dart/moq/lib/video.dart index 4b2d361661d..25bc978dbc0 100644 --- a/dart/moq/lib/video.dart +++ b/dart/moq/lib/video.dart @@ -38,7 +38,7 @@ typedef Frame = MoqVideoFrame; /// One encoded access unit from an [Encoder]. typedef Packet = MoqVideoPacket; -/// H.264 or H.265. +/// Selects the video encoder codec. Build one with `Codec.h264()` or `Codec.h265()`. typedef Codec = MoqVideoCodec; /// A CPU pixel layout (I420 or RGBA). @@ -162,7 +162,7 @@ final class DecodedFrame { _inner.pixels(format: format); /// The decoder's platform surface, or null when the frame is in CPU memory. - Surface? surface() => surfaceFrom(_inner.surface()); + Surface? surface() => _inner.surface(); /// Release the frame's surface back to the decoder. void dispose() => _inner.dispose(); diff --git a/dart/moq/test/moq_test.dart b/dart/moq/test/moq_test.dart index 98022098b36..f8fa33ab14b 100644 --- a/dart/moq/test/moq_test.dart +++ b/dart/moq/test/moq_test.dart @@ -6,7 +6,6 @@ import 'package:moq/audio.dart' as moq_audio; import 'package:moq/media.dart' as moq_media; import 'package:moq/json.dart' as moq_json; import 'package:moq/moq.dart'; -import 'package:moq/src/surface.dart' show surfaceFrom; import 'package:moq/video.dart' as moq_video; import 'package:test/test.dart'; @@ -158,19 +157,20 @@ void main() { broadcast.close(); }); - test('an omitted max age is zero and the unlimited flag sets none', () { + test('an omitted max age is zero and a null one sets none', () { final broadcast = BroadcastProducer(); - final omitted = broadcast - .publishTrack(name: 'omitted', info: null) - .consume(subscription: null) - .info(); - expect(omitted.maxAge, Duration.zero); + for (final (i, info) in [null, TrackInfo()].indexed) { + final omitted = broadcast + .publishTrack(name: 'omitted$i', info: info) + .consume(subscription: null) + .info(); + expect(omitted.maxAge, Duration.zero); + } final unlimited = broadcast - .publishTrack(name: 'unlimited', info: TrackInfo(maxAgeUnlimited: true)) + .publishTrack(name: 'unlimited', info: TrackInfo(maxAge: null)) .consume(subscription: null) .info(); expect(unlimited.maxAge, isNull); - expect(unlimited.maxAgeUnlimited, isTrue); broadcast.close(); }); @@ -204,7 +204,7 @@ void main() { final broadcast = BroadcastProducer(); final track = broadcast.publishTrack( name: 'backlog', - info: TrackInfo(maxAgeUnlimited: true, timescale: 1000000), + info: TrackInfo(maxAge: null, timescale: 1000000), ); for (var ms = 0; ms < 3; ms++) { final group = track.appendGroup(); @@ -912,9 +912,9 @@ void main() { broadcast: broadcast, track: broadcast.publishTrack( name: 'status', - info: MoqTrackInfo( + info: TrackInfo( timescale: 1000000, - compression: MoqCompression.deflate, + compression: Compression.deflate(), ), ), config: moq_json.SnapshotConfig(), @@ -951,9 +951,9 @@ void main() { final producer = moq_json.WindowProducer( track: broadcast.publishTrack( name: 'log', - info: MoqTrackInfo( + info: TrackInfo( timescale: 1000000, - compression: MoqCompression.deflate, + compression: Compression.deflate(), ), ), config: moq_json.WindowConfig(), @@ -1015,7 +1015,7 @@ void main() { framerate: moq_video.FrameRate(numerator: 30000, denominator: 1001), ), output: moq_video.EncoderOutput( - codec: moq_video.Codec.h264, + codec: moq_video.Codec.h264(), kind: moq_video.SoftwareEncoder(), ), @@ -1079,14 +1079,6 @@ void main() { broadcast.close(); }); - // A surface kind the package predates maps to the fallback arm instead of failing. - test('video surface maps an unknown kind', () { - expect(surfaceFrom(null), isNull); - final pixels = surfaceFrom(PixelBufferMoqVideoSurface(7)); - expect((pixels as moq_video.PixelBuffer).pointer, 7); - expect(surfaceFrom(_FutureSurface()), isA()); - }); - // A fixed playout delay is reported back as is, and an estimated one moves as frames are read. test('audio consumer reports its playout delay', () async { final broadcast = BroadcastProducer(); @@ -1184,15 +1176,3 @@ void main() { broadcast.close(); }); } - -/// Stands in for a generated surface variant this package predates. -final class _FutureSurface extends MoqVideoSurface { - @override - RustBuffer lower() => throw UnimplementedError(); - - @override - int allocationSize() => throw UnimplementedError(); - - @override - int write(Uint8List buf) => throw UnimplementedError(); -} diff --git a/dart/moq_ffi/lib/src/moq.dart b/dart/moq_ffi/lib/src/moq.dart index 74bbb704978..adade58bd01 100644 --- a/dart/moq_ffi/lib/src/moq.dart +++ b/dart/moq_ffi/lib/src/moq.dart @@ -3238,14 +3238,12 @@ class FfiConverterMoqPosition { class MoqTrackInfo { final int priority; final Duration? maxAge; - final bool maxAgeUnlimited; final int? refresh; final int? timescale; final MoqCompression? compression; MoqTrackInfo({ this.priority = 0, - this.maxAge = null, - this.maxAgeUnlimited = false, + this.maxAge, this.refresh = null, this.timescale = null, this.compression = null, @@ -3269,11 +3267,6 @@ class FfiConverterMoqTrackInfo { ); final maxAge = maxAge_lifted.value; new_offset += maxAge_lifted.bytesRead; - final maxAgeUnlimited_lifted = FfiConverterBool.read( - Uint8List.view(buf.buffer, new_offset), - ); - final maxAgeUnlimited = maxAgeUnlimited_lifted.value; - new_offset += maxAgeUnlimited_lifted.bytesRead; final refresh_lifted = FfiConverterOptionalUInt32.read( Uint8List.view(buf.buffer, new_offset), ); @@ -3293,7 +3286,6 @@ class FfiConverterMoqTrackInfo { MoqTrackInfo( priority: priority, maxAge: maxAge, - maxAgeUnlimited: maxAgeUnlimited, refresh: refresh, timescale: timescale, compression: compression, @@ -3306,7 +3298,6 @@ class FfiConverterMoqTrackInfo { final total_length = FfiConverterInt8.allocationSize(value.priority) + FfiConverterOptionalDuration.allocationSize(value.maxAge) + - FfiConverterBool.allocationSize(value.maxAgeUnlimited) + FfiConverterOptionalUInt32.allocationSize(value.refresh) + FfiConverterOptionalUInt64.allocationSize(value.timescale) + FfiConverterOptionalMoqCompression.allocationSize(value.compression) + @@ -3326,10 +3317,6 @@ class FfiConverterMoqTrackInfo { value.maxAge, Uint8List.view(buf.buffer, new_offset), ); - new_offset += FfiConverterBool.write( - value.maxAgeUnlimited, - Uint8List.view(buf.buffer, new_offset), - ); new_offset += FfiConverterOptionalUInt32.write( value.refresh, Uint8List.view(buf.buffer, new_offset), @@ -3348,7 +3335,6 @@ class FfiConverterMoqTrackInfo { static int allocationSize(MoqTrackInfo value) { return FfiConverterInt8.allocationSize(value.priority) + FfiConverterOptionalDuration.allocationSize(value.maxAge) + - FfiConverterBool.allocationSize(value.maxAgeUnlimited) + FfiConverterOptionalUInt32.allocationSize(value.refresh) + FfiConverterOptionalUInt64.allocationSize(value.timescale) + FfiConverterOptionalMoqCompression.allocationSize(value.compression) + @@ -8657,41 +8643,7 @@ class OfflineMoqAnnounceEvent extends MoqAnnounceEvent { } } -enum MoqCompression { deflate } - -class FfiConverterMoqCompression { - static LiftRetVal read(Uint8List buf) { - final index = buf.buffer.asByteData(buf.offsetInBytes).getInt32(0); - switch (index) { - case 1: - return LiftRetVal(MoqCompression.deflate, 4); - default: - throw UniffiInternalError( - UniffiInternalError.unexpectedEnumCase, - "Unable to determine enum variant", - ); - } - } - - static MoqCompression lift(RustBuffer buffer) { - return FfiConverterMoqCompression.read(buffer.asUint8List()).value; - } - - static RustBuffer lower(MoqCompression input) { - return toRustBuffer(createUint8ListFromInt(input.index + 1)); - } - - static int allocationSize(MoqCompression _value) { - return 4; - } - - static int write(MoqCompression value, Uint8List buf) { - buf.buffer.asByteData(buf.offsetInBytes).setInt32(0, value.index + 1); - return 4; - } -} - -enum MoqTransport { quic, webSocket, tcp, unix, webTransport } +enum MoqTransport { quic, webSocket, tcp, unix, webTransport, unknown } class FfiConverterMoqTransport { static LiftRetVal read(Uint8List buf) { @@ -8707,6 +8659,8 @@ class FfiConverterMoqTransport { return LiftRetVal(MoqTransport.unix, 4); case 5: return LiftRetVal(MoqTransport.webTransport, 4); + case 6: + return LiftRetVal(MoqTransport.unknown, 4); default: throw UniffiInternalError( UniffiInternalError.unexpectedEnumCase, @@ -9010,42 +8964,6 @@ class ClosedMoqConnectionPhase extends MoqConnectionPhase { } } -enum MoqVideoCodec { h264, h265 } - -class FfiConverterMoqVideoCodec { - static LiftRetVal read(Uint8List buf) { - final index = buf.buffer.asByteData(buf.offsetInBytes).getInt32(0); - switch (index) { - case 1: - return LiftRetVal(MoqVideoCodec.h264, 4); - case 2: - return LiftRetVal(MoqVideoCodec.h265, 4); - default: - throw UniffiInternalError( - UniffiInternalError.unexpectedEnumCase, - "Unable to determine enum variant", - ); - } - } - - static MoqVideoCodec lift(RustBuffer buffer) { - return FfiConverterMoqVideoCodec.read(buffer.asUint8List()).value; - } - - static RustBuffer lower(MoqVideoCodec input) { - return toRustBuffer(createUint8ListFromInt(input.index + 1)); - } - - static int allocationSize(MoqVideoCodec _value) { - return 4; - } - - static int write(MoqVideoCodec value, Uint8List buf) { - buf.buffer.asByteData(buf.offsetInBytes).setInt32(0, value.index + 1); - return 4; - } -} - abstract class MoqVideoEncoderKind { RustBuffer lower(); int allocationSize(); @@ -9468,6 +9386,12 @@ class FfiConverterMoqVideoSurface { lifted.value, lifted.bytesRead - subview.offsetInBytes + 4, ); + case 2: + final lifted = UnknownMoqVideoSurface.read(subview); + return LiftRetVal( + lifted.value, + lifted.bytesRead - subview.offsetInBytes + 4, + ); default: throw UniffiInternalError( UniffiInternalError.unexpectedEnumCase, @@ -9527,6 +9451,34 @@ class PixelBufferMoqVideoSurface extends MoqVideoSurface { } } +class UnknownMoqVideoSurface extends MoqVideoSurface { + UnknownMoqVideoSurface(); + UnknownMoqVideoSurface._(); + static LiftRetVal read(Uint8List buf) { + int new_offset = buf.offsetInBytes; + return LiftRetVal(UnknownMoqVideoSurface._(), new_offset); + } + + @override + RustBuffer lower() { + final buf = Uint8List(allocationSize()); + write(buf); + return toRustBuffer(buf); + } + + @override + int allocationSize() { + return 4; + } + + @override + int write(Uint8List buf) { + buf.buffer.asByteData(buf.offsetInBytes).setInt32(0, 2); + int new_offset = buf.offsetInBytes + 4; + return new_offset; + } +} + abstract class MoqAudioCodecInterface {} final _MoqAudioCodecFinalizer = Finalizer>((ptr) { @@ -14750,6 +14702,135 @@ class FfiConverterMoqBroadcastRequests { } } +abstract class MoqCompressionInterface { + String name(); +} + +final _MoqCompressionFinalizer = Finalizer>((ptr) { + rustCall((status) => uniffi_moq_ffi_fn_free_moqcompression(ptr, status)); +}); + +class MoqCompression implements MoqCompressionInterface { + late final Pointer _ptr; + bool _isDisposed = false; + MoqCompression._(this._ptr) { + _MoqCompressionFinalizer.attach(this, _ptr, detach: this); + } + MoqCompression.deflate() + : _ptr = rustCall( + (status) => + uniffi_moq_ffi_fn_constructor_moqcompression_deflate(status), + null, + ) { + _MoqCompressionFinalizer.attach(this, _ptr, detach: this); + } + factory MoqCompression.lift(Pointer ptr) { + return MoqCompression._(ptr); + } + Pointer uniffiClonePointer() { + if (_isDisposed) { + throw StateError("Object has already been disposed"); + } + return rustCall( + (status) => uniffi_moq_ffi_fn_clone_moqcompression(_ptr, status), + ); + } + + void dispose() { + if (_isDisposed) { + return; + } + final status = calloc(); + _isDisposed = true; + _MoqCompressionFinalizer.detach(this); + try { + uniffi_moq_ffi_fn_free_moqcompression(_ptr, status); + checkCallStatus(NullRustCallStatusErrorHandler(), status); + } finally { + calloc.free(status); + } + } + + String debugString() { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqcompression_uniffi_trait_debug( + uniffiClonePointer(), + status, + ), + FfiConverterString.lift, + null, + ); + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + if (other is! MoqCompression) { + return false; + } + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqcompression_uniffi_trait_eq_eq( + uniffiClonePointer(), + FfiConverterMoqCompression.lower(other), + status, + ), + FfiConverterBool.lift, + null, + ); + } + + @override + int get hashCode { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqcompression_uniffi_trait_hash( + uniffiClonePointer(), + status, + ), + FfiConverterUInt64.lift, + null, + ); + } + + String name() { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqcompression_name( + uniffiClonePointer(), + status, + ), + FfiConverterString.lift, + null, + ); + } +} + +class FfiConverterMoqCompression { + static MoqCompression lift(Pointer ptr) { + return MoqCompression.lift(ptr); + } + + static Pointer lower(MoqCompression value) { + return value.uniffiClonePointer(); + } + + static int allocationSize(MoqCompression value) { + return 8; + } + + static LiftRetVal read(Uint8List buf) { + final handle = buf.buffer.asByteData(buf.offsetInBytes).getInt64(0); + final pointer = Pointer.fromAddress(handle); + return LiftRetVal(MoqCompression.lift(pointer), 8); + } + + static int write(MoqCompression value, Uint8List buf) { + final handle = lower(value); + buf.buffer.asByteData(buf.offsetInBytes).setInt64(0, handle.address); + return 8; + } +} + abstract class MoqFillInterface { MoqGroupProducer accept({required int sequence}); void dropGroups({required int start, required int end}); @@ -16767,6 +16848,86 @@ class FfiConverterMoqSocketTrackStream { } } +abstract class MoqVideoCodecInterface {} + +final _MoqVideoCodecFinalizer = Finalizer>((ptr) { + rustCall((status) => uniffi_moq_ffi_fn_free_moqvideocodec(ptr, status)); +}); + +class MoqVideoCodec implements MoqVideoCodecInterface { + late final Pointer _ptr; + bool _isDisposed = false; + MoqVideoCodec._(this._ptr) { + _MoqVideoCodecFinalizer.attach(this, _ptr, detach: this); + } + MoqVideoCodec.h264() + : _ptr = rustCall( + (status) => uniffi_moq_ffi_fn_constructor_moqvideocodec_h264(status), + null, + ) { + _MoqVideoCodecFinalizer.attach(this, _ptr, detach: this); + } + MoqVideoCodec.h265() + : _ptr = rustCall( + (status) => uniffi_moq_ffi_fn_constructor_moqvideocodec_h265(status), + null, + ) { + _MoqVideoCodecFinalizer.attach(this, _ptr, detach: this); + } + factory MoqVideoCodec.lift(Pointer ptr) { + return MoqVideoCodec._(ptr); + } + Pointer uniffiClonePointer() { + if (_isDisposed) { + throw StateError("Object has already been disposed"); + } + return rustCall( + (status) => uniffi_moq_ffi_fn_clone_moqvideocodec(_ptr, status), + ); + } + + void dispose() { + if (_isDisposed) { + return; + } + final status = calloc(); + _isDisposed = true; + _MoqVideoCodecFinalizer.detach(this); + try { + uniffi_moq_ffi_fn_free_moqvideocodec(_ptr, status); + checkCallStatus(NullRustCallStatusErrorHandler(), status); + } finally { + calloc.free(status); + } + } +} + +class FfiConverterMoqVideoCodec { + static MoqVideoCodec lift(Pointer ptr) { + return MoqVideoCodec.lift(ptr); + } + + static Pointer lower(MoqVideoCodec value) { + return value.uniffiClonePointer(); + } + + static int allocationSize(MoqVideoCodec value) { + return 8; + } + + static LiftRetVal read(Uint8List buf) { + final handle = buf.buffer.asByteData(buf.offsetInBytes).getInt64(0); + final pointer = Pointer.fromAddress(handle); + return LiftRetVal(MoqVideoCodec.lift(pointer), 8); + } + + static int write(MoqVideoCodec value, Uint8List buf) { + final handle = lower(value); + buf.buffer.asByteData(buf.offsetInBytes).setInt64(0, handle.address); + return 8; + } +} + abstract class MoqVideoConsumerInterface { void cancel(); UniffiRustFuture next(); @@ -22597,6 +22758,71 @@ uniffi_moq_ffi_fn_method_moqbroadcastrequests_requested_track( Pointer ptr, ); +@Native Function(Pointer, Pointer)>( + assetId: _uniffiAssetId, +) +external Pointer uniffi_moq_ffi_fn_clone_moqcompression( + Pointer handle, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_free_moqcompression( + Pointer handle, + Pointer uniffiStatus, +); + +@Native Function(Pointer)>( + assetId: _uniffiAssetId, +) +external Pointer uniffi_moq_ffi_fn_constructor_moqcompression_deflate( + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external RustBuffer uniffi_moq_ffi_fn_method_moqcompression_name( + Pointer ptr, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external RustBuffer uniffi_moq_ffi_fn_method_moqcompression_uniffi_trait_debug( + Pointer ptr, + Pointer uniffiStatus, +); + +@Native, Pointer, Pointer)>( + assetId: _uniffiAssetId, +) +external int uniffi_moq_ffi_fn_method_moqcompression_uniffi_trait_eq_eq( + Pointer ptr, + Pointer other, + Pointer uniffiStatus, +); + +@Native, Pointer, Pointer)>( + assetId: _uniffiAssetId, +) +external int uniffi_moq_ffi_fn_method_moqcompression_uniffi_trait_eq_ne( + Pointer ptr, + Pointer other, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external int uniffi_moq_ffi_fn_method_moqcompression_uniffi_trait_hash( + Pointer ptr, + Pointer uniffiStatus, +); + @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) @@ -23532,6 +23758,36 @@ external RustBuffer uniffi_moq_ffi_fn_method_moqsockettrackstream_session( Pointer uniffiStatus, ); +@Native Function(Pointer, Pointer)>( + assetId: _uniffiAssetId, +) +external Pointer uniffi_moq_ffi_fn_clone_moqvideocodec( + Pointer handle, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_free_moqvideocodec( + Pointer handle, + Pointer uniffiStatus, +); + +@Native Function(Pointer)>( + assetId: _uniffiAssetId, +) +external Pointer uniffi_moq_ffi_fn_constructor_moqvideocodec_h264( + Pointer uniffiStatus, +); + +@Native Function(Pointer)>( + assetId: _uniffiAssetId, +) +external Pointer uniffi_moq_ffi_fn_constructor_moqvideocodec_h265( + Pointer uniffiStatus, +); + @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) @@ -24619,6 +24875,9 @@ external int uniffi_moq_ffi_checksum_method_moqbroadcastrequests_datagrams(); external int uniffi_moq_ffi_checksum_method_moqbroadcastrequests_requested_track(); +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqcompression_name(); + @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqfill_accept(); @@ -24989,6 +25248,9 @@ external int uniffi_moq_ffi_checksum_constructor_moqoriginproducer_new(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_constructor_moqbroadcastproducer_new(); +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_constructor_moqcompression_deflate(); + @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_constructor_moqserver_new(); @@ -25007,6 +25269,12 @@ external int uniffi_moq_ffi_checksum_constructor_moqcongestioncontrol_none(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_constructor_moqsocketendpoint_new(); +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_constructor_moqvideocodec_h264(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_constructor_moqvideocodec_h265(); + @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_constructor_moqvideoconsumer_subscribe(); @@ -25533,6 +25801,9 @@ void _checkApiChecksums() { 42416) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } + if (uniffi_moq_ffi_checksum_method_moqcompression_name() != 61978) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } if (uniffi_moq_ffi_checksum_method_moqfill_accept() != 42158) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } @@ -25919,6 +26190,9 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_constructor_moqbroadcastproducer_new() != 2448) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } + if (uniffi_moq_ffi_checksum_constructor_moqcompression_deflate() != 31663) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } if (uniffi_moq_ffi_checksum_constructor_moqserver_new() != 49910) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } @@ -25940,6 +26214,12 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_constructor_moqsocketendpoint_new() != 25288) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } + if (uniffi_moq_ffi_checksum_constructor_moqvideocodec_h264() != 25757) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_constructor_moqvideocodec_h265() != 27465) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } if (uniffi_moq_ffi_checksum_constructor_moqvideoconsumer_subscribe() != 7811) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); diff --git a/demo/carla/sim/moq_carla_sim/publish.py b/demo/carla/sim/moq_carla_sim/publish.py index a471431d696..40c9d7b1e0f 100644 --- a/demo/carla/sim/moq_carla_sim/publish.py +++ b/demo/carla/sim/moq_carla_sim/publish.py @@ -185,7 +185,7 @@ class StatusPublisher: """ def __init__(self, broadcast: moq.BroadcastProducer) -> None: - track = broadcast.publish_track("status", moq.TrackInfo(timescale=1_000, compression=moq.Compression.DEFLATE)) + track = broadcast.publish_track("status", moq.TrackInfo(timescale=1_000, compression=moq.Compression.deflate())) self._catalog = moq.media.CatalogProducer(broadcast) self._producer = moq.json.SnapshotProducer(broadcast, track) # Weak: watching demand neither keeps the track open nor locks it. diff --git a/demo/carla/sim/tests/conftest.py b/demo/carla/sim/tests/conftest.py index b0845af8c01..7b48cff94a7 100644 --- a/demo/carla/sim/tests/conftest.py +++ b/demo/carla/sim/tests/conftest.py @@ -29,7 +29,7 @@ def update(self, value: object, timestamp: object) -> None: moq.Subscription = lambda **kwargs: SimpleNamespace(**kwargs) moq.Delay = lambda **kwargs: SimpleNamespace(**kwargs) moq.Order = SimpleNamespace(ASCENDING="ascending") -moq.Compression = SimpleNamespace(DEFLATE="deflate") +moq.Compression = SimpleNamespace(deflate=lambda: "deflate") # Tests that run a truck's endpoint script it in place of this. moq.socket = ModuleType("moq.socket") moq.Timestamp = lambda value, scale: SimpleNamespace(value=value, scale=scale) diff --git a/doc/lib/cpp/index.md b/doc/lib/cpp/index.md index 03f97e97982..eb1c1cc62bc 100644 --- a/doc/lib/cpp/index.md +++ b/doc/lib/cpp/index.md @@ -142,7 +142,7 @@ auto broadcast = route->broadcast(); auto audio = ok(moq::MediaTrackProducer::audio(broadcast, moq::MediaTarget::kNamed{}, {moq::AudioFormat::kOpus, opus_init})); ok(audio->write_frame({packet, moq::Timestamp{960, 48'000}})); // 20 ms -moq::VideoEncoderOutput output{moq::VideoCodec::kH264, std::nullopt, std::nullopt, moq::VideoEncoderKind::kAuto{}}; +moq::VideoEncoderOutput output{moq::VideoCodec::h264(), std::nullopt, std::nullopt, moq::VideoEncoderKind::kAuto{}}; auto catalog = ok(moq::MediaCatalogProducer::init(broadcast)); auto video = ok(moq::VideoProducer::init(catalog, {{moq::VideoPixelFormat::kRgba, 1280, 720, {30000, 1001}}, output, "camera", nullptr})); ok(video->write({{0, 30'000}, rgba})); @@ -231,11 +231,11 @@ screen.reset(); // stopped watching: its share returns to camera ## Compressed tracks -`moq::TrackInfo::compression` set to DEFLATE on a raw track sends each group DEFLATE-compressed to opt-in `moq-lite-07-wip` peers; other peers, and every reader here, get the original frames. +`moq::TrackInfo::compression` set to `moq::Compression::deflate()` on a raw track sends each group DEFLATE-compressed to opt-in `moq-lite-07-wip` peers; other peers, and every reader here, get the original frames. ## Subscription defaults -Start every subscription from `moq::subscription_defaults()` and change its fields. It holds moq-net's defaults, a zero `delay` that starts at the newest group and skips a superseded one at once, and passing `std::nullopt` for a subscription means the same. A bare `moq::Subscription{}` does not: the generated records carry no duration defaults, so its unset `delay.max` sets no subscriber limit and its unset `delay.min` leaves the target latency unstated. +Start every subscription from `moq::subscription_defaults()` and change its fields. It holds moq-net's defaults, a zero `delay` that starts at the newest group and skips a superseded one at once, and passing `std::nullopt` for a subscription means the same. A bare `moq::Subscription{}` does not: the generated records carry no duration defaults, so its unset `delay.max` sets no subscriber limit and its unset `delay.min` leaves the target latency unstated. Likewise a bare `moq::TrackInfo{}` leaves `max_age` unset, which sets no publisher limit, while passing `std::nullopt` for the info keeps moq-net's zero, which serves only the live edge; set `max_age` to zero to keep that default in a record. ## Track demand diff --git a/doc/lib/dart/index.md b/doc/lib/dart/index.md index 15173e1d06a..5980e26795e 100644 --- a/doc/lib/dart/index.md +++ b/doc/lib/dart/index.md @@ -18,7 +18,7 @@ Import `package:moq/media.dart` with a prefix for catalogs, encoded-media import container consumers. `TrackProducer.audio` / `.video` take a broadcast, an init record, and a `Named` or `Requested` target. `CatalogProducer(broadcast: ...)` owns catalog properties and sections; it holds the broadcast weakly and fails after the broadcast closes. -Publish JSON tracks with `MoqTrackInfo(compression: MoqCompression.deflate)`; a `package:moq/json.dart` consumer reads one with no option of its own. +Publish JSON tracks with `TrackInfo(compression: Compression.deflate())`; a `package:moq/json.dart` consumer reads one with no option of its own. Every write takes a timestamp, and the library never substitutes zero or now. `SnapshotProducer.update`, `StreamProducer.append`, and `WindowProducer.push` and `pop` require a timestamp on the broadcast clock (`CatalogProducer.now()`), the epoch every track in the broadcast shares, so their track needs a timescale. `package:moq/json.dart` consumers return `Value` (`value`, `timestamp`) from `next()`; a snapshot consumer @@ -26,7 +26,8 @@ yields each state in order, and `latest()` skips to the newest. Media times are exact `Timestamp` records, `value` units at `scale` units per second, so a 90 kHz tick survives a read and republish. `Duration.toTimestamp()` converts exactly; `Timestamp.toDuration()` rounds down to a whole microsecond. A raw track with a `null` timescale is untimed: each frame carries `Timestamp.unscaled(key)`, its group's key, whose `scale` is `null`. -`MoqTrackInfo.compression` set to `MoqCompression.deflate` on a raw track sends each group DEFLATE-compressed to opt-in `moq-lite-07-wip` peers; other peers, and every reader here, get the original frames. +`TrackInfo`'s `maxAge`, how long a superseded group stays fresh, defaults to zero, which serves only the live edge; an explicit `null` sets no publisher limit, as it does for `Delay.max`. The generated `MoqTrackInfo` leaves an omitted `maxAge` null instead. +`TrackInfo.compression` set to `Compression.deflate()` on a raw track sends each group DEFLATE-compressed to opt-in `moq-lite-07-wip` peers; other peers, and every reader here, get the original frames. Whole-frame media writes require caller time; container imports keep their own timeline handling. Timed raw/data tracks require caller-supplied timestamps. Use `CatalogProducer.now()` to stamp a locally created event on the broadcast clock; reading it fixes that clock for later media producers. @@ -94,7 +95,7 @@ final encoder = video.Producer( framerate: video.FrameRate(numerator: 30000, denominator: 1001), ), output: video.EncoderOutput( - codec: video.Codec.h264, + codec: video.Codec.h264(), kind: video.AutoEncoder(), ), track: 'camera', diff --git a/doc/lib/go/index.md b/doc/lib/go/index.md index c1b631341df..67812fa4704 100644 --- a/doc/lib/go/index.md +++ b/doc/lib/go/index.md @@ -21,7 +21,7 @@ catalog writes fail with `ErrClosed` after the broadcast closes. Media timestamp `TimestampFromScale` and `TimestampFromDuration` build one exactly; `TimestampToDuration` rounds down to a whole nanosecond. Every write takes a timestamp, and the library never substitutes zero or now. A raw track with a `nil` timescale is untimed: each frame carries `moq.Unscaled(key)`, its group's key, whose `Scale` is `nil`. -`TrackInfo.Compression` set to `CompressionDeflate` sends each group DEFLATE-compressed to opt-in `moq-lite-07-wip` peers; other peers, and every reader here, get the original frames. Set it on JSON tracks. +`TrackInfo.Compression` set to `DeflateCompression()` sends each group DEFLATE-compressed to opt-in `moq-lite-07-wip` peers; other peers, and every reader here, get the original frames. Set it on JSON tracks. The JSON producers' `Update`, `Append`, `Push`, and `Pop` take a final `moq.Timestamp` on the broadcast clock, the epoch every track in the broadcast shares, so their track needs a timescale. JSON consumers return a `*Timed` holding the value and that timestamp; `SnapshotConsumer.Latest` skips to the newest state where `Next` yields each one. A read timestamp is at the track's timescale. @@ -106,7 +106,7 @@ track := "camera" catalogProducer, _ := moqmedia.NewCatalogProducer(broadcast) video, _ := moqvideo.NewProducer(catalogProducer, moqvideo.ProducerOptions{ Input: moqvideo.EncoderInput{Format: moq.VideoPixelFormatRgba, Width: 1280, Height: 720, Framerate: moqvideo.FrameRate{Numerator: 30000, Denominator: 1001}}, - Output: moqvideo.EncoderOutput{Codec: moq.VideoCodecH264, Kind: moq.AutoEncoder()}, + Output: moqvideo.EncoderOutput{Codec: moq.H264VideoCodec(), Kind: moq.AutoEncoder()}, Track: &track, }) _ = video.Write(moqvideo.Frame{Timestamp: moq.TimestampFromScale(pts, 90_000), Data: rgba}) diff --git a/doc/lib/kt/index.md b/doc/lib/kt/index.md index f65d08fec2b..107fb69749c 100644 --- a/doc/lib/kt/index.md +++ b/doc/lib/kt/index.md @@ -16,7 +16,7 @@ x86\_64) and desktop JVM (Linux x86\_64/aarch64, macOS arm64, Windows x64). `dev.moq.media` owns catalogs, encoded imports, and container consumers. `TrackProducer.audio` / `.video` take a broadcast, a `Named` or `Requested` target, and an init record. `CatalogProducer(broadcast)` holds its broadcast weakly and fails with `Closed` after it closes. -Publish JSON tracks with `TrackInfo(compression = Compression.DEFLATE)`; a `dev.moq.json` consumer reads one with no option of its own. +Publish JSON tracks with `TrackInfo(maxAge = Duration.ZERO, compression = Compression.deflate())`; a `dev.moq.json` consumer reads one with no option of its own. Every write takes a timestamp, and the library never substitutes zero or now. `SnapshotProducer.update`, `StreamProducer.append`, and `WindowProducer.push` and `pop` require a timestamp on the broadcast clock (`CatalogProducer.now()`), the epoch every track in the broadcast shares, so their track needs a timescale. `dev.moq.json` consumers' `values()` emits `Value` (`value`, `timestamp`) and `valuesAs()` emits `Timed`; @@ -24,7 +24,8 @@ a snapshot consumer yields each state in order, and `latest()` skips to the newe A `Timestamp(value, scale)` is exact and reads back at the track's timescale, so a 90 kHz tick republishes unchanged. `Duration.toTimestamp()` is exact at nanosecond scale; `Timestamp.toDuration()` rounds down to a whole nanosecond. A raw track with a `null` timescale is untimed: each frame carries `Timestamp.unscaled(key)`, its group's key, whose `scale` is `null`. -`MoqTrackInfo.compression` set to `DEFLATE` on a raw track sends each group DEFLATE-compressed to opt-in `moq-lite-07-wip` peers; other peers, and every reader here, get the original frames. +`TrackInfo` names `maxAge` (a `java.time.Duration`), how long a superseded group stays fresh: `Duration.ZERO` serves only the live edge, and `null` sets no publisher limit, as `null` does for `Delay.max`. +`TrackInfo.compression` set to `Compression.deflate()` on a raw track sends each group DEFLATE-compressed to opt-in `moq-lite-07-wip` peers; other peers, and every reader here, get the original frames. Whole-frame media writes require caller time; container imports keep their own timeline handling. Timed raw/data tracks require caller-supplied timestamps. Use `CatalogProducer.now()` to stamp a locally created event on the broadcast clock; reading it fixes that clock for later media producers. @@ -83,7 +84,7 @@ Moq.connect("https://relay.example.com").use { moq -> val video = dev.moq.video.Producer( CatalogProducer(broadcast), dev.moq.video.ProducerOptions(input = VideoEncoderInput(format = VideoPixelFormat.RGBA, width = 1280u, height = 720u, framerate = dev.moq.video.FrameRate(30000u, 1001u)), - output = VideoEncoderOutput(codec = VideoCodec.H264, bitrate = null, join = null, kind = autoEncoder), track = "camera"), + output = VideoEncoderOutput(codec = VideoCodec.h264(), bitrate = null, join = null, kind = autoEncoder), track = "camera"), ) video.write(VideoFrame(timestamp = pts, data = rgba)) route.announce() // the route mints its own instance: route.instance() diff --git a/doc/lib/py/index.md b/doc/lib/py/index.md index 7e05799070e..7729e5b2e07 100644 --- a/doc/lib/py/index.md +++ b/doc/lib/py/index.md @@ -28,7 +28,7 @@ Every write takes a timestamp, and the library never substitutes zero or now. JSON consumers yield `moq.json.Timed(value, timestamp)`; a snapshot consumer yields each state in order, and `await consumer.latest()` skips to the newest. A window consumer's value is a `WindowEventPush`, `WindowEventPop`, or `WindowEventSkip`. A raw track with a `None` timescale is untimed: each frame carries `moq.Timestamp.unscaled(key)`, its group's key, whose `scale` is `None`. -`TrackInfo(compression=moq.Compression.DEFLATE)` sends each group DEFLATE-compressed to opt-in `moq-lite-07-wip` peers; other peers, and every reader here, get the original frames. Set it on JSON tracks. +`TrackInfo(compression=moq.Compression.deflate())` sends each group DEFLATE-compressed to opt-in `moq-lite-07-wip` peers; other peers, and every reader here, get the original frames. Set it on JSON tracks. The JSON producers' `update`, `append`, `push`, and `pop` require a `timestamp` on the broadcast clock, the epoch every track in the broadcast shares, so their track needs a timescale. Whole-frame media writes require caller time; container imports keep their own timeline handling. Timed raw/data tracks require caller-supplied timestamps. Use `CatalogProducer.now()` to stamp a locally @@ -86,7 +86,7 @@ async def main(): catalog_producer, moq.VideoEncoderInput(format=moq.VideoPixelFormat.RGBA, width=1280, height=720, framerate=moq.video.FrameRate(numerator=30000, denominator=1001)), moq.VideoEncoderOutput( - codec=moq.VideoCodec.H264, + codec=moq.VideoCodec.h264(), kind=moq.VideoEncoderKind.AUTO(), # pyright: ignore[reportArgumentType] ), track="camera", @@ -96,7 +96,7 @@ async def main(): # Raw bytes and JSON events = broadcast.publish_track("events") events.write_frame(b'{"cmd": "ready"}', moq.Timestamp.unscaled(0)) # untimed: the first group's key - status_track = broadcast.publish_track("status", moq.TrackInfo(timescale=1_000, compression=moq.Compression.DEFLATE)) + status_track = broadcast.publish_track("status", moq.TrackInfo(timescale=1_000, compression=moq.Compression.deflate())) status = moq.json.SnapshotProducer(broadcast, status_track) status.update({"state": "live", "viewers": 42}, catalog_producer.now()) diff --git a/doc/lib/swift/index.md b/doc/lib/swift/index.md index 81d3667ff02..02525f24e6a 100644 --- a/doc/lib/swift/index.md +++ b/doc/lib/swift/index.md @@ -20,13 +20,14 @@ Its writes fail after closing or releasing the broadcast. Media timestamps are exact `Timestamp` records, `value` units at `scale` units per second, carried at the track's timescale (a write at another scale rounds down to it). On macOS 13+ and iOS, `try Timestamp(duration)` converts a `Duration` exactly, and `try timestamp.duration` rounds down to a whole attosecond. -Publish JSON tracks with `TrackInfo(compression: .deflate)`; a `Json` consumer reads one with no option of its own. +Publish JSON tracks with `TrackInfo(maxAge: 0, compression: Compression.deflate())`; a `Json` consumer reads one with no option of its own. Every write takes a timestamp, and the library never substitutes zero or now. `Json.SnapshotProducer.update`, `Json.StreamProducer.append`, and `Json.WindowProducer.push` and `pop` require a timestamp on the broadcast clock (`Media.CatalogProducer.now()`), the epoch every track in the broadcast shares, so their track needs a timescale. `Json` consumers yield `Json.Timed` (`value`, `timestamp`); a snapshot consumer yields each state in order, and `latest()` skips to the newest. A raw track with a `nil` timescale is untimed: each frame carries `Timestamp.unscaled(key)`, its group's key, whose `scale` is `nil`. -`MoqTrackInfo.compression` set to `.deflate` on a raw track sends each group DEFLATE-compressed to opt-in `moq-lite-07-wip` peers; other peers, and every reader here, get the original frames. +`TrackInfo` names `maxAge`, how long a superseded group stays fresh: `0` serves only the live edge, and `nil` sets no publisher limit, as `nil` does for `Delay.max`. +`TrackInfo.compression` set to `Compression.deflate()` on a raw track sends each group DEFLATE-compressed to opt-in `moq-lite-07-wip` peers; other peers, and every reader here, get the original frames. Whole-frame media writes require caller time; container imports keep their own timeline handling. Timed raw/data tracks require caller-supplied timestamps. Use `Media.CatalogProducer.now()` to stamp a locally created event on the broadcast clock; reading it fixes that clock for later media producers. @@ -80,7 +81,7 @@ try audio.cut() // audio has no keyframes, so this is what gives it groups let video = try Video.Producer( catalog: Media.CatalogProducer(broadcast: broadcast), input: VideoEncoderInput(format: .rgba, width: 1280, height: 720, framerate: Video.FrameRate(numerator: 30000, denominator: 1001)), - output: VideoEncoderOutput(codec: .h264, kind: .auto), + output: VideoEncoderOutput(codec: VideoCodec.h264(), kind: .auto), track: "camera" ) try video.write(VideoFrame(timestamp: pts, data: rgba)) diff --git a/go/wrapper/README.md b/go/wrapper/README.md index ccc2ae9ee9a..525a15c0421 100644 --- a/go/wrapper/README.md +++ b/go/wrapper/README.md @@ -146,8 +146,7 @@ broadcast := route.Broadcast() // Every JSON write is stamped, so the track is timed. JSON is small and repetitive, so // compress it on the wire. scale := uint64(1_000) -deflate := moq.CompressionDeflate -track, _ := broadcast.PublishTrack("status", &moq.TrackInfo{Timescale: &scale, Compression: &deflate}) +track, _ := broadcast.PublishTrack("status", &moq.TrackInfo{Timescale: &scale, Compression: moq.DeflateCompression()}) status, _ := moqjson.NewSnapshotProducer(broadcast, track, moqjson.SnapshotOptions{}) catalog, _ := moqmedia.NewCatalogProducer(broadcast) now, _ := catalog.Now() diff --git a/go/wrapper/json/json_test.go b/go/wrapper/json/json_test.go index 0613367dbf2..21fc13328e0 100644 --- a/go/wrapper/json/json_test.go +++ b/go/wrapper/json/json_test.go @@ -57,8 +57,7 @@ func TestTracks(t *testing.T) { broadcast, consumer := newBroadcast(t) scale := uint64(1_000_000) - deflate := moq.CompressionDeflate - track, err := broadcast.PublishTrack("status", &moq.TrackInfo{Timescale: &scale, Compression: &deflate}) + track, err := broadcast.PublishTrack("status", &moq.TrackInfo{Timescale: &scale, Compression: moq.DeflateCompression()}) if err != nil { t.Fatal(err) } @@ -138,8 +137,7 @@ func TestWindow(t *testing.T) { broadcast, consumer := newBroadcast(t) scale := uint64(1_000_000) - deflate := moq.CompressionDeflate - track, err := broadcast.PublishTrack("log", &moq.TrackInfo{Timescale: &scale, Compression: &deflate}) + track, err := broadcast.PublishTrack("log", &moq.TrackInfo{Timescale: &scale, Compression: moq.DeflateCompression()}) if err != nil { t.Fatal(err) } diff --git a/go/wrapper/moq_test.go b/go/wrapper/moq_test.go index b26217b31e4..beb66694860 100644 --- a/go/wrapper/moq_test.go +++ b/go/wrapper/moq_test.go @@ -449,7 +449,7 @@ func testDecodeVideoFrame(t *testing.T, surface bool) { } video, err := moqvideo.NewProducer(catalogProducer, moqvideo.ProducerOptions{ Input: moqvideo.EncoderInput{Format: moq.VideoPixelFormatRgba, Width: 320, Height: 240, Framerate: moqvideo.FrameRate{Numerator: 30000, Denominator: 1001}}, - Output: moqvideo.EncoderOutput{Codec: moq.VideoCodecH264, Kind: moq.SoftwareEncoder()}, + Output: moqvideo.EncoderOutput{Codec: moq.H264VideoCodec(), Kind: moq.SoftwareEncoder()}, Track: &track, Bandwidth: nil, }) diff --git a/go/wrapper/records.go b/go/wrapper/records.go index fdc03bdda23..47ba35468c0 100644 --- a/go/wrapper/records.go +++ b/go/wrapper/records.go @@ -176,7 +176,7 @@ type TrackInfo struct { // only the live edge. MaxAge time.Duration // MaxAgeUnlimited ignores MaxAge and sets no publisher limit, leaving only the - // cache to bound how long a superseded group is served. + // cache to bound how long a superseded group is served: the ffi record's null MaxAge. MaxAgeUnlimited bool Refresh *uint32 Timescale *uint64 @@ -188,11 +188,10 @@ func trackInfoFFI(info *TrackInfo) (*ffi.MoqTrackInfo, error) { return nil, nil } out := &ffi.MoqTrackInfo{ - Priority: info.Priority, - MaxAgeUnlimited: info.MaxAgeUnlimited, - Refresh: info.Refresh, - Timescale: info.Timescale, - Compression: info.Compression, + Priority: info.Priority, + Refresh: info.Refresh, + Timescale: info.Timescale, + Compression: info.Compression, } if !info.MaxAgeUnlimited { out.MaxAge = &info.MaxAge @@ -203,12 +202,12 @@ func trackInfoFFI(info *TrackInfo) (*ffi.MoqTrackInfo, error) { func trackInfoFromFFI(info ffi.MoqTrackInfo) TrackInfo { out := TrackInfo{ Priority: info.Priority, - MaxAgeUnlimited: info.MaxAgeUnlimited, + MaxAgeUnlimited: info.MaxAge == nil, Refresh: info.Refresh, Timescale: info.Timescale, Compression: info.Compression, } - if info.MaxAge != nil && !info.MaxAgeUnlimited { + if info.MaxAge != nil { out.MaxAge = *info.MaxAge } return out diff --git a/go/wrapper/server.go b/go/wrapper/server.go index b445052e8d6..dcb355d28af 100644 --- a/go/wrapper/server.go +++ b/go/wrapper/server.go @@ -23,6 +23,8 @@ const ( TransportUnix = ffi.MoqTransportUnix // TransportWebTransport is a session that arrived over WebTransport (HTTP/3). TransportWebTransport = ffi.MoqTransportWebTransport + // TransportUnknown is a session that arrived over a transport this version cannot name yet. + TransportUnknown = ffi.MoqTransportUnknown ) // Request is an incoming session that can be accepted (Accept) or rejected (Reject). diff --git a/go/wrapper/subscribe.go b/go/wrapper/subscribe.go index 2d8f116b4cd..95dc964acbc 100644 --- a/go/wrapper/subscribe.go +++ b/go/wrapper/subscribe.go @@ -209,38 +209,22 @@ func (f *VideoDecodedFrame) Pixels(format VideoPixelFormat) ([]byte, error) { // memory. Only a video.Consumer with DecoderOutput.Surface set produces one, // and it stays valid until Close. func (f *VideoDecodedFrame) Surface() VideoSurface { - return videoSurface(f.inner.Surface()) -} - -// VideoSurface is a decoded frame's platform surface: VideoSurfacePixelBuffer on macOS and iOS. -// Switch on it with a default case, since new platforms add kinds. -type VideoSurface interface { - isVideoSurface() -} - -// VideoSurfacePixelBuffer is an Apple CVPixelBufferRef (IOSurface-backed NV12), as the address in Pointer. -type VideoSurfacePixelBuffer struct { - Pointer uint64 -} - -// VideoSurfaceUnknown is a surface kind this version of the package does not know yet. -type VideoSurfaceUnknown struct{} - -func (VideoSurfacePixelBuffer) isVideoSurface() {} -func (VideoSurfaceUnknown) isVideoSurface() {} - -func videoSurface(surface *ffi.MoqVideoSurface) VideoSurface { - if surface == nil { - return nil - } - switch surface := (*surface).(type) { - case ffi.MoqVideoSurfacePixelBuffer: - return VideoSurfacePixelBuffer{Pointer: surface.Pointer} - default: - return VideoSurfaceUnknown{} + if surface := f.inner.Surface(); surface != nil { + return *surface } + return nil } +type ( + // VideoSurface is a decoded frame's platform surface: VideoSurfacePixelBuffer on macOS and + // iOS, or VideoSurfaceUnknown for a kind this version cannot name yet. + VideoSurface = ffi.MoqVideoSurface + // VideoSurfacePixelBuffer is an Apple CVPixelBufferRef (IOSurface-backed NV12), as the address in Pointer. + VideoSurfacePixelBuffer = ffi.MoqVideoSurfacePixelBuffer + // VideoSurfaceUnknown is a surface kind this version of the package cannot name yet. + VideoSurfaceUnknown = ffi.MoqVideoSurfaceUnknown +) + // Close releases the frame's surface back to the decoder. func (f *VideoDecodedFrame) Close() { f.inner.Destroy() diff --git a/go/wrapper/subscribe_internal_test.go b/go/wrapper/subscribe_internal_test.go deleted file mode 100644 index c6eaf3902c3..00000000000 --- a/go/wrapper/subscribe_internal_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package moq - -import ( - "testing" - - ffi "moq.dev/moq-ffi/moq" -) - -// futureSurface stands in for an ffi surface variant this wrapper predates. -type futureSurface struct{} - -func (futureSurface) Destroy() {} - -func TestVideoSurfaceUnknown(t *testing.T) { - if got := videoSurface(nil); got != nil { - t.Fatalf("videoSurface(nil) = %#v, want nil", got) - } - var pixels ffi.MoqVideoSurface = ffi.MoqVideoSurfacePixelBuffer{Pointer: 7} - if got := videoSurface(&pixels); got != (VideoSurfacePixelBuffer{Pointer: 7}) { - t.Fatalf("videoSurface(PixelBuffer) = %#v", got) - } - var future ffi.MoqVideoSurface = futureSurface{} - if got := videoSurface(&future); got != (VideoSurfaceUnknown{}) { - t.Fatalf("videoSurface(future) = %#v, want VideoSurfaceUnknown", got) - } -} diff --git a/go/wrapper/types.go b/go/wrapper/types.go index a38b8625881..27003c5b850 100644 --- a/go/wrapper/types.go +++ b/go/wrapper/types.go @@ -73,11 +73,14 @@ type ( AnchorTime = ffi.MoqAnchorTime // Order is which of a subscription's pending groups the publisher sends first. Order = ffi.MoqOrder - // Compression is how a track's frames are compressed on the wire: CompressionDeflate. + // Compression is how a track's frames are compressed on the wire. Build one with + // DeflateCompression, and compare a received one by Name; a new compression joins as a + // new builder. Compression = ffi.MoqCompression // Position is a location within a track: a group sequence and a frame index in it. Position = ffi.MoqPosition - // VideoCodec identifies a published video track's codec: H.264 or H.265. + // VideoCodec selects the video encoder codec. Build one with H264VideoCodec or + // H265VideoCodec; adding a codec later adds a constructor, not a breaking enum change. VideoCodec = ffi.MoqVideoCodec // VideoPixelFormat is a CPU pixel layout (I420 or RGBA): written to video.Producer, or read from a VideoDecodedFrame. VideoPixelFormat = ffi.MoqVideoPixelFormat @@ -120,14 +123,16 @@ const ( VideoPixelFormatRgba = ffi.MoqVideoPixelFormatRgba ) -// VideoCodec values: the codec a published video track is encoded to. -const ( - // VideoCodecH264 publishes H.264 / AVC as an avc3 track. - VideoCodecH264 = ffi.MoqVideoCodecH264 - // VideoCodecH265 publishes H.265 / HEVC as a hev1 track. Hardware only, so it - // fails where no hardware encoder is available. - VideoCodecH265 = ffi.MoqVideoCodecH265 -) +// H264VideoCodec publishes H.264 / AVC as an avc3 track. +func H264VideoCodec() *VideoCodec { + return ffi.MoqVideoCodecH264() +} + +// H265VideoCodec publishes H.265 / HEVC as a hev1 track. Hardware only, so it +// fails where no hardware encoder is available. +func H265VideoCodec() *VideoCodec { + return ffi.MoqVideoCodecH265() +} // AutoEncoder prefers a platform hardware encoder, falling back to software. func AutoEncoder() VideoEncoderKind { @@ -160,11 +165,10 @@ const ( OrderDescending = ffi.MoqOrderDescending ) -// Compression values: how a track's frames are compressed on the wire. -const ( - // CompressionDeflate makes each group one DEFLATE stream, which suits small, repetitive frames like JSON. - CompressionDeflate = ffi.MoqCompressionDeflate -) +// DeflateCompression makes each group one DEFLATE stream, which suits small, repetitive frames like JSON. +func DeflateCompression() *Compression { + return ffi.MoqCompressionDeflate() +} // LossCongestionControl is loss-based (CUBIC): it chases throughput, so the send rate sawtooths. func LossCongestionControl() *CongestionControl { diff --git a/go/wrapper/video/video.go b/go/wrapper/video/video.go index e431be7fe4c..b98b1bfc005 100644 --- a/go/wrapper/video/video.go +++ b/go/wrapper/video/video.go @@ -13,8 +13,8 @@ import ( "moq.dev/moq/media" ) -// Codec selects H.264 or H.265. -type Codec = ffi.MoqVideoCodec +// Codec selects the video codec; build one with moq.H264VideoCodec or moq.H265VideoCodec. +type Codec = *ffi.MoqVideoCodec // PixelFormat is a CPU pixel layout (I420 or RGBA). type PixelFormat = ffi.MoqVideoPixelFormat diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt index feb00115144..1bd3e37c5dc 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt @@ -268,7 +268,8 @@ typealias FetchGroupOptions = uniffi.moq.MoqFetchGroupOptions typealias TrackInfo = uniffi.moq.MoqTrackInfo /** - * How a track's frames are compressed on the wire: `DEFLATE`, or `null` in [TrackInfo] for none. + * How a track's frames are compressed on the wire: `Compression.deflate()`, or `null` in + * [TrackInfo] for none. Compare a received one with `==` or by `name()`. */ typealias Compression = uniffi.moq.MoqCompression @@ -307,7 +308,7 @@ typealias AudioEncoderOutput = uniffi.moq.MoqAudioEncoderOutput /** One video frame: pixels in the configured layout plus a presentation timestamp. */ typealias VideoFrame = uniffi.moq.MoqVideoFrame -/** A video codec identifier (H.264 or H.265). */ +/** Selects the video encoder codec. Build one with `VideoCodec.h264()` or `VideoCodec.h265()`. */ typealias VideoCodec = uniffi.moq.MoqVideoCodec /** @@ -407,7 +408,7 @@ typealias ProtocolError = uniffi.moq.MoqProtocolError // directly. `dev.moq.media.Container` aliases `MoqContainer` for signatures, but its // variants still need the full name (`uniffi.moq.MoqContainer.Loc`). Enums // (AudioFormat) are fine: entry access through the alias works. Objects -// (AudioCodec) expose constructors through the alias (`AudioCodec.opus()`). +// (AudioCodec, VideoCodec, Compression) expose constructors through the alias (`AudioCodec.opus()`). /** Writes live datagrams with an independent sequence counter and no cache. */ typealias DatagramProducer = uniffi.moq.MoqDatagramProducer diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/json/Tracks.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/json/Tracks.kt index 0c91326308b..6635ef706e0 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/json/Tracks.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/json/Tracks.kt @@ -4,14 +4,14 @@ package dev.moq.json // producer takes over a `dev.moq.TrackProducer` (the snapshot and stream // producers also advertise it in the broadcast's catalog, which has no window // mode), and a consumer takes over a `dev.moq.TrackConsumer` that has not read -// a group yet. Compression is the track's, set through `TrackInfo(compression = -// Compression.DEFLATE)`. +// a group yet. Compression is the track's, set through `TrackInfo(maxAge = Duration.ZERO, +// compression = Compression.deflate())`. // Every write (a snapshot update, a stream append, a window push or pop) takes a // timestamp on the broadcast clock, the epoch every track in the broadcast // shares, so the track needs a timescale; one without is refused: // -// val track = broadcast.publishTrack("status", TrackInfo(timescale = 1_000uL, compression = -// Compression.DEFLATE)) +// val track = broadcast.publishTrack("status", TrackInfo(maxAge = Duration.ZERO, +// timescale = 1_000uL, compression = Compression.deflate())) // val status = SnapshotProducer(broadcast, track, SnapshotConfig()) // status.update(Status(state = "live"), CatalogProducer(broadcast).now()) // val reader = SnapshotConsumer(consumer, "status") diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/video/Video.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/video/Video.kt index 2ca7a8e341b..3556ce4e78b 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/video/Video.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/video/Video.kt @@ -32,7 +32,7 @@ typealias Frame = uniffi.moq.MoqVideoFrame /** One encoded access unit from an [Encoder]. */ typealias Packet = uniffi.moq.MoqVideoPacket -/** H.264 or H.265. */ +/** Selects the video encoder codec. Build one with `Codec.h264()` or `Codec.h265()`. */ typealias Codec = uniffi.moq.MoqVideoCodec /** A CPU pixel layout (I420 or RGBA). */ @@ -122,26 +122,16 @@ class DecodedFrame internal constructor(private val inner: uniffi.moq.MoqVideoDe fun pixels(format: PixelFormat): ByteArray = inner.pixels(format) /** The decoder's platform surface, or null when the frame is in CPU memory. */ - fun surface(): Surface? = inner.surface()?.let(Surface::from) + fun surface(): Surface? = inner.surface() /** Release the frame's surface back to the decoder. */ override fun close() = inner.close() } /** - * The platform image backing a [DecodedFrame], when [DecoderOutput] asked for one. Match it with an - * `else` branch, since new platforms add kinds. + * The platform image backing a [DecodedFrame], when [DecoderOutput] asked for one: a + * `uniffi.moq.MoqVideoSurface.PixelBuffer` (macOS and iOS), valid while its frame lives, or + * `uniffi.moq.MoqVideoSurface.Unknown` for a kind this version cannot name yet. Kotlin can't reach + * a sealed type's subtypes through this alias, so match on the full names. */ -abstract class Surface internal constructor() { - /** A borrowed `CVPixelBufferRef` address (macOS and iOS), valid while its frame lives. */ - data class PixelBuffer(val pointer: ULong) : Surface() - - /** A surface kind this version of the package does not know yet. */ - data object Unknown : Surface() - - internal companion object { - /** Maps a generated surface, so a variant this package predates is [Unknown]. */ - fun from(surface: MoqVideoSurface): Surface = - (surface as? MoqVideoSurface.PixelBuffer)?.let { PixelBuffer(it.pointer) } ?: Unknown - } -} +typealias Surface = MoqVideoSurface diff --git a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt index 25e55244b5b..16b99ba1803 100644 --- a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt +++ b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt @@ -315,7 +315,7 @@ class SmokeTest { @Test fun `broadcast consumer fetches cached group`() = runTest { BroadcastProducer().use { broadcast -> - val track = broadcast.publishTrack("events", TrackInfo(timescale = 1_000_000uL)) + val track = broadcast.publishTrack("events", TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000_000uL)) val group = track.appendGroup() group.writeFrame( Frame( @@ -351,7 +351,7 @@ class SmokeTest { val track = broadcast.publishTrack( "backlog", - TrackInfo(maxAgeUnlimited = true, timescale = 1_000_000uL), + TrackInfo(maxAge = null, timescale = 1_000_000uL), ) for (ms in 0uL until 3uL) { val group = track.appendGroup() @@ -405,7 +405,7 @@ class SmokeTest { @Test fun `readFrame skips empty then populated groups`() = runTest { BroadcastProducer().use { broadcast -> - val track = broadcast.publishTrack("status", TrackInfo(timescale = 1_000_000uL)) + val track = broadcast.publishTrack("status", TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000_000uL)) val consumer = track.consume(null) track.appendGroup().finish() track.appendGroup().finish() @@ -439,17 +439,16 @@ class SmokeTest { } @Test - fun `an omitted max age is zero and the unlimited flag sets none`() { + fun `an omitted info has a zero max age and a null one sets none`() { BroadcastProducer().use { broadcast -> val omitted = broadcast.publishTrack("omitted", null).consume(null).info() assertEquals(java.time.Duration.ZERO, omitted.maxAge) val unlimited = broadcast - .publishTrack("unlimited", TrackInfo(maxAgeUnlimited = true)) + .publishTrack("unlimited", TrackInfo(maxAge = null)) .consume(null) .info() assertNull(unlimited.maxAge) - assertTrue(unlimited.maxAgeUnlimited) } } @@ -539,7 +538,7 @@ class SmokeTest { val track = broadcast.publishTrack( "ticks", - timestamp.scale?.let { TrackInfo(timescale = it) }, + timestamp.scale?.let { TrackInfo(maxAge = java.time.Duration.ZERO, timescale = it) }, ) val consumer = track.consume(null) track.writeFrame(Frame(payload = ByteArray(0), timestamp = timestamp)) @@ -552,7 +551,7 @@ class SmokeTest { @Test fun `out of range timestamps are refused`() { BroadcastProducer().use { broadcast -> - val track = broadcast.publishTrack("ticks", TrackInfo(timescale = 90_000uL)) + val track = broadcast.publishTrack("ticks", TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 90_000uL)) for (timestamp in listOf( Timestamp(1uL, 0uL), @@ -594,7 +593,7 @@ class SmokeTest { fun `typed json snapshot round-trips a serializable value`() = runTest { BroadcastProducer().use { broadcast -> val config = SnapshotConfig(deltas = true) - val track = broadcast.publishTrack("status", TrackInfo(timescale = 1_000_000uL)) + val track = broadcast.publishTrack("status", TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000_000uL)) SnapshotProducer(broadcast, track, config).use { producer -> val consumer = SnapshotConsumer(broadcast.consume(), "status") for (n in 1..4) producer.update( @@ -626,7 +625,7 @@ class SmokeTest { val track = broadcast.publishTrack( "log", - TrackInfo(timescale = 1_000_000uL, compression = Compression.DEFLATE), + TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000_000uL, compression = Compression.deflate()), ) val producer = WindowProducer(track, config) val consumer = WindowConsumer(broadcast.consume().subscribeTrack("log", null)) @@ -663,7 +662,7 @@ class SmokeTest { fun `json producer demand follows subscribers`() = runTest { BroadcastProducer().use { broadcast -> val config = SnapshotConfig(deltas = false) - val track = broadcast.publishTrack("status", TrackInfo(timescale = 1_000uL)) + val track = broadcast.publishTrack("status", TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000uL)) SnapshotProducer(broadcast, track, config).use { producer -> val demand: TrackDemand = producer.demand() assertEquals("status", demand.name()) @@ -682,7 +681,7 @@ class SmokeTest { BroadcastProducer().use { broadcast -> val config = SnapshotConfig(deltas = false) // A demand watcher does not own the writer; keep it alive through collection. - val track = broadcast.publishTrack("status", TrackInfo(timescale = 1_000uL)) + val track = broadcast.publishTrack("status", TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000uL)) SnapshotProducer(broadcast, track, config).use { producer -> val demand: TrackDemand = producer.demand() producer.update(Status(state = "live"), Timestamp(1uL, 1_000uL)) @@ -705,7 +704,7 @@ class SmokeTest { fun `raw json string passes through unencoded`() = runTest { BroadcastProducer().use { broadcast -> val config = SnapshotConfig(deltas = false) - val track = broadcast.publishTrack("status", TrackInfo(timescale = 1_000uL)) + val track = broadcast.publishTrack("status", TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000uL)) SnapshotProducer(broadcast, track, config).use { producer -> producer.update("""{"state":"raw"}""", Timestamp(1uL, 1_000uL)) @@ -1320,7 +1319,7 @@ class SmokeTest { ), output = VideoEncoderOutput( - codec = VideoCodec.H264, + codec = VideoCodec.h264(), kind = softwareEncoder, ), track = "camera", diff --git a/kt/moq/src/jvmTest/kotlin/dev/moq/FfiBench.kt b/kt/moq/src/jvmTest/kotlin/dev/moq/FfiBench.kt index d66b8fa64aa..45adff7fa64 100644 --- a/kt/moq/src/jvmTest/kotlin/dev/moq/FfiBench.kt +++ b/kt/moq/src/jvmTest/kotlin/dev/moq/FfiBench.kt @@ -87,7 +87,7 @@ class FfiBench { val broadcast = route.broadcast() val tracks = (0 until case.publishers).map { - broadcast.publishTrack("$it", TrackInfo(timescale = 1_000_000uL)) + broadcast.publishTrack("$it", TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000_000uL)) } val consumers = tracks.flatMap { track -> (0 until case.subscribers).map { track.consume(null) } diff --git a/py/moq-rs/README.md b/py/moq-rs/README.md index a8089509f7d..c25787c9f2e 100644 --- a/py/moq-rs/README.md +++ b/py/moq-rs/README.md @@ -232,7 +232,7 @@ and `.cut()` ends its open group so the next edit opens one restating the window no window mode, so `WindowProducer` takes only the track. A raw frame on a scale-less track carries `Timestamp.unscaled` at its group key, but every JSON write takes a time on the broadcast clock. Publish JSON tracks with -`TrackInfo(compression=moq.Compression.DEFLATE)`: the track compresses each group on the wire, and consumers read it the +`TrackInfo(compression=moq.Compression.deflate())`: the track compresses each group on the wire, and consumers read it the same either way. Opaque bytes go on a plain `TrackProducer`. ### Subscribing diff --git a/py/moq-rs/moq/__init__.py b/py/moq-rs/moq/__init__.py index e8ecfb5a11b..0098af0db11 100644 --- a/py/moq-rs/moq/__init__.py +++ b/py/moq-rs/moq/__init__.py @@ -96,8 +96,6 @@ VideoEncoderOutput, VideoPixelFormat, VideoSurface, - VideoSurfacePixelBuffer, - VideoSurfaceUnknown, WebSocketConfig, ) @@ -180,8 +178,6 @@ "VideoEncoderOutput", "VideoDecodedFrame", "VideoSurface", - "VideoSurfacePixelBuffer", - "VideoSurfaceUnknown", "VideoPixelFormat", "Viewer", "Viewers", diff --git a/py/moq-rs/moq/_records.py b/py/moq-rs/moq/_records.py index 59d1bb9a064..8a5f2dc90ba 100644 --- a/py/moq-rs/moq/_records.py +++ b/py/moq-rs/moq/_records.py @@ -321,7 +321,6 @@ def _ffi(self) -> MoqTrackInfo: return MoqTrackInfo( priority=self.priority, max_age=self.max_age, - max_age_unlimited=self.max_age is None, refresh=self.refresh, timescale=self.timescale, compression=self.compression, @@ -331,7 +330,7 @@ def _ffi(self) -> MoqTrackInfo: def _from_ffi(info: MoqTrackInfo) -> TrackInfo: return TrackInfo( priority=info.priority, - max_age=None if info.max_age_unlimited else (info.max_age or timedelta(0)), + max_age=info.max_age, refresh=info.refresh, timescale=info.timescale, compression=info.compression, @@ -535,30 +534,8 @@ def pixels(self, format: MoqVideoPixelFormat) -> bytes: """The picture converted to tightly packed CPU pixels in ``format``.""" return self._inner.pixels(format) - def surface(self) -> VideoSurface | None: - """The decoder's platform surface, when the decoder output asked for one.""" - return _surface(self._inner.surface()) - - -class VideoSurface: - """A decoded frame's platform surface; match it with a fallback arm, since new platforms add kinds.""" - - -@dataclass(frozen=True) -class VideoSurfacePixelBuffer(VideoSurface): - """An Apple ``CVPixelBufferRef`` (IOSurface-backed NV12) address, valid while its frame lives.""" - - pointer: int - - -@dataclass(frozen=True) -class VideoSurfaceUnknown(VideoSurface): - """A surface kind this version of the package does not know yet.""" - - -def _surface(surface: MoqVideoSurface | None) -> VideoSurface | None: - if surface is None: - return None - if isinstance(surface, MoqVideoSurface.PIXEL_BUFFER): - return VideoSurfacePixelBuffer(surface.pointer) - return VideoSurfaceUnknown() + def surface(self) -> MoqVideoSurface | None: + """The decoder's platform surface, when the decoder output asked for one: a + ``VideoSurface.PIXEL_BUFFER`` on macOS and iOS, or ``VideoSurface.UNKNOWN`` for a kind + this version cannot name yet.""" + return self._inner.surface() diff --git a/py/moq-rs/moq/json.py b/py/moq-rs/moq/json.py index bf7ae383a87..35eccebeaa6 100644 --- a/py/moq-rs/moq/json.py +++ b/py/moq-rs/moq/json.py @@ -6,7 +6,7 @@ :class:`~moq.TrackConsumer` that has not read a group yet. Either track can come from a request as well as by name. Values are any JSON-serializable Python object. -Compression is the track's: publish it with ``TrackInfo(compression=Compression.DEFLATE)``, which JSON benefits from, +Compression is the track's: publish it with ``TrackInfo(compression=Compression.deflate())``, which JSON benefits from, and a consumer reads it with no option of its own. Every write (a snapshot update, a stream append, a window push or pop) takes a timestamp on the diff --git a/py/moq-rs/moq/types.py b/py/moq-rs/moq/types.py index 2628f449bc9..c46ae8948f2 100644 --- a/py/moq-rs/moq/types.py +++ b/py/moq-rs/moq/types.py @@ -65,6 +65,9 @@ from moq_ffi import ( MoqVideoPixelFormat as VideoPixelFormat, ) +from moq_ffi import ( + MoqVideoSurface as VideoSurface, +) from ._records import ( Anchor, @@ -81,9 +84,6 @@ Timestamp, TrackInfo, VideoDecodedFrame, - VideoSurface, - VideoSurfacePixelBuffer, - VideoSurfaceUnknown, WebSocketConfig, ) @@ -123,8 +123,6 @@ "VideoEncoderOutput", "VideoDecodedFrame", "VideoSurface", - "VideoSurfacePixelBuffer", - "VideoSurfaceUnknown", "VideoPixelFormat", "WebSocketConfig", ] diff --git a/py/moq-rs/tests/test_local.py b/py/moq-rs/tests/test_local.py index 096af13b292..deba9f1cc26 100644 --- a/py/moq-rs/tests/test_local.py +++ b/py/moq-rs/tests/test_local.py @@ -537,7 +537,7 @@ async def test_publish_track_info_and_subscription(): def test_track_info_keeps_native_default_priority(): """A partially configured TrackInfo keeps moq-ffi's default priority of 0.""" - native = moq_ffi.MoqTrackInfo().priority + native = moq_ffi.MoqTrackInfo(max_age=None).priority assert moq.TrackInfo()._ffi().priority == native assert moq.TrackInfo(max_age=timedelta(seconds=2))._ffi().priority == native assert moq.TrackInfo(timescale=90_000)._ffi().priority == native @@ -560,6 +560,17 @@ def test_track_info_max_age(): broadcast.close() +def test_track_info_reads_compression_back(): + """A received compression compares equal to the selector and names itself.""" + broadcast = moq.BroadcastProducer() + info = moq.TrackInfo(compression=moq.Compression.deflate()) + got = broadcast.publish_track("deflate", info).consume().info() + assert got.compression == moq.Compression.deflate() + assert got.compression is not None and got.compression.name() == "deflate" + assert broadcast.publish_track("plain").consume().info().compression is None + broadcast.close() + + def test_default_subscription_skips_superseded_groups_at_once(): """A bare record carries moq-net's zero delay too; only an explicit None leaves a bound unset.""" assert moq.Subscription.default() == moq.Subscription() @@ -610,7 +621,7 @@ async def test_fetch_group_and_serve_dynamic_miss(): async def test_json_snapshot_roundtrip(): broadcast = moq.BroadcastProducer() - track = broadcast.publish_track("status", moq.TrackInfo(timescale=1_000_000, compression=moq.Compression.DEFLATE)) + track = broadcast.publish_track("status", moq.TrackInfo(timescale=1_000_000, compression=moq.Compression.deflate())) producer = moq.json.SnapshotProducer(broadcast, track) consumer = moq.json.SnapshotConsumer(broadcast.consume(), "status") @@ -644,7 +655,7 @@ async def test_json_stream_roundtrip(): async def test_json_window_roundtrip(): broadcast = moq.BroadcastProducer() - track = broadcast.publish_track("log", moq.TrackInfo(timescale=1_000_000, compression=moq.Compression.DEFLATE)) + track = broadcast.publish_track("log", moq.TrackInfo(timescale=1_000_000, compression=moq.Compression.deflate())) producer = moq.json.WindowProducer(track) consumer = moq.json.WindowConsumer(await broadcast.consume().subscribe_track("log")) demand = producer.demand() @@ -730,7 +741,7 @@ async def test_json_window_skips_records_outside_the_checkpoint(): async def test_json_producers_report_demand(): broadcast = moq.BroadcastProducer() - timed = moq.TrackInfo(timescale=1_000, compression=moq.Compression.DEFLATE) + timed = moq.TrackInfo(timescale=1_000, compression=moq.Compression.deflate()) snapshot = moq.json.SnapshotProducer(broadcast, broadcast.publish_track("status", timed)) stream = moq.json.StreamProducer(broadcast, broadcast.publish_track("events", timed)) snapshot_demand = snapshot.demand() @@ -1593,7 +1604,7 @@ def test_video_encoder_submits_and_receives(): framerate=moq.video.FrameRate(numerator=30, denominator=1), ), moq.video.EncoderOutput( - codec=moq.video.Codec.H264, + codec=moq.video.Codec.h264(), kind=cast(moq.video.EncoderKind, moq.video.EncoderKind.SOFTWARE()), ), ) @@ -1633,11 +1644,13 @@ def test_audio_encoder_frame_init_and_bitrate(): def test_video_namespace_names_its_configuration_types(): """``moq.video`` names every type its records take.""" + codec = moq.video.Codec.h264() output = moq.video.EncoderOutput( - codec=moq.video.Codec.H264, + codec=codec, kind=cast(moq.video.EncoderKind, moq.video.EncoderKind.AUTO()), ) - assert output.codec == moq.VideoCodec.H264 + assert output.codec is codec + assert isinstance(codec, moq.VideoCodec) assert moq.video.PixelFormat.RGBA == moq.VideoPixelFormat.RGBA @@ -1733,7 +1746,7 @@ async def test_decode_video_frame(): # variant inside the enum without declaring it a subclass, so the cast is # what makes the variant typecheck. moq.VideoEncoderOutput( - codec=moq.VideoCodec.H264, + codec=moq.VideoCodec.h264(), kind=cast(moq.VideoEncoderKind, moq.VideoEncoderKind.SOFTWARE()), ), track="camera", @@ -1775,15 +1788,6 @@ async def test_decode_video_frame(): broadcast.close() -def test_video_surface_unknown_kind() -> None: - """A surface kind this package predates maps to the fallback arm instead of failing.""" - from moq._records import _surface - - assert _surface(None) is None - assert _surface(cast(Any, moq_ffi.MoqVideoSurface.PIXEL_BUFFER(7))) == moq.VideoSurfacePixelBuffer(7) - assert _surface(cast(Any, object())) == moq.VideoSurfaceUnknown() - - async def test_broadcast_is_reachable_only_while_announced(): origin = moq.OriginProducer() route = origin.route("live", hidden=True) diff --git a/rs/moq-ffi/AGENTS.md b/rs/moq-ffi/AGENTS.md index af8e861fe5d..356c889aba5 100644 --- a/rs/moq-ffi/AGENTS.md +++ b/rs/moq-ffi/AGENTS.md @@ -5,6 +5,15 @@ The UniFFI core every non-Rust binding is generated from (proc macros, no `.udl` - The wrappers give each layer its own namespace, following `json`: `moq.json` (Python), `moq.dev/moq/json` (Go), `dev.moq.json` (Kotlin), `package:moq/json.dart` (Dart), and the `Json` enum (Swift). - Keep wrappers thin and named like the Rust API. Swift and Python extend through labeled/keyword args with defaults; Go, Kotlin, and Dart take an options struct. +# Open sets + +Swift, Kotlin, and Dart switch over enums exhaustively, so a new variant breaks every caller's source. + +- A selector the caller passes from a set Rust can grow (a codec, a compression) is an object with one constructor per member, like `MoqAudioCodec`. Give it `Eq` and a name when the caller also reads it back. +- An enum the caller reads from a set Rust can grow (a transport, a surface) carries an `Unknown` variant in moq-ffi, where Rust maps whatever it cannot name yet. Wrappers alias it rather than fence it again. +- A new variant of such an enum maps to `Unknown` until an API cut, since `sh/api-diff` counts any line added inside an existing declaration as a break. +- A null duration means no limit, as `MoqDelay.max` and `MoqTrackInfo.max_age` do. Where a language has no null, such as a Go struct or the C API, a boolean beside the value says so, so a zeroed struct keeps the default. + # Gotchas - UniFFI ignores `#[cfg]` inside an export impl; gate at the module. diff --git a/rs/moq-ffi/src/bench.rs b/rs/moq-ffi/src/bench.rs index 973d4a85bd1..5d4a7257d0a 100644 --- a/rs/moq-ffi/src/bench.rs +++ b/rs/moq-ffi/src/bench.rs @@ -258,8 +258,7 @@ async fn rust_ffi() { let broadcast = route.broadcast(); let timed = MoqTrackInfo { priority: 0, - max_age: None, - max_age_unlimited: false, + max_age: Some(Duration::ZERO), refresh: None, timescale: Some(1_000_000), compression: None, diff --git a/rs/moq-ffi/src/producer.rs b/rs/moq-ffi/src/producer.rs index 26f1e1fea4b..67157422fd8 100644 --- a/rs/moq-ffi/src/producer.rs +++ b/rs/moq-ffi/src/producer.rs @@ -32,23 +32,21 @@ impl From for MoqPosition { /// Publisher-side track properties, mirroring [`moq_net::track::Info`]. /// /// Construct with the fields you care about; the rest use raw-track defaults -/// (priority 0, a zero max age, untimed). +/// (priority 0, untimed, uncompressed). A null record uses moq-net's zero `max_age` too. +/// Uniffi can't default a duration, so Kotlin and Swift name `max_age`, the Python, Go, and +/// Dart wrappers default an omitted one to zero, and a bare C++ record leaves it unset, as +/// [`MoqDelay`](crate::consumer::MoqDelay) does. #[derive(Clone, uniffi::Record)] pub struct MoqTrackInfo { /// Priority, used only to break ties between subscriptions of equal subscriber priority. /// Higher is more urgent; the default 0 is the midpoint. #[uniffi(default = 0)] pub priority: i8, - /// How long a superseded group stays fresh, or null for the default, zero: only the live - /// edge is served. The publisher-side half of - /// [`MoqDelay::max`](crate::consumer::MoqDelay::max). Ignored when `max_age_unlimited` is - /// set. Uniffi can't default a duration, hence null rather than zero. - #[uniffi(default = None)] + /// How long a superseded group stays fresh, or null for no publisher limit, leaving only + /// the cache to bound how long one is served. Zero serves only the live edge. The + /// publisher-side half of [`MoqDelay::max`](crate::consumer::MoqDelay::max), which reads + /// null the same way. pub max_age: Option, - /// Set no publisher age limit, ignoring `max_age` and leaving only the cache to bound how - /// long a superseded group is served. A received track that advertised none reports this. - #[uniffi(default = false)] - pub max_age_unlimited: bool, /// How many times its first frame a group's later bytes may grow before a joining /// subscriber asks for a new group, or null to never ask. See /// [`MoqTrackDemand::wanted`](crate::demand::MoqTrackDemand::wanted). @@ -60,21 +58,33 @@ pub struct MoqTrackInfo { /// How each group is compressed on the wire to peers that support it, or null to send /// frames as written. Readers always see the original frames. #[uniffi(default = None)] - pub compression: Option, + pub compression: Option>, } /// How a track's frames are compressed, mirroring [`moq_net::track::Compression`]; an /// uncompressed track has none. -#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)] -pub enum MoqCompression { +/// +/// An immutable object so adding a compression later does not break callers switching over a +/// closed enum. Compare a received one by [`name`](Self::name). +#[derive(Debug, PartialEq, Eq, Hash, uniffi::Object)] +#[uniffi::export(Debug, Eq, Hash)] +pub struct MoqCompression(moq_net::track::Compression); + +#[uniffi::export] +impl MoqCompression { /// Each group is one DEFLATE stream, which suits small, repetitive frames like JSON. - Deflate, -} + #[uniffi::constructor] + pub fn deflate() -> Arc { + Arc::new(Self(moq_net::track::Compression::Deflate)) + } -fn compression(compression: Option) -> moq_net::track::Compression { - match compression { - None => moq_net::track::Compression::None, - Some(MoqCompression::Deflate) => moq_net::track::Compression::Deflate, + /// The compression's lowercase name, such as `deflate`. + pub fn name(&self) -> String { + match self.0 { + moq_net::track::Compression::Deflate => "deflate".into(), + // A compression added to moq-net before this binding names it. + other => format!("{other:?}").to_lowercase(), + } } } @@ -84,19 +94,18 @@ impl TryFrom for moq_net::track::Info { fn try_from(info: MoqTrackInfo) -> Result { let mut out = moq_net::track::Info::default() .with_priority(info.priority) - .with_refresh(info.refresh); - if info.max_age_unlimited { - out = out.with_max_age(None); - } else if let Some(max_age) = info.max_age { - out = out.with_max_age(max_age); - } + .with_refresh(info.refresh) + .with_max_age(info.max_age); if let Some(ticks) = info.timescale { let scale = moq_net::Timescale::new(ticks).map_err(|_| MoqError::Codec { reason: format!("invalid timescale: {ticks}"), })?; out = out.with_timescale(scale); } - Ok(out.with_compression(compression(info.compression))) + let compression = info + .compression + .map_or(moq_net::track::Compression::None, |compression| compression.0); + Ok(out.with_compression(compression)) } } @@ -117,11 +126,10 @@ impl From<&moq_net::track::Info> for MoqTrackInfo { Self { priority: info.priority, max_age: info.max_age.map(crate::ffi::duration), - max_age_unlimited: info.max_age.is_none(), refresh: info.refresh, timescale: info.timescale.map(|timescale| timescale.as_u64()), - // A codec this binding cannot name yet reads as uncompressed, as its frames do. - compression: (info.compression == moq_net::track::Compression::Deflate).then_some(MoqCompression::Deflate), + compression: (info.compression != moq_net::track::Compression::None) + .then(|| Arc::new(MoqCompression(info.compression))), } } } @@ -1169,32 +1177,40 @@ mod metadata_tests { #[test] fn max_age_survives_binding_conversion() { - let info = |max_age, max_age_unlimited| MoqTrackInfo { + let info = |max_age| MoqTrackInfo { priority: 0, max_age, - max_age_unlimited, refresh: None, timescale: None, compression: None, }; let zero = Some(std::time::Duration::ZERO); - let five = Some(std::time::Duration::from_secs(5)); assert_eq!(raw_track_info(None).unwrap().max_age, zero); - for (max_age, unlimited, want) in [ - (None, false, zero), - (five, false, five), - (None, true, None), - // The flag wins over a stated age. - (five, true, None), - ] { - let model = moq_net::track::Info::try_from(info(max_age, unlimited)).unwrap(); - assert_eq!(model.max_age, want); + // Null is no limit, as `MoqDelay.max` reads it, and zero is the live edge only. + for max_age in [None, zero, Some(std::time::Duration::from_secs(5))] { + let model = moq_net::track::Info::try_from(info(max_age)).unwrap(); + assert_eq!(model.max_age, max_age); // A received record republishes unchanged. let back = MoqTrackInfo::from(&model); - assert_eq!(moq_net::track::Info::try_from(back).unwrap().max_age, want); + assert_eq!(back.max_age, max_age); } } + #[test] + fn compression_survives_binding_conversion() { + let model = moq_net::track::Info::default(); + assert!(MoqTrackInfo::from(&model).compression.is_none()); + let deflate = model.with_compression(moq_net::track::Compression::Deflate); + let info = MoqTrackInfo::from(&deflate); + let read = info.compression.clone().unwrap(); + assert_eq!(*read, *MoqCompression::deflate()); + assert_eq!(read.name(), "deflate"); + assert_eq!( + moq_net::track::Info::try_from(info).unwrap().compression, + moq_net::track::Compression::Deflate + ); + } + /// C and C++ abort on a duration past `i64::MAX` nanoseconds, so a peer's longer age saturates. #[test] fn oversized_max_age_saturates_for_the_bindings() { diff --git a/rs/moq-ffi/src/server.rs b/rs/moq-ffi/src/server.rs index 332069047ff..210fb640e67 100644 --- a/rs/moq-ffi/src/server.rs +++ b/rs/moq-ffi/src/server.rs @@ -374,7 +374,7 @@ impl MoqServer { Err(driver) => return cancelled(driver).await, }; match request? { - Some(request) => Ok(Some(MoqRequest::new(request, origins.publish, origins.consume)?)), + Some(request) => Ok(Some(MoqRequest::new(request, origins.publish, origins.consume))), None => { driver.finished().await?; Ok(None) @@ -437,20 +437,20 @@ pub enum MoqTransport { Unix, /// WebTransport over HTTP/3 on QUIC. WebTransport, + /// A transport this version of the bindings cannot name yet. + Unknown, } -impl TryFrom for MoqTransport { - type Error = MoqError; - - fn try_from(value: moq_tokio::Transport) -> Result { - Ok(match value { +impl From for MoqTransport { + fn from(value: moq_tokio::Transport) -> Self { + match value { moq_tokio::Transport::Quic => Self::Quic, moq_tokio::Transport::WebSocket => Self::WebSocket, moq_tokio::Transport::Tcp => Self::Tcp, moq_tokio::Transport::Unix => Self::Unix, moq_tokio::Transport::WebTransport => Self::WebTransport, - _ => return Err(MoqError::Unsupported), - }) + _ => Self::Unknown, + } } } @@ -460,18 +460,18 @@ mod transport_tests { use moq_tokio::Transport; #[test] - fn converts_supported_transports() { - assert_eq!(MoqTransport::try_from(Transport::Quic).unwrap(), MoqTransport::Quic); - assert_eq!( - MoqTransport::try_from(Transport::WebSocket).unwrap(), - MoqTransport::WebSocket - ); - assert_eq!(MoqTransport::try_from(Transport::Tcp).unwrap(), MoqTransport::Tcp); - assert_eq!(MoqTransport::try_from(Transport::Unix).unwrap(), MoqTransport::Unix); - assert_eq!( - MoqTransport::try_from(Transport::WebTransport).unwrap(), - MoqTransport::WebTransport - ); + fn names_each_transport_it_knows() { + for (transport, want) in [ + (Transport::Quic, MoqTransport::Quic), + (Transport::WebSocket, MoqTransport::WebSocket), + (Transport::Tcp, MoqTransport::Tcp), + (Transport::Unix, MoqTransport::Unix), + (Transport::WebTransport, MoqTransport::WebTransport), + // A request over a transport the bindings cannot name still reaches the caller. + (Transport::WebRtc, MoqTransport::Unknown), + ] { + assert_eq!(MoqTransport::from(transport), want); + } } } @@ -495,13 +495,13 @@ impl MoqRequest { request: moq_tokio::server::Request, publish: Option>, consume: Option>, - ) -> Result, MoqError> { - let transport = request.transport().try_into()?; + ) -> Arc { + let transport = request.transport().into(); let url = request.url().map(|u| u.to_string()); let path = request.path().to_string(); let query = request.query().map(str::to_string); let peer_implementation = request.peer_implementation().map(str::to_string); - Ok(Arc::new(Self { + Arc::new(Self { task: Task::new(RequestState { request: OneShot::new(request), publish, @@ -512,7 +512,7 @@ impl MoqRequest { path, query, peer_implementation, - })) + }) } } diff --git a/rs/moq-ffi/src/socket.rs b/rs/moq-ffi/src/socket.rs index 6b3568bcb38..74b44321e1f 100644 --- a/rs/moq-ffi/src/socket.rs +++ b/rs/moq-ffi/src/socket.rs @@ -231,7 +231,7 @@ mod tests { let reverse = server.producer(); let consumer = server.consumer(); drop(server); - assert!(consumer.info().max_age_unlimited); + assert_eq!(consumer.info().max_age, None); // Create the later group first: the reliable ascending reader must wait for 0. let later = producer.create_group(1).unwrap(); later.write_frame(frame(&later, b"later")).unwrap(); diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index 7b55eaeedf9..d42af60b623 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -49,8 +49,7 @@ fn timed() -> moq_net::track::Info { fn timed_info() -> MoqTrackInfo { MoqTrackInfo { priority: 0, - max_age: None, - max_age_unlimited: false, + max_age: Some(Duration::ZERO), refresh: None, timescale: Some(1_000_000), compression: None, @@ -60,7 +59,7 @@ fn timed_info() -> MoqTrackInfo { /// [`timed_info`] with no publisher age limit, for a test that reads superseded groups. fn unlimited_info() -> MoqTrackInfo { MoqTrackInfo { - max_age_unlimited: true, + max_age: None, ..timed_info() } } @@ -1195,10 +1194,9 @@ async fn raw_track_info_reports_publisher_properties() { let info = MoqTrackInfo { priority: 7, max_age: Some(Duration::from_millis(2_500)), - max_age_unlimited: false, refresh: Some(2), timescale: Some(90_000), - compression: Some(crate::producer::MoqCompression::Deflate), + compression: Some(MoqCompression::deflate()), }; let track = broadcast.publish_track("status".into(), Some(info)).unwrap(); let consumer = track.consume(None).unwrap(); @@ -1206,10 +1204,9 @@ async fn raw_track_info_reports_publisher_properties() { let got = consumer.info(); assert_eq!(got.priority, 7); assert_eq!(got.max_age, Some(Duration::from_millis(2_500))); - assert!(!got.max_age_unlimited); assert_eq!(got.refresh, Some(2)); assert_eq!(got.timescale, Some(90_000)); - assert_eq!(got.compression, Some(crate::producer::MoqCompression::Deflate)); + assert_eq!(got.compression.unwrap().name(), "deflate"); } #[tokio::test] @@ -1280,8 +1277,7 @@ async fn data_writes_preserve_the_callers_timestamp() { "data".into(), Some(MoqTrackInfo { priority: 0, - max_age: None, - max_age_unlimited: false, + max_age: Some(Duration::ZERO), refresh: None, timescale: timestamp.scale, compression: None, @@ -1384,11 +1380,10 @@ async fn json_snapshot_roundtrip() { let config = MoqJsonSnapshotConfig { deltas: true }; let info = MoqTrackInfo { priority: 0, - max_age: None, - max_age_unlimited: false, + max_age: Some(Duration::ZERO), timescale: Some(1_000_000), refresh: None, - compression: Some(crate::producer::MoqCompression::Deflate), + compression: Some(MoqCompression::deflate()), }; let track = broadcast.publish_track("meta".into(), Some(info)).unwrap(); let producer = MoqJsonSnapshotProducer::new(&broadcast, &track, config.clone()).unwrap(); @@ -1458,8 +1453,7 @@ async fn json_snapshot_refreshes_for_a_joiner() { "meta".into(), Some(MoqTrackInfo { priority: 127, - max_age: None, - max_age_unlimited: false, + max_age: Some(Duration::ZERO), refresh: Some(1), timescale: Some(1_000_000), compression: None, @@ -1690,8 +1684,7 @@ async fn json_window_refreshes_a_bounded_checkpoint_for_a_joiner() { "log".into(), Some(MoqTrackInfo { priority: 127, - max_age: None, - max_age_unlimited: false, + max_age: Some(Duration::ZERO), refresh: Some(1), timescale: Some(1_000_000), compression: None, @@ -4116,7 +4109,7 @@ async fn video_raw_publish_consume() { }, }, output: MoqVideoEncoderOutput { - codec: MoqVideoCodec::H264, + codec: MoqVideoCodec::h264(), bitrate: None, join: None, // Software so the test is deterministic everywhere: `Auto` would @@ -4241,7 +4234,7 @@ async fn video_decode_frame_ownership() { }, }, output: MoqVideoEncoderOutput { - codec: MoqVideoCodec::H264, + codec: MoqVideoCodec::h264(), bitrate: None, join: None, // Software so the encode is deterministic everywhere. @@ -4391,7 +4384,7 @@ async fn video_decode_start() { }, }, output: MoqVideoEncoderOutput { - codec: MoqVideoCodec::H264, + codec: MoqVideoCodec::h264(), bitrate: None, join: None, kind: MoqVideoEncoderKind::Software, @@ -4511,7 +4504,7 @@ async fn video_raw_publish_from_many_threads() { }, }, output: MoqVideoEncoderOutput { - codec: MoqVideoCodec::H264, + codec: MoqVideoCodec::h264(), // An explicit ceiling so the retunes below stay under the rate the // encoder opened at, which openh264 requires. bitrate: Some(1_000_000), @@ -4590,7 +4583,7 @@ async fn video_raw_publish_rejects_bad_frames() { }, }; let output = || MoqVideoEncoderOutput { - codec: MoqVideoCodec::H264, + codec: MoqVideoCodec::h264(), bitrate: None, join: None, kind: MoqVideoEncoderKind::Software, @@ -7761,7 +7754,7 @@ async fn video_encoder_follows_a_shrinking_grant() { }, }, output: MoqVideoEncoderOutput { - codec: MoqVideoCodec::H264, + codec: MoqVideoCodec::h264(), bitrate: Some(4_000_000), join: None, kind: MoqVideoEncoderKind::Software, @@ -7809,7 +7802,7 @@ fn software_camera(bitrate: u64) -> (crate::video::MoqVideoEncoderInput, crate:: }, }, MoqVideoEncoderOutput { - codec: MoqVideoCodec::H264, + codec: MoqVideoCodec::h264(), bitrate: Some(bitrate), join: None, kind: MoqVideoEncoderKind::Software, @@ -9692,7 +9685,6 @@ async fn audio_subscribe_configuration_boundary() { Some(MoqTrackInfo { priority: 0, max_age: Some(Duration::from_millis(10)), - max_age_unlimited: false, refresh: None, timescale: None, compression: None, diff --git a/rs/moq-ffi/src/video.rs b/rs/moq-ffi/src/video.rs index 51026fe02bd..9b04ecabd13 100644 --- a/rs/moq-ffi/src/video.rs +++ b/rs/moq-ffi/src/video.rs @@ -36,20 +36,30 @@ pub enum MoqVideoPixelFormat { /// /// Not every codec has a backend on every machine: H.265 is hardware-only, so /// publishing it fails where no hardware encoder is available. -#[derive(Clone, Copy, uniffi::Enum)] -pub enum MoqVideoCodec { - /// H.264 / AVC, published as an `avc3` track. - H264, - /// H.265 / HEVC, published as a `hev1` track. - H265, +/// +/// An immutable object so adding a codec later does not break callers +/// switching over a closed enum. +#[derive(uniffi::Object)] +pub struct MoqVideoCodec { + inner: moq_video::encode::Codec, } -impl From for moq_video::encode::Codec { - fn from(c: MoqVideoCodec) -> Self { - match c { - MoqVideoCodec::H264 => Self::H264, - MoqVideoCodec::H265 => Self::H265, - } +#[uniffi::export] +impl MoqVideoCodec { + /// H.264 / AVC, published as an `avc3` track. + #[uniffi::constructor] + pub fn h264() -> Arc { + Arc::new(Self { + inner: moq_video::encode::Codec::H264, + }) + } + + /// H.265 / HEVC, published as a `hev1` track. + #[uniffi::constructor] + pub fn h265() -> Arc { + Arc::new(Self { + inner: moq_video::encode::Codec::H265, + }) } } @@ -127,7 +137,7 @@ pub struct MoqVideoEncoderInput { #[derive(uniffi::Record)] pub struct MoqVideoEncoderOutput { /// The codec used to encode this rendition. - pub codec: MoqVideoCodec, + pub codec: Arc, /// Target bitrate in bits per second. `None` derives one from the resolution /// and framerate. #[uniffi(default = None)] @@ -206,7 +216,7 @@ fn video_encoder_config( ) -> Result { let framerate = input.framerate.try_into()?; let mut config = moq_video::encode::Config::new(input.width, input.height, framerate); - config.codec = output.codec.into(); + config.codec = output.codec.inner; config.kind = output.kind.clone().into(); config.bitrate = output.bitrate.map(moq_net::bandwidth::Rate::from_bps); if let Some(join) = output.join { @@ -1122,14 +1132,15 @@ pub struct MoqVideoDecoderOutput { /// Keep the frame until every GPU command reading the surface has completed: /// the surface belongs to the decoder's pool, and releasing the frame is what /// lets the decoder reuse it. -#[derive(Clone, Copy, uniffi::Enum)] -#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)] pub enum MoqVideoSurface { /// An Apple `CVPixelBufferRef` from VideoToolbox, IOSurface-backed NV12. PixelBuffer { /// The borrowed CVPixelBuffer address, valid while the frame is held. pointer: u64, }, + /// A platform surface this version of the bindings cannot name yet. + Unknown, } /// One decoded video frame, owning the surface it was decoded into. @@ -1186,11 +1197,13 @@ impl MoqVideoDecodedFrame { /// Only a [`surface`](MoqVideoDecoderOutput::surface) decode produces one. pub fn surface(&self) -> Option { match &self.frame.surface { + moq_video::Surface::I420(_) => None, #[cfg(any(target_os = "macos", target_os = "ios"))] moq_video::Surface::PixelBuffer(pixels) => Some(MoqVideoSurface::PixelBuffer { pointer: std::ptr::from_ref(pixels.buffer()).addr() as u64, }), - _ => None, + #[allow(unreachable_patterns, reason = "a platform whose every surface has a variant")] + _ => Some(MoqVideoSurface::Unknown), } } } @@ -1455,7 +1468,7 @@ mod finish_tests { #[test] fn encoder_config_preserves_exact_rates_and_rejects_invalid_ratios() { let output = MoqVideoEncoderOutput { - codec: MoqVideoCodec::H264, + codec: MoqVideoCodec::h264(), bitrate: None, join: None, kind: MoqVideoEncoderKind::Software, @@ -1509,7 +1522,7 @@ mod finish_tests { }, }, MoqVideoEncoderOutput { - codec: MoqVideoCodec::H264, + codec: MoqVideoCodec::h264(), bitrate: Some(500_000), join: None, kind: MoqVideoEncoderKind::Software, @@ -1568,7 +1581,7 @@ mod finish_tests { }, }; let output = MoqVideoEncoderOutput { - codec: MoqVideoCodec::H264, + codec: MoqVideoCodec::h264(), bitrate: Some(4_000_000), join: None, kind: MoqVideoEncoderKind::Software, @@ -1630,7 +1643,7 @@ mod finish_tests { }, }; let output = MoqVideoEncoderOutput { - codec: MoqVideoCodec::H264, + codec: MoqVideoCodec::h264(), bitrate: Some(1_000_000), join: None, kind: MoqVideoEncoderKind::Software, @@ -1886,7 +1899,7 @@ mod rung_tests { fn output(bitrate: u64) -> MoqVideoEncoderOutput { MoqVideoEncoderOutput { - codec: MoqVideoCodec::H264, + codec: MoqVideoCodec::h264(), bitrate: Some(bitrate), join: None, kind: MoqVideoEncoderKind::Software, diff --git a/swift/README.md b/swift/README.md index ca712d3e86c..9e8deecf354 100644 --- a/swift/README.md +++ b/swift/README.md @@ -64,7 +64,7 @@ try route.announce() // hidden routes are invisible; hold the route while it sho Cancelling the surrounding Swift `Task` propagates through to the underlying `cancel()` calls on each consumer. `session.shutdown()` requests a drain immediately; `try await session.closed()` waits for it and throws on delivery failure. `cancel(code: 0)` remains immediate. -A note on enum casing: `MoqError` keeps Rust's PascalCase variants, each carrying `message: String` (e.g. `MoqError.Closed(message: "...")`); plain enums round-trip to lowerCamelCase (`AudioSampleFormat.s16`). Audio codecs are objects with constructors (`AudioCodec.opus()`). +A note on enum casing: `MoqError` keeps Rust's PascalCase variants, some with no payload (`MoqError.Closed`) and some carrying named fields (`MoqError.Transport(reason: "...")`); plain enums round-trip to lowerCamelCase (`AudioSampleFormat.s16`). Selectors Rust can add to are objects with constructors (`AudioCodec.opus()`, `VideoCodec.h264()`, `Compression.deflate()`), and `Transport` and `Video.Surface` carry an `.unknown` case for what this version cannot name yet. ## API shape @@ -96,7 +96,7 @@ zero `delay.max`. You opt into one of three distinct modes: `Json.SnapshotProduc (lossless append-log, every record preserved in order), or `Json.WindowProducer`/`Json.WindowConsumer` (a sliding window of records a reader can join at any point, not advertised in the catalog). Values encode/decode at the boundary with `JSONEncoder`/`JSONDecoder`; the consumer is an `AsyncSequence` of the decoded type. Publish the -track with `TrackInfo(compression: .deflate)`; consumers read it the same either way. Every JSON write +track with `TrackInfo(maxAge: 0, compression: Compression.deflate())`; consumers read it the same either way. Every JSON write (snapshot update, stream append, window push or pop) takes a timestamp on the broadcast clock (`Media.CatalogProducer.now()`), so the track needs a timescale. diff --git a/swift/Sources/Moq/Aliases.swift b/swift/Sources/Moq/Aliases.swift index 1b2c12f13bc..87b506609ec 100644 --- a/swift/Sources/Moq/Aliases.swift +++ b/swift/Sources/Moq/Aliases.swift @@ -45,7 +45,7 @@ public typealias VideoEncoderOutput = MoqFFI.MoqVideoEncoderOutput /// A CPU pixel layout (I420 or RGBA): fed to a `Video.Producer`, or delivered /// by a `Video.Consumer`. public typealias VideoPixelFormat = MoqFFI.MoqVideoPixelFormat -/// A video codec identifier (H.264 or H.265). +/// Selects the video encoder codec. Build one with `VideoCodec.h264()` or `VideoCodec.h265()`. public typealias VideoCodec = MoqFFI.MoqVideoCodec /// Which encoder implementation to use: automatic, hardware, software, or one /// named backend. @@ -81,7 +81,8 @@ public typealias FetchGroupOptions = MoqFFI.MoqFetchGroupOptions /// Publisher-side track properties: priority, group ordering, max age, /// and timescale. public typealias TrackInfo = MoqFFI.MoqTrackInfo -/// How a track's frames are compressed on the wire: `.deflate`, or `nil` in `TrackInfo` for none. +/// How a track's frames are compressed on the wire: `Compression.deflate()`, or `nil` in `TrackInfo` +/// for none. Compare a received one with `==` or by `name()`. public typealias Compression = MoqFFI.MoqCompression /// A snapshot of connection statistics (RTT, bandwidth estimates, byte/packet @@ -116,7 +117,8 @@ public typealias ConnectionPhase = MoqFFI.MoqConnectionPhase /// One coherent connection lifecycle snapshot. public typealias ConnectionState = MoqFFI.MoqConnectionState -/// The network transport carrying an incoming session. +/// The network transport carrying an incoming session, or `.unknown` for one this version cannot +/// name yet. public typealias Transport = MoqFFI.MoqTransport /// The error thrown by every throwing call in this package. Already conforms to diff --git a/swift/Sources/Moq/Json.swift b/swift/Sources/Moq/Json.swift index 650e8f70b15..0ef6c0e2190 100644 --- a/swift/Sources/Moq/Json.swift +++ b/swift/Sources/Moq/Json.swift @@ -10,12 +10,12 @@ import MoqFFI /// Foundation before the swift-foundation rewrite (iOS < 18 / macOS < 15), so encode an object /// or array there. /// -/// Compression is the track's: publish JSON with `TrackInfo(compression: .deflate)`, and a consumer reads -/// it with no option of its own. +/// Compression is the track's: publish JSON with `TrackInfo(maxAge: 0, compression: Compression.deflate())`, +/// and a consumer reads it with no option of its own. /// /// Every write (a snapshot update, a stream append, a window push or pop) takes a timestamp on the /// broadcast clock, the epoch every track in the broadcast shares: read it with -/// `Media.CatalogProducer.now()`. The track needs a timescale (`TrackInfo(timescale: 1000)`); one +/// `Media.CatalogProducer.now()`. The track needs a timescale (`TrackInfo(maxAge: 0, timescale: 1000)`); one /// without is refused. public enum Json {} diff --git a/swift/Sources/Moq/Video.swift b/swift/Sources/Moq/Video.swift index f02502b31d5..4be16aa5c13 100644 --- a/swift/Sources/Moq/Video.swift +++ b/swift/Sources/Moq/Video.swift @@ -55,28 +55,16 @@ public enum Video { public func pixels(format: PixelFormat) throws -> Data { try ffi.pixels(format: format) } /// The decoder's platform surface, or `nil` when the frame is in CPU memory. - public func surface() -> Surface? { ffi.surface().map(Surface.init) } + public func surface() -> Surface? { ffi.surface() } } - /// The platform image backing a `DecodedFrame`, when `DecoderOutput` asked for one. - public enum Surface: Sendable, Equatable { - /// A borrowed `CVPixelBufferRef` address, valid while its frame lives. - case pixelBuffer(pointer: UInt64) - /// A surface kind this version of the package does not know yet. - case unknown - - init(_ surface: MoqVideoSurface) { - // `if case` rather than `switch`, so a variant this package predates maps to `.unknown`. - if case .pixelBuffer(let pointer) = surface { - self = .pixelBuffer(pointer: pointer) - } else { - self = .unknown - } - } - } + /// The platform image backing a `DecodedFrame`, when `DecoderOutput` asked for one: a borrowed + /// `CVPixelBufferRef` address (`.pixelBuffer`), valid while its frame lives, or `.unknown` for a + /// kind this version cannot name yet. + public typealias Surface = MoqVideoSurface /// One encoded access unit from an `Encoder`. public typealias Packet = MoqVideoPacket - /// A video codec identifier (H.264 or H.265). + /// Selects the video encoder codec. Build one with `Codec.h264()` or `Codec.h265()`. public typealias Codec = VideoCodec /// A CPU pixel layout (I420 or RGBA). public typealias PixelFormat = VideoPixelFormat diff --git a/swift/Tests/MoqTests/FfiBench.swift b/swift/Tests/MoqTests/FfiBench.swift index 680af329f83..74e25e70356 100644 --- a/swift/Tests/MoqTests/FfiBench.swift +++ b/swift/Tests/MoqTests/FfiBench.swift @@ -75,7 +75,7 @@ final class FfiBench: XCTestCase { defer { withExtendedLifetime(route) {} } let broadcast = route.broadcast let tracks = try (0..( broadcast: broadcast, track: try broadcast.publishTrack( - name: "status", info: TrackInfo(timescale: 1_000_000, compression: .deflate))) + name: "status", info: TrackInfo(maxAge: 0, timescale: 1_000_000, compression: Compression.deflate()))) let consumer = try Json.SnapshotConsumer( broadcast: try broadcast.consume(), name: "status") @@ -652,7 +652,7 @@ final class SmokeTests: XCTestCase { let broadcast = try BroadcastProducer() let producer = try Json.StreamProducer( broadcast: broadcast, - track: try broadcast.publishTrack(name: "events", info: TrackInfo(timescale: 1_000_000))) + track: try broadcast.publishTrack(name: "events", info: TrackInfo(maxAge: 0, timescale: 1_000_000))) let consumer = try Json.StreamConsumer( track: try await broadcast.consume().subscribeTrack(name: "events")) @@ -674,7 +674,7 @@ final class SmokeTests: XCTestCase { let broadcast = try BroadcastProducer() let producer = try Json.WindowProducer( - track: try broadcast.publishTrack(name: "log", info: TrackInfo(timescale: 1_000_000, compression: .deflate)) + track: try broadcast.publishTrack(name: "log", info: TrackInfo(maxAge: 0, timescale: 1_000_000, compression: Compression.deflate())) ) let consumer = try Json.WindowConsumer( track: try await broadcast.consume().subscribeTrack(name: "log")) @@ -707,7 +707,7 @@ final class SmokeTests: XCTestCase { func testJsonProducersReportDemand() async throws { let broadcast = try BroadcastProducer() - let timed = TrackInfo(timescale: 1_000_000) + let timed = TrackInfo(maxAge: 0, timescale: 1_000_000) let snapshot = try Json.SnapshotProducer<[String: Int]>( broadcast: broadcast, track: try broadcast.publishTrack(name: "status", info: timed)) let stream = try Json.StreamProducer<[String: Int]>( @@ -787,16 +787,15 @@ final class SmokeTests: XCTestCase { let broadcast = try BroadcastProducer() let omitted = try broadcast.publishTrack(name: "omitted").consume().info() XCTAssertEqual(omitted.maxAge, 0) - let info = TrackInfo(maxAgeUnlimited: true) + let info = TrackInfo(maxAge: nil) let unlimited = try broadcast.publishTrack(name: "unlimited", info: info).consume().info() XCTAssertNil(unlimited.maxAge) - XCTAssertTrue(unlimited.maxAgeUnlimited) try broadcast.close() } func testRawTrackTimestamps() async throws { let broadcast = try BroadcastProducer() - let track = try broadcast.publishTrack(name: "events", info: TrackInfo(timescale: 1_000_000)) + let track = try broadcast.publishTrack(name: "events", info: TrackInfo(maxAge: 0, timescale: 1_000_000)) let consumer = try track.consume() let payload = Data("ready".utf8) @@ -822,7 +821,7 @@ final class SmokeTests: XCTestCase { func testTimestampsAreExact() async throws { let broadcast = try BroadcastProducer() - let track = try broadcast.publishTrack(name: "video", info: TrackInfo(timescale: 90_000)) + let track = try broadcast.publishTrack(name: "video", info: TrackInfo(maxAge: 0, timescale: 90_000)) let consumer = try track.consume() // A present zero stays present, and one 90 kHz tick reads back as itself rather than @@ -883,7 +882,7 @@ final class SmokeTests: XCTestCase { func testReadFrameSkipsEmptyThenPopulatedGroups() async throws { let broadcast = try BroadcastProducer() - let track = try broadcast.publishTrack(name: "status", info: TrackInfo(timescale: 1_000_000)) + let track = try broadcast.publishTrack(name: "status", info: TrackInfo(maxAge: 0, timescale: 1_000_000)) let consumer = try track.consume() try track.appendGroup().finish() @@ -1008,7 +1007,7 @@ final class SmokeTests: XCTestCase { catalog: Media.CatalogProducer(broadcast: broadcast), input: VideoEncoderInput( format: .rgba, width: 320, height: 240, framerate: Video.FrameRate(numerator: 30000, denominator: 1001)), - output: VideoEncoderOutput(codec: .h264, kind: .software), + output: VideoEncoderOutput(codec: VideoCodec.h264(), kind: .software), track: "camera" ) try route.announce() From d5912736717a4f176db6fc24658dfdb98e18cc5b Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 07:19:25 -0800 Subject: [PATCH 3/6] style: format the binding tests --- dart/moq/test/moq_test.dart | 10 +--- .../kotlin/dev/moq/Aliases.kt | 3 +- .../kotlin/dev/moq/SmokeTest.kt | 57 ++++++++++++++----- kt/moq/src/jvmTest/kotlin/dev/moq/FfiBench.kt | 5 +- swift/Tests/MoqTests/SmokeTests.swift | 3 +- 5 files changed, 54 insertions(+), 24 deletions(-) diff --git a/dart/moq/test/moq_test.dart b/dart/moq/test/moq_test.dart index f8fa33ab14b..b000d9bf18e 100644 --- a/dart/moq/test/moq_test.dart +++ b/dart/moq/test/moq_test.dart @@ -912,10 +912,7 @@ void main() { broadcast: broadcast, track: broadcast.publishTrack( name: 'status', - info: TrackInfo( - timescale: 1000000, - compression: Compression.deflate(), - ), + info: TrackInfo(timescale: 1000000, compression: Compression.deflate()), ), config: moq_json.SnapshotConfig(), ); @@ -951,10 +948,7 @@ void main() { final producer = moq_json.WindowProducer( track: broadcast.publishTrack( name: 'log', - info: TrackInfo( - timescale: 1000000, - compression: Compression.deflate(), - ), + info: TrackInfo(timescale: 1000000, compression: Compression.deflate()), ), config: moq_json.WindowConfig(), ); diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt index 1bd3e37c5dc..cb4360fec39 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt @@ -408,7 +408,8 @@ typealias ProtocolError = uniffi.moq.MoqProtocolError // directly. `dev.moq.media.Container` aliases `MoqContainer` for signatures, but its // variants still need the full name (`uniffi.moq.MoqContainer.Loc`). Enums // (AudioFormat) are fine: entry access through the alias works. Objects -// (AudioCodec, VideoCodec, Compression) expose constructors through the alias (`AudioCodec.opus()`). +// (AudioCodec, VideoCodec, Compression) expose constructors through the alias +// (`AudioCodec.opus()`). /** Writes live datagrams with an independent sequence counter and no cache. */ typealias DatagramProducer = uniffi.moq.MoqDatagramProducer diff --git a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt index 16b99ba1803..e5edc6b4db6 100644 --- a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt +++ b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt @@ -315,7 +315,11 @@ class SmokeTest { @Test fun `broadcast consumer fetches cached group`() = runTest { BroadcastProducer().use { broadcast -> - val track = broadcast.publishTrack("events", TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000_000uL)) + val track = + broadcast.publishTrack( + "events", + TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000_000uL), + ) val group = track.appendGroup() group.writeFrame( Frame( @@ -405,7 +409,11 @@ class SmokeTest { @Test fun `readFrame skips empty then populated groups`() = runTest { BroadcastProducer().use { broadcast -> - val track = broadcast.publishTrack("status", TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000_000uL)) + val track = + broadcast.publishTrack( + "status", + TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000_000uL), + ) val consumer = track.consume(null) track.appendGroup().finish() track.appendGroup().finish() @@ -444,10 +452,7 @@ class SmokeTest { val omitted = broadcast.publishTrack("omitted", null).consume(null).info() assertEquals(java.time.Duration.ZERO, omitted.maxAge) val unlimited = - broadcast - .publishTrack("unlimited", TrackInfo(maxAge = null)) - .consume(null) - .info() + broadcast.publishTrack("unlimited", TrackInfo(maxAge = null)).consume(null).info() assertNull(unlimited.maxAge) } } @@ -538,7 +543,9 @@ class SmokeTest { val track = broadcast.publishTrack( "ticks", - timestamp.scale?.let { TrackInfo(maxAge = java.time.Duration.ZERO, timescale = it) }, + timestamp.scale?.let { + TrackInfo(maxAge = java.time.Duration.ZERO, timescale = it) + }, ) val consumer = track.consume(null) track.writeFrame(Frame(payload = ByteArray(0), timestamp = timestamp)) @@ -551,7 +558,11 @@ class SmokeTest { @Test fun `out of range timestamps are refused`() { BroadcastProducer().use { broadcast -> - val track = broadcast.publishTrack("ticks", TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 90_000uL)) + val track = + broadcast.publishTrack( + "ticks", + TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 90_000uL), + ) for (timestamp in listOf( Timestamp(1uL, 0uL), @@ -593,7 +604,11 @@ class SmokeTest { fun `typed json snapshot round-trips a serializable value`() = runTest { BroadcastProducer().use { broadcast -> val config = SnapshotConfig(deltas = true) - val track = broadcast.publishTrack("status", TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000_000uL)) + val track = + broadcast.publishTrack( + "status", + TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000_000uL), + ) SnapshotProducer(broadcast, track, config).use { producer -> val consumer = SnapshotConsumer(broadcast.consume(), "status") for (n in 1..4) producer.update( @@ -625,7 +640,11 @@ class SmokeTest { val track = broadcast.publishTrack( "log", - TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000_000uL, compression = Compression.deflate()), + TrackInfo( + maxAge = java.time.Duration.ZERO, + timescale = 1_000_000uL, + compression = Compression.deflate(), + ), ) val producer = WindowProducer(track, config) val consumer = WindowConsumer(broadcast.consume().subscribeTrack("log", null)) @@ -662,7 +681,11 @@ class SmokeTest { fun `json producer demand follows subscribers`() = runTest { BroadcastProducer().use { broadcast -> val config = SnapshotConfig(deltas = false) - val track = broadcast.publishTrack("status", TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000uL)) + val track = + broadcast.publishTrack( + "status", + TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000uL), + ) SnapshotProducer(broadcast, track, config).use { producer -> val demand: TrackDemand = producer.demand() assertEquals("status", demand.name()) @@ -681,7 +704,11 @@ class SmokeTest { BroadcastProducer().use { broadcast -> val config = SnapshotConfig(deltas = false) // A demand watcher does not own the writer; keep it alive through collection. - val track = broadcast.publishTrack("status", TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000uL)) + val track = + broadcast.publishTrack( + "status", + TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000uL), + ) SnapshotProducer(broadcast, track, config).use { producer -> val demand: TrackDemand = producer.demand() producer.update(Status(state = "live"), Timestamp(1uL, 1_000uL)) @@ -704,7 +731,11 @@ class SmokeTest { fun `raw json string passes through unencoded`() = runTest { BroadcastProducer().use { broadcast -> val config = SnapshotConfig(deltas = false) - val track = broadcast.publishTrack("status", TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000uL)) + val track = + broadcast.publishTrack( + "status", + TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000uL), + ) SnapshotProducer(broadcast, track, config).use { producer -> producer.update("""{"state":"raw"}""", Timestamp(1uL, 1_000uL)) diff --git a/kt/moq/src/jvmTest/kotlin/dev/moq/FfiBench.kt b/kt/moq/src/jvmTest/kotlin/dev/moq/FfiBench.kt index 45adff7fa64..00f275afd6b 100644 --- a/kt/moq/src/jvmTest/kotlin/dev/moq/FfiBench.kt +++ b/kt/moq/src/jvmTest/kotlin/dev/moq/FfiBench.kt @@ -87,7 +87,10 @@ class FfiBench { val broadcast = route.broadcast() val tracks = (0 until case.publishers).map { - broadcast.publishTrack("$it", TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000_000uL)) + broadcast.publishTrack( + "$it", + TrackInfo(maxAge = java.time.Duration.ZERO, timescale = 1_000_000uL), + ) } val consumers = tracks.flatMap { track -> (0 until case.subscribers).map { track.consume(null) } diff --git a/swift/Tests/MoqTests/SmokeTests.swift b/swift/Tests/MoqTests/SmokeTests.swift index 59e327dd62f..eb8b4259564 100644 --- a/swift/Tests/MoqTests/SmokeTests.swift +++ b/swift/Tests/MoqTests/SmokeTests.swift @@ -674,7 +674,8 @@ final class SmokeTests: XCTestCase { let broadcast = try BroadcastProducer() let producer = try Json.WindowProducer( - track: try broadcast.publishTrack(name: "log", info: TrackInfo(maxAge: 0, timescale: 1_000_000, compression: Compression.deflate())) + track: try broadcast.publishTrack( + name: "log", info: TrackInfo(maxAge: 0, timescale: 1_000_000, compression: Compression.deflate())) ) let consumer = try Json.WindowConsumer( track: try await broadcast.consume().subscribeTrack(name: "log")) From 258a40a9966cce59edc59036adc0b906901e7314 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 07:28:32 -0800 Subject: [PATCH 4/6] fix(go,py): map an optional compression object and name the max age in raw records Co-Authored-By: Claude Opus 5.5 --- go/wrapper/moq_test.go | 28 ++++++++++++++++++++++++ go/wrapper/records.go | 6 +++-- py/moq-ffi/tests/exit_inside_callback.py | 2 +- 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/go/wrapper/moq_test.go b/go/wrapper/moq_test.go index beb66694860..f58f986cbde 100644 --- a/go/wrapper/moq_test.go +++ b/go/wrapper/moq_test.go @@ -650,6 +650,34 @@ func TestTrackInfoMaxAge(t *testing.T) { } } +// A compression survives the record mapping both ways, and nil reads back as none. +func TestTrackInfoCompression(t *testing.T) { + broadcast, err := moq.NewBroadcastProducer() + if err != nil { + t.Fatal(err) + } + for i, in := range []*moq.Compression{nil, moq.DeflateCompression()} { + track, err := broadcast.PublishTrack(fmt.Sprint(i), &moq.TrackInfo{Compression: in}) + if err != nil { + t.Fatal(err) + } + consumer, err := track.Consume(nil) + if err != nil { + t.Fatal(err) + } + got := consumer.Info().Compression + if in == nil && got != nil { + t.Errorf("case %d: Compression = %s, want none", i, got.Name()) + } + if in != nil && (got == nil || got.Name() != "deflate") { + t.Errorf("case %d: Compression = %v, want deflate", i, got) + } + } + if err := broadcast.Close(); err != nil { + t.Fatal(err) + } +} + func TestBroadcastConsumerClosed(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), testTimeout) defer cancel() diff --git a/go/wrapper/records.go b/go/wrapper/records.go index 47ba35468c0..9b0743272c8 100644 --- a/go/wrapper/records.go +++ b/go/wrapper/records.go @@ -191,7 +191,7 @@ func trackInfoFFI(info *TrackInfo) (*ffi.MoqTrackInfo, error) { Priority: info.Priority, Refresh: info.Refresh, Timescale: info.Timescale, - Compression: info.Compression, + Compression: optional(info.Compression), } if !info.MaxAgeUnlimited { out.MaxAge = &info.MaxAge @@ -205,11 +205,13 @@ func trackInfoFromFFI(info ffi.MoqTrackInfo) TrackInfo { MaxAgeUnlimited: info.MaxAge == nil, Refresh: info.Refresh, Timescale: info.Timescale, - Compression: info.Compression, } if info.MaxAge != nil { out.MaxAge = *info.MaxAge } + if info.Compression != nil { + out.Compression = *info.Compression + } return out } diff --git a/py/moq-ffi/tests/exit_inside_callback.py b/py/moq-ffi/tests/exit_inside_callback.py index 410acc25133..6e2f9cafbf5 100644 --- a/py/moq-ffi/tests/exit_inside_callback.py +++ b/py/moq-ffi/tests/exit_inside_callback.py @@ -56,7 +56,7 @@ async def main() -> None: origin = moq_ffi.MoqOriginProducer(moq_ffi.MoqOriginConfig()) route = origin.route("exit", moq_ffi.MoqRouteOptions()) broadcast = route.broadcast() - track = broadcast.publish_track("data", moq_ffi.MoqTrackInfo(timescale=1_000_000)) + track = broadcast.publish_track("data", moq_ffi.MoqTrackInfo(max_age=None, timescale=1_000_000)) consumer = await origin.consume().request("exit") subscriber = await consumer.subscribe_track("data", None) From 55d920f9bfa9416944ecbfece01fb2bc8f8b74ed Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 07:48:20 -0800 Subject: [PATCH 5/6] quest: finish the open-selector quest Co-Authored-By: Claude Opus 5.5 --- quest/m2/README.md | 3 +- quest/m2/congestion-names.md | 1 - quest/m2/ffi-open-selectors.md | 95 ---------------------------------- quest/m2/transport-names.md | 5 +- quest/m2/unused-api/README.md | 5 +- quest/m3/ffi-exporter.md | 4 +- quest/m4/track-info-docs.md | 8 +-- 7 files changed, 11 insertions(+), 110 deletions(-) delete mode 100644 quest/m2/ffi-open-selectors.md diff --git a/quest/m2/README.md b/quest/m2/README.md index 42df4d4cfa6..7bd79d6334c 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -73,8 +73,7 @@ removal, a rename, or a wire, catalog, or format change that is free until - **JS and browser.** [`@moq/net`](/quest/m2/js-net-api.md), [signals](/quest/m2/signals-semantics.md), [`@moq/ui`](/quest/m2/ui-private.md), and [room, publish, and OBS names](/quest/m2/browser-packages.md). -- **Bindings.** [Open selectors](/quest/m2/ffi-open-selectors.md), - [Dart as experimental](/quest/m2/dart-experimental.md), and +- **Bindings.** [Dart as experimental](/quest/m2/dart-experimental.md) and [the C API as `libmoq`](/quest/m2/libmoq-name.md), reversing 2026-10-25. The bindings break twice by decision: at 0.22, and again at [the exporter switch](/quest/m3/ffi-exporter.md). diff --git a/quest/m2/congestion-names.md b/quest/m2/congestion-names.md index 24ef7e3ebfa..2d74ce1b7d5 100644 --- a/quest/m2/congestion-names.md +++ b/quest/m2/congestion-names.md @@ -83,4 +83,3 @@ none. ## Related - [Realtime uplink congestion control](/quest/m4/quic-realtime.md) - its winner joins this enum under its own name -- [Open-set selectors in the bindings](/quest/m2/ffi-open-selectors.md) - the rule the binding selector already follows diff --git a/quest/m2/ffi-open-selectors.md b/quest/m2/ffi-open-selectors.md deleted file mode 100644 index c3cd0497c92..00000000000 --- a/quest/m2/ffi-open-selectors.md +++ /dev/null @@ -1,95 +0,0 @@ -# [M] Binding selectors can grow, and a null max age means unlimited - -## Goal - -A value in the bindings that names an open set, one Rust can add a member -to, never forces a breaking binding release when it grows. -`rs/moq-ffi/AGENTS.md` states the rule: a selector a caller passes is an -object with constructors, and an enum a caller reads has a catch-all. `MoqVideoCodec` and -`MoqCompression` are objects, as `MoqAudioCodec` and `MoqCongestionControl` -already are; `MoqTransport` and `MoqVideoSurface` have an unknown variant in -moq-ffi, so the wrappers' hand-written fences are gone. - -In `MoqTrackInfo`, a null `max_age` means no limit, as a null `MoqDelay.max` -does and as Rust, JS, and Python already read it, and `max_age_unlimited` is -gone. - -## Plan - -Decided 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): - -- ✅ Open the selectors: one rule in `rs/moq-ffi/AGENTS.md`, applied to - `MoqVideoCodec`, `MoqTransport`, `MoqVideoSurface`, and `MoqCompression` - (rejected: leaving them and treating every new variant as a break; also - collapsing `MoqError`, which is worth it only if the bindings were not - about to change exporter). -- ✅ `TrackInfo.max_age` null means unlimited and `max_age_unlimited` is - deleted (rejected: keeping both fields; leaving it for the exporter). -- Not selected, so unchanged: the `Moq` facade Kotlin and Dart start from, - where the other languages start from `Client`. -- The maintainer accepted that the bindings break again when - [the exporter switch](/quest/m3/ffi-exporter.md) lands, so this quest - makes only the reshapes that outlive the generator: a rule and these six - types. - -Facts found by the audit: - -- Swift, Kotlin, and Dart switch over enums exhaustively and the wrappers - alias the generated enums, so a new variant breaks source. Two selectors - were made objects for this reason: `MoqAudioCodec` - (`rs/moq-ffi/src/audio.rs:58-62`, "so adding a codec later does not break - callers switching over a closed enum") and `MoqCongestionControl` - (`session.rs:148`). -- Their siblings are closed while the Rust they mirror is open: - `MoqVideoCodec` (`video.rs:40`, two variants; AV1 or VP9 is a break); - `MoqTransport` (`server.rs:429`), where an unmapped transport makes - `transport()` fail with `Unsupported` (`:452`); `MoqVideoSurface` - (`video.rs:1126`), one variant with Android's `HardwareBuffer` planned, - which each wrapper fences by hand (`swift/Sources/Moq/Video.swift:62-75`, - and Swift's fence is itself a closed enum); `MoqCompression` - (`producer.rs:69`), one variant. -- `MoqTrackInfo.max_age` is "null for the default, zero", with - `max_age_unlimited` overriding it (`producer.rs:42-51`, conversion at - `:88-92`), while reading inverts it: `info()` reports unlimited as - `max_age: None` plus the flag (`:120`). `MoqDelay.max` is null for no - limit. Swift, Kotlin, Dart, C++, and generated C see the raw record, so - `TrackInfo(maxAge: nil)` serves only the live edge. - -For the PR: - -- Write the rule first, in `rs/moq-ffi/AGENTS.md`: a selector naming an open - set is an object; an enum a caller reads carries a catch-all in moq-ffi, - not in each wrapper; a null duration means no limit. Recommended third - clause: a new variant of a closed enum waits for an API cut, since - `sh/api-diff/run.sh` counts a line added inside an existing declaration as - a break (`:54-79`). -- `MoqVideoCodec` and `MoqCompression` become objects with one constructor - per member and a name accessor, following `MoqAudioCodec`. `MoqCompression` - is also read back from `info()`, so it needs equality or a name a caller - can compare. -- `MoqTransport` and `MoqVideoSurface` gain the catch-all; `transport()` - stops failing on a transport it cannot name; delete each wrapper's fence - (Swift, Dart, Python, Kotlin, Go) and take the generated one. -- `max_age` becomes a required field with no default, null for unlimited, - as `MoqSubscription.delay` is required. Python, Go, and Dart already - default an omitted value in the wrapper; check each still defaults to - zero, and that Swift and Kotlin callers must now state it. Remove the - flag from moq-ffi, the hand-written C API (`rs/moq-c/src/api.rs`), every - wrapper, and their tests. -- Follow the sync table from `rs/moq-ffi` outward: every wrapper, `cpp/moq`, - `cpp/obs` if it names a codec, each `doc/lib` page, and the Impact section - for each package's `MIGRATE.md`. Run `just test interop --all`. -- Fix `swift/README.md:67` while in the Swift docs: it says each `MoqError` - case carries `message: String`, which `swift/Sources/Moq/Errors.swift` - does not have. -- [Track info docs](/quest/m4/track-info-docs.md) describes the record after - this lands. - -Public API: breaking in every binding (two enums become objects, two gain a -variant, `max_age` changes meaning and `max_age_unlimited` is removed). -Wire: none. - -## Related - -- [Switch moq's bindings to rust2's exporter](/quest/m3/ffi-exporter.md) - the second binding break, which must keep these shapes -- [Bindings address groups by start](/quest/m2/time-addressing/bindings.md) - the other binding rename before the cut diff --git a/quest/m2/transport-names.md b/quest/m2/transport-names.md index a3c7cb56c89..3f7eeefd18f 100644 --- a/quest/m2/transport-names.md +++ b/quest/m2/transport-names.md @@ -61,8 +61,8 @@ For the PR: crates. Extend the relay's mapping and `is_public_transport` (a TLS link is public the same way plaintext TCP is; say so in its doc). - Mirror it in `@moq/auth`'s contract enum and in `MoqTransport` with every - wrapper. If [open-set selectors](/quest/m2/ffi-open-selectors.md) has - landed, `MoqTransport` is already an object and this adds a constructor. + wrapper. `MoqTransport` carries an `Unknown` variant (the open-set rule in + `rs/moq-ffi/AGENTS.md`), so `Tls` joins as a named variant before the cut. - Grep for consumers of the `"tcp"` string: relay metrics labels (`rs/moq-relay/src/internal.rs` uses `"tcp"` for the listener, which stays, since the listener is one TCP port), stats labels, `doc/bin/relay`, @@ -83,5 +83,4 @@ and logs. Wire: none. ## Related -- [Open-set selectors in the bindings](/quest/m2/ffi-open-selectors.md) - makes `MoqTransport` able to grow without a break - [The unused transport API](/quest/m2/unused-api/transport.md) - removes `Transport::WebRtc` from the same enum diff --git a/quest/m2/unused-api/README.md b/quest/m2/unused-api/README.md index 5e66951e21b..85d751027e0 100644 --- a/quest/m2/unused-api/README.md +++ b/quest/m2/unused-api/README.md @@ -32,9 +32,8 @@ into moq-ffi. Not part of the sweep, because each has its own quest: socket endpoints ([removed for Kixel](/quest/m2/sockets/README.md)), `setup::Extensions` -([the ietf extension](/quest/m2/ietf-records-per-track.md)), the public -route API ([the route switch](/quest/m2/multicast/switch.md)), and the -bindings' selectors ([open selectors](/quest/m2/ffi-open-selectors.md)). +([the ietf extension](/quest/m2/ietf-records-per-track.md)), and the public +route API ([the route switch](/quest/m2/multicast/switch.md)). Public API: each child lists what leaves. Wire: none. diff --git a/quest/m3/ffi-exporter.md b/quest/m3/ffi-exporter.md index 9c097c78409..252d2a81df8 100644 --- a/quest/m3/ffi-exporter.md +++ b/quest/m3/ffi-exporter.md @@ -140,8 +140,8 @@ So "wrapper APIs do not change" in the bullets above, carried over from the abandoned fork plan, is a property to measure, not assume: the switch's PR diffs each language's public API (`sh/api-diff`) and its Impact section lists every rename for the packages' `MIGRATE.md`. Reshapes that outlive the generator -land before the cut instead, in -[the selector quest](/quest/m2/ffi-open-selectors.md) and +land before the cut instead: the open-set rule in `rs/moq-ffi/AGENTS.md` +(selector objects, `Unknown` variants, and a null `max_age` for no limit) and [the group rename](/quest/m2/time-addressing/bindings.md); the switch keeps those shapes. The audit's other binding findings were not picked: the `Moq` facade Kotlin and Dart start from stays, and `MoqError`'s variants stay as diff --git a/quest/m4/track-info-docs.md b/quest/m4/track-info-docs.md index 01ec9b81587..b4f5a31a073 100644 --- a/quest/m4/track-info-docs.md +++ b/quest/m4/track-info-docs.md @@ -17,10 +17,10 @@ The docs say "priority, ordering, latency budget, and timescale" (Kotlin, Dart) and "priority, group ordering, max age, and timescale" (Swift). `MoqTrackInfo` (`rs/moq-ffi/src/producer.rs`) has `priority`, `max_age`, `refresh`, `timescale` and `compression`. Ordering and delay are subscriber-side -(`MoqSubscription`). #7729 added `max_age_unlimited`, which -[the selector quest](/quest/m2/ffi-open-selectors.md) deletes in favor of a -null `max_age` (decided 2026-11-16), so describe the record as it stands -when this lands. +(`MoqSubscription`). #7729 added `max_age_unlimited`, since deleted from +moq-ffi in favor of a null `max_age` meaning no limit; Go and the C API keep a +`MaxAgeUnlimited` / `max_age_unlimited` flag, since a zeroed struct there +cannot hold null. - Name the fields, or describe the record's purpose without a list that can drift. Prefer the one-line purpose plus a pointer to the record, so a new From 16d3d8dfa2b3a309421eed958cd1a87b92e11f53 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Mon, 16 Nov 2026 13:52:28 -0800 Subject: [PATCH 6/6] fix(cpp,swift): the probe keeps a zero max age, and the Swift JSON example names a timescale Co-Authored-By: Claude Opus 5.5 --- cpp/moq/test/probe.cpp | 2 ++ swift/README.md | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/cpp/moq/test/probe.cpp b/cpp/moq/test/probe.cpp index 171f8054ea4..594849b893e 100644 --- a/cpp/moq/test/probe.cpp +++ b/cpp/moq/test/probe.cpp @@ -146,6 +146,7 @@ void timestamp_roundtrip() { auto broadcast = ok(moq::BroadcastProducer::init(), "timestamp broadcast"); moq::TrackInfo timed; + timed.max_age = std::chrono::nanoseconds::zero(); timed.timescale = 90000; auto track = ok(broadcast->publish_track("timed", timed), "publish timed track"); auto consumer = ok(track->consume(std::nullopt), "consume timed track"); @@ -367,6 +368,7 @@ int main() CHECK(route->instance_id() && !route->instance_id()->is_minted()); auto broadcast = route->broadcast(); moq::TrackInfo info; + info.max_age = std::chrono::nanoseconds::zero(); info.timescale = 1000000; auto track = ok(broadcast->publish_track("data", info), "publish_track"); ok(route->announce(), "announce"); diff --git a/swift/README.md b/swift/README.md index 9e8deecf354..c8baef7b26e 100644 --- a/swift/README.md +++ b/swift/README.md @@ -96,7 +96,7 @@ zero `delay.max`. You opt into one of three distinct modes: `Json.SnapshotProduc (lossless append-log, every record preserved in order), or `Json.WindowProducer`/`Json.WindowConsumer` (a sliding window of records a reader can join at any point, not advertised in the catalog). Values encode/decode at the boundary with `JSONEncoder`/`JSONDecoder`; the consumer is an `AsyncSequence` of the decoded type. Publish the -track with `TrackInfo(maxAge: 0, compression: Compression.deflate())`; consumers read it the same either way. Every JSON write +track with `TrackInfo(maxAge: 0, timescale: 1_000_000, compression: Compression.deflate())`; consumers read it the same either way. Every JSON write (snapshot update, stream append, window push or pop) takes a timestamp on the broadcast clock (`Media.CatalogProducer.now()`), so the track needs a timescale.