moq_wasm.pipecat

A pipecat transport on a moq_wasm.Session, in place of pipecat's MOQTransport (docs/architecture/python/sdk.md "pipecat"). Needs the pipecat extra: moq-wasm[pipecat].

 1"""A pipecat transport on a `moq_wasm.Session`, in place of pipecat's `MOQTransport`
 2(docs/architecture/python/sdk.md "pipecat"). Needs the `pipecat` extra: `moq-wasm[pipecat]`."""
 3
 4from moq_wasm.pipecat._participant import MoqWasmTrack, MoqWasmTrackMessage
 5from moq_wasm.pipecat._room import MoqWasmEventRecord, MoqWasmTrackObject
 6from moq_wasm.pipecat._transport import (
 7    MoqWasmInputParams,
 8    MoqWasmInputTransport,
 9    MoqWasmOutputTransport,
10    MoqWasmParams,
11    MoqWasmParticipantInput,
12    MoqWasmTransport,
13)
14
15__all__ = [
16    "MoqWasmInputParams",
17    "MoqWasmInputTransport",
18    "MoqWasmOutputTransport",
19    "MoqWasmParams",
20    "MoqWasmParticipantInput",
21    "MoqWasmEventRecord",
22    "MoqWasmTrack",
23    "MoqWasmTrackMessage",
24    "MoqWasmTrackObject",
25    "MoqWasmTransport",
26]
class MoqWasmInputParams(pipecat.transports.base_transport.TransportParams):
68class MoqWasmInputParams(TransportParams):
69    """`TransportParams` configuring how participant broadcasts are received.
70
71    - **Video sources**: `"camera"` uses `video_in_track` (default: lowest-bitrate decodable LOC video);
72      other source names match that track name directly. `video_in_enabled` subscribes to `video_in_sources`
73      on join; other sources subscribe on demand (`capture_participant_video` / `UserImageRequestFrame`).
74    - **Audio channels**: `audio_in_channels` (`1` default, or `2`). Keep `1` when using Pipecat's stock
75      VAD/turn analyzers (Silero, Smart Turn), which expect mono PCM.
76    - **Sample rate**: leave `audio_in_sample_rate` unset and configure `PipelineParams(audio_in_sample_rate=...)`
77      so inputs match the pipeline's analyzers (a mismatch causes analyzers to misread audio, e.g. 8 kHz in a
78      16 kHz pipeline yields no speech).
79
80    Parameters:
81        video_in_track: Selector for each participant's `"camera"` track (errors go to `on_error` / `ErrorFrame`
82            without dropping the active track).
83        data_in_tracks: Participant data track names emitted as `InputTransportMessageFrame(MoqWasmTrackMessage)`.
84    """
85
86    video_in_track: Callable[[Catalog], CatalogTrack | None] | None = None
87    data_in_tracks: list[str] = []

TransportParams configuring how participant broadcasts are received.

  • Video sources: "camera" uses video_in_track (default: lowest-bitrate decodable LOC video); other source names match that track name directly. video_in_enabled subscribes to video_in_sources on join; other sources subscribe on demand (capture_participant_video / UserImageRequestFrame).
  • Audio channels: audio_in_channels (1 default, or 2). Keep 1 when using Pipecat's stock VAD/turn analyzers (Silero, Smart Turn), which expect mono PCM.
  • Sample rate: leave audio_in_sample_rate unset and configure PipelineParams(audio_in_sample_rate=...) so inputs match the pipeline's analyzers (a mismatch causes analyzers to misread audio, e.g. 8 kHz in a 16 kHz pipeline yields no speech).

Parameters: video_in_track: Selector for each participant's "camera" track (errors go to on_error / ErrorFrame without dropping the active track). data_in_tracks: Participant data track names emitted as InputTransportMessageFrame(MoqWasmTrackMessage).

video_in_track: Callable[[moq_wasm.media.Catalog], moq_wasm.media.CatalogTrack | None] | None = None
data_in_tracks: list[str] = []
class MoqWasmInputTransport(moq_wasm.pipecat._transport._ReceivingInput):
261class MoqWasmInputTransport(_ReceivingInput):
262    """The input of `MoqWasmTransport`: every participant of its room. With
263    `audio_in_stream_on_start` False when it starts, no participant's audio is subscribed to until
264    an `InputTransportStartAudioStreamingFrame`. It serves one pipeline run: the next pipeline
265    takes a new input from `MoqWasmTransport.input`."""
266
267    def __init__(self, room: Room, params: MoqWasmParams, **kwargs):
268        super().__init__(params, **kwargs)
269        self._room = room
270        # The leaving of the room for an EndFrame, before the frame is passed on or in `stop`.
271        self._leaving_at_end: Once[None] = Once()
272
273    async def start(self, frame: StartFrame):
274        await super().start(frame)
275        if self.ran:
276            return
277        if self._params.audio_in_stream_on_start:
278            await self._room.start_audio()
279        if await _open_room(self, self._room):
280            await self.set_transport_ready(frame)
281
282    async def process_frame(self, frame: Frame, direction: FrameDirection):
283        if isinstance(frame, EndFrame):
284            # pipecat's input passes an EndFrame on before it stops, and the pipeline ends once
285            # the frame came out of it: the room is left first, so the failure of a withdrawal this
286            # input makes, as the room's last processor, goes upstream while the pipeline runs.
287            await self._leave_at_end()
288        await super().process_frame(frame, direction)
289
290    async def stop(self, frame: EndFrame):
291        await super().stop(frame)
292        await self._leave_at_end()
293
294    async def _leave_at_end(self) -> None:
295        await self._leaving_at_end.run(lambda: _leave_room(self, self._room))
296
297    async def cancel(self, frame: CancelFrame):
298        await super().cancel(frame)
299        await _leave_room(self, self._room)
300
301    async def cleanup(self):
302        # pipecat cleans up every processor, also one that no EndFrame or CancelFrame reached; the
303        # room is left even when pipecat's cleanup fails.
304        try:
305            await super().cleanup()
306        finally:
307            await self._room.stop(self)
308
309    async def _start_audio_in_streaming(self):
310        await self._room.start_audio()
311
312    async def request_image(self, request: UserImageRequestFrame) -> None:
313        await self._room.request_image(request)

The input of MoqWasmTransport: every participant of its room. With audio_in_stream_on_start False when it starts, no participant's audio is subscribed to until an InputTransportStartAudioStreamingFrame. It serves one pipeline run: the next pipeline takes a new input from MoqWasmTransport.input.

MoqWasmInputTransport( room: moq_wasm.pipecat._room.Room, params: MoqWasmParams, **kwargs)
267    def __init__(self, room: Room, params: MoqWasmParams, **kwargs):
268        super().__init__(params, **kwargs)
269        self._room = room
270        # The leaving of the room for an EndFrame, before the frame is passed on or in `stop`.
271        self._leaving_at_end: Once[None] = Once()

Initialize the base input transport.

Args: params: Transport configuration parameters. **kwargs: Additional arguments passed to parent class.

async def start(self, frame: pipecat.frames.frames.StartFrame):
273    async def start(self, frame: StartFrame):
274        await super().start(frame)
275        if self.ran:
276            return
277        if self._params.audio_in_stream_on_start:
278            await self._room.start_audio()
279        if await _open_room(self, self._room):
280            await self.set_transport_ready(frame)

Start the input transport and initialize components.

Args: frame: The start frame containing initialization parameters.

async def process_frame( self, frame: pipecat.frames.frames.Frame, direction: pipecat.processors.frame_processor.FrameDirection):
282    async def process_frame(self, frame: Frame, direction: FrameDirection):
283        if isinstance(frame, EndFrame):
284            # pipecat's input passes an EndFrame on before it stops, and the pipeline ends once
285            # the frame came out of it: the room is left first, so the failure of a withdrawal this
286            # input makes, as the room's last processor, goes upstream while the pipeline runs.
287            await self._leave_at_end()
288        await super().process_frame(frame, direction)

Process a frame.

Args: frame: The frame to process. direction: The direction of frame flow.

async def stop(self, frame: pipecat.frames.frames.EndFrame):
290    async def stop(self, frame: EndFrame):
291        await super().stop(frame)
292        await self._leave_at_end()

Stop the input transport and cleanup resources.

Args: frame: The end frame signaling transport shutdown.

async def cancel(self, frame: pipecat.frames.frames.CancelFrame):
297    async def cancel(self, frame: CancelFrame):
298        await super().cancel(frame)
299        await _leave_room(self, self._room)

Cancel the input transport and stop all processing.

Args: frame: The cancel frame signaling immediate cancellation.

async def cleanup(self):
301    async def cleanup(self):
302        # pipecat cleans up every processor, also one that no EndFrame or CancelFrame reached; the
303        # room is left even when pipecat's cleanup fails.
304        try:
305            await super().cleanup()
306        finally:
307            await self._room.stop(self)

Release input transport resources at teardown.

