moq_wasm.media

Follows and publishes MSF broadcasts on a moq_wasm.Session (docs/architecture/python/sdk.md "Media").

 1"""Follows and publishes MSF broadcasts on a `moq_wasm.Session` (docs/architecture/python/sdk.md
 2"Media")."""
 3
 4from moq_wasm._following import Following
 5from moq_wasm._native import Demand
 6from moq_wasm.media._catalog import CATALOG_TRACK_NAME, Catalog, CatalogTrack
 7from moq_wasm.media._event_timeline import EventRecord, EventTimeline
 8from moq_wasm.media._local_broadcast import LocalBroadcast, create_broadcast
 9from moq_wasm.media._media_source import MediaSource, Rendition
10from moq_wasm.media._remote_broadcast import RemoteBroadcast, watch_broadcasts
11
12__all__ = [
13    "CATALOG_TRACK_NAME",
14    "Catalog",
15    "CatalogTrack",
16    "Demand",
17    "EventRecord",
18    "EventTimeline",
19    "Following",
20    "LocalBroadcast",
21    "MediaSource",
22    "RemoteBroadcast",
23    "Rendition",
24    "create_broadcast",
25    "watch_broadcasts",
26]
CATALOG_TRACK_NAME = 'catalog'
@dataclass(frozen=True)
class Catalog:
 47@dataclass(frozen=True)
 48class Catalog:
 49    """An independent draft-02 MSF catalog; `fields` holds every field of its root as it was
 50    written, `tracks` and `initDataList` included."""
 51
 52    tracks: list[CatalogTrack]
 53    fields: dict[str, Any] = field(default_factory=dict, compare=False, repr=False)
 54
 55    @classmethod
 56    def parse(cls, payload: bytes) -> "Catalog":
 57        """Raises ValueError for what `moq_wasm.parse_catalog` refuses."""
 58        document = parse_catalog(payload)
 59        return cls([CatalogTrack.from_json(track) for track in document["tracks"]], document)
 60
 61    def init_data(self, track: CatalogTrack) -> bytes | None:
 62        """The initialization data `track`'s `initRef` points at in this catalog's `initDataList`
 63        (draft-ietf-moq-msf-02 §5.1.7, §5.2.14), such as an AAC AudioSpecificConfig or a CMAF
 64        initialization segment, decoded from Base64. None for a track without `initRef`, one whose
 65        entry this catalog lacks, and one of the `track-property` or `object-property` types, whose
 66        data the track or its objects carry instead. Raises ValueError when an `inline` entry's data
 67        is not Base64."""
 68        init_ref = track.fields.get("initRef")
 69        entries = self.fields.get("initDataList")
 70        if init_ref is None or not isinstance(entries, list):
 71            return None
 72        for entry in entries:
 73            if isinstance(entry, dict) and entry.get("id") == init_ref:
 74                if entry.get("type") != "inline":
 75                    return None
 76                try:
 77                    return base64.b64decode(entry.get("data", ""), validate=True)
 78                except (binascii.Error, TypeError) as error:
 79                    raise ValueError(f"initialization data {init_ref!r} is not Base64: {error}") from None
 80        return None
 81
 82    def select(
 83        self,
 84        *,
 85        role: str | None = None,
 86        packaging: str | None = None,
 87        codec: str | None = None,
 88        prefer: Literal["lowest_bitrate", "highest_bitrate"] | None = None,
 89    ) -> CatalogTrack | None:
 90        """The track whose fields match those given, the first in the catalog or the one `prefer`
 91        names. `codec` matches the codec string or its first element: `"avc1"` matches
 92        `"avc1.42e01f"`. A track without a bitrate, which draft-ietf-moq-msf-02 requires only of
 93        audio and video, counts as the highest."""
 94        matching = [
 95            track
 96            for track in self.tracks
 97            if (role is None or track.role == role)
 98            and (packaging is None or track.packaging == packaging)
 99            and (codec is None or _codec_matches(track.codec, codec))
100        ]
101        if not matching:
102            return None
103        if prefer == "lowest_bitrate":
104            return min(matching, key=_bitrate_or_highest)
105        if prefer == "highest_bitrate":
106            return max(matching, key=_bitrate_or_highest)
107        return matching[0]

An independent draft-02 MSF catalog; fields holds every field of its root as it was written, tracks and initDataList included.

Catalog( tracks: list[CatalogTrack], fields: dict[str, typing.Any] = <factory>)
tracks: list[CatalogTrack]
fields: dict[str, typing.Any]
@classmethod
def parse(cls, payload: bytes) -> Catalog:
55    @classmethod
56    def parse(cls, payload: bytes) -> "Catalog":
57        """Raises ValueError for what `moq_wasm.parse_catalog` refuses."""
58        document = parse_catalog(payload)
59        return cls([CatalogTrack.from_json(track) for track in document["tracks"]], document)

Raises ValueError for what moq_wasm.parse_catalog refuses.

def init_data(self, track: CatalogTrack) -> bytes | None:
61    def init_data(self, track: CatalogTrack) -> bytes | None:
62        """The initialization data `track`'s `initRef` points at in this catalog's `initDataList`
63        (draft-ietf-moq-msf-02 §5.1.7, §5.2.14), such as an AAC AudioSpecificConfig or a CMAF
64        initialization segment, decoded from Base64. None for a track without `initRef`, one whose
65        entry this catalog lacks, and one of the `track-property` or `object-property` types, whose
66        data the track or its objects carry instead. Raises ValueError when an `inline` entry's data
67        is not Base64."""
68        init_ref = track.fields.get("initRef")
69        entries = self.fields.get("initDataList")
70        if init_ref is None or not isinstance(entries, list):
71            return None
72        for entry in entries:
73            if isinstance(entry, dict) and entry.get("id") == init_ref:
74                if entry.get("type") != "inline":
75                    return None
76                try:
77                    return base64.b64decode(entry.get("data", ""), validate=True)
78                except (binascii.Error, TypeError) as error:
79                    raise ValueError(f"initialization data {init_ref!r} is not Base64: {error}") from None
80        return None

The initialization data track's initRef points at in this catalog's initDataList (draft-ietf-moq-msf-02 §5.1.7, §5.2.14), such as an AAC AudioSpecificConfig or a CMAF initialization segment, decoded from Base64. None for a track without initRef, one whose entry this catalog lacks, and one of the track-property or object-property types, whose data the track or its objects carry instead. Raises ValueError when an inline entry's data is not Base64.

def select( self, *, role: str | None = None, packaging: str | None = None, codec: str | None = None, prefer: Literal['lowest_bitrate', 'highest_bitrate'] | None = None) -> CatalogTrack | None:
 82    def select(
 83        self,
 84        *,
 85        role: str | None = None,
 86        packaging: str | None = None,
 87        codec: str | None = None,
 88        prefer: Literal["lowest_bitrate", "highest_bitrate"] | None = None,
 89    ) -> CatalogTrack | None:
 90        """The track whose fields match those given, the first in the catalog or the one `prefer`
 91        names. `codec` matches the codec string or its first element: `"avc1"` matches
 92        `"avc1.42e01f"`. A track without a bitrate, which draft-ietf-moq-msf-02 requires only of
 93        audio and video, counts as the highest."""
 94        matching = [
 95            track
 96            for track in self.tracks
 97            if (role is None or track.role == role)
 98            and (packaging is None or track.packaging == packaging)
 99            and (codec is None or _codec_matches(track.codec, codec))
100        ]
101        if not matching:
102            return None
103        if prefer == "lowest_bitrate":
104            return min(matching, key=_bitrate_or_highest)
105        if prefer == "highest_bitrate":
106            return max(matching, key=_bitrate_or_highest)
107        return matching[0]

The track whose fields match those given, the first in the catalog or the one prefer names. codec matches the codec string or its first element: "avc1" matches "avc1.42e01f". A track without a bitrate, which draft-ietf-moq-msf-02 requires only of audio and video, counts as the highest.

@dataclass(frozen=True)
class CatalogTrack:
12@dataclass(frozen=True)
13class CatalogTrack:
14    """A track of an MSF catalog (draft-ietf-moq-msf-02 §5.2); `fields` holds every field as it
15    was written, including those without an attribute here."""
16
17    name: str
18    namespace: list[str] | None = None
19    role: str | None = None
20    packaging: str | None = None
21    codec: str | None = None
22    bitrate: int | None = None
23    width: int | None = None
24    height: int | None = None
25    framerate: float | None = None
26    samplerate: int | None = None
27    fields: dict[str, Any] = field(default_factory=dict, compare=False, repr=False)
28
29    @classmethod
30    def from_json(cls, track: dict[str, Any]) -> "CatalogTrack":
31        namespace = track.get("namespace")
32        return cls(
33            name=track["name"],
34            namespace=namespace.split("/") if namespace else None,
35            role=track.get("role"),
36            packaging=track.get("packaging"),
37            codec=track.get("codec"),
38            bitrate=track.get("bitrate"),
39            width=track.get("width"),
40            height=track.get("height"),
41            framerate=track.get("framerate"),
42            samplerate=track.get("samplerate"),
43            fields=track,
44        )

A track of an MSF catalog (draft-ietf-moq-msf-02 §5.2); fields holds every field as it was written, including those without an attribute here.

CatalogTrack( name: str, namespace: list[str] | None = None, role: str | None = None, packaging: str | None = None, codec: str | None = None, bitrate: int | None = None, width: int | None = None, height: int | None = None, framerate: float | None = None, samplerate: int | None = None, fields: dict[str, typing.Any] = <factory>)
name: str
namespace: list[str] | None = None
role: str | None = None
packaging: str | None = None
codec: str | None = None
bitrate: int | None = None
width: int | None = None
height: int | None = None
framerate: float | None = None
samplerate: int | None = None
fields: dict[str, typing.Any]
@classmethod
def from_json( cls, track: dict[str, typing.Any]) -> CatalogTrack:
29    @classmethod
30    def from_json(cls, track: dict[str, Any]) -> "CatalogTrack":
31        namespace = track.get("namespace")
32        return cls(
33            name=track["name"],
34            namespace=namespace.split("/") if namespace else None,
35            role=track.get("role"),
36            packaging=track.get("packaging"),
37            codec=track.get("codec"),
38            bitrate=track.get("bitrate"),
39            width=track.get("width"),
40            height=track.get("height"),
41            framerate=track.get("framerate"),
42            samplerate=track.get("samplerate"),
43            fields=track,
44        )
class Demand:

Whether a subscriber takes track_name (draft-18 §10.10).

track_name
wanted
EventRecord = dict[str, typing.Any]
class EventTimeline:
11class EventTimeline:
12    """Writes a draft-ietf-moq-msf-02 §8 event timeline on a track as one group: it opens with an
13    empty record list once the track is registered, at once for a writer registered already, and
14    each record is one more object, so a late joiner's joining FETCH brings those the track still
15    keeps (`retention_seconds`). A record is the §8 JSON object, such as `{"L": [group, object],
16    "data": ...}` or `{"T": milliseconds, "data": ...}`."""
17
18    def __init__(self, writer: TrackWriter):
19        self._writer = writer
20        self._opening: Once[None] = Once()
21        writer._when_bound(self._open)
22
23    async def append(self, record: EventRecord) -> None:
24        """Waits until the track is registered and the timeline opened, then writes `record`.
25        Raises ValueError at once for a record JSON cannot carry, such as one with a NaN, what
26        failed the track's registration or the opening write, which closes the track, and
27        RuntimeError once the track was closed, as by leaving its broadcast, even while the opening
28        was sent."""
29        payload = _encode([record])
30        await self._writer.registered()
31        await self._open()
32        await self._writer.write(payload)
33
34    async def _open(self) -> None:
35        """Writes the opening empty record list once, ahead of every record."""
36        await self._opening.run(self._write_opening)
37
38    async def _write_opening(self) -> None:
39        await self._writer.write(_encode([]), new_group=True)

