Skip to main content

active_call/media/track/
mod.rs

1use crate::event::EventSender;
2use crate::media::processor::{Processor, ProcessorChain};
3use crate::media::{AudioFrame, TrackId};
4use anyhow::Result;
5use async_trait::async_trait;
6use audio_codec::CodecType;
7use tokio::sync::mpsc;
8use tokio::time::Duration;
9use tokio_util::sync::CancellationToken;
10
11pub type TrackPacketSender = mpsc::UnboundedSender<AudioFrame>;
12pub type TrackPacketReceiver = mpsc::UnboundedReceiver<AudioFrame>;
13
14// New shared track configuration struct
15#[derive(Debug, Clone)]
16pub struct TrackConfig {
17    pub codec: CodecType,
18    // Packet time in milliseconds (typically 10, 20, or 30ms)
19    pub ptime: Duration,
20    // Sample rate for PCM audio (e.g., 8000, 16000, 48000)
21    pub samplerate: u32,
22    // Number of audio channels (1 for mono, 2 for stereo)
23    pub channels: u16,
24}
25
26impl Default for TrackConfig {
27    fn default() -> Self {
28        Self {
29            codec: CodecType::G722,
30            samplerate: 16000,
31            channels: 1,
32            ptime: Duration::from_millis(20),
33        }
34    }
35}
36
37impl TrackConfig {
38    pub fn with_ptime(mut self, ptime: Duration) -> Self {
39        self.ptime = ptime;
40        self
41    }
42
43    pub fn with_sample_rate(mut self, sample_rate: u32) -> Self {
44        self.samplerate = sample_rate;
45        self
46    }
47
48    pub fn with_channels(mut self, channels: u16) -> Self {
49        self.channels = channels;
50        self
51    }
52}
53
54pub mod dtmf;
55pub mod file;
56pub mod forwarding;
57pub mod media_pass;
58pub mod rtc;
59pub mod track_codec;
60pub mod tts;
61pub mod websocket;
62#[async_trait]
63pub trait Track: Send + Sync {
64    fn ssrc(&self) -> u32;
65    fn id(&self) -> &TrackId;
66    /// The track's lifecycle token: cancelled by `stop()`/`stop_graceful()`
67    /// (directly or through the track's own event loop teardown).
68    ///
69    /// Per-track background workers spawned on behalf of this track (e.g. the
70    /// inactivity watchdog created by `setup_track_with_stream`) MUST derive
71    /// their lifetime from this token, so that stopping or replacing the
72    /// track disarms them. Binding those workers to the session token instead
73    /// leaves "zombie" watchdogs behind: a retired leg keeps its frozen
74    /// last-frame timestamp and eventually fires `SessionEvent::Inactivity`
75    /// against a call that is alive and well (seen with INVITE-mode
76    /// auto-refer transfers, where the superseded bridge leg's watchdog
77    /// killed the session ~50s after a successful transfer).
78    fn cancel_token(&self) -> CancellationToken;
79    fn config(&self) -> &TrackConfig;
80    fn set_paused(&self, _paused: bool) -> bool {
81        false
82    }
83    fn is_paused(&self) -> bool {
84        false
85    }
86    fn processor_chain(&mut self) -> &mut ProcessorChain;
87    /// Cancel the track's media pipeline (per-track workers, inactivity
88    /// watchdog) WITHOUT closing the underlying transport. Used when a track
89    /// is replaced by a successor: the successor's media setup must not race
90    /// against the predecessor's transport teardown.
91    /// The full `stop()` (which closes the transport) follows afterwards.
92    ///
93    /// Default: cancel the track's own token, so a replaced track stops
94    /// producing frames at once — otherwise it keeps feeding the shared packet
95    /// sender during the deferred-stop grace period and its audio interleaves
96    /// with the successor's (e.g. a ringtone bleeding into the first Play/TTS).
97    /// The transport-sparing part lives in `stop()`, not here: e.g. `RtcTrack`
98    /// closes its PeerConnection only in `stop()`, which `MediaStream` defers.
99    fn cancel_pipeline(&self) {
100        self.cancel_token().cancel();
101    }
102    fn insert_processor(&mut self, processor: Box<dyn Processor>) {
103        self.processor_chain().insert_processor(processor);
104    }
105    fn append_processor(&mut self, processor: Box<dyn Processor>) {
106        self.processor_chain().append_processor(processor);
107    }
108    /// Attach a raw-tap receiver that mirrors inbound frames at their native
109    /// (pre-resample) sample rate, used by the native-samplerate recorder.
110    /// Setting `None` detaches an existing tap.
111    fn set_raw_tap(&mut self, tap: Option<mpsc::UnboundedSender<AudioFrame>>) {
112        // Record this track's id as the tap owner so relayed frames (e.g. the
113        // caller's audio forwarded through the media-pass track) are not
114        // mirrored a second time.
115        let owner = self.id().clone();
116        let chain = self.processor_chain();
117        chain.set_raw_tap(tap);
118        chain.set_tap_owner(Some(owner));
119    }
120    async fn handshake(&mut self, offer: String, timeout: Option<Duration>) -> Result<String>;
121    async fn update_remote_description(&mut self, answer: &String) -> Result<()>;
122    async fn update_remote_description_force(&mut self, answer: &String) -> Result<()> {
123        // Default implementation: force update is same as regular update for most tracks
124        self.update_remote_description(answer).await
125    }
126    /// Apply a provisional remote description (SIP 183 early media). Unlike
127    /// `update_remote_description`, this must not finalize SDP negotiation —
128    /// the real answer (200 OK) is still to come. Default: same as a regular
129    /// update, for track types that don't have a signaling state machine.
130    async fn update_remote_description_provisional(&mut self, answer: &String) -> Result<()> {
131        self.update_remote_description(answer).await
132    }
133    async fn start(
134        &mut self,
135        event_sender: EventSender,
136        packet_sender: TrackPacketSender,
137    ) -> Result<()>;
138    async fn stop(&self) -> Result<()>;
139    async fn stop_graceful(&self) -> Result<()> {
140        self.stop().await
141    }
142    async fn send_packet(&mut self, packet: &AudioFrame) -> Result<()>;
143    /// Feed a remotely-gathered ICE candidate into this track's PeerConnection.
144    /// Default no-op for track types that aren't backed by ICE (file/tts/websocket tracks).
145    fn add_ice_candidate(
146        &self,
147        _candidate: &str,
148        _sdp_mid: Option<&str>,
149        _sdp_mline_index: Option<u32>,
150    ) -> Result<()> {
151        Ok(())
152    }
153    /// The call was answered locally: Accept sent the 200 OK, or a WebRTC
154    /// track answered the browser's offer. `rtp_timeout`, when given,
155    /// replaces the configured RTP timeout. Default no-op for track types
156    /// without RTP timeout monitoring.
157    fn on_answered(&self, _rtp_timeout: Option<Duration>) {}
158    /// The track is done for good (stopped, or lost its transport), though
159    /// it may stay registered until replaced. Default: never.
160    fn has_ended(&self) -> bool {
161        false
162    }
163}