async def request_image(self, request: pipecat.frames.frames.UserImageRequestFrame) -> None:
312    async def request_image(self, request: UserImageRequestFrame) -> None:
313        await self._room.request_image(request)
class MoqWasmOutputTransport(moq_wasm.pipecat._transport._OneRun, pipecat.transports.base_output.BaseOutputTransport):
446class MoqWasmOutputTransport(_OneRun, BaseOutputTransport):
447    """Publishes audio (Opus), video (`video_out_codec`), and immediate `MoqWasmTrackObject` / `MoqWasmEventRecord`
448    messages in frame order (not paced to queued audio or `pts`, which only times downstream forwarding; messages
449    stay written even if a later interruption drops the frame).
450
451    Single-use per pipeline run; obtain a fresh instance from `MoqWasmTransport.output()` for each pipeline.
452    Permanent media failure emits a permanent `ErrorFrame` when no data/timeline tracks are configured.
453    """
454
455    def __init__(self, room: Room, params: MoqWasmParams, **kwargs):
456        super().__init__(params, **kwargs)
457        self._room = room
458        # Whether media is all the output writes, so that it can do nothing once publishing it
459        # failed.
460        self._media_only = not (params.data_out_tracks or params.event_timelines_out)
461        # Set up with the output's sample rate, which pipecat sets in `setup`.
462        self._audio_in: _AudioNormalizer | None = None
463
464    def _audio_filter(self) -> BaseAudioFilter | None:
465        return self._params.audio_out_filter
466
467    async def setup(self, setup: FrameProcessorSetup):
468        await super().setup(setup)
469        self._audio_in = _AudioNormalizer(self.sample_rate, self._params.audio_out_channels)
470
471    async def start(self, frame: StartFrame):
472        await super().start(frame)
473        if self.ran:
474            return
475        await self._end_stopped_senders()
476        # A sample rate under 100 Hz has no sample in 10 ms: an audio sender would cut empty chunks
477        # forever, so the output can write nothing.
478        if self._params.audio_out_enabled and self.audio_chunk_size <= 0:
479            error = ValueError(f"{self.sample_rate} Hz audio has no sample in 10 ms")
480            await self.push_error(f"cannot write audio: {error}", error, force_treat_as_permanent=True)
481            return
482        if await _open_room(self, self._room):
483            await self.set_transport_ready(frame)
484
485    async def set_transport_ready(self, frame: StartFrame):
486        # pipecat's, with the output's own media sender; the transport refuses output destinations,
487        # so the default one is all it starts.
488        self._media_senders[None] = sender = _MediaSender(
489            self,
490            destination=None,
491            sample_rate=self.sample_rate,
492            audio_chunk_size=self.audio_chunk_size,
493            params=self._params,
494        )
495        await sender.start(frame)
496        await self.push_frame(OutputTransportReadyFrame(), FrameDirection.UPSTREAM)
497
498    async def _end_stopped_senders(self) -> None:
499        """Ends the media senders a `StopFrame` left running: pipecat keeps a stopped processor
500        running, and `set_transport_ready` starts new senders in their place at the next
501        `StartFrame`. The audio queued before the `StopFrame` was written as it went through."""
502        senders = list(self._media_senders.values())
503        self._media_senders.clear()
504        for sender in senders:
505            await sender.cleanup()
506
507    async def stop(self, frame: EndFrame):
508        # pipecat writes the audio queued before the EndFrame, in chunks of `audio_out_10ms_chunks`;
509        # the speech's last chunk, short of one, is queued ahead of it, padded with silence, as
510        # pipecat does at a TTSStoppedFrame. The audio task writes the speech's last packet after
511        # it.
512        try:
513            try:
514                if self._params.audio_out_enabled:
515                    for sender in self._media_senders.values():
516                        await sender._enqueue_flushed_audio_buffer()
517            finally:
518                await super().stop(frame)
519        except Exception as error:
520            await self._report_write_failure(f"cannot write the end of the speech: {error}", error)
521        finally:
522            await _leave_room(self, self._room)
523
524    async def cancel(self, frame: CancelFrame):
525        try:
526            await super().cancel(frame)
527        finally:
528            await _leave_room(self, self._room)
529
530    async def cleanup(self):
531        # pipecat cleans up every processor, also one that no EndFrame or CancelFrame reached; the
532        # room is left even when pipecat's cleanup fails.
533        try:
534            await super().cleanup()
535        finally:
536            await self._room.stop(self)
537
538    async def process_frame(self, frame: Frame, direction: FrameDirection):
539        # The output publishes one broadcast, pipecat's default destination: a frame for another
540        # destination, as for another transport's output in the same pipeline, goes on as it came,
541        # leaving the output's resampler, senders and room alone. It goes on before pipecat's
542        # processor handles a CancelFrame or an InterruptionFrame, and past the end of the speech
543        # `push_frame` writes at a TTSStoppedFrame or a StopFrame, which are the pipeline's only
544        # without a destination.
545        if frame.transport_destination is not None:
546            await super().push_frame(frame, direction)
547            return
548        audio_in = self._audio_in if self._params.audio_out_enabled else None
549        # Before pipecat's processor and media sender handle the interruption, which waits for an
550        # uninterruptible picture being written: the chunk being written stops at its next packet,
551        # and the interruptible chunks queued after it are dropped at once, so none is written
552        # meanwhile.
553        if isinstance(frame, InterruptionFrame):
554            self._room.interrupt_audio()
555            sender = self._media_senders.get(None)
556            if isinstance(sender, _MediaSender):
557                sender.drop_interruptible_audio()
558            if audio_in is not None:
559                audio_in.interrupt()
560        # pipecat's media sender cuts the audio of consecutive frames into chunks, each labelled
561        # with the output's sample rate and the channel count of the frame that completed it, and
562        # its own resampler takes one input rate and mono only: each frame is queued at the output's
563        # rate and channel count, and one that cannot be is dropped here.
564        elif direction == FrameDirection.DOWNSTREAM and audio_in is not None and isinstance(frame, OutputAudioRawFrame):
565            try:
566                frame = audio_in.normalized(frame)
567            except ValueError as error:
568                await FrameProcessor.process_frame(self, frame, direction)
569                await self.push_error(f"cannot write audio: {error}", error)
570                return
571        # The end of the speech, which makes pipecat write its last chunk. pipecat queues that
572        # chunk, short of `audio_out_10ms_chunks`, only at a TTSStoppedFrame, and the output's
573        # `stop` does at an EndFrame; the senders a StopFrame leaves are replaced at the next
574        # StartFrame, which would drop it, and the pipeline flush probe of
575        # `PipelineWorker.flush_pipeline` tells that all the frames before it were handled, which
576        # that chunk would belie.
577        elif (
578            direction == FrameDirection.DOWNSTREAM
579            and audio_in is not None
580            and isinstance(frame, (TTSStoppedFrame, EndFrame, StopFrame, PipelineFlushFrame))
581        ):
582            await self._queue_end_of_speech(
583                audio_in, direction, last_chunk=isinstance(frame, (StopFrame, PipelineFlushFrame))
584            )
585        # pipecat writes an urgent message with `send_message` as it comes, either way, and passes
586        # on none: one this transport does not write goes on the way it came instead, to the next
587        # processor, such as another transport's output.
588        elif isinstance(frame, OutputTransportMessageUrgentFrame):
589            await FrameProcessor.process_frame(self, frame, direction)
590            if not await self._write_message(frame.message):
591                await self.push_frame(frame, direction)
592            return
593        # pipecat passes a message on behind the audio queued, calling `send_message`, which the
594        # media sender skips (`_MediaSender._handle_frame`), or once its `pts` is due, and drops it
595        # when an interruption or a StopFrame comes first: each is written as it comes instead,
596        # timed or not, in frame order, so a group opened by one is the group the next one
597        # continues, and a flush probe or a StopFrame after it finds it written.
598        elif direction == FrameDirection.DOWNSTREAM and isinstance(frame, OutputTransportMessageFrame):
599            await self._write_message(frame.message)
600        # pipecat's video sender cycles a sprite's pictures and resizes each picture before
601        # `write_video_frame`, and an empty sprite or a picture it cannot resize would end its task
602        # for good: each picture is queued as the encoder reads it, and a frame the encoder would
603        # refuse or pipecat could not show is dropped here.
604        elif (
605            direction == FrameDirection.DOWNSTREAM
606            and self._params.video_out_enabled
607            and isinstance(frame, (OutputImageRawFrame, SpriteFrame))
608        ):
609            try:
610                frame = self._normalized_pictures(frame)
611            except ValueError as error:
612                await FrameProcessor.process_frame(self, frame, direction)
613                await self.push_error(f"cannot write a picture: {error}", error)
614                return
615            # pipecat shows a sprite, and a picture synchronized with the audio once the audio
616            # queued before it was written, by making them the pictures its video sender cycles,
617            # which a live sender does not read: a sprite's pictures go to the live queue one after
618            # the other, each as interruptible as the sprite, an assistant image among them too,
619            # which stays out of the assistant's context, as pipecat passes on no picture of a
620            # sprite. A synchronized picture goes behind the chunks queued as a `_SyncedPicture`
621            # noting the speech before it that the resampler and pipecat's last chunk hold, which is
622            # queued only after it; once pipecat's sender reached it, `write_transport_frame` has it
623            # written at the timestamp where that speech ends.
624            sender = self._media_senders.get(frame.transport_destination)
625            if isinstance(sender, _MediaSender) and isinstance(frame, OutputImageRawFrame) and frame.sync_with_audio:
626                await FrameProcessor.process_frame(self, frame, direction)
627                pending = audio_in.held_micros() + sender.held_audio_micros() if audio_in is not None else 0.0
628                await sender.handle_synced_picture(_SyncedPicture.of(frame, pending))
629                return
630            if self._params.video_out_is_live and isinstance(sender, _MediaSender) and isinstance(frame, SpriteFrame):
631                await FrameProcessor.process_frame(self, frame, direction)
632                pictures = [
633                    _copied(picture, sync_with_audio=False, interruptible=frame.interruptible) for picture in frame.images
634                ]
635                await sender.queue_live_pictures(pictures)
636                return
637        await super().process_frame(frame, direction)
638
639    async def _queue_end_of_speech(self, audio_in: "_AudioNormalizer", direction: FrameDirection, *, last_chunk: bool):
640        """Queues what the resampler holds of the speech ahead of the frame being processed and,
641        with `last_chunk`, pipecat's last chunk of it, short of `audio_out_10ms_chunks`, padded with
642        silence. A failure is pushed as an ErrorFrame, and the frame goes on all the same, so an
643        EndFrame still stops the output and ends the pipeline."""
644        try:
645            tail = audio_in.flush()
646            if tail is not None:
647                await super().process_frame(tail, direction)
648            if last_chunk:
649                for sender in self._media_senders.values():
650                    await sender._enqueue_flushed_audio_buffer()
651        except Exception as error:
652            await self.push_error(f"cannot write the end of the speech: {error}", error)
653
654    async def _finish_speech(self) -> None:
655        """Writes the speech's last packet, which the encoder holds; a failure is pushed upstream as
656        a failed audio write is."""
657        try:
658            self._room.finish_audio()
659        except Exception as error:
660            await self._report_write_failure(f"cannot write the end of the speech: {error}", error)
661
662    async def _handle_frame(self, frame: Frame):
663        # pipecat drops a frame for which it has no media sender, and an output whose room never
664        # opened has none, which pipecat's default ProcessorUnusablePolicy.CONTINUE keeps running:
665        # such a frame goes on, so a StopFrame still stops the pipeline, but the audio and pictures
666        # the output did not write do not, and an InterruptionFrame went on already.
667        if frame.transport_destination not in self._media_senders and not isinstance(
668            frame, (InterruptionFrame, OutputAudioRawFrame, OutputImageRawFrame, SpriteFrame)
669        ):
670            await self.push_frame(frame)
671            return
672        await super()._handle_frame(frame)
673
674    def _normalized_pictures(self, frame: OutputImageRawFrame | SpriteFrame) -> OutputImageRawFrame | SpriteFrame:
675        """A copy of `frame` whose pictures carry their image as bytes, their color format, RGB for
676        one without, and their size as two integers. Raises ValueError for a sprite without
677        pictures, and for a picture the encoder would refuse or pipecat's video sender could not
678        resize to the output's size."""
679        if isinstance(frame, OutputImageRawFrame):
680            return self._normalized_picture(frame)
681        if not frame.images:
682            raise ValueError("a sprite without pictures")
683        return _copied(frame, images=[self._normalized_picture(picture) for picture in frame.images])
684
685    def _normalized_picture(self, picture: OutputImageRawFrame) -> OutputImageRawFrame:
686        color_format = picture.format or "RGB"
687        image, size = _checked_picture(picture.image, picture.size, color_format)
688        output_size = (self._params.video_out_width, self._params.video_out_height)
689        # The media sender resizes with Pillow, as pipecat's does, which reads no BGR.
690        if color_format in ("BGR", "BGRA") and size != output_size:
691            raise ValueError(f"pipecat cannot resize a {color_format} picture to {output_size[0]}x{output_size[1]}")
692        return _copied(picture, image=image, format=color_format, size=size)
693
694    async def write_transport_frame(self, frame: Frame):
695        # pipecat's audio task reached a synchronized picture: the chunks queued before it were
696        # written, so the speech before it ends after the packets written, what the Opus encoder
697        # holds and what the output held short of a chunk as the picture came. It is written from
698        # now, at that timestamp, so it neither waits for speech after it nor stalls the pictures
699        # after it, and off the audio task, whose speech its encode would hold up. The audio task
700        # waits for an assistant image, so it is passed on before the frames after it.
701        sender = self._media_senders.get(frame.transport_destination)
702        if isinstance(frame, _SyncedPicture) and isinstance(sender, _MediaSender):
703            writing = sender.write_synced_picture(frame, self._room.speech_end_micros(frame.pending_micros))
704            if isinstance(frame.picture, AssistantImageRawFrame):
705                await asyncio.wait([writing])
706
707    async def push_frame(self, frame: Frame, direction: FrameDirection = FrameDirection.DOWNSTREAM):
708        # The audio task passes a picture it reached on, as pipecat does: the draw or the write of
709        # a picture queued behind the audio passes the picture on instead, once written.
710        if isinstance(frame, (_SyncedPicture, _AssistantImage)):
711            return
712        sender = self._media_senders.get(frame.transport_destination)
713        # pipecat's media sender pushes a TTSStoppedFrame, a StopFrame or a pipeline flush probe on
714        # once it wrote the speech queued ahead of it: the utterance's last packet is written then,
715        # before an interruption could drop it. The senders a StopFrame leaves are replaced at the
716        # next StartFrame, which would drop the pictures given to them and not yet written, and a
717        # flush probe tells that the frames before it were handled: the pictures given before it,
718        # as it found them on reaching the output, are written first, as at an EndFrame.
719        downstream = direction == FrameDirection.DOWNSTREAM
720        if isinstance(frame, (TTSStoppedFrame, StopFrame, PipelineFlushFrame)) and downstream:
721            await self._finish_speech()
722        if isinstance(frame, (StopFrame, PipelineFlushFrame)) and downstream and isinstance(sender, _MediaSender):
723            await sender.write_given_pictures(frame)
724        await super().push_frame(frame, direction)
725
726    # pipecat's media sender writes the audio and the messages in one task and the pictures in
727    # another, which a write that raises would end for good: a failed write is pushed upstream as an
728    # ErrorFrame instead, and the frames after it are written. Once publishing the media source
729    # failed, which it does for good, the room drops the audio and pictures after it, and the write
730    # returns False, so pipecat does not pass the audio on as sent.
731
732    async def write_audio_frame(self, frame: OutputAudioRawFrame) -> bool:
733        try:
734            return await self._room.write_audio(
735                frame.audio, frame.sample_rate, frame.num_channels, interruptible=frame.interruptible
736            )
737        except Exception as error:
738            await self._report_write_failure(f"cannot write audio: {error}", error)
739            return False
740
741    async def write_video_frame(self, frame: OutputImageRawFrame) -> bool:
742        return await self._write_picture(frame, None)
743
744    async def _write_picture(self, frame: OutputImageRawFrame, timestamp_micros: int | None) -> bool:
745        try:
746            return await self._room.write_picture(
747                frame.image, frame.size, frame.format or "RGB", timestamp_micros=timestamp_micros
748            )
749        except Exception as error:
750            await self._report_write_failure(f"cannot write a picture: {error}", error)
751            return False
752
753    async def _report_write_failure(self, message: str, error: Exception) -> None:
754        """Pushes a failed media write upstream as an `ErrorFrame`, non-fatal for a failure such as
755        a picture the encoder refuses. The one that found publishing the media source failed is
756        treated as permanent when the output writes no data track or event timeline: media was all
757        it could do."""
758        await self.push_error(message, error, force_treat_as_permanent=self._media_only and self._room.media_failed)
759
760    async def send_message(self, frame: OutputTransportMessageFrame | OutputTransportMessageUrgentFrame):
761        """Writes the message `frame` carries at once when it is for one of the transport's tracks,
762        as the output does for a frame that reaches it, and writes nothing for a frame for another
763        destination; a failed write is pushed upstream as a non-fatal `ErrorFrame`. pipecat calls
764        it for no frame that reaches the output."""
765        if frame.transport_destination is None:
766            await self._write_message(frame.message)
767
768    async def _write_message(self, message: object) -> bool:
769        """Writes `message` when it is for one of the transport's tracks; returns whether it was,
770        also when writing it failed, which is pushed upstream as a non-fatal `ErrorFrame`."""
771        try:
772            return await self._room.write_message(message)
773        except Exception as error:
774            await self.push_error(f"cannot write the message: {error}", error)
775            return True