Writes a draft-ietf-moq-msf-02 §8 event timeline on a track as one group: it opens with an empty record list once the track is registered, at once for a writer registered already, and each record is one more object, so a late joiner's joining FETCH brings those the track still keeps (retention_seconds). A record is the §8 JSON object, such as {"L": [group, object], "data": ...} or {"T": milliseconds, "data": ...}.

EventTimeline(writer: moq_wasm.TrackWriter)
18    def __init__(self, writer: TrackWriter):
19        self._writer = writer
20        self._opening: Once[None] = Once()
21        writer._when_bound(self._open)
async def append(self, record: dict[str, typing.Any]) -> None:
23    async def append(self, record: EventRecord) -> None:
24        """Waits until the track is registered and the timeline opened, then writes `record`.
25        Raises ValueError at once for a record JSON cannot carry, such as one with a NaN, what
26        failed the track's registration or the opening write, which closes the track, and
27        RuntimeError once the track was closed, as by leaving its broadcast, even while the opening
28        was sent."""
29        payload = _encode([record])
30        await self._writer.registered()
31        await self._open()
32        await self._writer.write(payload)

Waits until the track is registered and the timeline opened, then writes record. Raises ValueError at once for a record JSON cannot carry, such as one with a NaN, what failed the track's registration or the opening write, which closes the track, and RuntimeError once the track was closed, as by leaving its broadcast, even while the opening was sent.

class Following(collections.abc.AsyncIterator[~T]):
 11class Following(AsyncIterator[T]):
 12    """What `RemoteBroadcast` follows: its catalogs, a track's objects or its subscriptions; and the
 13    pictures `moq_wasm.codecs` decodes. Each read advances it in the reader's own task, awaiting
 14    its sources directly, and keeps its state between reads, so a read cancelled, as by
 15    `asyncio.wait_for` timing out, leaves the next read to go on where it stopped: what the SDK
 16    awaits, a `moq_wasm.Subscription`'s read or a SUBSCRIBE, stays in flight for it. One read at a
 17    time: a read while another waits raises RuntimeError at once.
 18
 19    `aclose()` unsubscribes, waiting until the UNSUBSCRIBE was sent, after the relay answered a
 20    SUBSCRIBE still in flight, even when its caller is cancelled meanwhile, then raises the
 21    caller's cancellation; reads after it raise StopAsyncIteration. Called from another task while
 22    a read waits, it cancels that read, which raises StopAsyncIteration. Called from within a read,
 23    as from an `on_subscribed` callback, it returns at once: the read finishes the close and raises
 24    StopAsyncIteration instead of returning what it read. A task the read awaits must not await
 25    `aclose()`, which waits for the read. The iteration ending, or raising, unsubscribes too,
 26    before the read raises; a read cancelled meanwhile leaves that to the next read. Read it in
 27    `contextlib.aclosing` to unsubscribe as soon as the reading stops: one dropped without
 28    `aclose()` unsubscribes only once it is garbage collected."""
 29
 30    # Whether `aclose()` from another task cancels the read in flight: false for an iteration whose
 31    # reads await a source of the caller's, which the cancellation would reach.
 32    _interrupts = True
 33
 34    def __init__(self, what: str):
 35        self._what = what
 36        # The task of the read in flight.
 37        self._reader: asyncio.Task | None = None
 38        # The task of the read whose advance (`_next`) is in flight; `_idle` is clear meanwhile.
 39        self._advancing: asyncio.Task | None = None
 40        self._idle = asyncio.Event()
 41        self._idle.set()
 42        # Whether `aclose()` cancelled the advance in flight, which the read takes back.
 43        self._interrupting = False
 44        # What the read raises once the close the iteration's end started finished: the failure
 45        # that ended it, or StopAsyncIteration.
 46        self._ending: BaseException | None = None
 47        self._closing: Once[None] = Once()
 48
 49    def __aiter__(self) -> "Following[T]":
 50        return self
 51
 52    async def __anext__(self) -> T:
 53        if self._reader is not None:
 54            raise RuntimeError(f"{self._what} is already being read")
 55        reader = asyncio.current_task()
 56        assert reader is not None, "a read runs in a task"
 57        self._reader = reader
 58        try:
 59            if self._ending is None:
 60                if self._closing.started:
 61                    raise StopAsyncIteration
 62                item = await self._advance(reader)
 63                if self._ending is None:
 64                    return cast(T, item)
 65            # Ended, failed or closed during the read: the close goes first. A read cancelled
 66            # meanwhile, as by a timeout, leaves it going for the next read to wait for.
 67            closing = self._start_closing()
 68            await asyncio.wait([closing])
 69            ending, self._ending = self._ending, None
 70            if isinstance(ending, StopAsyncIteration):
 71                closing.result()
 72            raise ending
 73        finally:
 74            self._reader = None
 75
 76    async def _advance(self, reader: asyncio.Task) -> T | None:
 77        """`_next()`; sets `_ending` when the iteration ended, failed or was closed meanwhile, and
 78        raises the reader's own cancellation, which leaves the state to the next read."""
 79        self._advancing = reader
 80        self._idle.clear()
 81        try:
 82            item = await self._next()
 83        except BaseException as error:
 84            interrupted = self._take_interruption(reader)
 85            if isinstance(error, asyncio.CancelledError) and not interrupted and reader.cancelling():
 86                raise
 87            stopped = interrupted or isinstance(error, StopAsyncIteration)
 88            self._ending = StopAsyncIteration() if stopped else error
 89            return None
 90        else:
 91            self._take_interruption(reader)
 92            if self._closing.started:
 93                self._ending = StopAsyncIteration()
 94            return item
 95        finally:
 96            self._advancing = None
 97            self._idle.set()
 98
 99    async def aclose(self) -> None:
100        closing = self._start_closing()
101        if self._advancing is not None and self._advancing is asyncio.current_task():
102            return
103        await wait_through_cancellation([closing])
104        closing.result()
105
106    def _start_closing(self) -> asyncio.Future[None]:
107        """Starts the close unless it started, cancelling an advance in flight in another task;
108        returns a future of the caller's own that resolves once it finished."""
109        advancing = self._advancing
110        if not self._closing.started and self._interrupts and advancing is not None:
111            if advancing is not asyncio.current_task():
112                self._interrupting = True
113                advancing.cancel()
114        return self._closing.start(self._close)
115
116    def _take_interruption(self, reader: asyncio.Task) -> bool:
117        """Takes back the cancellation `aclose()` sent the read; whether the read was cancelled by
118        it alone."""
119        if not self._interrupting:
120            return False
121        self._interrupting = False
122        return reader.uncancel() == 0
123
124    async def _close(self) -> None:
125        if self._interrupts:
126            await self._idle.wait()
127        await self._release()
128
129    async def _next(self) -> T:
130        """Advances the iteration; raises StopAsyncIteration at its end. Cancelled, it leaves its
131        state consistent for the next call."""
132        raise NotImplementedError
133
134    async def _release(self) -> None:
135        """Releases what the iteration owns, once no read is in flight."""

What RemoteBroadcast follows: its catalogs, a track's objects or its subscriptions; and the pictures moq_wasm.codecs decodes. Each read advances it in the reader's own task, awaiting its sources directly, and keeps its state between reads, so a read cancelled, as by asyncio.wait_for timing out, leaves the next read to go on where it stopped: what the SDK awaits, a moq_wasm.Subscription's read or a SUBSCRIBE, stays in flight for it. One read at a time: a read while another waits raises RuntimeError at once.

aclose() unsubscribes, waiting until the UNSUBSCRIBE was sent, after the relay answered a SUBSCRIBE still in flight, even when its caller is cancelled meanwhile, then raises the caller's cancellation; reads after it raise StopAsyncIteration. Called from another task while a read waits, it cancels that read, which raises StopAsyncIteration. Called from within a read, as from an on_subscribed callback, it returns at once: the read finishes the close and raises StopAsyncIteration instead of returning what it read. A task the read awaits must not await aclose(), which waits for the read. The iteration ending, or raising, unsubscribes too, before the read raises; a read cancelled meanwhile leaves that to the next read. Read it in contextlib.aclosing to unsubscribe as soon as the reading stops: one dropped without aclose() unsubscribes only once it is garbage collected.

Following(what: str)
34    def __init__(self, what: str):
35        self._what = what
36        # The task of the read in flight.
37        self._reader: asyncio.Task | None = None
38        # The task of the read whose advance (`_next`) is in flight; `_idle` is clear meanwhile.
39        self._advancing: asyncio.Task | None = None
40        self._idle = asyncio.Event()
41        self._idle.set()
42        # Whether `aclose()` cancelled the advance in flight, which the read takes back.
43        self._interrupting = False
44        # What the read raises once the close the iteration's end started finished: the failure
45        # that ended it, or StopAsyncIteration.
46        self._ending: BaseException | None = None
47        self._closing: Once[None] = Once()
async def aclose(self) -> None:
 99    async def aclose(self) -> None:
