diff --git a/cpp/moq/include/moq/moq.hpp b/cpp/moq/include/moq/moq.hpp index 92075cef5b3..df911cce4f5 100644 --- a/cpp/moq/include/moq/moq.hpp +++ b/cpp/moq/include/moq/moq.hpp @@ -5,6 +5,7 @@ #include +#include #include #include #include @@ -192,6 +193,24 @@ inline expected log_level(const std::string &level) { return moq_log_level(level); } +// Mints a fresh publisher epoch, ordered newest last. Announce one per run in Route::epoch, +// so viewers see a restart as a new broadcast instead of a stalled one. +inline std::string mint_epoch() { + return moq_mint_epoch(); +} + +// The wall-clock time an epoch encodes, to the millisecond. Errors unless it is a UUIDv7. +// Millisecond ticks hold every 48-bit UUIDv7 time, where system_clock's nanoseconds overflow in 2262. +inline expected> +epoch_time(const std::string &epoch) { + auto ms = moq_epoch_time_ms(epoch); + if (!ms) { + return unexpected(std::move(ms).error()); + } + return std::chrono::time_point( + std::chrono::milliseconds(static_cast(*ms))); +} + #ifdef MOQ_COROUTINES namespace detail { diff --git a/cpp/moq/test/probe.cpp b/cpp/moq/test/probe.cpp index 6cde2edd613..f67593c8b45 100644 --- a/cpp/moq/test/probe.cpp +++ b/cpp/moq/test/probe.cpp @@ -109,6 +109,13 @@ int main() { // It prints the message Rust's Display gives. CHECK(fingerprints.error().to_string() == "bind: not listening; call listen() first"); + // An epoch's time keeps every 48-bit millisecond, past where system_clock's nanoseconds wrap. + CHECK(ok(moq::epoch_time("018bcfe5-6800-7000-8000-000000000000"), "epoch_time").time_since_epoch() == + std::chrono::milliseconds(1700000000000)); + CHECK(ok(moq::epoch_time("ffffffff-ffff-7000-8000-000000000000"), "epoch_time").time_since_epoch() == + std::chrono::milliseconds(0xffffffffffff)); + CHECK(!moq::epoch_time("not-an-epoch")); + // Publisher: a server whose origin serves one broadcast with one track. auto origin = moq::OriginProducer::init({}); auto broadcast = ok(origin->create_broadcast("probe"), "create_broadcast"); diff --git a/cpp/obs/src/moq-output.cpp b/cpp/obs/src/moq-output.cpp index ead595aa9aa..9ae0466914f 100644 --- a/cpp/obs/src/moq-output.cpp +++ b/cpp/obs/src/moq-output.cpp @@ -239,7 +239,7 @@ void MoQOutput::OnConnect(const std::shared_ptr ¤t, moq::expected auto elapsed = std::chrono::steady_clock::now() - current->started; auto ms = static_cast(std::chrono::duration_cast(elapsed).count()); - const int connect_epoch = static_cast((*result)->epoch()); + const int connects = static_cast((*result)->connects()); current->session = *result; current->connected = true; @@ -256,7 +256,7 @@ void MoQOutput::OnConnect(const std::shared_ptr ¤t, moq::expected // Clamp sub-millisecond connects to 1 so that sentinel stays honest. connect_time_ms = ms > 0 ? ms : 1; - LOG_INFO("MoQ session connected (%d ms, epoch %d): %s", ms, connect_epoch, MoQRedactUrl(current->url).c_str()); + LOG_INFO("MoQ session connected (%d ms, connect %d): %s", ms, connects, MoQRedactUrl(current->url).c_str()); WatchStatus(current); } @@ -282,7 +282,7 @@ void MoQOutput::OnStatus(const std::shared_ptr ¤t, moq::expected< switch (*result) { case moq::ConnectionStatus::kConnected: { - const int connect_epoch = static_cast(current->session->epoch()); + const int connects = static_cast(current->session->connects()); current->live = true; { std::lock_guard lock(mutex); @@ -290,7 +290,7 @@ void MoQOutput::OnStatus(const std::shared_ptr ¤t, moq::expected< last_failure_code = MoQError::None; last_failure_reason.clear(); } - LOG_INFO("MoQ session reconnected (epoch %d): %s", connect_epoch, MoQRedactUrl(current->url).c_str()); + LOG_INFO("MoQ session reconnected (connect %d): %s", connects, MoQRedactUrl(current->url).c_str()); break; } case moq::ConnectionStatus::kDisconnected: { @@ -472,8 +472,8 @@ int MoQOutput::GetReconnectCount() } // Read live rather than tracked from status(), which coalesces a drop that // reconnects before it is asked again. - const uint64_t connect_epoch = current ? current->epoch() : 0; - return connect_epoch > 1 ? static_cast(connect_epoch - 1) : 0; + const uint64_t connects = current ? current->connects() : 0; + return connects > 1 ? static_cast(connects - 1) : 0; } bool MoQOutput::IsLiveSession() diff --git a/cpp/obs/src/moq-output.h b/cpp/obs/src/moq-output.h index ce7d30b30ba..19969442221 100644 --- a/cpp/obs/src/moq-output.h +++ b/cpp/obs/src/moq-output.h @@ -51,7 +51,7 @@ class MoQOutput { }; bool TryGetConnectionStats(ConnectionStats *out); - // Successful (re)connects after the first for this Start(); 0 until epoch >= 2. + // Successful (re)connects after the first for this Start(); 0 until connects() >= 2. int GetReconnectCount(); // True while the current Start() attempt has an open MoQ session. diff --git a/cpp/obs/src/moq-source.cpp b/cpp/obs/src/moq-source.cpp index 44e97d95cae..706cfaf65dd 100644 --- a/cpp/obs/src/moq-source.cpp +++ b/cpp/obs/src/moq-source.cpp @@ -446,7 +446,7 @@ static void moq_source_on_connect(struct moq_source *ctx, const std::shared_ptr< } conn->session = *result; - LOG_INFO("MoQ session connected (epoch %llu)", (unsigned long long)conn->session->epoch()); + LOG_INFO("MoQ session connected (connect %llu)", (unsigned long long)conn->session->connects()); moq_source_watch_status(ctx, conn); // Wait for the broadcast to be announced. Announcements arrive over the session @@ -521,7 +521,7 @@ static void moq_source_on_status(struct moq_source *ctx, const std::shared_ptrsession->epoch()); + LOG_INFO("MoQ session reconnected (connect %llu)", (unsigned long long)conn->session->connects()); break; case moq::ConnectionStatus::kDisconnected: LOG_WARNING("MoQ session dropped, reconnecting"); diff --git a/dart/moq/README.md b/dart/moq/README.md index 08d2f7db99e..c3bfa3b0e1d 100644 --- a/dart/moq/README.md +++ b/dart/moq/README.md @@ -10,10 +10,14 @@ final announced = connection.announced( options: const AnnounceOptions(prefix: 'live/', filter: '*/camera'), ); await for (final event in announced.updates()) { - if (event is AnnounceEventStart) { - // Prefix stays origin-relative; captures reports wildcard matches. - print(event.announce.prefix); - print(event.announce.captures); + // A restart is a new publisher run at the same path: request it again. + switch (event) { + case AnnounceEventStart(:final announce) || + AnnounceEventRestart(:final announce): + // Prefix stays origin-relative; captures reports wildcard matches. + print(announce.prefix); + print(announce.captures); + default: } } ``` @@ -32,7 +36,7 @@ final broadcast = server.createBroadcast('live'); broadcast.announce(route: MoqRoute()); // unannounced broadcasts are invisible await for (final request in server.requests()) { final session = await request.accept(); - print(session.epoch()); + print(session.connects()); } ``` diff --git a/dart/moq/lib/moq.dart b/dart/moq/lib/moq.dart index f034dd7e015..7bdaaaf25da 100644 --- a/dart/moq/lib/moq.dart +++ b/dart/moq/lib/moq.dart @@ -6,4 +6,5 @@ export 'package:moq_ffi/moq_ffi.dart'; export 'src/aliases.dart'; export 'src/client.dart'; export 'src/durations.dart'; +export 'src/epoch.dart'; export 'src/server.dart'; diff --git a/dart/moq/lib/src/aliases.dart b/dart/moq/lib/src/aliases.dart index ea9d88c7061..e98f7ca7f33 100644 --- a/dart/moq/lib/src/aliases.dart +++ b/dart/moq/lib/src/aliases.dart @@ -53,7 +53,7 @@ typedef AnnouncedBroadcast = MoqAnnouncedBroadcast; typedef Announce = MoqAnnounce; /// What an [AnnounceConsumer] yields: [AnnounceEventStart], -/// [AnnounceEventUpdate], or [AnnounceEventEnd]. +/// [AnnounceEventUpdate], [AnnounceEventEnd], or [AnnounceEventRestart]. typedef AnnounceEvent = MoqAnnounceEvent; /// A route now covers the prefix; the stream had none there. @@ -65,6 +65,10 @@ typedef AnnounceEventUpdate = UpdateMoqAnnounceEvent; /// No route covers the prefix any more; carries its last route. typedef AnnounceEventEnd = EndMoqAnnounceEvent; +/// Another publisher instance now serves the prefix: drop what was resolved +/// under it and request afresh. +typedef AnnounceEventRestart = RestartMoqAnnounceEvent; + /// The write side of a broadcast: publish tracks into it. typedef BroadcastProducer = MoqBroadcastProducer; diff --git a/dart/moq/lib/src/client.dart b/dart/moq/lib/src/client.dart index bfc239de7a2..0e811ce8f88 100644 --- a/dart/moq/lib/src/client.dart +++ b/dart/moq/lib/src/client.dart @@ -178,9 +178,9 @@ final class Moq { Future requestBroadcast(String path) => session.consume().requestBroadcast(path: path); - /// The connection epoch: 1 for the connect that built this session, one more + /// How many times this session has connected: 1 for the connect that built it, one more /// on each reconnect. A server-accepted session stays at 1. - int get epoch => session.epoch(); + int get connects => session.connects(); /// The session's bandwidth allocator. /// diff --git a/dart/moq/lib/src/epoch.dart b/dart/moq/lib/src/epoch.dart new file mode 100644 index 00000000000..d628417c0b5 --- /dev/null +++ b/dart/moq/lib/src/epoch.dart @@ -0,0 +1,14 @@ +import 'package:moq_ffi/moq_ffi.dart'; + +/// Mint a fresh publisher epoch from the wall clock and secure randomness, +/// ordered newest last. Mint one per publisher run and announce it in +/// `MoqRoute.epoch`, so viewers see a restart as a new broadcast instead of a +/// stalled one. +String mintEpoch() => moqMintEpoch(); + +/// The UTC wall-clock time [epoch] encodes, to the millisecond. Throws unless +/// it is a lowercase hyphenated UUIDv7. +DateTime epochTime(String epoch) => DateTime.fromMillisecondsSinceEpoch( + moqEpochTimeMs(epoch: epoch), + isUtc: true, +); diff --git a/dart/moq/test/moq_test.dart b/dart/moq/test/moq_test.dart index c8ec6754f00..b419019357a 100644 --- a/dart/moq/test/moq_test.dart +++ b/dart/moq/test/moq_test.dart @@ -231,6 +231,30 @@ void main() { announced.dispose(); }); + test('a new epoch restarts announce consumers', () async { + final origin = MoqOriginProducer(config: MoqOriginConfig()); + final announced = origin.consume().announced(config: MoqAnnounceConfig()); + final broadcast = origin.createBroadcast(path: 'epoch'); + + final first = mintEpoch(); + expect( + epochTime('018bcfe5-6800-7000-8000-000000000000'), + DateTime.utc(2023, 11, 14, 22, 13, 20), + ); + broadcast.announce(route: MoqRoute(epoch: first)); + final start = await nextRoute(announced) as AnnounceEventStart; + expect(start.announce.route.epoch, first); + + final second = mintEpoch(); + broadcast.announce(route: MoqRoute(epoch: second)); + final restart = await nextRoute(announced) as AnnounceEventRestart; + expect(restart.announce.route.epoch, second); + + expect(() => epochTime('not-an-epoch'), throwsA(isA())); + announced.cancel(); + announced.dispose(); + }); + test('announced pattern reports captures', () async { final origin = MoqOriginProducer(config: MoqOriginConfig()); final announced = origin.consume().announced( diff --git a/dart/moq_ffi/lib/src/moq.dart b/dart/moq_ffi/lib/src/moq.dart index fb5544322f6..6aa3ba5a2bb 100644 --- a/dart/moq_ffi/lib/src/moq.dart +++ b/dart/moq_ffi/lib/src/moq.dart @@ -1911,7 +1911,13 @@ class MoqRoute { final List hops; final int cost; final bool anonymous; - MoqRoute({this.hops = const [], this.cost = 0, this.anonymous = false}); + final String? epoch; + MoqRoute({ + this.hops = const [], + this.cost = 0, + this.anonymous = false, + this.epoch = null, + }); } class FfiConverterMoqRoute { @@ -1936,8 +1942,13 @@ class FfiConverterMoqRoute { ); final anonymous = anonymous_lifted.value; new_offset += anonymous_lifted.bytesRead; + final epoch_lifted = FfiConverterOptionalString.read( + Uint8List.view(buf.buffer, new_offset), + ); + final epoch = epoch_lifted.value; + new_offset += epoch_lifted.bytesRead; return LiftRetVal( - MoqRoute(hops: hops, cost: cost, anonymous: anonymous), + MoqRoute(hops: hops, cost: cost, anonymous: anonymous, epoch: epoch), new_offset - buf.offsetInBytes, ); } @@ -1947,6 +1958,7 @@ class FfiConverterMoqRoute { FfiConverterSequenceUInt64.allocationSize(value.hops) + FfiConverterUInt64.allocationSize(value.cost) + FfiConverterBool.allocationSize(value.anonymous) + + FfiConverterOptionalString.allocationSize(value.epoch) + 0; final buf = Uint8List(total_length); write(value, buf); @@ -1967,6 +1979,10 @@ class FfiConverterMoqRoute { value.anonymous, Uint8List.view(buf.buffer, new_offset), ); + new_offset += FfiConverterOptionalString.write( + value.epoch, + Uint8List.view(buf.buffer, new_offset), + ); return new_offset - buf.offsetInBytes; } @@ -1974,6 +1990,7 @@ class FfiConverterMoqRoute { return FfiConverterSequenceUInt64.allocationSize(value.hops) + FfiConverterUInt64.allocationSize(value.cost) + FfiConverterBool.allocationSize(value.anonymous) + + FfiConverterOptionalString.allocationSize(value.epoch) + 0; } } @@ -3079,18 +3096,24 @@ class FfiConverterMoqException { lifted.bytesRead - subview.offsetInBytes + 4, ); case 27: - final lifted = UnresolvableBroadcastMoqException.read(subview); + final lifted = InvalidEpochMoqException.read(subview); return LiftRetVal( lifted.value, lifted.bytesRead - subview.offsetInBytes + 4, ); case 28: - final lifted = LogMoqException.read(subview); + final lifted = UnresolvableBroadcastMoqException.read(subview); return LiftRetVal( lifted.value, lifted.bytesRead - subview.offsetInBytes + 4, ); case 29: + final lifted = LogMoqException.read(subview); + return LiftRetVal( + lifted.value, + lifted.bytesRead - subview.offsetInBytes + 4, + ); + case 30: final lifted = ConfigMoqException.read(subview); return LiftRetVal( lifted.value, @@ -4005,6 +4028,44 @@ class InvalidPatternMoqException extends MoqException { } } +class InvalidEpochMoqException extends MoqException { + final String reason; + InvalidEpochMoqException(String this.reason); + InvalidEpochMoqException._(String this.reason); + static LiftRetVal read(Uint8List buf) { + int new_offset = buf.offsetInBytes; + final reason_lifted = FfiConverterString.read( + Uint8List.view(buf.buffer, new_offset), + ); + final reason = reason_lifted.value; + new_offset += reason_lifted.bytesRead; + return LiftRetVal(InvalidEpochMoqException._(reason), new_offset); + } + + @override + RustBuffer lower() { + final buf = Uint8List(allocationSize()); + write(buf); + return toRustBuffer(buf); + } + + @override + int allocationSize() { + return FfiConverterString.allocationSize(reason) + 4; + } + + @override + int write(Uint8List buf) { + buf.buffer.asByteData(buf.offsetInBytes).setInt32(0, 27); + int new_offset = buf.offsetInBytes + 4; + new_offset += FfiConverterString.write( + reason, + Uint8List.view(buf.buffer, new_offset), + ); + return new_offset; + } +} + class UnresolvableBroadcastMoqException extends MoqException { final String reason; UnresolvableBroadcastMoqException(String this.reason); @@ -4033,7 +4094,7 @@ class UnresolvableBroadcastMoqException extends MoqException { @override int write(Uint8List buf) { - buf.buffer.asByteData(buf.offsetInBytes).setInt32(0, 27); + buf.buffer.asByteData(buf.offsetInBytes).setInt32(0, 28); int new_offset = buf.offsetInBytes + 4; new_offset += FfiConverterString.write( reason, @@ -4071,7 +4132,7 @@ class LogMoqException extends MoqException { @override int write(Uint8List buf) { - buf.buffer.asByteData(buf.offsetInBytes).setInt32(0, 28); + buf.buffer.asByteData(buf.offsetInBytes).setInt32(0, 29); int new_offset = buf.offsetInBytes + 4; new_offset += FfiConverterString.write( reason, @@ -4109,7 +4170,7 @@ class ConfigMoqException extends MoqException { @override int write(Uint8List buf) { - buf.buffer.asByteData(buf.offsetInBytes).setInt32(0, 29); + buf.buffer.asByteData(buf.offsetInBytes).setInt32(0, 30); int new_offset = buf.offsetInBytes + 4; new_offset += FfiConverterString.write( reason, @@ -8828,8 +8889,8 @@ abstract class MoqSessionInterface { MoqBandwidth bandwidth(); void cancel({required int code}); Future closed(); + int connects(); MoqOriginConsumer consume(); - int epoch(); MoqOriginProducer publish(); Future shutdown(); MoqConnectionStats stats(); @@ -8891,24 +8952,24 @@ class MoqSession implements MoqSessionInterface { ); } - MoqOriginConsumer consume() { + int connects() { return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqsession_consume( + (status) => uniffi_moq_ffi_fn_method_moqsession_connects( uniffiClonePointer(), status, ), - FfiConverterMoqOriginConsumer.lift, + FfiConverterUInt64.lift, null, ); } - int epoch() { + MoqOriginConsumer consume() { return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqsession_epoch( + (status) => uniffi_moq_ffi_fn_method_moqsession_consume( uniffiClonePointer(), status, ), - FfiConverterUInt64.lift, + FfiConverterMoqOriginConsumer.lift, null, ); } @@ -10333,6 +10394,25 @@ void moqLogLevel({required String level}) { }, moqExceptionErrorHandler); } +int moqEpochTimeMs({required String epoch}) { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_func_moq_epoch_time_ms( + FfiConverterString.lower(epoch), + status, + ), + FfiConverterUInt64.lift, + moqExceptionErrorHandler, + ); +} + +String moqMintEpoch() { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_func_moq_mint_epoch(status), + FfiConverterString.lift, + null, + ); +} + @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) @@ -12202,18 +12282,18 @@ external Pointer uniffi_moq_ffi_fn_method_moqsession_closed( Pointer ptr, ); -@Native Function(Pointer, Pointer)>( +@Native, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_method_moqsession_consume( +external int uniffi_moq_ffi_fn_method_moqsession_connects( Pointer ptr, Pointer uniffiStatus, ); -@Native, Pointer)>( +@Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external int uniffi_moq_ffi_fn_method_moqsession_epoch( +external Pointer uniffi_moq_ffi_fn_method_moqsession_consume( Pointer ptr, Pointer uniffiStatus, ); @@ -12260,6 +12340,19 @@ external void uniffi_moq_ffi_fn_func_moq_log_level( Pointer uniffiStatus, ); +@Native)>( + assetId: _uniffiAssetId, +) +external int uniffi_moq_ffi_fn_func_moq_epoch_time_ms( + RustBuffer epoch, + Pointer uniffiStatus, +); + +@Native)>(assetId: _uniffiAssetId) +external RustBuffer uniffi_moq_ffi_fn_func_moq_mint_epoch( + Pointer uniffiStatus, +); + @Native< Void Function( Pointer, @@ -12587,6 +12680,12 @@ external void ffi_moq_ffi_rust_future_complete_void( @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_func_moq_log_level(); +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_func_moq_epoch_time_ms(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_func_moq_mint_epoch(); + @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqbandwidth_reserve(); @@ -12999,10 +13098,10 @@ external int uniffi_moq_ffi_checksum_method_moqsession_cancel(); external int uniffi_moq_ffi_checksum_method_moqsession_closed(); @Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqsession_consume(); +external int uniffi_moq_ffi_checksum_method_moqsession_connects(); @Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqsession_epoch(); +external int uniffi_moq_ffi_checksum_method_moqsession_consume(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqsession_publish(); @@ -13096,6 +13195,12 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_func_moq_log_level() != 24625) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } + if (uniffi_moq_ffi_checksum_func_moq_epoch_time_ms() != 13125) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_func_moq_mint_epoch() != 34550) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } if (uniffi_moq_ffi_checksum_method_moqbandwidth_reserve() != 60458) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } @@ -13355,7 +13460,7 @@ void _checkApiChecksums() { 54021) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqorigindynamic_update() != 7304) { + if (uniffi_moq_ffi_checksum_method_moqorigindynamic_update() != 15163) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqoriginproducer_consume() != 52357) { @@ -13514,7 +13619,7 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqclient_cancel() != 29949) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqclient_connect() != 61750) { + if (uniffi_moq_ffi_checksum_method_moqclient_connect() != 18055) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqsession_bandwidth() != 8006) { @@ -13526,10 +13631,10 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqsession_closed() != 7901) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqsession_consume() != 57909) { + if (uniffi_moq_ffi_checksum_method_moqsession_connects() != 18791) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqsession_epoch() != 32695) { + if (uniffi_moq_ffi_checksum_method_moqsession_consume() != 57909) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqsession_publish() != 15240) { diff --git a/doc/lib/cpp/index.md b/doc/lib/cpp/index.md index c9d81c0b434..043767dd08a 100644 --- a/doc/lib/cpp/index.md +++ b/doc/lib/cpp/index.md @@ -115,7 +115,9 @@ ok(audio->write_frame({packet, 20'000})); moq::VideoEncoderOutput output{moq::VideoCodec::kH264, "camera", std::nullopt, std::nullopt, moq::VideoEncoderKind::kAuto{}}; auto video = ok(broadcast->encode_video({moq::VideoPixelFormat::kRgba, 1280, 720, 30}, output, nullptr)); ok(video->write({0, rgba})); -ok(broadcast->announce({})); +moq::Route route; +route.epoch = moq::mint_epoch(); // a fresh epoch per run +ok(broadcast->announce(route)); ok(broadcast->close()); // keep the producer alive while publishing, then close explicitly ``` diff --git a/doc/lib/dart/index.md b/doc/lib/dart/index.md index 18b326fbb6a..359acf0670d 100644 --- a/doc/lib/dart/index.md +++ b/doc/lib/dart/index.md @@ -37,9 +37,13 @@ moq ) .updates() .listen((event) { - if (event is AnnounceEventStart) { - print(event.announce.prefix); - print(event.announce.captures); + // A restart is a new publisher run at the same path: request it again. + switch (event) { + case AnnounceEventStart(:final announce) || + AnnounceEventRestart(:final announce): + print(announce.prefix); + print(announce.captures); + default: } }); final broadcast = await moq.requestBroadcast('live/camera'); @@ -54,7 +58,7 @@ final track = mine.publishTrack(name: 'video', info: null); final group = track.appendGroup(); group.writeFrame(frame: Frame(payload: bytes, timestampUs: 0)); group.finish(); -mine.announce(route: MoqRoute()); +mine.announce(route: MoqRoute(epoch: mintEpoch())); // a fresh epoch per run track.finish(); mine.close(); diff --git a/doc/lib/go/index.md b/doc/lib/go/index.md index 94b9d45180f..706cf5c58e9 100644 --- a/doc/lib/go/index.md +++ b/doc/lib/go/index.md @@ -45,13 +45,18 @@ for event, err := range announced.All(ctx) { if moq.IsShutdown(err) { break } log.Fatal(err) } - ann, ok := event.(moq.AnnounceEventStart) - if !ok { + var ann moq.Announce + switch event := event.(type) { + case moq.AnnounceEventStart: + ann = event.Announce + case moq.AnnounceEventRestart: // a new publisher run at the same path: request it again + ann = event.Announce + default: continue // AnnounceEventUpdate or AnnounceEventEnd } // Prefix stays origin-relative; Captures reports what each wildcard matched. - fmt.Printf("captures: %v\n", ann.Announce.Captures) - broadcast, err := client.RequestBroadcast(ctx, ann.Announce.Prefix) + fmt.Printf("captures: %v\n", ann.Captures) + broadcast, err := client.RequestBroadcast(ctx, ann.Prefix) if err != nil { log.Fatal(err) } @@ -81,7 +86,8 @@ video, _ := broadcast.EncodeVideo( nil, ) _ = video.Write(moq.VideoFrame{TimestampUs: pts, Data: rgba}) -_ = broadcast.Announce(moq.Route{}) +epoch := moq.MintEpoch() // a fresh epoch per run +_ = broadcast.Announce(moq.Route{Epoch: &epoch}) _ = audio.Finish() _ = video.Finish() broadcast.Close() // keep the producer reachable while publishing, then close explicitly diff --git a/doc/lib/kt/index.md b/doc/lib/kt/index.md index cf6f1745d1f..50609f3ed37 100644 --- a/doc/lib/kt/index.md +++ b/doc/lib/kt/index.md @@ -33,10 +33,15 @@ import dev.moq.media.* // Subscribe. The Flow is live, so run it in its own coroutine. Moq.connect("https://relay.example.com", ClientConfig(tls = ClientTls(roots = listOf("ca.pem")))).use { moq -> moq.announced(AnnounceConfig(prefix = "live/", filter = "*/camera")).updates().collect { event -> - if (event !is AnnounceEventStart) return@collect // Update or End + // A restart is a new publisher run at the same path: request it again. + val announce = when (event) { + is AnnounceEventStart -> event.announce + is AnnounceEventRestart -> event.announce + else -> return@collect // Update or End + } // Prefixes stay origin-relative; captures reports what each wildcard matched. - println(event.announce.captures) - val broadcast = moq.requestBroadcast(event.announce.prefix) + println(announce.captures) + val broadcast = moq.requestBroadcast(announce.prefix) println(catalog(broadcast)) } } @@ -56,7 +61,7 @@ Moq.connect("https://relay.example.com").use { moq -> VideoEncoderOutput(codec = VideoCodec.H264, track = "camera", bitrate = null, gop = null, kind = autoEncoder), ) video.write(VideoFrame(timestampUs = pts, data = rgba)) - broadcast.announce(Route()) + broadcast.announce(Route(epoch = mintEpoch())) // a fresh epoch per run audio.finish() video.finish() broadcast.end() diff --git a/doc/lib/py/index.md b/doc/lib/py/index.md index 91e4da49bb8..a6f1338dd29 100644 --- a/doc/lib/py/index.md +++ b/doc/lib/py/index.md @@ -30,7 +30,8 @@ async def main(): async with moq.Client("https://cdn.moq.dev/anon") as client: # The filter is relative to the literal prefix; prefixes stay origin-relative. async for event in client.announced("live/", filter="*/camera"): - if not isinstance(event, moq.AnnounceEventStart): + # A restart is a new publisher run at the same path: request it again. + if not isinstance(event, (moq.AnnounceEventStart, moq.AnnounceEventRestart)): continue # AnnounceEventUpdate or AnnounceEventEnd announcement = event.announce print(announcement.captures) # what * matched, or None for a partial overlap @@ -73,7 +74,7 @@ async def main(): status = moq.json.SnapshotProducer(broadcast, broadcast.publish_track("status"), compression=True) status.update({"state": "live", "viewers": 42}) - broadcast.announce() + broadcast.announce(moq.Route(epoch=moq.mint_epoch())) # a fresh epoch per run audio.finish() video.finish() events.finish() diff --git a/doc/lib/swift/index.md b/doc/lib/swift/index.md index e4803e4a1f5..84de1787c9c 100644 --- a/doc/lib/swift/index.md +++ b/doc/lib/swift/index.md @@ -35,7 +35,12 @@ let client = try Client() let session = try await client.connect(to: "https://relay.example.com") for try await event in try session.consume.announced(prefix: "live/", filter: "*/camera") { - guard case .start(let announcement) = event else { continue } // .update or .end + // A restart is a new publisher run at the same path: request it again. + let announcement: Announce + switch event { + case .start(let started), .restart(let started): announcement = started + default: continue // .update or .end + } // Prefixes stay origin-relative; captures reports what each wildcard matched. print(announcement.captures ?? []) let broadcast = try await session.consume.requestBroadcast(path: announcement.prefix) @@ -58,7 +63,7 @@ let video = try broadcast.encodeVideo( output: VideoEncoderOutput(codec: .h264, track: "camera", kind: .auto) ) try video.write(VideoFrame(timestampUs: pts, data: rgba)) -try broadcast.announce() +try broadcast.announce(route: Route(epoch: mintEpoch())) // a fresh epoch per run try audio.finish() try video.finish() try broadcast.close() diff --git a/doc/setup/upgrade.md b/doc/setup/upgrade.md index 53ee0a6f7b4..223f9a460a0 100644 --- a/doc/setup/upgrade.md +++ b/doc/setup/upgrade.md @@ -34,6 +34,14 @@ These land with the next breaking release, not the 2026-09-23 train. moq-lite 06 and older and moq-transport. moq-lite 07 adds `ANNOUNCE_RESTART` (0x3), and lite-06's `ANNOUNCE_RESTART` is named `ANNOUNCE_UPDATE`, as it always meant. +- **"Epoch" means only the publisher epoch.** The reconnect counter is + `connects()`: `moq_tokio::Connection::epoch()` and moq-ffi's + `MoqSession::epoch()` are `connects()`, which is Python's `connects()`, Go's + `Connects()`, Swift's and Kotlin's `connects()`, and Dart's `connects`. The + audio re-anchor is `reanchor()`: `moq_audio::encode::Producer::reset_epoch` and + moq-ffi's `MoqAudioProducer::reset_epoch` are `reanchor`, which is Python's + `reanchor()` (was `reset_epoch()`), Swift's, Kotlin's, and Dart `moq_ffi`'s + `reanchor()` (was `resetEpoch()`), and Go's `Reanchor()` (was `ResetEpoch()`). - **`moq export ts --linger` waits only for the same publisher instance.** A restarted publisher (a new epoch, or any return on a version without one) exits 1 unless `--stitch` follows it as a program switch. `export srt` takes diff --git a/go/wrapper/README.md b/go/wrapper/README.md index 7845ae8bd9d..8e70ffb5368 100644 --- a/go/wrapper/README.md +++ b/go/wrapper/README.md @@ -50,9 +50,12 @@ for event, err := range announced.All(ctx) { } log.Fatal(err) } - if event, ok := event.(moq.AnnounceEventStart); ok { + switch event := event.(type) { + case moq.AnnounceEventStart: // Prefix stays origin-relative; Captures reports wildcard matches. fmt.Println("got broadcast", event.Announce.Prefix) + case moq.AnnounceEventRestart: // a new publisher run at the same path + fmt.Println("restarted broadcast", event.Announce.Prefix) } } ``` diff --git a/go/wrapper/errors.go b/go/wrapper/errors.go index c7ea7001534..6c0e0fa64c3 100644 --- a/go/wrapper/errors.go +++ b/go/wrapper/errors.go @@ -77,6 +77,8 @@ var ( ErrAlreadyCommitted = ffi.ErrMoqErrorAlreadyCommitted // ErrInvalidRoute is returned when a route has an invalid hop ID or too many hops. ErrInvalidRoute = ffi.ErrMoqErrorInvalidRoute + // ErrInvalidEpoch is returned when an epoch is not a lowercase hyphenated UUIDv7. + ErrInvalidEpoch = ffi.ErrMoqErrorInvalidEpoch // ErrInvalidPattern is returned when a path pattern is empty, has a doubled slash, or uses a reserved segment form. ErrInvalidPattern = ffi.ErrMoqErrorInvalidPattern // ErrUnresolvableBroadcast is returned when a referenced sibling broadcast cannot be resolved without an origin. diff --git a/go/wrapper/errors_test.go b/go/wrapper/errors_test.go index 451c53c6418..627f6bb6943 100644 --- a/go/wrapper/errors_test.go +++ b/go/wrapper/errors_test.go @@ -92,6 +92,7 @@ func TestErrorSentinels(t *testing.T) { {"Unsupported", ffi.NewMoqErrorUnsupported(), moq.ErrUnsupported}, {"InvalidRoute", ffi.NewMoqErrorInvalidRoute(""), moq.ErrInvalidRoute}, {"InvalidPattern", ffi.NewMoqErrorInvalidPattern(""), moq.ErrInvalidPattern}, + {"InvalidEpoch", ffi.NewMoqErrorInvalidEpoch(""), moq.ErrInvalidEpoch}, {"UnresolvableBroadcast", ffi.NewMoqErrorUnresolvableBroadcast(""), moq.ErrUnresolvableBroadcast}, {"AlreadyCommitted", ffi.NewMoqErrorAlreadyCommitted(), moq.ErrAlreadyCommitted}, {"Log", ffi.NewMoqErrorLog(""), moq.ErrLog}, diff --git a/go/wrapper/moq_test.go b/go/wrapper/moq_test.go index 5c91342ea6e..2be3a9de5a2 100644 --- a/go/wrapper/moq_test.go +++ b/go/wrapper/moq_test.go @@ -1315,6 +1315,47 @@ func TestAnnouncedExactFilterCapturesEmpty(t *testing.T) { } } +// A route carries the publisher's epoch, and a new one restarts announce consumers. +func TestAnnouncedEpochRestarts(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), testTimeout) + defer cancel() + + origin := newOrigin(t) + announced, err := origin.Consume().Announced(moq.AnnounceOptions{}) + if err != nil { + t.Fatal(err) + } + defer announced.Cancel() + + broadcast, err := origin.CreateBroadcast("epoch") + if err != nil { + t.Fatal(err) + } + first := moq.MintEpoch() + if at, err := moq.EpochTime("018bcfe5-6800-7000-8000-000000000000"); err != nil || !at.Equal(time.UnixMilli(1_700_000_000_000)) { + t.Fatalf("EpochTime = %v, %v; want 2023-11-14T22:13:20Z", at, err) + } + if err := broadcast.Announce(moq.Route{Epoch: &first}); err != nil { + t.Fatal(err) + } + if start := nextAnnounced(t, ctx, announced); start.Route.Epoch == nil || *start.Route.Epoch != first { + t.Fatalf("start epoch = %v, want %s", start.Route.Epoch, first) + } + + second := moq.MintEpoch() + if err := broadcast.Announce(moq.Route{Epoch: &second}); err != nil { + t.Fatal(err) + } + restart, ok := nextRoute(t, ctx, announced).(moq.AnnounceEventRestart) + if !ok || restart.Announce.Route.Epoch == nil || *restart.Announce.Route.Epoch != second { + t.Fatalf("restart = %+v, want epoch %s", restart, second) + } + + if _, err := moq.EpochTime("not-an-epoch"); !errors.Is(err, moq.ErrInvalidEpoch) { + t.Fatalf("EpochTime(bad) = %v, want ErrInvalidEpoch", err) + } +} + // nextRoute returns the next announce event. func nextRoute(t *testing.T, ctx context.Context, announced *moq.AnnounceConsumer) moq.AnnounceEvent { t.Helper() diff --git a/go/wrapper/publish.go b/go/wrapper/publish.go index ec2a165c628..6a8139d9495 100644 --- a/go/wrapper/publish.go +++ b/go/wrapper/publish.go @@ -465,9 +465,9 @@ func (a *AudioProducer) Unused(ctx context.Context) error { return a.inner.Unused(ctx) } -// ResetEpoch re-anchors the timeline to the next frame after an idle gap. -func (a *AudioProducer) ResetEpoch() error { - return a.inner.ResetEpoch() +// Reanchor re-anchors the timeline to the next frame after an idle gap. +func (a *AudioProducer) Reanchor() error { + return a.inner.Reanchor() } // Write pushes one frame of PCM in the configured input format. diff --git a/go/wrapper/reconnect_test.go b/go/wrapper/reconnect_test.go index 9442547e712..6377d8c9d64 100644 --- a/go/wrapper/reconnect_test.go +++ b/go/wrapper/reconnect_test.go @@ -90,15 +90,15 @@ func dialWorker(t *testing.T, ctx context.Context, url string) *moq.Client { return client } -// waitEpoch blocks until the session reports at least want connections, proving +// waitConnects blocks until the session reports at least want connections, proving // the worker redialed rather than just reusing the transport. -func waitEpoch(t *testing.T, ctx context.Context, session *moq.Session, want uint64) { +func waitConnects(t *testing.T, ctx context.Context, session *moq.Session, want uint64) { t.Helper() - for session.Epoch() < want { + for session.Connects() < want { select { case <-ctx.Done(): - t.Fatalf("epoch = %d, want >= %d", session.Epoch(), want) + t.Fatalf("connects = %d, want >= %d", session.Connects(), want) case <-time.After(10 * time.Millisecond): } } @@ -148,7 +148,7 @@ func TestServerCloseReleasesPort(t *testing.T) { // A Go worker survives a relay restart the way a moq-c worker does: the session // redials with backoff, the publisher re-announces its broadcast to the fresh -// relay, and the subscriber's subscription receives frames again. The epoch +// relay, and the subscriber's subscription receives frames again. The connect count // pairs with Status so a worker can log each reconnect. func TestReconnectAcrossRelayRestart(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), reconnectTimeout) @@ -223,9 +223,9 @@ func TestReconnectAcrossRelayRestart(t *testing.T) { current = current.restart(t, ctx) defer func() { _ = current.server.Close() }() - // Both workers observe the reconnect and advance their epoch past the first. - waitEpoch(t, ctx, publisher.Session(), 2) - waitEpoch(t, ctx, subscriber.Session(), 2) + // Both workers observe the reconnect and advance their connect count past the first. + waitConnects(t, ctx, publisher.Session(), 2) + waitConnects(t, ctx, subscriber.Session(), 2) // The publisher re-announces the broadcast the fresh relay never saw. awaitAnnouncement(t, ctx, announced, "live") diff --git a/go/wrapper/session.go b/go/wrapper/session.go index ff8b3c458a4..4e9ab981fb2 100644 --- a/go/wrapper/session.go +++ b/go/wrapper/session.go @@ -37,14 +37,14 @@ func (s *Session) Status(ctx context.Context) (ConnectionStatus, error) { return bridge.Call(ctx, s.abort, s.inner.Status) } -// Epoch is the connection epoch: 1 for the connect that built this session, one +// Connects counts how many times this session has connected: 1 for the connect that built it, one // more on each reconnect. A server-accepted session stays at 1. // // Pair it with Status to log each reconnect by number: a ConnectionStatusConnected whose -// Epoch grew is a reconnect. Like Status, it reports the current state, so a +// count grew is a reconnect. Like Status, it reports the current state, so a // drop that reconnects between reads is coalesced away. -func (s *Session) Epoch() uint64 { - return s.inner.Epoch() +func (s *Session) Connects() uint64 { + return s.inner.Connects() } // Stats snapshots the current connection statistics. diff --git a/go/wrapper/types.go b/go/wrapper/types.go index 709dc1d0ab2..f03cc846378 100644 --- a/go/wrapper/types.go +++ b/go/wrapper/types.go @@ -1,6 +1,10 @@ package moq -import ffi "moq.dev/moq-ffi/moq" +import ( + "time" + + ffi "moq.dev/moq-ffi/moq" +) // Record, enum, and small object types re-exported from the ffi layer without the Moq prefix. // These are plain data, so type aliases are exact: a moq.AudioFrame is an @@ -29,7 +33,7 @@ type ( ProtocolKind = ffi.MoqProtocolKind // OriginConfig configures a new origin, such as its maximum cache size in bytes. OriginConfig = ffi.MoqOriginConfig - // Route is the hop chain a broadcast takes to reach an origin, and its static production and link cost (lower wins). + // Route is the publisher Epoch a broadcast is announced under (nil when unknown), the hop chain it takes to reach an origin, and its static production and link cost (lower wins). Route = ffi.MoqRoute // Announce is a route over a prefix: the origin-relative Prefix, what each filter // wildcard matched (nil Captures for a route that only overlaps the scope), and the @@ -37,7 +41,7 @@ type ( // [OriginConsumer.RequestBroadcast]. Announce = ffi.MoqAnnounce // AnnounceEvent is what an AnnounceConsumer yields: AnnounceEventStart, - // AnnounceEventUpdate, or AnnounceEventEnd. + // AnnounceEventUpdate, AnnounceEventEnd, or AnnounceEventRestart. AnnounceEvent = ffi.MoqAnnounceEvent // AnnounceEventStart reports a route now covering a prefix that had none. AnnounceEventStart = ffi.MoqAnnounceEventStart @@ -45,6 +49,9 @@ type ( AnnounceEventUpdate = ffi.MoqAnnounceEventUpdate // AnnounceEventEnd reports that no route covers a prefix any more, carrying its last route. AnnounceEventEnd = ffi.MoqAnnounceEventEnd + // AnnounceEventRestart reports another publisher instance now serving a prefix: + // drop what was resolved under it and request afresh. + AnnounceEventRestart = ffi.MoqAnnounceEventRestart // VideoDecoderOutput configures what DecodeVideo delivers: an optional resize, a max delay, and whether frames keep the decoder's surface (macOS only; refused elsewhere). VideoDecoderOutput = ffi.MoqVideoDecoderOutput // VideoSurface is a decoded frame's platform surface, from VideoDecodedFrame.Surface: VideoSurfacePixelBuffer on macOS and iOS. @@ -141,6 +148,23 @@ func LogLevel(level string) error { return ffi.MoqLogLevel(level) } +// MintEpoch mints a fresh publisher epoch from the wall clock and secure randomness, +// ordered newest last. Mint one per publisher run and announce it in Route.Epoch, so +// viewers see a restart as a new broadcast instead of a stalled one. +func MintEpoch() string { + return ffi.MoqMintEpoch() +} + +// EpochTime is the wall-clock time an epoch encodes, to the millisecond. It +// returns ErrInvalidEpoch unless epoch is a lowercase hyphenated UUIDv7. +func EpochTime(epoch string) (time.Time, error) { + ms, err := ffi.MoqEpochTimeMs(epoch) + if err != nil { + return time.Time{}, err + } + return time.UnixMilli(int64(ms)), nil +} + // Protocol registries and recognized kinds carried by ProtocolError. const ( // ErrorScopeSession identifies a session close code. diff --git a/kt/README.md b/kt/README.md index 1d8d539ebc9..65eca11cb0c 100644 --- a/kt/README.md +++ b/kt/README.md @@ -31,12 +31,17 @@ import kotlinx.coroutines.flow.collect // connect() wires up an internal origin and returns a live connection. Moq.connect("https://relay.example.com").use { moq -> moq.announced(AnnounceConfig(prefix = "demos/", filter = "*/camera")).updates().collect { event -> - if (event !is AnnounceEventStart) return@collect + // A restart is a new publisher run at the same path: request it again. + val announce = when (event) { + is AnnounceEventStart -> event.announce + is AnnounceEventRestart -> event.announce + else -> return@collect // Update or End + } // Prefix stays origin-relative; captures reports what * matched. - println("got broadcast ${event.announce.prefix}") - println("captures ${event.announce.captures}") + println("got broadcast ${announce.prefix}") + println("captures ${announce.captures}") - val catalog = dev.moq.media.catalog(moq.requestBroadcast(event.announce.prefix)) + val catalog = dev.moq.media.catalog(moq.requestBroadcast(announce.prefix)) println("catalog: $catalog") } } diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt index f02d7055d34..b7bae56f747 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt @@ -51,7 +51,7 @@ typealias AnnouncedBroadcast = uniffi.moq.MoqAnnouncedBroadcast typealias Announce = uniffi.moq.MoqAnnounce /** * What an [AnnounceConsumer] yields: [AnnounceEventStart], [AnnounceEventUpdate], - * or [AnnounceEventEnd]. + * [AnnounceEventEnd], or [AnnounceEventRestart]. */ typealias AnnounceEvent = uniffi.moq.MoqAnnounceEvent // Kotlin cannot reach a sealed class's subtypes through its typealias, so each @@ -62,6 +62,8 @@ typealias AnnounceEventStart = uniffi.moq.MoqAnnounceEvent.Start typealias AnnounceEventUpdate = uniffi.moq.MoqAnnounceEvent.Update /** No route covers the prefix any more; carries its last route. */ typealias AnnounceEventEnd = uniffi.moq.MoqAnnounceEvent.End +/** Another publisher instance now serves the prefix: drop what was resolved under it and request afresh. */ +typealias AnnounceEventRestart = uniffi.moq.MoqAnnounceEvent.Restart // Broadcast / track / group producers and consumers. /** The write side of a broadcast: publish tracks into it. */ typealias BroadcastProducer = uniffi.moq.MoqBroadcastProducer @@ -103,7 +105,7 @@ typealias VideoProducer = uniffi.moq.MoqVideoProducer typealias Datagram = uniffi.moq.MoqDatagram /** A payload plus the timestamp it should be presented at. */ typealias Frame = uniffi.moq.MoqFrame -/** A path-prefix route: the prefix it covers, relay hop ids (oldest first), and static production and link cost (lower wins). */ +/** A path-prefix route: the publisher epoch it serves (null when unknown), relay hop ids (oldest first), and static production and link cost (lower wins). */ typealias Route = uniffi.moq.MoqRoute /** Tunes how a track subscription is delivered: priority, group ordering, and range. */ typealias Subscription = uniffi.moq.MoqSubscription diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Epoch.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Epoch.kt new file mode 100644 index 00000000000..d68c9678f3f --- /dev/null +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Epoch.kt @@ -0,0 +1,17 @@ +package dev.moq + +import kotlin.time.Instant + +/** + * Mint a fresh publisher epoch from the wall clock and secure randomness, ordered + * newest last. Mint one per publisher run and announce it in [Route.epoch], so + * viewers see a restart as a new broadcast instead of a stalled one. + */ +fun mintEpoch(): String = uniffi.moq.moqMintEpoch() + +/** + * The wall-clock time [epoch] encodes, to the millisecond. Throws unless it is a + * lowercase hyphenated UUIDv7. + */ +fun epochTime(epoch: String): Instant = + Instant.fromEpochMilliseconds(uniffi.moq.moqEpochTimeMs(epoch).toLong()) diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt index 2e8dd95f60a..62bb61c9f8b 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt @@ -51,12 +51,12 @@ class Moq internal constructor( suspend fun requestBroadcast(path: String): BroadcastConsumer = session.consume().requestBroadcast(path) /** - * The connection epoch: 1 for the connect that built this session, one more on + * How many times this session has connected: 1 for the connect that built it, one more on * each reconnect. A server-accepted session stays at 1. * * Pair it with [Session.status] to log each reconnect by number. */ - fun epoch(): ULong = session.epoch() + fun connects(): ULong = session.connects() /** * The session's bandwidth allocator. diff --git a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt index e7dfd13bf93..783d555331b 100644 --- a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt +++ b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt @@ -25,6 +25,7 @@ import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Duration.Companion.microseconds import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Instant @Serializable private data class Status(val state: String) @@ -397,6 +398,27 @@ class SmokeTest { } } + @Test + fun `a new epoch restarts announce consumers`() = runTest { + OriginProducer(OriginConfig()).use { origin -> + val announced = origin.consume().announced(AnnounceConfig()) + origin.createBroadcast("epoch").use { broadcast -> + val first = mintEpoch() + assertEquals(Instant.fromEpochMilliseconds(1_700_000_000_000), epochTime("018bcfe5-6800-7000-8000-000000000000")) + broadcast.announce(Route(epoch = first)) + val start = assertIs(announced.nextRoute()) + assertEquals(first, start.announce.route.epoch) + + val second = mintEpoch() + broadcast.announce(Route(epoch = second)) + val restart = assertIs(announced.nextRoute()) + assertEquals(second, restart.announce.route.epoch) + + assertFailsWith { epochTime("not-an-epoch") } + } + } + } + @Test fun `announced pattern reports captures`() = runTest { OriginProducer(OriginConfig()).use { origin -> diff --git a/py/moq-rs/README.md b/py/moq-rs/README.md index 44fed722ff6..592b5a22f94 100644 --- a/py/moq-rs/README.md +++ b/py/moq-rs/README.md @@ -29,7 +29,8 @@ import moq async def main(): async with moq.connect("https://cdn.moq.dev/anon") as client: async for event in client.announced(): - if not isinstance(event, moq.AnnounceEventStart): + # A restart is a new publisher run at the same path: request it again. + if not isinstance(event, (moq.AnnounceEventStart, moq.AnnounceEventRestart)): continue # AnnounceEventUpdate or AnnounceEventEnd # A route covers a prefix and carries no broadcast, so resolve the path. broadcast = await client.request_broadcast(event.announce.prefix) @@ -69,7 +70,8 @@ async def main(): audio.write_frame(payload, timestamp=timedelta(milliseconds=20)) audio.cut() - broadcast.announce() + # A fresh epoch per run tells viewers a restart is a new broadcast. + broadcast.announce(moq.Route(epoch=moq.mint_epoch())) # Clean up audio.finish() @@ -149,7 +151,7 @@ client = moq.Client( - `.cancel(code)`, `await session.shutdown()`. Cancel immediately, or drain finished tracks within one second, raising on failure. - `.publish() → OriginProducer`, `.consume() → OriginConsumer`. The wired origin sides. - `.stats() → ConnectionStats`. Snapshot RTT, bandwidth estimates, and byte/packet counters. - - `await .status() → ConnectionStatus`, `.epoch()`. Watch reconnects; the epoch counts connections, 1 on the first. + - `await .status() → ConnectionStatus`, `.connects()`. Watch reconnects; `connects()` counts connections, 1 on the first. - `.bandwidth() → Bandwidth`. Divide the send estimate between encoders and app-owned tracks. ### Publishing @@ -222,7 +224,7 @@ Every handle whose cleanup is `cancel()` is an async context manager, so exiting - `await .requested_broadcast() → BroadcastRequest`. Call `.accept(broadcast)` to serve it, or `.reject(code)` to fail the requester. - Async iterator yielding `BroadcastRequest` - **`OriginConsumer`**. Discover broadcasts. - - `.announced(prefix, filter=None) → AnnounceConsumer` (async iterator of `AnnounceEvent`: `AnnounceEventStart`, `AnnounceEventUpdate`, or `AnnounceEventEnd`, each carrying an `Announce`); `filter` is a pattern relative to the literal prefix, while each `Announce.prefix` stays origin-relative and `.captures` reports wildcard matches + - `.announced(prefix, filter=None) → AnnounceConsumer` (async iterator of `AnnounceEvent`: `AnnounceEventStart`, `AnnounceEventUpdate`, `AnnounceEventEnd`, or `AnnounceEventRestart`, each carrying an `Announce` whose `.route.epoch` names the publisher run; on a restart, request the path again); `filter` is a pattern relative to the literal prefix, while each `Announce.prefix` stays origin-relative and `.captures` reports wildcard matches - `.announced_broadcast(path) → AnnouncedBroadcast` (awaitable, waits until something serves the path) - `.request_broadcast(path) → BroadcastConsumer` (awaitable; announced now or a dynamic fallback, else raises) diff --git a/py/moq-rs/docs/index.md b/py/moq-rs/docs/index.md index 1368e929129..f2f28724214 100644 --- a/py/moq-rs/docs/index.md +++ b/py/moq-rs/docs/index.md @@ -143,6 +143,7 @@ broadcast, and producers advertise it in the catalog. AnnounceEventStart AnnounceEventUpdate AnnounceEventEnd + AnnounceEventRestart ``` ## Data types @@ -201,6 +202,8 @@ Rust side ([`moq-ffi`](https://crates.io/crates/moq-ffi)). is_shutdown protocol_error log_level + mint_epoch + epoch_time ``` ```{toctree} diff --git a/py/moq-rs/moq/__init__.py b/py/moq-rs/moq/__init__.py index 400eff93182..d5a64c7c4ac 100644 --- a/py/moq-rs/moq/__init__.py +++ b/py/moq-rs/moq/__init__.py @@ -8,6 +8,7 @@ # A submodule, not in __all__: a star import would shadow the stdlib `json`. from . import json as json from .client import Client, connect +from .epoch import epoch_time, mint_epoch from .errors import is_auth, is_shutdown, protocol_error from .log import log_level from .origin import ( @@ -16,6 +17,7 @@ AnnouncedBroadcast, AnnounceEvent, AnnounceEventEnd, + AnnounceEventRestart, AnnounceEventStart, AnnounceEventUpdate, BroadcastRequest, @@ -80,6 +82,7 @@ "AnnouncedBroadcast", "AnnounceEvent", "AnnounceEventEnd", + "AnnounceEventRestart", "AnnounceEventStart", "AnnounceEventUpdate", "AudioCodec", @@ -137,9 +140,11 @@ "VideoPixelFormat", "VideoProducer", "connect", + "epoch_time", "is_auth", "is_shutdown", "log_level", + "mint_epoch", "protocol_error", ] diff --git a/py/moq-rs/moq/epoch.py b/py/moq-rs/moq/epoch.py new file mode 100644 index 00000000000..cab5657a446 --- /dev/null +++ b/py/moq-rs/moq/epoch.py @@ -0,0 +1,25 @@ +"""Publisher epochs: the UUIDv7 text a route carries to name one publisher run.""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone + +from moq_ffi import moq_epoch_time_ms, moq_mint_epoch + + +def mint_epoch() -> str: + """Mint a fresh epoch from the wall clock and secure randomness, ordered newest last. + + Mint one per publisher run and announce it with ``Route(epoch=...)``, so a + restart reads as a new broadcast to viewers instead of a stalled one. + """ + return moq_mint_epoch() + + +def epoch_time(epoch: str) -> datetime: + """The UTC wall-clock time an epoch encodes, to the millisecond. + + Raises `moq.Error` unless ``epoch`` is a lowercase hyphenated UUIDv7, and + ``OverflowError`` for a time past year 9999, which ``datetime`` cannot hold. + """ + return datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(milliseconds=moq_epoch_time_ms(epoch)) diff --git a/py/moq-rs/moq/origin.py b/py/moq-rs/moq/origin.py index e1c0fc9ac21..c5bdd575d6b 100644 --- a/py/moq-rs/moq/origin.py +++ b/py/moq-rs/moq/origin.py @@ -32,8 +32,8 @@ AnnounceEvent = MoqAnnounceEvent """What :class:`AnnounceConsumer` yields: :data:`AnnounceEventStart`, -:data:`AnnounceEventUpdate`, or :data:`AnnounceEventEnd`, each carrying an -:data:`Announce` as ``announce``. +:data:`AnnounceEventUpdate`, :data:`AnnounceEventEnd`, or +:data:`AnnounceEventRestart`, each carrying an :data:`Announce` as ``announce``. """ AnnounceEventStart = MoqAnnounceEvent.START @@ -45,6 +45,10 @@ AnnounceEventEnd = MoqAnnounceEvent.END """No route covers the prefix any more; carries its last route.""" +AnnounceEventRestart = MoqAnnounceEvent.RESTART +"""Another publisher instance now serves the prefix: drop what was resolved under +it and request afresh.""" + class AnnounceConsumer: """Async-iterable stream of :data:`AnnounceEvent` as they arrive. diff --git a/py/moq-rs/moq/publish.py b/py/moq-rs/moq/publish.py index dac6dd7b8c1..31eff150de2 100644 --- a/py/moq-rs/moq/publish.py +++ b/py/moq-rs/moq/publish.py @@ -318,9 +318,9 @@ async def unused(self) -> None: """Wait until this audio track has no active subscribers. Prefer :meth:`demand`.""" await self._inner.unused() - def reset_epoch(self) -> None: + def reanchor(self) -> None: """Re-anchor the timeline to the next frame after an idle gap.""" - self._inner.reset_epoch() + self._inner.reanchor() def write(self, frame: AudioFrame) -> None: """Push one frame of PCM in the configured input format.""" diff --git a/py/moq-rs/moq/session.py b/py/moq-rs/moq/session.py index b0f55851a4e..63254829f5c 100644 --- a/py/moq-rs/moq/session.py +++ b/py/moq-rs/moq/session.py @@ -59,13 +59,13 @@ async def status(self) -> ConnectionStatus: are the ones that already healed. Do not count outages with it.""" return await self._inner.status() - def epoch(self) -> int: - """The connection epoch: 1 for the connect that built this session, one more + def connects(self) -> int: + """How many times this session has connected: 1 for the connect that built it, one more on each reconnect. A server-accepted session stays at 1. Pair it with :meth:`status` to log each reconnect by number; a - ``CONNECTED`` status whose epoch grew is a reconnect.""" - return self._inner.epoch() + ``CONNECTED`` status whose count grew is a reconnect.""" + return self._inner.connects() def cancel(self, code: int) -> None: """Close the session with the given error code.""" diff --git a/py/moq-rs/tests/test_local.py b/py/moq-rs/tests/test_local.py index e032a0b6033..d082dce0baa 100644 --- a/py/moq-rs/tests/test_local.py +++ b/py/moq-rs/tests/test_local.py @@ -2,7 +2,7 @@ import asyncio import struct -from datetime import timedelta +from datetime import datetime, timedelta, timezone from typing import cast import moq @@ -373,6 +373,35 @@ async def test_announced_broadcast(): break +async def test_announced_epoch_restarts(): + origin = moq.OriginProducer() + consumer = origin.consume() + announced = consumer.announced() + broadcast = origin.create_broadcast("epoch") + + first = moq.mint_epoch() + fixed = datetime(2023, 11, 14, 22, 13, 20, tzinfo=timezone.utc) + assert moq.epoch_time("018bcfe5-6800-7000-8000-000000000000") == fixed + broadcast.announce(moq.Route(epoch=first)) + start = await next_route(announced) + assert isinstance(start, moq.AnnounceEventStart) + assert start.announce.route.epoch == first + + second = moq.mint_epoch() + broadcast.announce(moq.Route(epoch=second)) + restart = await next_route(announced) + assert isinstance(restart, moq.AnnounceEventRestart) + assert restart.announce.route.epoch == second + + with pytest.raises(moq.Error.InvalidEpoch): # type: ignore[attr-defined] + moq.epoch_time(first.upper()) + with pytest.raises(OverflowError): + moq.epoch_time("ffffffff-ffff-7000-8000-000000000000") + with pytest.raises(moq.Error.InvalidEpoch): # type: ignore[attr-defined] + broadcast.announce(moq.Route(epoch="not-an-epoch")) + broadcast.close() + + def test_publish_lifecycle(): broadcast = moq.BroadcastProducer() track = broadcast.publish_track("status") diff --git a/quest/m0/broadcast-epoch/README.md b/quest/m0/broadcast-epoch/README.md index 18605c77e29..24985e11b50 100644 --- a/quest/m0/broadcast-epoch/README.md +++ b/quest/m0/broadcast-epoch/README.md @@ -73,7 +73,7 @@ Decided: [catalog references quest](/quest/m0/broadcast-epoch/catalog-references.md) owns the schemas, readers, and compatibility documentation. - Every first-party publisher that can restart mints its own: the apps, - moq-boy, the ingest gateways, moqsink, and the bindings below. Players + moq-boy, the ingest gateways, moqsink, and the bindings. Players (`moq play`, `@moq/watch`, demo/web) follow the announce `Restart`. moq-stats mints one per [group announcement](/doc/concept/stats.md#broadcasts), which also gated the release (decided 2026-10-04). @@ -126,7 +126,6 @@ End+Start. The child quests own their focused regressions. - [Resume duplicates](/quest/m0/broadcast-epoch/resume-duplicates.md) - a delayed group is delivered once even beyond the old 1024-entry history - [Catalog references](/quest/m0/broadcast-epoch/catalog-references.md) - players and exporters pin siblings consistently, with optional reference epochs and documented legacy best effort - [Publish catalog restart](/quest/m0/broadcast-epoch/publish-catalog-restart.md) - `@moq/publish` never reuses catalog group numbers under one name and epoch after a re-announce -- [Bindings](/quest/m0/broadcast-epoch/bindings.md) - moq-ffi and every wrapper expose the epoch and let a publisher announce one - [Stats totals and prefix tracks](/quest/m0/broadcast-epoch/stats-split.md) - the same release retires the per-path stats maps for totals and on-demand prefix tracks (decided 2026-10-05) ## Related diff --git a/quest/m0/broadcast-epoch/bindings.md b/quest/m0/broadcast-epoch/bindings.md deleted file mode 100644 index b92627e9a5f..00000000000 --- a/quest/m0/broadcast-epoch/bindings.md +++ /dev/null @@ -1,32 +0,0 @@ -# [M] Bindings expose epochs - -## Goal - -`moq-ffi` and the py, swift, kt, go, and dart wrappers can announce an epoch like Rust, with a minting helper. The generated C and C++ -bindings pick it up from moq-ffi; libmoq gets no new API. The epoch on an announced route is -readable, and a publisher can pass an explicit one. Every wrapper surfaces -the `Restart` announce event. The reconnect counter `session.epoch()` and the -audio timeline re-anchor `reset_epoch` are renamed so "epoch" has one meaning. - -## Plan - -- Expose the parsed epoch (text and time) and an explicit-epoch publish - argument. Keep the surface to what a binding consumer needs. -- Rename the reconnect counter, `moq_tokio::Connection::epoch()` and - `session.epoch()` in every binding (for example to `connects()`). That is - a break. -- Rename the audio re-anchor the same way (decided 2026-10-08, since it also - says "epoch"): `moq_audio::encode::Producer::reset_epoch`, its moq-ffi - method, the wrappers that expose it, and moq-boy's copy. -- `MoqAnnounceEvent::Restart` lands in moq-ffi; each wrapper maps it. -- Update `doc/lib/{py,swift,kt,go,dart}` per the cross-package sync table, - and run `just test smoke --all`. - -Decided in the 2026-09-30 audit: libmoq is frozen (renamed `rs/moq-c`), so C and C++ consumers get epochs from moq-ffi. - -Reversed 2026-10-09 by the maintainer: the -[FFI shape](/quest/m1/ffi-shape/README.md) line (#4519) landed first, so this -builds on its reshaped wrappers (`MoqClientConfig`, the `media` namespace) -instead. Its `epoch()` rename should still reach the same binding release as -the line's [Codecs](/quest/m1/ffi-shape/codec.md), so the wrappers break once. - diff --git a/quest/m1/cpp-release.md b/quest/m1/cpp-release.md index 8c60910ae36..cc034bc2ba6 100644 --- a/quest/m1/cpp-release.md +++ b/quest/m1/cpp-release.md @@ -36,7 +36,6 @@ release. The nightly dry-run preparation can proceed independently. ## Required - [Codecs](/quest/m1/ffi-shape/codec.md) - settle the audio and video binding API before publishing -- [Bindings](/quest/m0/broadcast-epoch/bindings.md) - include the epoch rename in the same breaking release - [Client settings parity](/quest/m1/obs-client-config.md) - the OBS Advanced settings the migration dropped come back - [Session report parity](/quest/m1/obs-session-report.md) - the dock shows the negotiated protocol and the reconnect failure again - [Generated C++ shape](/quest/m1/cpp-generated-shape.md) - each type has one name and `moq::expected` one type before the API ships diff --git a/quest/m1/dart-publish.md b/quest/m1/dart-publish.md index 3735a295e34..a0b9546c4ef 100644 --- a/quest/m1/dart-publish.md +++ b/quest/m1/dart-publish.md @@ -31,7 +31,6 @@ Public API: none. Wire: none. ## Required - [Codecs](/quest/m1/ffi-shape/codec.md) - settle the audio and video binding API before publishing -- [Bindings](/quest/m0/broadcast-epoch/bindings.md) - include the epoch rename in the same breaking release ## Related diff --git a/quest/m1/ffi-shape/README.md b/quest/m1/ffi-shape/README.md index 8abf07a0777..c9d7c104951 100644 --- a/quest/m1/ffi-shape/README.md +++ b/quest/m1/ffi-shape/README.md @@ -19,13 +19,12 @@ media, and request-accept children, and the remaining children PR straight to each `main` merge meant hand-porting moq-ffi changes onto moved code. - The bindings still break once per release, not once per merge: binding releases (moq-ffi and the Python, Go, Swift, Kotlin, Dart, and C++ - packages) wait until [Codecs](/quest/m1/ffi-shape/codec.md) and - [Bindings](/quest/m0/broadcast-epoch/bindings.md)' `epoch()` rename both merge - (confirmed as hard release gates in the 2026-10-10 audit). Codecs ranks - first below for that reason. Dart is published (`moq` 0.1.0, `moq_ffi` 0.4.x), so + packages) wait until [Codecs](/quest/m1/ffi-shape/codec.md) merges + (confirmed as a hard release gate in the 2026-10-10 audit), joining the + named error fields and the broadcast-epoch renames (`connects()`, + `reanchor()`) already on `main`. Codecs ranks first below for that reason. + Dart is published (`moq` 0.1.0, `moq_ffi` 0.4.x), so its renames get the same upgrade notes as the others. -- Bindings no longer lands first (reversing the 2026-10-05 audit): it adopts - the reshaped wrappers on `main` instead of this line rebasing onto it. - The C++ package (#4079) landed first, so #4519 ported `cpp/moq` (including the hand-kept `moq::` aliases `just cpp check` audits), `cpp/obs`, and the C++ interop client. C++ stays a flat `moq::` namespace with `Media*` type @@ -72,5 +71,4 @@ runs `just test interop --all`. ## Required - [Codecs](/quest/m1/ffi-shape/codec.md) - audio and video producers, codec-only encoders, and decoders move under their own namespaces, named as in Rust; binding releases wait for it -- [Bindings](/quest/m0/broadcast-epoch/bindings.md) - the wrappers expose epochs and rename `session.epoch()`, on the reshaped wrappers - [Layers guide](/quest/m1/ffi-shape/layers-guide.md) - a `doc/lib` page maps each Rust layer to every binding's module, once Codecs adds `audio` and `video` diff --git a/quest/m1/ffi-shape/codec.md b/quest/m1/ffi-shape/codec.md index 909fad4c4b3..30948dccd17 100644 --- a/quest/m1/ffi-shape/codec.md +++ b/quest/m1/ffi-shape/codec.md @@ -57,9 +57,9 @@ literal. Update the wrappers and docs that restate 20000 (the Python test asserting the default, `doc/lib/{py,swift,kt,go,dart}`). libmoq already reads 0 as the default. -Binding releases wait for this quest and the -[epoch rename](/quest/m0/broadcast-epoch/bindings.md), so consumers take -one breaking release (hard gates confirmed in the 2026-10-10 audit). The +Binding releases wait for this quest, so consumers take one breaking release +with the named error fields and epoch renames already on `main` (hard gate +confirmed in the 2026-10-10 audit). The generated C++ follows moq-ffi: update `cpp/moq`'s `moq::` aliases (which `just cpp check` audits), anything in `cpp/obs` that calls the moved verbs, and `doc/lib/cpp`. diff --git a/quest/m1/js-session-parity.md b/quest/m1/js-session-parity.md index 7888cf051ff..a93e1c0bf14 100644 --- a/quest/m1/js-session-parity.md +++ b/quest/m1/js-session-parity.md @@ -18,7 +18,7 @@ since it waits on #4225 and the caps do not. Decided 2026-10-08: the resolved-epoch check is done for JS (`broadcast.Consumer.epoch` mirrors `broadcast::Info::epoch`), and the -bindings' epoch surface is [Bindings](/quest/m0/broadcast-epoch/bindings.md)'s. +bindings expose epochs on announced routes through moq-ffi. ## Related diff --git a/quest/m1/obs-epoch.md b/quest/m1/obs-epoch.md index 70742101d18..53433f55c8e 100644 --- a/quest/m1/obs-epoch.md +++ b/quest/m1/obs-epoch.md @@ -16,9 +16,5 @@ release gate waits only on `moqsink`. the C++ line moves the plugin onto (decided in the 2026-09-30 audit: libmoq, now moq-c, gets no new API). - Nothing mints by default: the plugin mints one per Start Streaming and - announces it through the route. + announces it through the route: `moq::mint_epoch()` into `Route::epoch`. - Show the epoch in the dock, and update `doc/bin/obs.md` if it shows it. - -## Required - -- [Bindings](/quest/m0/broadcast-epoch/bindings.md) - moq-ffi exposes epochs diff --git a/rs/moq-audio/src/encode/capture.rs b/rs/moq-audio/src/encode/capture.rs index 39cff5d6122..8fe2be135fc 100644 --- a/rs/moq-audio/src/encode/capture.rs +++ b/rs/moq-audio/src/encode/capture.rs @@ -532,7 +532,7 @@ impl Driver { match event { DriveEvent::Control(None) => return Ok(()), DriveEvent::Control(Some(_)) => { - self.producer_mut().reset_epoch(); + self.producer_mut().reanchor(); } DriveEvent::Capture(Ok(())) => return Ok(()), DriveEvent::Capture(Err(err)) => { @@ -818,7 +818,7 @@ trait Output { fn starting(&mut self) {} fn live(&mut self, _device: Option) {} fn failed(&mut self, _error: &Error) {} - fn reset_epoch(&mut self); + fn reanchor(&mut self); /// The broadcast timestamp of a buffer captured at `captured`, or now when unknown. fn stamp(&self, captured: Option) -> Result; fn write(&mut self, samples: capture::Samples, timestamp_us: u64) -> Result<(), Error>; @@ -864,8 +864,8 @@ impl Output for EncoderOutput<'_, E> { ); } - fn reset_epoch(&mut self) { - self.producer.reset_epoch(); + fn reanchor(&mut self) { + self.producer.reanchor(); } fn stamp(&self, captured: Option) -> Result { @@ -966,7 +966,7 @@ impl Converter { } /// Return converted samples plus the timestamp of the first input buffered - /// into them. The timestamp preserves the epoch when resampling spans reads. + /// into them. The timestamp preserves the anchor when resampling spans reads. fn process( &mut self, mut samples: capture::Samples, @@ -1115,7 +1115,7 @@ impl Supervisor { biased; unused = demand.unused() => { drop(input); - output.reset_epoch(); + output.reanchor(); if !unused { return match last_error { Some(err) => Err(err), @@ -1140,7 +1140,7 @@ impl Supervisor { // A bounded-queue drop is a real hole in the timeline. The next // buffer re-anchors at its own capture instant. if samples.gap { - output.reset_epoch(); + output.reanchor(); } let timestamp_us = output.stamp(samples.captured)?; if let Some((samples, timestamp_us)) = converter.process(samples, timestamp_us)? { @@ -1167,7 +1167,7 @@ impl Supervisor { // The failed stream was dropped by the match above. Reset before waiting // so a publication that ends during recovery cannot flush stale samples. - output.reset_epoch(); + output.reanchor(); tracing::warn!(error = %failure, "audio capture unavailable"); last_error = Some(failure); @@ -1338,7 +1338,7 @@ mod tests { } impl Output for MockOutput { - fn reset_epoch(&mut self) { + fn reanchor(&mut self) { self.events.push(OutputEvent::Reset); } @@ -1921,7 +1921,7 @@ mod tests { } #[tokio::test(start_paused = true)] - async fn successful_reopen_resumes_the_same_output_after_an_epoch_reset() { + async fn successful_reopen_resumes_the_same_output_after_a_reanchor() { let (failed_tx, failed) = stream(None); failed_tx .try_push(Err(capture::Failure::retry(Error::Capture("lost".into())))) @@ -2338,7 +2338,7 @@ mod tests { } /// A device that fails and reopens counts its samples from zero again. The broadcast - /// continues forward from the reopen instead of rewinding to the old epoch. + /// continues forward from the reopen instead of rewinding to the old anchor. #[tokio::test] async fn a_device_restart_continues_forward() { let (first, failing) = stream(None); diff --git a/rs/moq-audio/src/encode/producer.rs b/rs/moq-audio/src/encode/producer.rs index 2ed39176765..85c479b0545 100644 --- a/rs/moq-audio/src/encode/producer.rs +++ b/rs/moq-audio/src/encode/producer.rs @@ -50,7 +50,7 @@ pub struct Options { /// they are encoded rather than buffered until the group fills. A longer /// [`Settings::frame_duration`] (up to 60 ms for Opus) also packs more audio /// per group, at the cost of encoder latency. An unfinished group remains open - /// across a pause or [`Producer::reset_epoch`] until the next write; use + /// across a pause or [`Producer::reanchor`] until the next write; use /// [`Producer::discontinuity`] to close it when capture stops. pub group_duration: std::time::Duration, } @@ -88,12 +88,12 @@ pub struct Producer { group_samples: u64, /// Codec samples in the open group. grouped: u64, - /// Samples emitted since the current epoch (reset by [`reset_epoch`](Self::reset_epoch)). + /// Samples emitted since the current anchor (reset by [`reanchor`](Self::reanchor)). frames_produced: u64, /// Wall-clock anchor in microseconds, taken from the first frame after each - /// (re)start. Emitted PTS = `epoch + frames_produced / codec_rate`. `None` + /// (re)start. Emitted PTS = `anchor + frames_produced / codec_rate`. `None` /// until the first write so the next frame re-anchors to its timestamp. - epoch_us: Option, + anchor_us: Option, /// An encoder reset that still needs a marker group before its next packet. pending_discontinuity: bool, /// Whether a marker group already separates the next packet from prior codec state. @@ -207,7 +207,7 @@ impl Reserved { group_samples: registered.group_samples, grouped: 0, frames_produced: 0, - epoch_us: None, + anchor_us: None, pending_discontinuity: false, decoder_boundary: true, activity: Activity::Active, @@ -311,9 +311,9 @@ impl Producer { /// released-then-reopened microphone) so the gap appears in the PTS and /// audio stays aligned with a wall-clock video track, rather than the gap /// being compressed out by the running sample count. Mirrors moq-boy's - /// `reset_epoch`. If the codec had started, a marker group is published before + /// `reanchor`. If the codec had started, a marker group is published before /// the next packet so subscribers jump the playhead. - pub fn reset_epoch(&mut self) { + pub fn reanchor(&mut self) { if self.encoder.started() && !self.decoder_boundary { self.pending_discontinuity = true; } @@ -321,14 +321,14 @@ impl Producer { } fn reset_state(&mut self) { - self.epoch_us = None; + self.anchor_us = None; self.activity = Activity::Active; self.frames_produced = 0; self.pending.clear(); self.encoder.reset(); // The resampler holds samples of its own, plus filter state primed by them. // Left alone, `finish` would flush that pre-reset audio onto the track - // (stamped at an epoch that no longer exists), and the next write would run + // (stamped at an anchor that no longer exists), and the next write would run // the new audio through a filter still ringing with the old. if let Some(resampler) = self.resampler.as_mut() { resampler.reset(); @@ -339,11 +339,11 @@ impl Producer { /// publishes as many packets as the input contains; any partial trailing /// frame is carried to the next call. /// - /// The first frame after construction (or [`reset_epoch`](Self::reset_epoch)) - /// anchors the timeline: its timestamp becomes the epoch, and emitted PTS + /// The first frame after construction (or [`reanchor`](Self::reanchor)) + /// anchors the timeline: its timestamp becomes the anchor, and emitted PTS /// then advances purely by the running sample count, so subsequent frames' /// timestamps are ignored. An idle gap is only reflected in the PTS if you - /// call [`reset_epoch`](Self::reset_epoch) on resume (which re-anchors from + /// call [`reanchor`](Self::reanchor) on resume (which re-anchors from /// the next frame's wall-clock stamp); writing straight across a gap without /// resetting compresses it out. /// @@ -364,7 +364,7 @@ impl Producer { let timestamp_us = u64::try_from(frame.timestamp.as_micros()) .map_err(|_| Error::Unsupported(format!("frame timestamp {:?} out of range", frame.timestamp)))?; - let epoch_us = *self.epoch_us.get_or_insert(timestamp_us); + let anchor_us = *self.anchor_us.get_or_insert(timestamp_us); let input = &self.input; let (format, channels) = (input.format, input.layout.channels()); @@ -380,19 +380,19 @@ impl Producer { self.pending.extend(pcm); - self.publish_full_frames(epoch_us) + self.publish_full_frames(anchor_us) } /// Encode and publish every full frame in `pending`, keeping any partial /// trailing frame for the next call. - fn publish_full_frames(&mut self, epoch_us: u64) -> Result<(), Error> { + fn publish_full_frames(&mut self, anchor_us: u64) -> Result<(), Error> { let frame_samples = self.encoder.frame_size() * self.encoder.codec_channels() as usize; while self.pending.len() >= frame_samples { let chunk: Vec = self.pending.drain(..frame_samples).collect(); let packet = self.encoder.encode(&chunk)?; let timestamp = Self::timestamp( - epoch_us, + anchor_us, self.frames_produced, self.encoder.folded_delay(), self.encoder.codec_rate(), @@ -406,16 +406,16 @@ impl Producer { Ok(()) } - /// PTS of the frame `frames` samples past the epoch, stamped `delay` samples + /// PTS of the frame `frames` samples past the anchor, stamped `delay` samples /// earlier to fold in codec priming the catalog can't signal. /// - /// Priming that would land before a zero epoch is stamped at zero instead: it + /// Priming that would land before a zero anchor is stamped at zero instead: it /// decodes to the codec's warm-up rather than to input, so only its spacing is /// lost. - fn timestamp(epoch_us: u64, frames: u64, delay: usize, codec_rate: u32) -> Result { + fn timestamp(anchor_us: u64, frames: u64, delay: usize, codec_rate: u32) -> Result { let frames = i128::from(frames) - delay as i128; let offset_us = (frames * 1_000_000).div_euclid(i128::from(codec_rate)); - let micros = (i128::from(epoch_us) + offset_us).max(0); + let micros = (i128::from(anchor_us) + offset_us).max(0); let micros = u64::try_from(micros).map_err(|_| moq_net::TimeOverflow)?; Ok(Timestamp::from_micros(micros)?) } @@ -478,8 +478,8 @@ impl Producer { /// Mark a break in the published timeline and reset codec state. /// /// Call this when capture stops rather than merely gapping between packets: going idle, - /// switching source, or anything else that resumes on a re-anchored epoch. Buffered samples - /// are dropped, and the next frame anchors a fresh codec epoch. See + /// switching source, or anything else that resumes on a new anchor. Buffered samples + /// are dropped, and the next frame sets a fresh anchor. See /// [`Producer::discontinuity`](moq_mux::container::Producer::discontinuity). pub fn discontinuity(&mut self) -> Result<(), Error> { self.track.discontinuity()?; @@ -508,17 +508,17 @@ impl Producer { // The drained resampler tail can span multiple frames. Publish those first // so only the final partial frame reaches the encoder's terminal drain. - let epoch_us = self.epoch_us.unwrap_or(0); - self.publish_full_frames(epoch_us)?; + let anchor_us = self.anchor_us.unwrap_or(0); + self.publish_full_frames(anchor_us)?; let frame_size = self.encoder.frame_size(); let codec_rate = self.encoder.codec_rate(); let channels = self.encoder.codec_channels() as usize; let source_frames = self.pending.len() / channels; let delay = self.encoder.folded_delay(); - let start = Self::timestamp(epoch_us, self.frames_produced, delay, codec_rate)?; + let start = Self::timestamp(anchor_us, self.frames_produced, delay, codec_rate)?; // The source ends where it ends: priming only moves the packets carrying it. - let end = Self::timestamp(epoch_us, self.frames_produced + source_frames as u64, 0, codec_rate)?; + let end = Self::timestamp(anchor_us, self.frames_produced + source_frames as u64, 0, codec_rate)?; let finish = self.encoder.drain(&self.pending)?; let discard_padding = finish.discard_padding(); let packets = finish.into_packets(); @@ -536,7 +536,7 @@ impl Producer { )?; } else { for packet in packets { - let timestamp = Self::timestamp(epoch_us, self.frames_produced, delay, codec_rate)?; + let timestamp = Self::timestamp(anchor_us, self.frames_produced, delay, codec_rate)?; self.activity = packet.activity; self.publish(packet, timestamp)?; self.frames_produced += frame_size as u64; @@ -705,11 +705,11 @@ mod tests { assert_eq!(packets, 11); } - /// `reset_epoch` promises to drop buffered samples, and the resampler buffers + /// `reanchor` promises to drop buffered samples, and the resampler buffers /// samples of its own. Leaving those behind let `finish` flush pre-reset audio - /// onto the track, stamped at an epoch that no longer exists. + /// onto the track, stamped at an anchor that no longer exists. #[tokio::test] - async fn reset_epoch_drops_the_resampler_buffer_too() { + async fn reanchor_drops_the_resampler_buffer_too() { let input = Input { format: Format::F32, sample_rate: 44_100, @@ -741,7 +741,7 @@ mod tests { .write(&Frame::new(data.into(), moq_net::Timestamp::ZERO)) .unwrap(); - producer.reset_epoch(); + producer.reanchor(); producer.finish().unwrap(); // The reset dropped everything, so the track ends without a packet. @@ -750,7 +750,7 @@ mod tests { /// Resetting after a full frame drops codec lookahead as well as producer buffers. #[tokio::test] - async fn reset_epoch_drops_the_encoder_lookahead() { + async fn reanchor_drops_the_encoder_lookahead() { let mut broadcast = moq_net::broadcast::Info::new().produce(); let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap(); let consumer = broadcast.consume(); @@ -779,7 +779,7 @@ mod tests { ); producer.write(&full_frame(1_000_000)).unwrap(); - producer.reset_epoch(); + producer.reanchor(); producer.finish().unwrap(); assert!(track.read().await.unwrap().is_some()); @@ -788,7 +788,7 @@ mod tests { /// A codec reset starts a new pre-skip interval at the receiver too. #[tokio::test] - async fn reset_epoch_restarts_the_decoder() { + async fn reanchor_restarts_the_decoder() { let input = Input { format: Format::F32, sample_rate: 48_000, @@ -818,10 +818,10 @@ mod tests { .unwrap(); producer.write(&full_frame(0)).unwrap(); - let first = audio.read().await.unwrap().expect("first epoch packet"); + let first = audio.read().await.unwrap().expect("first packet before the reanchor"); assert_eq!(first.data.len() / size_of::(), 960 - 312); - producer.reset_epoch(); + producer.reanchor(); producer.write(&full_frame(1_000_000)).unwrap(); producer.finish().unwrap(); @@ -831,7 +831,7 @@ mod tests { resumed_frames += frame.data.len() / size_of::(); } } - assert!(resumed_frames > 0, "the resumed epoch still decodes"); + assert!(resumed_frames > 0, "the reanchored audio still decodes"); } #[tokio::test] @@ -898,7 +898,7 @@ mod tests { } /// Publish each frame and read back the resulting packet PTS (microseconds). - /// If `reset_before` contains an index, `reset_epoch()` is called before that + /// If `reset_before` contains an index, `reanchor()` is called before that /// frame's `write`. async fn published_pts(frames: &[Frame], reset_before: Option) -> Vec { let mut broadcast = moq_net::broadcast::Info::new().produce(); @@ -925,7 +925,7 @@ mod tests { let mut pts = Vec::new(); for (i, frame) in frames.iter().enumerate() { if reset_before == Some(i) { - producer.reset_epoch(); + producer.reanchor(); } producer.write(frame).unwrap(); let read = reader.read().await.unwrap().expect("a packet per full frame"); @@ -1054,7 +1054,7 @@ mod tests { assert!(partial.poll_read_frame(&moq_net::kio::Waiter::noop()).is_pending()); if deferred { - producer.reset_epoch(); + producer.reanchor(); assert!(partial.poll_read_frame(&moq_net::kio::Waiter::noop()).is_pending()); } else { producer.discontinuity().unwrap(); @@ -1068,7 +1068,7 @@ mod tests { assert_eq!( resumed.sequence, partial.sequence + 2, - "one marker separates the epochs" + "one marker separates the anchors" ); for _ in 0..5 { assert!(resumed.read_frame().await.unwrap().is_some()); @@ -1078,18 +1078,18 @@ mod tests { } #[tokio::test] - async fn epoch_anchors_to_first_frame_timestamp() { - // The first frame's timestamp becomes the epoch (regression guard: the + async fn anchors_to_first_frame_timestamp() { + // The first frame's timestamp becomes the anchor (regression guard: the // old code derived PTS purely from the sample count, always near 0). let pts = published_pts(&[full_frame(1_000_000)], None).await; assert_eq!(pts, vec![1_000_000]); } /// AAC can't signal its encoder delay, so each packet is stamped that much - /// earlier and the first input sample still decodes at the epoch. + /// earlier and the first input sample still decodes at the anchor. #[tokio::test] async fn aac_folds_the_encoder_delay_into_timestamps() { - async fn pts(epoch_us: u64) -> Vec { + async fn pts(anchor_us: u64) -> Vec { let mut broadcast = moq_net::broadcast::Info::new().produce(); let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap(); let consumer = broadcast.consume(); @@ -1115,7 +1115,7 @@ mod tests { moq_mux::container::legacy::Wire(moq_mux::container::Kind::Audio), ); - producer.write(&pcm_frame(&[0.1; 4 * 1024], epoch_us)).unwrap(); + producer.write(&pcm_frame(&[0.1; 4 * 1024], anchor_us)).unwrap(); let mut pts = Vec::new(); for _ in 0..4 { pts.push(reader.read().await.unwrap().expect("a packet").timestamp.as_micros()); @@ -1125,16 +1125,16 @@ mod tests { // 2112 frames of delay at 48 kHz is 44 ms, rounded down per packet. assert_eq!(pts(1_000_000).await, vec![956_000, 977_333, 998_666, 1_020_000]); - // Priming before a zero epoch stamps at zero; the input still starts on time. + // Priming before a zero anchor stamps at zero; the input still starts on time. assert_eq!(pts(0).await, vec![0, 0, 0, 20_000]); } /// The encoder needs no correction for the resampler's own delay: it anchors - /// the epoch to the first input timestamp and advances by emitted samples, + /// the anchor to the first input timestamp and advances by emitted samples, /// while `Resampler::process` drops its startup silence rather than passing it /// on, so the first sample published is the first sample written. Anything /// that let that delay through would shift every PTS on a resampled track, - /// which no `reset_epoch` would ever correct. + /// which no `reanchor` would ever correct. #[tokio::test] async fn resampling_does_not_shift_the_first_pts() { let mut broadcast = moq_net::broadcast::Info::new().produce(); @@ -1174,14 +1174,14 @@ mod tests { #[tokio::test] async fn pts_advances_by_frame_duration_ignoring_later_timestamps() { // Second frame's own timestamp (way ahead) is ignored; PTS advances by - // exactly one 20 ms frame from the epoch. + // exactly one 20 ms frame from the anchor. let pts = published_pts(&[full_frame(1_000), full_frame(999_999)], None).await; assert_eq!(pts, vec![1_000, 1_000 + 20_000]); } #[tokio::test] - async fn reset_epoch_reanchors_so_the_gap_lands_in_pts() { - // Frame at t=0, then reset_epoch + a frame at t=5s: the 5 s idle gap must + async fn reanchor_lets_the_gap_land_in_pts() { + // Frame at t=0, then reanchor + a frame at t=5s: the 5 s idle gap must // appear in the PTS (otherwise audio drifts behind a wall-clock video track). let pts = published_pts(&[full_frame(0), full_frame(5_000_000)], Some(1)).await; assert_eq!(pts, vec![0, 5_000_000]); diff --git a/rs/moq-boy/src/audio.rs b/rs/moq-boy/src/audio.rs index 7c9e333d4cb..7d9304c7496 100644 --- a/rs/moq-boy/src/audio.rs +++ b/rs/moq-boy/src/audio.rs @@ -3,7 +3,7 @@ //! A thin wrapper over [`moq_audio::encode::Producer`], which resamples to //! 48 kHz, encodes Opus, and anchors timestamps to a wall clock so audio stays //! in sync with video. `push_samples` stamps each buffer with the shared -//! emulator clock; `reset_epoch` re-anchors on pause/resume so the gap lands in +//! emulator clock; `reanchor` re-anchors on pause/resume so the gap lands in //! the PTS. use std::time::Duration; @@ -41,11 +41,11 @@ impl AudioEncoder { } /// Re-anchor the timeline so a pause gap shows up in the audio PTS. - pub fn reset_epoch(&mut self) { - self.producer.reset_epoch(); + pub fn reanchor(&mut self) { + self.producer.reanchor(); } - /// Publish a marker group marking the pause, so the gap the re-anchored epoch is about + /// Publish a marker group marking the pause, so the gap the reanchor is about /// to open reads as a break rather than one very long packet. pub fn discontinuity(&mut self) -> Result<()> { self.producer.discontinuity()?; diff --git a/rs/moq-boy/src/main.rs b/rs/moq-boy/src/main.rs index 549e0dac83c..b9bcb741f9d 100644 --- a/rs/moq-boy/src/main.rs +++ b/rs/moq-boy/src/main.rs @@ -17,7 +17,7 @@ //! audio_active ─┘ //! either true → resumed (condvar notified) //! -//! On resume → force video keyframe, re-anchor audio epoch +//! On resume → force video keyframe, reanchor audio //! ``` //! //! Emulator state is preserved across pauses: a new viewer joining after a @@ -355,7 +355,7 @@ fn run_emulator( // Force a keyframe so new viewers can start decoding. session.video_encoder.force_keyframe(); // Re-anchor audio timestamps so the pause gap appears in PTS. - audio_encoder.reset_epoch(); + audio_encoder.reanchor(); } // Drain pending viewer commands before sleeping, so input that @@ -446,7 +446,7 @@ fn run_emulator( if is_audio { // Re-anchor audio PTS when audio resumes after being inactive. if !was_audio_active { - audio_encoder.reset_epoch(); + audio_encoder.reanchor(); } let samples = emu.audio_samples(); if !samples.is_empty() diff --git a/rs/moq-c/src/api.rs b/rs/moq-c/src/api.rs index 3e9f68bf611..4dbea6607b6 100644 --- a/rs/moq-c/src/api.rs +++ b/rs/moq-c/src/api.rs @@ -1201,7 +1201,7 @@ unsafe fn connect_session( /// since the origins outlive the underlying connection. /// /// `on_status` reports the session lifecycle through its status code: -/// - `> 0` on every (re)connect, carrying the connection epoch (`1` = first connect, +/// - `> 0` on every (re)connect, carrying the connect count (`1` = first connect, /// `2` = first reconnect, and so on), so a reconnect is distinguishable from the /// initial connect. May fire repeatedly. Transient disconnects are not reported. /// - `0` when the session is closed cleanly via [moq_session_close] (terminal). diff --git a/rs/moq-c/src/session.rs b/rs/moq-c/src/session.rs index 50ee51e6da2..30eef612912 100644 --- a/rs/moq-c/src/session.rs +++ b/rs/moq-c/src/session.rs @@ -202,7 +202,7 @@ impl Session { })); } - // A server-accepted session is a single transport, so it only ever reaches epoch 1. + // A server-accepted session is a single transport, so it only ever connects once. callback.call(1); Err(session.closed().await.into()) } @@ -251,7 +251,7 @@ impl Session { } } - /// Forward connection epochs to the status callback until the reconnect loop stops. + /// Forward connect counts to the status callback until the reconnect loop stops. /// /// Returns the terminal error via `?`. Disconnects aren't reported: status 0 is reserved for a /// clean close (delivered as the terminal callback once the task ends). @@ -260,11 +260,11 @@ impl Session { loop { if let moq_tokio::Status::Connected = reconnect.status().await.map_err(map_connect_error)? { connects += 1; - // Positive status carries the connection epoch, so callers can tell a + // Positive status carries the connect count, so callers can tell a // reconnect (>1) from the first connect (1). No lock is held, so the C // callback is free to re-enter moq-c. let code = i32::try_from(connects) - .context("connection epoch exceeded i32::MAX") + .context("connect count exceeded i32::MAX") .map_err(|err| Error::Connect(Arc::new(err)))?; callback.call(code); } diff --git a/rs/moq-c/src/test.rs b/rs/moq-c/src/test.rs index 0cd26c5372a..02ce3a5d608 100644 --- a/rs/moq-c/src/test.rs +++ b/rs/moq-c/src/test.rs @@ -4817,7 +4817,7 @@ fn server_accepts_a_session() { "accept consumes the request" ); - // Both sides report the first (and, for the server, only) epoch. + // Both sides report the first (and, for the server, only) connect. assert_eq!(session_cb.recv(), 1); assert_eq!(client_cb.recv(), 1); diff --git a/rs/moq-ffi/src/audio.rs b/rs/moq-ffi/src/audio.rs index e5e650d0724..172db6ecc93 100644 --- a/rs/moq-ffi/src/audio.rs +++ b/rs/moq-ffi/src/audio.rs @@ -231,11 +231,11 @@ impl MoqAudioProducer { /// /// Call this before writing after an idle gap so the gap remains visible in /// the audio PTS instead of being compressed out by the running sample count. - pub fn reset_epoch(&self) -> Result<(), MoqError> { + pub fn reanchor(&self) -> Result<(), MoqError> { let _guard = crate::ffi::runtime().enter(); let mut guard = self.inner.lock().unwrap(); let producer = guard.as_mut().ok_or(MoqError::Closed)?; - producer.reset_epoch(); + producer.reanchor(); Ok(()) } diff --git a/rs/moq-ffi/src/error.rs b/rs/moq-ffi/src/error.rs index 3bb5767d21f..d73304027b3 100644 --- a/rs/moq-ffi/src/error.rs +++ b/rs/moq-ffi/src/error.rs @@ -270,6 +270,10 @@ pub enum MoqError { #[error("invalid pattern: {reason}")] InvalidPattern { reason: String }, + /// An epoch was not a lowercase hyphenated UUIDv7. + #[error("{reason}")] + InvalidEpoch { reason: String }, + /// A catalog rendition named another broadcast, but this consumer came from a standalone /// broadcast rather than an origin, so there is nothing to resolve the reference against. #[error("unresolvable broadcast reference: {reason}")] @@ -404,6 +408,7 @@ from_message! { tracing::metadata::ParseLevelError => LogLevel, serde_json::Error => Json, moq_net::InvalidPattern => InvalidPattern, + moq_net::InvalidEpoch => InvalidEpoch, } #[cfg(not(target_arch = "wasm32"))] diff --git a/rs/moq-ffi/src/origin.rs b/rs/moq-ffi/src/origin.rs index d468212c00c..47eb40da433 100644 --- a/rs/moq-ffi/src/origin.rs +++ b/rs/moq-ffi/src/origin.rs @@ -27,7 +27,7 @@ pub struct MoqAnnounceConfig { pub hidden: bool, } -/// A path-prefix route: hops and a static cost for an advertisement. +/// A path-prefix route: hops, a static cost, and the publisher epoch for an advertisement. /// /// Pair one with `MoqBroadcastProducer::announce` for an exact path, or with /// `MoqOriginProducer::dynamic` for a prefix. Observe them with @@ -50,6 +50,14 @@ pub struct MoqRoute { /// fully identified one, whatever the costs say. #[uniffi(default = false)] pub anonymous: bool, + /// The publisher instance the route serves, as UUIDv7 text, or `None` when unknown. + /// + /// A publisher that can restart sets a fresh one per run from `moq_mint_epoch`, so + /// viewers see a restart instead of a stalled broadcast. Routes with the same epoch + /// serve the same bytes, so redundant publishers share one. Among routes at a + /// prefix the newest epoch wins, and changing it is a `MoqAnnounceEvent::Restart`. + #[uniffi(default = None)] + pub epoch: Option, } impl From for MoqRoute { @@ -58,6 +66,7 @@ impl From for MoqRoute { hops: route.hops.iter().map(|origin| origin.id()).collect(), cost: route.cost.value(), anonymous: route.is_anonymous(), + epoch: route.epoch.map(|epoch| epoch.to_string()), } } } @@ -76,12 +85,33 @@ impl TryFrom for moq_net::origin::Route { hops.push(origin) .map_err(|e| MoqError::InvalidRoute { reason: e.to_string() })?; } - Ok(moq_net::origin::Route::default() + let mut out = moq_net::origin::Route::default() .with_cost(moq_net::origin::Cost::new(route.cost)) - .with_hops(hops)) + .with_hops(hops); + if let Some(epoch) = route.epoch { + out = out.with_epoch(epoch.parse()?); + } + Ok(out) } } +/// Mint a fresh publisher epoch from the wall clock and secure randomness, ordered newest last. +#[uniffi::export] +pub fn moq_mint_epoch() -> String { + moq_net::Epoch::mint().to_string() +} + +/// The wall-clock time an epoch encodes, in milliseconds since the Unix epoch. +/// +/// Errors with `InvalidEpoch` unless the text is a lowercase hyphenated UUIDv7. +#[uniffi::export] +pub fn moq_epoch_time_ms(epoch: String) -> Result { + let epoch: moq_net::Epoch = epoch.parse()?; + let since = epoch.time().duration_since(std::time::UNIX_EPOCH).unwrap_or_default(); + // A UUIDv7 holds 48 bits of milliseconds, so this never truncates. + Ok(since.as_millis() as u64) +} + #[derive(uniffi::Object)] pub struct MoqOriginProducer { inner: moq_net::origin::Producer, @@ -175,7 +205,7 @@ pub struct MoqAnnounce { pub prefix: String, /// What each wildcard matched, or `None` when the route only overlaps the scope. pub captures: Option>, - /// The route serving the prefix: its hops and a static cost. + /// The route serving the prefix: its epoch, hops, and a static cost. pub route: MoqRoute, } @@ -426,7 +456,7 @@ impl MoqOriginDynamic { .await } - /// Re-price the route in place: replace its hops and a static cost. The prefix cannot + /// Replace the route in place: its epoch, hops, and a static cost. The prefix cannot /// change; call `dynamic` again instead. pub fn update(&self, route: MoqRoute) -> Result<(), MoqError> { let _guard = crate::ffi::enter(); diff --git a/rs/moq-ffi/src/session.rs b/rs/moq-ffi/src/session.rs index 84388a81177..c4c1a8800cd 100644 --- a/rs/moq-ffi/src/session.rs +++ b/rs/moq-ffi/src/session.rs @@ -565,7 +565,7 @@ impl MoqClient { /// A native session automatically reconnects with backoff when the transport drops /// (unless [`MoqClientConfig::once`] is set), and broadcasts consumed through it ride out /// the gap. Watch [`MoqSession::status`] for the connect/disconnect transitions, - /// [`MoqSession::epoch`] for the reconnect count, and [`MoqSession::closed`] for the + /// [`MoqSession::connects`] for the reconnect count, and [`MoqSession::closed`] for the /// connection giving up for good. /// /// Both origin sides are always accessible via [`MoqSession::publish`] and @@ -799,16 +799,16 @@ impl MoqSession { .await } - /// The connection epoch: 1 for the connect this session was built from, one more + /// How many times this session has connected: 1 for the connect it was built from, one more /// on each reconnect. A server-accepted session is a single transport, so it stays 1. /// /// The count pairs with [`status`](Self::status): a `Connected` transition whose - /// epoch grew is a reconnect, so a worker can log each one by number. Migrations + /// count grew is a reconnect, so a worker can log each one by number. Migrations /// count too, since the replacement is a new session. - pub fn epoch(&self) -> u64 { + pub fn connects(&self) -> u64 { match &self.inner { #[cfg(not(target_arch = "wasm32"))] - Inner::Connection(connection) => connection.epoch(), + Inner::Connection(connection) => connection.connects(), Inner::Session(_) => 1, } } diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index 9be9b9eb05c..2b9b002933e 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -329,6 +329,7 @@ fn route_cost_conversions_are_lossless() { hops: vec![], cost: 5, anonymous: false, + epoch: None, }) .unwrap(); assert_eq!(seeded.cost, moq_net::origin::Cost::new(5)); @@ -350,6 +351,7 @@ async fn announced_route_keeps_static_cost_on_reannounce() { hops: vec![], cost: 9, anonymous: false, + epoch: None, }) .unwrap(); @@ -375,6 +377,76 @@ async fn announced_route_keeps_static_cost_on_reannounce() { broadcast.close().unwrap(); } +#[test] +fn epoch_helpers_mint_parse_and_refuse() { + let epoch = moq_mint_epoch(); + let parsed: moq_net::Epoch = epoch.parse().unwrap(); + let unix_ms = parsed.time().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis(); + assert_eq!(u128::from(moq_epoch_time_ms(epoch.clone()).unwrap()), unix_ms); + assert!(moq_mint_epoch() > epoch, "a later mint orders newer"); + + // The text the route carries round-trips, and anything but a UUIDv7 is refused. + let route = MoqRoute { + epoch: Some(epoch.clone()), + ..Default::default() + }; + let back = moq_net::origin::Route::try_from(route.clone()).unwrap(); + assert_eq!(back.epoch, Some(parsed)); + assert_eq!(MoqRoute::from(back), route); + + let uuid_v4 = "6ba7b810-9dad-41d1-80b4-00c04fd430c8".to_string(); + for bad in [uuid_v4, epoch.to_uppercase(), String::new()] { + assert!(matches!( + moq_epoch_time_ms(bad.clone()), + Err(MoqError::InvalidEpoch { .. }) + )); + let route = MoqRoute { + epoch: Some(bad), + ..Default::default() + }; + assert!(matches!( + moq_net::origin::Route::try_from(route), + Err(MoqError::InvalidEpoch { .. }) + )); + } +} + +#[tokio::test] +async fn announced_epoch_restarts_on_a_new_epoch() { + let origin = MoqOriginProducer::new(MoqOriginConfig::default()); + let consumer = origin.consume(); + let announced = consumer.announced(MoqAnnounceConfig::default()).unwrap(); + let broadcast = origin.create_broadcast("epoch-route".into()).unwrap(); + + let first = moq_mint_epoch(); + broadcast + .announce(MoqRoute { + epoch: Some(first.clone()), + ..Default::default() + }) + .unwrap(); + let announce = next_announced(&announced).await; + assert_eq!(announce.route.epoch, Some(first)); + + // A new run of the same publisher is another instance: consumers restart onto it. + let second = moq_mint_epoch(); + broadcast + .announce(MoqRoute { + epoch: Some(second.clone()), + ..Default::default() + }) + .unwrap(); + match next_event(&announced).await { + MoqAnnounceEvent::Restart { announce } => { + assert_eq!(announce.prefix, "epoch-route"); + assert_eq!(announce.route.epoch, Some(second)); + } + other => panic!("expected a restart, got {other:?}"), + } + + broadcast.close().unwrap(); +} + #[test] fn publish_media_lifecycle() { let broadcast = MoqBroadcastProducer::new().unwrap(); @@ -503,7 +575,7 @@ async fn raw_audio_activity() { .await .expect("timed out waiting for raw audio to become used again") .unwrap(); - audio.reset_epoch().unwrap(); + audio.reanchor().unwrap(); audio .write(MoqAudioFrame { timestamp_us: RESUMED_TIMESTAMP_US, @@ -4299,7 +4371,7 @@ async fn client_reconnects_and_resumes_announcements() { .expect("status timed out") .expect("status errored"); assert_eq!(status, MoqConnectionStatus::Connected); - assert_eq!(cs.epoch(), 1); + assert_eq!(cs.connects(), 1); // Kill the transport under the client, simulating a relay restart. // Nothing accepts the redial until the gate opens. @@ -4323,15 +4395,15 @@ async fn client_reconnects_and_resumes_announcements() { .expect("reconnect status errored"); assert_eq!(status, MoqConnectionStatus::Connected); - // The reconnect advances the epoch. The watcher may land just after the status + // The reconnect advances the count. The watcher may land just after the status // edge it watched, so poll rather than assume ordering. tokio::time::timeout(TIMEOUT, async { - while cs.epoch() < 2 { + while cs.connects() < 2 { tokio::time::sleep(Duration::from_millis(10)).await; } }) .await - .expect("the epoch did not advance on reconnect"); + .expect("the connect count did not advance on reconnect"); let server_session = tokio::time::timeout(TIMEOUT, accept) .await diff --git a/rs/moq-tokio/src/connection.rs b/rs/moq-tokio/src/connection.rs index f3bf763f31e..1fbb4372517 100644 --- a/rs/moq-tokio/src/connection.rs +++ b/rs/moq-tokio/src/connection.rs @@ -453,8 +453,8 @@ struct State { status: Option, /// How many sessions have been live on this handle, counting the current one. /// Advanced by `Shared::connected` with the same write that publishes `status`, - /// so a reader can't see `Connected` without its epoch. - epoch: u64, + /// so a reader can't see `Connected` without its count. + connects: u64, /// Cumulative connects and disconnects, bumped by the reconnect loop itself so a session that /// connects and drops before a consumer polls still counts. presence: moq_net::stats::Presence, @@ -507,7 +507,7 @@ impl Shared { state.presence.sessions_ended += 1; } state.status = Some(Status::Connected); - state.epoch += 1; + state.connects += 1; state.presence.sessions_started += 1; state.version = Some(session.version()); state.transport = Some(transport); @@ -664,7 +664,7 @@ pub struct Snapshot { /// and [`recv_bandwidth`](Self::recv_bandwidth) track the live session and reset while disconnected. /// The extra toggle a plain session doesn't have is the connection lifecycle: [`established`](Self::established) /// waits for the first session, [`connected`](Self::connected) reads the current state synchronously, -/// [`epoch`](Self::epoch) counts the sessions so far, and [`status`](Self::status) waits for the +/// [`connects`](Self::connects) counts the sessions so far, and [`status`](Self::status) waits for the /// next change. [`closed`](Self::closed) waits for the loop to stop. Clones share the loop; it /// stops when the last clone drops (or on an explicit [`abort`](Self::abort)). #[derive(Clone)] @@ -1202,8 +1202,8 @@ impl Connection { /// Advanced in the same write that publishes [`Status::Connected`], so reading /// after a `Connected` status never returns a stale count. Zero only if no /// session has connected yet, which [`established`](Self::established) rules out. - pub fn epoch(&self) -> u64 { - self.state.read().epoch + pub fn connects(&self) -> u64 { + self.state.read().connects } /// The negotiated MoQ version of the live session, or `None` while disconnected. @@ -2588,7 +2588,7 @@ mod tests { ); assert!(connection.connected()); assert_eq!(connection.transport(), Some(crate::Transport::WebTransport)); - assert_eq!(connection.epoch(), 2); + assert_eq!(connection.connects(), 2); let (transport, _quic) = fallback.accept().await; assert_eq!(transport, crate::Transport::WebTransport); // QUIC works on this network, so the next dial gives it the head start again. @@ -2677,7 +2677,7 @@ mod tests { let status = tokio::time::timeout(UPGRADE_WAIT, connection.status()).await.unwrap(); assert_eq!(status.unwrap(), Status::Connected); assert_eq!(connection.transport(), Some(crate::Transport::WebSocket)); - assert_eq!(connection.epoch(), 1); + assert_eq!(connection.connects(), 1); assert!( websocket.draining().peek().is_none(), "the refused upgrade drained WebSocket" @@ -2798,7 +2798,7 @@ mod tests { .expect("a failed WebSocket handshake must fall back to the pending QUIC dial"); assert_eq!(connection.transport(), Some(crate::Transport::WebTransport)); - assert_eq!(connection.epoch(), 1); + assert_eq!(connection.connects(), 1); let (transport, _session) = fallback.accept().await; assert_eq!(transport, crate::Transport::WebTransport); // QUIC works on this network, so the next dial gives it the head start again. @@ -2848,7 +2848,7 @@ mod tests { // QUIC's win dropped the fallback before it dialed, so there is nothing else to // accept and nothing to upgrade from. assert!(fallback.accepted.try_recv().is_err(), "a second session was opened"); - assert_eq!(connection.epoch(), 1); + assert_eq!(connection.connects(), 1); assert!(!crate::websocket::won(&fallback.url)); } diff --git a/rs/moq-tokio/tests/backend.rs b/rs/moq-tokio/tests/backend.rs index 367fea04e1c..bce0781c987 100644 --- a/rs/moq-tokio/tests/backend.rs +++ b/rs/moq-tokio/tests/backend.rs @@ -968,7 +968,7 @@ async fn noq_client_close_drains_migrated_predecessor() { subscribed_tx.send(()).unwrap(); // Once the replacement is live, only the predecessor serves the subscription. - while connection.epoch() < 2 || !connection.connected() { + while connection.connects() < 2 || !connection.connected() { connection.status().await.expect("connection stopped"); } migrated_tx.send(()).unwrap(); diff --git a/rs/moq-tokio/tests/reconnect.rs b/rs/moq-tokio/tests/reconnect.rs index c2ecf04bf74..6515721fb96 100644 --- a/rs/moq-tokio/tests/reconnect.rs +++ b/rs/moq-tokio/tests/reconnect.rs @@ -54,11 +54,11 @@ async fn a_transient_failure_retries_until_the_budget_runs_out() { ); } -/// The epoch advances in the same write that reports `Connected`, so a caller -/// pairing [`Connection::status`] with [`Connection::epoch`] never sees a stale +/// The connect count advances in the same write that reports `Connected`, so a caller +/// pairing [`Connection::status`] with [`Connection::connects`] never sees a stale /// count, however fast the redial. #[tokio::test] -async fn the_epoch_advances_on_reconnect() { +async fn the_connect_count_advances_on_reconnect() { let (port, mut sessions, _task) = spawn_server().await; let url: url::Url = format!("tcp://localhost:{port}/").parse().expect("parse url"); let mut connection = quick_client(Default::default()).connect(url); @@ -68,19 +68,19 @@ async fn the_epoch_advances_on_reconnect() { .expect("status timed out") .expect("status failed"); assert_eq!(status, moq_tokio::Status::Connected); - assert_eq!(connection.epoch(), 1, "the first connect is epoch 1"); + assert_eq!(connection.connects(), 1, "the first connect counts 1"); // Dropping the server's handle closes the session, so the loop redials. let session = sessions.recv().await.expect("server stopped accepting"); drop(session); tokio::time::timeout(Duration::from_secs(10), async { - while connection.epoch() < 2 { + while connection.connects() < 2 { tokio::time::sleep(Duration::from_millis(10)).await; } }) .await - .expect("the epoch never advanced past the first connect"); + .expect("the connect count never advanced past the first connect"); } #[tokio::test] diff --git a/swift/README.md b/swift/README.md index 46bae58e111..6242cdc9349 100644 --- a/swift/README.md +++ b/swift/README.md @@ -35,8 +35,13 @@ let session = try await client.connect(to: "https://relay.example.com") // origin between both sides. let announced = try session.consume.announced(prefix: "demos/", filter: "*/camera") for try await event in announced { - // `.update` reprices a route and `.end` retracts it. - guard case .start(let announcement) = event else { continue } + // `.update` reprices a route and `.end` retracts it. A `.restart` is a new + // publisher run at the same path: request it again. + let announcement: Announce + switch event { + case .start(let started), .restart(let started): announcement = started + default: continue + } // Prefix stays origin-relative; captures reports what * matched. print("got broadcast \(announcement.prefix)") print("captures \(announcement.captures ?? [])") diff --git a/swift/Sources/Moq/Aliases.swift b/swift/Sources/Moq/Aliases.swift index 2d96d853fb8..bfe8018b5fc 100644 --- a/swift/Sources/Moq/Aliases.swift +++ b/swift/Sources/Moq/Aliases.swift @@ -48,15 +48,16 @@ public typealias VideoCodec = MoqFFI.MoqVideoCodec public typealias VideoEncoderKind = MoqFFI.MoqVideoEncoderKind /// A best-effort raw-track datagram as received: sequence, timestamp, and payload. public typealias Datagram = MoqFFI.MoqDatagram -/// A path-prefix route: the prefix it covers, relay hop ids (oldest first), -/// and its static production and link cost, lower wins. +/// A path-prefix route: the publisher `epoch` it serves (`nil` when unknown), +/// relay hop ids (oldest first), and its static production and link cost, +/// lower wins. public typealias Route = MoqFFI.MoqRoute /// A route over a prefix: the origin-relative `prefix`, what each filter /// wildcard matched (`captures`, `nil` for a partial overlap), and the `route` /// serving it. Resolve a path with `OriginConsumer.requestBroadcast`. public typealias Announce = MoqFFI.MoqAnnounce -/// What an `AnnounceConsumer` yields: `.start`, `.update`, or `.end`, each -/// carrying an `Announce`. +/// What an `AnnounceConsumer` yields: `.start`, `.update`, `.end`, or +/// `.restart` (request the path again), each carrying an `Announce`. public typealias AnnounceEvent = MoqFFI.MoqAnnounceEvent /// Per-subscription delivery preferences: priority, group ordering, latency /// budget, and group range. diff --git a/swift/Sources/Moq/Audio.swift b/swift/Sources/Moq/Audio.swift index 8372079aca9..0ed76459bb3 100644 --- a/swift/Sources/Moq/Audio.swift +++ b/swift/Sources/Moq/Audio.swift @@ -60,8 +60,8 @@ public final class AudioProducer: Sendable { } /// Re-anchor the timeline to the next frame after an idle gap. - public func resetEpoch() throws { - try ffi.resetEpoch() + public func reanchor() throws { + try ffi.reanchor() } /// Encode and write one PCM frame. diff --git a/swift/Sources/Moq/Client.swift b/swift/Sources/Moq/Client.swift index 3cf061b0d51..f65422a28af 100644 --- a/swift/Sources/Moq/Client.swift +++ b/swift/Sources/Moq/Client.swift @@ -95,13 +95,13 @@ public final class Session: Sendable { try await ffi.status() } - /// The connection epoch: 1 for the connect that built this session, one more + /// How many times this session has connected: 1 for the connect that built it, one more /// on each reconnect. A server-accepted session stays at 1. /// /// Pair it with `status()` to log each reconnect by number: a `.connected` - /// status whose epoch grew is a reconnect. - public func epoch() -> UInt64 { - ffi.epoch() + /// status whose count grew is a reconnect. + public func connects() -> UInt64 { + ffi.connects() } /// Close the session with the given error code. Code 0 means "no error"; diff --git a/swift/Sources/Moq/Epoch.swift b/swift/Sources/Moq/Epoch.swift new file mode 100644 index 00000000000..6b249201f9f --- /dev/null +++ b/swift/Sources/Moq/Epoch.swift @@ -0,0 +1,17 @@ +import Foundation +import MoqFFI + +/// Mint a fresh publisher epoch from the wall clock and secure randomness, +/// ordered newest last. Mint one per publisher run and announce it in +/// `Route.epoch`, so viewers see a restart as a new broadcast instead of a +/// stalled one. +public func mintEpoch() -> String { + moqMintEpoch() +} + +/// The wall-clock time an epoch encodes, to the millisecond. Throws unless +/// `epoch` is a lowercase hyphenated UUIDv7. +public func epochTime(_ epoch: String) throws -> Date { + let ms = try moqEpochTimeMs(epoch: epoch) + return Date(timeIntervalSince1970: Double(ms) / 1000) +} diff --git a/swift/Tests/MoqTests/SmokeTests.swift b/swift/Tests/MoqTests/SmokeTests.swift index 05ebb92e9a1..f8c80f98263 100644 --- a/swift/Tests/MoqTests/SmokeTests.swift +++ b/swift/Tests/MoqTests/SmokeTests.swift @@ -137,6 +137,29 @@ final class SmokeTests: XCTestCase { XCTAssertEqual(update.captures, ["alice"]) } + func testAnnouncedEpochRestarts() async throws { + let origin = OriginProducer() + let announced = try origin.consume().announced(prefix: "") + let broadcast = try origin.createBroadcast(path: "epoch") + + let first = mintEpoch() + XCTAssertEqual(try epochTime("018bcfe5-6800-7000-8000-000000000000"), Date(timeIntervalSince1970: 1_700_000_000)) + try broadcast.announce(route: Route(epoch: first)) + guard case .start(let start) = try await nextRoute(announced) else { + return XCTFail("expected an announcement") + } + XCTAssertEqual(start.route.epoch, first) + + let second = mintEpoch() + try broadcast.announce(route: Route(epoch: second)) + guard case .restart(let restart) = try await nextRoute(announced) else { + return XCTFail("expected a restart") + } + XCTAssertEqual(restart.route.epoch, second) + + XCTAssertThrowsError(try epochTime("not-an-epoch")) + } + func testDynamicServesARequestUnderAPrefix() async throws { let origin = OriginProducer() let dynamic = try origin.dynamic(prefix: "live")