Publishes audio (Opus), video (video_out_codec), and immediate MoqWasmTrackObject / MoqWasmEventRecord messages in frame order (not paced to queued audio or pts, which only times downstream forwarding; messages stay written even if a later interruption drops the frame).

Single-use per pipeline run; obtain a fresh instance from MoqWasmTransport.output() for each pipeline. Permanent media failure emits a permanent ErrorFrame when no data/timeline tracks are configured.

MoqWasmOutputTransport( room: moq_wasm.pipecat._room.Room, params: MoqWasmParams, **kwargs)
455    def __init__(self, room: Room, params: MoqWasmParams, **kwargs):
456        super().__init__(params, **kwargs)
457        self._room = room
458        # Whether media is all the output writes, so that it can do nothing once publishing it
459        # failed.
460        self._media_only = not (params.data_out_tracks or params.event_timelines_out)
461        # Set up with the output's sample rate, which pipecat sets in `setup`.
462        self._audio_in: _AudioNormalizer | None = None

Initialize the frame processor.

Args: name: Optional name for this processor instance. enable_direct_mode: Whether to process frames immediately or use internal queues. metrics: Optional metrics collector for this processor. **kwargs: Additional arguments passed to parent class.

async def setup(self, setup: pipecat.processors.frame_processor.FrameProcessorSetup):
467    async def setup(self, setup: FrameProcessorSetup):
468        await super().setup(setup)
469        self._audio_in = _AudioNormalizer(self.sample_rate, self._params.audio_out_channels)