100        closing = self._start_closing()
101        if self._advancing is not None and self._advancing is asyncio.current_task():
102            return
103        await wait_through_cancellation([closing])
104        closing.result()
class LocalBroadcast:
 27class LocalBroadcast:
 28    """A namespace and its tracks published by this session (use with `async with`).
 29
 30    Tracks added before the first `await` inside `async with` are registered before `PUBLISH_NAMESPACE`;
 31    later tracks register individually (writes before registration are dropped).
 32    If publishing fails, all tracks raise that error on write, and normal exit re-raises it if not yet raised.
 33    """
 34
 35    def __init__(self, session: Session, namespace: list[str]):
 36        # Immutable, so a caller changing a list cannot redirect the withdrawal.
 37        self._namespace = tuple(namespace)
 38        self._session = session
 39        self._pending: list[TrackWriter] = []
 40        # False once the batch registered before the PUBLISH_NAMESPACE is complete.
 41        self._batching = True
 42        self._publishing: asyncio.Task[Announcement] | None = None
 43        self._registering: set[asyncio.Task] = set()
 44        # Every track the broadcast added and whose close has not finished, closed when it is left.
 45        self._writers: list[TrackWriter] = []
 46        self._media_sources: list[MediaSource] = []
 47        # The tracks the media broadcast publishes: the catalog, each source's and rendition's, and
 48        # those its catalog lists next to them.
 49        self._media_tracks: set[str] = set()
 50        # Those of `_media_tracks` claimed only as listed next to a source, not as a source's own.
 51        self._implied_tracks: set[str] = set()
 52        self._media_broadcast: _native.MediaBroadcast | None = None
 53        # Set as leaving starts, so nothing is added to a broadcast that is being withdrawn.
 54        self._left = False
 55        # What failed the publishing, which settles the tracks and media sources waiting for it.
 56        self._failure: Exception | None = None
 57        # Whether `_failure` was raised to the caller, by `published()`, a track or a media source.
 58        self._failure_raised = False
 59        self._leaving: Once[None] = Once()
 60
 61    @property
 62    def namespace(self) -> list[str]:
 63        """A copy: changing it changes nothing the broadcast does."""
 64        return list(self._namespace)
 65
 66    def publish_track(
 67        self,
 68        name: str,
 69        *,
 70        retention_seconds: float = DEFAULT_RETENTION_SECONDS,
 71        datagram: bool = False,
 72        priority: int = DEFAULT_PRIORITY,
 73    ) -> TrackWriter:
 74        """Add a data track (`retention_seconds`, `datagram`, `priority` match `Session.publish_track`).
 75
 76        Tracks added before the first `await` register before `PUBLISH_NAMESPACE` (so `publish` is not supported).
 77        Raises `RuntimeError` if the broadcast has exited or the track name is already claimed;
 78        `registered()` raises `ValueError` if `retention_seconds` or `datagram` conflicts with a prior registration.
 79        """
 80        self._raise_if_left()
 81        if self._publishing is not None:
 82            writer = self._session._track_writer(
 83                self.namespace, name, retention_seconds, publish=False, datagram=datagram, priority=priority
 84            )
 85        else:
 86            if name in self._declared_tracks():
 87                raise RuntimeError(f"the broadcast already publishes track {name} of {self.namespace}")
 88            writer = TrackWriter(
 89                self._session, self.namespace, name, retention_seconds, datagram=datagram, priority=priority
 90            )
 91            self._session._on_end_while_held(writer, TrackWriter._end_with)
 92        self._writers.append(writer)
 93        writer._on_closed.append(lambda: self._forget(writer))
 94        if self._failure is not None:
 95            writer._end_with(self._failure, raised=self._raised_failure)
 96        elif self._batching:
 97            self._pending.append(writer)
 98        else:
 99            task = asyncio.create_task(self._register_late(writer))
100            self._registering.add(task)
101            task.add_done_callback(self._registering.discard)
102        return writer
103
104    async def _register_late(self, writer: TrackWriter) -> None:
105        """Registers a track added after the namespace was published; `writer.registered()` raises
106        what failed it. A writer that will not be registered, as one whose registration failed or
107        was cancelled by leaving, has nothing left to close, and the broadcast forgets it. One
108        registered whose opening failed or was cancelled is closing, and the broadcast keeps it
109        until its close finished, so leaving waits for that."""
110        try:
111            await self._session._register(writer)
112        except BaseException as error:
113            if writer._writer is None:
114                self._forget(writer)
115            if not isinstance(error, Exception):
116                raise
117            logger.warning("track %s of %s was not registered: %r", writer.name, self.namespace, error)
118
119    def _forget(self, writer: TrackWriter) -> None:
120        """Unlinks a writer the broadcast has nothing left to close for: its close finished, or it
121        will not be registered, whichever comes first, as when it is closed while its registration
122        fails. A closed writer still waiting for the batch, which would not register it, leaves the
123        batch too."""
124        if writer in self._writers:
125            self._writers.remove(writer)
126        if writer._closed and writer in self._pending:
127            self._pending.remove(writer)
128
129    def event_timeline(self, name: str, *, retention_seconds: float = DEFAULT_RETENTION_SECONDS) -> EventTimeline:
130        return EventTimeline(self.publish_track(name, retention_seconds=retention_seconds))
131
132    def add_media_source(
133        self,
134        video: str = "video",
135        audio: str = "audio",
136        *,
137        label: str,
138        video_bitrate: int | None = None,
139        video_framerate: int | None = None,
140        cmaf: bool = False,
141        on_demand: bool = True,
142    ) -> MediaSource:
143        """Add an encoded video/audio source listed in `catalog` with `<video>_timeline` (and `_cmaf` siblings when `cmaf=True`).
144
145        Must be called before the first `await` inside `async with` (default `"video"`/`"audio"` also claim `chat` and an `audio` placeholder).
146        Raises `RuntimeError` if called too late, after exit, or on track-name collision;
147        `ValueError` for invalid bitrate/framerate or conflicting prior session registrations; `TypeError` for wrong option types.
148        """
149        self._raise_if_left()
150        if self._failure is not None:
151            raise RuntimeError("the broadcast was not published") from self._failure
152        if not self._batching:
153            raise RuntimeError("add media sources before the broadcast is published")
154        source = MediaSource(
155            video,
156            audio,
157            label=label,
158            video_bitrate=video_bitrate,
159            video_framerate=video_framerate,
160            cmaf=cmaf,
161            on_demand=on_demand,
162        )
163        self._claim_source_tracks(source)
164        source._claim_tracks = self._claim_media_tracks
165        if self._publishing is not None:
166            self._session._on_end(source._stop_with_session)
167        else:
168            self._session._on_end_while_held(source, MediaSource._stop_with_session)
169        self._media_sources.append(source)
170        return source
171
172    def _claim_source_tracks(self, source: MediaSource) -> None:
173        """Claims the tracks the media broadcast publishes for `source`: its own, the catalog with
174        the first source, and those the catalog lists next to it, which sources share. A source's
175        own audio takes the place of an audio placeholder; another of its tracks named as a track
176        the catalog lists next to a source is refused, as is such a track named as another source's
177        own one, while its placeholder is not. Another track named as the placeholder, as a video
178        named `audio`, is refused in either order, since the native catalog lists the placeholder
179        while no source's audio has its name (`audio_placeholder` in
180        crates/broadcast/src/broadcast.rs). A source naming two of its own tracks alike is refused
181        before its audio takes a placeholder's place, which would leave one name to both."""
182        own = [*([] if self._media_sources else [CATALOG_TRACK_NAME]), *source._track_names()]
183        self._refuse_duplicates(own)
184        replacing = {name for name in own if name in self._implied_tracks}
185        for name in replacing - ({DEFAULT_AUDIO} & {source.audio}):
186            raise RuntimeError(f"the broadcast already publishes track {name} of {self.namespace}")
187        placeholder_taken = any(added.audio == DEFAULT_AUDIO for added in self._media_sources)
188        implied = []
189        for name in source._implied_track_names():
190            if name in self._implied_tracks or (name == DEFAULT_AUDIO and placeholder_taken):
191                continue
192            implied.append(name)
193        self._claim_media_tracks([*(name for name in own if name not in replacing), *implied])
194        self._implied_tracks -= replacing
195        self._implied_tracks.update(implied)
196
197    def _claim_media_tracks(self, names: list[str]) -> None:
198        """Claims tracks the media broadcast publishes. Raises RuntimeError, claiming none of them,
199        once the broadcast was left, and while another track of the broadcast, or once it was
200        entered of the session, has one of the names, and ValueError for a name the session
201        registered in datagrams or with another retention."""
202        self._raise_if_left()
203        self._refuse_duplicates(names)
204        self._session._refuse_other_registrations(self._namespace, _media_retentions(names))
205        if self._publishing is not None:
206            self._session._claim_tracks(self._namespace, {name: self for name in names})
207        else:
208            declared = self._declared_tracks()
209            for name in names:
210                if name in declared:
211                    raise RuntimeError(f"the broadcast already publishes track {name} of {self.namespace}")
212        self._media_tracks.update(names)
213
214    def _refuse_duplicates(self, names: list[str]) -> None:
215        if len(set(names)) < len(names):
216            raise RuntimeError(f"a media source of {self.namespace} names two of its tracks alike: {names}")
217
218    def _declared_tracks(self) -> dict[str, object]:
219        """The owner of each track declared on the broadcast, which entering it claims in the
220        session."""
221        owners: dict[str, object] = {name: self for name in self._media_tracks}
222        owners.update((writer.name, writer) for writer in self._writers if not writer._closed)
223        return owners
224
225    def _raise_if_left(self) -> None:
226        if self._left:
227            raise RuntimeError(f"the broadcast of {self.namespace} was left")
228
229    async def __aenter__(self) -> "LocalBroadcast":
230        """Raises RuntimeError for a broadcast entered before, while another broadcast or
231        announcement of the session publishes the namespace, until it finished withdrawing it, and
232        while another writer of the session publishes a track declared on the broadcast, and
233        ValueError for a media source's track the session registered in datagrams or with another
234        retention since. Until it was entered, the session does not keep the broadcast or what was
235        declared on it alive, though it ends the tracks and media sources the app holds when it
236        ends, so a broadcast that could not be entered leaves nothing behind."""
237        if self._publishing is not None:
238            raise RuntimeError(f"the broadcast of {self.namespace} was entered before")
239        self._session._raise_if_ended()
240        # The session may have registered one otherwise since it was claimed.
241        self._session._refuse_other_registrations(self._namespace, _media_retentions(self._media_tracks))
242        self._session._own(self.namespace)
243        try:
244            self._session._claim_tracks(self._namespace, self._declared_tracks())
245        except BaseException:
246            self._session._disown(self.namespace)
247            raise
248        # The session holds the handles declared before from now on, as it does those added later.
249        for writer in self._writers:
250            self._session._forget_end_while_held(writer)
251            writer._end_with_session()
252        for source in self._media_sources:
253            self._session._forget_end_while_held(source)
254            self._session._on_end(source._stop_with_session)
255        self._publishing = asyncio.create_task(self._publish())
256        return self
257
258    async def _publish(self) -> Announcement:
259        try:
260            # Tracks added while a registration awaits join the batch, so all precede the namespace.
261            while self._pending:
262                await self._session._register(self._pending.pop(0))
263            self._batching = False
264            if self._media_sources:
265                announcement = await self._session._announce(
266                    self.namespace, lambda native: self._build_media(native).announce(), owns=False
267                )
268                for source in self._media_sources:
269                    source._announced.set()
270                return announcement
271            return await self._session._announce(
272                self.namespace, lambda native: native.announce(self.namespace), owns=False
273            )
274        except Exception as error:
275            self._fail(error)
276            raise
277
278    def _fail(self, error: Exception) -> None:
279        """The namespace will not be published: what waits for it raises `error` at once, and so do
280        the writes of every track, as the relay takes nothing of a namespace it refused."""
281        self._failure = error
282        for writer in self._writers:
283            writer._end_with(error, raised=self._raised_failure)
284        self._pending.clear()
285        for source in self._media_sources:
286            source._detach(error, failure=True, raised=self._raised_failure)
287
288    def _raised_failure(self) -> None:
289        self._failure_raised = True
290
291    def _build_media(self, native: _native.Session) -> _native.MediaBroadcast:
292        broadcast = native.media_broadcast(self.namespace)
293        self._media_broadcast = broadcast
294        try:
295            for source in self._media_sources:
296                source._build(broadcast, self._session._done)
297        except Exception:
298            # A source built before may have published the namespace with its catalog.
299            self._session._release_later(_namespace_key(self.namespace), self._withdraw_media(broadcast))
300            raise
301        return broadcast
302
303    async def _withdraw_media(self, broadcast: _native.MediaBroadcast) -> None:
304        """Closes a media broadcast that failed to build, then withdraws its namespace; its sources
305        were detached by the failure. A source built before publishes on its own, from its media
306        configuration: the namespace, its tracks and its catalog. Closing waits for that and ends
307        them, so the withdrawal follows it: sent while the source's PUBLISH_NAMESPACE was under way,
308        the withdrawal would leave the namespace published, and while its PUBLISH was, the relay
309        would leave that unanswered, and the close waiting for it would hang until the session
310        ended."""
311        try:
312            await broadcast.close()
313        except Exception as error:
314            logger.debug("closing the media broadcast of %s failed: %r", self.namespace, error)
315        try:
316            if not self._session._done.done():
317                await self._session._native.unannounce(self.namespace)
318        except Exception as error:
319            # Refused, as for a namespace no source published.
320            logger.debug("withdrawing the namespace %s failed: %r", self.namespace, error)
321
322    async def published(self) -> None:
323        """Waits until the namespace is published. Raises RuntimeError when the relay refuses it or
324        a track of the batch registered before it; the tracks and media sources then raise that
325        error too."""
326        assert self._publishing is not None, "use the broadcast with async with"
327        try:
328            await asyncio.shield(self._publishing)
329        except Exception as error:
330            if error is self._failure:
331                self._raised_failure()
332            raise
333
334    async def __aexit__(self, *exc_info: object) -> None:
335        """Withdraws the namespace and closes every track and media source, each even when an
336        earlier step raised; raises the first step's error. When the block exited normally, it
337        raises what kept the broadcast from being published, unless that was raised to the caller
338        before, so a refused broadcast does not look as if it ran. The session may publish the
339        namespace again once the leaving finished: cancelled, this leaves it running, and a later
340        call waits for it."""
341        assert self._publishing is not None
342        if not self._leaving.started:
343            # At once, so a publishing that has not started yet does not start.
344            self._left = True
345            for task in self._registering:
346                task.cancel()
347            self._publishing.cancel()
348        await self._leaving.run(self._leave_and_disown)
349        if exc_info[0] is None and self._failure is not None and not self._failure_raised:
350            self._raised_failure()
351            raise self._failure
352
353    async def _leave_and_disown(self) -> None:
354        try:
355            await self._leave()
356        finally:
357            # Recorded while the broadcast still owns its tracks, so no other writer registers one
358            # before.
359            self._session._record_media_tracks(self._namespace, _media_retentions(self._registered_media_tracks()))
360            self._session._release_tracks(self._namespace, {name: self for name in self._media_tracks})
361            self._session._disown(self.namespace)
362
363    def _registered_media_tracks(self) -> set[str]:
364        """The tracks the native media broadcast registered in the session's origin, or may have,
365        as a subscriber may take the catalog, and the tracks it lists, at any time: the catalog once
366        the media broadcast was built, and those its sources' configurations had it list."""
367        if self._media_broadcast is None:
368            return set()
369        names = {CATALOG_TRACK_NAME}
370        for source in self._media_sources:
371            names.update(source._registered_track_names())
372        return names
373
374    async def _leave(self) -> None:
375        assert self._publishing is not None
376        failures: list[BaseException] = []
377        await asyncio.gather(*self._registering, return_exceptions=True)
378        while self._pending:
379            self._pending.pop()._abandon()
380        try:
381            await asyncio.wait([self._publishing])
382            # What the publishing left to withdraw comes first: a PUBLISH_NAMESPACE its
383            # cancellation left running, once answered, or a media broadcast that failed to build.
384            await self._session._released(_namespace_key(self.namespace))
385            if not self._publishing.cancelled() and self._publishing.exception() is None:
386                await self._publishing.result().close()
387        except BaseException as error:
388            failures.append(error)
389        # Ends the subscriptions the relay still forwards, and the handles, so a writer kept past
390        # the broadcast cannot write into a later broadcast of the same namespace.
391        for writer in list(self._writers):
392            try:
393                await writer.close()
394            except BaseException as error:
395                failures.append(error)
396        for source in self._media_sources:
397            source._detach()
398            self._session._forget_end(source._stop_with_session)
399        if self._media_broadcast is not None:
400            try:
401                await self._media_broadcast.close()
402            except BaseException as error:
403                failures.append(error)
404        if failures:
405            raise failures[0]

