moq_wasm.codecs

PyAV codecs for the media of LOC tracks. Needs the codecs extra, moq-wasm[codecs]: the wheel carries no codec of its own (docs/architecture/python/sdk.md "No codec in the wheel").

  1"""PyAV codecs for the media of LOC tracks. Needs the `codecs` extra, `moq-wasm[codecs]`: the wheel
  2carries no codec of its own (docs/architecture/python/sdk.md "No codec in the wheel")."""
  3
  4import asyncio
  5import functools
  6import logging
  7import operator
  8import time
  9from collections import deque
 10from collections.abc import AsyncIterable, Awaitable, Callable
 11from dataclasses import dataclass, replace
 12from fractions import Fraction
 13from typing import cast
 14
 15import av
 16import numpy as np
 17from av.error import FFmpegError
 18from av.video.frame import PictureType
 19
 20from moq_wasm._native import Location, Object
 21from moq_wasm._once import in_thread, retrieve
 22from moq_wasm.media import Following, RemoteBroadcast
 23from moq_wasm.media._remote_broadcast import DEFAULT_DELIVERY_TIMEOUT_SECONDS, _Objects
 24
 25logger = logging.getLogger("moq_wasm")
 26
 27OPUS_SAMPLE_RATE = 48_000
 28PCM_LAYOUTS = {1: "mono", 2: "stereo"}
 29OPUS_BITRATE = 32_000
 30
 31# The Object Status of an object that ends its group (draft-ietf-moq-transport-14 §10.2.1.1).
 32END_OF_GROUP_STATUS = 3
 33# The LOC Video Config property: the codec's extradata, such as an H.264 avcC record
 34# (draft-ietf-moq-loc-04 §2.3.2.1).
 35VIDEO_CONFIG_ID = 0x0D
 36# How many groups `decode_pictures` decodes at once: the objects of groups in flight interleave, and a
 37# group still open when this many newer ones opened is taken as complete.
 38MAX_OPEN_GROUPS = 4
 39# How many complete groups `decode_pictures` remembers, to skip their late objects.
 40FINISHED_GROUPS_KEPT = 16
 41# How many objects, and how many bytes of their payloads, a group without a Video Config of its own
 42# holds while the group before it has not arrived, before `decode_pictures` takes that group as late
 43# or lost.
 44MAX_HELD_OBJECTS = 5
 45MAX_HELD_BYTES = 4 * 1024 * 1024
 46# How many objects in a row `decode_pictures` lets the decoder of a group joined at its keyframe
 47# refuse before it takes the track as undecodable.
 48MAX_REFUSED_OBJECTS = 3
 49# The first elements of the codec strings whose payloads may be length-prefixed, which only the Video
 50# Config tells how to read (draft-ietf-moq-loc-04 §2.1.3).
 51LENGTH_PREFIXED_CODECS = ("avc1", "avc3", "hvc1", "hev1")
 52# The 4-byte start code an Annex B payload starts with, and the 3-byte one a track without a Video
 53# Config may use instead (draft-ietf-moq-loc-04 §2.1.4).
 54START_CODE = b"\x00\x00\x00\x01"
 55SHORT_START_CODE = b"\x00\x00\x01"
 56# The NAL unit type of a sequence parameter set: H.264's (ITU-T H.264 Table 7-1) and H.265's (ITU-T
 57# H.265 Table 7-1).
 58H264_SPS = 7
 59HEVC_SPS = 33
 60
 61# A video codec string's first element, as the catalog writes it, to the PyAV decoders that decode
 62# it in software, the preferred first. FFmpeg's own AV1 decoder (`av1`) is left out: it decodes only
 63# through a hardware accelerator, which PyAV does not set up, and refuses every packet otherwise.
 64VIDEO_DECODERS = {
 65    "avc1": ("h264",),
 66    "avc3": ("h264",),
 67    "hvc1": ("hevc",),
 68    "hev1": ("hevc",),
 69    "vp8": ("vp8", "libvpx"),
 70    "vp09": ("vp9", "libvpx-vp9"),
 71    "av01": ("libdav1d", "libaom-av1"),
 72}
 73# Decoders forced to single-threaded mode: dav1d worker threads release packet payloads/opaque
 74# references asynchronously while acquiring the GIL, deadlocking against decoder teardown under GIL.
 75THREADLESS_DECODERS = ("libdav1d",)
 76
 77
 78def _decoder_name(codec: str) -> str | None:
 79    """The PyAV decoder `VideoDecoder` takes for `codec`, a WebCodecs codec string: the first of its
 80    `VIDEO_DECODERS` this PyAV build has, or None when it has none of them."""
 81    family = codec.split(".")[0]
 82    # Only the families `VIDEO_DECODERS` lists are looked up, and remembered, so the codec strings
 83    # of catalogs, unsupported ones included, do not pile up.
 84    return _family_decoder_name(family) if family in VIDEO_DECODERS else None
 85
 86
 87@functools.cache
 88def _family_decoder_name(family: str) -> str | None:
 89    for name in VIDEO_DECODERS[family]:
 90        try:
 91            av.Codec(name, "r")
 92        except ValueError:
 93            continue
 94        return name
 95    return None
 96
 97
 98class OpusDecoder:
 99    """Turns the Opus packets of a LOC audio track into 16-bit PCM at `sample_rate` with `channels`
100    interleaved channels, mono or stereo, mixed from the track's own. Raises ValueError for another
101    channel count."""
102
103    def __init__(self, sample_rate: int, channels: int = 1):
104        self._channels = channels
105        # `kind` types the context as audio, which PyAV 15 does not for
106        # `CodecContext.create("opus")`.
107        self._decoder = av.Codec("opus", "r").create("audio")
108        self._resampler = av.AudioResampler(format="s16", layout=_pcm_layout(channels), rate=sample_rate)
109
110    def decode(self, packet: bytes) -> bytes:
111        return b"".join(
112            bytes(resampled.planes[0])[: resampled.samples * self._channels * 2]
113            for decoded in self._decoder.decode(av.Packet(packet))
114            for resampled in self._resampler.resample(decoded)
115        )
116
117
118class _PcmResampler:
119    """Resamples 16-bit interleaved PCM, mono or stereo at any rate, to `sample_rate` and
120    `num_channels` as one stream, whose layout and rate may change from one call to the next. The
121    resampler holds back a few samples of what it was given; `flush` returns them at the end of the
122    stream, so what came out lasts as long as what went in."""
123
124    def __init__(self, sample_rate: int, num_channels: int):
125        self._layout = _pcm_layout(num_channels)
126        self._rate = sample_rate
127        # A resampler takes the layout and rate of its first frame only, so each input layout and
128        # rate gets one of its own.
129        self._resampler: av.AudioResampler | None = None
130        self._input: tuple[str, int] | None = None
131        # The input's duration and what the resamplers gave of it so far, in output samples: a
132        # resampler may keep, or drop at its end, a few samples of a short input.
133        self._samples_in = 0.0
134        self._samples_out = 0
135
136    def resample(self, pcm: bytes, sample_rate: int, num_channels: int = 1) -> bytes:
137        """What `pcm` makes of the stream so far. Raises ValueError for more than two channels and
138        for a `sample_rate` that is no positive integer, before it changes anything, so the stream
139        goes on with the next call. Empty `pcm` gives nothing and leaves the stream as it was: a
140        resampler refuses a frame of no samples."""
141        layout = _pcm_layout(num_channels)
142        sample_rate = _pcm_rate(sample_rate)
143        if not pcm:
144            return b""
145        frame = av.AudioFrame.from_ndarray(np.frombuffer(pcm, np.int16).reshape(1, -1), format="s16", layout=layout)
146        frame.sample_rate = sample_rate
147        drained = b""
148        if self._resampler is None or self._input != (layout, sample_rate):
149            drained = self._drain()
150            self._resampler = av.AudioResampler(format="s16", layout=self._layout, rate=self._rate)
151            self._input = (layout, sample_rate)
152        self._samples_in += frame.samples * self._rate / sample_rate
153        return drained + self._take(self._resampler.resample(frame))
154
155    def flush(self) -> bytes:
156        """The rest of the stream: what the resampler holds, then silence up to the input's
157        duration. The next call starts a new stream."""
158        pcm = self._drain()
159        missing = round(self._samples_in) - self._samples_out
160        if missing > 0:
161            pcm += bytes(missing * self._channels * 2)
162        self.reset()
163        return pcm
164
165    @property
166    def held_samples(self) -> int:
167        """The output samples of the stream so far that the resampler holds back."""
168        return max(round(self._samples_in) - self._samples_out, 0)
169
170    def reset(self) -> None:
171        """Drops what the resampler holds; the next call starts a new stream."""
172        self._resampler = None
173        self._input = None
174        self._samples_in = 0.0
175        self._samples_out = 0
176
177    @property
178    def _channels(self) -> int:
179        return 2 if self._layout == "stereo" else 1
180
181    def _drain(self) -> bytes:
182        """The samples the resampler holds, up to the input's duration; the resampler takes no
183        more. A resampler gives nothing of an input shorter than its filter, even flushed, so it is
184        given 20 ms of silence first, and what comes of the silence is dropped."""
185        if self._resampler is None or self._input is None:
186            return b""
187        layout, sample_rate = self._input
188        channels = 2 if layout == "stereo" else 1
189        padding = np.zeros((1, sample_rate // 50 * channels), np.int16)
190        silence = av.AudioFrame.from_ndarray(padding, format="s16", layout=layout)
191        silence.sample_rate = sample_rate
192        drained = [*self._resampler.resample(silence), *self._resampler.resample(None)]
193        self._resampler = None
194        return self._take(drained, limit=round(self._samples_in) - self._samples_out)
195
196    def _take(self, resampled: list[av.AudioFrame], limit: int | None = None) -> bytes:
197        """The frames' samples, or their first `limit` samples."""
198        pcm = b""
199        for frame in resampled:
200            samples = frame.to_ndarray()[:, : frame.samples * self._channels]
201            if limit is not None:
202                samples = samples[:, : max(limit, 0) * self._channels]
203                limit -= samples.shape[1] // self._channels
204            pcm += samples.tobytes()
205            self._samples_out += samples.shape[1] // self._channels
206        return pcm
207
208
209def _pcm_rate(sample_rate: int) -> int:
210    try:
211        rate = operator.index(sample_rate)
212    except TypeError:
213        rate = 0
214    if rate <= 0:
215        raise ValueError(f"the sample rate must be a positive integer: {sample_rate!r}")
216    return rate
217
218
219def _pcm_layout(num_channels: int) -> str:
220    layout = PCM_LAYOUTS.get(num_channels)
221    if layout is None:
222        raise ValueError(f"cannot take {num_channels} channels: give mono or stereo PCM")
223    return layout
224
225
226class OpusEncoder:
227    """Turns 16-bit PCM at any rate into 20 ms Opus packets at 48 kHz of `channels` channels, mono
228    or stereo, at `bitrate` bits a second. Raises ValueError for another channel count."""
229
230    def __init__(self, bitrate: int = OPUS_BITRATE, channels: int = 1):
231        self._layout = _pcm_layout(channels)
232        self._channels = channels
233        self._encoder = av.CodecContext.create("libopus", "w")
234        self._encoder.sample_rate = OPUS_SAMPLE_RATE
235        self._encoder.layout = self._layout
236        self._encoder.format = "s16"
237        self._encoder.bit_rate = bitrate
238        self._encoder.open()
239        self._resampler = _PcmResampler(OPUS_SAMPLE_RATE, channels)
240        self._fifo = av.AudioFifo()
241        self.frame_samples = self._encoder.frame_size
242
243    def encode(self, pcm: bytes, sample_rate: int, num_channels: int = 1) -> list[bytes]:
244        """Returns the packets `pcm`, 16-bit PCM at `sample_rate` with `num_channels` interleaved
245        channels, downmixed or upmixed to the encoder's, completes; the samples short of a packet
246        wait for the next call. The layout and rate may change from one call to the next. Raises
247        ValueError, taking none of `pcm`, for more than two channels and for a `sample_rate` that is
248        not a positive integer."""
249        self._write(self._resampler.resample(pcm, sample_rate, num_channels))
250        return self._encode_fifo()
251
252    def finish(self) -> list[bytes]:
253        """The packets of the samples the encoder still holds, at the end of a stream: at least the
254        input's duration, the last packet padded with silence. The encoder takes no more PCM after
255        it."""
256        self._write(self._resampler.flush())
257        self._write(bytes(-self._fifo.samples % self.frame_samples * self._channels * 2))
258        packets = self._encode_fifo()
259        packets.extend(bytes(packet) for packet in self._encoder.encode(None))
260        return packets
261
262    @property
263    def held_micros(self) -> float:
264        """Microseconds of the PCM taken that no packet returned yet carries: the samples short of
265        a packet and those the resampler holds back."""
266        return (self._fifo.samples + self._resampler.held_samples) * 1_000_000 / OPUS_SAMPLE_RATE
267
268    def _write(self, pcm: bytes) -> None:
269        """Writes 48 kHz PCM of the encoder's channels into the FIFO."""
270        if not pcm:
271            return
272        frame = av.AudioFrame.from_ndarray(
273            np.frombuffer(pcm, np.int16).reshape(1, -1), format="s16", layout=self._layout
274        )
275        frame.sample_rate = OPUS_SAMPLE_RATE
276        self._fifo.write(frame)
277
278    def _encode_fifo(self) -> list[bytes]:
279        packets = []
280        while (chunk := self._fifo.read(self.frame_samples)) is not None:
281            chunk.pts = None
282            packets.extend(bytes(packet) for packet in self._encoder.encode(chunk))
283        return packets
284
285
286class VideoDecoder:
287    """Decodes one LOC video group into pictures (create one per group; mid-group joins yield nothing).
288
289    With B-frames, frames may be delayed and finalized by `flush()`, each paired with its input `Location`.
290    `config` is the LOC Video Config extradata (e.g. H.264 `avcC` / H.265 `hvcC`).
291    """
292
293    def __init__(self, codec: str, config: bytes | None = None):
294        name = _decoder_name(codec)
295        if name is None:
296            raise ValueError(f"no decoder for video codec {codec}")
297        self._decoder = cast(av.VideoCodecContext, av.CodecContext.create(name, "r"))
298        if name in THREADLESS_DECODERS:
299            self._decoder.thread_count = 1
300        if config is not None:
301            self._decoder.extradata = config
302        # Each packet carries the Location of its object through the decoder to the pictures it
303        # makes, so a packet that makes none, as an invisible VP8 frame, leaves nothing behind.
304        self._decoder.copy_opaque = True
305        self._next_pts = 0
306
307    def decode(self, payload: bytes, location: Location | None = None) -> list[tuple[av.VideoFrame, Location | None]]:
308        """The pictures the object completes, in presentation order, each with the `location` of
309        the object it was decoded from; none for an object the decoder refuses."""
310        try:
311            return self._decode(payload, location)
312        except FFmpegError:
313            return []
314
315    def _decode(self, payload: bytes, location: Location | None) -> list[tuple[av.VideoFrame, Location | None]]:
316        """`decode`, raising the FFmpegError of an object the decoder refuses."""
317        packet = av.Packet(payload)
318        packet.pts = self._next_pts
319        packet.opaque = location
320        self._next_pts += 1
321        return self._located(self._decoder.decode(packet))
322
323    def flush(self) -> list[tuple[av.VideoFrame, Location | None]]:
324        """The pictures the decoder still holds, at the end of the group."""
325        try:
326            return self._located(self._decoder.decode(None))
327        except FFmpegError:
328            return []
329
330    def _located(self, pictures: list[av.VideoFrame]) -> list[tuple[av.VideoFrame, Location | None]]:
331        return [(picture, cast(Location | None, picture.opaque)) for picture in pictures if picture.pts is not None]
332
333
334class _Group:
335    """Decoder state for one video group.
336
337    - Re-initializes the decoder when an object carries a new LOC Video Config.
338    - For groups joined at object 0 (keyframe), raises `FFmpegError` after `MAX_REFUSED_OBJECTS`
339      consecutive decode errors or if the group flushes with zero frames after a refusal.
340    - Without a Video Config, H.264/H.265 payloads are detected as Annex B (3/4-byte start code) or
341      4-byte length-prefixed (rewritten to Annex B once in-band SPS arrives; unconfigured frames
342      before SPS are skipped and trigger `unconfigured`).
343    """
344
345    def __init__(self, codec: str, config: bytes | None, from_keyframe: bool, unconfigured: Callable[[], None]):
346        self._codec = codec
347        self._unconfigured = unconfigured
348        family = codec.split(".")[0]
349        self._length_prefixed = family in LENGTH_PREFIXED_CODECS
350        self._hevc = family in ("hvc1", "hev1")
351        # Whether a length-prefixed object of the group carried an SPS, which a group without a
352        # Video Config needs before its length-prefixed objects decode.
353        self._in_band_parameter_sets = False
354        # Whether the group's objects are Annex B, as its first one readable either way was; None
355        # before it.
356        self._framed_annex_b: bool | None = None
357        # The Video Config the group decodes with now.
358        self.config = config
359        self._decoder = VideoDecoder(codec, config)
360        self._from_keyframe = from_keyframe
361        self._refused_in_a_row = 0
362        self._refusal: FFmpegError | None = None
363        self._pictured = False
364
365    def decode(
366        self, payload: bytes, location: Location, config: bytes | None
367    ) -> list[tuple[av.VideoFrame, Location | None]]:
368        """The pictures the object completes; `config` is the Video Config the object carries."""
369        held_back = []
370        if config is not None and config != self.config:
371            held_back = self._decoder.flush()
372            self._pictured = self._pictured or bool(held_back)
373            self.config = config
374            self._decoder = VideoDecoder(self._codec, config)
375        if self.config is None and self._length_prefixed:
376            annex_b = self._annex_b(payload)
377            if annex_b is None:
378                # Without the parameter sets, as after a subscriber joined past the only object
379                # carrying the Video Config.
380                if self._from_keyframe:
381                    self._unconfigured()
382                return held_back
383            payload = annex_b
384        try:
385            pictures = self._decoder._decode(payload, location)
386        except FFmpegError as error:
387            self._refused_in_a_row += 1
388            self._refusal = error
389            if self._from_keyframe and self._refused_in_a_row >= MAX_REFUSED_OBJECTS:
390                raise
391            return held_back
392        self._refused_in_a_row = 0
393        self._pictured = self._pictured or bool(pictures)
394        return held_back + pictures
395
396    def _annex_b(self, payload: bytes) -> bytes | None:
397        """`payload`, of a group without a Video Config, in Annex B, or None when it cannot be read
398        without one. A payload starting with a start code whose 4-byte length prefixes also cover
399        it exactly, as a 3-byte one followed by the first bytes of a length of 256 to 511 bytes
400        does, is read as the group's earlier objects were (draft-ietf-moq-loc-04 §2.1.3–2.1.4); in
401        the group's first object, a 4-byte start code is Annex B and a 3-byte one a length."""
402        units = _length_prefixed_units(payload)
403        annex_b = payload.startswith((SHORT_START_CODE, START_CODE))
404        if annex_b and units is not None:
405            framed = self._framed_annex_b
406            annex_b = payload.startswith(START_CODE) if framed is None else framed
407        if annex_b or units is not None:
408            self._framed_annex_b = annex_b
409        if annex_b:
410            return payload
411        if units is None:
412            return None
413        self._in_band_parameter_sets = self._in_band_parameter_sets or any(map(self._is_sps, units))
414        return b"".join(START_CODE + unit for unit in units) if self._in_band_parameter_sets else None
415
416    def _is_sps(self, unit: bytes) -> bool:
417        if self._hevc:
418            return unit[0] >> 1 & 0x3F == HEVC_SPS
419        return unit[0] & 0x1F == H264_SPS
420
421    def flush(self) -> list[tuple[av.VideoFrame, Location | None]]:
422        pictures = self._decoder.flush()
423        if self._from_keyframe and not (self._pictured or pictures) and self._refusal is not None:
424            raise self._refusal
425        return pictures
426
427
428@dataclass(frozen=True)
429class _PassedConfig:
430    """The Video Config a group passes on to the group after it, and the group whose own one it is:
431    the group itself for one it carried, -1 for none or the initial one `decode_pictures` was
432    given."""
433
434    config: bytes | None
435    supplier: int
436
437
438@dataclass(frozen=True)
439class DecodedPicture:
440    picture: av.VideoFrame
441    location: Location
442    """The Location of the object the picture was decoded from."""
443    decoded_at: float
444    """`time.monotonic()` when it was decoded."""
445    largest: Location | None = None
446    """For a picture `follow_pictures` decoded, the Largest Location the SUBSCRIBE_OK of its
447    subscription reported: the pictures before it were replayed from what the relay held, older
448    than the subscription. None from `decode_pictures`, and for a track that had no object when it
449    was subscribed to."""
450
451
452def decode_pictures(
453    objects: AsyncIterable[Object], codec: str, *, interval: float = 0.0, config: bytes | None = None
454) -> Following[DecodedPicture]:
455    """Decode a single LOC video subscription in a worker thread, yielding pictures in presentation order
456    within each group (throttled to at most one every `interval` seconds; overlapping subgroups or
457    config-change re-decodes can interleave or repeat across groups). Use `follow_pictures()` across resubscriptions.
458
459    - **Config**: groups inherit the previous group's LOC Video Config (holding up to `MAX_HELD_OBJECTS` /
460      `MAX_HELD_BYTES` while waiting for an out-of-order predecessor, falling back to `config`, e.g.
461      `Catalog.init_data`) and re-decode if a provisional config changes. Length-prefixed H.264/H.265
462      frames arriving before parameter sets or a config are skipped with one warning.
463    - **Errors**: raises `ValueError` immediately for unsupported `codec`, and `av.error.FFmpegError` on
464      read if a keyframe-joined group fails to decode.
465    - **Lifecycle**: each group gets its own `VideoDecoder` (flushed on End-of-Group, after
466      `MAX_OPEN_GROUPS` newer groups, or at EOF). Does not close `objects`; timing out a read can cancel
467      an async generator (use `Subscription`, `RemoteBroadcast.subscriptions()`, or `follow_pictures()`
468      with timeouts). `aclose()` stops reads immediately and frees decoders once any in-flight worker step finishes.
469    """
470    return _DecodedPictures(objects, codec, interval, config)
471
472
473class _DecodedPictures(Following[DecodedPicture]):
474    """What `decode_pictures` returns: the pictures of each object, decoded whole in a thread, the
475    object in flight kept across a cancelled read."""
476
477    # Its reads await `objects`, which are the caller's.
478    _interrupts = False
479
480    def __init__(self, objects: AsyncIterable[Object], codec: str, interval: float, config: bytes | None):
481        super().__init__("the pictures")
482        # None once closed: the decoders and the pictures they hold are freed, once a decoding in a
483        # worker finished.
484        self._decoder: _PictureDecoder | None = _PictureDecoder(codec, interval, config)
485        self._objects = aiter(objects)
486        self._objects_ended = False
487        # The decoding of the latest object in a thread, or of the end of the objects.
488        self._decoding: asyncio.Future[list[DecodedPicture]] | None = None
489        self._pictures: deque[DecodedPicture] = deque()
490
491    async def _next(self) -> DecodedPicture:
492        while not self._pictures:
493            decoding = self._decoding
494            if decoding is None:
495                # Closed while an object that gave no picture was decoded, the objects are not read
496                # again.
497                if self._objects_ended or self._closing.started:
498                    raise StopAsyncIteration
499                try:
500                    video_object = await anext(self._objects)
501                except StopAsyncIteration:
502                    self._objects_ended = True
503                    video_object = None
504                decoder = self._decoder
505                if decoder is None or self._closing.started:
506                    raise StopAsyncIteration
507                step = decoder.finish if video_object is None else functools.partial(decoder.take, video_object)
508                decoding = self._decoding = in_thread(step)
509                # Its failure goes to the read, and to nobody once the decoding was dropped.
510                decoding.add_done_callback(retrieve)
511                # The read may wait on the next object once this one gave no picture: it holds no
512                # decoder meanwhile, so closing the decoding frees it.
513                del decoder, step
514            await asyncio.wait([decoding])
515            if self._closing.started:
516                raise StopAsyncIteration
517            self._decoding = None
518            self._pictures.extend(decoding.result())
519        return self._pictures.popleft()
520
521    async def _release(self) -> None:
522        # A read in flight, waiting on the caller's objects or on a decoding in a worker, is not
523        # waited for: it finds the decoding closed and drops what it read.
524        self._decoder = None
525        self._decoding = None
526        self._pictures.clear()
527
528
529class _PictureDecoder:
530    """The decoding state of `decode_pictures`, as its docstring describes it. Its steps are
531    synchronous, so each runs whole in a worker thread, and the state is never left halfway through
532    an object."""
533
534    def __init__(self, codec: str, interval: float, initial_config: bytes | None):
535        # Raises ValueError for an unknown codec.
536        VideoDecoder(codec)
537        self._codec = codec
538        self._interval = interval
539        self._initial_config = initial_config
540        self._next_picture_at = 0.0
541        # In the order the groups opened: each group's decoding, or the objects it holds while the
542        # group before it has not arrived.
543        self._groups: dict[int, _Group | list[Object]] = {}
544        self._finished: deque[int] = deque(maxlen=FINISHED_GROUPS_KEPT)
545        # The Video Config each of the latest groups passes on to the group after it, None for one
546        # without: the newest it carried, or else the one it inherits, even once the group can no
547        # longer decode its objects again with that one; beside it, the group whose own one it is,
548        # -1 for none or the initial one.
549        # An inherited one changes with its supplier's, and becomes the one of a group between the
550        # two that arrives late, as the groups after a lost group do.
551        self._configs: dict[int, _PassedConfig] = {}
552        # The groups that took the Video Config of the group before them while that one was open,
553        # which may change it yet: the objects each decoded since, to decode them again with a
554        # changed one.
555        self._provisional: dict[int, list[Object]] = {}
556        self._carries_configs = False
557        self._warned_unconfigured = False
558
559    def take(self, video_object: Object) -> list[DecodedPicture]:
560        """The pictures `video_object` completes."""
561        groups = self._groups
562        group_id = video_object.group_id
563        if video_object.status is not None:
564            return self._finish(group_id) if video_object.status == END_OF_GROUP_STATUS else []
565        if group_id in self._finished:
566            return []
567        config = _video_config(video_object.extension_headers)
568        self._carries_configs = self._carries_configs or config is not None
569        group = groups.get(group_id)
570        if isinstance(group, _Group):
571            return self._decode(group, video_object)
572        pictures = []
573        if group is None:
574            # The groups holding their objects before this one take the groups before them as late.
575            holding = sorted(held_id for held_id, held in groups.items() if isinstance(held, list) and held_id < group_id)
576            for held_id in holding:
577                pictures.extend(self._release(held_id))
578            if len(groups) >= MAX_OPEN_GROUPS:
579                pictures.extend(self._finish(next(iter(groups))))
580            first = all(seen > group_id for seen in (*self._configs, *self._finished))
581            if config is None and self._carries_configs and not first and group_id - 1 not in (*self._configs, *self._finished):
582                group = groups[group_id] = []
583            else:
584                pictures.extend(self._start(group_id, [video_object]))
585        if isinstance(group, list):
586            if config is not None:
587                pictures.extend(self._start(group_id, [video_object]))
588            else:
589                group.append(video_object)
590                if len(group) >= MAX_HELD_OBJECTS or _payload_bytes(group) >= MAX_HELD_BYTES:
591                    pictures.extend(self._release(group_id))
592        return pictures
593
594    def finish(self) -> list[DecodedPicture]:
595        """The pictures the groups still open hold back, at the end of the objects."""
596        pictures = []
597        while self._groups:
598            pictures.extend(self._finish(min(self._groups)))
599        return pictures
600
601    def _unconfigured(self) -> None:
602        """Warns, once, that length-prefixed objects are skipped for want of their parameter
603        sets."""
604        if not self._warned_unconfigured:
605            self._warned_unconfigured = True
606            logger.warning(
607                "%s objects skipped until a group carries its Video Config: they are length-prefixed "
608                "without their parameter sets in band, and the subscription joined past the object "
609                "carrying it with none given beforehand",
610                self._codec,
611            )
612
613    def _sampled(self, pictures: list[tuple[av.VideoFrame, Location | None]]) -> list[DecodedPicture]:
614        decoded_at = time.monotonic()
615        passed = []
616        for picture, location in pictures:
617            if location is None or decoded_at < self._next_picture_at:
618                continue
619            self._next_picture_at = decoded_at + self._interval
620            passed.append(DecodedPicture(picture, location, decoded_at))
621        return passed
622
623    def _remember(self, group_id: int, passed: _PassedConfig) -> None:
624        self._configs[group_id] = passed
625        if len(self._configs) > FINISHED_GROUPS_KEPT + MAX_OPEN_GROUPS:
626            del self._configs[min(self._configs)]
627
628    def _supplier(self, group_id: int) -> int:
629        """The group whose own Video Config `group_id` passes on; itself for one it does not
630        remember."""
631        passed = self._configs.get(group_id)
632        return group_id if passed is None else passed.supplier
633
634    def _inherited(self, group_id: int) -> _PassedConfig:
635        """The Video Config of the newest group before `group_id` that had one, with the group whose
636        own one it is, or else the initial one, of no group."""
637        configs = self._configs
638        earlier = [earlier_id for earlier_id, passed in configs.items() if earlier_id < group_id and passed.config is not None]
639        return configs[max(earlier)] if earlier else _PassedConfig(self._initial_config, -1)
640
641    def _decode(self, group: _Group, video_object: Object) -> list[DecodedPicture]:
642        group_id = video_object.group_id
643        location = Location(group_id, video_object.object_id)
644        config = _video_config(video_object.extension_headers)
645        previous = group.config
646        # A group carrying its first Video Config of its own supplies the groups after it from now
647        # on, even with the one it inherited: a late group before it no longer reaches them.
648        supplied = config is not None and self._supplier(group_id) != group_id
649        pictures = group.decode(video_object.payload, location, config)
650        if config is not None or self._supplier(group_id) == group_id:
651            self._remember(group_id, _PassedConfig(group.config, group_id))
652        kept = self._provisional.get(group_id)
653        if kept is not None:
654            kept.append(video_object)
655            # A Video Config of its own, or more decoded than a group holds while it waits, makes
656            # the group's final.
657            if config is not None or len(kept) > MAX_HELD_OBJECTS or _payload_bytes(kept) > MAX_HELD_BYTES:
658                del self._provisional[group_id]
659        decoded = self._sampled(pictures)
660        if group.config != previous or supplied:
661            decoded.extend(self._reconfigure(group_id, group.config))
662        return decoded
663
664    def _reconfigure(self, group_id: int, config: bytes | None) -> list[DecodedPicture]:
665        """Passes `config`, the new Video Config `group_id` passes on, or the one it now supplies
666        itself, to the groups after it that inherit theirs from no later group than it does, across
667        the groups that have not arrived: those are the groups until the next one with a Video
668        Config of its own. A group whose Video Config is provisional decodes what it decoded with
669        the old one again, with `config`, and gives its pictures again; one that decoded too much to
670        do so keeps decoding with the old one, but passes `config` on, so the groups after it decode
671        with it."""
672        passing = self._supplier(group_id)
673        pictures = []
674        for later_id, passed in sorted(self._configs.items()):
675            if later_id <= group_id or passed.supplier == later_id or passed.supplier > passing:
676                continue
677            self._remember(later_id, _PassedConfig(config, passing))
678            if passed.config == config:
679                continue
680            kept = self._provisional.get(later_id)
681            if not kept or not isinstance(self._groups.get(later_id), _Group):
682                continue
683            group = self._groups[later_id] = _Group(self._codec, config, kept[0].object_id == 0, self._unconfigured)
684            for video_object in kept:
685                location = Location(later_id, video_object.object_id)
686                pictures.extend(group.decode(video_object.payload, location, None))
687        return self._sampled(pictures)
688
689    def _start(self, group_id: int, held: list[Object]) -> list[DecodedPicture]:
690        """Decodes the group, from its first held object, with the Video Config that object
691        carries, or else the one it inherits, then passes the Video Config it passes on to the
692        groups after it, which may have started before this one arrived, or starts the group after
693        it if that one held its objects."""
694        passed = _PassedConfig(_video_config(held[0].extension_headers), group_id)
695        own = passed.config is not None
696        if not own:
697            passed = self._inherited(group_id)
698        group = self._groups[group_id] = _Group(self._codec, passed.config, held[0].object_id == 0 or own, self._unconfigured)
699        self._remember(group_id, passed)
700        if not own and isinstance(self._groups.get(group_id - 1), _Group):
701            self._provisional[group_id] = []
702        decoded = []
703        for video_object in held:
704            decoded.extend(self._decode(group, video_object))
705        passing = self._configs[group_id].config if group_id in self._configs else group.config
706        decoded.extend(self._reconfigure(group_id, passing))
707        return decoded + self._release(group_id + 1)
708
709    def _release(self, group_id: int) -> list[DecodedPicture]:
710        """Starts the group if it holds its objects, with the Video Config it inherits."""
711        held = self._groups.get(group_id)
712        return self._start(group_id, held) if isinstance(held, list) else []
713
714    def _finish(self, group_id: int) -> list[DecodedPicture]:
715        """Flushes the group, then starts the group after it if that one held its objects."""
716        decoded = self._release(group_id)
717        self._finished.append(group_id)
718        self._provisional.pop(group_id, None)
719        self._provisional.pop(group_id + 1, None)
720        group = self._groups.pop(group_id, None)
721        if group is not None:
722            decoded.extend(self._sampled(cast(_Group, group).flush()))
723        return decoded + self._release(group_id + 1)
724
725
726def follow_pictures(
727    remote: RemoteBroadcast,
728    name: str,
729    codec: str,
730    *,
731    namespace: list[str] | None = None,
732    interval: float = 0.0,
733    on_subscribed: Callable[[], Awaitable[None]] | None = None,
734    config: bytes | None = None,
735) -> "FollowedPictures":
736    """Follow and decode LOC video track `name` across resubscriptions (`from_group_start=True`).
737
738    Runs a fresh `decode_pictures()` per subscription while carrying forward the newest learned Video
739    Config (accessible via `FollowedPictures.config`, falling back to `config`).
740    Raises `ValueError` for unsupported `codec`; reads raise `SessionEnded` or `FFmpegError`.
741    Use with `contextlib.aclosing`.
742    """
743    return FollowedPictures(remote, name, codec, namespace, interval, on_subscribed, config)
744
745
746class FollowedPictures(Following[DecodedPicture]):
747    """What `follow_pictures` returns: the pictures of each subscription, decoded by a
748    `decode_pictures` of its own."""
749
750    def __init__(
751        self,
752        remote: RemoteBroadcast,
753        name: str,
754        codec: str,
755        namespace: list[str] | None,
756        interval: float,
757        on_subscribed: Callable[[], Awaitable[None]] | None,
758        config: bytes | None,
759    ):
760        super().__init__(f"the pictures of {name}")
761        # Raises ValueError for an unknown codec before subscribing.
762        VideoDecoder(codec)
763        self._codec = codec
764        self._interval = interval
765        self._config = config
766        self._subscriptions = remote._subscriptions(
767            name, namespace, on_subscribed, True, None, DEFAULT_DELIVERY_TIMEOUT_SECONDS
768        )
769        # The decoding of the current subscription, and the Largest Location its SUBSCRIBE_OK
770        # reported.
771        self._pictures: Following[DecodedPicture] | None = None
772        self._largest: Location | None = None
773
774    @property
775    def config(self) -> bytes | None:
776        """The Video Config the next subscription starts with: the one the newest object that
777        carried one brought, or else the `config` given."""
778        return self._config
779
780    async def _next(self) -> DecodedPicture:
781        while True:
782            if self._pictures is None:
783                objects = cast(_Objects, await anext(self._subscriptions))
784                if self._closing.started:
785                    # Closed by the `on_subscribed` callback.
786                    raise StopAsyncIteration
787                self._largest = objects._subscription.largest
788                self._pictures = decode_pictures(
789                    _NotedObjects(objects, self), self._codec, interval=self._interval, config=self._config
790                )
791            try:
792                picture = await anext(self._pictures)
793            except StopAsyncIteration:
794                self._pictures = None
795                continue
796            return replace(picture, largest=self._largest)
797
798    async def _release(self) -> None:
799        try:
800            await self._subscriptions.aclose()
801        finally:
802            # The decoders and the pictures they hold, freed once a decoding a cancelled read left
803            # in a worker finished; the Video Config learned stays for `config`.
804            self._pictures = None
805
806
807class _NotedObjects:
808    """The objects of one subscription, noting the Video Config of the newest one carrying one as
809    the one the next subscription starts with. Its groups may start at 0 again, so its locations
810    are not compared with an earlier one's."""
811
812    def __init__(self, objects: Following[Object], pictures: FollowedPictures):
813        self._objects = objects
814        self._pictures = pictures
815        self._newest: tuple[int, int] | None = None
816
817    def __aiter__(self) -> "_NotedObjects":
818        return self
819
820    async def __anext__(self) -> Object:
821        video_object = await anext(self._objects)
822        config = _video_config(video_object.extension_headers)
823        location = (video_object.group_id, video_object.object_id)
824        if config is not None and (self._newest is None or location >= self._newest):
825            self._pictures._config, self._newest = config, location
826        return video_object
827
828
829def _length_prefixed_units(payload: bytes) -> list[bytes] | None:
830    """The NAL units of `payload`, each after a 4-byte length, or None when such lengths do not
831    cover it exactly."""
832    units = []
833    offset = 0
834    while offset < len(payload):
835        length = int.from_bytes(payload[offset : offset + 4], "big")
836        offset += 4
837        if length == 0 or offset + length > len(payload):
838            return None
839        units.append(payload[offset : offset + length])
840        offset += length
841    return units or None
842
843
844def _payload_bytes(video_objects: list[Object]) -> int:
845    return sum(len(video_object.payload) for video_object in video_objects)
846
847
848def _video_config(extension_headers: list[tuple[int, int | bytes]]) -> bytes | None:
849    for header_id, value in extension_headers:
850        if header_id == VIDEO_CONFIG_ID and isinstance(value, bytes):
851            return value
852    return None
853
854
855# ITU-T H.264 Table A-1: level_idc, MaxMBPS (macroblocks/s), MaxFS (macroblocks/frame), MaxBR
856# (Baseline, 1000 bits/s). Level 1b is omitted.
857H264_LEVELS = [
858    (10, 1485, 99, 64),
859    (11, 3000, 396, 192),
860    (12, 6000, 396, 384),
861    (13, 11880, 396, 768),
862    (20, 11880, 396, 2000),
863    (21, 19800, 792, 4000),
864    (22, 20250, 1620, 4000),
865    (30, 40500, 1620, 10000),
866    (31, 108000, 3600, 14000),
867    (32, 216000, 5120, 20000),
868    (40, 245760, 8192, 20000),
869    (41, 245760, 8192, 50000),
870    (42, 522240, 8704, 50000),
871    (50, 589824, 22080, 135000),
872    (51, 983040, 36864, 240000),
873    (52, 2073600, 36864, 240000),
874    (60, 4177920, 139264, 240000),
875    (61, 8355840, 139264, 480000),
876    (62, 16711680, 139264, 800000),
877]
878
879
880def _h264_level(width: int, height: int, framerate: int, bitrate: int | None) -> int:
881    """Returns the lowest level whose limits take this size, framerate and bitrate (A.3.1):
882    macroblocks per frame <= MaxFS, each side <= sqrt(8 MaxFS), macroblocks per second <= MaxMBPS,
883    bitrate <= MaxBR. Returns the highest level when none does."""
884    mb_width, mb_height = -(-width // 16), -(-height // 16)
885    frame_size = mb_width * mb_height
886    for level, max_mbps, max_fs, max_br in H264_LEVELS:
887        fits = frame_size <= max_fs and max(mb_width, mb_height) ** 2 <= 8 * max_fs
888        if fits and frame_size * framerate <= max_mbps and (bitrate is None or bitrate <= max_br * 1000):
889            return level
890    return H264_LEVELS[-1][0]
891
892
893# VideoEncoder.encode's color formats -> (PyAV pixel format, bytes per pixel).
894COLOR_FORMATS = {"RGB": ("rgb24", 3), "RGBA": ("rgba", 4), "BGR": ("bgr24", 3), "BGRA": ("bgra", 4)}
895
896
897def _checked_picture(image: bytes, size: tuple[int, int], color_format: str) -> tuple[bytes, tuple[int, int]]:
898    if color_format not in COLOR_FORMATS:
899        raise ValueError(f"unsupported color format {color_format!r}: use one of {', '.join(COLOR_FORMATS)}")
900    try:
901        width, height = (operator.index(side) for side in size)
902    except (TypeError, ValueError):
903        raise ValueError(f"{size!r} is not a width and a height in pixels") from None
904    try:
905        view = memoryview(image)
906    except TypeError:
907        raise ValueError(f"a {type(image).__name__} is no picture: use bytes") from None
908    if not view.c_contiguous:
909        raise ValueError("a picture's buffer must be contiguous")
910    if width <= 0 or height <= 0 or view.nbytes != width * height * COLOR_FORMATS[color_format][1]:
911        raise ValueError(f"{view.nbytes} bytes are not {width}x{height} pixels in {color_format}")
912    return (image if isinstance(image, bytes) else view.tobytes()), (width, height)
913
914
915class VideoEncoder:
916    """Encodes RGB or BGR pictures into H.264 (Annex B, its parameter sets in every keyframe) or
917    VP8, at `bitrate` bits a second, or the encoder's default quality when it is None. A keyframe
918    comes every two seconds, and on `request_keyframe`. `codec_string` is the WebCodecs codec
919    string; for H.264 it names Constrained Baseline at the level the SPS carries."""
920
921    def __init__(self, codec: str, width: int, height: int, framerate: int, bitrate: int | None = None):
922        if codec == "H264":
923            level = _h264_level(width, height, framerate, bitrate)
924            # x264's baseline sets constraint_set0_flag and constraint_set1_flag: Constrained Baseline.
925            self.codec_string = f"avc1.42C0{level:02X}"
926            self._encoder = av.CodecContext.create("libx264", "w")
927            self._encoder.options = {
928                "preset": "ultrafast",
929                "tune": "zerolatency",
930                "profile": "baseline",
931                "x264-params": f"repeat-headers=1:keyint={2 * framerate}:scenecut=0:level={level}",
932            }
933        elif codec == "VP8":
934            self.codec_string = "vp8"
935            self._encoder = av.CodecContext.create("libvpx", "w")
936            self._encoder.options = {"deadline": "realtime", "lag-in-frames": "0"}
937            self._encoder.gop_size = 2 * framerate
938        else:
939            raise ValueError(f"unsupported video_out_codec {codec!r}: use 'H264' or 'VP8'")
940        self._encoder.width = width
941        self._encoder.height = height
942        self._encoder.pix_fmt = "yuv420p"
943        self._encoder.time_base = Fraction(1, framerate)
944        self._encoder.framerate = Fraction(framerate)
945        if bitrate is not None:
946            self._encoder.bit_rate = bitrate
947        self._encoder.open()
948        self._width = width
949        self._height = height
950        self._frames = 0
951        self._keyframe_requested = False
952
953    def request_keyframe(self) -> None:
954        self._keyframe_requested = True
955
956    def encode(self, image: bytes, size: tuple[int, int], color_format: str) -> list[bytes]:
957        """Returns the packets of `image`, `size` pixels in `color_format` (`RGB`, `RGBA`, `BGR` or
958        `BGRA`, 8 bits per channel), scaled to the encoder's size. Raises ValueError for another
959        format, a `size` that is not two integers, or an `image` that is not a contiguous buffer of
960        exactly that many bytes."""
961        image, (width, height) = _checked_picture(image, size, color_format)
962        pixel_format, channels = COLOR_FORMATS[color_format]
963        picture = av.VideoFrame.from_ndarray(
964            np.frombuffer(image, np.uint8).reshape(height, width, channels), format=pixel_format
965        ).reformat(width=self._width, height=self._height, format="yuv420p")
966        picture.pts = self._frames
967        self._frames += 1
968        if self._keyframe_requested:
969            picture.pict_type = PictureType.I
970            self._keyframe_requested = False
971        return [bytes(packet) for packet in self._encoder.encode(picture)]
logger = <Logger moq_wasm (WARNING)>
OPUS_SAMPLE_RATE = 48000
PCM_LAYOUTS = {1: 'mono', 2: 'stereo'}
OPUS_BITRATE = 32000
END_OF_GROUP_STATUS = 3
VIDEO_CONFIG_ID = 13
MAX_OPEN_GROUPS = 4
FINISHED_GROUPS_KEPT = 16
MAX_HELD_OBJECTS = 5
MAX_HELD_BYTES = 4194304
MAX_REFUSED_OBJECTS = 3
LENGTH_PREFIXED_CODECS = ('avc1', 'avc3', 'hvc1', 'hev1')
START_CODE = b'\x00\x00\x00\x01'
SHORT_START_CODE = b'\x00\x00\x01'
H264_SPS = 7
HEVC_SPS = 33
VIDEO_DECODERS = {'avc1': ('h264',), 'avc3': ('h264',), 'hvc1': ('hevc',), 'hev1': ('hevc',), 'vp8': ('vp8', 'libvpx'), 'vp09': ('vp9', 'libvpx-vp9'), 'av01': ('libdav1d', 'libaom-av1')}
THREADLESS_DECODERS = ('libdav1d',)
class OpusDecoder:
 99class OpusDecoder:
100    """Turns the Opus packets of a LOC audio track into 16-bit PCM at `sample_rate` with `channels`
101    interleaved channels, mono or stereo, mixed from the track's own. Raises ValueError for another
102    channel count."""
103
104    def __init__(self, sample_rate: int, channels: int = 1):
105        self._channels = channels
106        # `kind` types the context as audio, which PyAV 15 does not for
107        # `CodecContext.create("opus")`.
108        self._decoder = av.Codec("opus", "r").create("audio")
109        self._resampler = av.AudioResampler(format="s16", layout=_pcm_layout(channels), rate=sample_rate)
110
111    def decode(self, packet: bytes) -> bytes:
112        return b"".join(
113            bytes(resampled.planes[0])[: resampled.samples * self._channels * 2]
114            for decoded in self._decoder.decode(av.Packet(packet))
115            for resampled in self._resampler.resample(decoded)
116        )

Turns the Opus packets of a LOC audio track into 16-bit PCM at sample_rate with channels interleaved channels, mono or stereo, mixed from the track's own. Raises ValueError for another channel count.

OpusDecoder(sample_rate: int, channels: int = 1)
104    def __init__(self, sample_rate: int, channels: int = 1):
105        self._channels = channels
106        # `kind` types the context as audio, which PyAV 15 does not for
107        # `CodecContext.create("opus")`.
108        self._decoder = av.Codec("opus", "r").create("audio")
109        self._resampler = av.AudioResampler(format="s16", layout=_pcm_layout(channels), rate=sample_rate)
def decode(self, packet: bytes) -> bytes:
111    def decode(self, packet: bytes) -> bytes:
112        return b"".join(
113            bytes(resampled.planes[0])[: resampled.samples * self._channels * 2]
114            for decoded in self._decoder.decode(av.Packet(packet))
115            for resampled in self._resampler.resample(decoded)
116        )
class OpusEncoder:
227class OpusEncoder:
228    """Turns 16-bit PCM at any rate into 20 ms Opus packets at 48 kHz of `channels` channels, mono
229    or stereo, at `bitrate` bits a second. Raises ValueError for another channel count."""
230
231    def __init__(self, bitrate: int = OPUS_BITRATE, channels: int = 1):
232        self._layout = _pcm_layout(channels)
233        self._channels = channels
234        self._encoder = av.CodecContext.create("libopus", "w")
235        self._encoder.sample_rate = OPUS_SAMPLE_RATE
236        self._encoder.layout = self._layout
237        self._encoder.format = "s16"
238        self._encoder.bit_rate = bitrate
239        self._encoder.open()
240        self._resampler = _PcmResampler(OPUS_SAMPLE_RATE, channels)
241        self._fifo = av.AudioFifo()
242        self.frame_samples = self._encoder.frame_size
243
244    def encode(self, pcm: bytes, sample_rate: int, num_channels: int = 1) -> list[bytes]:
245        """Returns the packets `pcm`, 16-bit PCM at `sample_rate` with `num_channels` interleaved
246        channels, downmixed or upmixed to the encoder's, completes; the samples short of a packet
247        wait for the next call. The layout and rate may change from one call to the next. Raises
248        ValueError, taking none of `pcm`, for more than two channels and for a `sample_rate` that is
249        not a positive integer."""
250        self._write(self._resampler.resample(pcm, sample_rate, num_channels))
251        return self._encode_fifo()
252
253    def finish(self) -> list[bytes]:
254        """The packets of the samples the encoder still holds, at the end of a stream: at least the
255        input's duration, the last packet padded with silence. The encoder takes no more PCM after
256        it."""
257        self._write(self._resampler.flush())
258        self._write(bytes(-self._fifo.samples % self.frame_samples * self._channels * 2))
259        packets = self._encode_fifo()
260        packets.extend(bytes(packet) for packet in self._encoder.encode(None))
261        return packets
262
263    @property
264    def held_micros(self) -> float:
265        """Microseconds of the PCM taken that no packet returned yet carries: the samples short of
266        a packet and those the resampler holds back."""
267        return (self._fifo.samples + self._resampler.held_samples) * 1_000_000 / OPUS_SAMPLE_RATE
268
269    def _write(self, pcm: bytes) -> None:
270        """Writes 48 kHz PCM of the encoder's channels into the FIFO."""
271        if not pcm:
272            return
273        frame = av.AudioFrame.from_ndarray(
274            np.frombuffer(pcm, np.int16).reshape(1, -1), format="s16", layout=self._layout
275        )
276        frame.sample_rate = OPUS_SAMPLE_RATE
277        self._fifo.write(frame)
278
279    def _encode_fifo(self) -> list[bytes]:
280        packets = []
281        while (chunk := self._fifo.read(self.frame_samples)) is not None:
282            chunk.pts = None
283            packets.extend(bytes(packet) for packet in self._encoder.encode(chunk))
284        return packets

Turns 16-bit PCM at any rate into 20 ms Opus packets at 48 kHz of channels channels, mono or stereo, at bitrate bits a second. Raises ValueError for another channel count.

OpusEncoder(bitrate: int = 32000, channels: int = 1)
231    def __init__(self, bitrate: int = OPUS_BITRATE, channels: int = 1):
232        self._layout = _pcm_layout(channels)
233        self._channels = channels
234        self._encoder = av.CodecContext.create("libopus", "w")
235        self._encoder.sample_rate = OPUS_SAMPLE_RATE
236        self._encoder.layout = self._layout
237        self._encoder.format = "s16"
238        self._encoder.bit_rate = bitrate
239        self._encoder.open()
240        self._resampler = _PcmResampler(OPUS_SAMPLE_RATE, channels)
241        self._fifo = av.AudioFifo()
242        self.frame_samples = self._encoder.frame_size
frame_samples
def encode(self, pcm: bytes, sample_rate: int, num_channels: int = 1) -> list[bytes]:
244    def encode(self, pcm: bytes, sample_rate: int, num_channels: int = 1) -> list[bytes]:
245        """Returns the packets `pcm`, 16-bit PCM at `sample_rate` with `num_channels` interleaved
246        channels, downmixed or upmixed to the encoder's, completes; the samples short of a packet
247        wait for the next call. The layout and rate may change from one call to the next. Raises
248        ValueError, taking none of `pcm`, for more than two channels and for a `sample_rate` that is
249        not a positive integer."""
250        self._write(self._resampler.resample(pcm, sample_rate, num_channels))
251        return self._encode_fifo()

Returns the packets pcm, 16-bit PCM at sample_rate with num_channels interleaved channels, downmixed or upmixed to the encoder's, completes; the samples short of a packet wait for the next call. The layout and rate may change from one call to the next. Raises ValueError, taking none of pcm, for more than two channels and for a sample_rate that is not a positive integer.

def finish(self) -> list[bytes]:
253    def finish(self) -> list[bytes]:
254        """The packets of the samples the encoder still holds, at the end of a stream: at least the
255        input's duration, the last packet padded with silence. The encoder takes no more PCM after
256        it."""
257        self._write(self._resampler.flush())
258        self._write(bytes(-self._fifo.samples % self.frame_samples * self._channels * 2))
259        packets = self._encode_fifo()
260        packets.extend(bytes(packet) for packet in self._encoder.encode(None))
261        return packets

The packets of the samples the encoder still holds, at the end of a stream: at least the input's duration, the last packet padded with silence. The encoder takes no more PCM after it.

held_micros: float
263    @property
264    def held_micros(self) -> float:
265        """Microseconds of the PCM taken that no packet returned yet carries: the samples short of
266        a packet and those the resampler holds back."""
267        return (self._fifo.samples + self._resampler.held_samples) * 1_000_000 / OPUS_SAMPLE_RATE

Microseconds of the PCM taken that no packet returned yet carries: the samples short of a packet and those the resampler holds back.

class VideoDecoder:
287class VideoDecoder:
288    """Decodes one LOC video group into pictures (create one per group; mid-group joins yield nothing).
289
290    With B-frames, frames may be delayed and finalized by `flush()`, each paired with its input `Location`.
291    `config` is the LOC Video Config extradata (e.g. H.264 `avcC` / H.265 `hvcC`).
292    """
293
294    def __init__(self, codec: str, config: bytes | None = None):
295        name = _decoder_name(codec)
296        if name is None:
297            raise ValueError(f"no decoder for video codec {codec}")
298        self._decoder = cast(av.VideoCodecContext, av.CodecContext.create(name, "r"))
299        if name in THREADLESS_DECODERS:
300            self._decoder.thread_count = 1
301        if config is not None:
302            self._decoder.extradata = config
303        # Each packet carries the Location of its object through the decoder to the pictures it
304        # makes, so a packet that makes none, as an invisible VP8 frame, leaves nothing behind.
305        self._decoder.copy_opaque = True
306        self._next_pts = 0
307
308    def decode(self, payload: bytes, location: Location | None = None) -> list[tuple[av.VideoFrame, Location | None]]:
309        """The pictures the object completes, in presentation order, each with the `location` of
310        the object it was decoded from; none for an object the decoder refuses."""
311        try:
312            return self._decode(payload, location)
313        except FFmpegError:
314            return []
315
316    def _decode(self, payload: bytes, location: Location | None) -> list[tuple[av.VideoFrame, Location | None]]:
317        """`decode`, raising the FFmpegError of an object the decoder refuses."""
318        packet = av.Packet(payload)
319        packet.pts = self._next_pts
320        packet.opaque = location
321        self._next_pts += 1
322        return self._located(self._decoder.decode(packet))
323
324    def flush(self) -> list[tuple[av.VideoFrame, Location | None]]:
325        """The pictures the decoder still holds, at the end of the group."""
326        try:
327            return self._located(self._decoder.decode(None))
328        except FFmpegError:
329            return []
330
331    def _located(self, pictures: list[av.VideoFrame]) -> list[tuple[av.VideoFrame, Location | None]]:
332        return [(picture, cast(Location | None, picture.opaque)) for picture in pictures if picture.pts is not None]

Decodes one LOC video group into pictures (create one per group; mid-group joins yield nothing).

With B-frames, frames may be delayed and finalized by flush(), each paired with its input Location. config is the LOC Video Config extradata (e.g. H.264 avcC / H.265 hvcC).

VideoDecoder(codec: str, config: bytes | None = None)
294    def __init__(self, codec: str, config: bytes | None = None):
295        name = _decoder_name(codec)
296        if name is None:
297            raise ValueError(f"no decoder for video codec {codec}")
298        self._decoder = cast(av.VideoCodecContext, av.CodecContext.create(name, "r"))
299        if name in THREADLESS_DECODERS:
300            self._decoder.thread_count = 1
301        if config is not None:
302            self._decoder.extradata = config
303        # Each packet carries the Location of its object through the decoder to the pictures it
304        # makes, so a packet that makes none, as an invisible VP8 frame, leaves nothing behind.
305        self._decoder.copy_opaque = True
306        self._next_pts = 0
def decode( self, payload: bytes, location: moq_wasm.Location | None = None) -> list[tuple[av.video.frame.VideoFrame, moq_wasm.Location | None]]:
308    def decode(self, payload: bytes, location: Location | None = None) -> list[tuple[av.VideoFrame, Location | None]]:
309        """The pictures the object completes, in presentation order, each with the `location` of
310        the object it was decoded from; none for an object the decoder refuses."""
311        try:
312            return self._decode(payload, location)
313        except FFmpegError:
314            return []

The pictures the object completes, in presentation order, each with the location of the object it was decoded from; none for an object the decoder refuses.

def flush(self) -> list[tuple[av.video.frame.VideoFrame, moq_wasm.Location | None]]:
324    def flush(self) -> list[tuple[av.VideoFrame, Location | None]]:
325        """The pictures the decoder still holds, at the end of the group."""
326        try:
327            return self._located(self._decoder.decode(None))
328        except FFmpegError:
329            return []

The pictures the decoder still holds, at the end of the group.

@dataclass(frozen=True)
class DecodedPicture:
439@dataclass(frozen=True)
440class DecodedPicture:
441    picture: av.VideoFrame
442    location: Location
443    """The Location of the object the picture was decoded from."""
444    decoded_at: float
445    """`time.monotonic()` when it was decoded."""
446    largest: Location | None = None
447    """For a picture `follow_pictures` decoded, the Largest Location the SUBSCRIBE_OK of its
448    subscription reported: the pictures before it were replayed from what the relay held, older
449    than the subscription. None from `decode_pictures`, and for a track that had no object when it
450    was subscribed to."""
DecodedPicture( picture: av.video.frame.VideoFrame, location: moq_wasm.Location, decoded_at: float, largest: moq_wasm.Location | None = None)
picture: av.video.frame.VideoFrame
location: moq_wasm.Location

The Location of the object the picture was decoded from.

decoded_at: float

time.monotonic() when it was decoded.

largest: moq_wasm.Location | None = None

For a picture follow_pictures decoded, the Largest Location the SUBSCRIBE_OK of its subscription reported: the pictures before it were replayed from what the relay held, older than the subscription. None from decode_pictures, and for a track that had no object when it was subscribed to.

def decode_pictures( objects: AsyncIterable[moq_wasm.Object], codec: str, *, interval: float = 0.0, config: bytes | None = None) -> moq_wasm._following.Following[DecodedPicture]:
453def decode_pictures(
454    objects: AsyncIterable[Object], codec: str, *, interval: float = 0.0, config: bytes | None = None
455) -> Following[DecodedPicture]:
456    """Decode a single LOC video subscription in a worker thread, yielding pictures in presentation order
457    within each group (throttled to at most one every `interval` seconds; overlapping subgroups or
458    config-change re-decodes can interleave or repeat across groups). Use `follow_pictures()` across resubscriptions.
459
460    - **Config**: groups inherit the previous group's LOC Video Config (holding up to `MAX_HELD_OBJECTS` /
461      `MAX_HELD_BYTES` while waiting for an out-of-order predecessor, falling back to `config`, e.g.
462      `Catalog.init_data`) and re-decode if a provisional config changes. Length-prefixed H.264/H.265
463      frames arriving before parameter sets or a config are skipped with one warning.
464    - **Errors**: raises `ValueError` immediately for unsupported `codec`, and `av.error.FFmpegError` on
465      read if a keyframe-joined group fails to decode.
466    - **Lifecycle**: each group gets its own `VideoDecoder` (flushed on End-of-Group, after
467      `MAX_OPEN_GROUPS` newer groups, or at EOF). Does not close `objects`; timing out a read can cancel
468      an async generator (use `Subscription`, `RemoteBroadcast.subscriptions()`, or `follow_pictures()`
469      with timeouts). `aclose()` stops reads immediately and frees decoders once any in-flight worker step finishes.
470    """
471    return _DecodedPictures(objects, codec, interval, config)

Decode a single LOC video subscription in a worker thread, yielding pictures in presentation order within each group (throttled to at most one every interval seconds; overlapping subgroups or config-change re-decodes can interleave or repeat across groups). Use follow_pictures() across resubscriptions.

  • Config: groups inherit the previous group's LOC Video Config (holding up to MAX_HELD_OBJECTS / MAX_HELD_BYTES while waiting for an out-of-order predecessor, falling back to config, e.g. Catalog.init_data) and re-decode if a provisional config changes. Length-prefixed H.264/H.265 frames arriving before parameter sets or a config are skipped with one warning.
  • Errors: raises ValueError immediately for unsupported codec, and av.error.FFmpegError on read if a keyframe-joined group fails to decode.
  • Lifecycle: each group gets its own VideoDecoder (flushed on End-of-Group, after MAX_OPEN_GROUPS newer groups, or at EOF). Does not close objects; timing out a read can cancel an async generator (use Subscription, RemoteBroadcast.subscriptions(), or follow_pictures() with timeouts). aclose() stops reads immediately and frees decoders once any in-flight worker step finishes.
def follow_pictures( remote: moq_wasm.media.RemoteBroadcast, name: str, codec: str, *, namespace: list[str] | None = None, interval: float = 0.0, on_subscribed: Callable[[], Awaitable[None]] | None = None, config: bytes | None = None) -> FollowedPictures:
727def follow_pictures(
728    remote: RemoteBroadcast,
729    name: str,
730    codec: str,
731    *,
732    namespace: list[str] | None = None,
733    interval: float = 0.0,
734    on_subscribed: Callable[[], Awaitable[None]] | None = None,
735    config: bytes | None = None,
736) -> "FollowedPictures":
737    """Follow and decode LOC video track `name` across resubscriptions (`from_group_start=True`).
738
739    Runs a fresh `decode_pictures()` per subscription while carrying forward the newest learned Video
740    Config (accessible via `FollowedPictures.config`, falling back to `config`).
741    Raises `ValueError` for unsupported `codec`; reads raise `SessionEnded` or `FFmpegError`.
742    Use with `contextlib.aclosing`.
743    """
744    return FollowedPictures(remote, name, codec, namespace, interval, on_subscribed, config)

Follow and decode LOC video track name across resubscriptions (from_group_start=True).

Runs a fresh decode_pictures() per subscription while carrying forward the newest learned Video Config (accessible via FollowedPictures.config, falling back to config). Raises ValueError for unsupported codec; reads raise SessionEnded or FFmpegError. Use with contextlib.aclosing.

class FollowedPictures(moq_wasm._following.Following[moq_wasm.codecs.DecodedPicture]):
747class FollowedPictures(Following[DecodedPicture]):
748    """What `follow_pictures` returns: the pictures of each subscription, decoded by a
749    `decode_pictures` of its own."""
750
751    def __init__(
752        self,
753        remote: RemoteBroadcast,
754        name: str,
755        codec: str,
756        namespace: list[str] | None,
757        interval: float,
758        on_subscribed: Callable[[], Awaitable[None]] | None,
759        config: bytes | None,
760    ):
761        super().__init__(f"the pictures of {name}")
762        # Raises ValueError for an unknown codec before subscribing.
763        VideoDecoder(codec)
764        self._codec = codec
765        self._interval = interval
766        self._config = config
767        self._subscriptions = remote._subscriptions(
768            name, namespace, on_subscribed, True, None, DEFAULT_DELIVERY_TIMEOUT_SECONDS
769        )
770        # The decoding of the current subscription, and the Largest Location its SUBSCRIBE_OK
771        # reported.
772        self._pictures: Following[DecodedPicture] | None = None
773        self._largest: Location | None = None
774
775    @property
776    def config(self) -> bytes | None:
777        """The Video Config the next subscription starts with: the one the newest object that
778        carried one brought, or else the `config` given."""
779        return self._config
780
781    async def _next(self) -> DecodedPicture:
782        while True:
783            if self._pictures is None:
784                objects = cast(_Objects, await anext(self._subscriptions))
785                if self._closing.started:
786                    # Closed by the `on_subscribed` callback.
787                    raise StopAsyncIteration
788                self._largest = objects._subscription.largest
789                self._pictures = decode_pictures(
790                    _NotedObjects(objects, self), self._codec, interval=self._interval, config=self._config
791                )
792            try:
793                picture = await anext(self._pictures)
794            except StopAsyncIteration:
795                self._pictures = None
796                continue
797            return replace(picture, largest=self._largest)
798
799    async def _release(self) -> None:
800        try:
801            await self._subscriptions.aclose()
802        finally:
803            # The decoders and the pictures they hold, freed once a decoding a cancelled read left
804            # in a worker finished; the Video Config learned stays for `config`.
805            self._pictures = None

What follow_pictures returns: the pictures of each subscription, decoded by a decode_pictures of its own.

FollowedPictures( remote: moq_wasm.media.RemoteBroadcast, name: str, codec: str, namespace: list[str] | None, interval: float, on_subscribed: Callable[[], Awaitable[None]] | None, config: bytes | None)
751    def __init__(
752        self,
753        remote: RemoteBroadcast,
754        name: str,
755        codec: str,
756        namespace: list[str] | None,
757        interval: float,
758        on_subscribed: Callable[[], Awaitable[None]] | None,
759        config: bytes | None,
760    ):
761        super().__init__(f"the pictures of {name}")
762        # Raises ValueError for an unknown codec before subscribing.
763        VideoDecoder(codec)
764        self._codec = codec
765        self._interval = interval
766        self._config = config
767        self._subscriptions = remote._subscriptions(
768            name, namespace, on_subscribed, True, None, DEFAULT_DELIVERY_TIMEOUT_SECONDS
769        )
770        # The decoding of the current subscription, and the Largest Location its SUBSCRIBE_OK
771        # reported.
772        self._pictures: Following[DecodedPicture] | None = None
773        self._largest: Location | None = None
config: bytes | None
775    @property
776    def config(self) -> bytes | None:
777        """The Video Config the next subscription starts with: the one the newest object that
778        carried one brought, or else the `config` given."""
779        return self._config

The Video Config the next subscription starts with: the one the newest object that carried one brought, or else the config given.

H264_LEVELS = [(10, 1485, 99, 64), (11, 3000, 396, 192), (12, 6000, 396, 384), (13, 11880, 396, 768), (20, 11880, 396, 2000), (21, 19800, 792, 4000), (22, 20250, 1620, 4000), (30, 40500, 1620, 10000), (31, 108000, 3600, 14000), (32, 216000, 5120, 20000), (40, 245760, 8192, 20000), (41, 245760, 8192, 50000), (42, 522240, 8704, 50000), (50, 589824, 22080, 135000), (51, 983040, 36864, 240000), (52, 2073600, 36864, 240000), (60, 4177920, 139264, 240000), (61, 8355840, 139264, 480000), (62, 16711680, 139264, 800000)]
COLOR_FORMATS = {'RGB': ('rgb24', 3), 'RGBA': ('rgba', 4), 'BGR': ('bgr24', 3), 'BGRA': ('bgra', 4)}
class VideoEncoder:
916class VideoEncoder:
917    """Encodes RGB or BGR pictures into H.264 (Annex B, its parameter sets in every keyframe) or
918    VP8, at `bitrate` bits a second, or the encoder's default quality when it is None. A keyframe
919    comes every two seconds, and on `request_keyframe`. `codec_string` is the WebCodecs codec
920    string; for H.264 it names Constrained Baseline at the level the SPS carries."""
921
922    def __init__(self, codec: str, width: int, height: int, framerate: int, bitrate: int | None = None):
923        if codec == "H264":
924            level = _h264_level(width, height, framerate, bitrate)
925            # x264's baseline sets constraint_set0_flag and constraint_set1_flag: Constrained Baseline.
926            self.codec_string = f"avc1.42C0{level:02X}"
927            self._encoder = av.CodecContext.create("libx264", "w")
928            self._encoder.options = {
929                "preset": "ultrafast",
930                "tune": "zerolatency",
931                "profile": "baseline",
932                "x264-params": f"repeat-headers=1:keyint={2 * framerate}:scenecut=0:level={level}",
933            }
934        elif codec == "VP8":
935            self.codec_string = "vp8"
936            self._encoder = av.CodecContext.create("libvpx", "w")
937            self._encoder.options = {"deadline": "realtime", "lag-in-frames": "0"}
938            self._encoder.gop_size = 2 * framerate
939        else:
940            raise ValueError(f"unsupported video_out_codec {codec!r}: use 'H264' or 'VP8'")
941        self._encoder.width = width
942        self._encoder.height = height
943        self._encoder.pix_fmt = "yuv420p"
944        self._encoder.time_base = Fraction(1, framerate)
945        self._encoder.framerate = Fraction(framerate)
946        if bitrate is not None:
947            self._encoder.bit_rate = bitrate
948        self._encoder.open()
949        self._width = width
950        self._height = height
951        self._frames = 0
952        self._keyframe_requested = False
953
954    def request_keyframe(self) -> None:
955        self._keyframe_requested = True
956
957    def encode(self, image: bytes, size: tuple[int, int], color_format: str) -> list[bytes]:
958        """Returns the packets of `image`, `size` pixels in `color_format` (`RGB`, `RGBA`, `BGR` or
959        `BGRA`, 8 bits per channel), scaled to the encoder's size. Raises ValueError for another
960        format, a `size` that is not two integers, or an `image` that is not a contiguous buffer of
961        exactly that many bytes."""
962        image, (width, height) = _checked_picture(image, size, color_format)
963        pixel_format, channels = COLOR_FORMATS[color_format]
964        picture = av.VideoFrame.from_ndarray(
965            np.frombuffer(image, np.uint8).reshape(height, width, channels), format=pixel_format
966        ).reformat(width=self._width, height=self._height, format="yuv420p")
967        picture.pts = self._frames
968        self._frames += 1
969        if self._keyframe_requested:
970            picture.pict_type = PictureType.I
971            self._keyframe_requested = False
972        return [bytes(packet) for packet in self._encoder.encode(picture)]

Encodes RGB or BGR pictures into H.264 (Annex B, its parameter sets in every keyframe) or VP8, at bitrate bits a second, or the encoder's default quality when it is None. A keyframe comes every two seconds, and on request_keyframe. codec_string is the WebCodecs codec string; for H.264 it names Constrained Baseline at the level the SPS carries.

VideoEncoder( codec: str, width: int, height: int, framerate: int, bitrate: int | None = None)
922    def __init__(self, codec: str, width: int, height: int, framerate: int, bitrate: int | None = None):
923        if codec == "H264":
924            level = _h264_level(width, height, framerate, bitrate)
925            # x264's baseline sets constraint_set0_flag and constraint_set1_flag: Constrained Baseline.
926            self.codec_string = f"avc1.42C0{level:02X}"
927            self._encoder = av.CodecContext.create("libx264", "w")
928            self._encoder.options = {
929                "preset": "ultrafast",
930                "tune": "zerolatency",
931                "profile": "baseline",
932                "x264-params": f"repeat-headers=1:keyint={2 * framerate}:scenecut=0:level={level}",
933            }
934        elif codec == "VP8":
935            self.codec_string = "vp8"
936            self._encoder = av.CodecContext.create("libvpx", "w")
937            self._encoder.options = {"deadline": "realtime", "lag-in-frames": "0"}
938            self._encoder.gop_size = 2 * framerate
939        else:
940            raise ValueError(f"unsupported video_out_codec {codec!r}: use 'H264' or 'VP8'")
941        self._encoder.width = width
942        self._encoder.height = height
943        self._encoder.pix_fmt = "yuv420p"
944        self._encoder.time_base = Fraction(1, framerate)
945        self._encoder.framerate = Fraction(framerate)
946        if bitrate is not None:
947            self._encoder.bit_rate = bitrate
948        self._encoder.open()
949        self._width = width
950        self._height = height
951        self._frames = 0
952        self._keyframe_requested = False
def request_keyframe(self) -> None:
954    def request_keyframe(self) -> None:
955        self._keyframe_requested = True
def encode( self, image: bytes, size: tuple[int, int], color_format: str) -> list[bytes]:
957    def encode(self, image: bytes, size: tuple[int, int], color_format: str) -> list[bytes]:
958        """Returns the packets of `image`, `size` pixels in `color_format` (`RGB`, `RGBA`, `BGR` or
959        `BGRA`, 8 bits per channel), scaled to the encoder's size. Raises ValueError for another
960        format, a `size` that is not two integers, or an `image` that is not a contiguous buffer of
961        exactly that many bytes."""
962        image, (width, height) = _checked_picture(image, size, color_format)
963        pixel_format, channels = COLOR_FORMATS[color_format]
964        picture = av.VideoFrame.from_ndarray(
965            np.frombuffer(image, np.uint8).reshape(height, width, channels), format=pixel_format
966        ).reformat(width=self._width, height=self._height, format="yuv420p")
967        picture.pts = self._frames
968        self._frames += 1
969        if self._keyframe_requested:
970            picture.pict_type = PictureType.I
971            self._keyframe_requested = False
972        return [bytes(packet) for packet in self._encoder.encode(picture)]

Returns the packets of image, size pixels in color_format (RGB, RGBA, BGR or BGRA, 8 bits per channel), scaled to the encoder's size. Raises ValueError for another format, a size that is not two integers, or an image that is not a contiguous buffer of exactly that many bytes.