Set up the transport.

Args: setup: Configuration object containing setup parameters.

async def start(self, frame: pipecat.frames.frames.StartFrame):
471    async def start(self, frame: StartFrame):
472        await super().start(frame)
473        if self.ran:
474            return
475        await self._end_stopped_senders()
476        # A sample rate under 100 Hz has no sample in 10 ms: an audio sender would cut empty chunks
477        # forever, so the output can write nothing.
478        if self._params.audio_out_enabled and self.audio_chunk_size <= 0:
479            error = ValueError(f"{self.sample_rate} Hz audio has no sample in 10 ms")
480            await self.push_error(f"cannot write audio: {error}", error, force_treat_as_permanent=True)
481            return
482        if await _open_room(self, self._room):
483            await self.set_transport_ready(frame)

Start the output transport.

Base hook for subclasses, which reach it through super(). The transport's own audio configuration is resolved in setup().

Args: frame: The start frame containing initialization parameters.

async def set_transport_ready(self, frame: pipecat.frames.frames.StartFrame):
485    async def set_transport_ready(self, frame: StartFrame):
486        # pipecat's, with the output's own media sender; the transport refuses output destinations,
487        # so the default one is all it starts.
488        self._media_senders[None] = sender = _MediaSender(
489            self,
490            destination=None,
491            sample_rate=self.sample_rate,
492            audio_chunk_size=self.audio_chunk_size,
493            params=self._params,
494        )
495        await sender.start(frame)
496        await self.push_frame(OutputTransportReadyFrame(), FrameDirection.UPSTREAM)

Called when the transport is ready to stream.

Args: frame: The start frame containing initialization parameters.

async def stop(self, frame: pipecat.frames.frames.EndFrame):
507    async def stop(self, frame: EndFrame):
508        # pipecat writes the audio queued before the EndFrame, in chunks of `audio_out_10ms_chunks`;
509        # the speech's last chunk, short of one, is queued ahead of it, padded with silence, as
510        # pipecat does at a TTSStoppedFrame. The audio task writes the speech's last packet after
511        # it.
512        try:
513            try:
514                if self._params.audio_out_enabled:
515                    for sender in self._media_senders.values():
516                        await sender._enqueue_flushed_audio_buffer()
517            finally:
518                await super().stop(frame)
519        except Exception as error:
520            await self._report_write_failure(f"cannot write the end of the speech: {error}", error)
521        finally:
522            await _leave_room(self, self._room)

Stop the output transport and cleanup resources.

Args: frame: The end frame signaling transport shutdown.

async def cancel(self, frame: pipecat.frames.frames.CancelFrame):
524    async def cancel(self, frame: CancelFrame):
525        try:
526            await super().cancel(frame)
527        finally:
528            await _leave_room(self, self._room)

Cancel the output transport and stop all processing.

Args: frame: The cancel frame signaling immediate cancellation.

async def cleanup(self):
530    async def cleanup(self):
531        # pipecat cleans up every processor, also one that no EndFrame or CancelFrame reached; the
532        # room is left even when pipecat's cleanup fails.
533        try:
534            await super().cleanup()
535        finally:
536            await self._room.stop(self)

Release output transport resources at teardown.

async def process_frame( self, frame: pipecat.frames.frames.Frame, direction: pipecat.processors.frame_processor.FrameDirection):
538    async def process_frame(self, frame: Frame, direction: FrameDirection):
539        # The output publishes one broadcast, pipecat's default destination: a frame for another
540        # destination, as for another transport's output in the same pipeline, goes on as it came,
541        # leaving the output's resampler, senders and room alone. It goes on before pipecat's
542        # processor handles a CancelFrame or an InterruptionFrame, and past the end of the speech
543        # `push_frame` writes at a TTSStoppedFrame or a StopFrame, which are the pipeline's only
544        # without a destination.
545        if frame.transport_destination is not None:
546            await super().push_frame(frame, direction)
547            return
548        audio_in = self._audio_in if self._params.audio_out_enabled else None
549        # Before pipecat's processor and media sender handle the interruption, which waits for an
550        # uninterruptible picture being written: the chunk being written stops at its next packet,
551        # and the interruptible chunks queued after it are dropped at once, so none is written
552        # meanwhile.
553        if isinstance(frame, InterruptionFrame):
554            self._room.interrupt_audio()
555            sender = self._media_senders.get(None)
556            if isinstance(sender, _MediaSender):
557                sender.drop_interruptible_audio()
558            if audio_in is not None:
559                audio_in.interrupt()
560        # pipecat's media sender cuts the audio of consecutive frames into chunks, each labelled
561        # with the output's sample rate and the channel count of the frame that completed it, and
562        # its own resampler takes one input rate and mono only: each frame is queued at the output's
563        # rate and channel count, and one that cannot be is dropped here.
564        elif direction == FrameDirection.DOWNSTREAM and audio_in is not None and isinstance(frame, OutputAudioRawFrame):
565            try:
566                frame = audio_in.normalized(frame)
567            except ValueError as error:
568                await FrameProcessor.process_frame(self, frame, direction)
569                await self.push_error(f"cannot write audio: {error}", error)
570                return
571        # The end of the speech, which makes pipecat write its last chunk. pipecat queues that
572        # chunk, short of `audio_out_10ms_chunks`, only at a TTSStoppedFrame, and the output's
573        # `stop` does at an EndFrame; the senders a StopFrame leaves are replaced at the next
574        # StartFrame, which would drop it, and the pipeline flush probe of
575        # `PipelineWorker.flush_pipeline` tells that all the frames before it were handled, which
576        # that chunk would belie.
577        elif (
578            direction == FrameDirection.DOWNSTREAM
579            and audio_in is not None
580            and isinstance(frame, (TTSStoppedFrame, EndFrame, StopFrame, PipelineFlushFrame))
581        ):
582            await self._queue_end_of_speech(
583                audio_in, direction, last_chunk=isinstance(frame, (StopFrame, PipelineFlushFrame))
584            )
585        # pipecat writes an urgent message with `send_message` as it comes, either way, and passes
586        # on none: one this transport does not write goes on the way it came instead, to the next
587        # processor, such as another transport's output.
588        elif isinstance(frame, OutputTransportMessageUrgentFrame):
589            await FrameProcessor.process_frame(self, frame, direction)
590            if not await self._write_message(frame.message):
591                await self.push_frame(frame, direction)
592            return
593        # pipecat passes a message on behind the audio queued, calling `send_message`, which the
594        # media sender skips (`_MediaSender._handle_frame`), or once its `pts` is due, and drops it
595        # when an interruption or a StopFrame comes first: each is written as it comes instead,
596        # timed or not, in frame order, so a group opened by one is the group the next one
597        # continues, and a flush probe or a StopFrame after it finds it written.
598        elif direction == FrameDirection.DOWNSTREAM and isinstance(frame, OutputTransportMessageFrame):
599            await self._write_message(frame.message)
600        # pipecat's video sender cycles a sprite's pictures and resizes each picture before
601        # `write_video_frame`, and an empty sprite or a picture it cannot resize would end its task
602        # for good: each picture is queued as the encoder reads it, and a frame the encoder would
603        # refuse or pipecat could not show is dropped here.
604        elif (
605            direction == FrameDirection.DOWNSTREAM
606            and self._params.video_out_enabled
607            and isinstance(frame, (OutputImageRawFrame, SpriteFrame))
608        ):
609            try:
610                frame = self._normalized_pictures(frame)
611            except ValueError as error:
612                await FrameProcessor.process_frame(self, frame, direction)
613                await self.push_error(f"cannot write a picture: {error}", error)
614                return
615            # pipecat shows a sprite, and a picture synchronized with the audio once the audio
616            # queued before it was written, by making them the pictures its video sender cycles,
617            # which a live sender does not read: a sprite's pictures go to the live queue one after
618            # the other, each as interruptible as the sprite, an assistant image among them too,
619            # which stays out of the assistant's context, as pipecat passes on no picture of a
620            # sprite. A synchronized picture goes behind the chunks queued as a `_SyncedPicture`
621            # noting the speech before it that the resampler and pipecat's last chunk hold, which is
622            # queued only after it; once pipecat's sender reached it, `write_transport_frame` has it
623            # written at the timestamp where that speech ends.
624            sender = self._media_senders.get(frame.transport_destination)
625            if isinstance(sender, _MediaSender) and isinstance(frame, OutputImageRawFrame) and frame.sync_with_audio:
626                await FrameProcessor.process_frame(self, frame, direction)
627                pending = audio_in.held_micros() + sender.held_audio_micros() if audio_in is not None else 0.0
628                await sender.handle_synced_picture(_SyncedPicture.of(frame, pending))
629                return
630            if self._params.video_out_is_live and isinstance(sender, _MediaSender) and isinstance(frame, SpriteFrame):
631                await FrameProcessor.process_frame(self, frame, direction)
632                pictures = [
633                    _copied(picture, sync_with_audio=False, interruptible=frame.interruptible) for picture in frame.images
634                ]
635                await sender.queue_live_pictures(pictures)
636                return
637        await super().process_frame(frame, direction)