A namespace and its tracks published by this session (use with async with).

Tracks added before the first await inside async with are registered before PUBLISH_NAMESPACE; later tracks register individually (writes before registration are dropped). If publishing fails, all tracks raise that error on write, and normal exit re-raises it if not yet raised.

LocalBroadcast(session: moq_wasm.Session, namespace: list[str])
35    def __init__(self, session: Session, namespace: list[str]):
36        # Immutable, so a caller changing a list cannot redirect the withdrawal.
37        self._namespace = tuple(namespace)
38        self._session = session
39        self._pending: list[TrackWriter] = []
40        # False once the batch registered before the PUBLISH_NAMESPACE is complete.
41        self._batching = True
42        self._publishing: asyncio.Task[Announcement] | None = None
43        self._registering: set[asyncio.Task] = set()
44        # Every track the broadcast added and whose close has not finished, closed when it is left.
45        self._writers: list[TrackWriter] = []
46        self._media_sources: list[MediaSource] = []
47        # The tracks the media broadcast publishes: the catalog, each source's and rendition's, and
48        # those its catalog lists next to them.
49        self._media_tracks: set[str] = set()
50        # Those of `_media_tracks` claimed only as listed next to a source, not as a source's own.
51        self._implied_tracks: set[str] = set()
52        self._media_broadcast: _native.MediaBroadcast | None = None
53        # Set as leaving starts, so nothing is added to a broadcast that is being withdrawn.
54        self._left = False
55        # What failed the publishing, which settles the tracks and media sources waiting for it.
56        self._failure: Exception | None = None
57        # Whether `_failure` was raised to the caller, by `published()`, a track or a media source.
58        self._failure_raised = False
59        self._leaving: Once[None] = Once()
namespace: list[str]
61    @property
62    def namespace(self) -> list[str]:
63        """A copy: changing it changes nothing the broadcast does."""
64        return list(self._namespace)

A copy: changing it changes nothing the broadcast does.

def publish_track( self, name: str, *, retention_seconds: float = 60.0, datagram: bool = False, priority: int = 128) -> moq_wasm.TrackWriter:
 66    def publish_track(
 67        self,
 68        name: str,
 69        *,
 70        retention_seconds: float = DEFAULT_RETENTION_SECONDS,
 71        datagram: bool = False,
 72        priority: int = DEFAULT_PRIORITY,
 73    ) -> TrackWriter:
 74        """Add a data track (`retention_seconds`, `datagram`, `priority` match `Session.publish_track`).
 75
 76        Tracks added before the first `await` register before `PUBLISH_NAMESPACE` (so `publish` is not supported).
 77        Raises `RuntimeError` if the broadcast has exited or the track name is already claimed;
 78        `registered()` raises `ValueError` if `retention_seconds` or `datagram` conflicts with a prior registration.
 79        """
 80        self._raise_if_left()
 81        if self._publishing is not None:
 82            writer = self._session._track_writer(
 83                self.namespace, name, retention_seconds, publish=False, datagram=datagram, priority=priority
 84            )
 85        else:
 86            if name in self._declared_tracks():
 87                raise RuntimeError(f"the broadcast already publishes track {name} of {self.namespace}")
 88            writer = TrackWriter(
 89                self._session, self.namespace, name, retention_seconds, datagram=datagram, priority=priority
 90            )
 91            self._session._on_end_while_held(writer, TrackWriter._end_with)
 92        self._writers.append(writer)
 93        writer._on_closed.append(lambda: self._forget(writer))
 94        if self._failure is not None:
 95            writer._end_with(self._failure, raised=self._raised_failure)
 96        elif self._batching:
 97            self._pending.append(writer)
 98        else:
 99            task = asyncio.create_task(self._register_late(writer))
100            self._registering.add(task)
101            task.add_done_callback(self._registering.discard)
102        return writer

Add a data track (retention_seconds, datagram, priority match Session.publish_track).

Tracks added before the first await register before PUBLISH_NAMESPACE (so publish is not supported). Raises RuntimeError if the broadcast has exited or the track name is already claimed; registered() raises ValueError if retention_seconds or datagram conflicts with a prior registration.

def event_timeline( self, name: str, *, retention_seconds: float = 60.0) -> EventTimeline:
129    def event_timeline(self, name: str, *, retention_seconds: float = DEFAULT_RETENTION_SECONDS) -> EventTimeline:
130        return EventTimeline(self.publish_track(name, retention_seconds=retention_seconds))
def add_media_source( self, video: str = 'video', audio: str = 'audio', *, label: str, video_bitrate: int | None = None, video_framerate: int | None = None, cmaf: bool = False, on_demand: bool = True) -> MediaSource:
132    def add_media_source(
133        self,
134        video: str = "video",
135        audio: str = "audio",
136        *,
137        label: str,
138        video_bitrate: int | None = None,
139        video_framerate: int | None = None,
140        cmaf: bool = False,
141        on_demand: bool = True,
142    ) -> MediaSource:
143        """Add an encoded video/audio source listed in `catalog` with `<video>_timeline` (and `_cmaf` siblings when `cmaf=True`).
144
145        Must be called before the first `await` inside `async with` (default `"video"`/`"audio"` also claim `chat` and an `audio` placeholder).
146        Raises `RuntimeError` if called too late, after exit, or on track-name collision;
147        `ValueError` for invalid bitrate/framerate or conflicting prior session registrations; `TypeError` for wrong option types.
148        """
149        self._raise_if_left()
150        if self._failure is not None:
151            raise RuntimeError("the broadcast was not published") from self._failure
152        if not self._batching:
153            raise RuntimeError("add media sources before the broadcast is published")
154        source = MediaSource(
155            video,
156            audio,
157            label=label,
158            video_bitrate=video_bitrate,
159            video_framerate=video_framerate,
160            cmaf=cmaf,
161            on_demand=on_demand,
162        )
163        self._claim_source_tracks(source)
164        source._claim_tracks = self._claim_media_tracks
165        if self._publishing is not None:
166            self._session._on_end(source._stop_with_session)
167        else:
168            self._session._on_end_while_held(source, MediaSource._stop_with_session)
169        self._media_sources.append(source)
170        return source

Add an encoded video/audio source listed in catalog with <video>_timeline (and _cmaf siblings when cmaf=True).

Must be called before the first await inside async with (default "video"/"audio" also claim chat and an audio placeholder). Raises RuntimeError if called too late, after exit, or on track-name collision; ValueError for invalid bitrate/framerate or conflicting prior session registrations; TypeError for wrong option types.

async def published(self) -> None:
322    async def published(self) -> None:
323        """Waits until the namespace is published. Raises RuntimeError when the relay refuses it or
324        a track of the batch registered before it; the tracks and media sources then raise that
325        error too."""
326        assert self._publishing is not None, "use the broadcast with async with"
327        try:
328            await asyncio.shield(self._publishing)
329        except Exception as error:
330            if error is self._failure:
331                self._raised_failure()
332            raise

Waits until the namespace is published. Raises RuntimeError when the relay refuses it or a track of the batch registered before it; the tracks and media sources then raise that error too.

