Skip to main content

moq_ext_publisher/
publish.rs

1//! Publishing: a broadcast that exists apart from any transport.
2//!
3//! The video slot opens its source once and encodes it into every rendition of
4//! a ladder. Each rendition encodes only while someone watches it.
5
6use std::{
7    collections::VecDeque,
8    sync::{
9        Arc, Mutex,
10        atomic::{AtomicBool, AtomicU64, Ordering},
11    },
12    time::{Duration, Instant},
13};
14
15use moq_ext_json::ValueWriter;
16use moq_ext_sources::{
17    AudioSource, ByPtr, EncodedAudio, EncodedFrame, EncodedVideo, Error, SlotState, VideoSource,
18};
19use moq_net::Consume;
20use n0_future::{StreamExt, boxed::BoxStream, task::AbortOnDropHandle};
21use tokio::sync::watch;
22use tokio_util::sync::CancellationToken;
23use tracing::{Instrument, Span, debug, info, info_span, warn};
24
25use self::status::{Medium, StatusCell};
26pub use self::{
27    encoding::{AudioEncoding, VideoEncoding, VideoRendition, music, pcm, voice},
28    spec::MediaEncoding,
29    status::{PublishStatus, RenditionState},
30};
31use crate::stats::{PublishRecorder, PublishStats};
32
33/// Returns `timestamp` in microseconds.
34///
35/// Media timestamps always carry a time; only a scale-less track's key has
36/// none, and that reads as zero.
37pub(crate) fn micros(timestamp: moq_net::Timestamp) -> u128 {
38    timestamp.as_micros().unwrap_or(0)
39}
40
41mod audio;
42mod cuts;
43mod encoding;
44mod spec;
45pub(crate) mod status;
46mod video;
47
48/// A running slot task.
49///
50/// Dropping it cancels and aborts the task.
51#[derive(Debug)]
52pub(crate) struct SlotTask {
53    stop: CancellationToken,
54    /// Whether the task hands its tracks to its successor when it stops.
55    ///
56    /// [`hand_over`](Self::hand_over) sets it before `stop`, and the task
57    /// reads it once stopped.
58    handing_over: Arc<AtomicBool>,
59    task: Option<AbortOnDropHandle<()>>,
60}
61
62impl SlotTask {
63    /// Spawns `run` with a stop token that is a child of `closed`.
64    fn spawn<F, Fut>(
65        span: Span,
66        closed: &CancellationToken,
67        handing_over: Arc<AtomicBool>,
68        run: F,
69    ) -> Self
70    where
71        F: FnOnce(CancellationToken) -> Fut,
72        Fut: std::future::Future<Output = ()> + Send + 'static,
73    {
74        let stop = closed.child_token();
75        let task = n0_future::task::spawn(run(stop.clone()).instrument(span));
76        Self {
77            stop,
78            handing_over,
79            task: Some(AbortOnDropHandle::new(task)),
80        }
81    }
82
83    /// Stops the task for a successor, and waits at most `patience` for it to finish.
84    ///
85    /// A video task leaves its rendition tracks open for the successor to take
86    /// over, so subscribers keep their tracks. Other tasks finish theirs, as
87    /// [`finish`](Self::finish) does.
88    async fn hand_over(self, patience: Duration) {
89        self.handing_over.store(true, Ordering::Release);
90        self.finish(patience).await;
91    }
92
93    /// Stops the task and waits at most `patience` for it to finish.
94    ///
95    /// A task that finishes in time ends its tracks cleanly, so subscribers see
96    /// an end instead of a reset. A slower task is aborted.
97    pub(crate) async fn finish(mut self, patience: Duration) {
98        self.stop.cancel();
99        let Some(task) = self.task.take() else {
100            return;
101        };
102        if tokio::time::timeout(patience, task).await.is_err() {
103            debug!(
104                ?patience,
105                "a publish task did not finish in time and was aborted"
106            );
107        }
108    }
109}
110
111impl Drop for SlotTask {
112    fn drop(&mut self) {
113        self.stop.cancel();
114    }
115}
116
117/// How long a replaced or closed publish task gets to finish its tracks.
118const FINISH_PATIENCE: Duration = Duration::from_secs(2);
119
120/// Everything a slot task needs.
121struct Job {
122    producer: moq_net::broadcast::Producer,
123    catalog: moq_mux::catalog::Producer,
124    clock: moq_mux::Clock,
125    /// Where the video task records the source timestamp of each frame it publishes.
126    timestamps: TimestampLog,
127    /// Held while the task owns its track names.
128    tracks: Arc<tokio::sync::Mutex<()>>,
129    /// The tracks a replaced video task left open, for this one to take over.
130    handovers: video::Handovers,
131    handing_over: Arc<AtomicBool>,
132    stats: PublishRecorder,
133    reporter: status::Reporter,
134    /// The task this one replaces. It stops before the track names are taken.
135    predecessor: Option<SlotTask>,
136}
137
138impl Job {
139    /// Reports the slot running, with `rendition` publishing pre-encoded frames.
140    fn report_pre_encoded(&self, rendition: &str) {
141        self.reporter.slot(SlotState::Running);
142        self.reporter.rendition(
143            rendition,
144            status::RenditionState::Encoding {
145                encoder: "pre-encoded".to_string(),
146            },
147        );
148    }
149
150    /// Stops the predecessor, then locks the track names.
151    ///
152    /// Returns `None` if `stop` fires first. Tracks the predecessor left for
153    /// this task then stay for the next successor if there is one, and finish
154    /// otherwise.
155    async fn take_over(
156        &mut self,
157        stop: &CancellationToken,
158    ) -> Option<tokio::sync::OwnedMutexGuard<()>> {
159        let taken = async {
160            if let Some(predecessor) = self.predecessor.take() {
161                predecessor.hand_over(FINISH_PATIENCE).await;
162            }
163            self.tracks.clone().lock_owned().await
164        };
165        tokio::select! {
166            guard = taken => Some(guard),
167            () = stop.cancelled() => {
168                if !self.handing_over.load(Ordering::Acquire) {
169                    video::finish_handovers(&self.handovers);
170                }
171                None
172            }
173        }
174    }
175}
176
177/// How far past the broadcast clock a mapped timestamp may land before it counts as a break.
178///
179/// A source stamps a frame when it captures it, so its frames land at or
180/// before the clock's current time. One that lands later than this came from
181/// another timeline.
182const MAX_AHEAD: Duration = Duration::from_secs(1);
183
184/// The number of published video frames whose timestamps a broadcast keeps.
185///
186/// A broadcast keeps them only with [`VideoEncoding::record_timestamps`] on.
187/// The frames cover about 17 s at 30 fps and 8 s at 60 fps, several times what
188/// a subscriber needs to echo a timestamp back. An entry is two timestamps and
189/// two instants, 64 bytes, so a full log takes 32 KiB per broadcast. No pixels
190/// and no encoded data are kept.
191///
192/// [`VideoEncoding::record_timestamps`]: crate::VideoEncoding::record_timestamps
193const TIMESTAMP_HISTORY: usize = 512;
194
195/// What a [`TimestampLog`] keeps of one published frame.
196#[derive(Debug, Clone, Copy)]
197struct Logged {
198    /// The timestamp the source gave the frame.
199    source: moq_net::Timestamp,
200    /// When the frame entered the source, if known.
201    captured_at: Option<Instant>,
202    /// When the first rendition published the frame's encoded data.
203    encoded_at: Option<Instant>,
204}
205
206/// The source timestamp and capture instant of recently published video frames.
207///
208/// A ring of at most [`TIMESTAMP_HISTORY`] entries, sorted by broadcast
209/// timestamp. Broadcast timestamps rise, so an entry almost always goes at the
210/// end. A slower rendition that publishes a frame the others skipped inserts
211/// it a little before the end. The ring stays empty unless the video records
212/// its timestamps. Every rendition publishes a picture at the same broadcast
213/// timestamp, so the renditions of a ladder share one entry.
214#[derive(Debug, Clone, Default)]
215struct TimestampLog(Arc<Mutex<VecDeque<(moq_net::Timestamp, Logged)>>>);
216
217impl TimestampLog {
218    /// Records that the frame stamped `source`, captured at `captured_at`, was published at `published`.
219    ///
220    /// The first rendition to publish a frame records it. Forgets the oldest
221    /// entry past [`TIMESTAMP_HISTORY`].
222    fn record(
223        &self,
224        published: moq_net::Timestamp,
225        source: moq_net::Timestamp,
226        captured_at: Option<Instant>,
227    ) {
228        let mut log = self.0.lock().expect("poisoned");
229        let at = log.partition_point(|(logged, _)| *logged < published);
230        if log.get(at).is_some_and(|(logged, _)| *logged == published) {
231            return;
232        }
233        log.insert(
234            at,
235            (
236                published,
237                Logged {
238                    source,
239                    captured_at,
240                    encoded_at: None,
241                },
242            ),
243        );
244        if log.len() > TIMESTAMP_HISTORY {
245            log.pop_front();
246        }
247    }
248
249    /// Records that the frame published at `published` left an encoder at `at`.
250    ///
251    /// The first rendition to publish the frame records it.
252    fn encoded(&self, published: moq_net::Timestamp, at: Instant) {
253        let mut log = self.0.lock().expect("poisoned");
254        if let Ok(index) =
255            log.binary_search_by_key(&micros(published), |(logged, _)| micros(*logged))
256        {
257            log[index].1.encoded_at.get_or_insert(at);
258        }
259    }
260
261    /// Returns what was recorded of the frame published at `published`.
262    fn get(&self, published: moq_net::Timestamp) -> Option<Logged> {
263        let log = self.0.lock().expect("poisoned");
264        let at = log
265            .binary_search_by_key(&micros(published), |(logged, _)| micros(*logged))
266            .ok()?;
267        Some(log[at].1)
268    }
269
270    /// Returns the source timestamp of the frame published at `published`.
271    fn source(&self, published: moq_net::Timestamp) -> Option<moq_net::Timestamp> {
272        self.get(published).map(|logged| logged.source)
273    }
274}
275
276/// A mapping of a source's timestamps onto the broadcast clock.
277///
278/// The first frame lands at the clock's current time, and later frames keep
279/// the source's own cadence. A timeline breaks when a frame would land at or
280/// before the previous one, or more than [`MAX_AHEAD`] past the clock, as when
281/// an application pushes another device into the same source. The next frame
282/// then lands at the current time again, so the broadcast never goes back.
283///
284/// Clones share the anchor, so every rendition of a ladder carries the same
285/// timestamp for the same picture. Each clone keeps its own last timestamp.
286#[derive(Debug, Clone)]
287struct SourceClock {
288    clock: moq_mux::Clock,
289    anchor: Arc<Mutex<Anchor>>,
290    /// The last timestamp this clone mapped.
291    last: Option<moq_net::Timestamp>,
292    /// The breaks this clone has seen, to tell it about a new one once.
293    breaks: u64,
294    /// Where each mapping is recorded, for a clock that records them.
295    log: Option<TimestampLog>,
296}
297
298/// Where a [`SourceClock`] is anchored.
299#[derive(Debug, Default)]
300struct Anchor {
301    /// Broadcast micros minus source micros, unset before the first frame.
302    offset: Option<i128>,
303    /// How many times the source's timeline broke.
304    breaks: u64,
305}
306
307impl SourceClock {
308    /// Creates a source clock on `clock` that anchors at its first frame.
309    fn new(clock: moq_mux::Clock) -> Self {
310        Self {
311            clock,
312            anchor: Default::default(),
313            last: None,
314            breaks: 0,
315            log: None,
316        }
317    }
318
319    /// Records every mapping in `log`.
320    fn recording(mut self, log: TimestampLog) -> Self {
321        self.log = Some(log);
322        self
323    }
324
325    /// Reports whether the source's timeline broke since this clone last asked.
326    ///
327    /// An encoder starts a new group there, so the new source starts with a
328    /// keyframe instead of a delta on a picture of another source.
329    fn broke(&mut self) -> bool {
330        let breaks = self.anchor.lock().expect("poisoned").breaks;
331        std::mem::replace(&mut self.breaks, breaks) != breaks
332    }
333
334    /// Continues after `last`, the last timestamp a predecessor published on the same track.
335    fn after(mut self, last: Option<moq_net::Timestamp>) -> Self {
336        self.last = last;
337        self
338    }
339
340    /// Records in the log, if any, that the frame published at `published` left the encoder now.
341    fn encoded(&self, published: moq_net::Timestamp) {
342        if let Some(log) = &self.log {
343            log.encoded(published, Instant::now());
344        }
345    }
346
347    /// Returns the last timestamp this clone mapped.
348    fn last(&self) -> Option<moq_net::Timestamp> {
349        self.last
350    }
351
352    /// Returns `timestamp` on the broadcast clock, anchoring again if the source's timeline broke.
353    ///
354    /// `captured_at` is when the frame entered its source, for the log.
355    fn map(
356        &mut self,
357        timestamp: moq_net::Timestamp,
358        captured_at: Option<Instant>,
359    ) -> moq_net::Timestamp {
360        let now = micros(self.clock.now()) as i128;
361        let source = micros(timestamp) as i128;
362        let last = self.last.map(|last| micros(last) as i128);
363        let fits = |offset: i128| {
364            let mapped = source + offset;
365            last.is_none_or(|last| mapped > last) && mapped <= now + MAX_AHEAD.as_micros() as i128
366        };
367        let offset = {
368            let mut anchor = self.anchor.lock().expect("poisoned");
369            match anchor.offset {
370                Some(offset) if fits(offset) => offset,
371                previous => {
372                    let at = last.map_or(now, |last| now.max(last + 1));
373                    if let Some(previous) = previous {
374                        info!(
375                            source_us = source,
376                            jump_us = at - (source + previous),
377                            "the source's timeline broke, anchoring it at the broadcast clock again"
378                        );
379                        anchor.breaks += 1;
380                    }
381                    anchor.offset = Some(at - source);
382                    at - source
383                }
384            }
385        };
386        let micros = u64::try_from(source + offset).unwrap_or(0);
387        let mapped = moq_net::Timestamp::from_micros(micros).unwrap_or(timestamp);
388        self.last = Some(mapped);
389        if let Some(log) = &self.log {
390            log.record(mapped, timestamp, captured_at);
391        }
392        mapped
393    }
394}
395
396/// Publishes `frames` through `import` until they end or `stop` is cancelled.
397///
398/// Reports the slot running and `rendition` encoding at the first frame,
399/// and hands the track and the size of each frame to `per_frame`. Returns
400/// how many frames went out.
401async fn pump_frames(
402    job: &Job,
403    rendition: &str,
404    mut frames: BoxStream<Result<EncodedFrame, Error>>,
405    mut import: moq_mux::import::Track,
406    stop: &CancellationToken,
407    mut per_frame: impl FnMut(&mut moq_mux::import::Track, usize) -> Result<(), Error>,
408) -> Result<u64, Error> {
409    let mut offset = None;
410    let mut published = 0u64;
411    loop {
412        let frame = tokio::select! {
413            frame = frames.next() => frame.transpose()?,
414            () = stop.cancelled() => None,
415        };
416        let Some(frame) = frame else { break };
417        let size = frame.data.len();
418        let timestamp = wall_map(&mut offset, &job.clock, &frame);
419        import
420            .decode(frame.data, Some(timestamp))
421            .map_err(Error::decoder)?;
422        if published == 0 {
423            job.report_pre_encoded(rendition);
424        }
425        published += 1;
426        per_frame(&mut import, size)?;
427    }
428    // Dropping the finished track releases it.
429    let _finished = import.finish().map_err(Error::catalog)?;
430    Ok(published)
431}
432
433/// Returns the broadcast timestamp of `frame`, a frame of a pre-encoded stream.
434///
435/// `offset` comes from the wall-clock instant of the stream's first frame,
436/// so two streams whose frames agree on their instants, such as the audio
437/// and video of one file, stay in sync whenever each starts. Later frames
438/// keep the stream's own spacing, B-frame order included.
439fn wall_map(
440    offset: &mut Option<i128>,
441    clock: &moq_mux::Clock,
442    frame: &EncodedFrame,
443) -> moq_net::Timestamp {
444    let source = micros(frame.timestamp) as i128;
445    let offset = *offset.get_or_insert_with(|| {
446        // Tokio's clock, which the producer of a file uses too.
447        let now = tokio::time::Instant::now().into_std();
448        let ahead = frame.at.saturating_duration_since(now).as_micros() as i128
449            - now.saturating_duration_since(frame.at).as_micros() as i128;
450        micros(clock.now()) as i128 + ahead - source
451    });
452    let mapped = u64::try_from(source + offset).unwrap_or(0);
453    moq_net::Timestamp::from_micros(mapped).unwrap_or(frame.timestamp)
454}
455
456/// Reports how a pre-encoded stream that published `frames` frames, or failed, ended.
457///
458/// A stream that ends before its first frame never described itself. That
459/// is a failed source, not a finished stream.
460fn report_encoded_end(reporter: &status::Reporter, result: Result<u64, Error>, medium: &str) {
461    match result {
462        Ok(0) => reporter.slot(SlotState::Failed(ByPtr::new(Error::device_msg(format!(
463            "the pre-encoded {medium} ended before its first frame"
464        ))))),
465        Ok(frames) => {
466            debug!(frames, medium, "pre-encoded source ended");
467            reporter.slot(SlotState::Ended);
468        }
469        Err(err) => {
470            warn!(
471                error = format_args!("{err:#}"),
472                medium, "pre-encoded source failed"
473            );
474            reporter.slot(SlotState::Failed(ByPtr::new(err)));
475        }
476    }
477}
478
479/// The task a slot is running, with its generation and what it encodes.
480#[derive(Debug)]
481struct Slot {
482    generation: u64,
483    task: SlotTask,
484    source: SlotSource,
485}
486
487/// What a slot encodes, kept so the broadcast can hand it back.
488#[derive(Debug, Clone)]
489enum SlotSource {
490    Video(VideoSource),
491    Audio(AudioSource),
492    /// A pre-encoded stream, which has no raw source.
493    Encoded,
494}
495
496/// The state every clone of a [`LocalBroadcast`] shares.
497#[derive(derive_more::Debug)]
498#[debug("Shared {{ status: {status:?} }}")]
499struct Shared {
500    producer: moq_net::broadcast::Producer,
501    catalog: Mutex<moq_mux::catalog::Producer>,
502    clock: moq_mux::Clock,
503    /// The source timestamps and capture instants of the published video.
504    ///
505    /// [`LocalBroadcast::video_source_timestamp`] and
506    /// [`LocalBroadcast::video_captured_at`] and
507    /// [`LocalBroadcast::video_encoded_at`] read it.
508    video_timestamps: TimestampLog,
509    video: Mutex<Option<Slot>>,
510    audio: Mutex<Option<Slot>>,
511    /// Held by a video task while it owns track names, for a replacement to wait on.
512    video_tracks: Arc<tokio::sync::Mutex<()>>,
513    /// The same for audio, whose track name does not change on replacement.
514    audio_tracks: Arc<tokio::sync::Mutex<()>>,
515    /// The tracks a replaced video task left open for its successor.
516    video_handovers: video::Handovers,
517    generations: AtomicU64,
518    status: StatusCell,
519    stats: PublishRecorder,
520    /// Cancelled by `close`. Every publish task watches it.
521    closed: CancellationToken,
522    /// Cancelled once `close` has finished every track and the broadcast.
523    finished: CancellationToken,
524    /// The task `close` runs, held so it is not detached.
525    closer: Mutex<Option<AbortOnDropHandle<()>>>,
526    /// Cleared slots finishing their tracks, held so they are not detached.
527    retiring: Mutex<n0_future::task::JoinSet<()>>,
528    span: Span,
529}
530
531impl Shared {
532    /// Finishes the catalog and closes the broadcast.
533    fn end(&self) {
534        if let Err(err) = self.catalog.lock().expect("poisoned").finish() {
535            debug!(error = %err, "catalog did not finish cleanly");
536        }
537        self.producer.close();
538    }
539}
540
541impl Drop for Shared {
542    fn drop(&mut self) {
543        // The last handle is gone without `close`. End the broadcast so
544        // subscribers see it end instead of waiting on it.
545        self.closed.cancel();
546        self.end();
547    }
548}
549
550/// A broadcast this process produces.
551///
552/// It holds a catalog, a media clock, one video slot and one audio slot. A
553/// transport that publishes it hands it the broadcast to fill: build it with
554/// [`new_in`](Self::new_in) or `TryFrom<broadcast::Producer>`, as `iroh-live`'s
555/// `publish` does. A standalone one from [`new`](Self::new) reads in-process
556/// through [`consume`](Self::consume).
557///
558/// Cloning is cheap. [`close`](Self::close) ends the broadcast for every clone.
559/// The setters spawn an encoding task, so call them from within a Tokio
560/// runtime.
561///
562/// Dropping the last clone ends the broadcast without waiting: it aborts the
563/// encoding tasks and closes the catalog and the broadcast.
564#[derive(Debug, Clone)]
565pub struct LocalBroadcast {
566    shared: Arc<Shared>,
567}
568
569impl Default for LocalBroadcast {
570    fn default() -> Self {
571        Self::new()
572    }
573}
574
575impl TryFrom<moq_net::broadcast::Producer> for LocalBroadcast {
576    type Error = Error;
577
578    /// Fills `producer`, as [`LocalBroadcast::new_in`] does.
579    fn try_from(producer: moq_net::broadcast::Producer) -> Result<Self, Error> {
580        Self::new_in(producer)
581    }
582}
583
584impl LocalBroadcast {
585    /// Creates an empty broadcast of its own, published nowhere.
586    ///
587    /// For a local preview, a test, or a transport that takes any
588    /// `broadcast::Consumer`.
589    #[must_use]
590    pub fn new() -> Self {
591        Self::new_in(moq_net::broadcast::Info::new().produce())
592            .expect("a new broadcast has no catalog track and is open")
593    }
594
595    /// Creates an empty broadcast that fills `producer`.
596    ///
597    /// Pass the broadcast a transport created for publishing, such as an
598    /// `iroh_live_node::Publication`'s: its readers read what this writes, with
599    /// nothing copied in between. Closing this closes `producer`, which
600    /// withdraws the publication.
601    ///
602    /// # Errors
603    ///
604    /// Returns [`Error::Broadcast`] if `producer` already holds a catalog
605    /// track, or is closed.
606    pub fn new_in(mut producer: moq_net::broadcast::Producer) -> Result<Self, Error> {
607        // The catalog advertises the clock's wall mapping, so it is built with
608        // the clock that stamps the media.
609        let clock = moq_mux::Clock::new();
610        let config = moq_mux::catalog::Config::default()
611            .with_catalog(hang::catalog::Catalog::default())
612            .with_clock(clock.clone());
613        let catalog =
614            moq_mux::catalog::Producer::new(&mut producer, config).map_err(Error::broadcast)?;
615        let span = info_span!("broadcast");
616        Ok(Self {
617            shared: Arc::new(Shared {
618                producer,
619                catalog: Mutex::new(catalog),
620                clock,
621                video_timestamps: TimestampLog::default(),
622                video: Mutex::new(None),
623                audio: Mutex::new(None),
624                video_tracks: Default::default(),
625                audio_tracks: Default::default(),
626                video_handovers: Default::default(),
627                generations: AtomicU64::new(0),
628                status: StatusCell::default(),
629                stats: PublishRecorder::default(),
630                closed: CancellationToken::new(),
631                finished: CancellationToken::new(),
632                closer: Mutex::new(None),
633                retiring: Mutex::new(n0_future::task::JoinSet::new()),
634                span,
635            }),
636        })
637    }
638
639    /// Encodes `source` into every rendition of `encoding`, replacing the current video.
640    ///
641    /// Returns once the encoding task has started. Its progress shows in
642    /// [`status`](Self::status).
643    ///
644    /// A rendition with the name of one the replaced video published goes on
645    /// in the same track, so its viewers see the new source from its first
646    /// keyframe without subscribing again. If the new encoder's stream needs
647    /// another decoder, for example a new H.264 level after a switch to a
648    /// larger source, the rendition moves to a newly named track such as
649    /// `video/1`, and a player in automatic mode follows the catalog to it.
650    /// Renditions the new ladder lacks end.
651    ///
652    /// # Errors
653    ///
654    /// Fails on invalid configuration: an empty ladder, duplicate rendition
655    /// names, a rate above the source's, or a codec no compiled-in encoder
656    /// supports. Returns [`Error::Closed`] after [`close`](Self::close).
657    ///
658    /// # Panics
659    ///
660    /// Panics when called outside a Tokio runtime.
661    pub fn set_video(&self, source: VideoSource, encoding: VideoEncoding) -> Result<(), Error> {
662        self.check_open()?;
663        encoding.validate(source.format().rate)?;
664        let names: Vec<String> = encoding
665            .renditions
666            .iter()
667            .map(|rendition| rendition.name.clone())
668            .collect();
669        info!(parent: &self.shared.span, source = source.label(), renditions = ?names, "video set");
670        let kept = SlotSource::Video(source.clone());
671        self.replace(Medium::Video, names, kept, move |job, stop| {
672            video::run_raw(job, source, encoding, stop)
673        });
674        Ok(())
675    }
676
677    /// Publishes pre-encoded H.264 as the one video rendition, `video`, replacing the current video.
678    ///
679    /// The source is an Annex-B byte stream, such as `rpicam_h264` returns, or
680    /// the access units of a file, such as `MediaFile::encoded_video` returns,
681    /// which also lists the trade-offs of publishing without an encoder. The
682    /// stream's own parameter sets describe the rendition, so an Annex-B
683    /// stream should repeat them before every keyframe. A source that ends
684    /// before its first access unit shows as failed in
685    /// [`status`](Self::status). Whatever produces the frames stops when the
686    /// broadcast drops the source.
687    ///
688    /// # Errors
689    ///
690    /// Returns [`Error::Closed`] after [`close`](Self::close).
691    ///
692    /// # Panics
693    ///
694    /// Panics when called outside a Tokio runtime.
695    pub fn set_encoded_video(&self, source: EncodedVideo) -> Result<(), Error> {
696        self.check_open()?;
697        info!(parent: &self.shared.span, "pre-encoded video set");
698        self.replace(
699            Medium::Video,
700            vec![video::ENCODED_RENDITION.to_string()],
701            SlotSource::Encoded,
702            move |job, stop| video::run_encoded(job, source, stop),
703        );
704        Ok(())
705    }
706
707    /// Publishes pre-encoded audio as it is, replacing the current audio.
708    ///
709    /// For the AAC of a file, as `MediaFile::encoded_audio` returns it. Each
710    /// frame goes out in a group of its own. A source that ends before its
711    /// first frame shows as failed in [`status`](Self::status).
712    ///
713    /// # Errors
714    ///
715    /// Returns [`Error::Closed`] after [`close`](Self::close).
716    ///
717    /// # Panics
718    ///
719    /// Panics when called outside a Tokio runtime.
720    pub fn set_encoded_audio(&self, source: EncodedAudio) -> Result<(), Error> {
721        self.check_open()?;
722        info!(parent: &self.shared.span, "pre-encoded audio set");
723        self.replace(
724            Medium::Audio,
725            vec![moq_mux::import::AudioFormat::Aac.to_string()],
726            SlotSource::Encoded,
727            move |job, stop| audio::run_encoded(job, source, stop),
728        );
729        Ok(())
730    }
731
732    /// Publishes the H.264 video and the AAC audio of `file` as they are.
733    ///
734    /// Either track may be missing. A track in another codec is left out with
735    /// a warning, and the slot of a missing or left-out track keeps what it
736    /// had. `MediaFile::encoded_video` lists the trade-offs against decoding
737    /// the file.
738    ///
739    /// # Errors
740    ///
741    /// Returns [`Error::InvalidConfig`] if the file has neither H.264 video
742    /// nor AAC audio, and [`Error::Closed`] after [`close`](Self::close).
743    ///
744    /// # Panics
745    ///
746    /// Panics when called outside a Tokio runtime.
747    #[cfg(feature = "file")]
748    pub fn set_encoded_file(&self, file: &moq_ext_sources::MediaFile) -> Result<(), Error> {
749        self.check_open()?;
750        let info = file.info();
751        let video = info.video.as_ref().map(|_| file.encoded_video());
752        let audio = info.audio.as_ref().map(|_| file.encoded_audio());
753        let video_err = video.as_ref().and_then(|video| video.as_ref().err());
754        let audio_err = audio.as_ref().and_then(|audio| audio.as_ref().err());
755        if !matches!(video, Some(Ok(_))) && !matches!(audio, Some(Ok(_))) {
756            let reasons: Vec<String> = [video_err, audio_err]
757                .into_iter()
758                .flatten()
759                .map(ToString::to_string)
760                .collect();
761            return Err(Error::invalid(if reasons.is_empty() {
762                "the file has neither video nor audio".to_string()
763            } else {
764                reasons.join("; ")
765            }));
766        }
767        if let Some(err) = video_err {
768            warn!(parent: &self.shared.span, error = %err, "publishing the file's audio without its video");
769        }
770        if let Some(err) = audio_err {
771            warn!(parent: &self.shared.span, error = %err, "publishing the file's video without its audio");
772        }
773        if let Some(Ok(video)) = video {
774            self.set_encoded_video(video)?;
775        }
776        if let Some(Ok(audio)) = audio {
777            self.set_encoded_audio(audio)?;
778        }
779        Ok(())
780    }
781
782    /// Encodes `source` as the broadcast's audio, replacing the current audio.
783    ///
784    /// `encoding` is an [`AudioEncoding`], such as a preset from
785    /// [`audio_encoding`](crate::audio_encoding), or a moq-audio
786    /// `encode::Config` with the default group span.
787    ///
788    /// A microphone opens when the publication starts. If it fails then or
789    /// later, the audio slot shows the failure in [`status`](Self::status) and
790    /// stays failed until the audio is set again.
791    ///
792    /// # Errors
793    ///
794    /// Fails for an invalid encoding, or with [`Error::Closed`] after
795    /// [`close`](Self::close).
796    ///
797    /// # Panics
798    ///
799    /// Panics when called outside a Tokio runtime.
800    pub fn set_audio(
801        &self,
802        source: AudioSource,
803        encoding: impl Into<AudioEncoding>,
804    ) -> Result<(), Error> {
805        self.check_open()?;
806        let encoding = encoding.into();
807        encoding.validate()?;
808        let name = encoding.track_name();
809        info!(parent: &self.shared.span, source = source.label(), track = %name, "audio set");
810        let kept = SlotSource::Audio(source.clone());
811        self.replace(Medium::Audio, vec![name], kept, move |job, stop| {
812            audio::run(job, source, encoding, stop)
813        });
814        Ok(())
815    }
816
817    /// Creates a latest-value JSON track `name` in the broadcast, next to the media.
818    ///
819    /// For a setting or a status that rides along with the video and audio:
820    /// each [`update`](ValueWriter::update) replaces the value, and a reader
821    /// that subscribes late gets the current one at once. The track counts
822    /// milliseconds, and the [`ValueWriter`] stamps each update with the time
823    /// it is made; [`update_at`](ValueWriter::update_at) takes a time of the
824    /// caller's choice instead. The last clone of the writer to drop finishes
825    /// the track. A reader that asks for the track before it exists does not
826    /// find it, so create it before the broadcast is announced, for example
827    /// in the fill of `iroh_live_node::Node::publish_with`.
828    ///
829    /// # Errors
830    ///
831    /// Fails with [`Error::Closed`] after [`close`](Self::close), and with
832    /// [`Error::Broadcast`] if the broadcast already has a track `name`.
833    ///
834    /// # Examples
835    ///
836    /// ```
837    /// use moq_ext_publisher::LocalBroadcast;
838    ///
839    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
840    /// let broadcast = LocalBroadcast::new();
841    /// let control = broadcast.value_track::<u32>("control")?;
842    /// control.update(&30)?;
843    /// # Ok(())
844    /// # }
845    /// ```
846    pub fn value_track<T: serde::Serialize>(&self, name: &str) -> Result<ValueWriter<T>, Error> {
847        self.check_open()?;
848        let track = self
849            .shared
850            .producer
851            .create_track(
852                name,
853                moq_net::track::Info::default().with_timescale(moq_net::Timescale::MILLI),
854            )
855            .ok_or_else(|| Error::broadcast(moq_net::Error::Duplicate))?;
856        debug!(parent: &self.shared.span, track = name, "value track created");
857        Ok(ValueWriter::new(
858            track,
859            moq_json::snapshot::Config::default(),
860        ))
861    }
862
863    /// Returns the raw video source this broadcast encodes, if any.
864    ///
865    /// For a preview, read its [`frames`](VideoSource::frames). `None`
866    /// without video, and for a stream from
867    /// [`set_encoded_video`](Self::set_encoded_video). The source stays
868    /// here after it fails, until the video is set again or cleared.
869    #[must_use]
870    pub fn video_source(&self) -> Option<VideoSource> {
871        match &self.shared.video.lock().expect("poisoned").as_ref()?.source {
872            SlotSource::Video(source) => Some(source.clone()),
873            SlotSource::Audio(_) | SlotSource::Encoded => None,
874        }
875    }
876
877    /// Returns the audio source this broadcast encodes, if any.
878    ///
879    /// The source stays here after it fails, until the audio is set again or
880    /// cleared.
881    #[must_use]
882    pub fn audio_source(&self) -> Option<AudioSource> {
883        match &self.shared.audio.lock().expect("poisoned").as_ref()?.source {
884            SlotSource::Audio(source) => Some(source.clone()),
885            SlotSource::Video(_) | SlotSource::Encoded => None,
886        }
887    }
888
889    /// Stops publishing video.
890    pub fn clear_video(&self) {
891        self.clear(Medium::Video);
892    }
893
894    /// Stops publishing audio.
895    pub fn clear_audio(&self) {
896        self.clear(Medium::Audio);
897    }
898
899    /// Returns a receiver of the state of both slots and of every rendition.
900    ///
901    /// A borrow of the receiver blocks the broadcast's writes, so keep it short
902    /// and do not hold it across a call into the broadcast.
903    #[must_use]
904    pub fn status(&self) -> watch::Receiver<PublishStatus> {
905        self.shared.status.subscribe()
906    }
907
908    /// Returns the source timestamp of the video frame this broadcast published at `published`.
909    ///
910    /// The broadcast moves every source timestamp onto its own clock. A
911    /// subscriber that sends a decoded frame's timestamp back lets the
912    /// publisher find its own frame with this, without marking the pixels.
913    ///
914    /// It needs [`VideoEncoding::record_timestamps`] on the encoding the frame
915    /// was published with. Returns `None` without it, for a timestamp this
916    /// broadcast did not publish, for one older than the last 512 frames, and
917    /// for a pre-encoded source, whose timestamps are published as they are.
918    /// The record keeps only timestamps, 32 KiB at most, and no pixels
919    /// or encoded data.
920    ///
921    /// [`VideoEncoding::record_timestamps`]: crate::VideoEncoding::record_timestamps
922    ///
923    /// # Examples
924    ///
925    /// ```no_run
926    /// # fn example(broadcast: &moq_ext_publisher::LocalBroadcast, echoed: moq_net::Timestamp) {
927    /// // `echoed` is the timestamp of a frame a subscriber decoded, published
928    /// // with `VideoEncoding::record_timestamps` on.
929    /// if let Some(source) = broadcast.video_source_timestamp(echoed) {
930    ///     println!("the subscriber saw the frame the source stamped {source:?}");
931    /// }
932    /// # }
933    /// ```
934    #[must_use]
935    pub fn video_source_timestamp(
936        &self,
937        published: moq_net::Timestamp,
938    ) -> Option<moq_net::Timestamp> {
939        self.shared.video_timestamps.source(published)
940    }
941
942    /// Returns when the video frame this broadcast published at `published` entered its source.
943    ///
944    /// That is when the application pushed the frame into a
945    /// [`VideoSource::push`] sender, or when a capture or generator thread
946    /// handed it over, before it waited for an encoder. A subscriber that
947    /// sends a decoded frame's timestamp back lets the publisher measure the
948    /// round trip from capture with this, without a clock of its own for the
949    /// source's timestamps.
950    ///
951    /// It needs [`VideoEncoding::record_timestamps`] too, and returns `None` in
952    /// the same cases as [`video_source_timestamp`](Self::video_source_timestamp).
953    /// The instant is recorded per frame, not derived from the source
954    /// timestamp, because a source's timestamps come from its own clock: a
955    /// camera's from the device, a pushed frame's from the application.
956    ///
957    /// [`VideoEncoding::record_timestamps`]: crate::VideoEncoding::record_timestamps
958    ///
959    /// # Examples
960    ///
961    /// ```no_run
962    /// # fn example(broadcast: &moq_ext_publisher::LocalBroadcast, echoed: moq_net::Timestamp) {
963    /// // `echoed` is the timestamp of a frame a subscriber decoded and reported
964    /// // back, published with `VideoEncoding::record_timestamps` on.
965    /// if let Some(captured) = broadcast.video_captured_at(echoed) {
966    ///     println!("{:?} from capture to the report", captured.elapsed());
967    /// }
968    /// # }
969    /// ```
970    #[must_use]
971    pub fn video_captured_at(&self, published: moq_net::Timestamp) -> Option<Instant> {
972        self.shared
973            .video_timestamps
974            .get(published)
975            .and_then(|logged| logged.captured_at)
976    }
977
978    /// Returns when the video frame this broadcast published at `published` left its encoder.
979    ///
980    /// That is when the first rendition to encode the frame handed its
981    /// encoded data to the track. Less [`video_captured_at`](Self::video_captured_at),
982    /// it is the time the frame spent in the publisher: the wait for the
983    /// encoder, any scaling, and the encoding itself.
984    ///
985    /// It needs [`VideoEncoding::record_timestamps`] too, and returns `None` in
986    /// the same cases as [`video_source_timestamp`](Self::video_source_timestamp),
987    /// and for a frame still in the encoder.
988    ///
989    /// [`VideoEncoding::record_timestamps`]: crate::VideoEncoding::record_timestamps
990    ///
991    /// # Examples
992    ///
993    /// ```no_run
994    /// # fn example(broadcast: &moq_ext_publisher::LocalBroadcast, echoed: moq_net::Timestamp) {
995    /// let captured = broadcast.video_captured_at(echoed);
996    /// let encoded = broadcast.video_encoded_at(echoed);
997    /// if let (Some(captured), Some(encoded)) = (captured, encoded) {
998    ///     println!("{:?} from capture to the track", encoded - captured);
999    /// }
1000    /// # }
1001    /// ```
1002    #[must_use]
1003    pub fn video_encoded_at(&self, published: moq_net::Timestamp) -> Option<Instant> {
1004        self.shared
1005            .video_timestamps
1006            .get(published)
1007            .and_then(|logged| logged.encoded_at)
1008    }
1009
1010    /// Returns what the broadcast is sending, per rendition.
1011    #[must_use]
1012    pub fn stats(&self) -> PublishStats {
1013        let sent = self.shared.catalog.lock().expect("poisoned").stats();
1014        self.shared.stats.snapshot(sent)
1015    }
1016
1017    /// Returns a reader of the broadcast, for playing it in-process.
1018    ///
1019    /// The same as the [`Consume`] impl, without importing the trait:
1020    /// `RemoteBroadcast::from_local(&broadcast)` plays it.
1021    #[must_use]
1022    pub fn consume(&self) -> moq_net::broadcast::Consumer {
1023        self.shared.producer.consume()
1024    }
1025
1026    /// Closes the broadcast for every clone.
1027    ///
1028    /// Stops the encoders and lets each finish its track. Then it ends the
1029    /// catalog and the broadcast, which withdraws the broadcast everywhere it
1030    /// was published. Returns at once, and [`closed`](Self::closed) waits for
1031    /// the end. Calling it again does nothing.
1032    pub fn close(&self) {
1033        if self.shared.closed.is_cancelled() {
1034            return;
1035        }
1036        self.shared.closed.cancel();
1037        info!(parent: &self.shared.span, "closing");
1038        let video = self.shared.video.lock().expect("poisoned").take();
1039        let audio = self.shared.audio.lock().expect("poisoned").take();
1040        let shared = Arc::downgrade(&self.shared);
1041        let finished = self.shared.finished.clone();
1042        let task = n0_future::task::spawn(async move {
1043            if let Some(video) = video {
1044                video.task.finish(FINISH_PATIENCE).await;
1045            }
1046            if let Some(audio) = audio {
1047                audio.task.finish(FINISH_PATIENCE).await;
1048            }
1049            if let Some(shared) = shared.upgrade() {
1050                shared.end();
1051            }
1052            finished.cancel();
1053        });
1054        *self.shared.closer.lock().expect("poisoned") = Some(AbortOnDropHandle::new(task));
1055    }
1056
1057    /// Waits until the broadcast is closed and every track has finished.
1058    ///
1059    /// Cancellation safe.
1060    pub async fn closed(&self) {
1061        self.shared.finished.cancelled().await;
1062    }
1063
1064    /// Fails with [`Error::Closed`] once the broadcast is closed.
1065    fn check_open(&self) -> Result<(), Error> {
1066        if self.shared.closed.is_cancelled() {
1067            Err(n0_error::e!(Error::Closed))
1068        } else {
1069            Ok(())
1070        }
1071    }
1072
1073    /// Replaces a slot's task in one critical section.
1074    ///
1075    /// The new task finishes the old one before it takes the track names. The
1076    /// status moves to the new generation under the same lock, so a late report
1077    /// from the old task cannot land on the new slot.
1078    fn replace<F, Fut>(&self, medium: Medium, names: Vec<String>, source: SlotSource, run: F)
1079    where
1080        F: FnOnce(Job, CancellationToken) -> Fut,
1081        Fut: std::future::Future<Output = ()> + Send + 'static,
1082    {
1083        let shared = &self.shared;
1084        let (lock, tracks, handovers, span) = match medium {
1085            Medium::Video => (
1086                &shared.video,
1087                &shared.video_tracks,
1088                shared.video_handovers.clone(),
1089                info_span!(parent: &shared.span, "video"),
1090            ),
1091            // Audio finishes its track on replacement, so nothing is handed over.
1092            Medium::Audio => (
1093                &shared.audio,
1094                &shared.audio_tracks,
1095                Default::default(),
1096                info_span!(parent: &shared.span, "audio"),
1097            ),
1098        };
1099        let mut slot = lock.lock().expect("poisoned");
1100        let generation = shared.generations.fetch_add(1, Ordering::Relaxed) + 1;
1101        let handing_over = Arc::new(AtomicBool::new(false));
1102        let job = Job {
1103            producer: shared.producer.clone(),
1104            catalog: shared.catalog.lock().expect("poisoned").clone(),
1105            clock: shared.clock.clone(),
1106            timestamps: shared.video_timestamps.clone(),
1107            tracks: tracks.clone(),
1108            handovers,
1109            handing_over: handing_over.clone(),
1110            stats: shared.stats.clone(),
1111            reporter: shared.status.begin(medium, generation, &names),
1112            predecessor: slot.take().map(|previous| previous.task),
1113        };
1114        let task = SlotTask::spawn(span, &shared.closed, handing_over, |stop| run(job, stop));
1115        *slot = Some(Slot {
1116            generation,
1117            task,
1118            source,
1119        });
1120    }
1121
1122    /// Stops the task of a slot, and lets it finish its tracks in the background.
1123    fn clear(&self, medium: Medium) {
1124        let lock = match medium {
1125            Medium::Video => &self.shared.video,
1126            Medium::Audio => &self.shared.audio,
1127        };
1128        let previous = lock.lock().expect("poisoned").take();
1129        if let Some(previous) = previous {
1130            self.shared.status.clear(medium, previous.generation);
1131            let mut retiring = self.shared.retiring.lock().expect("poisoned");
1132            while retiring.try_join_next().is_some() {}
1133            retiring.spawn(previous.task.finish(FINISH_PATIENCE));
1134            match medium {
1135                Medium::Video => self.shared.stats.clear_video(),
1136                Medium::Audio => self.shared.stats.clear_audio(),
1137            }
1138            debug!(parent: &self.shared.span, ?medium, "slot cleared");
1139        }
1140    }
1141}
1142
1143impl Consume<moq_net::broadcast::Consumer> for LocalBroadcast {
1144    fn consume(&self) -> moq_net::broadcast::Consumer {
1145        Self::consume(self)
1146    }
1147}
1148
1149#[cfg(test)]
1150mod tests;