Process a frame.

Args: frame: The frame to process. direction: The direction of frame flow.

async def write_transport_frame(self, frame: pipecat.frames.frames.Frame):
694    async def write_transport_frame(self, frame: Frame):
695        # pipecat's audio task reached a synchronized picture: the chunks queued before it were
696        # written, so the speech before it ends after the packets written, what the Opus encoder
697        # holds and what the output held short of a chunk as the picture came. It is written from
698        # now, at that timestamp, so it neither waits for speech after it nor stalls the pictures
699        # after it, and off the audio task, whose speech its encode would hold up. The audio task
700        # waits for an assistant image, so it is passed on before the frames after it.
701        sender = self._media_senders.get(frame.transport_destination)
702        if isinstance(frame, _SyncedPicture) and isinstance(sender, _MediaSender):
703            writing = sender.write_synced_picture(frame, self._room.speech_end_micros(frame.pending_micros))
704            if isinstance(frame.picture, AssistantImageRawFrame):
705                await asyncio.wait([writing])

Handle a queued frame after preceding audio has been sent.

Override in transport subclasses to handle custom frame types that flow through the audio queue. Called by the media sender after the frame has waited for any preceding audio to finish.

Args: frame: The frame to handle.

async def push_frame( self, frame: pipecat.frames.frames.Frame, direction: pipecat.processors.frame_processor.FrameDirection = <FrameDirection.DOWNSTREAM: 1>):
707    async def push_frame(self, frame: Frame, direction: FrameDirection = FrameDirection.DOWNSTREAM):
708        # The audio task passes a picture it reached on, as pipecat does: the draw or the write of
709        # a picture queued behind the audio passes the picture on instead, once written.
710        if isinstance(frame, (_SyncedPicture, _AssistantImage)):
711            return
712        sender = self._media_senders.get(frame.transport_destination)
713        # pipecat's media sender pushes a TTSStoppedFrame, a StopFrame or a pipeline flush probe on
714        # once it wrote the speech queued ahead of it: the utterance's last packet is written then,
715        # before an interruption could drop it. The senders a StopFrame leaves are replaced at the
716        # next StartFrame, which would drop the pictures given to them and not yet written, and a
717        # flush probe tells that the frames before it were handled: the pictures given before it,
718        # as it found them on reaching the output, are written first, as at an EndFrame.
719        downstream = direction == FrameDirection.DOWNSTREAM
720        if isinstance(frame, (TTSStoppedFrame, StopFrame, PipelineFlushFrame)) and downstream:
721            await self._finish_speech()
722        if isinstance(frame, (StopFrame, PipelineFlushFrame)) and downstream and isinstance(sender, _MediaSender):
723            await sender.write_given_pictures(frame)
724        await super().push_frame(frame, direction)

Push a frame to the next processor in the pipeline.

Args: frame: The frame to push. direction: The direction to push the frame.

async def write_audio_frame(self, frame: pipecat.frames.frames.OutputAudioRawFrame) -> bool:
732    async def write_audio_frame(self, frame: OutputAudioRawFrame) -> bool:
733        try:
734            return await self._room.write_audio(
735                frame.audio, frame.sample_rate, frame.num_channels, interruptible=frame.interruptible
736            )
737        except Exception as error:
738            await self._report_write_failure(f"cannot write audio: {error}", error)
739            return False

Write an audio frame to the transport.

Args: frame: The output audio frame to write.

Returns: Whether the transport took the frame. A serializer that emits no payload has still taken it; see FrameSerializer.serialize().

async def write_video_frame(self, frame: pipecat.frames.frames.OutputImageRawFrame) -> bool:
741    async def write_video_frame(self, frame: OutputImageRawFrame) -> bool:
742        return await self._write_picture(frame, None)

Write a video frame to the transport.

Args: frame: The output video frame to write.

Returns: True if the video frame was written successfully, False otherwise.

async def send_message( self, frame: pipecat.frames.frames.OutputTransportMessageFrame | pipecat.frames.frames.OutputTransportMessageUrgentFrame):
760    async def send_message(self, frame: OutputTransportMessageFrame | OutputTransportMessageUrgentFrame):
761        """Writes the message `frame` carries at once when it is for one of the transport's tracks,
762        as the output does for a frame that reaches it, and writes nothing for a frame for another
763        destination; a failed write is pushed upstream as a non-fatal `ErrorFrame`. pipecat calls
764        it for no frame that reaches the output."""
765        if frame.transport_destination is None:
766            await self._write_message(frame.message)

Writes the message frame carries at once when it is for one of the transport's tracks, as the output does for a frame that reaches it, and writes nothing for a frame for another destination; a failed write is pushed upstream as a non-fatal ErrorFrame. pipecat calls it for no frame that reaches the output.

class MoqWasmParams(moq_wasm.pipecat.MoqWasmInputParams):
 90class MoqWasmParams(MoqWasmInputParams):
 91    """`MoqWasmInputParams` plus room namespace and published tracks.
 92
 93    Parameters:
 94        room: Room prefix; direct child namespaces are treated as participants.
 95        participant_id: Media source label and default broadcast suffix (`[*room, participant_id]`).
 96        broadcast: Explicit broadcast namespace override (e.g. `[*room, "bots", "chat-moderation"]`).
 97        data_out_tracks: Map of output data track names to `FETCH` retention seconds (`MoqWasmTrackObject`).
 98        event_timelines_out: Map of output event timeline names to retention seconds (`MoqWasmEventRecord`).
 99        empty_timeout: Seconds with no participants before `on_room_empty` fires and room watching stops.
100    """
101
102    room: list[str]
103    participant_id: str = "bot"
104    broadcast: list[str] | None = None
105    data_out_tracks: dict[str, float] = {}
106    event_timelines_out: dict[str, float] = {}
107    empty_timeout: float | None = None

MoqWasmInputParams plus room namespace and published tracks.

Parameters: room: Room prefix; direct child namespaces are treated as participants. participant_id: Media source label and default broadcast suffix ([*room, participant_id]). broadcast: Explicit broadcast namespace override (e.g. [*room, "bots", "chat-moderation"]). data_out_tracks: Map of output data track names to FETCH retention seconds (MoqWasmTrackObject). event_timelines_out: Map of output event timeline names to retention seconds (MoqWasmEventRecord). empty_timeout: Seconds with no participants before on_room_empty fires and room watching stops.