class MediaSource:
 25class MediaSource:
 26    """Video and audio source for a `LocalBroadcast` (MSF catalog, LOC tracks, media timeline).
 27
 28    Frames pushed before the broadcast is announced, after exit, or after session end are dropped.
 29    Once publishing fails (e.g. relay rejection or push error), subsequent calls raise `RuntimeError`.
 30    """
 31
 32    def __init__(
 33        self,
 34        video: str,
 35        audio: str,
 36        *,
 37        label: str,
 38        video_bitrate: int | None = None,
 39        video_framerate: int | None = None,
 40        cmaf: bool = False,
 41        on_demand: bool = True,
 42    ):
 43        # Checked here, so a broadcast with a source the native broadcast would refuse fails before
 44        # anything native is built.
 45        _check_type("video", video, str)
 46        _check_type("audio", audio, str)
 47        _check_type("label", label, str)
 48        _check_optional_unsigned("video_bitrate", video_bitrate, 64)
 49        _check_optional_unsigned("video_framerate", video_framerate, 32)
 50        _check_type("cmaf", cmaf, bool)
 51        _check_type("on_demand", on_demand, bool)
 52        self._video = video
 53        self._audio = audio
 54        self._label = label
 55        self._video_bitrate = video_bitrate
 56        self._video_framerate = video_framerate
 57        self._cmaf = cmaf
 58        self._on_demand = on_demand
 59        self._source: _native.MediaSource | None = None
 60        self._video_codec: str | None = None
 61        self._audio_config: tuple[str, int, int, bytes | None] | None = None
 62        # The tracks the native media broadcast registered, or may have, for the configurations a
 63        # later one replaced, as the CMAF sibling of an AAC audio replaced by Opus.
 64        self._replaced_track_names: set[str] = set()
 65        self._renditions: list[Rendition] = []
 66        self._built = asyncio.Event()
 67        # Set once the relay accepted the broadcast's namespace: the pushes reach the native source
 68        # only then, as the media of a namespace the relay refuses would be lost.
 69        self._announced = asyncio.Event()
 70        # Ended once the broadcast was left or the session ended, which stop the source, or by
 71        # what kept the broadcast from being published or stopped publishing the source.
 72        self._ended = Ended()
 73        self._session_ended: asyncio.Future[None] | None = None
 74        # The native request of each kind whose answer no caller took yet, as one whose caller was
 75        # cancelled: the next caller of the kind takes it, so no answer is lost.
 76        self._requests: dict[str, asyncio.Future] = {}
 77        # The kinds of request a caller awaits: one caller of a kind at a time, so no two take the
 78        # same answer.
 79        self._awaited: set[str] = set()
 80        # The native removal of each kind under way, which a later removal of the kind joins.
 81        self._removing: dict[str, asyncio.Future[None]] = {}
 82        # Set by the broadcast the source is added to: claims the tracks of a rendition, raising
 83        # RuntimeError while another track has the name of one of them.
 84        self._claim_tracks: Callable[[list[str]], None] | None = None
 85
 86    @property
 87    def video(self) -> str:
 88        """The video track's name; read-only, as the broadcast claimed the source's tracks by it."""
 89        return self._video
 90
 91    @property
 92    def audio(self) -> str:
 93        """The audio track's name; read-only, as `video` is."""
 94        return self._audio
 95
 96    def configure_video(self, codec: str) -> None:
 97        """`codec` is a WebCodecs codec string: `avc1.*` (Annex B), `hvc1.*` (Annex B), `vp8`,
 98        `vp09.*` or `av01.*`. Raises ValueError for another codec."""
 99        _check_video_codec(codec)
100        self._publish(lambda source: source.configure_video(codec))
101        self._video_codec = codec
102
103    def add_rendition(
104        self, name: str, *, label: str, bitrate: int | None = None, framerate: int | None = None
105    ) -> "Rendition":
106        """Add a video rendition `<video>_<name>` (plus `_cmaf` if enabled).
107
108        Feed the same pictures and keyframe positions as the primary video
109        (`bitrate` in bits/s and `framerate` go in the catalog).
110        Raises `ValueError`/`TypeError` for invalid options or conflicting prior registrations,
111        and `RuntimeError` on track-name collision or after publishing failure.
112        """
113        _check_type("name", name, str)
114        _check_type("label", label, str)
115        _check_optional_unsigned("bitrate", bitrate, 64)
116        _check_optional_unsigned("framerate", framerate, 32)
117        self._raise_if_failed()
118        if self._claim_tracks is not None:
119            self._claim_tracks(self._with_cmaf(f"{self.video}_{name}"))
120        rendition = Rendition(name, {"label": label, "bitrate": bitrate, "framerate": framerate})
121        self._renditions.append(rendition)
122        if self._source is not None:
123            assert self._session_ended is not None, "a built source knows its session"
124            rendition._build(self._source, self._session_ended, self._announced)
125        return rendition
126
127    def push_video(self, data: bytes, timestamp_micros: int) -> bool:
128        """Push one encoded video frame (`timestamp_micros` must be monotonic; keyframes start a new group).
129
130        Returns `False` if dropped (before announce, after exit/session end, on backpressure, or non-picture AU).
131        Raises `RuntimeError` before `configure_video()` or after publishing failure.
132        """
133        if self._video_codec is None:
134            raise RuntimeError("call configure_video first")
135        return self._publish(lambda source: source.push_video(data, timestamp_micros), push=True)
136
137    def configure_audio(
138        self, codec: str, sample_rate: int, channels: int, *, description: bytes | None = None
139    ) -> None:
140        """`"opus"`, or an AAC `"mp4a.40.*"` whose `description` is the AudioSpecificConfig;
141        raises ValueError for another codec, an AAC without it, and a negative `sample_rate` or
142        `channels`, or one too large, TypeError for one that is no integer, as None, and
143        RuntimeError once publishing the source failed. A refused configuration changes nothing."""
144        _check_unsigned("sample_rate", sample_rate, 32)
145        _check_unsigned("channels", channels, 8)
146        if codec != "opus" and not codec.startswith("mp4a.40."):
147            raise ValueError(f"unsupported audio codec: {codec}")
148        if codec != "opus":
149            if description is None:
150                raise ValueError("AAC needs its AudioSpecificConfig")
151            _native.check_audio_specific_config(description)
152        self._publish(lambda source: source.configure_audio(codec, sample_rate, channels, description=description))
153        self._replaced_track_names.update(self._registered_track_names())
154        self._audio_config = (codec, sample_rate, channels, description)
155
156    def push_audio(
157        self, data: bytes, timestamp_micros: int, *, level: int | None = None, voice_activity: bool = False
158    ) -> bool:
159        """One encoded audio frame; `level` and `voice_activity` as in
160        `_native.MediaSource.push_audio`. Returns whether the native source took it, as
161        `push_video` does. Raises RuntimeError before `configure_audio`, and once publishing the
162        source failed."""
163        if self._audio_config is None:
164            raise RuntimeError("call configure_audio first")
165        return self._publish(
166            lambda source: source.push_audio(data, timestamp_micros, level=level, voice_activity=voice_activity),
167            push=True,
168        )
169
170    def _publish(self, call: Callable[[_native.MediaSource], bool | None], *, push: bool = False) -> bool:
171        """`call` on the native source once it is built, and for a `push` once the broadcast was
172        published; returns whether the native source took it. Raises RuntimeError once publishing
173        the source failed; a failure of `call` in a live session is that failure."""
174        self._raise_if_failed()
175        if (source := self._source) is None or (push and not self._announced.is_set()):
176            return False
177        try:
178            return _call_native(lambda: call(source), self._session_ended)
179        except RuntimeError as failure:
180            # Ends the waiting requests with the failure.
181            self._detach(failure, failure=True)
182            raise
183
184    def _drops_pushes(self) -> bool:
185        """Whether a push is dropped without raising: before the broadcast is published, and after
186        it was left or once the session ended, unless publishing the source failed."""
187        if self._ended.failed:
188            return False
189        session_ended = self._session_ended is not None and self._session_ended.done()
190        return self._source is None or not self._announced.is_set() or self._ended.ended or session_ended
191
192    def _raise_if_failed(self) -> None:
193        if self._ended.failed:
194            raise RuntimeError("the media source stopped publishing") from self._ended.error()
195
196    async def remove_track(self, kind: str) -> None:
197        """`_native.MediaSource.remove_track` (`kind` is `"video"` or `"audio"`): stop pushing its
198        media first; `configure_video` or `configure_audio` and the media pushed after it publish
199        the track again. Before the broadcast is published, it forgets the kind's configuration
200        (the renditions' too, for the video). Raises ValueError for another kind, and RuntimeError
201        once publishing the source failed. The native removal runs to its end, the renditions'
202        removals after the video's included, even when its caller is cancelled, as by a timeout;
203        a call while it runs awaits it."""
204        if kind not in ("video", "audio"):
205            raise ValueError(f"unknown track kind: {kind}")
206        self._raise_if_failed()
207        if self._source is not None:
208            removing = self._removing.get(kind)
209            if removing is None or removing.done():
210                removing = self._removing[kind] = asyncio.ensure_future(self._source.remove_track(kind))
211                # Its failure goes to the callers, and to nobody once they were all cancelled.
212                removing.add_done_callback(retrieve)
213            await asyncio.shield(removing)
214        elif kind == "video":
215            self._video_codec = None
216            for rendition in self._renditions:
217                rendition._video_codec = None
218        else:
219            self._audio_config = None
220
221    async def keyframe_request(self) -> None:
222        """Resolves the next time a subscriber asks for a new group (NEW_GROUP_REQUEST) or the
223        broadcast needs one: encode the next frame as a keyframe then. Waits while the broadcast is
224        not published; raises RuntimeError once the broadcast was left or the session ended, and
225        what kept the broadcast from being published or stopped publishing the source. One caller
226        at a time: a call while another waits raises RuntimeError."""
227        await self._while_publishing("keyframe_request", lambda source: source.keyframe_request())
228
229    async def demand_change(self) -> _native.Demand:
230        """`_native.MediaSource.demand_change`; waits while the broadcast is not published. Raises
231        RuntimeError for a source added with `on_demand=False`, and once the broadcast was left or
232        the session ended; raises what kept the broadcast from being published or stopped
233        publishing the source. One caller at a time: a call while another waits raises
234        RuntimeError."""
235        if not self._on_demand:
236            raise RuntimeError("the source was added with on_demand=False")
237        return await self._while_publishing("demand_change", lambda source: source.demand_change())
238
239    async def _while_publishing(self, kind: str, request: Callable[[_native.MediaSource], Awaitable[T]]) -> T:
240        """`request` on the native source once it is built, ended by the source stopping. A request
241        of `kind` a cancelled caller left is awaited instead of a new one."""
242        if kind in self._awaited:
243            raise RuntimeError(f"{kind} is already awaited")
244        self._awaited.add(kind)
245        try:
246            return await self._request_while_publishing(kind, request)
247        finally:
248            self._awaited.discard(kind)
249
250    async def _request_while_publishing(
251        self, kind: str, request: Callable[[_native.MediaSource], Awaitable[T]]
252    ) -> T:
253        built = asyncio.ensure_future(self._built.wait())
254        try:
255            await self._ended.until(built)
256        finally:
257            built.cancel()
258        if self._ended.ended or self._source is None:
259            raise self._stopped_error()
260        answered = self._requests.get(kind)
261        if answered is None:
262            answered = self._requests[kind] = asyncio.ensure_future(request(self._source))
263        await self._ended.until(answered)
264        # Stopping the source cancels the native request, so a cancelled one means it stopped.
265        if not answered.done() or answered.cancelled():
266            raise self._stopped_error()
267        if self._requests.get(kind) is answered:
268            del self._requests[kind]
269        return answered.result()
270
271    def _track_names(self) -> list[str]:
272        """The tracks the media broadcast publishes for the source, its renditions aside."""
273        return [*self._with_cmaf(self.video), *self._with_cmaf(self.audio), f"{self.video}_timeline"]
274
275    def _implied_track_names(self) -> list[str]:
276        """The tracks the media broadcast lists in its catalog next to the source's own, ending
277        them once it no longer does (`build_catalog` in crates/broadcast/src/broadcast.rs): the chat
278        while it lists the default video or audio, and an audio placeholder, which an audio of that
279        name takes the place of, while it lists the default video."""
280        implied = [CHAT] if self.video == DEFAULT_VIDEO or self.audio == DEFAULT_AUDIO else []
281        if self.video == DEFAULT_VIDEO and self.audio != DEFAULT_AUDIO:
282            implied.append(DEFAULT_AUDIO)
283        return implied
284
285    def _registered_track_names(self) -> list[str]:
286        """The tracks the native media broadcast registered for the source, or may have: those its
287        catalog listed for a configuration that reached the native source, which it registers as
288        the catalog goes out or a subscriber takes one (`CatalogTrack::send` and `serve_subscribe`
289        under crates/broadcast/src/relay_connection): a configured video's or rendition's track and
290        CMAF sibling, a configured audio's track and an AAC one's CMAF sibling, the media timeline,
291        and the chat and the audio placeholder the default video lists, or the chat the default
292        audio does, for the configuration it has and each one it replaced since it was built. A
293        track named but never configured, as the video of an audio-only source, is not one."""
294        if not self._built.is_set():
295            return []
296        listed = list(self._replaced_track_names)
297        if self._video_codec is not None:
298            listed += self._with_cmaf(self.video)
299            if self.video == DEFAULT_VIDEO:
300                listed += [DEFAULT_AUDIO, CHAT]
301        if self._audio_config is not None:
302            aac = self._audio_config[0] != "opus"
303            listed += self._with_cmaf(self.audio) if aac else [self.audio]
304            if self.audio == DEFAULT_AUDIO:
305                listed.append(CHAT)
306        for rendition in self._renditions:
307            if rendition._video_codec is not None:
308                listed += self._with_cmaf(f"{self.video}_{rendition.name}")
309        if listed:
310            listed.append(f"{self.video}_timeline")
311        return listed
312
313    def _with_cmaf(self, track: str) -> list[str]:
314        """`track`, and its CMAF sibling when the source publishes them."""
315        return [track, f"{track}_cmaf"] if self._cmaf else [track]
316
317    def _build(self, broadcast: _native.MediaBroadcast, session_ended: asyncio.Future[None]) -> None:
318        source = broadcast.add_source(
319            self.video,
320            self.audio,
321            label=self._label,
322            video_bitrate=self._video_bitrate,
323            video_framerate=self._video_framerate,
324            cmaf=self._cmaf,
325            on_demand=self._on_demand,
326        )
327        if self._video_codec is not None:
328            source.configure_video(self._video_codec)
329        if self._audio_config is not None:
330            codec, sample_rate, channels, description = self._audio_config
331            source.configure_audio(codec, sample_rate, channels, description=description)
332        self._source = source
333        self._session_ended = session_ended
334        for rendition in self._renditions:
335            rendition._build(source, session_ended, self._announced)
336        self._built.set()
337
338    def _stopped_error(self) -> BaseException:
339        return self._ended.error() if self._ended.ended else RuntimeError("the media source stopped publishing")
340
341    def _detach(
342        self, error: Exception | None = None, *, failure: bool = False, raised: Callable[[], None] | None = None
343    ) -> None:
344        """Stops the source, which ends it with `error`, what kept its broadcast from being
345        published or stopped publishing the source, unless it ended before; with `failure`, its
346        pushes, configurations and renditions raise it too. `raised` is called each time it is
347        raised."""
348        self._end(error or RuntimeError("the media source stopped publishing"), failure=failure, raised=raised)
349        self._source = None
350        for rendition in self._renditions:
351            rendition._rendition = None
352
353    def _stop_with_session(self, _: BaseException) -> None:
354        """The session ended: the requests raise that the source stopped, and the pushes reach the
355        native source, which drops them."""
356        self._end(RuntimeError("the media source stopped publishing"), failure=False)
357
358    def _end(self, error: BaseException, *, failure: bool, raised: Callable[[], None] | None = None) -> None:
359        # A source that stopped before, as when the session ended, stays stopped, and so do its
360        # renditions.
361        if self._ended.end(error, failure=failure, raised=raised) and failure:
362            for rendition in self._renditions:
363                rendition._ended.end(error, raised=raised)
364        # Cancelling a native request drops its wait, so it takes no later notification.
365        for answered in self._requests.values():
366            answered.cancel()
367        self._requests.clear()

