From 9766bf689fe9fd5c07003f678bc09fde9d042f94 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 4 Nov 2026 02:06:49 -0800 Subject: [PATCH 1/9] chore(quest): claim quest/m1/datagram-tracks/bindings.md Quest-Claim: e21fda718f28f020 From 63e89cfd5676f94656215e618e892338b076f7e3 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 4 Nov 2026 02:27:34 -0800 Subject: [PATCH 2/9] feat(bindings)!: expose independent datagram tracks Co-Authored-By: GPT-6.1 Sol --- c/moq/MIGRATE.md | 4 + cpp/moq/MIGRATE.md | 4 + cpp/moq/test/probe.cpp | 25 + dart/moq/MIGRATE.md | 4 + dart/moq/lib/src/aliases.dart | 15 + dart/moq/test/moq_test.dart | 25 + dart/moq_ffi/MIGRATE.md | 4 + doc/lib/c/index.md | 2 +- doc/lib/index.md | 2 +- go/ffi/MIGRATE.md | 4 + go/wrapper/MIGRATE.md | 4 + go/wrapper/README.md | 15 +- go/wrapper/datagram.go | 147 +++++ go/wrapper/moq_test.go | 29 +- go/wrapper/publish.go | 12 - go/wrapper/records.go | 3 + go/wrapper/subscribe.go | 11 - kt/README.md | 2 +- kt/moq-ffi/MIGRATE.md | 4 + kt/moq/MIGRATE.md | 4 + .../kotlin/dev/moq/Aliases.kt | 15 + .../jvmAndAndroidMain/kotlin/dev/moq/Flows.kt | 6 +- .../kotlin/dev/moq/SmokeTest.kt | 24 + py/moq-ffi/MIGRATE.md | 4 + py/moq-rs/MIGRATE.md | 4 + py/moq-rs/README.md | 13 +- py/moq-rs/docs/index.md | 4 + py/moq-rs/moq/__init__.py | 7 + py/moq-rs/moq/_records.py | 3 + py/moq-rs/moq/datagram.py | 131 ++++ py/moq-rs/moq/publish.py | 32 +- py/moq-rs/moq/subscribe.py | 17 +- py/moq-rs/moq/types.py | 2 + py/moq-rs/tests/test_local.py | 35 +- rs/moq-c/MIGRATE.md | 8 +- rs/moq-c/src/api.rs | 27 +- rs/moq-c/src/consume.rs | 117 ++-- rs/moq-c/src/datagram.rs | 257 ++++++++ rs/moq-c/src/lib.rs | 2 + rs/moq-c/src/publish.rs | 311 +++++++--- rs/moq-c/src/test.rs | 104 +++- rs/moq-ffi/MIGRATE.md | 14 +- rs/moq-ffi/src/consumer.rs | 124 +--- rs/moq-ffi/src/datagram.rs | 326 ++++++++++ rs/moq-ffi/src/lib.rs | 1 + rs/moq-ffi/src/media.rs | 9 +- rs/moq-ffi/src/producer.rs | 177 ++---- rs/moq-ffi/src/test.rs | 567 ++++-------------- swift/MIGRATE.md | 4 + swift/README.md | 13 +- swift/Sources/Moq/Aliases.swift | 3 + swift/Sources/Moq/Datagram.swift | 136 +++++ swift/Sources/Moq/Track.swift | 29 +- swift/Tests/MoqTests/SmokeTests.swift | 24 + swift/ffi/MIGRATE.md | 4 + 55 files changed, 1860 insertions(+), 1014 deletions(-) create mode 100644 go/wrapper/datagram.go create mode 100644 py/moq-rs/moq/datagram.py create mode 100644 rs/moq-c/src/datagram.rs create mode 100644 rs/moq-ffi/src/datagram.rs create mode 100644 swift/Sources/Moq/Datagram.swift diff --git a/c/moq/MIGRATE.md b/c/moq/MIGRATE.md index 48c82e836c2..142a63ad1a0 100644 --- a/c/moq/MIGRATE.md +++ b/c/moq/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Separate datagram tracks + +Create a separate producer with `moq_publish_datagrams` and `moq_datagram_info`; replace `moq_publish_track_datagram` with `moq_publish_datagrams_append` on that handle, or `moq_publish_datagrams_insert` for an explicit sequence. `moq_consume_datagrams` now takes a subscriber priority before its callback and never subscribes to a stream track. Use `moq_publish_datagrams_demand` and `moq_datagram_demand_priority` for aggregate priority, and `moq_publish_datagrams_requests` / `moq_datagram_request_accept` for on-demand publishing. Finish or abort datagram producers separately. A zeroed datagram info is untimed, unlike the microsecond default of stream-track info. + ### Viewer targets are bounded ([#7090](https://github.com/moq-dev/moq/pull/7090)) Viewer ceilings and PROBE target overrides are refused with the new `MOQ_ERROR_OUT_OF_RANGE` once they would sum above 2^53 - 1 bps, the most a PROBE target carries; nothing changes on a refusal. `moq_viewers_watch`, `moq_viewers_set_target`, and `moq_viewer_update` return it. Handle the new variant wherever you match the error exhaustively. Regenerate bindings and rebuild the matching native library together. diff --git a/cpp/moq/MIGRATE.md b/cpp/moq/MIGRATE.md index 07314ea0fd7..b58893d9778 100644 --- a/cpp/moq/MIGRATE.md +++ b/cpp/moq/MIGRATE.md @@ -2,6 +2,10 @@ ## Unreleased +### Separate datagram tracks + +Replace stream-track datagram methods with `BroadcastProducer::create_datagrams(name, info)` and `BroadcastConsumer::datagrams(name)`. The generated `DatagramProducer` exposes `append(timestamp, payload)` and `insert(Datagram)`; `DatagramConsumer::recv()` returns an optional datagram through a future. `DatagramInfo` has only priority and optional timescale. Demand is aggregate subscriber `priority()` / `priority_changed(last)`; on-demand datagram requests come from `BroadcastRequests::datagrams()` / `DatagramRequests::requested()`. Stream tracks of the same name are independent. + ### Viewer targets are bounded ([#7090](https://github.com/moq-dev/moq/pull/7090)) Viewer ceilings and PROBE target overrides are refused with the new `moq::Error::kOutOfRange` once they would sum above 2^53 - 1 bps, the most a PROBE target carries; nothing changes on a refusal. `Viewers::watch` and `set_target` and `Viewer::update` return a `moq::expected` carrying it. Handle the new variant wherever you match the error exhaustively. Regenerate bindings and rebuild the matching native library together. diff --git a/cpp/moq/test/probe.cpp b/cpp/moq/test/probe.cpp index 706a8984065..7e0b4004636 100644 --- a/cpp/moq/test/probe.cpp +++ b/cpp/moq/test/probe.cpp @@ -114,6 +114,30 @@ bool same_time(const moq::Timestamp &a, const moq::Timestamp &b) // Timestamps are exact records: a 90 kHz tick and a present zero read back as written, an // untimed frame reads back untimed, and a record past the bounds is refused. +void datagram_tracks() +{ + auto broadcast = ok(moq::BroadcastProducer::init(), "datagram broadcast"); + auto stream = ok(broadcast->publish_track("events", std::nullopt), "stream"); + auto requests = ok(broadcast->requests(), "requests"); + auto datagrams = ok(requests->datagrams(), "datagram requests"); + auto source = ok(broadcast->consume(), "broadcast consumer"); + auto consumer = ok(source->datagrams("events"), "datagram consumer"); + ok(consumer->set_priority(12), "priority update"); + auto request = ok(datagrams->requested().get(), "datagram request"); + CHECK(ok(request->name(), "request name") == "events"); + auto producer = ok(request->accept(std::nullopt), "accept datagrams"); + CHECK(ok(producer->priority(), "aggregate priority") == 12); + CHECK(!ok(stream->demand(), "stream demand")->wanted()); + ok(producer->insert({7, std::nullopt, bytes("seven")}), "insert datagram"); + auto received = ok(consumer->recv().get(), "receive datagram"); + CHECK(received && received->sequence == 7 && received->payload == bytes("seven")); + consumer->cancel(); + CHECK(!ok(producer->priority_changed(12).get(), "released demand")); + ok(producer->finish(), "finish datagrams"); + datagrams->cancel(); + ok(broadcast->close(), "close datagram broadcast"); +} + void timestamp_roundtrip() { auto broadcast = ok(moq::BroadcastProducer::init(), "timestamp broadcast"); @@ -236,6 +260,7 @@ void audio_roundtrip() int main() { timestamp_roundtrip(); + datagram_tracks(); subscription_defaults(); audio_roundtrip(); auto timebase_owner = ok(moq::BroadcastProducer::init(), "timebase owner"); diff --git a/dart/moq/MIGRATE.md b/dart/moq/MIGRATE.md index 3b8b4f43267..082ea9dee42 100644 --- a/dart/moq/MIGRATE.md +++ b/dart/moq/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Separate datagram tracks + +Use `BroadcastProducer.createDatagrams(name: ..., info: ...)` and `BroadcastConsumer.datagrams(name: ...)` instead of stream-track datagram methods. `DatagramProducer.append(timestamp: ..., payload: ...)` assigns a sequence and `insert(datagram: ...)` preserves one; `DatagramConsumer.recv()` reads its own live cursor. `DatagramInfo` contains priority and optional timescale. Watch `priority()` / `priorityChanged(last: ...)` and serve on-demand tracks through `BroadcastRequests.datagrams()` / `DatagramRequests.requested()`. + ### Viewer targets are bounded ([#7090](https://github.com/moq-dev/moq/pull/7090)) Viewer ceilings and PROBE target overrides are refused with the new `OutOfRangeMoqException` once they would sum above 2^53 - 1 bps, the most a PROBE target carries; nothing changes on a refusal. `Viewers.watch` and `setTarget` and `Viewer.update` throw it. Handle the new variant wherever you match the error exhaustively. Regenerate bindings and rebuild the matching native library together. diff --git a/dart/moq/lib/src/aliases.dart b/dart/moq/lib/src/aliases.dart index fde53ff777c..59103941f61 100644 --- a/dart/moq/lib/src/aliases.dart +++ b/dart/moq/lib/src/aliases.dart @@ -240,3 +240,18 @@ typedef ProtocolKind = MoqProtocolKind; /// A protocol failure: scope, verbatim wire code, kind, and a diagnostic message. typedef ProtocolException = MoqProtocolException; + +/// Writes live datagrams with an independent sequence counter and no cache. +typedef DatagramProducer = MoqDatagramProducer; + +/// Reads a live datagram track in arrival order from its own cursor. +typedef DatagramConsumer = MoqDatagramConsumer; + +/// A requested datagram track awaiting acceptance or rejection. +typedef DatagramRequest = MoqDatagramRequest; + +/// Serves on-demand datagram tracks through their own request queue. +typedef DatagramRequests = MoqDatagramRequests; + +/// Publisher priority and optional timestamp scale fixed for a datagram track. +typedef DatagramInfo = MoqDatagramInfo; diff --git a/dart/moq/test/moq_test.dart b/dart/moq/test/moq_test.dart index 1124c71e377..ab121771e18 100644 --- a/dart/moq/test/moq_test.dart +++ b/dart/moq/test/moq_test.dart @@ -19,6 +19,31 @@ Future nextRoute(AnnounceConsumer announced) async { } void main() { + test('datagram-only requests have independent priority demand', () async { + final broadcast = BroadcastProducer(); + final stream = broadcast.publishTrack(name: 'events', info: null); + final requests = broadcast.requests().datagrams(); + final consumer = broadcast.consume().datagrams(name: 'events'); + consumer.setPriority(priority: 12); + final request = await requests.requested().timeout(timeout); + expect(request.name(), 'events'); + expect(request.priority(), 12); + final producer = request.accept(info: null); + expect(producer.priority(), 12); + expect(stream.demand().wanted(), isNull); + producer.insert( + datagram: Datagram(sequence: 7, payload: utf8.encode('seven')), + ); + final datagram = await consumer.recv().timeout(timeout); + expect(datagram?.sequence, 7); + expect(datagram?.payload, utf8.encode('seven')); + consumer.cancel(); + expect(await producer.priorityChanged(last: 12).timeout(timeout), isNull); + producer.finish(); + requests.cancel(); + broadcast.close(); + }); + test('container timebase belongs to one broadcast', () { final owner = BroadcastProducer(); final other = BroadcastProducer(); diff --git a/dart/moq_ffi/MIGRATE.md b/dart/moq_ffi/MIGRATE.md index df3475adb81..99ddbdd3834 100644 --- a/dart/moq_ffi/MIGRATE.md +++ b/dart/moq_ffi/MIGRATE.md @@ -2,6 +2,10 @@ ## Unreleased +### Separate datagram tracks + +Generated bindings now expose separate `MoqDatagramProducer`, `MoqDatagramConsumer`, `MoqDatagramInfo`, `MoqDatagramRequest`, and `MoqDatagramRequests` types. Create or subscribe through the broadcast's datagram methods, write with `append` / `insert`, and read with `recv`; stream-track datagram methods are removed. Demand is aggregate subscriber priority, and the broadcast request handler has a separate `datagrams` queue. Regenerate and rebuild native bindings together with your wrapper. + ### Viewer targets are bounded ([#7090](https://github.com/moq-dev/moq/pull/7090)) Viewer ceilings and PROBE target overrides are refused with the new `OutOfRangeMoqException` once they would sum above 2^53 - 1 bps, the most a PROBE target carries; nothing changes on a refusal. `MoqViewers.watch` and `setTarget` and `MoqViewer.update` throw it. Handle the new variant wherever you match the error exhaustively. Regenerate bindings and rebuild the matching native library together. diff --git a/doc/lib/c/index.md b/doc/lib/c/index.md index 64763727acd..f59d7597dde 100644 --- a/doc/lib/c/index.md +++ b/doc/lib/c/index.md @@ -110,7 +110,7 @@ inside. The header is the reference: each function carries a doc comment. - **Discovery.** Announcement captures are always a list of wildcard matches, empty when the filter has no wildcards. - **Ending cleanly.** When the input ends, finish every track, then call `moq_publish_catalog_finish()` to finish the catalog, which ends the content. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `moq_publish_close()` takes it offline. How long to keep it up is yours to decide. A track still open at the close ends with `UNROUTABLE` (an internal error over moq-transport, which has no such code), and its handle is released. Readers follow a publisher's runs by announcement, not by that error: see [identity and recovery](/concept/identity). - **Timeline breaks.** On a seek or pause, call `moq_publish_media_discontinuity`, then keep timestamps moving forward and resume video on a keyframe. -- **Timestamps.** A `moq_timestamp` is exact: `value` units at `scale` units per second, so a 90 kHz tick survives a read and republish. Frames, datagrams, and JSON values point `timestamp` at theirs, NULL on an untimed track and valid as long as the payload. Tracks moq-c creates are timed, so their raw writes need one. Stamp media frames and JSON writes from `moq_publish_catalog_now()`, the broadcast clock every track in the broadcast shares; media on a timeline of its own advertises the gap to the JSON tracks as catalog `delay`. JSON writes are converted to their track's milliseconds. A NULL timestamp on any JSON write (snapshot update, stream append, window push or pop) fails with `MOQ_ERROR_INVALID_POINTER` and publishes nothing. A zero scale or an out-of-range value fails with `MOQ_ERROR_TIMESTAMP_OVERFLOW`. +- **Timestamps.** A `moq_timestamp` is exact: `value` units at `scale` units per second, so a 90 kHz tick survives a read and republish. Frames, datagrams, and JSON values point `timestamp` at theirs, NULL on an untimed track and valid as long as the payload. Stream tracks moq-c creates are timed, so their raw writes need one. Datagram tracks are separate and default to untimed; set their timescale when creating them to require timestamps. Stamp media frames and JSON writes from `moq_publish_catalog_now()`, the broadcast clock every track in the broadcast shares; media on a timeline of its own advertises the gap to the JSON tracks as catalog `delay`. JSON writes are converted to their track's milliseconds. A NULL timestamp on any JSON write (snapshot update, stream append, window push or pop) fails with `MOQ_ERROR_INVALID_POINTER` and publishes nothing. A zero scale or an out-of-range value fails with `MOQ_ERROR_TIMESTAMP_OVERFLOW`. - **JSON values.** `moq_consume_json_value` fills `moq_json_value` with the document and its frame's timestamp. A snapshot consumer's callback fires for each state in order, but a group superseded before it is read is skipped. - **JSON windows.** `moq_publish_json_window` publishes a sliding run of records: `moq_publish_json_window_push` appends at the back, `moq_publish_json_window_pop` drops from the front, and `moq_publish_json_window_cut` closes the open group at a natural boundary. The catalog has no window mode, so a reader names the track. `moq_consume_json_window_event` fills `moq_json_window_event` with a push (the record at `start`, in `json`), a pop of `[start, end)`, or a skip of `[start, end)` that this reader joined too late to receive. Set `checkpoint_records` to bound what each new group restates for a window you never pop. - **Decoded reads.** `moq_decode_audio` and `moq_decode_video` deliver read ids in order: a frame, a gap where media was lost, or an end where the publisher stopped its encoder. Check `kind` on what `moq_decode_audio_read` or `moq_decode_video_read` writes. Free each id with `moq_decode_audio_read_free` or `moq_decode_video_read_free` promptly: a held video frame holds a decoder buffer, and the decoder stalls. A decoder reads everything the track still holds unless a live player sets `start` to `MOQ_DECODE_START_LATEST`, which joins at the newest group and skips the cached backlog. A decoder setup refusal reports `MOQ_ERROR_UNSUPPORTED_CONFIG` on its terminal callback, so the caller can try another rendition; later peer or decode failures retain their own error codes. diff --git a/doc/lib/index.md b/doc/lib/index.md index ddc34d5a9a0..7fdd728562b 100644 --- a/doc/lib/index.md +++ b/doc/lib/index.md @@ -69,7 +69,7 @@ how it looks in that language: - **Reconnect** automatically with backoff when the transport drops. - **Discover** broadcasts by prefix, wait for a specific one, or request one by path. Advertise an exact path (a created broadcast is invisible until announced), or claim a prefix and serve requests beneath it on demand. - **Publish and subscribe to media** with the hang catalog filled in from the bitstream, or hand over raw pixels and PCM and let the binding encode and decode (VideoToolbox, Media Foundation, NVENC, openh264, Opus). The built-in video encoder can follow the connection's send estimate. The audio decoder reports the playout delay to buffer ahead of the playhead, fixed or estimated from arrivals, so read each frame as soon as the last is handled rather than pacing reads to the speaker. -- **Raw tracks** of arbitrary bytes, with per-subscriber priority and max delay, and best-effort datagrams. +- **Raw stream tracks** of arbitrary bytes, with per-subscriber priority and max delay, and separate live datagram tracks without groups or caching. - **JSON tracks** as a latest value with merge-patch deltas, an append log, or a sliding window of records. Each value reads back with its frame timestamp, and a snapshot reader either replays every state or skips to the newest. - **Fetch** a single cached group by sequence. - **Catalog extensions**: write your own section next to `video` and `audio`, and read others' back. diff --git a/go/ffi/MIGRATE.md b/go/ffi/MIGRATE.md index b1665d13984..2bc8fde07ea 100644 --- a/go/ffi/MIGRATE.md +++ b/go/ffi/MIGRATE.md @@ -2,6 +2,10 @@ ## Unreleased +### Separate datagram tracks + +Generated bindings now expose separate `MoqDatagramProducer`, `MoqDatagramConsumer`, `MoqDatagramInfo`, `MoqDatagramRequest`, and `MoqDatagramRequests` types. Create or subscribe through the broadcast's datagram methods, write with `append` / `insert`, and read with `recv`; stream-track datagram methods are removed. Demand is aggregate subscriber priority, and the broadcast request handler has a separate `datagrams` queue. Regenerate and rebuild native bindings together with your wrapper. + ### Follow the core API migration guide These bindings are generated from moq-ffi. Apply every change in the diff --git a/go/wrapper/MIGRATE.md b/go/wrapper/MIGRATE.md index 08d483234ed..e62ca121aad 100644 --- a/go/wrapper/MIGRATE.md +++ b/go/wrapper/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Separate datagram tracks + +Replace stream-track `AppendDatagram` / `InsertDatagram` / `RecvDatagram` with `BroadcastProducer.CreateDatagrams(name, info)` and `BroadcastConsumer.Datagrams(name)`. `DatagramProducer.Append(timestamp, payload)` assigns a sequence and `Insert(Datagram)` preserves one. `DatagramConsumer.Recv(ctx)` and `All(ctx)` read its independent cursor. `DatagramInfo` carries priority and optional timescale. Watch `Priority()` / `PriorityChanged(ctx, last)` and serve on-demand tracks through `BroadcastRequests.Datagrams()` / `DatagramRequests.Requested(ctx)`. + ### Viewer targets are bounded ([#7090](https://github.com/moq-dev/moq/pull/7090)) Viewer ceilings and PROBE target overrides are refused with the new `ErrOutOfRange` once they would sum above 2^53 - 1 bps, the most a PROBE target carries; nothing changes on a refusal. `Viewers.Watch` returns `(*Viewer, error)`, and `Viewers.SetTarget` and `Viewer.Update` return an `error`. Handle the new variant wherever you match the error exhaustively. Regenerate bindings and rebuild the matching native library together. diff --git a/go/wrapper/README.md b/go/wrapper/README.md index 27feead3fa3..3983fe2a940 100644 --- a/go/wrapper/README.md +++ b/go/wrapper/README.md @@ -167,13 +167,14 @@ See the package doc for details. ## Raw datagrams -Raw tracks support best-effort datagrams alongside groups: `TrackProducer.AppendDatagram` -sends one `Frame` and returns its sequence number (`InsertDatagram` takes the caller's -own sequence instead), while `TrackConsumer.RecvDatagram` -and `TrackConsumer.Datagrams` receive them in arrival order. Payloads are capped at -1200 bytes. Datagram delivery requires a datagram-capable transport and lite-05 or -newer moq-lite; moq-transport, pre-lite-05, WebSocket, and TCP paths do not -deliver them, and there is no stream fallback. +Create a separate live track with `BroadcastProducer.CreateDatagrams(name, info)` and +subscribe with `BroadcastConsumer.Datagrams(name)`. `DatagramProducer.Append(timestamp, payload)` +assigns a sequence, `Insert(Datagram)` preserves one, and `DatagramConsumer.Recv(ctx)` or +`All(ctx)` reads in arrival order. Stream tracks of the same name are independent. +Watch aggregate subscriber demand with `Priority()` / `PriorityChanged(ctx, last)`, and +serve on-demand datagram tracks with `BroadcastRequests.Datagrams()`. +Keep payloads well below the path MTU. Delivery requires a datagram-capable transport and +lite-05 or newer; there is no stream fallback. ## Versioning diff --git a/go/wrapper/datagram.go b/go/wrapper/datagram.go new file mode 100644 index 00000000000..83e110773ea --- /dev/null +++ b/go/wrapper/datagram.go @@ -0,0 +1,147 @@ +package moq + +import ( + "context" + "iter" + + ffi "moq.dev/moq-ffi/moq" + "moq.dev/moq/internal/bridge" +) + +// CreateDatagrams creates a live datagram track in its own namespace. +func (b *BroadcastProducer) CreateDatagrams(name string, info *DatagramInfo) (*DatagramProducer, error) { + inner, err := b.inner.CreateDatagrams(name, info) + if err != nil { + return nil, err + } + return &DatagramProducer{inner: inner}, nil +} + +// Datagrams subscribes to a live datagram track from now on, without a stream subscription. +func (b *BroadcastConsumer) Datagrams(name string) (*DatagramConsumer, error) { + inner, err := b.inner.Datagrams(name) + if err != nil { + return nil, err + } + return &DatagramConsumer{inner: inner}, nil +} + +// DatagramProducer writes datagrams with an independent sequence counter and no cache. +type DatagramProducer struct{ inner *ffi.MoqDatagramProducer } + +// Name is the datagram track's name within its broadcast. +func (p *DatagramProducer) Name() (string, error) { return p.inner.Name() } + +// Info returns the track's fixed publisher properties. +func (p *DatagramProducer) Info() (DatagramInfo, error) { return p.inner.Info() } + +// Append sends a datagram and returns its sequence; keep payloads below the path MTU. +func (p *DatagramProducer) Append(timestamp *Timestamp, payload []byte) (uint64, error) { + return p.inner.Append(timestamp, payload) +} + +// Insert sends a datagram at its explicit sequence; appends continue past the highest one. +func (p *DatagramProducer) Insert(datagram Datagram) error { return p.inner.Insert(datagram) } + +// Consume creates a local reader starting with the next datagram written. +func (p *DatagramProducer) Consume() (*DatagramConsumer, error) { + inner, err := p.inner.Consume() + if err != nil { + return nil, err + } + return &DatagramConsumer{inner: inner}, nil +} + +// Priority is the highest subscriber priority, or nil while nobody consumes this track. +func (p *DatagramProducer) Priority() (*int8, error) { return p.inner.Priority() } + +// PriorityChanged waits until aggregate subscriber priority differs from last. +func (p *DatagramProducer) PriorityChanged(ctx context.Context, last *int8) (*int8, error) { + return p.inner.PriorityChanged(ctx, last) +} + +// Finish ends the track; existing consumers drain their unread datagrams. +func (p *DatagramProducer) Finish() error { return p.inner.Finish() } + +// Abort ends the track with an application error and discards unread datagrams. +func (p *DatagramProducer) Abort(code uint16) error { return p.inner.Abort(code) } + +// DatagramConsumer reads live datagrams in arrival order from its own cursor. +type DatagramConsumer struct{ inner *ffi.MoqDatagramConsumer } + +// Name is the datagram track's name within its broadcast. +func (c *DatagramConsumer) Name() (string, error) { return c.inner.Name() } + +// Info waits for the publisher to accept the track and returns its properties. +func (c *DatagramConsumer) Info(ctx context.Context) (DatagramInfo, error) { + return bridge.Call(ctx, c.inner.Cancel, c.inner.Info) +} + +// Recv returns the next datagram, or (nil, nil) after the track finishes. +func (c *DatagramConsumer) Recv(ctx context.Context) (*Datagram, error) { + return bridge.Call(ctx, c.inner.Cancel, c.inner.Recv) +} + +// All ranges over datagrams in arrival order. +func (c *DatagramConsumer) All(ctx context.Context) iter.Seq2[*Datagram, error] { + return bridge.Seq(ctx, c.Recv) +} + +// Priority is this consumer's subscriber priority. +func (c *DatagramConsumer) Priority() (int8, error) { return c.inner.Priority() } + +// SetPriority changes this consumer's priority, higher first. +func (c *DatagramConsumer) SetPriority(priority int8) error { return c.inner.SetPriority(priority) } + +// Cancel stops reads and releases this consumer's demand. +func (c *DatagramConsumer) Cancel() { c.inner.Cancel() } + +// Datagrams creates an on-demand handler for datagram tracks. +func (r *BroadcastRequests) Datagrams() (*DatagramRequests, error) { + inner, err := r.inner.Datagrams() + if err != nil { + return nil, err + } + return &DatagramRequests{inner: inner}, nil +} + +// DatagramRequests serves on-demand datagram tracks through their own queue. +type DatagramRequests struct{ inner *ffi.MoqDatagramRequests } + +// Requested waits for the next datagram track requested by a consumer. +func (r *DatagramRequests) Requested(ctx context.Context) (*DatagramRequest, error) { + inner, err := bridge.CallHandle(ctx, r.inner.Cancel, r.inner.Requested) + if err != nil { + return nil, err + } + return &DatagramRequest{inner: inner}, nil +} + +// All ranges over on-demand datagram requests. +func (r *DatagramRequests) All(ctx context.Context) iter.Seq2[*DatagramRequest, error] { + return bridge.Seq(ctx, r.Requested) +} + +// Cancel stops the handler and rejects requests it has not handed out. +func (r *DatagramRequests) Cancel() { r.inner.Cancel() } + +// DatagramRequest is a requested datagram track awaiting acceptance or rejection. +type DatagramRequest struct{ inner *ffi.MoqDatagramRequest } + +// Name is the requested datagram track's name. +func (r *DatagramRequest) Name() (string, error) { return r.inner.Name() } + +// Priority is the highest priority among consumers waiting for this track. +func (r *DatagramRequest) Priority() (*int8, error) { return r.inner.Priority() } + +// Accept accepts the request with its fixed publisher properties. +func (r *DatagramRequest) Accept(info *DatagramInfo) (*DatagramProducer, error) { + inner, err := r.inner.Accept(info) + if err != nil { + return nil, err + } + return &DatagramProducer{inner: inner}, nil +} + +// Abort rejects this request with an application error code. +func (r *DatagramRequest) Abort(code uint16) error { return r.inner.Abort(code) } diff --git a/go/wrapper/moq_test.go b/go/wrapper/moq_test.go index 4ff1c20af46..138ad74eb58 100644 --- a/go/wrapper/moq_test.go +++ b/go/wrapper/moq_test.go @@ -543,30 +543,43 @@ func TestInsertDatagramAndLargest(t *testing.T) { if err != nil { t.Fatal(err) } - track, err := broadcast.PublishTrack("events", timedInfo()) + track, err := broadcast.CreateDatagrams("events", nil) if err != nil { t.Fatal(err) } - consumer, err := track.Consume(nil) + consumer, err := track.Consume() if err != nil { t.Fatal(err) } - if err := track.InsertDatagram(7, moq.Frame{Payload: []byte("seven"), Timestamp: ts(0)}); err != nil { + if err := track.Insert(moq.Datagram{Sequence: 7, Payload: []byte("seven")}); err != nil { t.Fatal(err) } - datagram, err := consumer.RecvDatagram(ctx) + datagram, err := consumer.Recv(ctx) if err != nil { t.Fatal(err) } if datagram == nil || datagram.Sequence != 7 || string(datagram.Payload) != "seven" { t.Fatalf("got datagram %+v", datagram) } - if next, err := track.AppendDatagram(moq.Frame{Payload: []byte("next"), Timestamp: ts(0)}); err != nil || next != 8 { + if next, err := track.Append(nil, []byte("next")); err != nil || next != 8 { t.Fatalf("appended at %d, err %v", next, err) } - // Datagrams are numbered apart from groups, so they never move Largest. - if largest, err := track.Largest(); err != nil || largest != nil { - t.Fatalf("largest %v, err %v", largest, err) + if err := consumer.SetPriority(12); err != nil { + t.Fatal(err) + } + if priority, err := track.Priority(); err != nil || priority == nil || *priority != 12 { + t.Fatalf("priority %v, error %v", priority, err) + } + consumer.Cancel() + last := int8(12) + if priority, err := track.PriorityChanged(ctx, &last); err != nil || priority != nil { + t.Fatalf("priority %v, error %v", priority, err) + } + if err := track.Finish(); err != nil { + t.Fatal(err) + } + if err := broadcast.Close(); err != nil { + t.Fatal(err) } } diff --git a/go/wrapper/publish.go b/go/wrapper/publish.go index 4a7d2fca318..7abebe48368 100644 --- a/go/wrapper/publish.go +++ b/go/wrapper/publish.go @@ -210,18 +210,6 @@ func (t *TrackProducer) WriteFrame(frame Frame) error { return t.inner.WriteFrame(frame) } -// AppendDatagram sends frame as a best-effort datagram and returns the sequence number -// assigned to it. Payloads are capped at 1200 bytes. There is no stream fallback. -func (t *TrackProducer) AppendDatagram(frame Frame) (uint64, error) { - return t.inner.AppendDatagram(frame) -} - -// InsertDatagram sends frame as a best-effort datagram at an explicit sequence, for a -// caller that allocates its own. AppendDatagram continues after the largest one. -func (t *TrackProducer) InsertDatagram(sequence uint64, frame Frame) error { - return t.inner.InsertDatagram(sequence, frame) -} - // Largest reports the newest group written, at its newest frame, or nil // before any. func (t *TrackProducer) Largest() (*Position, error) { diff --git a/go/wrapper/records.go b/go/wrapper/records.go index 286554ca169..bc21962dbda 100644 --- a/go/wrapper/records.go +++ b/go/wrapper/records.go @@ -49,6 +49,9 @@ type Frame = ffi.MoqFrame // (nil from an untimed track), and payload. type Datagram = ffi.MoqDatagram +// DatagramInfo fixes a datagram track's publisher priority and optional timestamp scale. +type DatagramInfo = ffi.MoqDatagramInfo + // Delay is how far behind the live edge a subscriber or decoder plays: where it starts, and // how late it may fall. The zero Delay is moq-net's default, a stated zero for both, which // starts at the newest group and skips a superseded group at once. diff --git a/go/wrapper/subscribe.go b/go/wrapper/subscribe.go index f2543c372e8..47b868f1639 100644 --- a/go/wrapper/subscribe.go +++ b/go/wrapper/subscribe.go @@ -149,12 +149,6 @@ func (t *TrackConsumer) ReadFrame(ctx context.Context) (*Frame, error) { return bridge.Call(ctx, t.inner.Cancel, t.inner.ReadFrame) } -// RecvDatagram returns the next best-effort datagram in arrival order, or -// (nil, nil) when the track ends. -func (t *TrackConsumer) RecvDatagram(ctx context.Context) (*Datagram, error) { - return bridge.Call(ctx, t.inner.Cancel, t.inner.RecvDatagram) -} - // Info returns the publisher-side track properties learned during subscription. func (t *TrackConsumer) Info() TrackInfo { return trackInfoFromFFI(t.inner.Info()) @@ -181,11 +175,6 @@ func (t *TrackConsumer) GroupsAsArrived(ctx context.Context) iter.Seq2[*GroupCon return bridge.Seq(ctx, t.RecvGroup) } -// Datagrams ranges over best-effort datagrams in arrival order. -func (t *TrackConsumer) Datagrams(ctx context.Context) iter.Seq2[*Datagram, error] { - return bridge.Seq(ctx, t.RecvDatagram) -} - // Cancel stops the stream. func (t *TrackConsumer) Cancel() { t.inner.Cancel() diff --git a/kt/README.md b/kt/README.md index fe9ecd6fe69..0cf7f99bfb9 100644 --- a/kt/README.md +++ b/kt/README.md @@ -62,7 +62,7 @@ The `dev.moq` package is intentionally thin: Kotlin has extension functions, so - **Fetched media**: `dev.moq.media.GroupConsumer.fetch(...).frames()` streams the decoded frames of one retained group, then completes. `dev.moq.media.GroupConsumer(group, container)` decodes a raw group instead, such as one from `recvGroup()` for arrival-order reads. - **Timestamp conversions** (`Timestamp.kt`): media timestamps are exact `Timestamp(value, scale)` records. `Duration.toTimestamp()` builds one exactly at nanosecond scale, and `Timestamp.toDuration()` reads one back as a `kotlin.time.Duration`, rounded down to a whole nanosecond. Durations such as `stats.rtt` are already `java.time.Duration`. - **`logLevel(...)`**: configures native Rust tracing without importing the raw bindings package. -- **Raw datagrams**: `TrackProducer.appendDatagram(Frame(payload, timestamp))` sends one best-effort frame and returns its sequence, and `insertDatagram(sequence, frame)` takes the caller's own; `TrackConsumer.recvDatagram()` and `datagrams()` receive them. Payloads are capped at 1200 bytes, require a datagram-capable transport plus lite-05 or newer moq-lite, and have no stream fallback. +- **Datagram tracks**: create with `BroadcastProducer.createDatagrams(name, info)` and subscribe with `BroadcastConsumer.datagrams(name)`. The separate producer uses `append(timestamp, payload)` / `insert(Datagram)`, and its consumer uses `recv()` / the `datagrams()` flow. Aggregate demand is `priority()` / `priorityChanged(last)`; on-demand requests come from `BroadcastRequests.datagrams()`. Keep payloads below the path MTU; delivery needs a datagram-capable transport and lite-05 or newer, with no stream fallback. - **`MoqException.isShutdown`** (`Errors.kt`): true for the graceful `Cancelled`/`Closed` cases. ## Versioning diff --git a/kt/moq-ffi/MIGRATE.md b/kt/moq-ffi/MIGRATE.md index 2f15dab034f..8087cad4ed8 100644 --- a/kt/moq-ffi/MIGRATE.md +++ b/kt/moq-ffi/MIGRATE.md @@ -2,6 +2,10 @@ ## Unreleased +### Separate datagram tracks + +Generated bindings now expose separate `MoqDatagramProducer`, `MoqDatagramConsumer`, `MoqDatagramInfo`, `MoqDatagramRequest`, and `MoqDatagramRequests` types. Create or subscribe through the broadcast's datagram methods, write with `append` / `insert`, and read with `recv`; stream-track datagram methods are removed. Demand is aggregate subscriber priority, and the broadcast request handler has a separate `datagrams` queue. Regenerate and rebuild native bindings together with your wrapper. + ### Viewer targets are bounded ([#7090](https://github.com/moq-dev/moq/pull/7090)) Viewer ceilings and PROBE target overrides are refused with the new `MoqException.OutOfRange` once they would sum above 2^53 - 1 bps, the most a PROBE target carries; nothing changes on a refusal. `MoqViewers.watch` and `setTarget` and `MoqViewer.update` throw it. Handle the new variant wherever you match the error exhaustively. Regenerate bindings and rebuild the matching native library together. diff --git a/kt/moq/MIGRATE.md b/kt/moq/MIGRATE.md index 1085c33056d..15fa94007ff 100644 --- a/kt/moq/MIGRATE.md +++ b/kt/moq/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Separate datagram tracks + +Replace stream-track `appendDatagram` / `insertDatagram` / `recvDatagram` with `BroadcastProducer.createDatagrams(name, info)` and `BroadcastConsumer.datagrams(name)`. The separate `DatagramProducer` has `append(timestamp, payload)` and `insert(Datagram)`; `DatagramConsumer` has `recv()` and the `datagrams()` flow. Use `priority()` / `priorityChanged(last)` for aggregate demand, and `BroadcastRequests.datagrams()` / `DatagramRequests.requested()` for on-demand tracks. `DatagramInfo` has only publisher priority and optional timescale. + ### Viewer targets are bounded ([#7090](https://github.com/moq-dev/moq/pull/7090)) Viewer ceilings and PROBE target overrides are refused with the new `MoqException.OutOfRange` once they would sum above 2^53 - 1 bps, the most a PROBE target carries; nothing changes on a refusal. `Viewers.watch` and `setTarget` and `Viewer.update` throw it. Handle the new variant wherever you match the error exhaustively. Regenerate bindings and rebuild the matching native library together. diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt index e9c10ada02d..9cc0e2e07df 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt @@ -341,3 +341,18 @@ typealias ProtocolError = uniffi.moq.MoqProtocolError // 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()`). + +/** Writes live datagrams with an independent sequence counter and no cache. */ +typealias DatagramProducer = uniffi.moq.MoqDatagramProducer + +/** Reads a live datagram track in arrival order from its own cursor. */ +typealias DatagramConsumer = uniffi.moq.MoqDatagramConsumer + +/** A requested datagram track awaiting acceptance or rejection. */ +typealias DatagramRequest = uniffi.moq.MoqDatagramRequest + +/** Serves on-demand datagram tracks through their own request queue. */ +typealias DatagramRequests = uniffi.moq.MoqDatagramRequests + +/** Publisher priority and optional timestamp scale fixed for a datagram track. */ +typealias DatagramInfo = uniffi.moq.MoqDatagramInfo diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Flows.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Flows.kt index 90e8ec7da82..1cb73bbe325 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Flows.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Flows.kt @@ -38,7 +38,7 @@ fun TrackConsumer.groupsAsArrived(): Flow = pull({ cancel() }) { fun TrackConsumer.frames(): Flow = pull({ cancel() }) { readFrame() } /** Stream of best-effort datagrams in arrival order. */ -fun TrackConsumer.datagrams(): Flow = pull({ cancel() }) { recvDatagram() } +fun DatagramConsumer.datagrams(): Flow = pull({ cancel() }) { recv() } /** Stream of tracks requested by subscribers. */ fun BroadcastRequests.requestedTracks(): Flow = @@ -99,3 +99,7 @@ private fun pull(next: suspend () -> T?): Flow = flow { */ internal fun pull(cancel: () -> Unit, next: suspend () -> T?): Flow = pull(next).onCompletion { cause -> if (cause is CancellationException) cancel() } + +/** Stream of datagram tracks requested by consumers. */ +fun DatagramRequests.requestedDatagrams(): Flow = + pull({ cancel() }) { requested() } diff --git a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt index 31b6c21613a..2dc654f579d 100644 --- a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt +++ b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt @@ -65,6 +65,30 @@ private fun opusHead(): ByteArray = ) class SmokeTest { + @Test + fun `datagram-only requests have independent priority demand`() = runTest { + BroadcastProducer().use { broadcast -> + val stream = broadcast.publishTrack("events", null) + val requests = broadcast.requests().datagrams() + val consumer = broadcast.consume().datagrams("events") + consumer.setPriority(12) + val request = requests.requested() + assertEquals("events", request.name()) + assertEquals(12.toByte(), request.priority()) + val producer = request.accept(null) + assertEquals(12.toByte(), producer.priority()) + assertNull(stream.demand().wanted()) + producer.insert(Datagram(7uL, null, "seven".encodeToByteArray())) + val datagram = assertNotNull(consumer.recv()) + assertEquals(7uL, datagram.sequence) + assertEquals("seven", datagram.payload.decodeToString()) + consumer.cancel() + assertNull(producer.priorityChanged(12)) + producer.finish() + requests.cancel() + } + } + @Test fun `destroyed object arguments are refused before native calls`() { val broadcast = BroadcastProducer() diff --git a/py/moq-ffi/MIGRATE.md b/py/moq-ffi/MIGRATE.md index ab1806ded62..6fa2a27f768 100644 --- a/py/moq-ffi/MIGRATE.md +++ b/py/moq-ffi/MIGRATE.md @@ -2,6 +2,10 @@ ## Unreleased +### Separate datagram tracks + +Generated bindings now expose separate `MoqDatagramProducer`, `MoqDatagramConsumer`, `MoqDatagramInfo`, `MoqDatagramRequest`, and `MoqDatagramRequests` types. Create or subscribe through the broadcast's datagram methods, write with `append` / `insert`, and read with `recv`; stream-track datagram methods are removed. Demand is aggregate subscriber priority, and the broadcast request handler has a separate `datagrams` queue. Regenerate and rebuild native bindings together with your wrapper. + ### Viewer targets are bounded ([#7090](https://github.com/moq-dev/moq/pull/7090)) Viewer ceilings and PROBE target overrides are refused with the new `MoqError.OutOfRange` once they would sum above 2^53 - 1 bps, the most a PROBE target carries; nothing changes on a refusal. `MoqViewers.watch` and `set_target` and `MoqViewer.update` raise it. Handle the new variant wherever you match the error exhaustively. Regenerate bindings and rebuild the matching native library together. diff --git a/py/moq-rs/MIGRATE.md b/py/moq-rs/MIGRATE.md index 27249eeaf44..c91e4961475 100644 --- a/py/moq-rs/MIGRATE.md +++ b/py/moq-rs/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Separate datagram tracks + +Replace stream-track `append_datagram` / `insert_datagram` / `recv_datagram` with `broadcast.create_datagrams(name, info)` and `broadcast.consume().datagrams(name)`. The returned `DatagramProducer` uses `append(payload, timestamp=...)` and `insert(Datagram(...))`; `DatagramConsumer` supports `recv()` and async iteration. `DatagramInfo` contains priority and optional timescale. Demand is `priority()` / `await priority_changed(last)`; on-demand handlers come from `broadcast.requests().datagrams()`. Stream tracks of the same name are independent. + ### Viewer targets are bounded ([#7090](https://github.com/moq-dev/moq/pull/7090)) Viewer ceilings and PROBE target overrides are refused with the new `moq.Error.OutOfRange` once they would sum above 2^53 - 1 bps, the most a PROBE target carries; nothing changes on a refusal. `Viewers.watch` and `set_target` and `Viewer.update` raise it. Handle the new variant wherever you match the error exhaustively. Regenerate bindings and rebuild the matching native library together. diff --git a/py/moq-rs/README.md b/py/moq-rs/README.md index 06a0a24f11f..7bbb2f5ef77 100644 --- a/py/moq-rs/README.md +++ b/py/moq-rs/README.md @@ -183,8 +183,6 @@ client = moq.Client( - `.finish()` ends at the live edge; the handle remains so `.abort(error_code)` can still run. - `.finish_at(final_sequence)` declares the first group that will never be produced while leaving lower groups writable. - `.abort(error_code)` terminates the track or group with an application error. - - `.append_datagram(payload, timestamp=None) -> sequence` (`TrackProducer`) sends a best-effort datagram. Payloads are capped at 1200 bytes and there is no stream fallback. - - `.insert_datagram(sequence, payload, timestamp=None)` (`TrackProducer`) sends one at the caller's own sequence. - `.largest() -> Position | None` (`TrackProducer`) reports the newest group written, at its newest frame. Datagrams are numbered apart from groups and never move it. ### Media @@ -244,7 +242,6 @@ same either way. Opaque bytes go on a plain `TrackProducer`. - `await .recv_group() → GroupConsumer | None`. Arrival order, which may be out of sequence. Prefer it when latency matters more than order. - `.groups_as_arrived()`. Async iterator over `recv_group()`. - `.read_frame() -> Frame | None` returns the first frame of the next group. Empty groups are skipped; `None` is track EOF. - - `await .recv_datagram() -> Datagram | None` for best-effort raw track datagrams. - `.info() → TrackInfo` - `.update(subscription)`. Change delivery priority, staleness, or group range after subscribing. - **`GroupConsumer`**. Async iterator of raw `Frame`s. @@ -295,3 +292,13 @@ Every handle whose cleanup is `cancel()` is an async context manager, so exiting - [`moq-ffi`](https://pypi.org/project/moq-ffi/). The raw UniFFI bindings this package wraps. Use it directly only if you need the unwrapped `Moq`-prefixed API. - [MoQ project](https://github.com/moq-dev/moq). Full monorepo with Rust server, TypeScript browser lib, and more. + +## Datagram tracks + +Create a separate live track with `broadcast.create_datagrams(name, info)` and subscribe +with `broadcast.consume().datagrams(name)`. The `DatagramProducer` writes with +`append(payload, timestamp=...)` or `insert(Datagram(...))`, and the `DatagramConsumer` +reads with `await recv()` or async iteration. Demand is aggregate subscriber `priority()` / +`await priority_changed(last)`; `broadcast.requests().datagrams()` handles on-demand tracks. +Keep payloads below the path MTU. Delivery needs a datagram-capable transport and lite-05 or +newer, without a stream fallback. Stream tracks of the same name are independent. diff --git a/py/moq-rs/docs/index.md b/py/moq-rs/docs/index.md index e563f229ac9..b342bfb7814 100644 --- a/py/moq-rs/docs/index.md +++ b/py/moq-rs/docs/index.md @@ -62,6 +62,9 @@ asyncio.run(main()) BroadcastRequests BroadcastRequest TrackProducer + DatagramProducer + DatagramRequests + DatagramRequest TrackDemand TrackRequests TrackRequest @@ -80,6 +83,7 @@ asyncio.run(main()) BroadcastConsumer TrackConsumer + DatagramConsumer GroupConsumer ``` diff --git a/py/moq-rs/moq/__init__.py b/py/moq-rs/moq/__init__.py index 016bb64095d..ada21ed35f0 100644 --- a/py/moq-rs/moq/__init__.py +++ b/py/moq-rs/moq/__init__.py @@ -11,6 +11,7 @@ from . import json as json from . import video as video from .client import Client, CongestionControl, connect, qlog_supported, versions +from .datagram import DatagramConsumer, DatagramProducer, DatagramRequest, DatagramRequests from .errors import is_auth, is_shutdown, protocol_error from .log import log_level from .origin import ( @@ -69,6 +70,7 @@ ConnectionState, ConnectionStats, Datagram, + DatagramInfo, Delay, ErrorScope, FetchGroupOptions, @@ -123,6 +125,11 @@ "ConnectionPhase", "ConnectionState", "Datagram", + "DatagramInfo", + "DatagramConsumer", + "DatagramProducer", + "DatagramRequest", + "DatagramRequests", "Delay", "Error", "ErrorScope", diff --git a/py/moq-rs/moq/_records.py b/py/moq-rs/moq/_records.py index 2f51ecfd577..a6cf14ad01d 100644 --- a/py/moq-rs/moq/_records.py +++ b/py/moq-rs/moq/_records.py @@ -127,6 +127,9 @@ class Datagram: timestamp: Timestamp | None payload: bytes + def _ffi(self) -> MoqDatagram: + return MoqDatagram(sequence=self.sequence, timestamp=_opt_ts(self.timestamp), payload=self.payload) + @staticmethod def _from_ffi(datagram: MoqDatagram) -> Datagram: return Datagram( diff --git a/py/moq-rs/moq/datagram.py b/py/moq-rs/moq/datagram.py new file mode 100644 index 00000000000..d1d66675019 --- /dev/null +++ b/py/moq-rs/moq/datagram.py @@ -0,0 +1,131 @@ +"""Live datagram tracks with their own producers, consumers, and requests.""" + +from __future__ import annotations + +from moq_ffi import MoqDatagramConsumer, MoqDatagramProducer, MoqDatagramRequest, MoqDatagramRequests + +from ._records import _opt_ts +from ._stream import _Stream +from .types import Datagram, DatagramInfo, Timestamp + + +class DatagramProducer: + """Writes live datagrams with an independent sequence counter and no cache.""" + + def __init__(self, inner: MoqDatagramProducer) -> None: + self._inner = inner + + @property + def name(self) -> str: + """The datagram track's name within its broadcast.""" + return self._inner.name() + + def info(self) -> DatagramInfo: + """The publisher properties fixed when this track was created.""" + return self._inner.info() + + def append(self, payload: bytes, *, timestamp: Timestamp | None = None) -> int: + """Send a datagram and return its sequence; keep the payload below the path MTU.""" + return self._inner.append(_opt_ts(timestamp), payload) + + def insert(self, datagram: Datagram) -> None: + """Send a datagram at its explicit sequence; appends continue past the highest one.""" + self._inner.insert(datagram._ffi()) + + def consume(self) -> DatagramConsumer: + """Create a local consumer starting with the next datagram written.""" + return DatagramConsumer(self._inner.consume()) + + def priority(self) -> int | None: + """The highest subscriber priority, or None while nobody consumes this track.""" + return self._inner.priority() + + async def priority_changed(self, last: int | None) -> int | None: + """Wait until aggregate subscriber priority differs from last.""" + return await self._inner.priority_changed(last) + + def finish(self) -> None: + """Finish the track; existing consumers drain their unread datagrams.""" + self._inner.finish() + + def abort(self, error_code: int) -> None: + """Abort the track with an application error, discarding unread datagrams.""" + self._inner.abort(error_code) + + +class DatagramConsumer(_Stream[Datagram]): + """Reads live datagrams in arrival order, starting when this consumer was created.""" + + def __init__(self, inner: MoqDatagramConsumer) -> None: + self._inner = inner + + @property + def name(self) -> str: + """The datagram track's name within its broadcast.""" + return self._inner.name() + + async def info(self) -> DatagramInfo: + """Wait for the publisher to accept the track and return its properties.""" + return await self._inner.info() + + async def recv(self) -> Datagram | None: + """Receive the next datagram, or None after the track finishes.""" + datagram = await self._inner.recv() + return None if datagram is None else Datagram._from_ffi(datagram) + + async def _next(self) -> Datagram | None: + return await self.recv() + + def priority(self) -> int: + """This consumer's subscriber priority.""" + return self._inner.priority() + + def set_priority(self, priority: int) -> None: + """Change this consumer's subscriber priority, higher first.""" + self._inner.set_priority(priority) + + def cancel(self) -> None: + """Cancel reads and release this consumer's demand.""" + self._inner.cancel() + + +class DatagramRequest: + """A requested datagram track awaiting acceptance or rejection.""" + + def __init__(self, inner: MoqDatagramRequest) -> None: + self._inner = inner + + @property + def name(self) -> str: + """The requested datagram track's name.""" + return self._inner.name() + + def priority(self) -> int | None: + """The highest priority among consumers waiting for this track.""" + return self._inner.priority() + + def accept(self, info: DatagramInfo | None = None) -> DatagramProducer: + """Accept the request with its fixed publisher properties.""" + return DatagramProducer(self._inner.accept(info)) + + def abort(self, error_code: int) -> None: + """Reject this request with an application error code.""" + self._inner.abort(error_code) + + +class DatagramRequests(_Stream[DatagramRequest]): + """Serves on-demand datagram tracks through their own request queue.""" + + def __init__(self, inner: MoqDatagramRequests) -> None: + self._inner = inner + + async def requested(self) -> DatagramRequest: + """Wait for the next datagram track requested by a consumer.""" + return DatagramRequest(await self._inner.requested()) + + async def _next(self) -> DatagramRequest: + return await self.requested() + + def cancel(self) -> None: + """Cancel the handler and reject requests it has not handed out.""" + self._inner.cancel() diff --git a/py/moq-rs/moq/publish.py b/py/moq-rs/moq/publish.py index 4b1482e1876..ed555cfe651 100644 --- a/py/moq-rs/moq/publish.py +++ b/py/moq-rs/moq/publish.py @@ -20,6 +20,7 @@ from ._records import _subscription, _track_info from ._stream import _Stream from .types import ( + DatagramInfo, Frame, Position, Subscription, @@ -28,6 +29,7 @@ ) if TYPE_CHECKING: + from .datagram import DatagramProducer, DatagramRequests from .subscribe import BroadcastConsumer, GroupConsumer, TrackConsumer @@ -122,24 +124,8 @@ def write_frame(self, payload: bytes, timestamp: Timestamp | None = None) -> Non """Write a single-frame group with its presentation timestamp.""" self._inner.write_frame(Frame(payload, timestamp)._ffi()) - def append_datagram(self, payload: bytes, timestamp: Timestamp | None = None) -> int: - """Send a best-effort datagram and return its sequence number. - - Payloads are capped at 1200 bytes. Datagram delivery requires a datagram-capable - transport and wire version; there is no stream fallback. - """ - return self._inner.append_datagram(Frame(payload, timestamp)._ffi()) - - def insert_datagram(self, sequence: int, payload: bytes, timestamp: Timestamp | None = None) -> None: - """Send a best-effort datagram at an explicit sequence number. - - For a caller that allocates its own sequences; :meth:`append_datagram` - continues after the largest one. - """ - self._inner.insert_datagram(sequence, Frame(payload, timestamp)._ffi()) - def largest(self) -> Position | None: - """The newest group written, at its newest frame; ``None`` before any. Datagrams never move it.""" + """The newest group written, at its newest frame; ``None`` before any.""" return self._inner.largest() def consume(self, subscription: Subscription | None = None) -> TrackConsumer: @@ -318,6 +304,12 @@ async def requested_track(self) -> TrackRequest: """Await the next track a subscriber requested but that isn't published yet.""" return TrackRequest(await self._inner.requested_track()) + def datagrams(self) -> DatagramRequests: + """Serve on-demand datagram tracks through their own request queue.""" + from .datagram import DatagramRequests + + return DatagramRequests(self._inner.datagrams()) + def cancel(self) -> None: """Stop accepting track requests and release the underlying handle.""" self._inner.cancel() @@ -345,6 +337,12 @@ def requests(self) -> BroadcastRequests: """Accept subscriptions to tracks that are not published yet.""" return BroadcastRequests(self._inner.requests()) + def create_datagrams(self, name: str, info: DatagramInfo | None = None) -> DatagramProducer: + """Create a live datagram track, independent of stream tracks with the same name.""" + from .datagram import DatagramProducer + + return DatagramProducer(self._inner.create_datagrams(name, info)) + def publish_track(self, name: str, info: TrackInfo | None = None) -> TrackProducer: """Create a track. Send any bytes, no codec validation. ``info`` sets track properties (priority, cache, timescale); omit for defaults.""" diff --git a/py/moq-rs/moq/subscribe.py b/py/moq-rs/moq/subscribe.py index 560e18696e5..732ca03b448 100644 --- a/py/moq-rs/moq/subscribe.py +++ b/py/moq-rs/moq/subscribe.py @@ -15,7 +15,6 @@ from ._records import _subscription from ._stream import _Stream from .types import ( - Datagram, FetchGroupOptions, Frame, Subscription, @@ -23,6 +22,7 @@ ) if TYPE_CHECKING: + from .datagram import DatagramConsumer from .media import Audio, Video @@ -116,15 +116,6 @@ async def read_frame(self) -> Frame | None: """ return _frame(await self._inner.read_frame()) - async def recv_datagram(self) -> Datagram | None: - """Receive the next best-effort datagram in arrival order. - - Returns ``None`` when the track ends. Datagrams are unavailable over stream-only - transports and older wire versions. - """ - datagram = await self._inner.recv_datagram() - return None if datagram is None else Datagram._from_ffi(datagram) - def info(self) -> TrackInfo: """Return the publisher-side track properties.""" return TrackInfo._from_ffi(self._inner.info()) @@ -151,6 +142,12 @@ class BroadcastConsumer: def __init__(self, inner: MoqBroadcastConsumer) -> None: self._inner = inner + def datagrams(self, name: str) -> DatagramConsumer: + """Subscribe to a live datagram track from now on, without a stream subscription.""" + from .datagram import DatagramConsumer + + return DatagramConsumer(self._inner.datagrams(name)) + async def closed(self) -> None: """Wait until the broadcast ends: its publisher closed it, or every producer left.""" await self._inner.closed() diff --git a/py/moq-rs/moq/types.py b/py/moq-rs/moq/types.py index 07ea1e05a49..26300416244 100644 --- a/py/moq-rs/moq/types.py +++ b/py/moq-rs/moq/types.py @@ -22,6 +22,7 @@ from moq_ffi import ( MoqConnectionState as ConnectionState, ) +from moq_ffi import MoqDatagramInfo as DatagramInfo from moq_ffi import ( MoqErrorScope as ErrorScope, ) @@ -95,6 +96,7 @@ "ConnectionPhase", "ConnectionState", "Datagram", + "DatagramInfo", "Delay", "ErrorScope", "Frame", diff --git a/py/moq-rs/tests/test_local.py b/py/moq-rs/tests/test_local.py index 770d8e0ede1..4e11a3c75ff 100644 --- a/py/moq-rs/tests/test_local.py +++ b/py/moq-rs/tests/test_local.py @@ -118,18 +118,23 @@ async def reject(): await task -async def test_insert_datagram_keeps_its_sequence_apart_from_groups(): +async def test_datagram_tracks_have_independent_sequences_and_priority(): broadcast = moq.BroadcastProducer() - track = broadcast.publish_track("events") + stream = broadcast.publish_track("events") + track = broadcast.create_datagrams("events") consumer = track.consume() - - track.insert_datagram(7, b"seven") - datagram = await asyncio.wait_for(consumer.recv_datagram(), 5) + consumer.set_priority(7) + assert track.priority() == 7 + assert stream.demand().wanted() is None + track.insert(moq.Datagram(sequence=7, payload=b"seven", timestamp=None)) + datagram = await asyncio.wait_for(consumer.recv(), 5) assert datagram is not None assert (datagram.sequence, datagram.payload) == (7, b"seven") - assert track.append_datagram(b"next") == 8 + assert track.append(b"next") == 8 # Datagrams are numbered apart from groups, so they never move `largest`. - assert track.largest() is None + assert stream.largest() is None + consumer.cancel() + assert await track.priority_changed(7) is None async def test_broadcast_consumer_closed_resolves_on_close(): @@ -1825,3 +1830,19 @@ def test_container_timebase_belongs_to_one_broadcast(): with pytest.raises(moq.Error.Closed): moq.media.Timebase(owner) other.close() + + +async def test_datagram_only_request_reaches_its_handler(): + broadcast = moq.BroadcastProducer() + requests = broadcast.requests().datagrams() + consumer = broadcast.consume().datagrams("events") + request = await requests.requested() + assert request.name == "events" + track = request.accept() + assert (await consumer.info()).timescale is None + track.append(b"payload") + assert (await consumer.recv()).payload == b"payload" + track.finish() + assert await consumer.recv() is None + requests.cancel() + broadcast.close() diff --git a/rs/moq-c/MIGRATE.md b/rs/moq-c/MIGRATE.md index b75c742e14a..25180fa86c6 100644 --- a/rs/moq-c/MIGRATE.md +++ b/rs/moq-c/MIGRATE.md @@ -4,13 +4,9 @@ How to update your code for each breaking change, newest first. ## Unreleased -### Datagrams are a track of their own +### Separate datagram tracks -A raw track's datagrams travel on a separate datagram track of the same name, so the C ABI is unchanged but some results differ: - -- `moq_publish_track_datagram` numbers datagrams on their own, apart from groups, and `moq_datagram.sequence` is that number. Don't compare it with group sequences. -- `moq_consume_datagrams` receives only the datagrams sent once its subscription is answered. Every raw track carries a datagram track, but a name with none, such as a media or JSON track, ends the callback with a not-found error. -- moq-transport carries no datagrams. +Create a separate producer with `moq_publish_datagrams` and `moq_datagram_info`; replace `moq_publish_track_datagram` with `moq_publish_datagrams_append` on that handle, or `moq_publish_datagrams_insert` for an explicit sequence. `moq_consume_datagrams` now takes a subscriber priority before its callback and never subscribes to a stream track. Use `moq_publish_datagrams_demand` and `moq_datagram_demand_priority` for aggregate priority, and `moq_publish_datagrams_requests` / `moq_datagram_request_accept` for on-demand publishing. Finish or abort datagram producers separately. A zeroed datagram info is untimed, unlike the microsecond default of stream-track info. ### JSON writes refuse a NULL timestamp ([#7691](https://github.com/moq-dev/moq/pull/7691)) diff --git a/rs/moq-c/src/api.rs b/rs/moq-c/src/api.rs index 9b5a9767c38..2e09b1abb18 100644 --- a/rs/moq-c/src/api.rs +++ b/rs/moq-c/src/api.rs @@ -3170,23 +3170,15 @@ pub unsafe extern "C" fn moq_publish_track_frame( }) } -/// Send a best-effort datagram on a raw track created by [moq_publish_track]. +/// Append a datagram to a producer from [crate::moq_publish_datagrams], returning its sequence. /// -/// Takes `payload` then `timestamp`, matching [moq_publish_track_frame]. The payload must -/// be at most 1200 bytes. On success the datagram's sequence number, counted apart from the -/// track's groups, is written to `out_sequence` when it is non-NULL. A subscriber receives the -/// datagrams sent once its [moq_consume_datagrams] subscription is answered, and counts toward -/// the track's demand. Datagrams are delivered only on -/// transports and wire versions with a datagram channel; there is no group fallback. -/// -/// Returns a zero on success, or a negative code on failure. +/// Keep the payload well below the path MTU. No stream fallback is available. /// /// # Safety -/// - The caller must ensure that payload is a valid pointer to payload_size bytes of data. -/// - `timestamp` must be NULL or a valid pointer to a [moq_timestamp]. -/// - `out_sequence` must be NULL or a valid pointer to a `uint64_t`. +/// `payload` must point to `payload_size` bytes, `timestamp` must be NULL or valid, +/// and `out_sequence` must be NULL or writable. #[unsafe(no_mangle)] -pub unsafe extern "C" fn moq_publish_track_datagram( +pub unsafe extern "C" fn moq_publish_datagrams_append( track: u32, payload: *const u8, payload_size: usize, @@ -3197,7 +3189,7 @@ pub unsafe extern "C" fn moq_publish_track_datagram( let track = ffi::parse_id(track)?; let payload = unsafe { ffi::parse_slice(payload, payload_size)? }; let timestamp = unsafe { ffi::parse_timestamp(timestamp)? }; - let sequence = State::lock().publish.track_datagram(track, timestamp, payload)?; + let sequence = State::lock().publish.datagrams_append(track, timestamp, payload)?; if let Some(out) = unsafe { out_sequence.as_mut() } { *out = sequence; } @@ -4300,7 +4292,7 @@ pub extern "C" fn moq_consume_track_cancel(track: u32) -> i32 { }) } -/// Subscribe to a raw track's best-effort datagrams by name. +/// Subscribe to a live datagram track by name, at the given subscriber priority. /// /// The datagram counterpart to [moq_consume_track], on its own subscription, delivering the /// datagrams sent once the publisher answered it. `on_datagram` @@ -4322,6 +4314,7 @@ pub unsafe extern "C" fn moq_consume_datagrams( broadcast: u32, name: *const c_char, name_len: usize, + priority: i8, on_datagram: ffi::moq_status_callback, user_data: *mut c_void, ) -> i32 { @@ -4329,7 +4322,9 @@ pub unsafe extern "C" fn moq_consume_datagrams( let broadcast = ffi::parse_id(broadcast)?; let name = unsafe { ffi::parse_str(name, name_len)? }; let on_datagram = unsafe { ffi::OnStatus::new(user_data, on_datagram)? }; - State::lock().consume.datagram_track(broadcast, name, on_datagram) + State::lock() + .consume + .datagram_track(broadcast, name, priority, on_datagram) }) } diff --git a/rs/moq-c/src/consume.rs b/rs/moq-c/src/consume.rs index 649b8e988cc..02c0f30e3b4 100644 --- a/rs/moq-c/src/consume.rs +++ b/rs/moq-c/src/consume.rs @@ -16,6 +16,11 @@ use crate::{ moq_json_window_kind, moq_section, moq_string, moq_timestamp, moq_video_config, moq_video_properties, }; +struct DatagramTaskEntry { + task: Task, + track: crate::state::Shared, +} + struct ConsumeCatalog { broadcast: moq_net::broadcast::Consumer, @@ -237,7 +242,7 @@ pub struct Consume { raw_frame: NonZeroSlab>, /// Raw track datagram consumer tasks (best-effort, parallel to `raw_task`). - datagram_task: NonZeroSlab, + datagram_task: NonZeroSlab, /// Buffered datagrams ready for consumption. datagram: NonZeroSlab>, @@ -829,12 +834,18 @@ impl Consume { Ok(()) } - /// Subscribe to a raw track's best-effort datagrams by name. + /// Subscribe to a live datagram track by name. /// /// Parallel to [`Self::raw_track`], but delivers datagrams instead of frames. /// `on_datagram` is called with a datagram ID for each datagram in arrival order; /// each must be released with [`Self::datagram_close`]. - pub fn datagram_track(&mut self, broadcast: Id, name: &str, on_datagram: OnStatus) -> Result { + pub fn datagram_track( + &mut self, + broadcast: Id, + name: &str, + priority: i8, + on_datagram: OnStatus, + ) -> Result { let context = self.broadcast.get(broadcast).ok_or(Error::BroadcastNotFound)?; let driver = context .origin @@ -844,58 +855,27 @@ impl Consume { let broadcast = context.broadcast.clone(); let name = name.to_string(); - // The datagrams ride a datagram track of the track's name. Subscribing to the track - // first keeps what a datagram reader always was to its publisher: demand on the track, - // and a request a dynamic publisher creates both from. A name with no stream track, - // whose publisher made only a datagram track, is read without one. `subscribe` blocks - // on the publisher's answer, so run it inside the task. - self.datagram_task.spawn( - on_datagram, - |state| &mut state.consume.datagram_task, - |mut close| async move { - driver - .watch(async move { - let Some(track) = - Self::until_closed(&mut close, Self::subscribe_demand(&broadcast, &name)).await? - else { - return Ok(()); - }; - let datagrams = broadcast.datagrams(&name)?; - Self::run_datagrams(on_datagram, datagrams, track, close).await - }) - .await - }, - ) - } - - /// Subscribe to `name`'s stream track for its demand, or `None` when the name has none. - async fn subscribe_demand( - broadcast: &moq_net::broadcast::Consumer, - name: &str, - ) -> Result, Error> { - let missing = |err: &moq_net::Error| { - matches!( - err, - moq_net::Error::NotFound | moq_net::Error::Stream(moq_net::StreamError::NotFound) - ) - }; - let track = match broadcast.track(name) { - Ok(track) => track, - Err(err) if missing(&err) => return Ok(None), - Err(err) => return Err(err.into()), - }; - match track.subscribe(None).await { - Ok(subscriber) => Ok(Some(subscriber)), - Err(err) if missing(&err) => Ok(None), - Err(err) => Err(err.into()), - } + let mut datagrams = broadcast.datagrams(&name)?; + datagrams.set_priority(priority); + let track = crate::state::Shared::new(datagrams); + let (task, close) = Task::new(on_datagram); + let id = self.datagram_task.insert(DatagramTaskEntry { + task, + track: track.clone(), + })?; + tokio::spawn(async move { + let res = crate::ffi::run(driver.watch(Self::run_datagrams(on_datagram, track, close))).await; + let entry = State::lock().consume.datagram_task.remove(id); + if let Some(entry) = entry { + entry.task.callback.call(res); + } + }); + Ok(id) } async fn run_datagrams( callback: OnStatus, - mut track: moq_net::datagram::Consumer, - // Held for its demand only; its groups go unread. - _subscriber: Option, + track: crate::state::Shared, mut close: oneshot::Receiver<()>, ) -> Result<(), Error> { loop { @@ -903,7 +883,13 @@ impl Consume { let datagram = tokio::select! { biased; _ = &mut close => return Ok(()), - datagram = track.recv() => match datagram? { + datagram = kio::wait(|waiter| { + let mut guard = track.lock(); + match guard.as_mut() { + Some(track) => track.poll_recv(waiter), + None => Poll::Ready(Err(moq_net::Error::Closed)), + } + }) => match datagram? { Some(datagram) => datagram, None => return Ok(()), }, @@ -917,7 +903,32 @@ impl Consume { } pub fn datagram_track_close(&mut self, track: Id) -> Result<(), Error> { - self.datagram_task.close(track, Error::TrackNotFound) + self.datagram_task + .get_mut(track) + .ok_or(Error::TrackNotFound)? + .task + .close(Error::TrackNotFound) + } + + pub fn datagram_track_priority(&mut self, id: Id, priority: i8) -> Result<(), Error> { + let entry = self.datagram_task.get(id).ok_or(Error::TrackNotFound)?; + entry + .track + .lock() + .as_mut() + .ok_or(Error::TrackNotFound)? + .set_priority(priority); + Ok(()) + } + + pub fn datagram_track_info(&self, id: Id) -> Result, Error> { + let entry = self.datagram_task.get(id).ok_or(Error::TrackNotFound)?; + let guard = entry.track.lock(); + let track = guard.as_ref().ok_or(Error::TrackNotFound)?; + match track.poll_info(&kio::Waiter::noop()) { + Poll::Ready(info) => Ok(Some(info?)), + Poll::Pending => Ok(None), + } } /// Fill `dst` with a datagram's payload, timestamp, and sequence. The pointer is diff --git a/rs/moq-c/src/datagram.rs b/rs/moq-c/src/datagram.rs new file mode 100644 index 00000000000..4f45baf7163 --- /dev/null +++ b/rs/moq-c/src/datagram.rs @@ -0,0 +1,257 @@ +//! Independent live datagram track handles. + +use std::ffi::{c_char, c_void}; + +use crate::{Error, State, ffi, moq_datagram, moq_string}; + +/// Fixed publisher properties of a datagram track; zeroed means untimed, priority zero. +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct moq_datagram_info { + /// Publisher priority, breaking ties between equal subscriber priorities. + pub priority: i8, + /// Timestamp ticks per second, or zero for an untimed track. + pub timescale: u64, +} + +impl TryFrom for moq_net::datagram::Info { + type Error = Error; + + fn try_from(info: moq_datagram_info) -> Result { + let timescale = match info.timescale { + 0 => None, + scale => Some(moq_net::Timescale::new(scale)?), + }; + Ok(Self::default().with_timescale(timescale).with_priority(info.priority)) + } +} + +unsafe fn info(info: *const moq_datagram_info) -> Result { + unsafe { info.as_ref() }.copied().unwrap_or_default().try_into() +} + +/// Create a live datagram producer, independent of any stream track with the same name. +/// +/// Returns its positive handle, or a negative error. NULL info uses the datagram defaults. +/// +/// # Safety +/// `name` must point to `name_len` bytes; `info` must be NULL or a valid record. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn moq_publish_datagrams( + broadcast: u32, + name: *const c_char, + name_len: usize, + properties: *const moq_datagram_info, +) -> i32 { + ffi::enter(|| { + let broadcast = ffi::parse_id(broadcast)?; + let name = unsafe { ffi::parse_str(name, name_len)? }; + let info = unsafe { info(properties)? }; + State::lock().publish.datagrams(broadcast, name, info) + }) +} + +/// Insert a datagram at its explicit sequence; later appends continue past the highest one. +/// +/// # Safety +/// `datagram` must point to a record whose payload and optional timestamp are valid. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn moq_publish_datagrams_insert(producer: u32, datagram: *const moq_datagram) -> i32 { + ffi::enter(|| { + let producer = ffi::parse_id(producer)?; + let datagram = unsafe { datagram.as_ref() }.ok_or(Error::InvalidPointer)?; + let payload = unsafe { ffi::parse_slice(datagram.payload, datagram.payload_size)? }; + let timestamp = unsafe { ffi::parse_timestamp(datagram.timestamp)? }; + State::lock().publish.datagrams_insert( + producer, + moq_net::Datagram { + sequence: datagram.sequence, + timestamp, + payload: bytes::Bytes::copy_from_slice(payload), + }, + ) + }) +} + +/// Finish the datagram track and release its producer; existing readers drain unread datagrams. +#[unsafe(no_mangle)] +pub extern "C" fn moq_publish_datagrams_finish(producer: u32) -> i32 { + ffi::enter(|| State::lock().publish.datagrams_finish(ffi::parse_id(producer)?)) +} + +/// Abort the datagram track with an application error and release its producer. +#[unsafe(no_mangle)] +pub extern "C" fn moq_publish_datagrams_abort(producer: u32, error_code: u16) -> i32 { + ffi::enter(|| { + State::lock() + .publish + .datagrams_abort(ffi::parse_id(producer)?, error_code) + }) +} + +unsafe fn priority(value: Option, present: *mut bool, out: *mut i8) -> Result<(), Error> { + let present = unsafe { present.as_mut() }.ok_or(Error::InvalidPointer)?; + let out = unsafe { out.as_mut() }.ok_or(Error::InvalidPointer)?; + *present = value.is_some(); + *out = value.unwrap_or_default(); + Ok(()) +} + +/// Read the highest subscriber priority; `present` is false while nobody consumes the track. +/// +/// # Safety +/// `present` and `out` must point to writable values. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn moq_publish_datagrams_priority(producer: u32, present: *mut bool, out: *mut i8) -> i32 { + ffi::enter(|| { + let value = State::lock().publish.datagrams_priority(ffi::parse_id(producer)?)?; + unsafe { priority(value, present, out) } + }) +} + +/// Watch aggregate priority changes, receiving WANTED or UNWANTED, then one terminal status. +/// +/// Read the priority with `moq_datagram_demand_priority` from a change callback. Closing the +/// producer or watcher ends it with zero. Release user_data only in the terminal callback. +/// +/// # Safety +/// `user_data` must remain valid until the callback receives its terminal status. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn moq_publish_datagrams_demand( + producer: u32, + callback: ffi::moq_status_callback, + user_data: *mut c_void, +) -> i32 { + ffi::enter(|| { + let producer = ffi::parse_id(producer)?; + let callback = unsafe { ffi::OnStatus::new(user_data, callback)? }; + State::lock().publish.datagrams_demand(producer, callback) + }) +} + +/// Read a datagram demand watcher's current aggregate priority. +/// +/// # Safety +/// `present` and `out` must point to writable values. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn moq_datagram_demand_priority(watcher: u32, present: *mut bool, out: *mut i8) -> i32 { + ffi::enter(|| { + let value = State::lock() + .publish + .datagram_demand_priority(ffi::parse_id(watcher)?)?; + unsafe { priority(value, present, out) } + }) +} + +/// Cancel a datagram demand watcher; its terminal callback still fires. +#[unsafe(no_mangle)] +pub extern "C" fn moq_datagram_demand_cancel(watcher: u32) -> i32 { + ffi::enter(|| State::lock().publish.datagram_demand_close(ffi::parse_id(watcher)?)) +} + +/// Serve on-demand datagram tracks, yielding request handles and then one terminal status. +/// +/// This handler is independent of stream-track requests. Cancel with `moq_publish_requests_cancel`. +/// +/// # Safety +/// `user_data` must remain valid until the callback receives its terminal status. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn moq_publish_datagrams_requests( + broadcast: u32, + callback: ffi::moq_status_callback, + user_data: *mut c_void, +) -> i32 { + ffi::enter(|| { + let broadcast = ffi::parse_id(broadcast)?; + let callback = unsafe { ffi::OnStatus::new(user_data, callback)? }; + State::lock().publish.datagrams_dynamic(broadcast, callback) + }) +} + +/// Borrow a datagram request's name until it is accepted, aborted, or freed. +/// +/// # Safety +/// `dst` must point to a writable string record. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn moq_datagram_request_name(request: u32, dst: *mut moq_string) -> i32 { + ffi::enter(|| { + let request = ffi::parse_id(request)?; + let dst = unsafe { dst.as_mut() }.ok_or(Error::InvalidPointer)?; + State::lock().publish.datagram_request_name(request, dst) + }) +} + +/// Read the highest priority among consumers waiting for this datagram request. +/// +/// # Safety +/// `present` and `out` must point to writable values. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn moq_datagram_request_priority(request: u32, present: *mut bool, out: *mut i8) -> i32 { + ffi::enter(|| { + let value = State::lock() + .publish + .datagram_request_priority(ffi::parse_id(request)?)?; + unsafe { priority(value, present, out) } + }) +} + +/// Accept a datagram request, releasing it and returning its positive producer handle. +/// +/// # Safety +/// `properties` must be NULL or point to a valid datagram info record. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn moq_datagram_request_accept(request: u32, properties: *const moq_datagram_info) -> i32 { + ffi::enter(|| { + let request = ffi::parse_id(request)?; + let info = unsafe { info(properties)? }; + State::lock().publish.datagram_request_accept(request, info) + }) +} + +/// Reject a datagram request with an application error and release it. +#[unsafe(no_mangle)] +pub extern "C" fn moq_datagram_request_abort(request: u32, error_code: u16) -> i32 { + ffi::enter(|| { + State::lock() + .publish + .datagram_request_abort(ffi::parse_id(request)?, error_code) + }) +} + +/// Release a datagram request, rejecting consumers still waiting for it. +#[unsafe(no_mangle)] +pub extern "C" fn moq_datagram_request_free(request: u32) -> i32 { + ffi::enter(|| State::lock().publish.datagram_request_free(ffi::parse_id(request)?)) +} + +/// Change a datagram consumer's subscriber priority, higher first. +#[unsafe(no_mangle)] +pub extern "C" fn moq_consume_datagrams_set_priority(consumer: u32, priority: i8) -> i32 { + ffi::enter(|| { + State::lock() + .consume + .datagram_track_priority(ffi::parse_id(consumer)?, priority) + }) +} + +/// Read accepted publisher properties, returning 1 when available or 0 while still pending. +/// +/// # Safety +/// `dst` must point to a writable datagram info record. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn moq_consume_datagrams_info(consumer: u32, dst: *mut moq_datagram_info) -> i32 { + ffi::enter(|| { + let dst = unsafe { dst.as_mut() }.ok_or(Error::InvalidPointer)?; + let info = State::lock().consume.datagram_track_info(ffi::parse_id(consumer)?)?; + match info { + Some(info) => { + *dst = moq_datagram_info { + priority: info.priority, + timescale: info.timescale.map(|scale| scale.as_u64()).unwrap_or_default(), + }; + Ok(1) + } + None => Ok(0), + } + }) +} diff --git a/rs/moq-c/src/lib.rs b/rs/moq-c/src/lib.rs index 74c2fba2d66..194b44cdd98 100644 --- a/rs/moq-c/src/lib.rs +++ b/rs/moq-c/src/lib.rs @@ -23,6 +23,7 @@ mod audio; mod bandwidth; mod client; mod consume; +mod datagram; mod decode; mod error; mod ffi; @@ -38,6 +39,7 @@ mod video; pub use api::*; pub use audio::*; pub use bandwidth::*; +pub use datagram::*; pub use decode::{moq_decode_gap, moq_decode_read_kind, moq_decode_start}; pub use error::*; pub use ffi::{moq_state_callback, moq_status_callback}; diff --git a/rs/moq-c/src/publish.rs b/rs/moq-c/src/publish.rs index 43d3c075573..9eb045961a6 100644 --- a/rs/moq-c/src/publish.rs +++ b/rs/moq-c/src/publish.rs @@ -29,6 +29,7 @@ struct TrackRequest { enum Request { Track(Box), Fill(moq_net::track::Fill), + Datagram(DatagramRequest), } /// One group of a fill, handed to C as a group request: the frozen ABI answers fills a @@ -46,6 +47,7 @@ enum Dynamic { Broadcast(moq_net::broadcast::Requests, Id, Children), /// Group requests (fetches of uncached groups) on a track. Track(moq_net::track::Requests), + Datagrams(moq_net::broadcast::DatagramRequests, Children), } /// A published broadcast: its producer, its catalog, and the renditions the caller authored by @@ -70,6 +72,7 @@ pub(crate) enum Child { Media(Id), Container(Id), Track(Id), + Datagrams(Id), Audio(Id), Video(Id), JsonSnapshot(Id), @@ -90,8 +93,6 @@ enum Family { open: HashSet, /// Finished producers, kept so a late subscriber still finds their tracks. kept: Vec>, - /// The broadcast, which a raw track creates its datagram track on. - broadcast: moq_net::broadcast::Producer, }, /// The broadcast closed: its children ended and new ones are refused. Closed, @@ -111,16 +112,15 @@ pub struct Children(Arc>); #[cfg(test)] impl Default for Children { fn default() -> Self { - Self::new(moq_net::broadcast::Info::new().produce()) + Self::new() } } impl Children { - fn new(broadcast: moq_net::broadcast::Producer) -> Self { + fn new() -> Self { Self(Arc::new(std::sync::Mutex::new(Family::Open { open: HashSet::new(), kept: Vec::new(), - broadcast, }))) } @@ -159,17 +159,6 @@ impl Children { } } - /// Create the datagram track carrying the datagrams of the raw track `name` with `info`. - fn datagrams(&self, name: &str, info: &moq_net::track::Info) -> Result { - let Family::Open { broadcast, .. } = &*self.lock() else { - return Err(Error::BroadcastNotFound); - }; - let info = moq_net::datagram::Info::default() - .with_timescale(info.timescale) - .with_priority(info.priority); - Ok(broadcast.create_datagrams(name, info)?) - } - /// Stop tracking `child`, which ended on its own. pub(crate) fn forget(&self, child: Child) { if let Family::Open { open, .. } = &mut *self.lock() { @@ -213,22 +202,11 @@ impl Abort for Kept> { } } -/// A raw track and the datagram track of the same name that carries its datagrams. -struct Raw { - track: moq_net::track::Producer, - datagrams: moq_net::datagram::Producer, -} - -impl Abort for Kept { +impl Abort for Kept { fn abort(self, err: moq_net::Error) { - let Raw { track, datagrams } = self.inner; - // A track with a declared end ends there, as when its last producer drops. - if track.finished().is_some() { - datagrams.finish(); - return; + if self.inner.finished().is_none() { + let _ = self.inner.abort(err); } - datagrams.abort(err.clone()); - let _ = track.abort(err); } } @@ -315,7 +293,10 @@ pub struct Publish { containers: NonZeroSlab, /// Raw track producers (no media/container/catalog framing). - tracks: NonZeroSlab>, + tracks: NonZeroSlab>, + datagrams: NonZeroSlab, + datagram_request: NonZeroSlab, + datagram_demand: NonZeroSlab, /// Raw group producers, created from a raw track producer. groups: NonZeroSlab, @@ -381,7 +362,7 @@ impl Publish { let id = self.broadcasts.insert(Broadcast { driver, - children: Children::new(broadcast.clone()), + children: Children::new(), producer: broadcast, catalog, video: BTreeMap::new(), @@ -398,8 +379,8 @@ impl Publish { ) -> Result<(Id, Id), Error> { let broadcast = self.create((publication.broadcast().clone(), driver.clone()))?; let id = self.publications.insert(Publication { - driver, broadcast, + driver, inner: publication, }); match id { @@ -813,22 +794,21 @@ impl Publish { Ok(()) } - /// The raw track producer behind a handle, for tests that publish what the C API - /// can't express (an untimed frame). #[cfg(test)] - pub(crate) fn track_producer(&mut self, track: Id) -> Option<&mut moq_net::track::Producer> { - self.tracks.get_mut(track).map(|raw| &mut raw.inner.track) + pub(crate) fn datagram_producer(&self, id: Id) -> Option { + self.datagrams.get(id).map(|track| track.producer.clone()) } - /// A raw track's datagram producer, for tests that send a datagram once a reader listens. + /// The raw track producer behind a handle, for tests that publish what the C API + /// can't express (an untimed frame). #[cfg(test)] - pub(crate) fn datagram_producer(&self, track: Id) -> Option { - self.tracks.get(track).map(|raw| raw.inner.datagrams.clone()) + pub(crate) fn track_producer(&mut self, track: Id) -> Option<&mut moq_net::track::Producer> { + self.tracks.get_mut(track).map(|raw| &mut raw.inner) } /// A watch-only handle to a raw track's subscriber demand. pub fn track_demand(&self, track: Id) -> Result { - Ok(self.tracks.get(track).ok_or(Error::TrackNotFound)?.track.demand()) + Ok(self.tracks.get(track).ok_or(Error::TrackNotFound)?.inner.demand()) } /// A watch-only handle to a media importer's subscriber demand. @@ -925,7 +905,7 @@ impl Publish { /// Serve fetches of uncached groups on a raw track, delivering each as a group-request /// handle via `on_group`. pub fn track_dynamic(&mut self, track: Id, on_group: OnStatus) -> Result { - let dynamic = self.tracks.get(track).ok_or(Error::TrackNotFound)?.track.requests(); + let dynamic = self.tracks.get(track).ok_or(Error::TrackNotFound)?.inner.requests(); self.spawn_dynamic(Dynamic::Track(dynamic), on_group, Default::default()) } @@ -981,6 +961,7 @@ impl Publish { })) }) } + Dynamic::Datagrams(dynamic, children) => dynamic.poll_requested(waiter).map_ok(|request| Request::Datagram(DatagramRequest { request, children: children.clone() })), Dynamic::Track(dynamic) => dynamic.poll_requested_fill(waiter).map_ok(Request::Fill), } }) => res, @@ -996,6 +977,7 @@ impl Publish { // Hold the lock only to buffer the request; release it before the callback. let id = match request { Request::Track(request) => State::lock().publish.track_request.insert(*request)?, + Request::Datagram(request) => State::lock().publish.datagram_request.insert(request)?, Request::Fill(fill) => { let mut serve = Box::pin(Self::serve_fill(callback, Arc::new(fill))); fills.push(move |waiter: &kio::Waiter| waiter.poll_future(serve.as_mut())); @@ -1054,22 +1036,8 @@ impl Publish { /// Accept a track request as a raw track, returning a track handle like [`Self::track`]. pub fn track_request_accept(&mut self, request: Id, info: moq_net::track::Info) -> Result { let TrackRequest { children, request, .. } = self.track_request.remove(request).ok_or(Error::NotFound)?; - let datagrams = match children.datagrams(request.name(), &info) { - Ok(datagrams) => datagrams, - Err(err) => { - // A closed broadcast ends its subscribers the way a publisher leaving does. - request.reject(match &err { - Error::Moq(err) => err.clone(), - _ => moq_net::Error::Unroutable, - }); - return Err(err); - } - }; let raw = Kept { - inner: Raw { - track: request.accept(info), - datagrams, - }, + inner: request.accept(info), children: children.clone(), }; children.insert(&mut self.tracks, raw, Child::Track) @@ -1166,16 +1134,9 @@ impl Publish { let children = self.children(broadcast)?; let broadcast = self.producer(broadcast)?; let info = info.unwrap_or_default(); - let datagrams = children.datagrams(name, &info)?; - let track = match broadcast.create_track(name, info) { - Ok(track) => track, - Err(err) => { - datagrams.abort(err.clone()); - return Err(err.into()); - } - }; + let track = broadcast.create_track(name, info)?; let raw = Kept { - inner: Raw { track, datagrams }, + inner: track, children: children.clone(), }; children.insert(&mut self.tracks, raw, Child::Track) @@ -1184,14 +1145,14 @@ impl Publish { /// Append a new group to a raw track, returning a group producer. pub fn track_group(&mut self, track: Id) -> Result { let raw = self.tracks.get_mut(track).ok_or(Error::TrackNotFound)?; - let group = raw.track.append_group()?; + let group = raw.inner.append_group()?; self.groups.insert(group) } /// Create a raw group with an explicit sequence number. pub fn track_group_at(&mut self, track: Id, sequence: u64) -> Result { let raw = self.tracks.get_mut(track).ok_or(Error::TrackNotFound)?; - let group = raw.track.create_group(moq_net::group::Info { sequence })?; + let group = raw.inner.create_group(moq_net::group::Info { sequence })?; self.groups.insert(group) } @@ -1203,41 +1164,21 @@ impl Publish { payload: &[u8], ) -> Result<(), Error> { let raw = self.tracks.get_mut(track).ok_or(Error::TrackNotFound)?; - raw.track + raw.inner .write_frame(timestamp, bytes::Bytes::copy_from_slice(payload))?; Ok(()) } - /// Send a best-effort datagram on a raw track's datagram track, returning its sequence. - /// - /// Datagrams are delivered only on transports and wire versions with a datagram channel; - /// there is no group fallback. - pub fn track_datagram( - &mut self, - track: Id, - timestamp: Option, - payload: &[u8], - ) -> Result { - let raw = self.tracks.get_mut(track).ok_or(Error::TrackNotFound)?; - Ok(raw - .datagrams - .append(timestamp, bytes::Bytes::copy_from_slice(payload))?) - } - /// Finish a raw track. No more groups or frames can be written. /// /// [`Self::track_finish_at`] declares the boundary ahead of time, so this keeps that /// boundary and only releases the handle; the broadcast keeps the track. pub fn track_finish(&mut self, track: Id) -> Result<(), Error> { let id = track; - let Kept { - inner: Raw { track, datagrams }, - children, - } = self.tracks.remove(id).ok_or(Error::TrackNotFound)?; + let Kept { inner: track, children } = self.tracks.remove(id).ok_or(Error::TrackNotFound)?; if track.finished().is_none() { track.finish()?; } - datagrams.finish(); Kept { inner: track, children }.keep(Child::Track(id)); Ok(()) } @@ -1245,7 +1186,7 @@ impl Publish { /// Declare a raw track's exclusive final group sequence. pub fn track_finish_at(&mut self, track: Id, final_sequence: u64) -> Result<(), Error> { let raw = self.tracks.get_mut(track).ok_or(Error::TrackNotFound)?; - raw.track + raw.inner .finish_at(moq_net::track::Position::group(final_sequence), None)?; Ok(()) } @@ -1256,8 +1197,7 @@ impl Publish { let raw = self.tracks.remove(id).ok_or(Error::TrackNotFound)?; raw.children.forget(Child::Track(id)); let err = moq_net::Error::App(error_code); - raw.inner.datagrams.abort(err.clone()); - raw.inner.track.abort(err)?; + raw.inner.abort(err)?; Ok(()) } @@ -1522,6 +1462,7 @@ impl State { match child { Child::Media(id) => self.publish.media.remove(id).map(|media| media.abort(err.clone())), Child::Container(id) => self.publish.containers.remove(id).map(|media| media.abort(err.clone())), + Child::Datagrams(id) => self.publish.datagrams.remove(id).map(|track| track.abort(err.clone())), Child::Track(id) => self.publish.tracks.remove(id).map(|track| track.abort(err.clone())), Child::Audio(id) => self .audio @@ -1684,7 +1625,7 @@ mod children_tests { let mut datagram_reader = datagrams.consume(); let mut tracks = NonZeroSlab::default(); let kept = Kept { - inner: Raw { track, datagrams }, + inner: track, children: children.clone(), }; assert!(matches!( @@ -1692,6 +1633,16 @@ mod children_tests { Err(Error::BroadcastNotFound) )); assert!(matches!(reader.recv_group().await, Err(moq_net::Error::Unroutable))); + let mut producers = NonZeroSlab::default(); + let datagrams = Datagrams { + producer: datagrams, + children: children.clone(), + alive: kio::Producer::new(()), + }; + assert!(matches!( + children.insert(&mut producers, datagrams, Child::Datagrams), + Err(Error::BroadcastNotFound) + )); assert!(matches!(datagram_reader.recv().await, Err(moq_net::Error::Unroutable))); } } @@ -1790,3 +1741,175 @@ mod supervision_tests { assert!(consumer.is_closed()); } } + +/// A datagram producer and the signal ending its demand watchers. +struct Datagrams { + producer: moq_net::datagram::Producer, + children: Children, + alive: kio::Producer<()>, +} + +impl Abort for Datagrams { + fn abort(self, err: moq_net::Error) { + self.producer.abort(err); + } +} + +struct DatagramRequest { + request: moq_net::datagram::Request, + children: Children, +} + +struct DatagramDemand { + task: Task, + producer: moq_net::datagram::Producer, +} + +impl Publish { + pub fn datagrams(&mut self, broadcast: Id, name: &str, info: moq_net::datagram::Info) -> Result { + let children = self.children(broadcast)?; + let producer = self.producer(broadcast)?.create_datagrams(name, info)?; + let entry = Datagrams { + producer, + children: children.clone(), + alive: kio::Producer::new(()), + }; + children.insert(&mut self.datagrams, entry, Child::Datagrams) + } + + pub fn datagrams_append( + &mut self, + track: Id, + timestamp: Option, + payload: &[u8], + ) -> Result { + Ok(self + .datagrams + .get_mut(track) + .ok_or(Error::TrackNotFound)? + .producer + .append(timestamp, bytes::Bytes::copy_from_slice(payload))?) + } + + pub fn datagrams_insert(&mut self, track: Id, datagram: moq_net::Datagram) -> Result<(), Error> { + Ok(self + .datagrams + .get_mut(track) + .ok_or(Error::TrackNotFound)? + .producer + .insert(datagram)?) + } + + pub fn datagrams_priority(&self, track: Id) -> Result, Error> { + Ok(self + .datagrams + .get(track) + .ok_or(Error::TrackNotFound)? + .producer + .priority()) + } + + pub fn datagrams_finish(&mut self, id: Id) -> Result<(), Error> { + let entry = self.datagrams.remove(id).ok_or(Error::TrackNotFound)?; + entry.children.forget(Child::Datagrams(id)); + entry.producer.finish(); + Ok(()) + } + + pub fn datagrams_abort(&mut self, id: Id, code: u16) -> Result<(), Error> { + let entry = self.datagrams.remove(id).ok_or(Error::TrackNotFound)?; + entry.children.forget(Child::Datagrams(id)); + entry.abort(moq_net::Error::App(code)); + Ok(()) + } + + pub fn datagrams_dynamic(&mut self, broadcast: Id, callback: OnStatus) -> Result { + let broadcast = self.broadcast(broadcast)?; + let dynamic = Dynamic::Datagrams(broadcast.producer.requests().datagrams(), broadcast.children.clone()); + let driver = broadcast.driver.clone(); + self.spawn_dynamic(dynamic, callback, driver) + } + + pub fn datagram_request_name(&self, id: Id, dst: &mut crate::moq_string) -> Result<(), Error> { + let name = self.datagram_request.get(id).ok_or(Error::NotFound)?.request.name(); + *dst = crate::moq_string { + data: name.as_ptr().cast(), + len: name.len(), + }; + Ok(()) + } + + pub fn datagram_request_priority(&self, id: Id) -> Result, Error> { + Ok(self.datagram_request.get(id).ok_or(Error::NotFound)?.request.priority()) + } + + pub fn datagram_request_accept(&mut self, id: Id, info: moq_net::datagram::Info) -> Result { + let request = self.datagram_request.remove(id).ok_or(Error::NotFound)?; + let entry = Datagrams { + producer: request.request.accept(info), + children: request.children.clone(), + alive: kio::Producer::new(()), + }; + request.children.insert(&mut self.datagrams, entry, Child::Datagrams) + } + + pub fn datagram_request_abort(&mut self, id: Id, code: u16) -> Result<(), Error> { + self.datagram_request + .remove(id) + .ok_or(Error::NotFound)? + .request + .reject(moq_net::Error::App(code)); + Ok(()) + } + + pub fn datagram_request_free(&mut self, id: Id) -> Result<(), Error> { + self.datagram_request.remove(id).ok_or(Error::NotFound)?; + Ok(()) + } + + pub fn datagrams_demand(&mut self, track: Id, callback: OnStatus) -> Result { + let entry = self.datagrams.get(track).ok_or(Error::TrackNotFound)?; + let producer = entry.producer.clone(); + let alive = entry.alive.consume(); + let (task, mut close) = Task::new(callback); + let id = self.datagram_demand.insert(DatagramDemand { + task, + producer: producer.clone(), + })?; + tokio::spawn(async move { + let res = crate::ffi::run(async move { + let mut priority = producer.priority(); + loop { + callback.call(match priority { + Some(_) => moq_demand::MOQ_DEMAND_WANTED as i32, + None => moq_demand::MOQ_DEMAND_UNWANTED as i32, + }); + priority = tokio::select! { + biased; + _ = &mut close => return Ok(()), + _ = alive.closed() => return Ok(()), + priority = kio::wait(|waiter| producer.poll_priority(waiter, priority)) => priority, + }; + } + }) + .await; + let entry = State::lock().publish.datagram_demand.remove(id); + if let Some(entry) = entry { + entry.task.callback.call(res); + } + }); + Ok(id) + } + + pub fn datagram_demand_priority(&self, id: Id) -> Result, Error> { + Ok(self.datagram_demand.get(id).ok_or(Error::NotFound)?.producer.priority()) + } + + pub fn datagram_demand_close(&mut self, id: Id) -> Result<(), Error> { + self.datagram_demand + .get_mut(id) + .ok_or(Error::NotFound)? + .task + .close(Error::NotFound) + } +} diff --git a/rs/moq-c/src/test.rs b/rs/moq-c/src/test.rs index 788cd996a4d..02c4764a521 100644 --- a/rs/moq-c/src/test.rs +++ b/rs/moq-c/src/test.rs @@ -1809,6 +1809,17 @@ fn timestamps_round_trip_exactly() { .into() }; let track = create(name); + let datagram_track = id(unsafe { + moq_publish_datagrams( + broadcast, + name.as_ptr().cast(), + name.len(), + &moq_datagram_info { + priority: 0, + timescale: written.map(|_| 90_000).unwrap_or_default(), + }, + ) + }); let json_name = format!("{name}.json"); let json_track = create(&json_name); @@ -1829,6 +1840,7 @@ fn timestamps_round_trip_exactly() { consume, name.as_ptr().cast(), name.len(), + 0, Some(channel_callback), datagrams.ptr, ) @@ -1862,10 +1874,16 @@ fn timestamps_round_trip_exactly() { assert_eq!(moq_consume_track_frame_free(frame_id), 0); // The datagram consumer is live once its subscription is answered. - wait_datagram_reader(track); + wait_datagram_reader(datagram_track); assert_eq!( unsafe { - moq_publish_track_datagram(track, payload.as_ptr(), payload.len(), timestamp, std::ptr::null_mut()) + moq_publish_datagrams_append( + datagram_track, + payload.as_ptr(), + payload.len(), + timestamp, + std::ptr::null_mut(), + ) }, 0 ); @@ -2054,13 +2072,12 @@ fn raw_track_publish_consume() { assert_eq!(moq_origin_close(origin), 0); } -/// Wait until a raw track's datagram track has a reader, which a datagram consumer becomes -/// once its subscription is answered. +/// Wait until a datagram producer has a reader. fn wait_datagram_reader(track: u32) { let datagrams = State::lock() .publish .datagram_producer(Id::try_from(track).unwrap()) - .expect("a raw track"); + .expect("a datagram track"); let reader = kio::wait(|waiter| match datagrams.poll_priority(waiter, None) { std::task::Poll::Ready(Some(_)) => std::task::Poll::Ready(()), _ => std::task::Poll::Pending, @@ -2070,39 +2087,63 @@ fn wait_datagram_reader(track: u32) { .expect("no datagram reader arrived"); } -/// A datagram reader subscribes to its track, as before datagrams had a track of their own: -/// the publisher sees it as demand, and a dynamic publisher learns of the track from it. +/// A datagram-only reader reaches its own handler and aggregate priority demand. #[test] fn a_datagram_reader_is_demand_and_requests_its_track() { let origin = id(moq_origin_create()); let broadcast = publish_broadcast(origin, b"datagram-demand"); let request_cb = Callback::new(); - let dynamic = id(unsafe { moq_publish_requests(broadcast, Some(channel_callback), request_cb.ptr) }); + let dynamic = id(unsafe { moq_publish_datagrams_requests(broadcast, Some(channel_callback), request_cb.ptr) }); let consume = consume_local(broadcast); // Nothing publishes the track yet: the reader's request reaches the handler. let name = b"events"; + let stream = id(unsafe { moq_publish_track(broadcast, name.as_ptr().cast(), name.len(), std::ptr::null()) }); + let stream_demand = Callback::new(); + let stream_watcher = id(unsafe { moq_publish_track_demand(stream, Some(channel_callback), stream_demand.ptr) }); + assert_eq!(stream_demand.recv(), moq_demand::MOQ_DEMAND_UNWANTED as i32); let dg_cb = Callback::new(); let consumer = id(unsafe { moq_consume_datagrams( consume, name.as_ptr() as *const c_char, name.len(), + 0, Some(channel_callback), dg_cb.ptr, ) }); let request = id(request_cb.recv()); - let track = id(unsafe { moq_track_request_accept(request, std::ptr::null()) }); + let track = id(unsafe { + moq_datagram_request_accept( + request, + &moq_datagram_info { + priority: 0, + timescale: 1_000_000, + }, + ) + }); let demand_cb = Callback::new(); - let _watcher = id(unsafe { moq_publish_track_demand(track, Some(channel_callback), demand_cb.ptr) }); + let watcher = id(unsafe { moq_publish_datagrams_demand(track, Some(channel_callback), demand_cb.ptr) }); assert_eq!(demand_cb.recv(), moq_demand::MOQ_DEMAND_WANTED as i32); wait_datagram_reader(track); + assert_eq!(moq_consume_datagrams_set_priority(consumer, 12), 0); + assert_eq!(demand_cb.recv(), moq_demand::MOQ_DEMAND_WANTED as i32); + let mut present = false; + let mut priority = 0; + assert_eq!( + unsafe { moq_datagram_demand_priority(watcher, &mut present, &mut priority) }, + 0 + ); + assert!(present); + assert_eq!(priority, 12); let payload = b"on demand"; assert_eq!( - unsafe { moq_publish_track_datagram(track, payload.as_ptr(), payload.len(), µs(7), std::ptr::null_mut()) }, + unsafe { + moq_publish_datagrams_append(track, payload.as_ptr(), payload.len(), µs(7), std::ptr::null_mut()) + }, 0 ); let dg_id = id(dg_cb.recv()); @@ -2125,9 +2166,11 @@ fn a_datagram_reader_is_demand_and_requests_its_track() { assert_eq!(dg_cb.recv_terminal(), 0); assert_eq!(demand_cb.recv(), moq_demand::MOQ_DEMAND_UNWANTED as i32); + assert_eq!(moq_publish_demand_cancel(stream_watcher), 0); + assert_eq!(stream_demand.recv_terminal(), 0); assert_eq!(moq_publish_requests_cancel(dynamic), 0); assert_eq!(request_cb.recv_terminal(), 0); - assert_eq!(moq_publish_track_finish(track), 0); + assert_eq!(moq_publish_datagrams_finish(track), 0); assert_eq!(moq_consume_close(consume), 0); assert_eq!(moq_publish_close(broadcast), 0); assert_eq!(demand_cb.recv_terminal(), 0); @@ -2151,6 +2194,7 @@ fn a_datagram_only_track_is_read() { consume, name.as_ptr() as *const c_char, name.len(), + 0, Some(channel_callback), dg_cb.ptr, ) @@ -2191,11 +2235,14 @@ fn raw_track_datagram_publish_consume() { let track_name = b"events"; let track = id(unsafe { - moq_publish_track( + moq_publish_datagrams( broadcast, track_name.as_ptr() as *const c_char, track_name.len(), - std::ptr::null(), + &moq_datagram_info { + priority: 0, + timescale: 1_000_000, + }, ) }); @@ -2207,6 +2254,7 @@ fn raw_track_datagram_publish_consume() { consume, track_name.as_ptr() as *const c_char, track_name.len(), + 0, Some(channel_callback), dg_cb.ptr, ) @@ -2216,7 +2264,9 @@ fn raw_track_datagram_publish_consume() { let payload = b"hello datagram"; let mut sequence: u64 = u64::MAX; assert_eq!( - unsafe { moq_publish_track_datagram(track, payload.as_ptr(), payload.len(), µs(120_000), &mut sequence) }, + unsafe { + moq_publish_datagrams_append(track, payload.as_ptr(), payload.len(), µs(120_000), &mut sequence) + }, 0 ); @@ -2239,7 +2289,7 @@ fn raw_track_datagram_publish_consume() { // before the Callback (user_data) drops. assert_eq!(dg_cb.recv_terminal(), 0, "clean close delivers terminal 0"); assert!(moq_consume_datagrams_cancel(consumer) < 0, "double-close should fail"); - assert_eq!(moq_publish_track_finish(track), 0); + assert_eq!(moq_publish_datagrams_finish(track), 0); assert_eq!(moq_consume_close(consume), 0); assert_eq!(moq_publish_close(broadcast), 0); assert_eq!(moq_origin_close(origin), 0); @@ -3167,6 +3217,7 @@ const NAMED_CONSUMERS: [NamedConsumer; 5] = [ consume, name.as_ptr() as *const c_char, name.len(), + 0, Some(channel_callback), user_data, ) @@ -3237,18 +3288,35 @@ fn named_consumers_cancel_while_subscribing() { // Unknown tracks become requests, which leave each subscribe pending until answered. let request_cb = Callback::new(); let dynamic = id(unsafe { moq_publish_requests(broadcast, Some(channel_callback), request_cb.ptr) }); + let datagram_cb = Callback::new(); + let datagram_dynamic = + id(unsafe { moq_publish_datagrams_requests(broadcast, Some(channel_callback), datagram_cb.ptr) }); let consume = consume_local(broadcast); for (name, consumer, cancel) in NAMED_CONSUMERS { let cb = Callback::new(); let task = id(consumer(consume, name, cb.ptr)); - let request = id(request_cb.recv()); + let datagrams = name == b"datagrams"; + let request = id(if datagrams { + datagram_cb.recv() + } else { + request_cb.recv() + }); assert_eq!(cancel(task), 0); assert_eq!(cb.recv_terminal(), 0, "a cancelled subscribe ends cleanly"); - assert_eq!(moq_track_request_free(request), 0); + assert_eq!( + if datagrams { + moq_datagram_request_free(request) + } else { + moq_track_request_free(request) + }, + 0 + ); } + assert_eq!(moq_publish_requests_cancel(datagram_dynamic), 0); + assert_eq!(datagram_cb.recv_terminal(), 0); assert_eq!(moq_publish_requests_cancel(dynamic), 0); assert_eq!(request_cb.recv_terminal(), 0); assert_eq!(moq_consume_close(consume), 0); diff --git a/rs/moq-ffi/MIGRATE.md b/rs/moq-ffi/MIGRATE.md index 5260084c9d4..d3c58a7211b 100644 --- a/rs/moq-ffi/MIGRATE.md +++ b/rs/moq-ffi/MIGRATE.md @@ -5,19 +5,13 @@ These are the UniFFI names; each language wrapper has its own `MIGRATE.md` in it ## Unreleased -### Viewer targets are bounded ([#7090](https://github.com/moq-dev/moq/pull/7090)) - -Viewer ceilings and PROBE target overrides are refused with the new `MoqError::OutOfRange` once they would sum above 2^53 - 1 bps, the most a PROBE target carries; nothing changes on a refusal. `MoqViewers::watch` and `set_target` and `MoqViewer::update` return a `Result`. Handle the new variant wherever you match the error exhaustively. Regenerate bindings and rebuild the matching native library together. +### Separate datagram tracks -### Datagrams are a track of their own +`MoqTrackProducer::{append_datagram, insert_datagram}` and `MoqTrackConsumer::recv_datagram` are removed. Use `MoqBroadcastProducer::create_datagrams(name, info)` and `MoqBroadcastConsumer::datagrams(name)` for separate `MoqDatagramProducer`/`MoqDatagramConsumer` handles. `append(timestamp, payload)` assigns a sequence; `insert(MoqDatagram)` preserves one; `recv()` reads it. `MoqDatagramInfo` has only priority and optional timescale. Watch aggregate subscriber priority with `priority()` / `priority_changed(last)`, and handle dynamic tracks with `MoqBroadcastRequests::datagrams()` / `MoqDatagramRequests::requested()`. Stream and datagram tracks of the same name have independent demand and lifetimes. -A raw track's datagrams travel on a separate datagram track of the same name, so the API is unchanged but some results differ: +### Viewer targets are bounded ([#7090](https://github.com/moq-dev/moq/pull/7090)) -- `append_datagram` numbers datagrams on their own, apart from groups, and `MoqDatagram.sequence` is that number. Don't compare it with group sequences. -- `MoqTrackProducer::largest` reports groups only: a datagram never moves it. -- `insert_datagram` ignores a `finish_at` boundary. -- A `MoqTrackConsumer` from `subscribe_track` subscribes to datagrams on its first `recv_datagram` and receives only those sent from then on, so start reading before the datagrams you need are sent. One from `MoqTrackProducer::consume` receives those sent after it was created. -- `recv_datagram` fails with `NotFound` on a track with no datagram track, such as a media or JSON track, and over moq-transport, which carries no datagrams. Every raw track has one. +Viewer ceilings and PROBE target overrides are refused with the new `MoqError::OutOfRange` once they would sum above 2^53 - 1 bps, the most a PROBE target carries; nothing changes on a refusal. `MoqViewers::watch` and `set_target` and `MoqViewer::update` return a `Result`. Handle the new variant wherever you match the error exhaustively. Regenerate bindings and rebuild the matching native library together. ### `MoqVideoInit.lower` takes either producer kind ([#7699](https://github.com/moq-dev/moq/pull/7699)) diff --git a/rs/moq-ffi/src/consumer.rs b/rs/moq-ffi/src/consumer.rs index ef266870504..573c8bbceca 100644 --- a/rs/moq-ffi/src/consumer.rs +++ b/rs/moq-ffi/src/consumer.rs @@ -362,8 +362,7 @@ impl MoqBroadcastConsumer { .watch(async { let subscription = subscription.map(moq_net::track::Subscription::try_from).transpose()?; let track = self.inner.track(&name)?.subscribe(subscription).await?; - let datagrams = Datagrams::Remote(self.inner.clone()); - Ok(Arc::new(MoqTrackConsumer::new(track, datagrams, self.driver.clone()))) + Ok(Arc::new(MoqTrackConsumer::new(track, self.driver.clone()))) }) .await } @@ -406,7 +405,6 @@ pub(crate) fn map_fetch_error(err: moq_net::Error) -> MoqError { /// binding can't express in its type system, so the handle commits on the first group /// read instead: whichever group cursor a caller reaches for first is the one this /// track keeps, and reaching for the other afterwards is [`MoqError::AlreadyCommitted`]. -/// Datagrams are a separate track of the same name, so reading them never commits. enum Cursor { /// No group read has happened yet; the track can still commit either way. Uncommitted(moq_net::track::Subscriber), @@ -430,17 +428,6 @@ struct OrderedCursor { struct TrackInner { track: Cursor, - datagrams: Datagrams, -} - -/// The datagram track of a track's name. A subscribed track opens it on the first datagram -/// read, so a reader that never asks for datagrams never subscribes to them. -pub(crate) enum Datagrams { - /// Not opened yet; opened from the broadcast the track was subscribed through. - Remote(moq_net::broadcast::Consumer), - Open(moq_net::datagram::Consumer), - /// Read from a track that had already finished, so it has no datagrams to come. - Ended, } impl TrackInner { @@ -537,89 +524,12 @@ impl TrackInner { } } } - - /// The datagram consumer, opened now if this is the first datagram read, or `None` once - /// there are none to come. - fn datagrams( - &mut self, - control: &moq_net::track::Control, - ) -> Result, MoqError> { - let name = match &self.track { - Cursor::Uncommitted(track) | Cursor::Arrival(track) => track.name(), - Cursor::Ordered(ordered) => ordered.track.name(), - // Poisoned mid-conversion; see `arrival`. - Cursor::Converting => return Err(MoqError::Closed), - }; - if let Datagrams::Remote(broadcast) = &self.datagrams { - match broadcast.datagrams(name) { - Ok(mut opened) => { - opened.set_priority(control.subscription().priority); - self.datagrams = Datagrams::Open(opened); - } - Err(err) => self.datagrams = self.missing(err)?, - } - } - match &mut self.datagrams { - Datagrams::Open(datagrams) => Ok(Some(datagrams)), - Datagrams::Ended => Ok(None), - Datagrams::Remote(_) => unreachable!("opened above"), - } - } - - /// The datagrams after looking them up failed with `err`: none to come when the track - /// declared its end, since its datagram track finished with it and a finished one is no - /// longer found, or else `err`. - fn missing(&mut self, err: moq_net::Error) -> Result { - let missing = matches!( - err, - moq_net::Error::NotFound | moq_net::Error::Stream(moq_net::StreamError::NotFound) - ); - let waiter = kio::Waiter::noop(); - let finished = match &mut self.track { - Cursor::Uncommitted(track) | Cursor::Arrival(track) => track.poll_finished(&waiter), - Cursor::Ordered(ordered) => waiter.poll_future(std::pin::pin!(ordered.track.finished())), - Cursor::Converting => Poll::Pending, - }; - match (missing, finished) { - (true, Poll::Ready(Ok(_))) => Ok(Datagrams::Ended), - _ => Err(err.into()), - } - } - - fn poll_recv_datagram( - &mut self, - waiter: &kio::Waiter, - control: &moq_net::track::Control, - ) -> Poll, MoqError>> { - let datagrams = match self.datagrams(control) { - Ok(Some(datagrams)) => datagrams, - Ok(None) => return Poll::Ready(Ok(None)), - Err(err) => return Poll::Ready(Err(err)), - }; - let datagram = match ready!(datagrams.poll_recv(waiter)) { - Ok(Some(datagram)) => datagram, - Ok(None) => return Poll::Ready(Ok(None)), - Err(err) => { - self.datagrams = match self.missing(err) { - Ok(ended) => ended, - Err(err) => return Poll::Ready(Err(err)), - }; - return Poll::Ready(Ok(None)); - } - }; - Poll::Ready(Ok(Some(MoqDatagram { - sequence: datagram.sequence, - timestamp: datagram.timestamp.map(Into::into), - payload: datagram.payload.to_vec(), - }))) - } } -/// A subscribed track whose groups, frames, or datagrams can be read. +/// A subscribed stream track whose groups and frames can be read. #[derive(uniffi::Object)] pub struct MoqTrackConsumer { - /// Every read polls this; none holds it across a wait, so a datagram read progresses while - /// a group read is parked, and vice versa. + /// Reads poll in place without holding a lock across a wait. reads: Polled, control: moq_net::track::Control, info: moq_net::track::Info, @@ -628,13 +538,12 @@ pub struct MoqTrackConsumer { } impl MoqTrackConsumer { - pub(crate) fn new(track: moq_net::track::Subscriber, datagrams: Datagrams, driver: Background) -> Self { + pub(crate) fn new(track: moq_net::track::Subscriber, driver: Background) -> Self { let control = track.control(); let info = track.info().clone(); Self { reads: Polled::new(TrackInner { track: Cursor::Uncommitted(track), - datagrams, }) .supervised(driver.clone()), control, @@ -646,7 +555,7 @@ impl MoqTrackConsumer { /// Hand the subscription to a typed reader (a JSON consumer, say), closing this handle. /// /// Errors with [`MoqError::AlreadyCommitted`] once a group read has started, since the reader - /// would miss whatever that read consumed. A datagram read still parked resolves `Cancelled`. + /// would miss whatever that read consumed. pub(crate) fn take(&self) -> Result<(moq_net::track::Subscriber, Background), MoqError> { let inner = self .reads @@ -714,23 +623,6 @@ impl MoqTrackConsumer { Ok(frame.map(raw_frame)) } - /// Receive the next best-effort datagram in arrival order. - /// - /// A consumer from [`MoqTrackProducer::consume`](crate::producer::MoqTrackProducer::consume) - /// receives the datagrams sent after it was created. One from a subscription subscribes to - /// the track's datagrams on its first call, receiving those sent from then on, so start - /// reading before the ones you want are sent. Returns `None` when the track ends. - /// Datagram delivery is unavailable over pre-lite-05 moq-lite, moq-transport, and - /// stream-only transports. Datagrams are separate from groups, so this works alongside - /// either group order, never commits the track to one, and progresses while a group - /// read is pending. - pub async fn recv_datagram(&self) -> Result, MoqError> { - let control = &self.control; - self.reads - .wait(|inner, waiter| inner.poll_recv_datagram(waiter, control)) - .await - } - /// Return the publisher-side track properties learned during subscription. pub fn info(&self) -> MoqTrackInfo { MoqTrackInfo::from(&self.info) @@ -743,16 +635,10 @@ impl MoqTrackConsumer { /// preferences as they were. pub fn update(&self, subscription: MoqSubscription) -> Result<(), MoqError> { let subscription: moq_net::track::Subscription = subscription.try_into()?; - let priority = subscription.priority; match self.control.update(subscription) { Ok(()) | Err(moq_net::Error::Closed) => {} Err(err) => return Err(err.into()), } - self.reads.peek_mut(|inner| { - if let Datagrams::Open(datagrams) = &mut inner.datagrams { - datagrams.set_priority(priority); - } - }); Ok(()) } diff --git a/rs/moq-ffi/src/datagram.rs b/rs/moq-ffi/src/datagram.rs new file mode 100644 index 00000000000..353c25f2614 --- /dev/null +++ b/rs/moq-ffi/src/datagram.rs @@ -0,0 +1,326 @@ +//! Live datagram tracks, independent of stream tracks with the same name. + +use std::sync::Arc; +use std::task::{Poll, ready}; + +use crate::consumer::MoqBroadcastConsumer; +use crate::error::MoqError; +use crate::ffi::{Background, Polled}; +use crate::media::{MoqDatagram, MoqTimestamp}; +use crate::producer::{Child, Children, MoqBroadcastProducer, MoqBroadcastRequests}; + +/// Publisher properties of a datagram track, fixed at creation. +#[derive(Clone, Default, uniffi::Record)] +pub struct MoqDatagramInfo { + /// Publisher priority, breaking ties between equal subscriber priorities. + #[uniffi(default = 0)] + pub priority: i8, + /// Timestamp ticks per second, or null for an untimed track. + #[uniffi(default = None)] + pub timescale: Option, +} + +impl TryFrom for moq_net::datagram::Info { + type Error = MoqError; + + fn try_from(info: MoqDatagramInfo) -> Result { + let timescale = info + .timescale + .map(moq_net::Timescale::new) + .transpose() + .map_err(|_| MoqError::Codec { + reason: "invalid datagram timescale".into(), + })?; + Ok(Self::default().with_priority(info.priority).with_timescale(timescale)) + } +} + +impl From for MoqDatagramInfo { + fn from(info: moq_net::datagram::Info) -> Self { + Self { + priority: info.priority, + timescale: info.timescale.map(|scale| scale.as_u64()), + } + } +} + +#[uniffi::export] +impl MoqBroadcastProducer { + /// Create a live datagram track in its own namespace. + pub fn create_datagrams( + &self, + name: String, + info: Option, + ) -> Result, MoqError> { + let _guard = crate::ffi::enter(); + let info = info.unwrap_or_default().try_into()?; + self.with_state(|state| { + let producer = state.broadcast.create_datagrams(name, info)?; + MoqDatagramProducer::child(producer, &state.children) + }) + } +} + +#[uniffi::export] +impl MoqBroadcastConsumer { + /// Subscribe to a live datagram track, receiving only datagrams written from now on. + pub fn datagrams(&self, name: String) -> Result, MoqError> { + let _guard = crate::ffi::enter(); + self.driver.check()?; + Ok(Arc::new(MoqDatagramConsumer::new( + self.inner.datagrams(&name)?, + self.driver.clone(), + ))) + } +} + +/// Writes datagrams with a shared sequence counter and no groups or cache. +#[derive(uniffi::Object)] +pub struct MoqDatagramProducer { + inner: Polled, +} + +impl MoqDatagramProducer { + fn child(producer: moq_net::datagram::Producer, children: &Children) -> Result, MoqError> { + children.adopt(Arc::new(Self { + inner: Polled::new(producer), + })) + } +} + +impl Child for MoqDatagramProducer { + fn abort(&self, err: moq_net::Error) { + let _guard = crate::ffi::enter(); + if let Ok(producer) = self.inner.take(|_| Ok(())) { + producer.abort(err); + } + } +} + +impl Drop for MoqDatagramProducer { + fn drop(&mut self) { + Child::abort(self, moq_net::Error::Unroutable); + } +} + +#[uniffi::export] +impl MoqDatagramProducer { + /// The datagram track's name. + pub fn name(&self) -> Result { + self.inner + .peek(|producer| producer.name().to_owned()) + .ok_or(MoqError::Closed) + } + + /// The publisher properties fixed when this track was created. + pub fn info(&self) -> Result { + self.inner + .peek(|producer| (*producer.info()).into()) + .ok_or(MoqError::Closed) + } + + /// Append a datagram, returning its assigned sequence; its timestamp must match the track. + pub fn append(&self, timestamp: Option, payload: Vec) -> Result { + let _guard = crate::ffi::enter(); + let timestamp = timestamp.map(TryInto::try_into).transpose()?; + Ok(self + .inner + .peek_mut(|producer| producer.append(timestamp, payload)) + .ok_or(MoqError::Closed)??) + } + + /// Insert a datagram at its explicit sequence; later appends continue past the highest one. + pub fn insert(&self, datagram: MoqDatagram) -> Result<(), MoqError> { + let _guard = crate::ffi::enter(); + let datagram = moq_net::Datagram { + sequence: datagram.sequence, + timestamp: datagram.timestamp.map(TryInto::try_into).transpose()?, + payload: datagram.payload.into(), + }; + Ok(self + .inner + .peek_mut(|producer| producer.insert(datagram)) + .ok_or(MoqError::Closed)??) + } + + /// Create a local consumer, starting with the next datagram written. + pub fn consume(&self) -> Result, MoqError> { + let _guard = crate::ffi::enter(); + let consumer = self.inner.peek(|producer| producer.consume()).ok_or(MoqError::Closed)?; + Ok(Arc::new(MoqDatagramConsumer::new(consumer, Background::default()))) + } + + /// The highest subscriber priority, or null while nobody consumes this track. + pub fn priority(&self) -> Result, MoqError> { + self.inner.peek(|producer| producer.priority()).ok_or(MoqError::Closed) + } + + /// Wait until the aggregate subscriber priority differs from `last`. + pub async fn priority_changed(&self, last: Option) -> Result, MoqError> { + self.inner + .wait(|producer, waiter| Poll::Ready(Ok(ready!(producer.poll_priority(waiter, last))))) + .await + } + + /// Finish the track; existing consumers drain their unread datagrams before its end. + pub fn finish(&self) -> Result<(), MoqError> { + let _guard = crate::ffi::enter(); + self.inner.take(|_| Ok(()))?.finish(); + Ok(()) + } + + /// Abort the track with an application error, discarding unread datagrams. + pub fn abort(&self, error_code: u16) -> Result<(), MoqError> { + let _guard = crate::ffi::enter(); + self.inner.take(|_| Ok(()))?.abort(moq_net::Error::App(error_code)); + Ok(()) + } +} + +/// Reads a live datagram track from its own arrival cursor. +#[derive(uniffi::Object)] +pub struct MoqDatagramConsumer { + inner: Polled, +} + +impl MoqDatagramConsumer { + fn new(consumer: moq_net::datagram::Consumer, driver: Background) -> Self { + Self { + inner: Polled::new(consumer).supervised(driver), + } + } +} + +#[uniffi::export] +impl MoqDatagramConsumer { + /// The datagram track's name. + pub fn name(&self) -> Result { + self.inner + .peek(|consumer| consumer.name().to_owned()) + .ok_or(MoqError::Closed) + } + + /// Wait for the publisher to accept this track and return its properties. + pub async fn info(&self) -> Result { + self.inner + .wait(|consumer, waiter| Poll::Ready(Ok(ready!(consumer.poll_info(waiter))?.into()))) + .await + } + + /// Receive the next datagram in arrival order, or null after the track finishes. + pub async fn recv(&self) -> Result, MoqError> { + self.inner + .wait(|consumer, waiter| { + Poll::Ready(Ok(ready!(consumer.poll_recv(waiter))?.map(|datagram| MoqDatagram { + sequence: datagram.sequence, + timestamp: datagram.timestamp.map(Into::into), + payload: datagram.payload.to_vec(), + }))) + }) + .await + } + + /// This consumer's subscriber priority. + pub fn priority(&self) -> Result { + self.inner.peek(|consumer| consumer.priority()).ok_or(MoqError::Closed) + } + + /// Change this consumer's subscriber priority, higher first. + pub fn set_priority(&self, priority: i8) -> Result<(), MoqError> { + let _guard = crate::ffi::enter(); + self.inner + .peek_mut(|consumer| consumer.set_priority(priority)) + .ok_or(MoqError::Closed) + } + + /// Cancel current and future reads and release this consumer's demand. + pub fn cancel(&self) { + self.inner.cancel(); + } +} + +/// Handles requests for datagram tracks separately from stream tracks. +#[derive(uniffi::Object)] +pub struct MoqDatagramRequests { + inner: Polled, + children: Children, +} + +#[uniffi::export] +impl MoqBroadcastRequests { + /// Create an on-demand handler for datagram tracks. + pub fn datagrams(&self) -> Result, MoqError> { + let _guard = crate::ffi::enter(); + let requests = self + .reads + .peek(|inner| inner.requests.datagrams()) + .ok_or(MoqError::Closed)?; + Ok(Arc::new(MoqDatagramRequests { + inner: Polled::new(requests).supervised(self.driver.clone()), + children: self.children.clone(), + })) + } +} + +#[uniffi::export] +impl MoqDatagramRequests { + /// Wait for the next datagram track requested by a consumer. + pub async fn requested(&self) -> Result, MoqError> { + let request = self + .inner + .wait(|requests, waiter| Poll::Ready(Ok(ready!(requests.poll_requested(waiter))?))) + .await?; + Ok(Arc::new(MoqDatagramRequest { + inner: std::sync::Mutex::new(Some(request)), + children: self.children.clone(), + })) + } + + /// Cancel the handler and reject requests it has not handed out. + pub fn cancel(&self) { + self.inner.cancel(); + } +} + +/// A requested datagram track awaiting acceptance or rejection. +#[derive(uniffi::Object)] +pub struct MoqDatagramRequest { + inner: std::sync::Mutex>, + children: Children, +} + +#[uniffi::export] +impl MoqDatagramRequest { + /// The requested datagram track's name. + pub fn name(&self) -> Result { + Ok(self + .inner + .lock() + .unwrap() + .as_ref() + .ok_or(MoqError::Closed)? + .name() + .to_owned()) + } + + /// The highest priority among the consumers waiting for this track. + pub fn priority(&self) -> Result, MoqError> { + Ok(self.inner.lock().unwrap().as_ref().ok_or(MoqError::Closed)?.priority()) + } + + /// Accept the request with its fixed publisher properties. + pub fn accept(&self, info: Option) -> Result, MoqError> { + let _guard = crate::ffi::enter(); + let info = info.unwrap_or_default().try_into()?; + let request = self.inner.lock().unwrap().take().ok_or(MoqError::Closed)?; + MoqDatagramProducer::child(request.accept(info), &self.children) + } + + /// Reject this request with an application error code. + pub fn abort(&self, error_code: u16) -> Result<(), MoqError> { + let _guard = crate::ffi::enter(); + let request = self.inner.lock().unwrap().take().ok_or(MoqError::Closed)?; + request.reject(moq_net::Error::App(error_code)); + Ok(()) + } +} diff --git a/rs/moq-ffi/src/lib.rs b/rs/moq-ffi/src/lib.rs index 5e8e59729ff..2b68dd8e6e6 100644 --- a/rs/moq-ffi/src/lib.rs +++ b/rs/moq-ffi/src/lib.rs @@ -16,6 +16,7 @@ pub mod audio; pub mod auth; pub mod bandwidth; pub mod consumer; +pub mod datagram; pub mod demand; pub mod error; mod ffi; diff --git a/rs/moq-ffi/src/media.rs b/rs/moq-ffi/src/media.rs index 5f74160b019..c47289c0188 100644 --- a/rs/moq-ffi/src/media.rs +++ b/rs/moq-ffi/src/media.rs @@ -254,19 +254,16 @@ pub struct MoqMediaFrame { pub keyframe: bool, } -/// A best-effort raw track datagram, as received. -/// -/// Send one with [`append_datagram`](crate::producer::MoqTrackProducer::append_datagram), which -/// takes a [`MoqFrame`] and assigns the sequence number for you. +/// A datagram payload with its own sequence and optional timestamp. #[derive(uniffi::Record)] pub struct MoqDatagram { - /// The datagram's sequence number, counted apart from the track's groups. + /// The datagram track's own sequence number. #[uniffi(default = 0)] pub sequence: u64, /// Presentation timestamp, or null on an untimed track, on both publish and receive. #[uniffi(default = None)] pub timestamp: Option, - /// Datagram payload, capped at 1200 bytes. + /// Datagram payload; keep it well below the path MTU so each hop can carry it. pub payload: Vec, } diff --git a/rs/moq-ffi/src/producer.rs b/rs/moq-ffi/src/producer.rs index 4228694b7fe..d43b4115dee 100644 --- a/rs/moq-ffi/src/producer.rs +++ b/rs/moq-ffi/src/producer.rs @@ -5,7 +5,7 @@ use std::task::{Poll, ready}; use moq_mux::catalog::hang::Extra; -use crate::consumer::{Datagrams, MoqBroadcastConsumer, MoqGroupConsumer, MoqOrder, MoqSubscription, MoqTrackConsumer}; +use crate::consumer::{MoqBroadcastConsumer, MoqGroupConsumer, MoqOrder, MoqSubscription, MoqTrackConsumer}; use crate::demand::MoqTrackDemand; use crate::error::MoqError; use crate::ffi::{Background, Polled}; @@ -84,13 +84,6 @@ fn raw_track_info(info: Option) -> Result moq_net::datagram::Info { - moq_net::datagram::Info::default() - .with_timescale(info.timescale) - .with_priority(info.priority) -} - impl From<&moq_net::track::Info> for MoqTrackInfo { fn from(info: &moq_net::track::Info) -> Self { Self { @@ -180,7 +173,7 @@ impl Children { } /// The broadcast, while a handle keeping it open still holds it. - fn broadcast(&self) -> Option> { + pub(crate) fn broadcast(&self) -> Option> { self.broadcast.upgrade() } @@ -249,14 +242,15 @@ pub struct MoqBroadcastProducer { /// A handler for requests for tracks in a broadcast. #[derive(uniffi::Object)] pub struct MoqBroadcastRequests { - reads: Polled, - children: Children, + pub(crate) reads: Polled, + pub(crate) children: Children, + pub(crate) driver: Background, } -struct RequestsInner { - requests: moq_net::broadcast::Requests, +pub(crate) struct RequestsInner { + pub(crate) requests: moq_net::broadcast::Requests, /// Holds the broadcast for [`Children::broadcast`] as long as `requests` keeps it open, so a - /// request accepted after the broadcast handle dropped still creates its datagram track. + /// request can still be accepted after the broadcast handle dropped. _broadcast: Arc, } @@ -344,6 +338,7 @@ impl MoqBroadcastProducer { }; Ok(Arc::new(MoqBroadcastRequests { reads: Polled::new(inner).supervised(state.driver.clone()), + driver: state.driver.clone(), children: state.children.clone(), })) }) @@ -371,15 +366,8 @@ impl MoqBroadcastProducer { let _guard = crate::ffi::enter(); self.with_state(|state| { let info = raw_track_info(info)?; - let datagrams = state.broadcast.create_datagrams(name.as_str(), datagram_info(&info))?; - let track = match state.broadcast.create_track(name, Some(info)) { - Ok(track) => track, - Err(err) => { - datagrams.abort(err.clone()); - return Err(err.into()); - } - }; - MoqTrackProducer::child(Raw::new(track, datagrams), &state.children) + let track = state.broadcast.create_track(name, Some(info))?; + MoqTrackProducer::child(track, &state.children) }) } @@ -633,21 +621,12 @@ impl MoqTrackRequest { let info = raw_track_info(info)?; let request = self.take()?; // Without a handle keeping it open, the broadcast has ended. - let Some(broadcast) = self.children.broadcast() else { + let Some(_broadcast) = self.children.broadcast() else { request.reject(moq_net::Error::Unroutable); return Err(MoqError::Closed); }; - // The datagram track first: accepting wakes the track's subscribers, and one that asks - // for its datagrams, or a lite-05/06 subscription that carries them, must find it. - let datagrams = match broadcast.create_datagrams(request.name(), datagram_info(&info)) { - Ok(datagrams) => datagrams, - Err(err) => { - request.reject(err.clone()); - return Err(err.into()); - } - }; let track = request.accept(Some(info)); - MoqTrackProducer::child(Raw::new(track, datagrams), &self.children) + MoqTrackProducer::child(track, &self.children) } /// Reject the request with an application error code, failing the waiting subscriber. @@ -661,54 +640,25 @@ impl MoqTrackRequest { // ---- Track Producer ---- -/// A track to which groups, frames, or datagrams can be published. +/// A stream track to which groups and frames can be published. /// /// Released before its finish, or still open when its broadcast closes, it ends its track with /// `Unroutable`, which a moq-transport reader sees as `Internal`: its wire has no such code. #[derive(uniffi::Object)] pub struct MoqTrackProducer { - inner: std::sync::Mutex>, + inner: std::sync::Mutex>, // Taken by the first finish, so repeating it keeps the track only once. keep: std::sync::Mutex>, } -/// A raw track and the datagram track of the same name that carries its datagrams. -struct Raw { - track: moq_net::track::Producer, - /// Ended with the track, so `None` once it finished. - datagrams: Option, -} - -impl Raw { - fn new(track: moq_net::track::Producer, datagrams: moq_net::datagram::Producer) -> Self { - Self { - track, - datagrams: Some(datagrams), - } - } - - /// End both tracks with `err`. A track with a declared end ends there instead, as when its - /// handle drops, and its datagrams finish with it. - fn abort(self, err: moq_net::Error) { - let finished = self.track.finished().is_some(); - if let Some(datagrams) = self.datagrams { - match finished { - true => datagrams.finish(), - false => datagrams.abort(err.clone()), - } - } - if !finished { - let _ = self.track.abort(err); - } - } -} - impl Child for MoqTrackProducer { fn abort(&self, err: moq_net::Error) { let _guard = crate::ffi::enter(); let raw = self.inner.lock().unwrap().take(); - if let Some(raw) = raw { - raw.abort(err); + if let Some(raw) = raw + && raw.finished().is_none() + { + let _ = raw.abort(err); } } } @@ -717,15 +667,17 @@ impl Drop for MoqTrackProducer { fn drop(&mut self) { let _guard = crate::ffi::enter(); // A finished track lives on in its broadcast, and may still take groups below its end. - if let Some(raw) = self.inner.get_mut().unwrap().take() { - raw.abort(moq_net::Error::Unroutable); + if let Some(raw) = self.inner.get_mut().unwrap().take() + && raw.finished().is_none() + { + let _ = raw.abort(moq_net::Error::Unroutable); } } } impl MoqTrackProducer { /// Wrap `raw` as a child of the broadcast `children` belongs to. - fn child(raw: Raw, children: &Children) -> Result, MoqError> { + fn child(raw: moq_net::track::Producer, children: &Children) -> Result, MoqError> { children.adopt(Arc::new(Self { inner: std::sync::Mutex::new(Some(raw)), keep: std::sync::Mutex::new(Some(children.clone())), @@ -735,7 +687,7 @@ impl MoqTrackProducer { pub(crate) fn track_demand(&self) -> Result { let guard = self.inner.lock().unwrap(); let raw = guard.as_ref().ok_or(MoqError::Closed)?; - Ok(raw.track.demand()) + Ok(raw.demand()) } /// Hand the track to a typed writer that `f` builds (a JSON producer, say), closing this @@ -748,7 +700,7 @@ impl MoqTrackProducer { // Taken for the whole construction, so a racing adopt finds the handle closed. `f` runs // outside the lock: it may take the broadcast's, which a close holds while it takes this one. let raw = self.inner.lock().unwrap().take().ok_or(MoqError::Closed)?; - let writer = match f(raw.track.clone()) { + let writer = match f(raw.clone()) { Ok(writer) => Arc::new(writer), Err(err) => { *self.inner.lock().unwrap() = Some(raw); @@ -760,10 +712,6 @@ impl MoqTrackProducer { return Err(err); } }; - // The writer publishes groups only. - if let Some(datagrams) = raw.datagrams { - datagrams.finish(); - } // A finished track has no family left to join, and ends at its declared end. let children = self.keep.lock().unwrap().clone(); match children { @@ -783,7 +731,7 @@ impl MoqTrackProducer { let _guard = crate::ffi::enter(); let guard = self.inner.lock().unwrap(); let raw = guard.as_ref().ok_or(MoqError::Closed)?; - Ok(Arc::new(MoqTrackRequests::new(raw.track.requests()))) + Ok(Arc::new(MoqTrackRequests::new(raw.requests()))) } /// A watch-only handle to this track's name and whether it has subscribers. @@ -800,17 +748,8 @@ impl MoqTrackProducer { let guard = self.inner.lock().unwrap(); let raw = guard.as_ref().ok_or(MoqError::Closed)?; let subscription = subscription.map(moq_net::track::Subscription::try_from).transpose()?; - let track = raw.track.subscribe(subscription); - // Opened now: a local reader costs no subscription, and reads what is sent from here on. - let datagrams = match &raw.datagrams { - Some(datagrams) => { - let mut datagrams = datagrams.consume(); - datagrams.set_priority(track.control().subscription().priority); - Datagrams::Open(datagrams) - } - None => Datagrams::Ended, - }; - Ok(Arc::new(MoqTrackConsumer::new(track, datagrams, Background::default()))) + let track = raw.subscribe(subscription); + Ok(Arc::new(MoqTrackConsumer::new(track, Background::default()))) } /// Append a new group to the track, returning a producer for writing frames into it. @@ -818,7 +757,7 @@ impl MoqTrackProducer { let _guard = crate::ffi::enter(); let mut guard = self.inner.lock().unwrap(); let raw = guard.as_mut().ok_or(MoqError::Closed)?; - let group = raw.track.append_group()?; + let group = raw.append_group()?; Ok(Arc::new(MoqGroupProducer { sequence: group.sequence, inner: std::sync::Mutex::new(Some(group)), @@ -833,7 +772,7 @@ impl MoqTrackProducer { let _guard = crate::ffi::enter(); let mut guard = self.inner.lock().unwrap(); let raw = guard.as_mut().ok_or(MoqError::Closed)?; - let group = raw.track.create_group(moq_net::group::Info { sequence })?; + let group = raw.create_group(moq_net::group::Info { sequence })?; Ok(Arc::new(MoqGroupProducer { sequence: group.sequence, inner: std::sync::Mutex::new(Some(group)), @@ -850,43 +789,10 @@ impl MoqTrackProducer { let timestamp = frame.timestamp.map(TryInto::try_into).transpose()?; let mut guard = self.inner.lock().unwrap(); let raw = guard.as_mut().ok_or(MoqError::Closed)?; - raw.track.write_frame(timestamp, frame.payload)?; + raw.write_frame(timestamp, frame.payload)?; Ok(()) } - /// Send `frame` as a best-effort datagram, returning the sequence number assigned to it. - /// - /// Datagrams are numbered on their own, apart from groups. A reader receives only those - /// sent after it subscribed to datagrams; see - /// [`recv_datagram`](crate::consumer::MoqTrackConsumer::recv_datagram). The payload must be - /// at most 1200 bytes. Datagrams are only delivered on transports and wire - /// versions with a datagram channel; there is no stream fallback. Like a frame, its - /// timestamp must match the track's timedness. - pub fn append_datagram(&self, frame: MoqFrame) -> Result { - let _guard = crate::ffi::enter(); - let timestamp = frame.timestamp.map(TryInto::try_into).transpose()?; - let mut guard = self.inner.lock().unwrap(); - let datagrams = guard.as_mut().and_then(|raw| raw.datagrams.as_mut()); - Ok(datagrams.ok_or(MoqError::Closed)?.append(timestamp, frame.payload)?) - } - - /// Send `frame` as a best-effort datagram at an explicit `sequence`. - /// - /// [`append_datagram`](Self::append_datagram) continues past the highest sequence sent; this - /// is for a caller that allocates its own, such as an encryption layer binding the sequence - /// into its nonce. The same payload, transport, and timedness rules apply. - pub fn insert_datagram(&self, sequence: u64, frame: MoqFrame) -> Result<(), MoqError> { - let _guard = crate::ffi::enter(); - let timestamp = frame.timestamp.map(TryInto::try_into).transpose()?; - let mut guard = self.inner.lock().unwrap(); - let datagrams = guard.as_mut().and_then(|raw| raw.datagrams.as_mut()); - Ok(datagrams.ok_or(MoqError::Closed)?.insert(moq_net::Datagram { - sequence, - timestamp, - payload: frame.payload.into(), - })?) - } - /// The newest content this track holds: its newest group, at that group's newest frame /// (0 while it is empty), or null before any group was written. /// @@ -896,7 +802,7 @@ impl MoqTrackProducer { let _guard = crate::ffi::enter(); let guard = self.inner.lock().unwrap(); let raw = guard.as_ref().ok_or(MoqError::Closed)?; - Ok(raw.track.largest().map(MoqPosition::from)) + Ok(raw.largest().map(MoqPosition::from)) } /// Abort this track with an application error code. @@ -905,10 +811,7 @@ impl MoqTrackProducer { let mut guard = self.inner.lock().unwrap(); let raw = guard.take().ok_or(MoqError::Closed)?; let err = moq_net::Error::App(error_code); - if let Some(datagrams) = raw.datagrams { - datagrams.abort(err.clone()); - } - raw.track.abort(err)?; + raw.abort(err)?; Ok(()) } @@ -921,14 +824,11 @@ impl MoqTrackProducer { let _guard = crate::ffi::enter(); let mut guard = self.inner.lock().unwrap(); let raw = guard.as_mut().ok_or(MoqError::Closed)?; - if raw.track.finished().is_none() { - raw.track.finish()?; - } - if let Some(datagrams) = raw.datagrams.take() { - datagrams.finish(); + if raw.finished().is_none() { + raw.finish()?; } if let Some(children) = self.keep.lock().unwrap().take() { - children.keep(raw.track.clone()); + children.keep(raw.clone()); } Ok(()) } @@ -942,8 +842,7 @@ impl MoqTrackProducer { let _guard = crate::ffi::enter(); let mut guard = self.inner.lock().unwrap(); let raw = guard.as_mut().ok_or(MoqError::Closed)?; - raw.track - .finish_at(moq_net::track::Position::group(final_sequence), None)?; + raw.finish_at(moq_net::track::Position::group(final_sequence), None)?; Ok(()) } } diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index d523344453b..b57f3ab8b60 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -7,6 +7,7 @@ use crate::consumer::MoqFetchGroupOptions; use crate::consumer::MoqGroupConsumer; use crate::consumer::MoqTrackConsumer; use crate::consumer::{MoqAnchor, MoqDelay, MoqOrder, MoqRange, MoqSubscription, moq_subscription_defaults}; +use crate::datagram::*; use crate::error::{MoqError, MoqProtocolError, MoqProtocolKind}; use crate::json::{ MoqJsonSnapshotConfig, MoqJsonSnapshotConsumer, MoqJsonSnapshotProducer, MoqJsonStreamConsumer, @@ -96,23 +97,6 @@ where handle } -/// The datagram `send` writes, read by a `recv_datagram` started first: a subscription -/// receives only datagrams sent after its first read. -async fn datagram_sent_by(consumer: &Arc, send: impl FnOnce() -> T) -> (T, MoqDatagram) { - let read = { - let consumer = consumer.clone(); - spawn_parked(async move { consumer.recv_datagram().await }).await - }; - let sent = send(); - let datagram = kio::clock::timeout(TIMEOUT, read) - .await - .expect("timed out waiting for a datagram") - .expect("datagram read panicked") - .unwrap() - .expect("expected a datagram"); - (sent, datagram) -} - /// Trust any certificate, for dialing a server with a generated one. fn insecure_tls() -> MoqClientTls { MoqClientTls { @@ -1247,28 +1231,20 @@ async fn raw_audio_codec_default_frame() { async fn raw_track_datagram_roundtrip() { let broadcast = MoqBroadcastProducer::new().unwrap(); let track = broadcast - .publish_track( + .create_datagrams( "events".into(), - Some(MoqTrackInfo { + Some(MoqDatagramInfo { priority: 0, - max_age: None, - refresh: None, timescale: Some(1_000_000), - compress: false, }), ) .unwrap(); - let consumer = track.consume(None).unwrap(); + let consumer = track.consume().unwrap(); let payload = b"hello datagram".to_vec(); // A local reader receives what is sent after it was created, before its first read. - let sequence = track - .append_datagram(MoqFrame { - payload: payload.clone(), - timestamp: Some(us(123_456)), - }) - .unwrap(); - let datagram = kio::clock::timeout(TIMEOUT, consumer.recv_datagram()) + let sequence = track.append(Some(us(123_456)), payload.clone()).unwrap(); + let datagram = kio::clock::timeout(TIMEOUT, consumer.recv()) .await .expect("timed out waiting for datagram") .unwrap() @@ -2024,47 +2000,21 @@ async fn track_request_demand_survives_accept() { ); } -/// A requested track carries datagrams, even accepted once only its request handler keeps -/// the broadcast open. +/// A datagram handler keeps its broadcast alive independently of the stream handler. #[tokio::test] -async fn requested_track_carries_datagrams() { +async fn requested_datagrams_outlive_the_broadcast_handle() { let broadcast = MoqBroadcastProducer::new().unwrap(); - let dynamic = broadcast.requests().unwrap(); - let consumer = broadcast.consume().unwrap(); + let requests = broadcast.requests().unwrap(); + let datagrams = requests.datagrams().unwrap(); + let consumer = broadcast.consume().unwrap().datagrams("events".into()).unwrap(); + drop(requests); drop(broadcast); - let subscribe = tokio::spawn(async move { consumer.subscribe_track("events".into(), None).await }); - let request = kio::clock::timeout(TIMEOUT, dynamic.requested_track()) - .await - .expect("timed out waiting for the request") - .unwrap(); - let track = request.accept(Some(timed_info())).unwrap(); - let consumer = subscribe.await.unwrap().unwrap(); - let (sequence, datagram) = - datagram_sent_by(&consumer, || track.append_datagram(datagram_frame(b"beep")).unwrap()).await; - assert_eq!((datagram.sequence, datagram.payload), (sequence, b"beep".to_vec())); -} - -/// A track that finished before its first datagram read has none to come: its datagram -/// track finished with it and is no longer found, which reads as the end, not an error. -#[tokio::test] -async fn a_finished_track_reads_no_datagrams() { - let broadcast = MoqBroadcastProducer::new().unwrap(); - let track = broadcast.publish_track("events".into(), Some(timed_info())).unwrap(); - let consumer = broadcast - .consume() - .unwrap() - .subscribe_track("events".into(), None) - .await - .unwrap(); - track.finish().unwrap(); - let read = kio::clock::timeout(TIMEOUT, consumer.recv_datagram()) - .await - .expect("timed out waiting for the end"); - assert!( - matches!(read, Ok(None)), - "{:?}", - read.map(|datagram| datagram.map(|d| d.sequence)) - ); + let request = datagrams.requested().await.unwrap(); + assert_eq!(request.name().unwrap(), "events"); + assert_eq!(request.priority().unwrap(), Some(0)); + let producer = request.accept(None).unwrap(); + producer.append(None, b"beep".to_vec()).unwrap(); + assert_eq!(consumer.recv().await.unwrap().unwrap().payload, b"beep"); } #[tokio::test] @@ -2128,7 +2078,7 @@ async fn dynamic_track_request() { } #[tokio::test] -async fn raw_untimed_frames_and_datagrams_roundtrip() { +async fn raw_untimed_frames_roundtrip() { let broadcast = MoqBroadcastProducer::new().unwrap(); let track = broadcast.publish_track("untimed".into(), None).unwrap(); let consumer = track.consume(None).unwrap(); @@ -2154,24 +2104,10 @@ async fn raw_untimed_frames_and_datagrams_roundtrip() { let frame = reader.read_frame().await.unwrap().unwrap(); assert_eq!(frame.payload, b"group"); assert_eq!(frame.timestamp, None); - let (_, datagram) = datagram_sent_by(&consumer, || { - track - .append_datagram(MoqFrame { - payload: b"datagram".to_vec(), - timestamp: None, - }) - .unwrap() - }) - .await; - assert_eq!(datagram.payload, b"datagram"); - assert_eq!(datagram.timestamp, None); track.finish().unwrap(); - // The datagrams end with the track, for readers from before and after the finish. - assert!(consumer.recv_datagram().await.unwrap().is_none()); - assert!(track.consume(None).unwrap().recv_datagram().await.unwrap().is_none()); } -/// An explicitly timed raw track refuses frames and datagrams without a timestamp. +/// An explicitly timed raw track refuses frames without a timestamp. #[test] fn raw_writes_need_a_timestamp() { let broadcast = MoqBroadcastProducer::new().unwrap(); @@ -2192,7 +2128,6 @@ fn raw_writes_need_a_timestamp() { ) }; assert!(refused(track.write_frame(untimed()).unwrap_err())); - assert!(refused(track.append_datagram(untimed()).unwrap_err())); let group = track.append_group().unwrap(); assert!(refused(group.write_frame(untimed()).unwrap_err())); } @@ -2269,26 +2204,6 @@ async fn timestamps_are_exact() { assert_eq!(frame.timestamp, Some(timestamp)); } - // An inserted datagram keeps the exact tick too. - let tick = MoqTimestamp { - value: 1, - scale: 90_000, - }; - let (_, datagram) = datagram_sent_by(&consumer, || { - track - .insert_datagram( - 7, - MoqFrame { - payload: b"datagram".to_vec(), - timestamp: Some(tick), - }, - ) - .unwrap() - }) - .await; - assert_eq!(datagram.sequence, 7); - assert_eq!(datagram.timestamp, Some(tick)); - for invalid in [ MoqTimestamp { value: 0, scale: 0 }, MoqTimestamp { @@ -5278,7 +5193,6 @@ async fn raw_track_next_group_is_repeatable() { /// The first group read commits the cursor either way: mixing arrival and sequence /// reads on one track is refused rather than silently interleaving two cursors. -/// Datagrams are a separate cursor, so they flow regardless of the commitment. #[tokio::test] async fn raw_track_group_order_commits_on_first_read() { let broadcast = MoqBroadcastProducer::new().unwrap(); @@ -5320,27 +5234,6 @@ async fn raw_track_group_order_commits_on_first_read() { .unwrap() .expect("expected a group"); assert_eq!(group.sequence(), 1); - - // A subscription subscribes to datagrams on its first read, so one sent before is not - // delivered. - track - .append_datagram(MoqFrame { - payload: b"early".to_vec(), - timestamp: Some(us(0)), - }) - .unwrap(); - // Datagrams never commit and keep working after a commitment. - let (sequence, datagram) = datagram_sent_by(&consumer, || { - track - .append_datagram(MoqFrame { - payload: b"beep".to_vec(), - timestamp: Some(us(0)), - }) - .unwrap() - }) - .await; - assert_eq!(datagram.sequence, sequence); - assert_eq!(datagram.payload, b"beep".to_vec()); } fn raw_track() -> ( @@ -5354,13 +5247,6 @@ fn raw_track() -> ( (broadcast, track, consumer) } -fn datagram_frame(payload: &[u8]) -> MoqFrame { - MoqFrame { - payload: payload.to_vec(), - timestamp: Some(us(1)), - } -} - fn group_frame(payload: &[u8]) -> MoqFrame { MoqFrame { payload: payload.to_vec(), @@ -5368,84 +5254,6 @@ fn group_frame(payload: &[u8]) -> MoqFrame { } } -/// A pending group-lane read must not stall `recv_datagram` on the same subscription. -async fn pending_group_does_not_block_datagram(start_group: F) -where - F: FnOnce(Arc) -> Fut, - Fut: Future> + Send + 'static, - T: Send + 'static, -{ - let (_broadcast, track, consumer) = raw_track(); - - let group_read = { - let consumer = consumer.clone(); - spawn_parked(start_group(consumer)).await - }; - assert!(!group_read.is_finished(), "group read should still be pending"); - - let (sequence, datagram) = - datagram_sent_by(&consumer, || track.append_datagram(datagram_frame(b"beep")).unwrap()).await; - assert_eq!(datagram.sequence, sequence); - assert_eq!(datagram.payload, b"beep".to_vec()); - assert!(!group_read.is_finished(), "group read should stay pending"); - - track.write_frame(group_frame(b"group")).unwrap(); - kio::clock::timeout(TIMEOUT, group_read) - .await - .expect("timed out waiting for the parked group") - .expect("group read panicked") - .unwrap(); -} - -/// A pending datagram read must not stall a group-lane read on the same subscription. -async fn pending_datagram_does_not_block_group(start_group: F) -where - F: FnOnce(Arc) -> Fut, - Fut: Future> + Send + 'static, - T: Send + 'static, -{ - let (_broadcast, track, consumer) = raw_track(); - - let datagram_read = { - let consumer = consumer.clone(); - spawn_parked(async move { consumer.recv_datagram().await }).await - }; - assert!(!datagram_read.is_finished(), "datagram read should still be pending"); - - track.write_frame(group_frame(b"group")).unwrap(); - kio::clock::timeout(TIMEOUT, start_group(consumer.clone())) - .await - .expect("timed out waiting for a group behind a pending datagram read") - .unwrap(); - assert!(!datagram_read.is_finished(), "datagram read should stay pending"); - - let sequence = track.append_datagram(datagram_frame(b"beep")).unwrap(); - let datagram = kio::clock::timeout(TIMEOUT, datagram_read) - .await - .expect("timed out waiting for the parked datagram") - .expect("datagram read panicked") - .unwrap() - .expect("expected a datagram"); - assert_eq!(datagram.sequence, sequence); - assert_eq!(datagram.payload, b"beep".to_vec()); -} - -/// `insert_datagram` sends at the caller's sequence, and later appends continue past it. -#[tokio::test] -async fn raw_track_insert_datagram_keeps_its_sequence() { - let (_broadcast, track, consumer) = raw_track(); - - let ((), datagram) = datagram_sent_by(&consumer, || { - track.insert_datagram(7, datagram_frame(b"seven")).unwrap() - }) - .await; - assert_eq!(datagram.sequence, 7); - assert_eq!(datagram.payload, b"seven".to_vec()); - assert_eq!(datagram.timestamp.map(micros), Some(1)); - - assert_eq!(track.append_datagram(datagram_frame(b"next")).unwrap(), 8); -} - /// `largest` follows the newest group and its newest frame. #[test] fn raw_track_largest_follows_writes() { @@ -5483,179 +5291,6 @@ async fn broadcast_consumer_closed_resolves_on_close() { .unwrap(); } -#[tokio::test] -async fn raw_track_pending_next_group_does_not_block_datagram() { - pending_group_does_not_block_datagram(|consumer| async move { consumer.next_group().await }).await; -} - -#[tokio::test] -async fn raw_track_pending_recv_group_does_not_block_datagram() { - pending_group_does_not_block_datagram(|consumer| async move { consumer.recv_group().await }).await; -} - -#[tokio::test] -async fn raw_track_pending_read_frame_does_not_block_datagram() { - pending_group_does_not_block_datagram(|consumer| async move { consumer.read_frame().await }).await; -} - -#[tokio::test] -async fn raw_track_pending_datagram_does_not_block_next_group() { - pending_datagram_does_not_block_group(|consumer| async move { consumer.next_group().await }).await; -} - -#[tokio::test] -async fn raw_track_pending_datagram_does_not_block_recv_group() { - pending_datagram_does_not_block_group(|consumer| async move { consumer.recv_group().await }).await; -} - -#[tokio::test] -async fn raw_track_pending_datagram_does_not_block_read_frame() { - pending_datagram_does_not_block_group(|consumer| async move { consumer.read_frame().await }).await; -} - -#[tokio::test] -async fn raw_track_update_during_pending_group_still_reads_datagram() { - let (_broadcast, track, consumer) = raw_track(); - - let group_read = { - let consumer = consumer.clone(); - spawn_parked(async move { consumer.next_group().await }).await - }; - - consumer - .update(MoqSubscription { - priority: 10, - delay: MoqDelay { - min: Some(Duration::ZERO), - max: Some(Duration::from_millis(25)), - }, - ranges: Some(vec![MoqRange { - start: MoqAnchor::Absolute { group: 0 }, - end: None, - }]), - order: None, - }) - .unwrap(); - - let (sequence, datagram) = datagram_sent_by(&consumer, || { - track.append_datagram(datagram_frame(b"after-update")).unwrap() - }) - .await; - assert_eq!(datagram.sequence, sequence); - assert_eq!(datagram.payload, b"after-update".to_vec()); - - track.write_frame(group_frame(b"group")).unwrap(); - kio::clock::timeout(TIMEOUT, group_read) - .await - .expect("timed out waiting for the parked group") - .expect("group read panicked") - .unwrap() - .expect("expected a group"); -} - -#[tokio::test] -async fn raw_track_dropping_a_pending_group_read_does_not_cancel_datagrams() { - let (_broadcast, track, consumer) = raw_track(); - - let group_read = { - let consumer = consumer.clone(); - spawn_parked(async move { consumer.next_group().await }).await - }; - group_read.abort(); - match group_read.await { - Err(err) if err.is_cancelled() => {} - Err(err) => panic!("aborted group read should join as cancelled, got {err}"), - Ok(_) => panic!("aborting the call should cancel only that future"), - } - - let (sequence, datagram) = datagram_sent_by(&consumer, || { - track.append_datagram(datagram_frame(b"still-open")).unwrap() - }) - .await; - assert_eq!(datagram.sequence, sequence); - - track.write_frame(group_frame(b"group")).unwrap(); - let group = kio::clock::timeout(TIMEOUT, consumer.next_group()) - .await - .expect("timed out waiting for a group after the cancelled read") - .unwrap() - .expect("expected a group"); - let frame = kio::clock::timeout(TIMEOUT, group.read_frame()) - .await - .expect("timed out waiting for the group's frame") - .unwrap() - .expect("expected a frame"); - assert_eq!(frame.payload, b"group".to_vec()); -} - -#[tokio::test] -async fn raw_track_dropping_a_pending_datagram_read_does_not_cancel_groups() { - let (_broadcast, track, consumer) = raw_track(); - - let datagram_read = { - let consumer = consumer.clone(); - spawn_parked(async move { consumer.recv_datagram().await }).await - }; - datagram_read.abort(); - match datagram_read.await { - Err(err) if err.is_cancelled() => {} - Err(err) => panic!("aborted datagram read should join as cancelled, got {err}"), - Ok(_) => panic!("aborting the call should cancel only that future"), - } - - track.write_frame(group_frame(b"group")).unwrap(); - let group = kio::clock::timeout(TIMEOUT, consumer.next_group()) - .await - .expect("timed out waiting for a group after a cancelled datagram read") - .unwrap() - .expect("expected a group"); - assert_eq!(group.sequence(), 0); - - let sequence = track.append_datagram(datagram_frame(b"later")).unwrap(); - let datagram = kio::clock::timeout(TIMEOUT, consumer.recv_datagram()) - .await - .expect("timed out waiting for a datagram after the cancelled read") - .unwrap() - .expect("expected a datagram"); - assert_eq!(datagram.sequence, sequence); -} - -#[tokio::test] -async fn raw_track_handle_cancel_aborts_both_pending_lanes() { - let (_broadcast, _track, consumer) = raw_track(); - - let group_read = { - let consumer = consumer.clone(); - spawn_parked(async move { consumer.next_group().await }).await - }; - let datagram_read = { - let consumer = consumer.clone(); - spawn_parked(async move { consumer.recv_datagram().await }).await - }; - - consumer.cancel(); - - match kio::clock::timeout(TIMEOUT, group_read) - .await - .expect("timed out waiting for cancelled group read") - .expect("group read panicked") - { - Err(MoqError::Cancelled) => {} - Err(err) => panic!("handle cancel should fail the group read, got {err:?}"), - Ok(_) => panic!("handle cancel should fail the group read"), - } - - match kio::clock::timeout(TIMEOUT, datagram_read) - .await - .expect("timed out waiting for cancelled datagram read") - .expect("datagram read panicked") - { - Err(MoqError::Cancelled) => {} - Err(err) => panic!("handle cancel should fail the datagram read, got {err:?}"), - Ok(_) => panic!("handle cancel should fail the datagram read"), - } -} - /// An empty completed group is not track EOF: `read_frame` waits for a later /// group on a still-open track. #[tokio::test] @@ -5737,11 +5372,7 @@ async fn raw_read_frame_skips_a_group_reset_as_old() { Some(moq_net::track::Info::default().with_timescale(moq_net::Timescale::MILLI)), ) .unwrap(); - let consumer = MoqTrackConsumer::new( - track.subscribe(None), - crate::consumer::Datagrams::Remote(broadcast.consume()), - crate::ffi::Background::default(), - ); + let consumer = MoqTrackConsumer::new(track.subscribe(None), crate::ffi::Background::default()); let expired = track.append_group().unwrap(); // The read holds the group when the reset lands, as one arriving over the wire does. @@ -6319,8 +5950,9 @@ async fn roundtrip(media: &MoqMediaTrackProducer, track: &MoqMediaTrackConsumer, /// A server publishing `path` and a client following it over default versions, which /// negotiate lite-06: the server's broadcast, the client's view of it, the client's session, /// and what keeps the server side alive. -async fn default_connection( +async fn datagram_connection( path: &str, + versions: Vec, ) -> ( Arc, Arc, @@ -6331,6 +5963,7 @@ async fn default_connection( let server = MoqServer::new(MoqServerConfig { bind: Some("127.0.0.1:0".into()), tls: localhost_tls(), + versions: versions.clone(), publish: Some(server_origin.clone()), ..Default::default() }) @@ -6349,6 +5982,7 @@ async fn default_connection( let viewer = MoqOriginProducer::new(MoqOriginConfig::default()); let client = MoqClient::new(MoqClientConfig { tls: insecure_tls(), + versions, bind: Some("127.0.0.1:0".into()), consume: Some(viewer.clone()), ..Default::default() @@ -6367,62 +6001,67 @@ async fn default_connection( (broadcast, remote, session, (server, server_origin, server_session)) } -/// Read one datagram from `consumer`, resending `track`'s until one arrives: the reader joins -/// the datagrams on its first read, which lands a moment later, and one sent before is gone. -async fn resend_until_read(track: &MoqTrackProducer, consumer: &Arc) -> MoqDatagram { - let read = { - let consumer = consumer.clone(); - spawn_parked(async move { consumer.recv_datagram().await }).await - }; - let send = async { - loop { - track - .append_datagram(MoqFrame { - payload: b"reading".to_vec(), - timestamp: Some(us(5_000)), - }) - .unwrap(); - kio::clock::sleep(Duration::from_millis(10)).await; - } - }; - tokio::select! { - read = kio::clock::timeout(TIMEOUT, read) => read.expect("timed out waiting for a datagram"), - _ = send => unreachable!(), - } - .expect("datagram read panicked") - .unwrap() - .expect("expected a datagram") -} - -/// A raw track's datagrams reach a remote reader over a default connection, which negotiates -/// lite-06: its subscription to the track carries the track's datagrams too. +/// A native datagram-only reader reaches a publisher on the default lite-06 path. #[tokio::test] -async fn raw_track_datagrams_cross_a_default_connection() { - let (broadcast, remote, session, _server) = default_connection("sensor").await; - let track = broadcast.publish_track("events".into(), Some(timed_info())).unwrap(); - let consumer = remote.subscribe_track("events".into(), None).await.unwrap(); - let datagram = resend_until_read(&track, &consumer).await; - assert_eq!(datagram.payload, b"reading"); - assert_eq!(datagram.timestamp.map(micros), Some(5_000)); +async fn datagrams_cross_a_default_connection() { + let (broadcast, remote, session, _server) = datagram_connection("sensor", vec![]).await; + let producer = broadcast + .create_datagrams( + "events".into(), + Some(MoqDatagramInfo { + timescale: Some(90_000), + priority: 7, + }), + ) + .unwrap(); + let consumer = remote.datagrams("events".into()).unwrap(); + assert_eq!(consumer.info().await.unwrap().timescale, Some(90_000)); + producer.priority_changed(None).await.unwrap(); + producer + .append( + Some(MoqTimestamp { + value: 1, + scale: 90_000, + }), + b"tick".to_vec(), + ) + .unwrap(); + let datagram = kio::clock::timeout(TIMEOUT, consumer.recv()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(datagram.payload, b"tick"); + assert_eq!( + datagram.timestamp, + Some(MoqTimestamp { + value: 1, + scale: 90_000 + }) + ); assert_eq!(session.state().version.as_deref(), Some("moq-lite-06")); } -/// So do a requested track's: its datagram track exists before the accept answers the -/// subscription that carries them. #[tokio::test] -async fn requested_track_datagrams_cross_a_default_connection() { - let (broadcast, remote, session, _server) = default_connection("sensor").await; - let dynamic = broadcast.requests().unwrap(); - let subscribe = tokio::spawn(async move { remote.subscribe_track("events".into(), None).await }); - let request = kio::clock::timeout(TIMEOUT, dynamic.requested_track()) +async fn requested_datagrams_cross_lite07() { + let (broadcast, remote, session, _server) = datagram_connection("sensor", vec!["moq-lite-07-wip".into()]).await; + let requests = broadcast.requests().unwrap(); + let datagrams = requests.datagrams().unwrap(); + let consumer = remote.datagrams("events".into()).unwrap(); + let request = kio::clock::timeout(TIMEOUT, datagrams.requested()) .await - .expect("timed out waiting for the request") + .unwrap() .unwrap(); - let track = request.accept(Some(timed_info())).unwrap(); - let consumer = kio::clock::timeout(TIMEOUT, subscribe).await.unwrap().unwrap().unwrap(); - let datagram = resend_until_read(&track, &consumer).await; - assert_eq!(datagram.payload, b"reading"); - assert_eq!(session.state().version.as_deref(), Some("moq-lite-06")); + let producer = request.accept(None).unwrap(); + consumer.info().await.unwrap(); + producer.append(None, b"only".to_vec()).unwrap(); + let datagram = kio::clock::timeout(TIMEOUT, consumer.recv()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(datagram.payload, b"only"); + assert_eq!(session.state().version.as_deref(), Some("moq-lite-07-wip")); } /// A replacement session from the same publisher re-announces every route while the old one @@ -9628,3 +9267,51 @@ async fn video_subscribe_configuration_boundary() { } broadcast.close().unwrap(); } + +#[tokio::test] +async fn datagram_demand_is_independent_and_aggregates_priority() { + let broadcast = MoqBroadcastProducer::new().unwrap(); + let stream = broadcast.publish_track("events".into(), None).unwrap(); + let demand = stream.demand().unwrap(); + let producer = broadcast.create_datagrams("events".into(), None).unwrap(); + assert_eq!(producer.priority().unwrap(), None); + producer.append(None, b"before".to_vec()).unwrap(); + let first = broadcast.consume().unwrap().datagrams("events".into()).unwrap(); + let second = producer.consume().unwrap(); + first.set_priority(-5).unwrap(); + second.set_priority(10).unwrap(); + assert_eq!(producer.priority().unwrap(), Some(10)); + assert_eq!(demand.wanted(), None); + producer + .insert(MoqDatagram { + sequence: 7, + timestamp: None, + payload: b"seven".to_vec(), + }) + .unwrap(); + let received = first.recv().await.unwrap().unwrap(); + assert_eq!(received.sequence, 7); + assert_eq!(received.timestamp, None); + assert_eq!(received.payload, b"seven"); + assert_eq!(producer.append(None, b"eight".to_vec()).unwrap(), 8); + second.cancel(); + assert_eq!(producer.priority_changed(Some(10)).await.unwrap(), Some(-5)); + stream.finish().unwrap(); + assert_eq!(first.recv().await.unwrap().unwrap().payload, b"eight"); + producer.finish().unwrap(); + assert!(first.recv().await.unwrap().is_none()); +} + +#[tokio::test] +async fn datagram_cancel_releases_demand_and_wakes_reads() { + let broadcast = MoqBroadcastProducer::new().unwrap(); + let producer = broadcast.create_datagrams("events".into(), None).unwrap(); + let consumer = producer.consume().unwrap(); + let pending = { + let consumer = consumer.clone(); + spawn_parked(async move { consumer.recv().await }).await + }; + consumer.cancel(); + assert!(matches!(pending.await.unwrap(), Err(MoqError::Cancelled))); + assert_eq!(producer.priority_changed(Some(0)).await.unwrap(), None); +} diff --git a/swift/MIGRATE.md b/swift/MIGRATE.md index 86895a6576a..3fb69ce1008 100644 --- a/swift/MIGRATE.md +++ b/swift/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Separate datagram tracks + +Replace stream-track `appendDatagram` / `insertDatagram` / `recvDatagram` with `BroadcastProducer.createDatagrams(name:info:)` and `BroadcastConsumer.datagrams(name:)`. `DatagramProducer.append(_:timestamp:)` assigns a sequence; `insert(_:)` takes a `Datagram`. `DatagramConsumer.recv()` and `AsyncSequence` read its independent cursor. Use `priority()` / `priorityChanged(last:)` for demand, and `BroadcastRequests.datagrams()` / `DatagramRequests.requested()` for on-demand tracks. `DatagramInfo` has priority and optional timescale, without stream ranges or cache settings. + ### Viewer targets are bounded ([#7090](https://github.com/moq-dev/moq/pull/7090)) Viewer ceilings and PROBE target overrides are refused with the new `MoqError.OutOfRange` once they would sum above 2^53 - 1 bps, the most a PROBE target carries; nothing changes on a refusal. `Viewers.watch(maxBps:)` and `setTarget(targetBps:)` and `Viewer.update(maxBps:)` throw it, so call them with `try`. Handle the new variant wherever you match the error exhaustively. Regenerate bindings and rebuild the matching native library together. diff --git a/swift/README.md b/swift/README.md index 69583d35e42..03ac586b513 100644 --- a/swift/README.md +++ b/swift/README.md @@ -78,12 +78,13 @@ Every consumer conforms to `AsyncSequence`, so `for try await x in consumer` wor Incoming server `Request` values expose the query-free `path` before acceptance. It is consistent across transports and is empty for the root or missing path. The encoded `query` may contain credentials. -Raw tracks also expose best-effort datagrams: `TrackProducer.appendDatagram(_:timestamp:)` -returns the assigned sequence number (`insertDatagram(_:sequence:timestamp:)` takes the -caller's own), `TrackConsumer.recvDatagram()` receives one datagram, -and `TrackConsumer.datagrams` streams them in arrival order. Payloads are capped at 1200 bytes. -Datagrams require a datagram-capable transport and lite-05 or newer moq-lite; moq-transport, -pre-lite-05, WebSocket, and TCP paths do not deliver them, and there is no stream fallback. +Create a separate live track with `BroadcastProducer.createDatagrams(name:info:)` and +subscribe with `BroadcastConsumer.datagrams(name:)`. `DatagramProducer.append(_:timestamp:)` +assigns a sequence, `insert(_:)` preserves one, and `DatagramConsumer.recv()` or its +`AsyncSequence` reads in arrival order. Demand is aggregate subscriber `priority()` / +`priorityChanged(last:)`; `BroadcastRequests.datagrams()` handles on-demand tracks. +Keep payloads below the path MTU. Delivery needs a datagram-capable transport and lite-05 +or newer, with no stream fallback. A stream track of the same name is independent. JSON tracks live under the `Json` namespace, mirroring the `moq-json` crate, and carry your own `Codable` types with the framing handled for you. Each type wraps a track: a producer takes over a diff --git a/swift/Sources/Moq/Aliases.swift b/swift/Sources/Moq/Aliases.swift index ad36ebfff33..b153ee69a94 100644 --- a/swift/Sources/Moq/Aliases.swift +++ b/swift/Sources/Moq/Aliases.swift @@ -143,3 +143,6 @@ extension Subscription { /// `Subscription(...)` must name `delay`. public static var `default`: Subscription { moqSubscriptionDefaults() } } + +/// Publisher priority and optional timestamp scale fixed for a datagram track. +public typealias DatagramInfo = MoqFFI.MoqDatagramInfo diff --git a/swift/Sources/Moq/Datagram.swift b/swift/Sources/Moq/Datagram.swift new file mode 100644 index 00000000000..c400501c60d --- /dev/null +++ b/swift/Sources/Moq/Datagram.swift @@ -0,0 +1,136 @@ +import Foundation +import MoqFFI + +extension BroadcastProducer { + /// Create a live datagram track in its own namespace. + public func createDatagrams(name: String, info: DatagramInfo? = nil) throws -> DatagramProducer { + DatagramProducer(try ffi.createDatagrams(name: name, info: info)) + } +} + +extension BroadcastConsumer { + /// Subscribe to a live datagram track from now on, without a stream subscription. + public func datagrams(name: String) throws -> DatagramConsumer { + DatagramConsumer(try ffi.datagrams(name: name)) + } +} + +/// Writes live datagrams with an independent sequence counter and no cache. +public final class DatagramProducer: Sendable { + let ffi: MoqDatagramProducer + + init(_ ffi: MoqDatagramProducer) { self.ffi = ffi } + + /// The datagram track's name within its broadcast. + public func name() throws -> String { try ffi.name() } + + /// The track's fixed publisher properties. + public func info() throws -> DatagramInfo { try ffi.info() } + + /// Send a datagram and return its sequence; keep the payload below the path MTU. + public func append(_ payload: Data, timestamp: Timestamp? = nil) throws -> UInt64 { + try ffi.append(timestamp: timestamp, payload: payload) + } + + /// Send a datagram at its explicit sequence; appends continue past the highest one. + public func insert(_ datagram: Datagram) throws { try ffi.insert(datagram: datagram) } + + /// Create a local reader starting with the next datagram written. + public func consume() throws -> DatagramConsumer { DatagramConsumer(try ffi.consume()) } + + /// The highest subscriber priority, or nil while nobody consumes this track. + public func priority() throws -> Int8? { try ffi.priority() } + + /// Wait until aggregate subscriber priority differs from last. + public func priorityChanged(last: Int8?) async throws -> Int8? { + try await ffi.priorityChanged(last: last) + } + + /// Finish the track; existing consumers drain their unread datagrams. + public func finish() throws { try ffi.finish() } + + /// Abort the track with an application error, discarding unread datagrams. + public func abort(errorCode: UInt16) throws { try ffi.abort(errorCode: errorCode) } +} + +/// Reads live datagrams in arrival order from its own cursor. +public final class DatagramConsumer: AsyncSequence, Sendable { + public typealias Element = Datagram + public typealias AsyncIterator = AsyncThrowingStream.Iterator + let ffi: MoqDatagramConsumer + + init(_ ffi: MoqDatagramConsumer) { self.ffi = ffi } + + /// The datagram track's name within its broadcast. + public func name() throws -> String { try ffi.name() } + + /// Wait for the publisher to accept this track and return its properties. + public func info() async throws -> DatagramInfo { try await ffi.info() } + + /// Receive the next datagram, or nil after the track finishes. + public func recv() async throws -> Datagram? { try await ffi.recv() } + + /// This consumer's subscriber priority. + public func priority() throws -> Int8 { try ffi.priority() } + + /// Change this consumer's subscriber priority, higher first. + public func setPriority(_ priority: Int8) throws { try ffi.setPriority(priority: priority) } + + /// Cancel reads and release this consumer's demand. + public func cancel() { ffi.cancel() } + + /// Iterate datagrams, cancelling native reads when iteration ends. + public func makeAsyncIterator() -> AsyncIterator { + moqStream(cancel: { [ffi] in ffi.cancel() }) { [ffi] in + try await ffi.recv() + }.makeAsyncIterator() + } +} + +extension BroadcastRequests { + /// Create an on-demand handler for datagram tracks. + public func datagrams() throws -> DatagramRequests { DatagramRequests(try ffi.datagrams()) } +} + +/// Serves on-demand datagram tracks through their own request queue. +public final class DatagramRequests: AsyncSequence, Sendable { + public typealias Element = DatagramRequest + public typealias AsyncIterator = AsyncThrowingStream.Iterator + let ffi: MoqDatagramRequests + + init(_ ffi: MoqDatagramRequests) { self.ffi = ffi } + + /// Wait for the next datagram track requested by a consumer. + public func requested() async throws -> DatagramRequest { DatagramRequest(try await ffi.requested()) } + + /// Cancel the handler and reject requests it has not handed out. + public func cancel() { ffi.cancel() } + + /// Iterate datagram requests, cancelling native waits when iteration ends. + public func makeAsyncIterator() -> AsyncIterator { + moqStream(cancel: { [ffi] in ffi.cancel() }) { [ffi] in + DatagramRequest(try await ffi.requested()) + }.makeAsyncIterator() + } +} + +/// A requested datagram track awaiting acceptance or rejection. +public final class DatagramRequest: Sendable { + let ffi: MoqDatagramRequest + + init(_ ffi: MoqDatagramRequest) { self.ffi = ffi } + + /// The requested datagram track's name. + public func name() throws -> String { try ffi.name() } + + /// The highest priority among consumers waiting for this track. + public func priority() throws -> Int8? { try ffi.priority() } + + /// Accept the request with its fixed publisher properties. + public func accept(info: DatagramInfo? = nil) throws -> DatagramProducer { + DatagramProducer(try ffi.accept(info: info)) + } + + /// Reject this request with an application error code. + public func abort(errorCode: UInt16) throws { try ffi.abort(errorCode: errorCode) } +} diff --git a/swift/Sources/Moq/Track.swift b/swift/Sources/Moq/Track.swift index b6fdf7f0931..edcaa8def56 100644 --- a/swift/Sources/Moq/Track.swift +++ b/swift/Sources/Moq/Track.swift @@ -34,11 +34,6 @@ public final class TrackConsumer: AsyncSequence, Sendable { try await ffi.readFrame() } - /// The next best-effort datagram in arrival order. `nil` once the track ends. - public func recvDatagram() async throws -> Datagram? { - try await ffi.recvDatagram() - } - /// The publisher-side properties learned during subscription. public func info() -> TrackInfo { ffi.info() @@ -55,14 +50,6 @@ public final class TrackConsumer: AsyncSequence, Sendable { ffi.cancel() } - /// Datagrams in arrival order. Datagram delivery requires a datagram-capable - /// transport and wire version; there is no stream fallback. - public var datagrams: AsyncThrowingStream { - moqStream(cancel: { [ffi] in ffi.cancel() }) { [ffi] in - try await ffi.recvDatagram() - } - } - /// Groups in arrival order, including out-of-sequence deliveries. The default /// `AsyncSequence` iteration uses sequence order instead. public var groupsAsArrived: AsyncThrowingStream { @@ -181,21 +168,7 @@ public final class TrackProducer: Sendable { try ffi.writeFrame(frame: Frame(payload: payload, timestamp: timestamp)) } - /// Send a best-effort datagram and return its sequence number. - /// - /// `timestamp` is the presentation timestamp, or untimed when nil. Payloads are - /// capped at 1200 bytes. There is no stream fallback. - public func appendDatagram(_ payload: Data, timestamp: Timestamp? = nil) throws -> UInt64 { - try ffi.appendDatagram(frame: Frame(payload: payload, timestamp: timestamp)) - } - - /// Send a best-effort datagram at an explicit sequence number, for a caller that - /// allocates its own. `appendDatagram` continues after the largest one. - public func insertDatagram(_ payload: Data, sequence: UInt64, timestamp: Timestamp? = nil) throws { - try ffi.insertDatagram(sequence: sequence, frame: Frame(payload: payload, timestamp: timestamp)) - } - - /// The newest group written, at its newest frame, or `nil` before any. Datagrams never move it. + /// The newest group written, at its newest frame, or `nil` before any. public func largest() throws -> Position? { try ffi.largest() } diff --git a/swift/Tests/MoqTests/SmokeTests.swift b/swift/Tests/MoqTests/SmokeTests.swift index 0d9131a52a8..661a3cd6e1e 100644 --- a/swift/Tests/MoqTests/SmokeTests.swift +++ b/swift/Tests/MoqTests/SmokeTests.swift @@ -26,6 +26,30 @@ private func assertTimeOverflow( } final class SmokeTests: XCTestCase { + func testDatagramOnlyRequestsHaveIndependentPriorityDemand() async throws { + let broadcast = try BroadcastProducer() + let stream = try broadcast.publishTrack(name: "events") + let requests = try broadcast.requests().datagrams() + let consumer = try broadcast.consume().datagrams(name: "events") + try consumer.setPriority(12) + let request = try await requests.requested() + XCTAssertEqual(try request.name(), "events") + XCTAssertEqual(try request.priority(), 12) + let producer = try request.accept() + XCTAssertEqual(try producer.priority(), 12) + XCTAssertNil(try stream.demand().wanted) + try producer.insert(Datagram(sequence: 7, timestamp: nil, payload: Data("seven".utf8))) + let datagram = try await consumer.recv() + XCTAssertEqual(datagram?.sequence, 7) + XCTAssertEqual(datagram?.payload, Data("seven".utf8)) + consumer.cancel() + let priority = try await producer.priorityChanged(last: 12) + XCTAssertNil(priority) + try producer.finish() + requests.cancel() + try broadcast.close() + } + func testDefaultSubscriptionSkipsSupersededGroupsAtOnce() { XCTAssertEqual(Subscription.default.delay.min, 0) XCTAssertEqual(Subscription.default.delay.max, 0) diff --git a/swift/ffi/MIGRATE.md b/swift/ffi/MIGRATE.md index 51bdd9b006f..564bba5aea2 100644 --- a/swift/ffi/MIGRATE.md +++ b/swift/ffi/MIGRATE.md @@ -2,6 +2,10 @@ ## Unreleased +### Separate datagram tracks + +Generated bindings now expose separate `MoqDatagramProducer`, `MoqDatagramConsumer`, `MoqDatagramInfo`, `MoqDatagramRequest`, and `MoqDatagramRequests` types. Create or subscribe through the broadcast's datagram methods, write with `append` / `insert`, and read with `recv`; stream-track datagram methods are removed. Demand is aggregate subscriber priority, and the broadcast request handler has a separate `datagrams` queue. Regenerate and rebuild native bindings together with your wrapper. + ### Follow the core API migration guide These bindings are generated from moq-ffi. Apply every change in the From 6982f0f61f2314f5122e171d234b6e993fd4c24a Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 4 Nov 2026 02:34:49 -0800 Subject: [PATCH 3/9] docs(bindings): record legacy request blocker and regenerate Dart Co-Authored-By: GPT-6.1 Sol --- dart/moq_ffi/lib/src/moq.dart | 1829 +++++++++++++++++----- dart/moq_ffi/lib/src/uniffi_runtime.dart | 2 + go/wrapper/README.md | 4 + py/moq-rs/README.md | 4 + py/moq-rs/tests/test_local.py | 4 +- quest/m1/datagram-tracks/bindings.md | 37 +- swift/README.md | 4 + 7 files changed, 1486 insertions(+), 398 deletions(-) diff --git a/dart/moq_ffi/lib/src/moq.dart b/dart/moq_ffi/lib/src/moq.dart index 27fe6eac5d0..5991cebdddb 100644 --- a/dart/moq_ffi/lib/src/moq.dart +++ b/dart/moq_ffi/lib/src/moq.dart @@ -8,7 +8,9 @@ import "dart:ffi"; import "dart:io" show Platform, File, Directory; import "dart:isolate"; import "dart:typed_data"; + import "package:ffi/ffi.dart"; + import "uniffi_runtime.dart"; export "uniffi_runtime.dart"; @@ -977,6 +979,65 @@ class FfiConverterMoqSubscription { } } +class MoqDatagramInfo { + final int priority; + final int? timescale; + MoqDatagramInfo({this.priority = 0, this.timescale = null}); +} + +class FfiConverterMoqDatagramInfo { + static MoqDatagramInfo lift(RustBuffer buf) { + return FfiConverterMoqDatagramInfo.read(buf.asUint8List()).value; + } + + static LiftRetVal read(Uint8List buf) { + int new_offset = buf.offsetInBytes; + final priority_lifted = FfiConverterInt8.read( + Uint8List.view(buf.buffer, new_offset), + ); + final priority = priority_lifted.value; + new_offset += priority_lifted.bytesRead; + final timescale_lifted = FfiConverterOptionalUInt64.read( + Uint8List.view(buf.buffer, new_offset), + ); + final timescale = timescale_lifted.value; + new_offset += timescale_lifted.bytesRead; + return LiftRetVal( + MoqDatagramInfo(priority: priority, timescale: timescale), + new_offset - buf.offsetInBytes, + ); + } + + static RustBuffer lower(MoqDatagramInfo value) { + final total_length = + FfiConverterInt8.allocationSize(value.priority) + + FfiConverterOptionalUInt64.allocationSize(value.timescale) + + 0; + final buf = Uint8List(total_length); + write(value, buf); + return toRustBuffer(buf); + } + + static int write(MoqDatagramInfo value, Uint8List buf) { + int new_offset = buf.offsetInBytes; + new_offset += FfiConverterInt8.write( + value.priority, + Uint8List.view(buf.buffer, new_offset), + ); + new_offset += FfiConverterOptionalUInt64.write( + value.timescale, + Uint8List.view(buf.buffer, new_offset), + ); + return new_offset - buf.offsetInBytes; + } + + static int allocationSize(MoqDatagramInfo value) { + return FfiConverterInt8.allocationSize(value.priority) + + FfiConverterOptionalUInt64.allocationSize(value.timescale) + + 0; + } +} + class MoqProtocolException { final MoqErrorScope scope; final int code; @@ -10440,6 +10501,7 @@ abstract class MoqBroadcastConsumerInterface { required String name, required MoqSubscription? subscription, }); + MoqDatagramConsumer datagrams({required String name}); } final _MoqBroadcastConsumerFinalizer = Finalizer>((ptr) { @@ -10554,6 +10616,18 @@ class MoqBroadcastConsumer implements MoqBroadcastConsumerInterface { moqExceptionErrorHandler, ); } + + MoqDatagramConsumer datagrams({required String name}) { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqbroadcastconsumer_datagrams( + uniffiClonePointer(), + FfiConverterString.lower(name), + status, + ), + FfiConverterMoqDatagramConsumer.lift, + moqExceptionErrorHandler, + ); + } } class FfiConverterMoqBroadcastConsumer { @@ -10691,7 +10765,6 @@ abstract class MoqTrackConsumerInterface { MoqTrackInfo info(); UniffiRustFuture nextGroup(); UniffiRustFuture readFrame(); - UniffiRustFuture recvDatagram(); UniffiRustFuture recvGroup(); void update({required MoqSubscription subscription}); } @@ -10781,20 +10854,6 @@ class MoqTrackConsumer implements MoqTrackConsumerInterface { ); } - UniffiRustFuture recvDatagram() { - return uniffiRustCallAsync( - () => uniffi_moq_ffi_fn_method_moqtrackconsumer_recv_datagram( - uniffiClonePointer(), - ), - ffi_moq_ffi_rust_future_poll_rust_buffer, - ffi_moq_ffi_rust_future_complete_rust_buffer, - ffi_moq_ffi_rust_future_cancel_rust_buffer, - ffi_moq_ffi_rust_future_free_rust_buffer, - FfiConverterOptionalMoqDatagram.lift, - moqExceptionErrorHandler, - ); - } - UniffiRustFuture recvGroup() { return uniffiRustCallAsync( () => uniffi_moq_ffi_fn_method_moqtrackconsumer_recv_group( @@ -10846,31 +10905,34 @@ class FfiConverterMoqTrackConsumer { } } -abstract class MoqTrackDemandInterface { +abstract class MoqDatagramConsumerInterface { + void cancel(); + UniffiRustFuture info(); String name(); - int? wanted(); - UniffiRustFuture wantedChanged(); + int priority(); + UniffiRustFuture recv(); + void setPriority({required int priority}); } -final _MoqTrackDemandFinalizer = Finalizer>((ptr) { - rustCall((status) => uniffi_moq_ffi_fn_free_moqtrackdemand(ptr, status)); +final _MoqDatagramConsumerFinalizer = Finalizer>((ptr) { + rustCall((status) => uniffi_moq_ffi_fn_free_moqdatagramconsumer(ptr, status)); }); -class MoqTrackDemand implements MoqTrackDemandInterface { +class MoqDatagramConsumer implements MoqDatagramConsumerInterface { late final Pointer _ptr; bool _isDisposed = false; - MoqTrackDemand._(this._ptr) { - _MoqTrackDemandFinalizer.attach(this, _ptr, detach: this); + MoqDatagramConsumer._(this._ptr) { + _MoqDatagramConsumerFinalizer.attach(this, _ptr, detach: this); } - factory MoqTrackDemand.lift(Pointer ptr) { - return MoqTrackDemand._(ptr); + factory MoqDatagramConsumer.lift(Pointer ptr) { + return MoqDatagramConsumer._(ptr); } Pointer uniffiClonePointer() { if (_isDisposed) { throw StateError("Object has already been disposed"); } return rustCall( - (status) => uniffi_moq_ffi_fn_clone_moqtrackdemand(_ptr, status), + (status) => uniffi_moq_ffi_fn_clone_moqdatagramconsumer(_ptr, status), ); } @@ -10880,115 +10942,142 @@ class MoqTrackDemand implements MoqTrackDemandInterface { } final status = calloc(); _isDisposed = true; - _MoqTrackDemandFinalizer.detach(this); + _MoqDatagramConsumerFinalizer.detach(this); try { - uniffi_moq_ffi_fn_free_moqtrackdemand(_ptr, status); + uniffi_moq_ffi_fn_free_moqdatagramconsumer(_ptr, status); checkCallStatus(NullRustCallStatusErrorHandler(), status); } finally { calloc.free(status); } } + void cancel() { + return rustCall((status) { + uniffi_moq_ffi_fn_method_moqdatagramconsumer_cancel( + uniffiClonePointer(), + status, + ); + }, null); + } + + UniffiRustFuture info() { + return uniffiRustCallAsync( + () => uniffi_moq_ffi_fn_method_moqdatagramconsumer_info( + uniffiClonePointer(), + ), + ffi_moq_ffi_rust_future_poll_rust_buffer, + ffi_moq_ffi_rust_future_complete_rust_buffer, + ffi_moq_ffi_rust_future_cancel_rust_buffer, + ffi_moq_ffi_rust_future_free_rust_buffer, + FfiConverterMoqDatagramInfo.lift, + moqExceptionErrorHandler, + ); + } + String name() { return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqtrackdemand_name( + (status) => uniffi_moq_ffi_fn_method_moqdatagramconsumer_name( uniffiClonePointer(), status, ), FfiConverterString.lift, - null, + moqExceptionErrorHandler, ); } - int? wanted() { + int priority() { return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqtrackdemand_wanted( + (status) => uniffi_moq_ffi_fn_method_moqdatagramconsumer_priority( uniffiClonePointer(), status, ), - FfiConverterOptionalUInt64.lift, - null, + FfiConverterInt8.lift, + moqExceptionErrorHandler, ); } - UniffiRustFuture wantedChanged() { + UniffiRustFuture recv() { return uniffiRustCallAsync( - () => uniffi_moq_ffi_fn_method_moqtrackdemand_wanted_changed( + () => uniffi_moq_ffi_fn_method_moqdatagramconsumer_recv( uniffiClonePointer(), ), ffi_moq_ffi_rust_future_poll_rust_buffer, ffi_moq_ffi_rust_future_complete_rust_buffer, ffi_moq_ffi_rust_future_cancel_rust_buffer, ffi_moq_ffi_rust_future_free_rust_buffer, - FfiConverterOptionalUInt64.lift, + FfiConverterOptionalMoqDatagram.lift, moqExceptionErrorHandler, ); } + + void setPriority({required int priority}) { + return rustCall((status) { + uniffi_moq_ffi_fn_method_moqdatagramconsumer_set_priority( + uniffiClonePointer(), + FfiConverterInt8.lower(priority), + status, + ); + }, moqExceptionErrorHandler); + } } -class FfiConverterMoqTrackDemand { - static MoqTrackDemand lift(Pointer ptr) { - return MoqTrackDemand.lift(ptr); +class FfiConverterMoqDatagramConsumer { + static MoqDatagramConsumer lift(Pointer ptr) { + return MoqDatagramConsumer.lift(ptr); } - static Pointer lower(MoqTrackDemand value) { + static Pointer lower(MoqDatagramConsumer value) { return value.uniffiClonePointer(); } - static int allocationSize(MoqTrackDemand value) { + static int allocationSize(MoqDatagramConsumer value) { return 8; } - static LiftRetVal read(Uint8List buf) { + static LiftRetVal read(Uint8List buf) { final handle = buf.buffer.asByteData(buf.offsetInBytes).getInt64(0); final pointer = Pointer.fromAddress(handle); - return LiftRetVal(MoqTrackDemand.lift(pointer), 8); + return LiftRetVal(MoqDatagramConsumer.lift(pointer), 8); } - static int write(MoqTrackDemand value, Uint8List buf) { + static int write(MoqDatagramConsumer value, Uint8List buf) { final handle = lower(value); buf.buffer.asByteData(buf.offsetInBytes).setInt64(0, handle.address); return 8; } } -abstract class MoqJsonSnapshotConsumerInterface { - void cancel(); - UniffiRustFuture latest(); - UniffiRustFuture next(); +abstract class MoqDatagramProducerInterface { + void abort({required int errorCode}); + int append({required MoqTimestamp? timestamp, required Uint8List payload}); + MoqDatagramConsumer consume(); + void finish(); + MoqDatagramInfo info(); + void insert({required MoqDatagram datagram}); + String name(); + int? priority(); + UniffiRustFuture priorityChanged({required int? last}); } -final _MoqJsonSnapshotConsumerFinalizer = Finalizer>((ptr) { - rustCall( - (status) => uniffi_moq_ffi_fn_free_moqjsonsnapshotconsumer(ptr, status), - ); +final _MoqDatagramProducerFinalizer = Finalizer>((ptr) { + rustCall((status) => uniffi_moq_ffi_fn_free_moqdatagramproducer(ptr, status)); }); -class MoqJsonSnapshotConsumer implements MoqJsonSnapshotConsumerInterface { +class MoqDatagramProducer implements MoqDatagramProducerInterface { late final Pointer _ptr; bool _isDisposed = false; - MoqJsonSnapshotConsumer._(this._ptr) { - _MoqJsonSnapshotConsumerFinalizer.attach(this, _ptr, detach: this); - } - MoqJsonSnapshotConsumer({required MoqTrackConsumer track}) - : _ptr = rustCall( - (status) => uniffi_moq_ffi_fn_constructor_moqjsonsnapshotconsumer_new( - FfiConverterMoqTrackConsumer.lower(track), - status, - ), - moqExceptionErrorHandler, - ) { - _MoqJsonSnapshotConsumerFinalizer.attach(this, _ptr, detach: this); + MoqDatagramProducer._(this._ptr) { + _MoqDatagramProducerFinalizer.attach(this, _ptr, detach: this); } - factory MoqJsonSnapshotConsumer.lift(Pointer ptr) { - return MoqJsonSnapshotConsumer._(ptr); + factory MoqDatagramProducer.lift(Pointer ptr) { + return MoqDatagramProducer._(ptr); } Pointer uniffiClonePointer() { if (_isDisposed) { throw StateError("Object has already been disposed"); } return rustCall( - (status) => uniffi_moq_ffi_fn_clone_moqjsonsnapshotconsumer(_ptr, status), + (status) => uniffi_moq_ffi_fn_clone_moqdatagramproducer(_ptr, status), ); } @@ -10998,98 +11087,595 @@ class MoqJsonSnapshotConsumer implements MoqJsonSnapshotConsumerInterface { } final status = calloc(); _isDisposed = true; - _MoqJsonSnapshotConsumerFinalizer.detach(this); + _MoqDatagramProducerFinalizer.detach(this); try { - uniffi_moq_ffi_fn_free_moqjsonsnapshotconsumer(_ptr, status); + uniffi_moq_ffi_fn_free_moqdatagramproducer(_ptr, status); checkCallStatus(NullRustCallStatusErrorHandler(), status); } finally { calloc.free(status); } } - void cancel() { + void abort({required int errorCode}) { return rustCall((status) { - uniffi_moq_ffi_fn_method_moqjsonsnapshotconsumer_cancel( + uniffi_moq_ffi_fn_method_moqdatagramproducer_abort( uniffiClonePointer(), + FfiConverterUInt16.lower(errorCode), status, ); - }, null); + }, moqExceptionErrorHandler); } - UniffiRustFuture latest() { - return uniffiRustCallAsync( - () => uniffi_moq_ffi_fn_method_moqjsonsnapshotconsumer_latest( + int append({required MoqTimestamp? timestamp, required Uint8List payload}) { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqdatagramproducer_append( + uniffiClonePointer(), + FfiConverterOptionalMoqTimestamp.lower(timestamp), + FfiConverterUint8List.lower(payload), + status, + ), + FfiConverterUInt64.lift, + moqExceptionErrorHandler, + ); + } + + MoqDatagramConsumer consume() { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqdatagramproducer_consume( uniffiClonePointer(), + status, ), - ffi_moq_ffi_rust_future_poll_rust_buffer, - ffi_moq_ffi_rust_future_complete_rust_buffer, - ffi_moq_ffi_rust_future_cancel_rust_buffer, - ffi_moq_ffi_rust_future_free_rust_buffer, - FfiConverterOptionalMoqJsonValue.lift, + FfiConverterMoqDatagramConsumer.lift, moqExceptionErrorHandler, ); } - UniffiRustFuture next() { + void finish() { + return rustCall((status) { + uniffi_moq_ffi_fn_method_moqdatagramproducer_finish( + uniffiClonePointer(), + status, + ); + }, moqExceptionErrorHandler); + } + + MoqDatagramInfo info() { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqdatagramproducer_info( + uniffiClonePointer(), + status, + ), + FfiConverterMoqDatagramInfo.lift, + moqExceptionErrorHandler, + ); + } + + void insert({required MoqDatagram datagram}) { + return rustCall((status) { + uniffi_moq_ffi_fn_method_moqdatagramproducer_insert( + uniffiClonePointer(), + FfiConverterMoqDatagram.lower(datagram), + status, + ); + }, moqExceptionErrorHandler); + } + + String name() { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqdatagramproducer_name( + uniffiClonePointer(), + status, + ), + FfiConverterString.lift, + moqExceptionErrorHandler, + ); + } + + int? priority() { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqdatagramproducer_priority( + uniffiClonePointer(), + status, + ), + FfiConverterOptionalInt8.lift, + moqExceptionErrorHandler, + ); + } + + UniffiRustFuture priorityChanged({required int? last}) { return uniffiRustCallAsync( - () => uniffi_moq_ffi_fn_method_moqjsonsnapshotconsumer_next( + () => uniffi_moq_ffi_fn_method_moqdatagramproducer_priority_changed( uniffiClonePointer(), + FfiConverterOptionalInt8.lower(last), ), ffi_moq_ffi_rust_future_poll_rust_buffer, ffi_moq_ffi_rust_future_complete_rust_buffer, ffi_moq_ffi_rust_future_cancel_rust_buffer, ffi_moq_ffi_rust_future_free_rust_buffer, - FfiConverterOptionalMoqJsonValue.lift, + FfiConverterOptionalInt8.lift, moqExceptionErrorHandler, ); } } -class FfiConverterMoqJsonSnapshotConsumer { - static MoqJsonSnapshotConsumer lift(Pointer ptr) { - return MoqJsonSnapshotConsumer.lift(ptr); +class FfiConverterMoqDatagramProducer { + static MoqDatagramProducer lift(Pointer ptr) { + return MoqDatagramProducer.lift(ptr); } - static Pointer lower(MoqJsonSnapshotConsumer value) { + static Pointer lower(MoqDatagramProducer value) { return value.uniffiClonePointer(); } - static int allocationSize(MoqJsonSnapshotConsumer value) { + static int allocationSize(MoqDatagramProducer value) { return 8; } - static LiftRetVal read(Uint8List buf) { + static LiftRetVal read(Uint8List buf) { final handle = buf.buffer.asByteData(buf.offsetInBytes).getInt64(0); final pointer = Pointer.fromAddress(handle); - return LiftRetVal(MoqJsonSnapshotConsumer.lift(pointer), 8); + return LiftRetVal(MoqDatagramProducer.lift(pointer), 8); } - static int write(MoqJsonSnapshotConsumer value, Uint8List buf) { + static int write(MoqDatagramProducer value, Uint8List buf) { final handle = lower(value); buf.buffer.asByteData(buf.offsetInBytes).setInt64(0, handle.address); return 8; } } -abstract class MoqJsonSnapshotProducerInterface { - MoqTrackDemand demand(); - void finish(); - void update({required String value, required MoqTimestamp timestamp}); +abstract class MoqDatagramRequestInterface { + void abort({required int errorCode}); + MoqDatagramProducer accept({required MoqDatagramInfo? info}); + String name(); + int? priority(); } -final _MoqJsonSnapshotProducerFinalizer = Finalizer>((ptr) { - rustCall( - (status) => uniffi_moq_ffi_fn_free_moqjsonsnapshotproducer(ptr, status), - ); +final _MoqDatagramRequestFinalizer = Finalizer>((ptr) { + rustCall((status) => uniffi_moq_ffi_fn_free_moqdatagramrequest(ptr, status)); }); -class MoqJsonSnapshotProducer implements MoqJsonSnapshotProducerInterface { +class MoqDatagramRequest implements MoqDatagramRequestInterface { late final Pointer _ptr; bool _isDisposed = false; - MoqJsonSnapshotProducer._(this._ptr) { - _MoqJsonSnapshotProducerFinalizer.attach(this, _ptr, detach: this); + MoqDatagramRequest._(this._ptr) { + _MoqDatagramRequestFinalizer.attach(this, _ptr, detach: this); } - MoqJsonSnapshotProducer({ + factory MoqDatagramRequest.lift(Pointer ptr) { + return MoqDatagramRequest._(ptr); + } + Pointer uniffiClonePointer() { + if (_isDisposed) { + throw StateError("Object has already been disposed"); + } + return rustCall( + (status) => uniffi_moq_ffi_fn_clone_moqdatagramrequest(_ptr, status), + ); + } + + void dispose() { + if (_isDisposed) { + return; + } + final status = calloc(); + _isDisposed = true; + _MoqDatagramRequestFinalizer.detach(this); + try { + uniffi_moq_ffi_fn_free_moqdatagramrequest(_ptr, status); + checkCallStatus(NullRustCallStatusErrorHandler(), status); + } finally { + calloc.free(status); + } + } + + void abort({required int errorCode}) { + return rustCall((status) { + uniffi_moq_ffi_fn_method_moqdatagramrequest_abort( + uniffiClonePointer(), + FfiConverterUInt16.lower(errorCode), + status, + ); + }, moqExceptionErrorHandler); + } + + MoqDatagramProducer accept({required MoqDatagramInfo? info}) { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqdatagramrequest_accept( + uniffiClonePointer(), + FfiConverterOptionalMoqDatagramInfo.lower(info), + status, + ), + FfiConverterMoqDatagramProducer.lift, + moqExceptionErrorHandler, + ); + } + + String name() { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqdatagramrequest_name( + uniffiClonePointer(), + status, + ), + FfiConverterString.lift, + moqExceptionErrorHandler, + ); + } + + int? priority() { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqdatagramrequest_priority( + uniffiClonePointer(), + status, + ), + FfiConverterOptionalInt8.lift, + moqExceptionErrorHandler, + ); + } +} + +class FfiConverterMoqDatagramRequest { + static MoqDatagramRequest lift(Pointer ptr) { + return MoqDatagramRequest.lift(ptr); + } + + static Pointer lower(MoqDatagramRequest value) { + return value.uniffiClonePointer(); + } + + static int allocationSize(MoqDatagramRequest value) { + return 8; + } + + static LiftRetVal read(Uint8List buf) { + final handle = buf.buffer.asByteData(buf.offsetInBytes).getInt64(0); + final pointer = Pointer.fromAddress(handle); + return LiftRetVal(MoqDatagramRequest.lift(pointer), 8); + } + + static int write(MoqDatagramRequest value, Uint8List buf) { + final handle = lower(value); + buf.buffer.asByteData(buf.offsetInBytes).setInt64(0, handle.address); + return 8; + } +} + +abstract class MoqDatagramRequestsInterface { + void cancel(); + UniffiRustFuture requested(); +} + +final _MoqDatagramRequestsFinalizer = Finalizer>((ptr) { + rustCall((status) => uniffi_moq_ffi_fn_free_moqdatagramrequests(ptr, status)); +}); + +class MoqDatagramRequests implements MoqDatagramRequestsInterface { + late final Pointer _ptr; + bool _isDisposed = false; + MoqDatagramRequests._(this._ptr) { + _MoqDatagramRequestsFinalizer.attach(this, _ptr, detach: this); + } + factory MoqDatagramRequests.lift(Pointer ptr) { + return MoqDatagramRequests._(ptr); + } + Pointer uniffiClonePointer() { + if (_isDisposed) { + throw StateError("Object has already been disposed"); + } + return rustCall( + (status) => uniffi_moq_ffi_fn_clone_moqdatagramrequests(_ptr, status), + ); + } + + void dispose() { + if (_isDisposed) { + return; + } + final status = calloc(); + _isDisposed = true; + _MoqDatagramRequestsFinalizer.detach(this); + try { + uniffi_moq_ffi_fn_free_moqdatagramrequests(_ptr, status); + checkCallStatus(NullRustCallStatusErrorHandler(), status); + } finally { + calloc.free(status); + } + } + + void cancel() { + return rustCall((status) { + uniffi_moq_ffi_fn_method_moqdatagramrequests_cancel( + uniffiClonePointer(), + status, + ); + }, null); + } + + UniffiRustFuture requested() { + return uniffiRustCallAsync( + () => uniffi_moq_ffi_fn_method_moqdatagramrequests_requested( + uniffiClonePointer(), + ), + ffi_moq_ffi_rust_future_poll_u64, + ffi_moq_ffi_rust_future_complete_u64, + ffi_moq_ffi_rust_future_cancel_u64, + ffi_moq_ffi_rust_future_free_u64, + (ptr) => + FfiConverterMoqDatagramRequest.lift(Pointer.fromAddress(ptr)), + moqExceptionErrorHandler, + ); + } +} + +class FfiConverterMoqDatagramRequests { + static MoqDatagramRequests lift(Pointer ptr) { + return MoqDatagramRequests.lift(ptr); + } + + static Pointer lower(MoqDatagramRequests value) { + return value.uniffiClonePointer(); + } + + static int allocationSize(MoqDatagramRequests value) { + return 8; + } + + static LiftRetVal read(Uint8List buf) { + final handle = buf.buffer.asByteData(buf.offsetInBytes).getInt64(0); + final pointer = Pointer.fromAddress(handle); + return LiftRetVal(MoqDatagramRequests.lift(pointer), 8); + } + + static int write(MoqDatagramRequests value, Uint8List buf) { + final handle = lower(value); + buf.buffer.asByteData(buf.offsetInBytes).setInt64(0, handle.address); + return 8; + } +} + +abstract class MoqTrackDemandInterface { + String name(); + int? wanted(); + UniffiRustFuture wantedChanged(); +} + +final _MoqTrackDemandFinalizer = Finalizer>((ptr) { + rustCall((status) => uniffi_moq_ffi_fn_free_moqtrackdemand(ptr, status)); +}); + +class MoqTrackDemand implements MoqTrackDemandInterface { + late final Pointer _ptr; + bool _isDisposed = false; + MoqTrackDemand._(this._ptr) { + _MoqTrackDemandFinalizer.attach(this, _ptr, detach: this); + } + factory MoqTrackDemand.lift(Pointer ptr) { + return MoqTrackDemand._(ptr); + } + Pointer uniffiClonePointer() { + if (_isDisposed) { + throw StateError("Object has already been disposed"); + } + return rustCall( + (status) => uniffi_moq_ffi_fn_clone_moqtrackdemand(_ptr, status), + ); + } + + void dispose() { + if (_isDisposed) { + return; + } + final status = calloc(); + _isDisposed = true; + _MoqTrackDemandFinalizer.detach(this); + try { + uniffi_moq_ffi_fn_free_moqtrackdemand(_ptr, status); + checkCallStatus(NullRustCallStatusErrorHandler(), status); + } finally { + calloc.free(status); + } + } + + String name() { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqtrackdemand_name( + uniffiClonePointer(), + status, + ), + FfiConverterString.lift, + null, + ); + } + + int? wanted() { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqtrackdemand_wanted( + uniffiClonePointer(), + status, + ), + FfiConverterOptionalUInt64.lift, + null, + ); + } + + UniffiRustFuture wantedChanged() { + return uniffiRustCallAsync( + () => uniffi_moq_ffi_fn_method_moqtrackdemand_wanted_changed( + uniffiClonePointer(), + ), + ffi_moq_ffi_rust_future_poll_rust_buffer, + ffi_moq_ffi_rust_future_complete_rust_buffer, + ffi_moq_ffi_rust_future_cancel_rust_buffer, + ffi_moq_ffi_rust_future_free_rust_buffer, + FfiConverterOptionalUInt64.lift, + moqExceptionErrorHandler, + ); + } +} + +class FfiConverterMoqTrackDemand { + static MoqTrackDemand lift(Pointer ptr) { + return MoqTrackDemand.lift(ptr); + } + + static Pointer lower(MoqTrackDemand value) { + return value.uniffiClonePointer(); + } + + static int allocationSize(MoqTrackDemand value) { + return 8; + } + + static LiftRetVal read(Uint8List buf) { + final handle = buf.buffer.asByteData(buf.offsetInBytes).getInt64(0); + final pointer = Pointer.fromAddress(handle); + return LiftRetVal(MoqTrackDemand.lift(pointer), 8); + } + + static int write(MoqTrackDemand value, Uint8List buf) { + final handle = lower(value); + buf.buffer.asByteData(buf.offsetInBytes).setInt64(0, handle.address); + return 8; + } +} + +abstract class MoqJsonSnapshotConsumerInterface { + void cancel(); + UniffiRustFuture latest(); + UniffiRustFuture next(); +} + +final _MoqJsonSnapshotConsumerFinalizer = Finalizer>((ptr) { + rustCall( + (status) => uniffi_moq_ffi_fn_free_moqjsonsnapshotconsumer(ptr, status), + ); +}); + +class MoqJsonSnapshotConsumer implements MoqJsonSnapshotConsumerInterface { + late final Pointer _ptr; + bool _isDisposed = false; + MoqJsonSnapshotConsumer._(this._ptr) { + _MoqJsonSnapshotConsumerFinalizer.attach(this, _ptr, detach: this); + } + MoqJsonSnapshotConsumer({required MoqTrackConsumer track}) + : _ptr = rustCall( + (status) => uniffi_moq_ffi_fn_constructor_moqjsonsnapshotconsumer_new( + FfiConverterMoqTrackConsumer.lower(track), + status, + ), + moqExceptionErrorHandler, + ) { + _MoqJsonSnapshotConsumerFinalizer.attach(this, _ptr, detach: this); + } + factory MoqJsonSnapshotConsumer.lift(Pointer ptr) { + return MoqJsonSnapshotConsumer._(ptr); + } + Pointer uniffiClonePointer() { + if (_isDisposed) { + throw StateError("Object has already been disposed"); + } + return rustCall( + (status) => uniffi_moq_ffi_fn_clone_moqjsonsnapshotconsumer(_ptr, status), + ); + } + + void dispose() { + if (_isDisposed) { + return; + } + final status = calloc(); + _isDisposed = true; + _MoqJsonSnapshotConsumerFinalizer.detach(this); + try { + uniffi_moq_ffi_fn_free_moqjsonsnapshotconsumer(_ptr, status); + checkCallStatus(NullRustCallStatusErrorHandler(), status); + } finally { + calloc.free(status); + } + } + + void cancel() { + return rustCall((status) { + uniffi_moq_ffi_fn_method_moqjsonsnapshotconsumer_cancel( + uniffiClonePointer(), + status, + ); + }, null); + } + + UniffiRustFuture latest() { + return uniffiRustCallAsync( + () => uniffi_moq_ffi_fn_method_moqjsonsnapshotconsumer_latest( + uniffiClonePointer(), + ), + ffi_moq_ffi_rust_future_poll_rust_buffer, + ffi_moq_ffi_rust_future_complete_rust_buffer, + ffi_moq_ffi_rust_future_cancel_rust_buffer, + ffi_moq_ffi_rust_future_free_rust_buffer, + FfiConverterOptionalMoqJsonValue.lift, + moqExceptionErrorHandler, + ); + } + + UniffiRustFuture next() { + return uniffiRustCallAsync( + () => uniffi_moq_ffi_fn_method_moqjsonsnapshotconsumer_next( + uniffiClonePointer(), + ), + ffi_moq_ffi_rust_future_poll_rust_buffer, + ffi_moq_ffi_rust_future_complete_rust_buffer, + ffi_moq_ffi_rust_future_cancel_rust_buffer, + ffi_moq_ffi_rust_future_free_rust_buffer, + FfiConverterOptionalMoqJsonValue.lift, + moqExceptionErrorHandler, + ); + } +} + +class FfiConverterMoqJsonSnapshotConsumer { + static MoqJsonSnapshotConsumer lift(Pointer ptr) { + return MoqJsonSnapshotConsumer.lift(ptr); + } + + static Pointer lower(MoqJsonSnapshotConsumer value) { + return value.uniffiClonePointer(); + } + + static int allocationSize(MoqJsonSnapshotConsumer value) { + return 8; + } + + static LiftRetVal read(Uint8List buf) { + final handle = buf.buffer.asByteData(buf.offsetInBytes).getInt64(0); + final pointer = Pointer.fromAddress(handle); + return LiftRetVal(MoqJsonSnapshotConsumer.lift(pointer), 8); + } + + static int write(MoqJsonSnapshotConsumer value, Uint8List buf) { + final handle = lower(value); + buf.buffer.asByteData(buf.offsetInBytes).setInt64(0, handle.address); + return 8; + } +} + +abstract class MoqJsonSnapshotProducerInterface { + MoqTrackDemand demand(); + void finish(); + void update({required String value, required MoqTimestamp timestamp}); +} + +final _MoqJsonSnapshotProducerFinalizer = Finalizer>((ptr) { + rustCall( + (status) => uniffi_moq_ffi_fn_free_moqjsonsnapshotproducer(ptr, status), + ); +}); + +class MoqJsonSnapshotProducer implements MoqJsonSnapshotProducerInterface { + late final Pointer _ptr; + bool _isDisposed = false; + MoqJsonSnapshotProducer._(this._ptr) { + _MoqJsonSnapshotProducerFinalizer.attach(this, _ptr, detach: this); + } + MoqJsonSnapshotProducer({ required MoqBroadcastProducer broadcast, required MoqTrackProducer track, required MoqJsonSnapshotConfig config, @@ -13472,6 +14058,10 @@ class FfiConverterMoqPublication { } abstract class MoqBroadcastProducerInterface { + MoqDatagramProducer createDatagrams({ + required String name, + required MoqDatagramInfo? info, + }); void close(); MoqBroadcastConsumer consume(); MoqTrackProducer publishTrack({ @@ -13528,6 +14118,23 @@ class MoqBroadcastProducer implements MoqBroadcastProducerInterface { } } + MoqDatagramProducer createDatagrams({ + required String name, + required MoqDatagramInfo? info, + }) { + return rustCallWithLifter( + (status) => + uniffi_moq_ffi_fn_method_moqbroadcastproducer_create_datagrams( + uniffiClonePointer(), + FfiConverterString.lower(name), + FfiConverterOptionalMoqDatagramInfo.lower(info), + status, + ), + FfiConverterMoqDatagramProducer.lift, + moqExceptionErrorHandler, + ); + } + void close() { return rustCall((status) { uniffi_moq_ffi_fn_method_moqbroadcastproducer_close( @@ -13603,6 +14210,7 @@ class FfiConverterMoqBroadcastProducer { } abstract class MoqBroadcastRequestsInterface { + MoqDatagramRequests datagrams(); void cancel(); UniffiRustFuture requestedTrack(); } @@ -13646,6 +14254,17 @@ class MoqBroadcastRequests implements MoqBroadcastRequestsInterface { } } + MoqDatagramRequests datagrams() { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqbroadcastrequests_datagrams( + uniffiClonePointer(), + status, + ), + FfiConverterMoqDatagramRequests.lift, + moqExceptionErrorHandler, + ); + } + void cancel() { return rustCall((status) { uniffi_moq_ffi_fn_method_moqbroadcastrequests_cancel( @@ -14034,14 +14653,12 @@ class FfiConverterMoqGroupProducer { abstract class MoqTrackProducerInterface { void abort({required int errorCode}); - int appendDatagram({required MoqFrame frame}); MoqGroupProducer appendGroup(); MoqTrackConsumer consume({required MoqSubscription? subscription}); MoqGroupProducer createGroup({required int sequence}); MoqTrackDemand demand(); void finish(); void finishAt({required int finalSequence}); - void insertDatagram({required int sequence, required MoqFrame frame}); MoqPosition? largest(); MoqTrackRequests requests(); void writeFrame({required MoqFrame frame}); @@ -14094,18 +14711,6 @@ class MoqTrackProducer implements MoqTrackProducerInterface { }, moqExceptionErrorHandler); } - int appendDatagram({required MoqFrame frame}) { - return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqtrackproducer_append_datagram( - uniffiClonePointer(), - FfiConverterMoqFrame.lower(frame), - status, - ), - FfiConverterUInt64.lift, - moqExceptionErrorHandler, - ); - } - MoqGroupProducer appendGroup() { return rustCallWithLifter( (status) => uniffi_moq_ffi_fn_method_moqtrackproducer_append_group( @@ -14171,17 +14776,6 @@ class MoqTrackProducer implements MoqTrackProducerInterface { }, moqExceptionErrorHandler); } - void insertDatagram({required int sequence, required MoqFrame frame}) { - return rustCall((status) { - uniffi_moq_ffi_fn_method_moqtrackproducer_insert_datagram( - uniffiClonePointer(), - FfiConverterUInt64.lower(sequence), - FfiConverterMoqFrame.lower(frame), - status, - ); - }, moqExceptionErrorHandler); - } - MoqPosition? largest() { return rustCallWithLifter( (status) => uniffi_moq_ffi_fn_method_moqtrackproducer_largest( @@ -16138,6 +16732,51 @@ class FfiConverterOptionalDuration { } } +class FfiConverterOptionalInt8 { + static int? lift(RustBuffer buf) { + return FfiConverterOptionalInt8.read(buf.asUint8List()).value; + } + + static LiftRetVal read(Uint8List buf) { + if (ByteData.view(buf.buffer, buf.offsetInBytes).getInt8(0) == 0) { + return LiftRetVal(null, 1); + } + final result = FfiConverterInt8.read( + Uint8List.view(buf.buffer, buf.offsetInBytes + 1), + ); + return LiftRetVal(result.value, result.bytesRead + 1); + } + + static int allocationSize([int? value]) { + if (value == null) { + return 1; + } + return FfiConverterInt8.allocationSize(value) + 1; + } + + static RustBuffer lower(int? value) { + if (value == null) { + return toRustBuffer(Uint8List.fromList([0])); + } + final buf = Uint8List(FfiConverterOptionalInt8.allocationSize(value)); + FfiConverterOptionalInt8.write(value, buf); + return toRustBuffer(buf); + } + + static int write(int? value, Uint8List buf) { + if (value == null) { + buf[0] = 0; + return 1; + } + buf[0] = 1; + return FfiConverterInt8.write( + value, + Uint8List.view(buf.buffer, buf.offsetInBytes + 1), + ) + + 1; + } +} + class FfiConverterOptionalMoqAllocator { static MoqAllocator? lift(RustBuffer buf) { return FfiConverterOptionalMoqAllocator.read(buf.asUint8List()).value; @@ -16448,24 +17087,71 @@ class FfiConverterOptionalMoqCongestionControl { return FfiConverterMoqCongestionControl.allocationSize(value) + 1; } - static RustBuffer lower(MoqCongestionControl? value) { + static RustBuffer lower(MoqCongestionControl? value) { + if (value == null) { + return toRustBuffer(Uint8List.fromList([0])); + } + final buf = Uint8List( + FfiConverterOptionalMoqCongestionControl.allocationSize(value), + ); + FfiConverterOptionalMoqCongestionControl.write(value, buf); + return toRustBuffer(buf); + } + + static int write(MoqCongestionControl? value, Uint8List buf) { + if (value == null) { + buf[0] = 0; + return 1; + } + buf[0] = 1; + return FfiConverterMoqCongestionControl.write( + value, + Uint8List.view(buf.buffer, buf.offsetInBytes + 1), + ) + + 1; + } +} + +class FfiConverterOptionalMoqDatagram { + static MoqDatagram? lift(RustBuffer buf) { + return FfiConverterOptionalMoqDatagram.read(buf.asUint8List()).value; + } + + static LiftRetVal read(Uint8List buf) { + if (ByteData.view(buf.buffer, buf.offsetInBytes).getInt8(0) == 0) { + return LiftRetVal(null, 1); + } + final result = FfiConverterMoqDatagram.read( + Uint8List.view(buf.buffer, buf.offsetInBytes + 1), + ); + return LiftRetVal(result.value, result.bytesRead + 1); + } + + static int allocationSize([MoqDatagram? value]) { + if (value == null) { + return 1; + } + return FfiConverterMoqDatagram.allocationSize(value) + 1; + } + + static RustBuffer lower(MoqDatagram? value) { if (value == null) { return toRustBuffer(Uint8List.fromList([0])); } final buf = Uint8List( - FfiConverterOptionalMoqCongestionControl.allocationSize(value), + FfiConverterOptionalMoqDatagram.allocationSize(value), ); - FfiConverterOptionalMoqCongestionControl.write(value, buf); + FfiConverterOptionalMoqDatagram.write(value, buf); return toRustBuffer(buf); } - static int write(MoqCongestionControl? value, Uint8List buf) { + static int write(MoqDatagram? value, Uint8List buf) { if (value == null) { buf[0] = 0; return 1; } buf[0] = 1; - return FfiConverterMoqCongestionControl.write( + return FfiConverterMoqDatagram.write( value, Uint8List.view(buf.buffer, buf.offsetInBytes + 1), ) + @@ -16473,46 +17159,46 @@ class FfiConverterOptionalMoqCongestionControl { } } -class FfiConverterOptionalMoqDatagram { - static MoqDatagram? lift(RustBuffer buf) { - return FfiConverterOptionalMoqDatagram.read(buf.asUint8List()).value; +class FfiConverterOptionalMoqDatagramInfo { + static MoqDatagramInfo? lift(RustBuffer buf) { + return FfiConverterOptionalMoqDatagramInfo.read(buf.asUint8List()).value; } - static LiftRetVal read(Uint8List buf) { + static LiftRetVal read(Uint8List buf) { if (ByteData.view(buf.buffer, buf.offsetInBytes).getInt8(0) == 0) { return LiftRetVal(null, 1); } - final result = FfiConverterMoqDatagram.read( + final result = FfiConverterMoqDatagramInfo.read( Uint8List.view(buf.buffer, buf.offsetInBytes + 1), ); - return LiftRetVal(result.value, result.bytesRead + 1); + return LiftRetVal(result.value, result.bytesRead + 1); } - static int allocationSize([MoqDatagram? value]) { + static int allocationSize([MoqDatagramInfo? value]) { if (value == null) { return 1; } - return FfiConverterMoqDatagram.allocationSize(value) + 1; + return FfiConverterMoqDatagramInfo.allocationSize(value) + 1; } - static RustBuffer lower(MoqDatagram? value) { + static RustBuffer lower(MoqDatagramInfo? value) { if (value == null) { return toRustBuffer(Uint8List.fromList([0])); } final buf = Uint8List( - FfiConverterOptionalMoqDatagram.allocationSize(value), + FfiConverterOptionalMoqDatagramInfo.allocationSize(value), ); - FfiConverterOptionalMoqDatagram.write(value, buf); + FfiConverterOptionalMoqDatagramInfo.write(value, buf); return toRustBuffer(buf); } - static int write(MoqDatagram? value, Uint8List buf) { + static int write(MoqDatagramInfo? value, Uint8List buf) { if (value == null) { buf[0] = 0; return 1; } buf[0] = 1; - return FfiConverterMoqDatagram.write( + return FfiConverterMoqDatagramInfo.write( value, Uint8List.view(buf.buffer, buf.offsetInBytes + 1), ) + @@ -18566,7 +19252,245 @@ external Pointer uniffi_moq_ffi_fn_constructor_moqaudioconsumer_subscribe( @Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_method_moqaudioconsumer_cancel( +external void uniffi_moq_ffi_fn_method_moqaudioconsumer_cancel( + Pointer ptr, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external RustBuffer uniffi_moq_ffi_fn_method_moqaudioconsumer_delay( + Pointer ptr, + Pointer uniffiStatus, +); + +@Native Function(Pointer)>(assetId: _uniffiAssetId) +external Pointer uniffi_moq_ffi_fn_method_moqaudioconsumer_next( + Pointer ptr, +); + +@Native Function(Pointer, Pointer)>( + assetId: _uniffiAssetId, +) +external Pointer uniffi_moq_ffi_fn_clone_moqaudioencoder( + Pointer handle, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_free_moqaudioencoder( + Pointer handle, + Pointer uniffiStatus, +); + +@Native Function(RustBuffer, Pointer)>( + assetId: _uniffiAssetId, +) +external Pointer uniffi_moq_ffi_fn_constructor_moqaudioencoder_new( + RustBuffer output, + Pointer uniffiStatus, +); + +@Native< + RustBuffer Function(Pointer, RustBuffer, Pointer) +>(assetId: _uniffiAssetId) +external RustBuffer uniffi_moq_ffi_fn_method_moqaudioencoder_encode( + Pointer ptr, + RustBuffer pcm, + Pointer uniffiStatus, +); + +@Native< + RustBuffer Function(Pointer, RustBuffer, Pointer) +>(assetId: _uniffiAssetId) +external RustBuffer uniffi_moq_ffi_fn_method_moqaudioencoder_finish( + Pointer ptr, + RustBuffer pcm, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external int uniffi_moq_ffi_fn_method_moqaudioencoder_frame_size( + Pointer ptr, + Pointer uniffiStatus, +); + +@Native, Uint64, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_method_moqaudioencoder_set_bitrate( + Pointer ptr, + int bitrate, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external RustBuffer uniffi_moq_ffi_fn_method_moqaudioencoder_track_init( + Pointer ptr, + Pointer uniffiStatus, +); + +@Native Function(Pointer, Pointer)>( + assetId: _uniffiAssetId, +) +external Pointer uniffi_moq_ffi_fn_clone_moqaudioproducer( + Pointer handle, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_free_moqaudioproducer( + Pointer handle, + Pointer uniffiStatus, +); + +@Native< + Pointer Function(Pointer, RustBuffer, Pointer) +>(assetId: _uniffiAssetId) +external Pointer uniffi_moq_ffi_fn_constructor_moqaudioproducer_new( + Pointer catalog, + RustBuffer options, + Pointer uniffiStatus, +); + +@Native Function(Pointer, Pointer)>( + assetId: _uniffiAssetId, +) +external Pointer uniffi_moq_ffi_fn_method_moqaudioproducer_demand( + Pointer ptr, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_method_moqaudioproducer_finish( + Pointer ptr, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_method_moqaudioproducer_reanchor( + Pointer ptr, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external RustBuffer uniffi_moq_ffi_fn_method_moqaudioproducer_reservation( + Pointer ptr, + Pointer uniffiStatus, +); + +@Native, RustBuffer, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_method_moqaudioproducer_write( + Pointer ptr, + RustBuffer frame, + Pointer uniffiStatus, +); + +@Native Function(Pointer, Pointer)>( + assetId: _uniffiAssetId, +) +external Pointer uniffi_moq_ffi_fn_clone_moqgrantconsumer( + Pointer handle, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_free_moqgrantconsumer( + Pointer handle, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_method_moqgrantconsumer_cancel( + Pointer ptr, + Pointer uniffiStatus, +); + +@Native Function(Pointer)>(assetId: _uniffiAssetId) +external Pointer uniffi_moq_ffi_fn_method_moqgrantconsumer_changed( + Pointer ptr, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external RustBuffer uniffi_moq_ffi_fn_method_moqgrantconsumer_grant( + Pointer ptr, + Pointer uniffiStatus, +); + +@Native Function(Pointer, Pointer)>( + assetId: _uniffiAssetId, +) +external Pointer uniffi_moq_ffi_fn_clone_moqallocator( + Pointer handle, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_free_moqallocator( + Pointer handle, + Pointer uniffiStatus, +); + +@Native< + Pointer Function( + Pointer, + Pointer, + Uint64, + Pointer, + ) +>(assetId: _uniffiAssetId) +external Pointer uniffi_moq_ffi_fn_method_moqallocator_reserve( + Pointer ptr, + Pointer demand, + int max_bps, + Pointer uniffiStatus, +); + +@Native Function(Pointer, Pointer)>( + assetId: _uniffiAssetId, +) +external Pointer uniffi_moq_ffi_fn_clone_moqbandwidthconsumer( + Pointer handle, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_free_moqbandwidthconsumer( + Pointer handle, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_method_moqbandwidthconsumer_cancel( Pointer ptr, Pointer uniffiStatus, ); @@ -18574,20 +19498,19 @@ external void uniffi_moq_ffi_fn_method_moqaudioconsumer_cancel( @Native, Pointer)>( assetId: _uniffiAssetId, ) -external RustBuffer uniffi_moq_ffi_fn_method_moqaudioconsumer_delay( +external RustBuffer uniffi_moq_ffi_fn_method_moqbandwidthconsumer_rate( Pointer ptr, Pointer uniffiStatus, ); @Native Function(Pointer)>(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqaudioconsumer_next( - Pointer ptr, -); +external Pointer +uniffi_moq_ffi_fn_method_moqbandwidthconsumer_rate_changed(Pointer ptr); @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_clone_moqaudioencoder( +external Pointer uniffi_moq_ffi_fn_clone_moqratecontrol( Pointer handle, Pointer uniffiStatus, ); @@ -18595,7 +19518,7 @@ external Pointer uniffi_moq_ffi_fn_clone_moqaudioencoder( @Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_free_moqaudioencoder( +external void uniffi_moq_ffi_fn_free_moqratecontrol( Pointer handle, Pointer uniffiStatus, ); @@ -18603,132 +19526,132 @@ external void uniffi_moq_ffi_fn_free_moqaudioencoder( @Native Function(RustBuffer, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_constructor_moqaudioencoder_new( - RustBuffer output, +external Pointer uniffi_moq_ffi_fn_constructor_moqratecontrol_new( + RustBuffer policy, Pointer uniffiStatus, ); -@Native< - RustBuffer Function(Pointer, RustBuffer, Pointer) ->(assetId: _uniffiAssetId) -external RustBuffer uniffi_moq_ffi_fn_method_moqaudioencoder_encode( +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external RustBuffer uniffi_moq_ffi_fn_method_moqratecontrol_target( Pointer ptr, - RustBuffer pcm, Pointer uniffiStatus, ); @Native< - RustBuffer Function(Pointer, RustBuffer, Pointer) + RustBuffer Function(Pointer, Pointer, Pointer) >(assetId: _uniffiAssetId) -external RustBuffer uniffi_moq_ffi_fn_method_moqaudioencoder_finish( +external RustBuffer uniffi_moq_ffi_fn_method_moqratecontrol_update( Pointer ptr, - RustBuffer pcm, + Pointer reservation, Pointer uniffiStatus, ); -@Native, Pointer)>( +@Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external int uniffi_moq_ffi_fn_method_moqaudioencoder_frame_size( - Pointer ptr, +external Pointer uniffi_moq_ffi_fn_clone_moqreservation( + Pointer handle, Pointer uniffiStatus, ); -@Native, Uint64, Pointer)>( +@Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_method_moqaudioencoder_set_bitrate( - Pointer ptr, - int bitrate, +external void uniffi_moq_ffi_fn_free_moqreservation( + Pointer handle, Pointer uniffiStatus, ); @Native, Pointer)>( assetId: _uniffiAssetId, ) -external RustBuffer uniffi_moq_ffi_fn_method_moqaudioencoder_track_init( +external RustBuffer uniffi_moq_ffi_fn_method_moqreservation_rate( Pointer ptr, Pointer uniffiStatus, ); -@Native Function(Pointer, Pointer)>( +@Native, Uint64, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_clone_moqaudioproducer( - Pointer handle, +external void uniffi_moq_ffi_fn_method_moqreservation_update( + Pointer ptr, + int max_bps, Pointer uniffiStatus, ); -@Native, Pointer)>( +@Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_free_moqaudioproducer( +external Pointer uniffi_moq_ffi_fn_clone_moqviewer( Pointer handle, Pointer uniffiStatus, ); -@Native< - Pointer Function(Pointer, RustBuffer, Pointer) ->(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_constructor_moqaudioproducer_new( - Pointer catalog, - RustBuffer options, +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_free_moqviewer( + Pointer handle, Pointer uniffiStatus, ); -@Native Function(Pointer, Pointer)>( +@Native, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_method_moqaudioproducer_demand( +external RustBuffer uniffi_moq_ffi_fn_method_moqviewer_rate( Pointer ptr, Pointer uniffiStatus, ); -@Native, Pointer)>( +@Native, Uint64, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_method_moqaudioproducer_finish( +external void uniffi_moq_ffi_fn_method_moqviewer_update( Pointer ptr, + int max_bps, Pointer uniffiStatus, ); -@Native, Pointer)>( +@Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_method_moqaudioproducer_reanchor( - Pointer ptr, +external Pointer uniffi_moq_ffi_fn_clone_moqviewers( + Pointer handle, Pointer uniffiStatus, ); -@Native, Pointer)>( +@Native, Pointer)>( assetId: _uniffiAssetId, ) -external RustBuffer uniffi_moq_ffi_fn_method_moqaudioproducer_reservation( - Pointer ptr, +external void uniffi_moq_ffi_fn_free_moqviewers( + Pointer handle, Pointer uniffiStatus, ); @Native, RustBuffer, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_method_moqaudioproducer_write( +external void uniffi_moq_ffi_fn_method_moqviewers_set_target( Pointer ptr, - RustBuffer frame, + RustBuffer target_bps, Pointer uniffiStatus, ); -@Native Function(Pointer, Pointer)>( +@Native Function(Pointer, Uint64, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_clone_moqgrantconsumer( - Pointer handle, +external Pointer uniffi_moq_ffi_fn_method_moqviewers_watch( + Pointer ptr, + int max_bps, Pointer uniffiStatus, ); -@Native, Pointer)>( +@Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_free_moqgrantconsumer( +external Pointer uniffi_moq_ffi_fn_clone_moqbroadcastconsumer( Pointer handle, Pointer uniffiStatus, ); @@ -18736,59 +19659,58 @@ external void uniffi_moq_ffi_fn_free_moqgrantconsumer( @Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_method_moqgrantconsumer_cancel( - Pointer ptr, +external void uniffi_moq_ffi_fn_free_moqbroadcastconsumer( + Pointer handle, Pointer uniffiStatus, ); @Native Function(Pointer)>(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqgrantconsumer_changed( +external Pointer uniffi_moq_ffi_fn_method_moqbroadcastconsumer_closed( Pointer ptr, ); -@Native, Pointer)>( +@Native Function(Pointer, RustBuffer, Uint64, RustBuffer)>( assetId: _uniffiAssetId, ) -external RustBuffer uniffi_moq_ffi_fn_method_moqgrantconsumer_grant( +external Pointer +uniffi_moq_ffi_fn_method_moqbroadcastconsumer_fetch_group( Pointer ptr, - Pointer uniffiStatus, + RustBuffer name, + int sequence, + RustBuffer options, ); -@Native Function(Pointer, Pointer)>( +@Native Function(Pointer, RustBuffer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_clone_moqallocator( - Pointer handle, - Pointer uniffiStatus, +external Pointer uniffi_moq_ffi_fn_method_moqbroadcastconsumer_resolve( + Pointer ptr, + RustBuffer rendition, ); -@Native, Pointer)>( +@Native Function(Pointer, RustBuffer, RustBuffer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_free_moqallocator( - Pointer handle, - Pointer uniffiStatus, +external Pointer +uniffi_moq_ffi_fn_method_moqbroadcastconsumer_subscribe_track( + Pointer ptr, + RustBuffer name, + RustBuffer subscription, ); @Native< - Pointer Function( - Pointer, - Pointer, - Uint64, - Pointer, - ) + Pointer Function(Pointer, RustBuffer, Pointer) >(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqallocator_reserve( +external Pointer uniffi_moq_ffi_fn_method_moqbroadcastconsumer_datagrams( Pointer ptr, - Pointer demand, - int max_bps, + RustBuffer name, Pointer uniffiStatus, ); @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_clone_moqbandwidthconsumer( +external Pointer uniffi_moq_ffi_fn_clone_moqgroupconsumer( Pointer handle, Pointer uniffiStatus, ); @@ -18796,7 +19718,7 @@ external Pointer uniffi_moq_ffi_fn_clone_moqbandwidthconsumer( @Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_free_moqbandwidthconsumer( +external void uniffi_moq_ffi_fn_free_moqgroupconsumer( Pointer handle, Pointer uniffiStatus, ); @@ -18804,27 +19726,28 @@ external void uniffi_moq_ffi_fn_free_moqbandwidthconsumer( @Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_method_moqbandwidthconsumer_cancel( +external void uniffi_moq_ffi_fn_method_moqgroupconsumer_cancel( Pointer ptr, Pointer uniffiStatus, ); -@Native, Pointer)>( +@Native Function(Pointer)>(assetId: _uniffiAssetId) +external Pointer uniffi_moq_ffi_fn_method_moqgroupconsumer_read_frame( + Pointer ptr, +); + +@Native, Pointer)>( assetId: _uniffiAssetId, ) -external RustBuffer uniffi_moq_ffi_fn_method_moqbandwidthconsumer_rate( +external int uniffi_moq_ffi_fn_method_moqgroupconsumer_sequence( Pointer ptr, Pointer uniffiStatus, ); -@Native Function(Pointer)>(assetId: _uniffiAssetId) -external Pointer -uniffi_moq_ffi_fn_method_moqbandwidthconsumer_rate_changed(Pointer ptr); - @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_clone_moqratecontrol( +external Pointer uniffi_moq_ffi_fn_clone_moqtrackconsumer( Pointer handle, Pointer uniffiStatus, ); @@ -18832,40 +19755,55 @@ external Pointer uniffi_moq_ffi_fn_clone_moqratecontrol( @Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_free_moqratecontrol( +external void uniffi_moq_ffi_fn_free_moqtrackconsumer( Pointer handle, Pointer uniffiStatus, ); -@Native Function(RustBuffer, Pointer)>( +@Native, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_constructor_moqratecontrol_new( - RustBuffer policy, +external void uniffi_moq_ffi_fn_method_moqtrackconsumer_cancel( + Pointer ptr, Pointer uniffiStatus, ); @Native, Pointer)>( assetId: _uniffiAssetId, ) -external RustBuffer uniffi_moq_ffi_fn_method_moqratecontrol_target( +external RustBuffer uniffi_moq_ffi_fn_method_moqtrackconsumer_info( Pointer ptr, Pointer uniffiStatus, ); -@Native< - RustBuffer Function(Pointer, Pointer, Pointer) ->(assetId: _uniffiAssetId) -external RustBuffer uniffi_moq_ffi_fn_method_moqratecontrol_update( +@Native Function(Pointer)>(assetId: _uniffiAssetId) +external Pointer uniffi_moq_ffi_fn_method_moqtrackconsumer_next_group( Pointer ptr, - Pointer reservation, +); + +@Native Function(Pointer)>(assetId: _uniffiAssetId) +external Pointer uniffi_moq_ffi_fn_method_moqtrackconsumer_read_frame( + Pointer ptr, +); + +@Native Function(Pointer)>(assetId: _uniffiAssetId) +external Pointer uniffi_moq_ffi_fn_method_moqtrackconsumer_recv_group( + Pointer ptr, +); + +@Native, RustBuffer, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_method_moqtrackconsumer_update( + Pointer ptr, + RustBuffer subscription, Pointer uniffiStatus, ); @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_clone_moqreservation( +external Pointer uniffi_moq_ffi_fn_clone_moqdatagramconsumer( Pointer handle, Pointer uniffiStatus, ); @@ -18873,32 +19811,58 @@ external Pointer uniffi_moq_ffi_fn_clone_moqreservation( @Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_free_moqreservation( +external void uniffi_moq_ffi_fn_free_moqdatagramconsumer( Pointer handle, Pointer uniffiStatus, ); +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_method_moqdatagramconsumer_cancel( + Pointer ptr, + Pointer uniffiStatus, +); + +@Native Function(Pointer)>(assetId: _uniffiAssetId) +external Pointer uniffi_moq_ffi_fn_method_moqdatagramconsumer_info( + Pointer ptr, +); + @Native, Pointer)>( assetId: _uniffiAssetId, ) -external RustBuffer uniffi_moq_ffi_fn_method_moqreservation_rate( +external RustBuffer uniffi_moq_ffi_fn_method_moqdatagramconsumer_name( Pointer ptr, Pointer uniffiStatus, ); -@Native, Uint64, Pointer)>( +@Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_method_moqreservation_update( +external int uniffi_moq_ffi_fn_method_moqdatagramconsumer_priority( Pointer ptr, - int max_bps, + Pointer uniffiStatus, +); + +@Native Function(Pointer)>(assetId: _uniffiAssetId) +external Pointer uniffi_moq_ffi_fn_method_moqdatagramconsumer_recv( + Pointer ptr, +); + +@Native, Int8, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_method_moqdatagramconsumer_set_priority( + Pointer ptr, + int priority, Pointer uniffiStatus, ); @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_clone_moqviewer( +external Pointer uniffi_moq_ffi_fn_clone_moqdatagramproducer( Pointer handle, Pointer uniffiStatus, ); @@ -18906,116 +19870,97 @@ external Pointer uniffi_moq_ffi_fn_clone_moqviewer( @Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_free_moqviewer( +external void uniffi_moq_ffi_fn_free_moqdatagramproducer( Pointer handle, Pointer uniffiStatus, ); -@Native, Pointer)>( +@Native, Uint16, Pointer)>( assetId: _uniffiAssetId, ) -external RustBuffer uniffi_moq_ffi_fn_method_moqviewer_rate( +external void uniffi_moq_ffi_fn_method_moqdatagramproducer_abort( Pointer ptr, + int error_code, Pointer uniffiStatus, ); -@Native, Uint64, Pointer)>( - assetId: _uniffiAssetId, -) -external void uniffi_moq_ffi_fn_method_moqviewer_update( +@Native< + Uint64 Function( + Pointer, + RustBuffer, + RustBuffer, + Pointer, + ) +>(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_fn_method_moqdatagramproducer_append( Pointer ptr, - int max_bps, + RustBuffer timestamp, + RustBuffer payload, Pointer uniffiStatus, ); @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_clone_moqviewers( - Pointer handle, +external Pointer uniffi_moq_ffi_fn_method_moqdatagramproducer_consume( + Pointer ptr, Pointer uniffiStatus, ); @Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_free_moqviewers( - Pointer handle, - Pointer uniffiStatus, -); - -@Native, RustBuffer, Pointer)>( - assetId: _uniffiAssetId, -) -external void uniffi_moq_ffi_fn_method_moqviewers_set_target( +external void uniffi_moq_ffi_fn_method_moqdatagramproducer_finish( Pointer ptr, - RustBuffer target_bps, Pointer uniffiStatus, ); -@Native Function(Pointer, Uint64, Pointer)>( +@Native, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_method_moqviewers_watch( +external RustBuffer uniffi_moq_ffi_fn_method_moqdatagramproducer_info( Pointer ptr, - int max_bps, Pointer uniffiStatus, ); -@Native Function(Pointer, Pointer)>( +@Native, RustBuffer, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_clone_moqbroadcastconsumer( - Pointer handle, +external void uniffi_moq_ffi_fn_method_moqdatagramproducer_insert( + Pointer ptr, + RustBuffer datagram, Pointer uniffiStatus, ); -@Native, Pointer)>( +@Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_free_moqbroadcastconsumer( - Pointer handle, - Pointer uniffiStatus, -); - -@Native Function(Pointer)>(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqbroadcastconsumer_closed( +external RustBuffer uniffi_moq_ffi_fn_method_moqdatagramproducer_name( Pointer ptr, + Pointer uniffiStatus, ); -@Native Function(Pointer, RustBuffer, Uint64, RustBuffer)>( +@Native, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer -uniffi_moq_ffi_fn_method_moqbroadcastconsumer_fetch_group( +external RustBuffer uniffi_moq_ffi_fn_method_moqdatagramproducer_priority( Pointer ptr, - RustBuffer name, - int sequence, - RustBuffer options, + Pointer uniffiStatus, ); @Native Function(Pointer, RustBuffer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_method_moqbroadcastconsumer_resolve( - Pointer ptr, - RustBuffer rendition, -); - -@Native Function(Pointer, RustBuffer, RustBuffer)>( - assetId: _uniffiAssetId, -) external Pointer -uniffi_moq_ffi_fn_method_moqbroadcastconsumer_subscribe_track( +uniffi_moq_ffi_fn_method_moqdatagramproducer_priority_changed( Pointer ptr, - RustBuffer name, - RustBuffer subscription, + RustBuffer last, ); @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_clone_moqgroupconsumer( +external Pointer uniffi_moq_ffi_fn_clone_moqdatagramrequest( Pointer handle, Pointer uniffiStatus, ); @@ -19023,44 +19968,49 @@ external Pointer uniffi_moq_ffi_fn_clone_moqgroupconsumer( @Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_free_moqgroupconsumer( +external void uniffi_moq_ffi_fn_free_moqdatagramrequest( Pointer handle, Pointer uniffiStatus, ); -@Native, Pointer)>( +@Native, Uint16, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_method_moqgroupconsumer_cancel( +external void uniffi_moq_ffi_fn_method_moqdatagramrequest_abort( Pointer ptr, + int error_code, Pointer uniffiStatus, ); -@Native Function(Pointer)>(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqgroupconsumer_read_frame( +@Native< + Pointer Function(Pointer, RustBuffer, Pointer) +>(assetId: _uniffiAssetId) +external Pointer uniffi_moq_ffi_fn_method_moqdatagramrequest_accept( Pointer ptr, + RustBuffer info, + Pointer uniffiStatus, ); -@Native, Pointer)>( +@Native, Pointer)>( assetId: _uniffiAssetId, ) -external int uniffi_moq_ffi_fn_method_moqgroupconsumer_sequence( +external RustBuffer uniffi_moq_ffi_fn_method_moqdatagramrequest_name( Pointer ptr, Pointer uniffiStatus, ); -@Native Function(Pointer, Pointer)>( +@Native, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_clone_moqtrackconsumer( - Pointer handle, +external RustBuffer uniffi_moq_ffi_fn_method_moqdatagramrequest_priority( + Pointer ptr, Pointer uniffiStatus, ); -@Native, Pointer)>( +@Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_free_moqtrackconsumer( +external Pointer uniffi_moq_ffi_fn_clone_moqdatagramrequests( Pointer handle, Pointer uniffiStatus, ); @@ -19068,46 +20018,22 @@ external void uniffi_moq_ffi_fn_free_moqtrackconsumer( @Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_method_moqtrackconsumer_cancel( - Pointer ptr, +external void uniffi_moq_ffi_fn_free_moqdatagramrequests( + Pointer handle, Pointer uniffiStatus, ); -@Native, Pointer)>( +@Native, Pointer)>( assetId: _uniffiAssetId, ) -external RustBuffer uniffi_moq_ffi_fn_method_moqtrackconsumer_info( +external void uniffi_moq_ffi_fn_method_moqdatagramrequests_cancel( Pointer ptr, Pointer uniffiStatus, ); @Native Function(Pointer)>(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqtrackconsumer_next_group( - Pointer ptr, -); - -@Native Function(Pointer)>(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqtrackconsumer_read_frame( - Pointer ptr, -); - -@Native Function(Pointer)>(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqtrackconsumer_recv_datagram( - Pointer ptr, -); - -@Native Function(Pointer)>(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqtrackconsumer_recv_group( - Pointer ptr, -); - -@Native, RustBuffer, Pointer)>( - assetId: _uniffiAssetId, -) -external void uniffi_moq_ffi_fn_method_moqtrackconsumer_update( +external Pointer uniffi_moq_ffi_fn_method_moqdatagramrequests_requested( Pointer ptr, - RustBuffer subscription, - Pointer uniffiStatus, ); @Native Function(Pointer, Pointer)>( @@ -20232,6 +21158,22 @@ external Pointer uniffi_moq_ffi_fn_constructor_moqbroadcastproducer_new( Pointer uniffiStatus, ); +@Native< + Pointer Function( + Pointer, + RustBuffer, + RustBuffer, + Pointer, + ) +>(assetId: _uniffiAssetId) +external Pointer +uniffi_moq_ffi_fn_method_moqbroadcastproducer_create_datagrams( + Pointer ptr, + RustBuffer name, + RustBuffer info, + Pointer uniffiStatus, +); + @Native, Pointer)>( assetId: _uniffiAssetId, ) @@ -20288,6 +21230,14 @@ external void uniffi_moq_ffi_fn_free_moqbroadcastrequests( Pointer uniffiStatus, ); +@Native Function(Pointer, Pointer)>( + assetId: _uniffiAssetId, +) +external Pointer uniffi_moq_ffi_fn_method_moqbroadcastrequests_datagrams( + Pointer ptr, + Pointer uniffiStatus, +); + @Native, Pointer)>( assetId: _uniffiAssetId, ) @@ -20496,15 +21446,6 @@ external void uniffi_moq_ffi_fn_method_moqtrackproducer_abort( Pointer uniffiStatus, ); -@Native, RustBuffer, Pointer)>( - assetId: _uniffiAssetId, -) -external int uniffi_moq_ffi_fn_method_moqtrackproducer_append_datagram( - Pointer ptr, - RustBuffer frame, - Pointer uniffiStatus, -); - @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) @@ -20556,16 +21497,6 @@ external void uniffi_moq_ffi_fn_method_moqtrackproducer_finish_at( Pointer uniffiStatus, ); -@Native< - Void Function(Pointer, Uint64, RustBuffer, Pointer) ->(assetId: _uniffiAssetId) -external void uniffi_moq_ffi_fn_method_moqtrackproducer_insert_datagram( - Pointer ptr, - int sequence, - RustBuffer frame, - Pointer uniffiStatus, -); - @Native, Pointer)>( assetId: _uniffiAssetId, ) @@ -21703,6 +22634,9 @@ external int uniffi_moq_ffi_checksum_method_moqbroadcastconsumer_resolve(); external int uniffi_moq_ffi_checksum_method_moqbroadcastconsumer_subscribe_track(); +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqbroadcastconsumer_datagrams(); + @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqgroupconsumer_cancel(); @@ -21724,15 +22658,76 @@ external int uniffi_moq_ffi_checksum_method_moqtrackconsumer_next_group(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqtrackconsumer_read_frame(); -@Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqtrackconsumer_recv_datagram(); - @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqtrackconsumer_recv_group(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqtrackconsumer_update(); +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramconsumer_cancel(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramconsumer_info(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramconsumer_name(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramconsumer_priority(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramconsumer_recv(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramconsumer_set_priority(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramproducer_abort(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramproducer_append(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramproducer_consume(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramproducer_finish(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramproducer_info(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramproducer_insert(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramproducer_name(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramproducer_priority(); + +@Native(assetId: _uniffiAssetId) +external int +uniffi_moq_ffi_checksum_method_moqdatagramproducer_priority_changed(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramrequest_abort(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramrequest_accept(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramrequest_name(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramrequest_priority(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramrequests_cancel(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqdatagramrequests_requested(); + @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqtrackdemand_name(); @@ -21949,6 +22944,10 @@ external int uniffi_moq_ffi_checksum_method_moqpublication_broadcast(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqpublication_unannounce(); +@Native(assetId: _uniffiAssetId) +external int +uniffi_moq_ffi_checksum_method_moqbroadcastproducer_create_datagrams(); + @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqbroadcastproducer_close(); @@ -21962,6 +22961,9 @@ uniffi_moq_ffi_checksum_method_moqbroadcastproducer_publish_track(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqbroadcastproducer_requests(); +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqbroadcastrequests_datagrams(); + @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqbroadcastrequests_cancel(); @@ -22023,9 +23025,6 @@ external int uniffi_moq_ffi_checksum_method_moqgroupproducer_write_frame(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqtrackproducer_abort(); -@Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqtrackproducer_append_datagram(); - @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqtrackproducer_append_group(); @@ -22044,9 +23043,6 @@ external int uniffi_moq_ffi_checksum_method_moqtrackproducer_finish(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqtrackproducer_finish_at(); -@Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqtrackproducer_insert_datagram(); - @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqtrackproducer_largest(); @@ -22437,6 +23433,10 @@ void _checkApiChecksums() { 2348) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } + if (uniffi_moq_ffi_checksum_method_moqbroadcastconsumer_datagrams() != + 16292) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } if (uniffi_moq_ffi_checksum_method_moqgroupconsumer_cancel() != 52548) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } @@ -22458,16 +23458,77 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqtrackconsumer_read_frame() != 42799) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqtrackconsumer_recv_datagram() != - 32344) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } if (uniffi_moq_ffi_checksum_method_moqtrackconsumer_recv_group() != 40781) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqtrackconsumer_update() != 39083) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } + if (uniffi_moq_ffi_checksum_method_moqdatagramconsumer_cancel() != 6776) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramconsumer_info() != 3189) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramconsumer_name() != 52846) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramconsumer_priority() != 5672) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramconsumer_recv() != 12965) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramconsumer_set_priority() != + 21604) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramproducer_abort() != 25849) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramproducer_append() != 5184) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramproducer_consume() != 17555) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramproducer_finish() != 15816) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramproducer_info() != 20823) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramproducer_insert() != 12626) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramproducer_name() != 21849) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramproducer_priority() != 2145) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramproducer_priority_changed() != + 17584) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramrequest_abort() != 45486) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramrequest_accept() != 58466) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramrequest_name() != 54318) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramrequest_priority() != 9109) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramrequests_cancel() != 15138) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqdatagramrequests_requested() != 25471) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } if (uniffi_moq_ffi_checksum_method_moqtrackdemand_name() != 14603) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } @@ -22697,6 +23758,10 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqpublication_unannounce() != 21154) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } + if (uniffi_moq_ffi_checksum_method_moqbroadcastproducer_create_datagrams() != + 14147) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } if (uniffi_moq_ffi_checksum_method_moqbroadcastproducer_close() != 21298) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } @@ -22710,6 +23775,10 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqbroadcastproducer_requests() != 27464) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } + if (uniffi_moq_ffi_checksum_method_moqbroadcastrequests_datagrams() != + 19965) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } if (uniffi_moq_ffi_checksum_method_moqbroadcastrequests_cancel() != 44028) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } @@ -22771,10 +23840,6 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqtrackproducer_abort() != 37537) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqtrackproducer_append_datagram() != - 38326) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } if (uniffi_moq_ffi_checksum_method_moqtrackproducer_append_group() != 45225) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } @@ -22793,10 +23858,6 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqtrackproducer_finish_at() != 24581) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqtrackproducer_insert_datagram() != - 30484) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } if (uniffi_moq_ffi_checksum_method_moqtrackproducer_largest() != 24089) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } diff --git a/dart/moq_ffi/lib/src/uniffi_runtime.dart b/dart/moq_ffi/lib/src/uniffi_runtime.dart index 3b7dd9cf392..66b9e185973 100644 --- a/dart/moq_ffi/lib/src/uniffi_runtime.dart +++ b/dart/moq_ffi/lib/src/uniffi_runtime.dart @@ -8,6 +8,7 @@ import "dart:ffi"; import "dart:io" show Platform, File, Directory; import "dart:isolate"; import "dart:typed_data"; + import "package:ffi/ffi.dart"; class UniffiInternalError implements Exception { @@ -252,6 +253,7 @@ mixin FfiConverterPrimitive on FfiConverter { @override T lower(T value) => value; } + Uint8List createUint8ListFromInt(int value) { int length = value.bitLength ~/ 8 + 1; if (length != 4 && length != 8) { diff --git a/go/wrapper/README.md b/go/wrapper/README.md index 3983fe2a940..0747dcc4a04 100644 --- a/go/wrapper/README.md +++ b/go/wrapper/README.md @@ -176,6 +176,10 @@ serve on-demand datagram tracks with `BroadcastRequests.Datagrams()`. Keep payloads well below the path MTU. Delivery requires a datagram-capable transport and lite-05 or newer; there is no stream fallback. +On lite-05/06, an on-demand datagram name reaches its handler only after the stream +lookup reports not-found. Keeping a stream handler alive without rejecting that name +leaves the datagram request pending; lite-07 uses independent requests. + ## Versioning `VERSION` holds the human-owned `MAJOR.MINOR` line (the wrapper API version). Bump it in a PR only for a breaking change to the wrapper's own API. The patch number is derived by CI from the existing mirror tags, so every release (whether triggered by a wrapper change or by a new `moq.dev/moq-ffi`) just takes the next patch on that line. diff --git a/py/moq-rs/README.md b/py/moq-rs/README.md index 7bbb2f5ef77..1fdb00b31e6 100644 --- a/py/moq-rs/README.md +++ b/py/moq-rs/README.md @@ -302,3 +302,7 @@ reads with `await recv()` or async iteration. Demand is aggregate subscriber `pr `await priority_changed(last)`; `broadcast.requests().datagrams()` handles on-demand tracks. Keep payloads below the path MTU. Delivery needs a datagram-capable transport and lite-05 or newer, without a stream fallback. Stream tracks of the same name are independent. + +On lite-05/06, an on-demand datagram name reaches its handler only after the stream +lookup reports not-found. Keeping a stream handler alive without rejecting that name +leaves the datagram request pending; lite-07 uses independent requests. diff --git a/py/moq-rs/tests/test_local.py b/py/moq-rs/tests/test_local.py index 4e11a3c75ff..3a17da2d637 100644 --- a/py/moq-rs/tests/test_local.py +++ b/py/moq-rs/tests/test_local.py @@ -1841,7 +1841,9 @@ async def test_datagram_only_request_reaches_its_handler(): track = request.accept() assert (await consumer.info()).timescale is None track.append(b"payload") - assert (await consumer.recv()).payload == b"payload" + datagram = await consumer.recv() + assert datagram is not None + assert datagram.payload == b"payload" track.finish() assert await consumer.recv() is None requests.cancel() diff --git a/quest/m1/datagram-tracks/bindings.md b/quest/m1/datagram-tracks/bindings.md index 5c65e5cd897..3cf626afe60 100644 --- a/quest/m1/datagram-tracks/bindings.md +++ b/quest/m1/datagram-tracks/bindings.md @@ -8,18 +8,29 @@ datagram methods on stream tracks, mirroring Rust's names. ## Plan -Follow the [epic](/quest/m1/datagram-tracks/README.md)'s decisions. Regenerate the -UniFFI outputs, update `go/wrapper` (`publish.go`, `subscribe.go`, -`records.go`) and `dart/moq`, and record the migration in each package's -`MIGRATE.md`. Update `doc/lib/*` where they show datagrams. - -Until this lands, moq-ffi and moq-c back the old API with the new types -([moq-dev/moq#7752](https://github.com/moq-dev/moq/pull/7752)): every raw track -publishes a datagram track of the same name, and a reader subscribes to the -stream track before it opens the datagram track, so a datagram reader still -shows as the track's demand and reaches a dynamic publisher's request handler. -Remove that coupling here, and give the separate types their own demand (the -datagram producer's aggregate priority) and on-demand requests -(`Requests::datagrams()`), so a native datagram-only reader is visible too. +Follow the [epic](/quest/m1/datagram-tracks/README.md)'s decisions. +The implementation in [moq-dev/moq#7847](https://github.com/moq-dev/moq/pull/7847) +removes the transitional stream/datagram coupling, exposes the separate types, +aggregate subscriber priority and `Requests::datagrams()` handlers, and updates +the wrappers, generated bindings and migration notes. No JS implementation is +owned here; [moq-dev/moq#7846](https://github.com/moq-dev/moq/pull/7846) owns it. + +What remains is legacy on-demand lookup when both stream and datagram handlers +are alive. On lite-05/06, Rust's `lite::publisher::Legacy` first requests the +stream track, and only asks for datagrams after a not-found result. A stream +handler that leaves an unknown stream request pending therefore prevents the +datagram request from reaching its handler. The bindings cannot reject a stream +request as not-found: their rejection method carries an application error. +Published datagram-only tracks on lite-06 and on-demand datagram-only tracks on +lite-07 work without stream demand. + +The reproduction changed `requested_datagrams_cross_lite07` in moq-ffi's tests +to negotiate the default versions while retaining both handlers: it timed out +waiting for the datagram request. Its lite-07 version passes. Resolve the +legacy lookup policy below, then finish the PR's checks and local review. Public API: breaking for every binding's datagrams. Wire: none. + +## Waiting + +- Maintainer: choose how legacy on-demand kind lookup should work when both handlers are live. Options: (1) change Rust's legacy lookup to discover the datagram kind without waiting for the stream handler (recommended; preserves the independent binding API), or (2) require stream handlers to reject missing names and add a not-found rejection to the bindings. This changes compatibility behavior or the public rejection API, which this unattended implementation was not authorized to settle. Verify with the default-version reproduction above; lite-07 and the static default-version tests already pass. diff --git a/swift/README.md b/swift/README.md index 03ac586b513..0a559e9a643 100644 --- a/swift/README.md +++ b/swift/README.md @@ -86,6 +86,10 @@ assigns a sequence, `insert(_:)` preserves one, and `DatagramConsumer.recv()` or Keep payloads below the path MTU. Delivery needs a datagram-capable transport and lite-05 or newer, with no stream fallback. A stream track of the same name is independent. +On lite-05/06, an on-demand datagram name reaches its handler only after the stream +lookup reports not-found. Keeping a stream handler alive without rejecting that name +leaves the datagram request pending; lite-07 uses independent requests. + JSON tracks live under the `Json` namespace, mirroring the `moq-json` crate, and carry your own `Codable` types with the framing handled for you. Each type wraps a track: a producer takes over a `TrackProducer` and advertises it in the broadcast's catalog, and a consumer takes over a From fcd161d830b63b8da161ce1c1b325d7f818b6532 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 4 Nov 2026 02:39:17 -0800 Subject: [PATCH 4/9] refactor(ffi): keep datagram request internals private Co-Authored-By: GPT-6.1 Sol --- cpp/moq/test/probe.cpp | 5 ++-- dart/moq/lib/src/aliases.dart | 2 +- .../kotlin/dev/moq/Aliases.kt | 2 +- py/moq-rs/moq/_records.py | 2 +- rs/moq-c/src/api.rs | 6 ++--- rs/moq-c/src/consume.rs | 2 +- rs/moq-ffi/src/datagram.rs | 21 +++++---------- rs/moq-ffi/src/producer.rs | 26 ++++++++++++++----- swift/Sources/Moq/Aliases.swift | 2 +- 9 files changed, 38 insertions(+), 30 deletions(-) diff --git a/cpp/moq/test/probe.cpp b/cpp/moq/test/probe.cpp index 42b1eb33f9b..2d7bbc1fb1c 100644 --- a/cpp/moq/test/probe.cpp +++ b/cpp/moq/test/probe.cpp @@ -112,8 +112,7 @@ bool same_time(const moq::Timestamp &a, const moq::Timestamp &b) return a.value * b.scale == b.value * a.scale; } -// Timestamps are exact records: a 90 kHz tick and a present zero read back as written, an -// untimed frame reads back untimed, and a record past the bounds is refused. +// A datagram-only request reaches its own handler and demand. void datagram_tracks() { auto broadcast = ok(moq::BroadcastProducer::init(), "datagram broadcast"); @@ -138,6 +137,8 @@ void datagram_tracks() ok(broadcast->close(), "close datagram broadcast"); } +// Timestamps are exact records: a 90 kHz tick and a present zero read back as written, an +// untimed frame reads back untimed, and a record past the bounds is refused. void timestamp_roundtrip() { auto broadcast = ok(moq::BroadcastProducer::init(), "timestamp broadcast"); diff --git a/dart/moq/lib/src/aliases.dart b/dart/moq/lib/src/aliases.dart index 59103941f61..81149d34860 100644 --- a/dart/moq/lib/src/aliases.dart +++ b/dart/moq/lib/src/aliases.dart @@ -128,7 +128,7 @@ typedef GroupProducer = MoqGroupProducer; /// The read side of a single group: yields timestamped raw frames. typedef GroupConsumer = MoqGroupConsumer; -/// A datagram-delivered frame, tagged with a per-track sequence number. +/// A datagram payload with its own sequence and optional timestamp. typedef Datagram = MoqDatagram; /// A payload plus the timestamp it should be presented at. diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt index 9cc0e2e07df..6ea2b02ec79 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt @@ -159,7 +159,7 @@ typealias GroupProducer = uniffi.moq.MoqGroupProducer typealias GroupConsumer = uniffi.moq.MoqGroupConsumer // Data types. -/** A datagram-delivered frame, tagged with a per-track sequence number. */ +/** A datagram payload with its own sequence and optional timestamp. */ typealias Datagram = uniffi.moq.MoqDatagram /** A payload plus the timestamp it should be presented at. */ diff --git a/py/moq-rs/moq/_records.py b/py/moq-rs/moq/_records.py index 58f3623b72f..1d8b712c5a3 100644 --- a/py/moq-rs/moq/_records.py +++ b/py/moq-rs/moq/_records.py @@ -118,7 +118,7 @@ def _from_ffi(frame: MoqFrame) -> Frame: @dataclass(frozen=True) class Datagram: - """A best-effort track datagram as received: sequence number, timestamp, and payload. + """A datagram payload with its own sequence and optional timestamp. ``timestamp`` is ``None`` on a datagram read from an untimed track. """ diff --git a/rs/moq-c/src/api.rs b/rs/moq-c/src/api.rs index 58d24da3cb1..b7190ab3e67 100644 --- a/rs/moq-c/src/api.rs +++ b/rs/moq-c/src/api.rs @@ -624,10 +624,10 @@ pub struct moq_media_read { pub end: moq_timestamp, } -/// A best-effort raw track datagram delivered via [moq_consume_datagrams]. +/// A live datagram delivered via [moq_consume_datagrams]. #[repr(C)] pub struct moq_datagram { - /// The payload of the datagram, or NULL/0 if the track has ended. + /// The datagram payload, valid until [moq_consume_datagram_free]. pub payload: *const u8, /// The length in bytes of `payload`. pub payload_size: usize, @@ -636,7 +636,7 @@ pub struct moq_datagram { /// long as `payload`. pub timestamp: *const moq_timestamp, - /// The datagram's sequence number, counted apart from the track's groups. + /// The datagram track's own sequence number. pub sequence: u64, } diff --git a/rs/moq-c/src/consume.rs b/rs/moq-c/src/consume.rs index 02c0f30e3b4..cf768de7341 100644 --- a/rs/moq-c/src/consume.rs +++ b/rs/moq-c/src/consume.rs @@ -241,7 +241,7 @@ pub struct Consume { /// Buffered raw frames ready for consumption. raw_frame: NonZeroSlab>, - /// Raw track datagram consumer tasks (best-effort, parallel to `raw_task`). + /// Live datagram consumer tasks, independent of stream-track readers. datagram_task: NonZeroSlab, /// Buffered datagrams ready for consumption. diff --git a/rs/moq-ffi/src/datagram.rs b/rs/moq-ffi/src/datagram.rs index 353c25f2614..1ef1cbde55d 100644 --- a/rs/moq-ffi/src/datagram.rs +++ b/rs/moq-ffi/src/datagram.rs @@ -7,7 +7,7 @@ use crate::consumer::MoqBroadcastConsumer; use crate::error::MoqError; use crate::ffi::{Background, Polled}; use crate::media::{MoqDatagram, MoqTimestamp}; -use crate::producer::{Child, Children, MoqBroadcastProducer, MoqBroadcastRequests}; +use crate::producer::{Child, Children, MoqBroadcastProducer}; /// Publisher properties of a datagram track, fixed at creation. #[derive(Clone, Default, uniffi::Record)] @@ -246,19 +246,12 @@ pub struct MoqDatagramRequests { children: Children, } -#[uniffi::export] -impl MoqBroadcastRequests { - /// Create an on-demand handler for datagram tracks. - pub fn datagrams(&self) -> Result, MoqError> { - let _guard = crate::ffi::enter(); - let requests = self - .reads - .peek(|inner| inner.requests.datagrams()) - .ok_or(MoqError::Closed)?; - Ok(Arc::new(MoqDatagramRequests { - inner: Polled::new(requests).supervised(self.driver.clone()), - children: self.children.clone(), - })) +impl MoqDatagramRequests { + pub(crate) fn new(requests: moq_net::broadcast::DatagramRequests, children: Children, driver: Background) -> Self { + Self { + inner: Polled::new(requests).supervised(driver), + children, + } } } diff --git a/rs/moq-ffi/src/producer.rs b/rs/moq-ffi/src/producer.rs index 180f105207a..66bb0f0ec47 100644 --- a/rs/moq-ffi/src/producer.rs +++ b/rs/moq-ffi/src/producer.rs @@ -181,7 +181,7 @@ impl Children { } /// The broadcast, while a handle keeping it open still holds it. - pub(crate) fn broadcast(&self) -> Option> { + fn broadcast(&self) -> Option> { self.broadcast.upgrade() } @@ -250,13 +250,13 @@ pub struct MoqBroadcastProducer { /// A handler for requests for tracks in a broadcast. #[derive(uniffi::Object)] pub struct MoqBroadcastRequests { - pub(crate) reads: Polled, - pub(crate) children: Children, - pub(crate) driver: Background, + reads: Polled, + children: Children, + driver: Background, } -pub(crate) struct RequestsInner { - pub(crate) requests: moq_net::broadcast::Requests, +struct RequestsInner { + requests: moq_net::broadcast::Requests, /// Holds the broadcast for [`Children::broadcast`] as long as `requests` keeps it open, so a /// request can still be accepted after the broadcast handle dropped. _broadcast: Arc, @@ -427,6 +427,20 @@ impl MoqBroadcastRequests { Ok(Arc::new(MoqTrackRequest::new(request, self.children.clone()))) } + /// Create an on-demand handler for datagram tracks. + pub fn datagrams(&self) -> Result, MoqError> { + let _guard = crate::ffi::enter(); + let requests = self + .reads + .peek(|inner| inner.requests.datagrams()) + .ok_or(MoqError::Closed)?; + Ok(Arc::new(crate::datagram::MoqDatagramRequests::new( + requests, + self.children.clone(), + self.driver.clone(), + ))) + } + /// Cancel all current and future `requested_track()` calls. /// /// Terminal: the dynamic broadcast is released here, not when the handle is, so any pending diff --git a/swift/Sources/Moq/Aliases.swift b/swift/Sources/Moq/Aliases.swift index b153ee69a94..c0b3c4022d4 100644 --- a/swift/Sources/Moq/Aliases.swift +++ b/swift/Sources/Moq/Aliases.swift @@ -49,7 +49,7 @@ public typealias VideoCodec = MoqFFI.MoqVideoCodec /// Which encoder implementation to use: automatic, hardware, software, or one /// named backend. public typealias VideoEncoderKind = MoqFFI.MoqVideoEncoderKind -/// A best-effort raw-track datagram as received: sequence, timestamp, and payload. +/// A datagram payload with its own sequence and optional timestamp. public typealias Datagram = MoqFFI.MoqDatagram /// How a broadcast advertises its exact path: its static production `cost`, /// lower wins, an optional stable `instance` (`nil` keeps the one the broadcast From baae2202080947ad044eb2c7f112ea776b1e6c1a Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 4 Nov 2026 02:40:52 -0800 Subject: [PATCH 5/9] fix(c): release datagram demand before terminal callback Co-Authored-By: GPT-6.1 Sol --- rs/moq-c/src/consume.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/rs/moq-c/src/consume.rs b/rs/moq-c/src/consume.rs index cf768de7341..71a47a26430 100644 --- a/rs/moq-c/src/consume.rs +++ b/rs/moq-c/src/consume.rs @@ -866,8 +866,9 @@ impl Consume { tokio::spawn(async move { let res = crate::ffi::run(driver.watch(Self::run_datagrams(on_datagram, track, close))).await; let entry = State::lock().consume.datagram_task.remove(id); - if let Some(entry) = entry { - entry.task.callback.call(res); + if let Some(DatagramTaskEntry { task, track }) = entry { + drop(track); + task.callback.call(res); } }); Ok(id) From eedcbff5ee51bafed5110f1276e9ec03dc5fa37d Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 4 Nov 2026 02:53:45 -0800 Subject: [PATCH 6/9] chore(dart): regenerate final datagram request metadata Co-Authored-By: GPT-6.1 Sol --- dart/moq_ffi/lib/src/moq.dart | 40 +++++++++++------------- dart/moq_ffi/lib/src/uniffi_runtime.dart | 2 -- 2 files changed, 19 insertions(+), 23 deletions(-) diff --git a/dart/moq_ffi/lib/src/moq.dart b/dart/moq_ffi/lib/src/moq.dart index 2716dd4a95b..b2055b918b1 100644 --- a/dart/moq_ffi/lib/src/moq.dart +++ b/dart/moq_ffi/lib/src/moq.dart @@ -8,9 +8,7 @@ import "dart:ffi"; import "dart:io" show Platform, File, Directory; import "dart:isolate"; import "dart:typed_data"; - import "package:ffi/ffi.dart"; - import "uniffi_runtime.dart"; export "uniffi_runtime.dart"; @@ -14224,8 +14222,8 @@ class FfiConverterMoqBroadcastProducer { } abstract class MoqBroadcastRequestsInterface { - MoqDatagramRequests datagrams(); void cancel(); + MoqDatagramRequests datagrams(); UniffiRustFuture requestedTrack(); } @@ -14268,6 +14266,15 @@ class MoqBroadcastRequests implements MoqBroadcastRequestsInterface { } } + void cancel() { + return rustCall((status) { + uniffi_moq_ffi_fn_method_moqbroadcastrequests_cancel( + uniffiClonePointer(), + status, + ); + }, null); + } + MoqDatagramRequests datagrams() { return rustCallWithLifter( (status) => uniffi_moq_ffi_fn_method_moqbroadcastrequests_datagrams( @@ -14279,15 +14286,6 @@ class MoqBroadcastRequests implements MoqBroadcastRequestsInterface { ); } - void cancel() { - return rustCall((status) { - uniffi_moq_ffi_fn_method_moqbroadcastrequests_cancel( - uniffiClonePointer(), - status, - ); - }, null); - } - UniffiRustFuture requestedTrack() { return uniffiRustCallAsync( () => uniffi_moq_ffi_fn_method_moqbroadcastrequests_requested_track( @@ -21244,18 +21242,18 @@ external void uniffi_moq_ffi_fn_free_moqbroadcastrequests( Pointer uniffiStatus, ); -@Native Function(Pointer, Pointer)>( +@Native, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_method_moqbroadcastrequests_datagrams( +external void uniffi_moq_ffi_fn_method_moqbroadcastrequests_cancel( Pointer ptr, Pointer uniffiStatus, ); -@Native, Pointer)>( +@Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_method_moqbroadcastrequests_cancel( +external Pointer uniffi_moq_ffi_fn_method_moqbroadcastrequests_datagrams( Pointer ptr, Pointer uniffiStatus, ); @@ -22976,10 +22974,10 @@ uniffi_moq_ffi_checksum_method_moqbroadcastproducer_publish_track(); external int uniffi_moq_ffi_checksum_method_moqbroadcastproducer_requests(); @Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqbroadcastrequests_datagrams(); +external int uniffi_moq_ffi_checksum_method_moqbroadcastrequests_cancel(); @Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqbroadcastrequests_cancel(); +external int uniffi_moq_ffi_checksum_method_moqbroadcastrequests_datagrams(); @Native(assetId: _uniffiAssetId) external int @@ -23789,11 +23787,11 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqbroadcastproducer_requests() != 27464) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqbroadcastrequests_datagrams() != - 19965) { + if (uniffi_moq_ffi_checksum_method_moqbroadcastrequests_cancel() != 44028) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqbroadcastrequests_cancel() != 44028) { + if (uniffi_moq_ffi_checksum_method_moqbroadcastrequests_datagrams() != + 17164) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqbroadcastrequests_requested_track() != diff --git a/dart/moq_ffi/lib/src/uniffi_runtime.dart b/dart/moq_ffi/lib/src/uniffi_runtime.dart index 66b9e185973..3b7dd9cf392 100644 --- a/dart/moq_ffi/lib/src/uniffi_runtime.dart +++ b/dart/moq_ffi/lib/src/uniffi_runtime.dart @@ -8,7 +8,6 @@ import "dart:ffi"; import "dart:io" show Platform, File, Directory; import "dart:isolate"; import "dart:typed_data"; - import "package:ffi/ffi.dart"; class UniffiInternalError implements Exception { @@ -253,7 +252,6 @@ mixin FfiConverterPrimitive on FfiConverter { @override T lower(T value) => value; } - Uint8List createUint8ListFromInt(int value) { int length = value.bitLength ~/ 8 + 1; if (length != 4 && length != 8) { From 2a2e6c5f090d7b9c088db993d81a0a3b59fe857b Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 4 Nov 2026 08:27:14 -0800 Subject: [PATCH 7/9] fix(net): answer lite-05/06 names from local datagram tracks without waiting for stream handlers A lite-05/06 subscription doesn't say which kind it asks for, so the publisher looked up the stream track first and fell back to the datagram track only on not-found. A stream request handler that left an unknown name unanswered, as the bindings' handlers may, stalled datagram readers. Once the stream lookup is pending, the publisher now asks a local datagram track too and serves it as soon as it answers, unless a producer serves the stream track, which keeps a name with both kinds a stream track with its datagrams beside it. A session's broadcast is asked only after the stream track is not found: an old session answers a datagram request by subscribing to the stream track, which fetch-only and query-only relays must not do. An origin front also routes datagram lookups to its source before it resolves requesters, so a lookup right after resolution no longer finds no source and fails Unroutable. Records the maintainer's 2026-11-04 decision and completes the bindings quest. Co-Authored-By: Claude Opus 5.5 --- quest/m1/datagram-tracks/README.md | 16 ++- quest/m1/datagram-tracks/bindings.md | 36 ------- rs/moq-ffi/src/test.rs | 17 +++- rs/moq-net/src/lite/publisher.rs | 118 ++++++++++++++++++++--- rs/moq-net/src/model/broadcast.rs | 38 ++++++++ rs/moq-net/src/model/datagram.rs | 4 + rs/moq-net/src/model/origin.rs | 6 ++ rs/moq-net/src/model/track.rs | 6 ++ rs/moq-net/tests/integration/datagram.rs | 65 +++++++++++++ 9 files changed, 254 insertions(+), 52 deletions(-) delete mode 100644 quest/m1/datagram-tracks/bindings.md diff --git a/quest/m1/datagram-tracks/README.md b/quest/m1/datagram-tracks/README.md index 143c558c70e..2de1a7452ae 100644 --- a/quest/m1/datagram-tracks/README.md +++ b/quest/m1/datagram-tracks/README.md @@ -77,6 +77,21 @@ Decided 2026-11-01 (maintainer, in `/quest-plan`): - Reason: lite-05/06 are the default connections, and moq-ffi/moq-c publish every raw track's datagrams beside it, so serving a name only one kind stopped their datagrams on the default path. +- **Old-version lookup.** ✅ Decided 2026-11-04 (maintainer, for + [moq-dev/moq#7847](https://github.com/moq-dev/moq/pull/7847)): change + Rust's lite-05/06 on-demand lookup to discover datagrams without waiting + for a stream-handler answer, keeping the independent binding request API. + Not chosen: requiring stream handlers to reject missing names, with a + not-found rejection added to the bindings. + - A published stream track still serves the name, with its datagram track + beside it. Otherwise a local datagram track answers as soon as its + handler does. Of a name whose two kinds are both requested on demand, + the first answer serves it. + - A session's broadcast is asked for datagrams only once its stream track + is not found: an old session answers a datagram request by subscribing to + the stream track, which a fetch-only or query-only relay must not do. + - Reason: a stream handler need not answer a name it doesn't serve, and + the bindings' rejection carries only an application error. - **Version.** ✅ lite-07, before it is finalized. [Finalize moq-lite-07](/quest/m1/lite07-finalize.md) requires this epic. lite-01..06 keep today's group datagrams. @@ -107,7 +122,6 @@ datagram track on lite-07, direct and through a relay. - [JS datagram tracks](/quest/m1/datagram-tracks/js.md) - `@moq/net` datagram types and the lite-07 datagram request - [moq-transport datagram tracks](/quest/m1/datagram-tracks/ietf.md) - Rust and JS map a datagram track to SUBSCRIBE and OBJECT_DATAGRAM with object ID 0, keeping the requested kind -- [Bindings datagram tracks](/quest/m1/datagram-tracks/bindings.md) - moq-ffi, moq-c, and every wrapper expose the separate datagram types ## Related diff --git a/quest/m1/datagram-tracks/bindings.md b/quest/m1/datagram-tracks/bindings.md deleted file mode 100644 index 3cf626afe60..00000000000 --- a/quest/m1/datagram-tracks/bindings.md +++ /dev/null @@ -1,36 +0,0 @@ -# [M] Bindings datagram tracks - -## Goal - -moq-ffi, moq-c, and every wrapper (Python, Swift, Kotlin, Go, Dart, C++) -expose the separate datagram producer and consumer types instead of -datagram methods on stream tracks, mirroring Rust's names. - -## Plan - -Follow the [epic](/quest/m1/datagram-tracks/README.md)'s decisions. -The implementation in [moq-dev/moq#7847](https://github.com/moq-dev/moq/pull/7847) -removes the transitional stream/datagram coupling, exposes the separate types, -aggregate subscriber priority and `Requests::datagrams()` handlers, and updates -the wrappers, generated bindings and migration notes. No JS implementation is -owned here; [moq-dev/moq#7846](https://github.com/moq-dev/moq/pull/7846) owns it. - -What remains is legacy on-demand lookup when both stream and datagram handlers -are alive. On lite-05/06, Rust's `lite::publisher::Legacy` first requests the -stream track, and only asks for datagrams after a not-found result. A stream -handler that leaves an unknown stream request pending therefore prevents the -datagram request from reaching its handler. The bindings cannot reject a stream -request as not-found: their rejection method carries an application error. -Published datagram-only tracks on lite-06 and on-demand datagram-only tracks on -lite-07 work without stream demand. - -The reproduction changed `requested_datagrams_cross_lite07` in moq-ffi's tests -to negotiate the default versions while retaining both handlers: it timed out -waiting for the datagram request. Its lite-07 version passes. Resolve the -legacy lookup policy below, then finish the PR's checks and local review. - -Public API: breaking for every binding's datagrams. Wire: none. - -## Waiting - -- Maintainer: choose how legacy on-demand kind lookup should work when both handlers are live. Options: (1) change Rust's legacy lookup to discover the datagram kind without waiting for the stream handler (recommended; preserves the independent binding API), or (2) require stream handlers to reject missing names and add a not-found rejection to the bindings. This changes compatibility behavior or the public rejection API, which this unattended implementation was not authorized to settle. Verify with the default-version reproduction above; lite-07 and the static default-version tests already pass. diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index 711c7f01d34..ee880532191 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -6057,9 +6057,22 @@ async fn datagrams_cross_a_default_connection() { assert_eq!(session.state().version.as_deref(), Some("moq-lite-06")); } +/// An on-demand datagram-only track reaches a reader on the default lite-06 path while a +/// stream handler leaves the name unanswered: the datagram handler's answer serves it. +#[tokio::test] +async fn requested_datagrams_cross_a_default_connection() { + requested_datagrams_cross(vec![], "moq-lite-06").await; +} + #[tokio::test] async fn requested_datagrams_cross_lite07() { - let (broadcast, remote, session, _server) = datagram_connection("sensor", vec!["moq-lite-07-wip".into()]).await; + requested_datagrams_cross(vec!["moq-lite-07-wip".into()], "moq-lite-07-wip").await; +} + +/// Reads a datagram track a datagram handler accepts over `versions`, which negotiate +/// `negotiated`, while the broadcast's stream handler stays alive and never answers. +async fn requested_datagrams_cross(versions: Vec, negotiated: &str) { + let (broadcast, remote, session, _server) = datagram_connection("sensor", versions).await; let requests = broadcast.requests().unwrap(); let datagrams = requests.datagrams().unwrap(); let consumer = remote.datagrams("events".into()).unwrap(); @@ -6076,7 +6089,7 @@ async fn requested_datagrams_cross_lite07() { .unwrap() .unwrap(); assert_eq!(datagram.payload, b"only"); - assert_eq!(session.state().version.as_deref(), Some("moq-lite-07-wip")); + assert_eq!(session.state().version.as_deref(), Some(negotiated)); } /// A replacement session from the same publisher re-announces every route while the old one diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index 6d3d12fb213..35bee7c59fc 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -2065,10 +2065,18 @@ impl Request for TrackInfoServe { waiter: &kio::Waiter, ) -> Poll, Error>> { let ietf = ready!(shared.peer_setup.poll_ietf(waiter)); - if let Self::Track(querying, legacy) = self - && let Poll::Ready(Err(err)) = querying.poll_ok(waiter) - { - *self = Self::Datagrams(Legacy::datagrams(legacy.take(), err)?); + if let Self::Track(querying, legacy) = self { + match querying.poll_ok(waiter) { + Poll::Ready(Err(err)) => *self = Self::Datagrams(Legacy::datagrams(legacy.take(), err)?), + // The stream track answers: let a pending datagram ask go, rather than hold it + // as long as the requester keeps the stream open. + Poll::Ready(Ok(_)) => drop(legacy.take()), + Poll::Pending => { + if let Poll::Ready(consumer) = Legacy::poll_datagrams(legacy, waiter) { + *self = Self::Datagrams(consumer); + } + } + } } let querying = match self { Self::Track(querying, _) => querying, @@ -2308,8 +2316,24 @@ impl Request for SubscribeServe { ) -> Poll, Error>> { loop { match self { - Self::Query { querying, .. } => { - let info = ready!(querying.poll_ok(waiter)); + Self::Query { querying, legacy, .. } => { + let info = match querying.poll_ok(waiter) { + Poll::Ready(info) => info, + Poll::Pending => { + let consumer = ready!(Legacy::poll_datagrams(legacy, waiter)); + let Self::Query { msg, update, .. } = std::mem::replace( + self, + Self::Drain { + children: Default::default(), + _track: None, + }, + ) else { + unreachable!() + }; + *self = Self::datagrams(consumer, &msg, update); + continue; + } + }; let Self::Query { msg, track, @@ -2337,9 +2361,27 @@ impl Request for SubscribeServe { let bounds = Bounds::new(&msg.ranges, info.timescale)?; *self = Self::subscribe(shared, *msg, bounds, &track, latest, update, legacy); } - Self::Confirm { subscribing, .. } => { + Self::Confirm { + subscribing, legacy, .. + } => { let ietf = ready!(shared.peer_setup.poll_ietf(waiter)); - let track = ready!(subscribing.poll_ok(waiter)); + let track = match subscribing.poll_ok(waiter) { + Poll::Ready(track) => track, + Poll::Pending => { + let consumer = ready!(Legacy::poll_datagrams(legacy, waiter)); + let Self::Confirm { msg, update, .. } = std::mem::replace( + self, + Self::Drain { + children: Default::default(), + _track: None, + }, + ) else { + unreachable!() + }; + *self = Self::datagrams(consumer, &msg, update); + continue; + } + }; let Self::Confirm { msg, bounds, @@ -2507,11 +2549,22 @@ impl Request for SubscribeServe { /// Lite-05/06 carry a name's stream track and datagram track on one subscription: a name /// with a stream track carries its datagram track beside it (see [`LegacyDatagrams`]), and -/// one with none is served from its datagram track alone. The stream track's lookup -/// resolves later through an origin, so the request keeps this until it does. +/// one with none is served from its datagram track alone. +/// +/// Once the stream track's lookup is pending, the request asks for the datagram track too, +/// since a handler may leave a name it doesn't serve unanswered: a local datagram track +/// answers the name without waiting for the stream track's lookup, which resolves later +/// through an origin, so the request keeps this until one of them answers. A datagram track +/// waits for the stream track's answer instead while a producer serves the stream track. A +/// relayed broadcast's is asked for only once its stream track is not found (see +/// [`crate::broadcast::Consumer::has_local_datagrams`]). Of a name whose two kinds are both +/// asked for on demand, the first answered serves it. struct Legacy { broadcast: crate::broadcast::Consumer, name: String, + /// The name's datagram track, asked for beside the stream track: `None` until asked, and + /// `Some(None)` once refused or not asked, as of a relayed broadcast. + datagrams: Option>, } impl Legacy { @@ -2521,10 +2574,37 @@ impl Legacy { Box::new(Self { broadcast: broadcast.clone(), name: name.to_string(), + datagrams: None, }) }) } + /// The datagram track to serve before the stream track answers: one a local handler or + /// producer answered while no producer serves the stream track. Pending otherwise, + /// waking with the stream track's lookup, which the caller polls first. + fn poll_datagrams(legacy: &mut Option>, waiter: &kio::Waiter) -> Poll { + let Some(this) = legacy else { + return Poll::Pending; + }; + let asked = this.datagrams.get_or_insert_with(|| { + this.broadcast + .has_local_datagrams() + .then(|| this.broadcast.datagrams(&this.name).ok()) + .flatten() + }); + let Some(consumer) = asked else { + return Poll::Pending; + }; + match ready!(consumer.poll_info(waiter)) { + Ok(_) if this.broadcast.publishes_track(&this.name) => Poll::Pending, + Ok(_) => Poll::Ready(asked.take().expect("checked above")), + Err(_) => { + *asked = None; + Poll::Pending + } + } + } + /// The datagram track to serve instead when the stream track's lookup failed with `err`, /// or `err` itself. fn datagrams(legacy: Option>, err: Error) -> Result { @@ -2534,7 +2614,10 @@ impl Legacy { if !matches!(err, Error::NotFound | Error::Stream(StreamError::NotFound)) { return Err(err); } - legacy.broadcast.datagrams(&legacy.name).map_err(|_| err) + let asked = legacy + .datagrams + .unwrap_or_else(|| legacy.broadcast.datagrams(&legacy.name).ok()); + asked.ok_or(err) } } @@ -2556,9 +2639,18 @@ impl LegacyDatagrams { /// of a stream track with `timescale`, or `None` when the version has no fallback or /// no datagram track is live. A relay holds one for each old-version stream track it /// subscribes to, so this asks no handler: a request would subscribe to the name again. + /// The request's own ask joins only once answered, the track then being live. fn join(legacy: Option>, id: u64, priority: i8, timescale: Option) -> Option { - let legacy = legacy?; - let mut consumer = legacy.broadcast.datagrams_live(&legacy.name)?; + let Legacy { + broadcast, + name, + datagrams, + } = *legacy?; + // An unanswered ask is dropped, which withdraws it. + let answered = datagrams + .flatten() + .filter(|asked| matches!(asked.poll_info(&kio::Waiter::noop()), Poll::Ready(Ok(_)))); + let mut consumer = answered.or_else(|| broadcast.datagrams_live(&name))?; consumer.set_priority(priority); Some(Self { consumer, diff --git a/rs/moq-net/src/model/broadcast.rs b/rs/moq-net/src/model/broadcast.rs index ed7306044f3..7d068b215ea 100644 --- a/rs/moq-net/src/model/broadcast.rs +++ b/rs/moq-net/src/model/broadcast.rs @@ -135,6 +135,8 @@ struct BroadcastState { datagram_handlers: usize, // Set on an origin's front: datagram lookups go to the source it serves from, if any. datagram_source: Option>, + // A session's source, relaying a peer's broadcast; see [`Consumer::has_local_datagrams`]. + relayed: bool, } impl BroadcastState { @@ -755,6 +757,7 @@ pub(crate) struct SourceGuard(Producer); impl SourceGuard { #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))] pub fn new(producer: Producer) -> Self { + producer.state.lock().relayed = true; Self(producer) } } @@ -1156,6 +1159,41 @@ impl Consumer { state.datagrams.get(name)?.try_consume(self.stats.clone()) } + /// Whether datagram lookups reach a local producer or handler, rather than a session that + /// relays a peer's broadcast, here or at the source an origin serves this broadcast from. + /// + /// A session always answers a lookup, and a moq-lite 05/06 one subscribes to the stream + /// track of the same name to answer one, so a lite-05/06 publisher only asks a local one + /// for a name's datagram track before its stream track answers. + #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))] + pub(crate) fn has_local_datagrams(&self) -> bool { + let state = self.state.lock(); + match &state.datagram_source { + Some(Some(source)) => { + let source = source.clone(); + drop(state); + source.has_local_datagrams() + } + Some(None) => false, + None => !state.relayed, + } + } + + /// Whether a producer serves the stream track `name`, here or at the source an origin + /// serves this broadcast from, rather than a request still waiting for an answer. + #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))] + pub(crate) fn publishes_track(&self, name: &str) -> bool { + let mut state = self.state.lock(); + if BroadcastState::live_track(&mut state, name).is_some_and(|live| live.minted()) { + return true; + } + let Some(Some(source)) = state.datagram_source.clone() else { + return false; + }; + drop(state); + source.publishes_track(name) + } + /// Join the demand of the track serving `name`, requesting it from a [`Requests`] /// when nothing serves it yet. Registers the subscription before exposing demand. /// Errors as [`Self::track`] does. diff --git a/rs/moq-net/src/model/datagram.rs b/rs/moq-net/src/model/datagram.rs index 42e45474f53..e5f53496471 100644 --- a/rs/moq-net/src/model/datagram.rs +++ b/rs/moq-net/src/model/datagram.rs @@ -26,6 +26,10 @@ //! name's datagram track before, or with, its stream track. //! - The wire never says a name has no datagram track, so a datagram reader of a name with //! only a stream track receives nothing until that track ends. +//! - The wire never says which kind a subscription asks for, so a publisher serves it from +//! the stream track when one is published, and otherwise from whichever kind answers +//! first: a local datagram track answers without waiting for a stream request handler, +//! which need not answer a name it doesn't serve. use std::{ collections::VecDeque, diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index 26eca71a138..f834fdfcc64 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -3798,6 +3798,12 @@ async fn serve_front(task: FrontTask) -> Vec { let Some((instance, asked)) = instances.get(&source).cloned() else { continue; }; + // Route datagram lookups before a requester can see the broadcast, + // which would otherwise find no source to ask. + if datagram_source != Some(source) { + datagram_source = Some(source); + broadcast.serve_datagrams_from(sources.get(&source).cloned()); + } resolved = Some(instance.clone()); if let Ok(mut pending) = request.write() && pending.resolved.is_none() diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index 4aa66e060fe..5540bc2a904 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -4248,6 +4248,12 @@ impl TrackWeak { Some((self.state.try_consume()?, preferences)) } + /// Whether a producer serves the track, rather than a request still waiting for one. + #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))] + pub(super) fn minted(&self) -> bool { + self.state.read().minted() + } + /// Read the cached track without joining its demand. pub(super) fn peek(&self) -> kio::ConsumerWeak { self.state.consume_weak() diff --git a/rs/moq-net/tests/integration/datagram.rs b/rs/moq-net/tests/integration/datagram.rs index dcd32922325..c9cea40e465 100644 --- a/rs/moq-net/tests/integration/datagram.rs +++ b/rs/moq-net/tests/integration/datagram.rs @@ -408,6 +408,71 @@ async fn lite05_and_lite06_finish_a_datagram_track_as_a_stream_subscriber_expect } } +/// Lite-05/06 serve a name from a datagram handler's answer without waiting for the stream +/// handler, which may leave a name it doesn't serve unanswered. +#[kio::test] +async fn lite05_and_lite06_answer_a_datagram_request_beside_a_silent_stream_handler() { + for version in ["moq-lite-05", "moq-lite-06"] { + let chain = Chain::new(&[version]).await; + // Never polled: a stream lookup of the name waits on it for good. + let requests = chain.publication.requests(); + let mut handler = requests.datagrams(); + let mut consumer = chain.remote().await.datagrams(TRACK).unwrap(); + let request = kio::clock::timeout(TIMEOUT, handler.requested()) + .await + .unwrap_or_else(|_| panic!("{version}: the request never reached the handler")) + .unwrap(); + assert_eq!(request.name(), TRACK, "{version}"); + let mut producer = request.accept(timed()); + kio::clock::timeout(TIMEOUT, consumer.info()) + .await + .unwrap_or_else(|_| panic!("{version}: the answer never arrived")) + .unwrap(); + kio::clock::timeout(TIMEOUT, datagram_priority(&producer, Some(0))) + .await + .unwrap_or_else(|_| panic!("{version}: the subscription never reached the publisher")); + + producer.append(millis(1), &b"requested"[..]).unwrap(); + let datagram = recv(&mut consumer).await.unwrap().expect("a datagram"); + assert_eq!(&datagram.payload[..], b"requested", "{version}"); + assert_eq!(datagram.timestamp, Some(millis(1)), "{version}"); + } +} + +/// An old hop answers a datagram lookup for every stream track it carries, so a relay serving +/// an old subscriber keeps a stream track's name a stream track, though that relayed answer +/// may arrive before the stream track's. +#[kio::test] +async fn an_old_subscriber_keeps_a_stream_track_across_mixed_hops() { + for hops in [ + &["moq-lite-06", "moq-lite-07-wip", "moq-lite-06"][..], + &["moq-lite-06", "moq-lite-06"], + ] { + let chain = Chain::new(hops).await; + let mut track = chain + .publication + .create_track(TRACK, moq_net::track::Info::default().with_timescale(Timescale::MILLI)) + .unwrap(); + let remote = chain.remote().await; + let mut subscriber = kio::clock::timeout(TIMEOUT, remote.track(TRACK).unwrap().subscribe(None)) + .await + .expect("subscribe timeout") + .unwrap_or_else(|err| panic!("{hops:?}: {err:?}")); + support::harness::subscribed(&track).await; + track.write_frame(millis(1), &b"frame"[..]).unwrap(); + let mut group = kio::clock::timeout(TIMEOUT, subscriber.recv_group()) + .await + .expect("group timeout") + .unwrap() + .expect("a group"); + assert_eq!( + &group.read_frame().await.unwrap().expect("a frame").payload[..], + b"frame", + "{hops:?}" + ); + } +} + /// A datagram track can't be asked for over a version or transport without datagrams. #[kio::test] async fn a_datagram_track_needs_datagrams() { From f10078b8b2e680cc53655943cc41098a4c3276a8 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 4 Nov 2026 08:38:40 -0800 Subject: [PATCH 8/9] fix(net): keep a relayed broadcast's datagram lookup for the not-found fallback A lite-05/06 lookup marked a relayed broadcast's datagram ask as refused while the stream track was pending, so a stream not-found then skipped the datagram track: a datagram-only track behind a lite-07 upstream never reached an old subscriber through the relay. Leave it unasked instead. Co-Authored-By: Claude Opus 5.5 --- rs/moq-net/src/lite/publisher.rs | 17 +++++++++-------- rs/moq-net/tests/integration/datagram.rs | 13 +++++++++++++ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index 35bee7c59fc..e72ada5a53b 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -2562,8 +2562,8 @@ impl Request for SubscribeServe { struct Legacy { broadcast: crate::broadcast::Consumer, name: String, - /// The name's datagram track, asked for beside the stream track: `None` until asked, and - /// `Some(None)` once refused or not asked, as of a relayed broadcast. + /// The name's datagram track, asked for beside the stream track: `None` until asked, as + /// a relayed broadcast's stays, and `Some(None)` once refused. datagrams: Option>, } @@ -2586,12 +2586,13 @@ impl Legacy { let Some(this) = legacy else { return Poll::Pending; }; - let asked = this.datagrams.get_or_insert_with(|| { - this.broadcast - .has_local_datagrams() - .then(|| this.broadcast.datagrams(&this.name).ok()) - .flatten() - }); + // A relayed broadcast is left unasked, for the stream track's not-found to ask. + if this.datagrams.is_none() && !this.broadcast.has_local_datagrams() { + return Poll::Pending; + } + let asked = this + .datagrams + .get_or_insert_with(|| this.broadcast.datagrams(&this.name).ok()); let Some(consumer) = asked else { return Poll::Pending; }; diff --git a/rs/moq-net/tests/integration/datagram.rs b/rs/moq-net/tests/integration/datagram.rs index c9cea40e465..97e2c74caab 100644 --- a/rs/moq-net/tests/integration/datagram.rs +++ b/rs/moq-net/tests/integration/datagram.rs @@ -439,6 +439,19 @@ async fn lite05_and_lite06_answer_a_datagram_request_beside_a_silent_stream_hand } } +/// A relay serving an old subscriber asks its upstream session for a name's datagram track +/// once the stream track is not found there, as one asks a lite-07 upstream. +#[kio::test] +async fn an_old_subscriber_reaches_a_datagram_track_through_a_lite07_relay() { + let chain = Chain::new(&["moq-lite-07-wip", "moq-lite-06"]).await; + let mut producer = chain.publication.create_datagrams(TRACK, timed()).unwrap(); + let mut consumer = chain.consume(&producer, 2).await; + producer.append(millis(4), &b"relayed"[..]).unwrap(); + let datagram = recv(&mut consumer).await.unwrap().expect("a datagram"); + assert_eq!(&datagram.payload[..], b"relayed"); + assert_eq!(datagram.timestamp, Some(millis(4))); +} + /// An old hop answers a datagram lookup for every stream track it carries, so a relay serving /// an old subscriber keeps a stream track's name a stream track, though that relayed answer /// may arrive before the stream track's. From 063f3a204faf6b964123c0e248abf1427dbc9e88 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 4 Nov 2026 09:10:59 -0800 Subject: [PATCH 9/9] fix(net): ask a late datagram handler once a lite-05/06 stream track is not found A lite-05/06 lookup cached a datagram lookup that failed before any request existed, such as before a datagram handler registered, as a refusal, so a stream track's not-found never asked the handler that registered meanwhile. Keep it unasked; only a handler's refusal is final. Also corrects the lite-05/06 lookup paragraph in the Go, Python and Swift READMEs, and folds moq-c's datagram migration note under one heading, noting that moq_consume_datagrams fails at once when nothing can serve the name. Co-Authored-By: Claude Opus 5.5 --- go/wrapper/README.md | 7 +++--- py/moq-rs/README.md | 7 +++--- rs/moq-c/MIGRATE.md | 6 ++--- rs/moq-net/src/lite/publisher.rs | 20 ++++++++++------ rs/moq-net/tests/integration/datagram.rs | 30 ++++++++++++++++++++++++ swift/README.md | 7 +++--- 6 files changed, 57 insertions(+), 20 deletions(-) diff --git a/go/wrapper/README.md b/go/wrapper/README.md index 0747dcc4a04..b14d4b13156 100644 --- a/go/wrapper/README.md +++ b/go/wrapper/README.md @@ -176,9 +176,10 @@ serve on-demand datagram tracks with `BroadcastRequests.Datagrams()`. Keep payloads well below the path MTU. Delivery requires a datagram-capable transport and lite-05 or newer; there is no stream fallback. -On lite-05/06, an on-demand datagram name reaches its handler only after the stream -lookup reports not-found. Keeping a stream handler alive without rejecting that name -leaves the datagram request pending; lite-07 uses independent requests. +On lite-05/06, a local datagram handler is asked for an on-demand name without waiting +for the stream handler, and answers it unless a stream track of that name is published. A +relayed broadcast asks its upstream for the datagram track only once the stream track is +not found. lite-07 uses independent requests. ## Versioning diff --git a/py/moq-rs/README.md b/py/moq-rs/README.md index 1fdb00b31e6..cf4c4c2dd08 100644 --- a/py/moq-rs/README.md +++ b/py/moq-rs/README.md @@ -303,6 +303,7 @@ reads with `await recv()` or async iteration. Demand is aggregate subscriber `pr Keep payloads below the path MTU. Delivery needs a datagram-capable transport and lite-05 or newer, without a stream fallback. Stream tracks of the same name are independent. -On lite-05/06, an on-demand datagram name reaches its handler only after the stream -lookup reports not-found. Keeping a stream handler alive without rejecting that name -leaves the datagram request pending; lite-07 uses independent requests. +On lite-05/06, a local datagram handler is asked for an on-demand name without waiting +for the stream handler, and answers it unless a stream track of that name is published. A +relayed broadcast asks its upstream for the datagram track only once the stream track is +not found. lite-07 uses independent requests. diff --git a/rs/moq-c/MIGRATE.md b/rs/moq-c/MIGRATE.md index a258ceea6c9..143245df61b 100644 --- a/rs/moq-c/MIGRATE.md +++ b/rs/moq-c/MIGRATE.md @@ -6,16 +6,14 @@ How to update your code for each breaking change, newest first. ### Separate datagram tracks +Create a separate producer with `moq_publish_datagrams` and `moq_datagram_info`; replace `moq_publish_track_datagram` with `moq_publish_datagrams_append` on that handle, or `moq_publish_datagrams_insert` for an explicit sequence. `moq_consume_datagrams` now takes a subscriber priority before its callback and never subscribes to a stream track. Use `moq_publish_datagrams_demand` and `moq_datagram_demand_priority` for aggregate priority, and `moq_publish_datagrams_requests` / `moq_datagram_request_accept` for on-demand publishing. Finish or abort datagram producers separately. A zeroed datagram info is untimed, unlike the microsecond default of stream-track info. `moq_consume_datagrams` returns a negative code at once when the broadcast has neither the datagram track nor a datagram request handler, and a remote name without one ends its callback with a not-found error. + ### Authored tracks default to a zero max age ([#7729](https://github.com/moq-dev/moq/pull/7729)) A NULL or zeroed `moq_track_info` now advertises a zero max age, serving only the live edge, instead of no publisher limit. `max_age_present` is gone and `max_age_us` always applies: drop the assignment where you set it to true, and set the new `max_age_unlimited`, which ignores `max_age_us`, where you relied on it being false for no limit. Recompile against the new header, since an old binary's `max_age_present` byte now reads as `max_age_unlimited`, and zero-initialize the struct (`moq_track_info info = {0};`) or assign every member, since an indeterminate member is undefined behavior. -### Datagrams are a track of their own - -Create a separate producer with `moq_publish_datagrams` and `moq_datagram_info`; replace `moq_publish_track_datagram` with `moq_publish_datagrams_append` on that handle, or `moq_publish_datagrams_insert` for an explicit sequence. `moq_consume_datagrams` now takes a subscriber priority before its callback and never subscribes to a stream track. Use `moq_publish_datagrams_demand` and `moq_datagram_demand_priority` for aggregate priority, and `moq_publish_datagrams_requests` / `moq_datagram_request_accept` for on-demand publishing. Finish or abort datagram producers separately. A zeroed datagram info is untimed, unlike the microsecond default of stream-track info. - ### JSON writes refuse a NULL timestamp ([#7691](https://github.com/moq-dev/moq/pull/7691)) `moq_publish_json_snapshot_update`, `moq_publish_json_stream_append`, `moq_publish_json_window_push`, and `moq_publish_json_window_pop` fail with `MOQ_ERROR_INVALID_POINTER` and publish nothing on a NULL `timestamp`, instead of stamping the broadcast clock's current time. diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index e72ada5a53b..15aae6cf6d1 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -2563,7 +2563,7 @@ struct Legacy { broadcast: crate::broadcast::Consumer, name: String, /// The name's datagram track, asked for beside the stream track: `None` until asked, as - /// a relayed broadcast's stays, and `Some(None)` once refused. + /// a relayed broadcast's stays, and `Some(None)` once a handler refused it. datagrams: Option>, } @@ -2586,13 +2586,19 @@ impl Legacy { let Some(this) = legacy else { return Poll::Pending; }; - // A relayed broadcast is left unasked, for the stream track's not-found to ask. - if this.datagrams.is_none() && !this.broadcast.has_local_datagrams() { - return Poll::Pending; + if this.datagrams.is_none() { + // A relayed broadcast is left unasked, for the stream track's not-found to ask. + if !this.broadcast.has_local_datagrams() { + return Poll::Pending; + } + // So is a name nothing can answer yet, such as before a handler exists: only a + // handler's refusal is final. + let Ok(consumer) = this.broadcast.datagrams(&this.name) else { + return Poll::Pending; + }; + this.datagrams = Some(Some(consumer)); } - let asked = this - .datagrams - .get_or_insert_with(|| this.broadcast.datagrams(&this.name).ok()); + let asked = this.datagrams.as_mut().expect("asked above"); let Some(consumer) = asked else { return Poll::Pending; }; diff --git a/rs/moq-net/tests/integration/datagram.rs b/rs/moq-net/tests/integration/datagram.rs index 97e2c74caab..f9a6fe309c7 100644 --- a/rs/moq-net/tests/integration/datagram.rs +++ b/rs/moq-net/tests/integration/datagram.rs @@ -439,6 +439,36 @@ async fn lite05_and_lite06_answer_a_datagram_request_beside_a_silent_stream_hand } } +/// A datagram handler that registers while a lite-06 name's stream lookup is pending is +/// still asked for the name once the stream track is not found. +#[kio::test] +async fn lite06_asks_a_late_datagram_handler_once_the_stream_track_is_not_found() { + let chain = Chain::new(&["moq-lite-06"]).await; + let mut requests = chain.publication.requests(); + let mut consumer = chain.remote().await.datagrams(TRACK).unwrap(); + let stream = kio::clock::timeout(TIMEOUT, requests.requested_track()) + .await + .expect("the stream lookup never reached the publisher") + .unwrap(); + let mut handler = requests.datagrams(); + stream.reject(Error::NotFound); + let request = kio::clock::timeout(TIMEOUT, handler.requested()) + .await + .expect("the datagram handler was never asked") + .unwrap(); + let mut producer = request.accept(timed()); + kio::clock::timeout(TIMEOUT, consumer.info()) + .await + .expect("info timeout") + .expect("the handler answered"); + kio::clock::timeout(TIMEOUT, datagram_priority(&producer, Some(0))) + .await + .expect("the subscription never reached the publisher"); + producer.append(millis(2), &b"late"[..]).unwrap(); + let datagram = recv(&mut consumer).await.unwrap().expect("a datagram"); + assert_eq!(&datagram.payload[..], b"late"); +} + /// A relay serving an old subscriber asks its upstream session for a name's datagram track /// once the stream track is not found there, as one asks a lite-07 upstream. #[kio::test] diff --git a/swift/README.md b/swift/README.md index 0a559e9a643..e7a0d9f1373 100644 --- a/swift/README.md +++ b/swift/README.md @@ -86,9 +86,10 @@ assigns a sequence, `insert(_:)` preserves one, and `DatagramConsumer.recv()` or Keep payloads below the path MTU. Delivery needs a datagram-capable transport and lite-05 or newer, with no stream fallback. A stream track of the same name is independent. -On lite-05/06, an on-demand datagram name reaches its handler only after the stream -lookup reports not-found. Keeping a stream handler alive without rejecting that name -leaves the datagram request pending; lite-07 uses independent requests. +On lite-05/06, a local datagram handler is asked for an on-demand name without waiting +for the stream handler, and answers it unless a stream track of that name is published. A +relayed broadcast asks its upstream for the datagram track only once the stream track is +not found. lite-07 uses independent requests. JSON tracks live under the `Json` namespace, mirroring the `moq-json` crate, and carry your own `Codable` types with the framing handled for you. Each type wraps a track: a producer takes over a