room: list[str] = PydanticUndefined
participant_id: str = 'bot'
broadcast: list[str] | None = None
data_out_tracks: dict[str, float] = {}
event_timelines_out: dict[str, float] = {}
empty_timeout: float | None = None
class MoqWasmParticipantInput(moq_wasm.pipecat._transport._ReceivingInput):
316class MoqWasmParticipantInput(_ReceivingInput):
317    """Receive-only input for a single participant's `RemoteBroadcast` (use one pipeline per speaker when running VAD).
318
319    - Subscribes from `StartFrame` until `EndFrame`/`CancelFrame`/`cleanup`, returning only after unsubscribing
320      and answering pending image requests. `StopFrame` pauses delivery without dropping subscriptions.
321    - Single-use per pipeline run; create a new instance for the next pipeline. Snapshots `params` on init.
322    - Event handler: `on_track_subscribed(MoqWasmTrack)`. Track decode errors emit a non-fatal `ErrorFrame`
323      and retry with exponential backoff.
324    """
325
326    def __init__(self, broadcast: RemoteBroadcast, params: MoqWasmInputParams, **kwargs):
327        params = _snapshot(params)
328        super().__init__(params, **kwargs)
329        self._participant_id = broadcast.namespace[-1]
330        # None once the receiving ended for good: an input the application still holds once it
331        # stopped keeps neither the participant's broadcast, nor through it the session, nor its
332        # catalog.
333        self._receiver: ParticipantReceiver | None = ParticipantReceiver(
334            broadcast, _receive_options(params), self, stream_audio=False
335        )
336        # Kept until its teardown finished, which `_stopping` runs once for the stop, the cancel and
337        # the cleanup: a caller pipecat cancels leaves it running for the others to wait for.
338        self._receiving: asyncio.Task | None = None
339        self._stopping: Once[None] = Once()
340        self._register_event_handler("on_track_subscribed")
341
342    async def start(self, frame: StartFrame):
343        await super().start(frame)
344        if self.ran:
345            return
346        await self.set_transport_ready(frame)
347        receiver = self._receiver
348        if receiver is None:
349            return
350        if self._params.audio_in_stream_on_start:
351            await receiver.start_audio()
352        # A StopFrame leaves the input receiving, as pipecat keeps a stopped processor running, and
353        # pausing it drops what it receives: the next StartFrame resumes that same receiving.
354        if self._receiving is None and not self._stopping.started:
355            self._receiving = asyncio.create_task(receiver.run())
356            self._receiving.add_done_callback(_log_failure)
357
358    async def _start_audio_in_streaming(self):
359        if self._receiver is not None:
360            await self._receiver.start_audio()
361
362    async def request_image(self, request: UserImageRequestFrame) -> None:
363        """`ParticipantReceiver.request_image`. A request for another participant, or made once the
364        receiving ended, is answered with an error at once, and the call, which the input's frame
365        processing awaits, returns once its `result_callback` did."""
366        if request.user_id != self._participant_id:
367            await self.answer_image_requests([request], f"no participant {request.user_id}")
368            return
369        if self._receiver is None:
370            await self.answer_image_requests([request], departure_error(self._participant_id))
371            return
372        await self._receiver.request_image(request)
373
374    async def stop(self, frame: EndFrame):
375        await self._stop_receiving()
376        await super().stop(frame)
377
378    async def cancel(self, frame: CancelFrame):
379        await self._stop_receiving()
380        await super().cancel(frame)
381
382    async def cleanup(self):
383        # pipecat cleans up every processor, also one that no EndFrame or CancelFrame reached; the
384        # tracks are unsubscribed even when pipecat's cleanup fails, as an audio filter's `stop`
385        # may.
386        try:
387            await super().cleanup()
388        finally:
389            await self._stop_receiving()
390
391    async def event(self, name: str, *args: object) -> None:
392        if name == "on_error":
393            message, error = args
394            assert isinstance(message, str) and isinstance(error, Exception)
395            await self.push_error(message, error)
396        else:
397            await self._call_event_handler(name, *args)
398
399    async def _stop_receiving(self) -> None:
400        """Cancels the receiving once and returns once its teardown finished: every track
401        unsubscribed and the image requests still waiting answered. Cancelling the caller, as
402        pipecat's cleanup cancels a stop in progress, leaves the teardown running."""
403        await self._stopping.run(self._end_receiving)
404
405    async def _end_receiving(self) -> None:
406        receiving = self._receiving
407        if receiving is not None:
408            # The receiving returns only once its teardown finished, also one the session's end
409            # started before this cancels it.
410            receiving.cancel()
411            await asyncio.wait([receiving])
412            # Its cancellation's traceback keeps the receiving's locals: an input the application
413            # still holds once it stopped keeps none of them.
414            self._receiving = None
415        self._receiver = None

Receive-only input for a single participant's RemoteBroadcast (use one pipeline per speaker when running VAD).

  • Subscribes from StartFrame until EndFrame/CancelFrame/cleanup, returning only after unsubscribing and answering pending image requests. StopFrame pauses delivery without dropping subscriptions.
  • Single-use per pipeline run; create a new instance for the next pipeline. Snapshots params on init.
  • Event handler: on_track_subscribed(MoqWasmTrack). Track decode errors emit a non-fatal ErrorFrame and retry with exponential backoff.
MoqWasmParticipantInput( broadcast: moq_wasm.media.RemoteBroadcast, params: MoqWasmInputParams, **kwargs)
326    def __init__(self, broadcast: RemoteBroadcast, params: MoqWasmInputParams, **kwargs):
327        params = _snapshot(params)
328        super().__init__(params, **kwargs)
329        self._participant_id = broadcast.namespace[-1]
330        # None once the receiving ended for good: an input the application still holds once it
331        # stopped keeps neither the participant's broadcast, nor through it the session, nor its
332        # catalog.
333        self._receiver: ParticipantReceiver | None = ParticipantReceiver(
334            broadcast, _receive_options(params), self, stream_audio=False
335        )
336        # Kept until its teardown finished, which `_stopping` runs once for the stop, the cancel and
337        # the cleanup: a caller pipecat cancels leaves it running for the others to wait for.
338        self._receiving: asyncio.Task | None = None
339        self._stopping: Once[None] = Once()
340        self._register_event_handler("on_track_subscribed")

Initialize the base input transport.

Args: params: Transport configuration parameters. **kwargs: Additional arguments passed to parent class.

async def start(self, frame: pipecat.frames.frames.StartFrame):
342    async def start(self, frame: StartFrame):
343        await super().start(frame)
344        if self.ran:
345            return
346        await self.set_transport_ready(frame)
347        receiver = self._receiver
348        if receiver is None:
349            return
350        if self._params.audio_in_stream_on_start:
351            await receiver.start_audio()
352        # A StopFrame leaves the input receiving, as pipecat keeps a stopped processor running, and
353        # pausing it drops what it receives: the next StartFrame resumes that same receiving.
354        if self._receiving is None and not self._stopping.started:
355            self._receiving = asyncio.create_task(receiver.run())
356            self._receiving.add_done_callback(_log_failure)

Start the input transport and initialize components.

Args: frame: The start frame containing initialization parameters.

async def request_image(self, request: pipecat.frames.frames.UserImageRequestFrame) -> None:
362    async def request_image(self, request: UserImageRequestFrame) -> None:
363        """`ParticipantReceiver.request_image`. A request for another participant, or made once the
364        receiving ended, is answered with an error at once, and the call, which the input's frame
365        processing awaits, returns once its `result_callback` did."""
366        if request.user_id != self._participant_id:
367            await self.answer_image_requests([request], f"no participant {request.user_id}")
368            return
369        if self._receiver is None:
370            await self.answer_image_requests([request], departure_error(self._participant_id))
371            return
372        await self._receiver.request_image(request)

ParticipantReceiver.request_image. A request for another participant, or made once the receiving ended, is answered with an error at once, and the call, which the input's frame processing awaits, returns once its result_callback did.

async def stop(self, frame: pipecat.frames.frames.EndFrame):
374    async def stop(self, frame: EndFrame):
375        await self._stop_receiving()
376        await super().stop(frame)

Stop the input transport and cleanup resources.

Args: frame: The end frame signaling transport shutdown.

async def cancel(self, frame: pipecat.frames.frames.CancelFrame):
378    async def cancel(self, frame: CancelFrame):
379        await self._stop_receiving()
380        await super().cancel(frame)

Cancel the input transport and stop all processing.

Args: frame: The cancel frame signaling immediate cancellation.

async def cleanup(self):
382    async def cleanup(self):
383        # pipecat cleans up every processor, also one that no EndFrame or CancelFrame reached; the
384        # tracks are unsubscribed even when pipecat's cleanup fails, as an audio filter's `stop`
385        # may.
386        try:
387            await super().cleanup()
388        finally:
389            await self._stop_receiving()

Release input transport resources at teardown.

async def event(self, name: str, *args: object) -> None:
391    async def event(self, name: str, *args: object) -> None:
392        if name == "on_error":
393            message, error = args
394            assert isinstance(message, str) and isinstance(error, Exception)
395            await self.push_error(message, error)
396        else:
397            await self._call_event_handler(name, *args)
@dataclass(frozen=True)
class MoqWasmEventRecord:
62@dataclass(frozen=True)
63class MoqWasmEventRecord:
64    """A record to append to one of the transport's `event_timelines_out`, the `message` of an
65    `OutputTransportMessageFrame`."""
66
67    track: str
68    record: EventRecord

A record to append to one of the transport's event_timelines_out, the message of an OutputTransportMessageFrame.