Video and audio source for a LocalBroadcast (MSF catalog, LOC tracks, media timeline).

Frames pushed before the broadcast is announced, after exit, or after session end are dropped. Once publishing fails (e.g. relay rejection or push error), subsequent calls raise RuntimeError.

MediaSource( video: str, audio: str, *, label: str, video_bitrate: int | None = None, video_framerate: int | None = None, cmaf: bool = False, on_demand: bool = True)
32    def __init__(
33        self,
34        video: str,
35        audio: str,
36        *,
37        label: str,
38        video_bitrate: int | None = None,
39        video_framerate: int | None = None,
40        cmaf: bool = False,
41        on_demand: bool = True,
42    ):
43        # Checked here, so a broadcast with a source the native broadcast would refuse fails before
44        # anything native is built.
45        _check_type("video", video, str)
46        _check_type("audio", audio, str)
47        _check_type("label", label, str)
48        _check_optional_unsigned("video_bitrate", video_bitrate, 64)
49        _check_optional_unsigned("video_framerate", video_framerate, 32)
50        _check_type("cmaf", cmaf, bool)
51        _check_type("on_demand", on_demand, bool)
52        self._video = video
53        self._audio = audio
54        self._label = label
55        self._video_bitrate = video_bitrate
56        self._video_framerate = video_framerate
57        self._cmaf = cmaf
58        self._on_demand = on_demand
59        self._source: _native.MediaSource | None = None
60        self._video_codec: str | None = None
61        self._audio_config: tuple[str, int, int, bytes | None] | None = None
62        # The tracks the native media broadcast registered, or may have, for the configurations a
63        # later one replaced, as the CMAF sibling of an AAC audio replaced by Opus.
64        self._replaced_track_names: set[str] = set()
65        self._renditions: list[Rendition] = []
66        self._built = asyncio.Event()
67        # Set once the relay accepted the broadcast's namespace: the pushes reach the native source
68        # only then, as the media of a namespace the relay refuses would be lost.
69        self._announced = asyncio.Event()
70        # Ended once the broadcast was left or the session ended, which stop the source, or by
71        # what kept the broadcast from being published or stopped publishing the source.
72        self._ended = Ended()
73        self._session_ended: asyncio.Future[None] | None = None
74        # The native request of each kind whose answer no caller took yet, as one whose caller was
75        # cancelled: the next caller of the kind takes it, so no answer is lost.
76        self._requests: dict[str, asyncio.Future] = {}
77        # The kinds of request a caller awaits: one caller of a kind at a time, so no two take the
78        # same answer.
79        self._awaited: set[str] = set()
80        # The native removal of each kind under way, which a later removal of the kind joins.
81        self._removing: dict[str, asyncio.Future[None]] = {}
82        # Set by the broadcast the source is added to: claims the tracks of a rendition, raising
83        # RuntimeError while another track has the name of one of them.
84        self._claim_tracks: Callable[[list[str]], None] | None = None
video: str
86    @property
87    def video(self) -> str:
88        """The video track's name; read-only, as the broadcast claimed the source's tracks by it."""
89        return self._video

The video track's name; read-only, as the broadcast claimed the source's tracks by it.

audio: str
91    @property
92    def audio(self) -> str:
93        """The audio track's name; read-only, as `video` is."""
94        return self._audio

The audio track's name; read-only, as video is.

def configure_video(self, codec: str) -> None:
 96    def configure_video(self, codec: str) -> None:
 97        """`codec` is a WebCodecs codec string: `avc1.*` (Annex B), `hvc1.*` (Annex B), `vp8`,
 98        `vp09.*` or `av01.*`. Raises ValueError for another codec."""
 99        _check_video_codec(codec)
100        self._publish(lambda source: source.configure_video(codec))
101        self._video_codec = codec

codec is a WebCodecs codec string: avc1.* (Annex B), hvc1.* (Annex B), vp8, vp09.* or av01.*. Raises ValueError for another codec.

def add_rendition( self, name: str, *, label: str, bitrate: int | None = None, framerate: int | None = None) -> Rendition:
103    def add_rendition(
104        self, name: str, *, label: str, bitrate: int | None = None, framerate: int | None = None
105    ) -> "Rendition":
106        """Add a video rendition `<video>_<name>` (plus `_cmaf` if enabled).
107
108        Feed the same pictures and keyframe positions as the primary video
109        (`bitrate` in bits/s and `framerate` go in the catalog).
110        Raises `ValueError`/`TypeError` for invalid options or conflicting prior registrations,
111        and `RuntimeError` on track-name collision or after publishing failure.
112        """
113        _check_type("name", name, str)
114        _check_type("label", label, str)
115        _check_optional_unsigned("bitrate", bitrate, 64)
116        _check_optional_unsigned("framerate", framerate, 32)
117        self._raise_if_failed()
118        if self._claim_tracks is not None:
119            self._claim_tracks(self._with_cmaf(f"{self.video}_{name}"))
120        rendition = Rendition(name, {"label": label, "bitrate": bitrate, "framerate": framerate})
121        self._renditions.append(rendition)
122        if self._source is not None:
123            assert self._session_ended is not None, "a built source knows its session"
124            rendition._build(self._source, self._session_ended, self._announced)
125        return rendition

Add a video rendition <video>_<name> (plus _cmaf if enabled).

Feed the same pictures and keyframe positions as the primary video (bitrate in bits/s and framerate go in the catalog). Raises ValueError/TypeError for invalid options or conflicting prior registrations, and RuntimeError on track-name collision or after publishing failure.

def push_video(self, data: bytes, timestamp_micros: int) -> bool:
127    def push_video(self, data: bytes, timestamp_micros: int) -> bool:
128        """Push one encoded video frame (`timestamp_micros` must be monotonic; keyframes start a new group).
129
130        Returns `False` if dropped (before announce, after exit/session end, on backpressure, or non-picture AU).
131        Raises `RuntimeError` before `configure_video()` or after publishing failure.
132        """
133        if self._video_codec is None:
134            raise RuntimeError("call configure_video first")
135        return self._publish(lambda source: source.push_video(data, timestamp_micros), push=True)

Push one encoded video frame (timestamp_micros must be monotonic; keyframes start a new group).