MoqWasmEventRecord(track: str, record: dict[str, typing.Any])
track: str
record: dict[str, typing.Any]
@dataclass(frozen=True)
class MoqWasmTrack:
38@dataclass(frozen=True)
39class MoqWasmTrack:
40    """A participant's track the transport subscribed to, for `on_track_subscribed`."""
41
42    participant_id: str
43    name: str
44    kind: Literal["audio", "video", "data"]

A participant's track the transport subscribed to, for on_track_subscribed.

MoqWasmTrack( participant_id: str, name: str, kind: Literal['audio', 'video', 'data'])
participant_id: str
name: str
kind: Literal['audio', 'video', 'data']
@dataclass(frozen=True)
class MoqWasmTrackMessage:
47@dataclass(frozen=True)
48class MoqWasmTrackMessage:
49    """An object of a participant's data track, the `message` of an `InputTransportMessageFrame`."""
50
51    participant_id: str
52    track: str
53    payload: bytes
54    location: Location

An object of a participant's data track, the message of an InputTransportMessageFrame.

MoqWasmTrackMessage( participant_id: str, track: str, payload: bytes, location: moq_wasm.Location)
participant_id: str
track: str
payload: bytes
location: moq_wasm.Location
@dataclass(frozen=True)
class MoqWasmTrackObject:
52@dataclass(frozen=True)
53class MoqWasmTrackObject:
54    """An object to write on one of the transport's `data_out_tracks`, the `message` of an
55    `OutputTransportMessageFrame`."""
56
57    track: str
58    payload: bytes
59    new_group: bool = True

An object to write on one of the transport's data_out_tracks, the message of an OutputTransportMessageFrame.

MoqWasmTrackObject(track: str, payload: bytes, new_group: bool = True)
track: str
payload: bytes
new_group: bool = True
class MoqWasmTransport(pipecat.transports.base_transport.BaseTransport):
1343class MoqWasmTransport(BaseTransport):
1344    """Pipecat transport backed by a `moq_wasm.Session` (each child namespace under `params.room` is a participant).
1345
1346    - **Events**: `on_connected`, `on_disconnected`, `on_client_connected(id)`, `on_client_disconnected(id)`,
1347      `on_track_subscribed(MoqWasmTrack)`, `on_error(message, exc)`, `on_room_empty`.
1348    - **Errors**: If opening the room fails, input and output emit a permanent `ErrorFrame`; configure
1349      `PipelineWorker(processor_unusable_policy=ProcessorUnusablePolicy.CANCEL)` (or `END`) to stop the pipeline.
1350      Leave errors emit a non-fatal `ErrorFrame` so shutdown still completes.
1351    - **Validation**: Raises `ValueError` for output destinations, `audio_in_filter` (use per-participant
1352      `MoqWasmParticipantInput` instead), non-mono/stereo `audio_out_channels`, `SoundfileMixer` with stereo,
1353      or non-positive `audio_out_10ms_chunks`. Snapshots `params` on init.
1354    - **Lifecycle**: Each `input()`/`output()` serves one pipeline run; after cleanup, calling `input()`/`output()`
1355      returns a fresh instance. `StopFrame` pauses without leaving the room and flushes queued audio/pictures
1356      (as does `PipelineWorker.flush_pipeline`).
1357    """
1358
1359    def __init__(
1360        self,
1361        session: Session,
1362        params: MoqWasmParams,
1363        input_name: str | None = None,
1364        output_name: str | None = None,
1365    ):
1366        super().__init__(input_name=input_name, output_name=output_name)
1367        params = _snapshot(params)
1368        if params.audio_out_destinations or params.video_out_destinations:
1369            raise ValueError("MoqWasmTransport publishes one broadcast: it takes no output destinations")
1370        if params.audio_in_filter is not None:
1371            raise ValueError(
1372                "MoqWasmTransport's input carries every participant's audio through one filter, which would mix"
1373                " their state: give each participant a MoqWasmParticipantInput with an audio_in_filter of its own"
1374            )
1375        if params.audio_out_channels not in (1, 2):
1376            raise ValueError("MoqWasmTransport takes mono or stereo output audio")
1377        if params.audio_out_channels != 1 and _has_soundfile_mixer(params.audio_out_mixer):
1378            raise ValueError(
1379                "pipecat's SoundfileMixer mixes its mono files into mono output audio only: set audio_out_channels=1"
1380            )
1381        # pipecat's media sender cuts the audio into chunks of this many 10 ms: with none, its loop
1382        # would queue empty chunks forever.
1383        if params.audio_out_10ms_chunks <= 0:
1384            raise ValueError("MoqWasmTransport takes a positive audio_out_10ms_chunks")
1385        self._params = params
1386        options = RoomOptions(
1387            room=params.room,
1388            participant_id=params.participant_id,
1389            broadcast=params.broadcast or [*params.room, params.participant_id],
1390            receive=_receive_options(params),
1391            audio_out=params.audio_out_enabled,
1392            video_out=params.video_out_enabled,
1393            video_out_codec=params.video_out_codec or DEFAULT_VIDEO_OUT_CODEC,
1394            video_out_size=(params.video_out_width, params.video_out_height),
1395            video_out_framerate=params.video_out_framerate,
1396            audio_out_bitrate=params.audio_out_bitrate,
1397            audio_out_channels=params.audio_out_channels,
1398            video_out_bitrate=params.video_out_bitrate,
1399            data_out_tracks=params.data_out_tracks,
1400            event_timelines_out=params.event_timelines_out,
1401            empty_timeout=params.empty_timeout,
1402        )
1403        self._room = Room(session, options, self)
1404        self._input: MoqWasmInputTransport | None = None
1405        self._output: MoqWasmOutputTransport | None = None
1406        for event in (
1407            "on_connected",
1408            "on_disconnected",
1409            "on_client_connected",
1410            "on_client_disconnected",
1411            "on_track_subscribed",
1412            "on_error",
1413            "on_room_empty",
1414        ):
1415            self._register_event_handler(event)
1416
1417    async def capture_participant_video(
1418        self,
1419        participant_id: str,
1420        framerate: int | None = 30,
1421        video_source: str = CAMERA_SOURCE,
1422        *,
1423        on_request_only: bool = False,
1424    ):
1425        """Receives a video source of a participant in the room at `framerate` pictures a second, or
1426        every picture when it is None, or only for image requests with `on_request_only`. As in
1427        pipecat, a `framerate` of 0 means `on_request_only`, and is deprecated."""
1428        if framerate == 0 and not on_request_only:
1429            warn_deprecated(
1430                "`MoqWasmTransport.capture_participant_video(framerate=0)` is deprecated since 1.13.0 and "
1431                "will be removed in 2.0.0. Use `on_request_only=True` instead.",
1432                stacklevel=2,
1433            )
1434        # The room takes None for request-only pictures and infinity for every picture.
1435        if on_request_only or framerate == 0:
1436            rate = None
1437        else:
1438            rate = float("inf") if framerate is None else framerate
1439        await self._room.capture(participant_id, video_source, rate)
1440
1441    async def release_participant_video(self, participant_id: str, video_source: str = CAMERA_SOURCE):
1442        """Stops receiving a video source of a participant, for a publisher that serves one profile to
1443        all its subscribers, such as ingest-gateway pull; the image requests waiting on it get an error.
1444        Returns once the source's track is unsubscribed, also when called again after a cancelled
1445        release. Not part of pipecat's API."""
1446        await self._room.release(participant_id, video_source)
1447
1448    def get_client_id(self, client: Any) -> str:
1449        """The participant id `on_client_connected` passed as `client`."""
1450        return client
1451
1452    def input(self) -> MoqWasmInputTransport:
1453        """The input of the pipeline being built: the same one until it ran, then a new one."""
1454        if self._input is None or self._input.ran:
1455            self._input = MoqWasmInputTransport(self._room, self._params, name=self._input_name)
1456        return self._input
1457
1458    def output(self) -> MoqWasmOutputTransport:
1459        """The output of the pipeline being built: the same one until it ran, then a new one."""
1460        if self._output is None or self._output.ran:
1461            self._output = MoqWasmOutputTransport(self._room, self._params, name=self._output_name)
1462        return self._output
1463
1464    def _receiving_input(self) -> MoqWasmInputTransport:
1465        """The input the room's participants go to: the latest one, even once it ran, so a
1466        participant's media arriving as its pipeline ends makes no input for the next pipeline."""
1467        return self._input if self._input is not None else self.input()
1468
1469    def audio_in_sample_rate(self) -> int:
1470        return self._receiving_input().audio_in_sample_rate()
1471
1472    async def push_audio(self, pcm: bytes, sample_rate: int, participant_id: str) -> None:
1473        await self._receiving_input().push_audio(pcm, sample_rate, participant_id)
1474
1475    async def push_picture(self, picture: ReceivedPicture) -> bool:
1476        return await self._receiving_input().push_picture(picture)
1477
1478    async def push_message(self, message: MoqWasmTrackMessage) -> None:
1479        await self._receiving_input().push_message(message)
1480
1481    async def answer_image_requests(self, requests: list[UserImageRequestFrame], error: str) -> None:
1482        await self._receiving_input().answer_image_requests(requests, error)
1483
1484    async def event(self, name: str, *args: object) -> None:
1485        await self._call_event_handler(name, *args)