Returns False if dropped (before announce, after exit/session end, on backpressure, or non-picture AU). Raises RuntimeError before configure_video() or after publishing failure.

def configure_audio( self, codec: str, sample_rate: int, channels: int, *, description: bytes | None = None) -> None:
137    def configure_audio(
138        self, codec: str, sample_rate: int, channels: int, *, description: bytes | None = None
139    ) -> None:
140        """`"opus"`, or an AAC `"mp4a.40.*"` whose `description` is the AudioSpecificConfig;
141        raises ValueError for another codec, an AAC without it, and a negative `sample_rate` or
142        `channels`, or one too large, TypeError for one that is no integer, as None, and
143        RuntimeError once publishing the source failed. A refused configuration changes nothing."""
144        _check_unsigned("sample_rate", sample_rate, 32)
145        _check_unsigned("channels", channels, 8)
146        if codec != "opus" and not codec.startswith("mp4a.40."):
147            raise ValueError(f"unsupported audio codec: {codec}")
148        if codec != "opus":
149            if description is None:
150                raise ValueError("AAC needs its AudioSpecificConfig")
151            _native.check_audio_specific_config(description)
152        self._publish(lambda source: source.configure_audio(codec, sample_rate, channels, description=description))
153        self._replaced_track_names.update(self._registered_track_names())
154        self._audio_config = (codec, sample_rate, channels, description)

"opus", or an AAC "mp4a.40.*" whose description is the AudioSpecificConfig; raises ValueError for another codec, an AAC without it, and a negative sample_rate or channels, or one too large, TypeError for one that is no integer, as None, and RuntimeError once publishing the source failed. A refused configuration changes nothing.

def push_audio( self, data: bytes, timestamp_micros: int, *, level: int | None = None, voice_activity: bool = False) -> bool:
156    def push_audio(
157        self, data: bytes, timestamp_micros: int, *, level: int | None = None, voice_activity: bool = False
158    ) -> bool:
159        """One encoded audio frame; `level` and `voice_activity` as in
160        `_native.MediaSource.push_audio`. Returns whether the native source took it, as
161        `push_video` does. Raises RuntimeError before `configure_audio`, and once publishing the
162        source failed."""
163        if self._audio_config is None:
164            raise RuntimeError("call configure_audio first")
165        return self._publish(
166            lambda source: source.push_audio(data, timestamp_micros, level=level, voice_activity=voice_activity),
167            push=True,
168        )

One encoded audio frame; level and voice_activity as in _native.MediaSource.push_audio. Returns whether the native source took it, as push_video does. Raises RuntimeError before configure_audio, and once publishing the source failed.

async def remove_track(self, kind: str) -> None:
196    async def remove_track(self, kind: str) -> None:
197        """`_native.MediaSource.remove_track` (`kind` is `"video"` or `"audio"`): stop pushing its
198        media first; `configure_video` or `configure_audio` and the media pushed after it publish
199        the track again. Before the broadcast is published, it forgets the kind's configuration
200        (the renditions' too, for the video). Raises ValueError for another kind, and RuntimeError
201        once publishing the source failed. The native removal runs to its end, the renditions'
202        removals after the video's included, even when its caller is cancelled, as by a timeout;
203        a call while it runs awaits it."""
204        if kind not in ("video", "audio"):
205            raise ValueError(f"unknown track kind: {kind}")
206        self._raise_if_failed()
207        if self._source is not None:
208            removing = self._removing.get(kind)
209            if removing is None or removing.done():
210                removing = self._removing[kind] = asyncio.ensure_future(self._source.remove_track(kind))
211                # Its failure goes to the callers, and to nobody once they were all cancelled.
212                removing.add_done_callback(retrieve)
213            await asyncio.shield(removing)
214        elif kind == "video":
215            self._video_codec = None
216            for rendition in self._renditions:
217                rendition._video_codec = None
218        else:
219            self._audio_config = None

_native.MediaSource.remove_track (kind is "video" or "audio"): stop pushing its media first; configure_video or configure_audio and the media pushed after it publish the track again. Before the broadcast is published, it forgets the kind's configuration (the renditions' too, for the video). Raises ValueError for another kind, and RuntimeError once publishing the source failed. The native removal runs to its end, the renditions' removals after the video's included, even when its caller is cancelled, as by a timeout; a call while it runs awaits it.

async def keyframe_request(self) -> None:
221    async def keyframe_request(self) -> None:
222        """Resolves the next time a subscriber asks for a new group (NEW_GROUP_REQUEST) or the
223        broadcast needs one: encode the next frame as a keyframe then. Waits while the broadcast is
224        not published; raises RuntimeError once the broadcast was left or the session ended, and
225        what kept the broadcast from being published or stopped publishing the source. One caller
226        at a time: a call while another waits raises RuntimeError."""
227        await self._while_publishing("keyframe_request", lambda source: source.keyframe_request())

Resolves the next time a subscriber asks for a new group (NEW_GROUP_REQUEST) or the broadcast needs one: encode the next frame as a keyframe then. Waits while the broadcast is not published; raises RuntimeError once the broadcast was left or the session ended, and what kept the broadcast from being published or stopped publishing the source. One caller at a time: a call while another waits raises RuntimeError.

async def demand_change(self) -> Demand:
229    async def demand_change(self) -> _native.Demand:
230        """`_native.MediaSource.demand_change`; waits while the broadcast is not published. Raises
231        RuntimeError for a source added with `on_demand=False`, and once the broadcast was left or
232        the session ended; raises what kept the broadcast from being published or stopped
233        publishing the source. One caller at a time: a call while another waits raises
234        RuntimeError."""
235        if not self._on_demand:
236            raise RuntimeError("the source was added with on_demand=False")
237        return await self._while_publishing("demand_change", lambda source: source.demand_change())

_native.MediaSource.demand_change; waits while the broadcast is not published. Raises RuntimeError for a source added with on_demand=False, and once the broadcast was left or the session ended; raises what kept the broadcast from being published or stopped publishing the source. One caller at a time: a call while another waits raises RuntimeError.

class RemoteBroadcast:
307class RemoteBroadcast:
308    """A remote publisher's broadcast. In `watch_broadcasts`, withdrawal cancels the handler (ending its
309    `catalogs()`, `follow()`, and `event_timeline()` iterators); republishing yields a new `RemoteBroadcast`."""
310
311    def __init__(self, session: Session, namespace: list[str]):
312        self.namespace = list(namespace)
313        self._session = session
314        self._newest_catalog_group: int | None = None
315
316    def catalogs(self) -> Following[Catalog]:
317        """Yield parsed MSF catalogs starting from the relay's current group (joining `FETCH`).
318
319        Unparseable catalogs and groups older than the newest catalog yielded by this or an earlier call on the
320        broadcast are skipped (draft-ietf-moq-msf-02 §5). Ends with the track; raises `RuntimeError` if
321        `SUBSCRIBE` fails. Use with `contextlib.aclosing`.
322        """
323        return _Catalogs(self)
324
325    def follow(
326        self,
327        name: str,
328        *,
329        namespace: list[str] | None = None,
330        on_subscribed: Callable[[], Awaitable[None]] | None = None,
331        delivery_timeout: float | None = DEFAULT_DELIVERY_TIMEOUT_SECONDS,
332    ) -> Following[Object]:
333        """Yield objects from track `name` (defaulting to this broadcast's namespace), retrying 1 s after track end or failure.
334
335        - `on_subscribed`: awaited after each accepted `SUBSCRIBE`.
336        - `delivery_timeout`: seconds before the relay drops stale groups (`None` for lossless tracks like chat).
337
338        Ends only on `SessionEnded` or an error from `on_subscribed`. Use `subscriptions()` if you need
339        to detect subscription boundaries; use with `contextlib.aclosing`.
340        """
341        return _Follow(self._subscriptions(name, namespace, on_subscribed, False, None, delivery_timeout), name)
342
343    def subscriptions(
344        self,
345        name: str,
346        *,
347        namespace: list[str] | None = None,
348        on_subscribed: Callable[[], Awaitable[None]] | None = None,
349        from_group_start: bool = False,
350        delivery_timeout: float | None = DEFAULT_DELIVERY_TIMEOUT_SECONDS,
351    ) -> Following[Following[Object]]:
352        """Like `follow()`, but yields one inner `Following[Object]` per subscription so stateful readers
353        (such as video decoders) can reset when a publisher restarts.
354
355        Advancing to the next subscription or closing unsubscribes the previous one; each yielded inner iterator
356        owns its subscription (staying subscribed until closed or dropped even if the outer iterator is dropped).
357        Cancelling a read does not end either iterator; cancelling during `on_subscribed` leaves the accepted
358        subscription for the next read without re-running `on_subscribed`. Read each inside `contextlib.aclosing`.
359        With `from_group_start=True`, joins via `subscribe_current_group` (joining `FETCH`) to start at the
360        current group's keyframe and Video Config.
361        """
362        return self._subscriptions(name, namespace, on_subscribed, from_group_start, None, delivery_timeout)
363
364    def event_timeline(
365        self, name: str, *, priority: int | None = None, delivery_timeout: float | None = None
366    ) -> Following[EventRecord]:
367        """Yield records from an MSF event timeline track (draft-ietf-moq-msf-02 §8), starting via joining `FETCH`.
368
369        Deduplicates records across resubscribes and skips malformed JSON objects.
370        `priority` defaults to 128; `delivery_timeout=None` is lossless. Use with `contextlib.aclosing`.
371        """
372        subscriptions = self._subscriptions(name, None, None, True, priority, delivery_timeout)
373        return _EventRecords(subscriptions, name, list(self.namespace))
374
375    def _subscriptions(
376        self,
377        name: str,
378        namespace: list[str] | None,
379        on_subscribed: Callable[[], Awaitable[None]] | None,
380        from_group_start: bool,
381        priority: int | None,
382        delivery_timeout: float | None,
383    ) -> _Subscriptions:
384        namespace = list(self.namespace if namespace is None else namespace)
385        return _Subscriptions(
386            self._session, namespace, name, on_subscribed, from_group_start, priority, delivery_timeout
387        )

A remote publisher's broadcast. In watch_broadcasts, withdrawal cancels the handler (ending its catalogs(), follow(), and event_timeline() iterators); republishing yields a new RemoteBroadcast.

RemoteBroadcast(session: moq_wasm.Session, namespace: list[str])
311    def __init__(self, session: Session, namespace: list[str]):
312        self.namespace = list(namespace)
313        self._session = session
314        self._newest_catalog_group: int | None = None
namespace
def catalogs(self) -> Following[Catalog]:
316    def catalogs(self) -> Following[Catalog]:
317        """Yield parsed MSF catalogs starting from the relay's current group (joining `FETCH`).
318
319        Unparseable catalogs and groups older than the newest catalog yielded by this or an earlier call on the
320        broadcast are skipped (draft-ietf-moq-msf-02 §5). Ends with the track; raises `RuntimeError` if
321        `SUBSCRIBE` fails. Use with `contextlib.aclosing`.
322        """
323        return _Catalogs(self)

Yield parsed MSF catalogs starting from the relay's current group (joining FETCH).

Unparseable catalogs and groups older than the newest catalog yielded by this or an earlier call on the broadcast are skipped (draft-ietf-moq-msf-02 §5). Ends with the track; raises RuntimeError if SUBSCRIBE fails. Use with contextlib.aclosing.