Pipecat transport backed by a moq_wasm.Session (each child namespace under params.room is a participant).

  • Events: on_connected, on_disconnected, on_client_connected(id), on_client_disconnected(id), on_track_subscribed(MoqWasmTrack), on_error(message, exc), on_room_empty.
  • Errors: If opening the room fails, input and output emit a permanent ErrorFrame; configure PipelineWorker(processor_unusable_policy=ProcessorUnusablePolicy.CANCEL) (or END) to stop the pipeline. Leave errors emit a non-fatal ErrorFrame so shutdown still completes.
  • Validation: Raises ValueError for output destinations, audio_in_filter (use per-participant MoqWasmParticipantInput instead), non-mono/stereo audio_out_channels, SoundfileMixer with stereo, or non-positive audio_out_10ms_chunks. Snapshots params on init.
  • Lifecycle: Each input()/output() serves one pipeline run; after cleanup, calling input()/output() returns a fresh instance. StopFrame pauses without leaving the room and flushes queued audio/pictures (as does PipelineWorker.flush_pipeline).
MoqWasmTransport( session: moq_wasm.Session, params: MoqWasmParams, input_name: str | None = None, output_name: str | None = None)
1359    def __init__(
1360        self,
1361        session: Session,
1362        params: MoqWasmParams,
1363        input_name: str | None = None,
1364        output_name: str | None = None,
1365    ):
1366        super().__init__(input_name=input_name, output_name=output_name)
1367        params = _snapshot(params)
1368        if params.audio_out_destinations or params.video_out_destinations:
1369            raise ValueError("MoqWasmTransport publishes one broadcast: it takes no output destinations")
1370        if params.audio_in_filter is not None:
1371            raise ValueError(
1372                "MoqWasmTransport's input carries every participant's audio through one filter, which would mix"
1373                " their state: give each participant a MoqWasmParticipantInput with an audio_in_filter of its own"
1374            )
1375        if params.audio_out_channels not in (1, 2):
1376            raise ValueError("MoqWasmTransport takes mono or stereo output audio")
1377        if params.audio_out_channels != 1 and _has_soundfile_mixer(params.audio_out_mixer):
1378            raise ValueError(
1379                "pipecat's SoundfileMixer mixes its mono files into mono output audio only: set audio_out_channels=1"
1380            )
1381        # pipecat's media sender cuts the audio into chunks of this many 10 ms: with none, its loop
1382        # would queue empty chunks forever.
1383        if params.audio_out_10ms_chunks <= 0:
1384            raise ValueError("MoqWasmTransport takes a positive audio_out_10ms_chunks")
1385        self._params = params
1386        options = RoomOptions(
1387            room=params.room,
1388            participant_id=params.participant_id,
1389            broadcast=params.broadcast or [*params.room, params.participant_id],
1390            receive=_receive_options(params),
1391            audio_out=params.audio_out_enabled,
1392            video_out=params.video_out_enabled,
1393            video_out_codec=params.video_out_codec or DEFAULT_VIDEO_OUT_CODEC,
1394            video_out_size=(params.video_out_width, params.video_out_height),
1395            video_out_framerate=params.video_out_framerate,
1396            audio_out_bitrate=params.audio_out_bitrate,
1397            audio_out_channels=params.audio_out_channels,
1398            video_out_bitrate=params.video_out_bitrate,
1399            data_out_tracks=params.data_out_tracks,
1400            event_timelines_out=params.event_timelines_out,
1401            empty_timeout=params.empty_timeout,
1402        )
1403        self._room = Room(session, options, self)
1404        self._input: MoqWasmInputTransport | None = None
1405        self._output: MoqWasmOutputTransport | None = None
1406        for event in (
1407            "on_connected",
1408            "on_disconnected",
1409            "on_client_connected",
1410            "on_client_disconnected",
1411            "on_track_subscribed",
1412            "on_error",
1413            "on_room_empty",
1414        ):
1415            self._register_event_handler(event)

Initialize the base transport.

Args: name: Optional name for the transport instance. input_name: Optional name for the input processor. output_name: Optional name for the output processor.

async def capture_participant_video( self, participant_id: str, framerate: int | None = 30, video_source: str = 'camera', *, on_request_only: bool = False):
1417    async def capture_participant_video(
1418        self,
1419        participant_id: str,
1420        framerate: int | None = 30,
1421        video_source: str = CAMERA_SOURCE,
1422        *,
1423        on_request_only: bool = False,
1424    ):
1425        """Receives a video source of a participant in the room at `framerate` pictures a second, or
1426        every picture when it is None, or only for image requests with `on_request_only`. As in
1427        pipecat, a `framerate` of 0 means `on_request_only`, and is deprecated."""
1428        if framerate == 0 and not on_request_only:
1429            warn_deprecated(
1430                "`MoqWasmTransport.capture_participant_video(framerate=0)` is deprecated since 1.13.0 and "
1431                "will be removed in 2.0.0. Use `on_request_only=True` instead.",
1432                stacklevel=2,
1433            )
1434        # The room takes None for request-only pictures and infinity for every picture.
1435        if on_request_only or framerate == 0:
1436            rate = None
1437        else:
1438            rate = float("inf") if framerate is None else framerate
1439        await self._room.capture(participant_id, video_source, rate)

Receives a video source of a participant in the room at framerate pictures a second, or every picture when it is None, or only for image requests with on_request_only. As in pipecat, a framerate of 0 means on_request_only, and is deprecated.

async def release_participant_video(self, participant_id: str, video_source: str = 'camera'):
1441    async def release_participant_video(self, participant_id: str, video_source: str = CAMERA_SOURCE):
1442        """Stops receiving a video source of a participant, for a publisher that serves one profile to
1443        all its subscribers, such as ingest-gateway pull; the image requests waiting on it get an error.
1444        Returns once the source's track is unsubscribed, also when called again after a cancelled
1445        release. Not part of pipecat's API."""
1446        await self._room.release(participant_id, video_source)

Stops receiving a video source of a participant, for a publisher that serves one profile to all its subscribers, such as ingest-gateway pull; the image requests waiting on it get an error. Returns once the source's track is unsubscribed, also when called again after a cancelled release. Not part of pipecat's API.

def get_client_id(self, client: Any) -> str:
1448    def get_client_id(self, client: Any) -> str:
1449        """The participant id `on_client_connected` passed as `client`."""
1450        return client

The participant id on_client_connected passed as client.

def input(self) -> MoqWasmInputTransport:
1452    def input(self) -> MoqWasmInputTransport:
1453        """The input of the pipeline being built: the same one until it ran, then a new one."""
1454        if self._input is None or self._input.ran:
1455            self._input = MoqWasmInputTransport(self._room, self._params, name=self._input_name)
1456        return self._input

The input of the pipeline being built: the same one until it ran, then a new one.

def output(self) -> MoqWasmOutputTransport:
1458    def output(self) -> MoqWasmOutputTransport:
1459        """The output of the pipeline being built: the same one until it ran, then a new one."""
1460        if self._output is None or self._output.ran:
1461            self._output = MoqWasmOutputTransport(self._room, self._params, name=self._output_name)
1462        return self._output

The output of the pipeline being built: the same one until it ran, then a new one.

def audio_in_sample_rate(self) -> int:
1469    def audio_in_sample_rate(self) -> int:
1470        return self._receiving_input().audio_in_sample_rate()
async def push_audio(self, pcm: bytes, sample_rate: int, participant_id: str) -> None:
1472    async def push_audio(self, pcm: bytes, sample_rate: int, participant_id: str) -> None:
1473        await self._receiving_input().push_audio(pcm, sample_rate, participant_id)
async def push_picture(self, picture: moq_wasm.pipecat._participant.ReceivedPicture) -> bool:
1475    async def push_picture(self, picture: ReceivedPicture) -> bool:
1476        return await self._receiving_input().push_picture(picture)
async def push_message(self, message: MoqWasmTrackMessage) -> None:
1478    async def push_message(self, message: MoqWasmTrackMessage) -> None:
1479        await self._receiving_input().push_message(message)
async def answer_image_requests( self, requests: list[pipecat.frames.frames.UserImageRequestFrame], error: str) -> None:
1481    async def answer_image_requests(self, requests: list[UserImageRequestFrame], error: str) -> None:
1482        await self._receiving_input().answer_image_requests(requests, error)
async def event(self, name: str, *args: object) -> None:
1484    async def event(self, name: str, *args: object) -> None:
1485        await self._call_event_handler(name, *args)