def follow( self, name: str, *, namespace: list[str] | None = None, on_subscribed: Callable[[], Awaitable[None]] | None = None, delivery_timeout: float | None = 2.0) -> Following[moq_wasm.Object]:
325    def follow(
326        self,
327        name: str,
328        *,
329        namespace: list[str] | None = None,
330        on_subscribed: Callable[[], Awaitable[None]] | None = None,
331        delivery_timeout: float | None = DEFAULT_DELIVERY_TIMEOUT_SECONDS,
332    ) -> Following[Object]:
333        """Yield objects from track `name` (defaulting to this broadcast's namespace), retrying 1 s after track end or failure.
334
335        - `on_subscribed`: awaited after each accepted `SUBSCRIBE`.
336        - `delivery_timeout`: seconds before the relay drops stale groups (`None` for lossless tracks like chat).
337
338        Ends only on `SessionEnded` or an error from `on_subscribed`. Use `subscriptions()` if you need
339        to detect subscription boundaries; use with `contextlib.aclosing`.
340        """
341        return _Follow(self._subscriptions(name, namespace, on_subscribed, False, None, delivery_timeout), name)

Yield objects from track name (defaulting to this broadcast's namespace), retrying 1 s after track end or failure.

  • on_subscribed: awaited after each accepted SUBSCRIBE.
  • delivery_timeout: seconds before the relay drops stale groups (None for lossless tracks like chat).

Ends only on SessionEnded or an error from on_subscribed. Use subscriptions() if you need to detect subscription boundaries; use with contextlib.aclosing.

def subscriptions( self, name: str, *, namespace: list[str] | None = None, on_subscribed: Callable[[], Awaitable[None]] | None = None, from_group_start: bool = False, delivery_timeout: float | None = 2.0) -> Following[Following[moq_wasm.Object]]:
343    def subscriptions(
344        self,
345        name: str,
346        *,
347        namespace: list[str] | None = None,
348        on_subscribed: Callable[[], Awaitable[None]] | None = None,
349        from_group_start: bool = False,
350        delivery_timeout: float | None = DEFAULT_DELIVERY_TIMEOUT_SECONDS,
351    ) -> Following[Following[Object]]:
352        """Like `follow()`, but yields one inner `Following[Object]` per subscription so stateful readers
353        (such as video decoders) can reset when a publisher restarts.
354
355        Advancing to the next subscription or closing unsubscribes the previous one; each yielded inner iterator
356        owns its subscription (staying subscribed until closed or dropped even if the outer iterator is dropped).
357        Cancelling a read does not end either iterator; cancelling during `on_subscribed` leaves the accepted
358        subscription for the next read without re-running `on_subscribed`. Read each inside `contextlib.aclosing`.
359        With `from_group_start=True`, joins via `subscribe_current_group` (joining `FETCH`) to start at the
360        current group's keyframe and Video Config.
361        """
362        return self._subscriptions(name, namespace, on_subscribed, from_group_start, None, delivery_timeout)

Like follow(), but yields one inner Following[Object] per subscription so stateful readers (such as video decoders) can reset when a publisher restarts.

Advancing to the next subscription or closing unsubscribes the previous one; each yielded inner iterator owns its subscription (staying subscribed until closed or dropped even if the outer iterator is dropped). Cancelling a read does not end either iterator; cancelling during on_subscribed leaves the accepted subscription for the next read without re-running on_subscribed. Read each inside contextlib.aclosing. With from_group_start=True, joins via subscribe_current_group (joining FETCH) to start at the current group's keyframe and Video Config.

def event_timeline( self, name: str, *, priority: int | None = None, delivery_timeout: float | None = None) -> Following[dict[str, typing.Any]]:
364    def event_timeline(
365        self, name: str, *, priority: int | None = None, delivery_timeout: float | None = None
366    ) -> Following[EventRecord]:
367        """Yield records from an MSF event timeline track (draft-ietf-moq-msf-02 §8), starting via joining `FETCH`.
368
369        Deduplicates records across resubscribes and skips malformed JSON objects.
370        `priority` defaults to 128; `delivery_timeout=None` is lossless. Use with `contextlib.aclosing`.
371        """
372        subscriptions = self._subscriptions(name, None, None, True, priority, delivery_timeout)
373        return _EventRecords(subscriptions, name, list(self.namespace))

Yield records from an MSF event timeline track (draft-ietf-moq-msf-02 §8), starting via joining FETCH.

Deduplicates records across resubscribes and skips malformed JSON objects. priority defaults to 128; delivery_timeout=None is lossless. Use with contextlib.aclosing.

class Rendition:
370class Rendition:
371    """Another encoding of a `MediaSource`'s video. Frames pushed before the broadcast is
372    published, the relay having accepted its namespace, or after it was left or the session ended,
373    are dropped. Once publishing the rendition or its source failed, its configuration and pushes
374    raise RuntimeError."""
375
376    def __init__(self, name: str, options: dict):
377        self._name = name
378        self._options = options
379        self._rendition: _native.Rendition | None = None
380        self._session_ended: asyncio.Future[None] | None = None
381        # Its source's: set once the relay accepted the broadcast's namespace.
382        self._announced: asyncio.Event | None = None
383        self._video_codec: str | None = None
384        # Ended by a failure to publish the rendition or its source.
385        self._ended = Ended()
386
387    @property
388    def name(self) -> str:
389        """Read-only, as the broadcast claimed the rendition's tracks by it."""
390        return self._name
391
392    def configure_video(self, codec: str) -> None:
393        """As `MediaSource.configure_video`; it may differ from the video's codec."""
394        _check_video_codec(codec)
395        self._publish(lambda rendition: rendition.configure_video(codec))
396        self._video_codec = codec
397
398    def push_video(self, data: bytes, timestamp_micros: int) -> bool:
399        """An encoded frame of the same picture as a video frame, at that frame's timestamp.
400        Returns whether the native rendition took it, as `MediaSource.push_video` does. Raises
401        RuntimeError before `configure_video`, and once publishing the rendition failed while the
402        session was live."""
403        if self._video_codec is None:
404            raise RuntimeError("call configure_video first")
405        return self._publish(lambda rendition: rendition.push_video(data, timestamp_micros), push=True)
406
407    def _publish(self, call: Callable[[_native.Rendition], bool | None], *, push: bool = False) -> bool:
408        """`call` on the native rendition once it is built, and for a `push` once the broadcast was
409        published; returns whether the native rendition took it. Raises RuntimeError once
410        publishing it failed; a failure of `call` in a live session is that failure."""
411        if self._ended.failed:
412            raise RuntimeError(f"rendition {self.name} stopped publishing") from self._ended.error()
413        if (rendition := self._rendition) is None:
414            return False
415        if push and not (self._announced is not None and self._announced.is_set()):
416            return False
417        try:
418            return _call_native(lambda: call(rendition), self._session_ended)
419        except RuntimeError as failure:
420            self._ended.end(failure)
421            raise
422
423    def _build(
424        self, source: _native.MediaSource, session_ended: asyncio.Future[None], announced: asyncio.Event
425    ) -> None:
426        rendition = source.add_rendition(self.name, **self._options)
427        if self._video_codec is not None:
428            rendition.configure_video(self._video_codec)
429        self._rendition = rendition
430        self._session_ended = session_ended
431        self._announced = announced

Another encoding of a MediaSource's video. Frames pushed before the broadcast is published, the relay having accepted its namespace, or after it was left or the session ended, are dropped. Once publishing the rendition or its source failed, its configuration and pushes raise RuntimeError.

Rendition(name: str, options: dict)
376    def __init__(self, name: str, options: dict):
377        self._name = name
378        self._options = options
379        self._rendition: _native.Rendition | None = None
380        self._session_ended: asyncio.Future[None] | None = None
381        # Its source's: set once the relay accepted the broadcast's namespace.
382        self._announced: asyncio.Event | None = None
383        self._video_codec: str | None = None
384        # Ended by a failure to publish the rendition or its source.
385        self._ended = Ended()
name: str
387    @property
388    def name(self) -> str:
389        """Read-only, as the broadcast claimed the rendition's tracks by it."""
390        return self._name

Read-only, as the broadcast claimed the rendition's tracks by it.

def configure_video(self, codec: str) -> None:
392    def configure_video(self, codec: str) -> None:
393        """As `MediaSource.configure_video`; it may differ from the video's codec."""
394        _check_video_codec(codec)
395        self._publish(lambda rendition: rendition.configure_video(codec))
396        self._video_codec = codec

As MediaSource.configure_video; it may differ from the video's codec.

def push_video(self, data: bytes, timestamp_micros: int) -> bool:
398    def push_video(self, data: bytes, timestamp_micros: int) -> bool:
399        """An encoded frame of the same picture as a video frame, at that frame's timestamp.
400        Returns whether the native rendition took it, as `MediaSource.push_video` does. Raises
401        RuntimeError before `configure_video`, and once publishing the rendition failed while the
402        session was live."""
403        if self._video_codec is None:
404            raise RuntimeError("call configure_video first")
405        return self._publish(lambda rendition: rendition.push_video(data, timestamp_micros), push=True)

An encoded frame of the same picture as a video frame, at that frame's timestamp. Returns whether the native rendition took it, as MediaSource.push_video does. Raises RuntimeError before configure_video, and once publishing the rendition failed while the session was live.

def create_broadcast( session: moq_wasm.Session, namespace: list[str]) -> LocalBroadcast:
413def create_broadcast(session: Session, namespace: list[str]) -> LocalBroadcast:
414    """Use it with `async with`: entering publishes the namespace, leaving withdraws it."""
415    return LocalBroadcast(session, namespace)

Use it with async with: entering publishes the namespace, leaving withdraws it.

async def watch_broadcasts( session: moq_wasm.Session, prefix: list[str], handler: Callable[[RemoteBroadcast], Awaitable[None]], *, filter: Callable[[list[str]], bool] | None = None, empty_timeout: float | None = None) -> None:
404async def watch_broadcasts(
405    session: Session,
406    prefix: list[str],
407    handler: Callable[[RemoteBroadcast], Awaitable[None]],
408    *,
409    filter: Callable[[list[str]], bool] | None = None,
410    empty_timeout: float | None = None,
411) -> None:
412    """Run `handler(RemoteBroadcast)` as a task for each remote namespace under `prefix` accepted by `filter`
413    (including namespaces already published before the call, skipping this session's own).
414
415    Cancels a handler on withdrawal, waits for teardown before restarting if republished, and logs handler
416    exceptions. Raises `SessionEnded` if the session ends, returns if `empty_timeout` elapses with no active
417    broadcasts, and raises `RuntimeError` if `SUBSCRIBE_NAMESPACE` fails.
418    """
419    watch = await session.watch_namespaces(prefix)
420    await follow_watch(session, watch, handler, filter=filter, empty_timeout=empty_timeout)

Run handler(RemoteBroadcast) as a task for each remote namespace under prefix accepted by filter (including namespaces already published before the call, skipping this session's own).

Cancels a handler on withdrawal, waits for teardown before restarting if republished, and logs handler exceptions. Raises SessionEnded if the session ends, returns if empty_timeout elapses with no active broadcasts, and raises RuntimeError if SUBSCRIBE_NAMESPACE fails.