Skip to main content

rtc/media_stream/
track.rs

1//! `MediaStreamTrack` implementation.
2//!
3//! This module is private; the type is re-exported from
4//! [`crate::media_stream`]. All user-facing documentation and examples live on
5//! [`MediaStreamTrack`] itself, so that rustdoc renders them and their doctests run.
6//!
7//! # Specification
8//!
9//! - [W3C MediaStreamTrack](https://www.w3.org/TR/mediacapture-streams/#mediastreamtrack)
10//! - [MDN MediaStreamTrack](https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack)
11
12use crate::media_stream::MediaStreamId;
13use crate::media_stream::track_capabilities::MediaTrackCapabilities;
14use crate::media_stream::track_constraints::MediaTrackConstraints;
15use crate::media_stream::track_settings::MediaTrackSettings;
16use crate::media_stream::track_state::MediaStreamTrackState;
17use crate::rtp_transceiver::rtp_sender::{
18    RTCRtpCodec, RTCRtpCodingParameters, RTCRtpEncodingParameters, RtpCodecKind,
19};
20use crate::rtp_transceiver::{RtpStreamId, SSRC};
21
22/// Unique identifier for a media stream track.
23///
24/// As defined in [MediaStreamTrack.id](https://www.w3.org/TR/mediacapture-streams/#dom-mediastreamtrack-id).
25pub type MediaStreamTrackId = String;
26
27/// Represents a single media track within a media stream.
28///
29/// A `MediaStreamTrack` represents an audio or video track from a media source.
30/// Each track has a unique identifier, a label (human-readable name), a kind
31/// (audio or video), and various state attributes.
32///
33/// The track can be enabled/disabled, muted/unmuted, and has a lifecycle state
34/// that progresses from "live" to "ended". Once ended, a track cannot be restarted.
35///
36/// # Specification
37///
38/// See [MediaStreamTrack](https://www.w3.org/TR/mediacapture-streams/#mediastreamtrack)
39/// in the W3C Media Capture and Streams specification.
40///
41/// # Examples
42///
43/// ```
44/// use rtc::media_stream::MediaStreamTrack;
45/// use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind};
46/// use rtc::rtp_transceiver::rtp_sender::{RTCRtpEncodingParameters, RTCRtpCodingParameters};
47///
48/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
49/// let track = MediaStreamTrack::new(
50///     "stream-id".to_string(),
51///     "track-id".to_string(),
52///     "Microphone".to_string(),
53///     RtpCodecKind::Audio,
54///     vec![RTCRtpEncodingParameters {
55///         rtp_coding_parameters: RTCRtpCodingParameters {
56///             ssrc: Some(12345),
57///             ..Default::default()
58///         },
59///         codec: RTCRtpCodec::default(),
60///         ..Default::default()
61///     }],
62/// );
63///
64/// assert_eq!(track.kind(), RtpCodecKind::Audio);
65/// assert_eq!(track.label(), "Microphone");
66/// assert!(track.enabled());
67/// assert!(!track.muted());
68/// # Ok(())
69/// # }
70/// ```
71///
72/// ## Controlling track state
73///
74/// ```
75/// use rtc::media_stream::MediaStreamTrack;
76///
77/// # fn example(mut track: MediaStreamTrack) {
78/// // Disable the track temporarily
79/// track.set_enabled(false);
80/// assert!(!track.enabled());
81///
82/// // Re-enable the track
83/// track.set_enabled(true);
84/// assert!(track.enabled());
85///
86/// // Stop the track permanently — a stopped track cannot be restarted
87/// track.stop();
88/// # }
89/// ```
90#[derive(Default, Debug, Clone)]
91pub struct MediaStreamTrack {
92    stream_id: MediaStreamId,
93    track_id: MediaStreamTrackId,
94    label: String,
95    kind: RtpCodecKind,
96    codings: Vec<RTCRtpEncodingParameters>,
97
98    muted: bool,
99    enabled: bool,
100    ready_state: MediaStreamTrackState,
101    restrictable: bool,
102    capabilities: MediaTrackCapabilities,
103    constraints: MediaTrackConstraints,
104    settings: MediaTrackSettings,
105}
106
107impl MediaStreamTrack {
108    /// Creates a new media stream track.
109    ///
110    /// # Parameters
111    ///
112    /// * `stream_id` - The ID of the [`MediaStream`](crate::media_stream::MediaStream) this track belongs to
113    /// * `track_id` - A unique identifier for this track (typically a UUID)
114    /// * `label` - A human-readable label for the track (e.g., "Built-in Microphone")
115    /// * `kind` - The kind of media: [`Audio`](RtpCodecKind::Audio) or [`Video`](RtpCodecKind::Video)
116    /// * `codings` - Vector of RTP encoding parameters, each containing SSRC, codec, and optional RID.
117    ///   For simulcast, provide multiple entries with different SSRCs and RIDs.
118    ///
119    /// # Returns
120    ///
121    /// A new `MediaStreamTrack` initialized with the provided parameters. The track
122    /// starts in the "live" state, enabled, and unmuted.
123    ///
124    /// # Specification
125    ///
126    /// See [MediaStreamTrack](https://www.w3.org/TR/mediacapture-streams/#mediastreamtrack).
127    ///
128    /// # Examples
129    ///
130    /// ```
131    /// use rtc::media_stream::MediaStreamTrack;
132    /// use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind};
133    /// use rtc::rtp_transceiver::rtp_sender::{RTCRtpEncodingParameters, RTCRtpCodingParameters};
134    /// use rtc::peer_connection::configuration::media_engine::MIME_TYPE_OPUS;
135    ///
136    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
137    /// let codec = RTCRtpCodec {
138    ///     mime_type: MIME_TYPE_OPUS.to_string(),
139    ///     clock_rate: 48000,
140    ///     channels: 2,
141    ///     sdp_fmtp_line: String::new(),
142    ///     rtcp_feedback: vec![],
143    /// };
144    ///
145    /// let audio_track = MediaStreamTrack::new(
146    ///     "my-stream".to_string(),
147    ///     "audio-1".to_string(),
148    ///     "Built-in Microphone".to_string(),
149    ///     RtpCodecKind::Audio,
150    ///     vec![RTCRtpEncodingParameters {
151    ///         rtp_coding_parameters: RTCRtpCodingParameters {
152    ///             ssrc: Some(123456),
153    ///             ..Default::default()
154    ///         },
155    ///         codec,
156    ///         ..Default::default()
157    ///     }],
158    /// );
159    ///
160    /// assert_eq!(audio_track.track_id(), "audio-1");
161    /// assert_eq!(audio_track.label(), "Built-in Microphone");
162    /// # Ok(())
163    /// # }
164    /// ```
165    pub fn new(
166        stream_id: MediaStreamId,
167        track_id: MediaStreamTrackId,
168        label: String,
169        kind: RtpCodecKind,
170        codings: Vec<RTCRtpEncodingParameters>,
171    ) -> Self {
172        Self {
173            stream_id,
174            track_id,
175            label,
176            kind,
177            codings,
178
179            muted: false,
180            enabled: true,
181            ready_state: MediaStreamTrackState::Live,
182            restrictable: false,
183
184            ..Default::default()
185        }
186    }
187
188    /// Returns the stream ID this track belongs to.
189    ///
190    /// # Specification
191    ///
192    /// Related to [MediaStream.id](https://www.w3.org/TR/mediacapture-streams/#dom-mediastream-id).
193    pub fn stream_id(&self) -> &MediaStreamId {
194        &self.stream_id
195    }
196
197    /// Returns the unique identifier of this track.
198    ///
199    /// The identifier is a 36-character Universally Unique Identifier (UUID)
200    /// assigned when the track is created and remains constant throughout
201    /// the track's lifetime.
202    ///
203    /// # Specification
204    ///
205    /// See [MediaStreamTrack.id](https://www.w3.org/TR/mediacapture-streams/#dom-mediastreamtrack-id).
206    pub fn track_id(&self) -> &MediaStreamTrackId {
207        &self.track_id
208    }
209
210    /// Returns the human-readable label of this track.
211    ///
212    /// The label is a user-agent assigned string that identifies the track source.
213    /// For example, "Internal Microphone" or "FaceTime HD Camera".
214    ///
215    /// # Specification
216    ///
217    /// See [MediaStreamTrack.label](https://www.w3.org/TR/mediacapture-streams/#dom-mediastreamtrack-label).
218    ///
219    /// # Examples
220    ///
221    /// ```
222    /// # use rtc::media_stream::MediaStreamTrack;
223    /// # use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind};
224    /// # fn example(track: MediaStreamTrack) {
225    /// println!("Track label: {}", track.label());
226    /// # }
227    /// ```
228    pub fn label(&self) -> &String {
229        &self.label
230    }
231
232    /// Returns the kind of media this track represents.
233    ///
234    /// Returns either [`RtpCodecKind::Audio`] for audio tracks or
235    /// [`RtpCodecKind::Video`] for video tracks.
236    ///
237    /// # Specification
238    ///
239    /// See [MediaStreamTrack.kind](https://www.w3.org/TR/mediacapture-streams/#dom-mediastreamtrack-kind).
240    ///
241    /// # Examples
242    ///
243    /// ```
244    /// # use rtc::media_stream::MediaStreamTrack;
245    /// # use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind};
246    /// # fn example(track: MediaStreamTrack) {
247    /// match track.kind() {
248    ///     RtpCodecKind::Audio => println!("This is an audio track"),
249    ///     RtpCodecKind::Video => println!("This is a video track"),
250    ///     _ => {},
251    /// }
252    /// # }
253    /// ```
254    pub fn kind(&self) -> RtpCodecKind {
255        self.kind
256    }
257
258    /// Returns the RTP stream ID (rid) for a given SSRC if this track is part of a simulcast or SVC configuration.
259    ///
260    /// The rid (restriction identifier) is used to identify different encodings of the
261    /// same media source in simulcast scenarios. This method finds the rid associated with
262    /// a specific SSRC.
263    ///
264    /// # Parameters
265    ///
266    /// * `ssrc` - The Synchronization Source identifier to look up
267    ///
268    /// # Returns
269    ///
270    /// Returns `Some(&RtpStreamId)` if a rid is found for the given SSRC, or `None` if:
271    /// - No encoding with the given SSRC exists
272    /// - The encoding has no rid configured
273    /// - This is a non-simulcast track
274    ///
275    /// # Specification
276    ///
277    /// See [RFC 8851 - RTP Payload Format Restrictions](https://datatracker.ietf.org/doc/html/rfc8851).
278    ///
279    /// # Examples
280    ///
281    /// ```
282    /// use rtc::media_stream::MediaStreamTrack;
283    /// use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind};
284    /// use rtc::rtp_transceiver::rtp_sender::{RTCRtpEncodingParameters, RTCRtpCodingParameters};
285    ///
286    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
287    /// let track = MediaStreamTrack::new(
288    ///     "stream-id".to_string(),
289    ///     "track-id".to_string(),
290    ///     "Video Track".to_string(),
291    ///     RtpCodecKind::Video,
292    ///     vec![RTCRtpEncodingParameters {
293    ///         rtp_coding_parameters: RTCRtpCodingParameters {
294    ///             rid: "q".to_string(), // quarter resolution
295    ///             ssrc: Some(12345),
296    ///             ..Default::default()
297    ///         },
298    ///         codec: RTCRtpCodec::default(),
299    ///         ..Default::default()
300    ///     }],
301    /// );
302    ///
303    /// // Get the rid for a specific SSRC
304    /// if let Some(rid) = track.rid(12345) {
305    ///     println!("RID for SSRC 12345: {}", rid);
306    /// }
307    /// # Ok(())
308    /// # }
309    /// ```
310    pub fn rid(&self, ssrc: SSRC) -> Option<&RtpStreamId> {
311        self.codings
312            .iter()
313            .find(|coding| {
314                !coding.rtp_coding_parameters.rid.is_empty()
315                    && coding
316                        .rtp_coding_parameters
317                        .ssrc
318                        .is_some_and(|t_ssrc| t_ssrc == ssrc)
319            })
320            .map(|coding| &coding.rtp_coding_parameters.rid)
321    }
322
323    /// Returns the RTP codec configuration for a specific SSRC.
324    ///
325    /// For simulcast tracks with multiple encodings, each encoding may have its own
326    /// codec configuration. This method retrieves the codec for a specific SSRC.
327    ///
328    /// # Parameters
329    ///
330    /// * `ssrc` - The Synchronization Source identifier to look up
331    ///
332    /// # Returns
333    ///
334    /// Returns `Some(&RTCRtpCodec)` if a codec is found for the given SSRC, or `None` if:
335    /// - No encoding with the given SSRC exists
336    /// - The encoding has no codec configured (empty MIME type)
337    ///
338    /// # Examples
339    ///
340    /// ```
341    /// use rtc::media_stream::MediaStreamTrack;
342    /// use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind};
343    /// use rtc::rtp_transceiver::rtp_sender::{RTCRtpEncodingParameters, RTCRtpCodingParameters};
344    /// use rtc::peer_connection::configuration::media_engine::MIME_TYPE_VP8;
345    ///
346    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
347    /// let codec = RTCRtpCodec {
348    ///     mime_type: MIME_TYPE_VP8.to_string(),
349    ///     clock_rate: 90000,
350    ///     channels: 0,
351    ///     sdp_fmtp_line: String::new(),
352    ///     rtcp_feedback: vec![],
353    /// };
354    ///
355    /// let track = MediaStreamTrack::new(
356    ///     "stream-id".to_string(),
357    ///     "track-id".to_string(),
358    ///     "Video Track".to_string(),
359    ///     RtpCodecKind::Video,
360    ///     vec![RTCRtpEncodingParameters {
361    ///         rtp_coding_parameters: RTCRtpCodingParameters {
362    ///             ssrc: Some(12345),
363    ///             ..Default::default()
364    ///         },
365    ///         codec,
366    ///         ..Default::default()
367    ///     }],
368    /// );
369    ///
370    /// // Get the codec for a specific SSRC
371    /// if let Some(codec) = track.codec(12345) {
372    ///     println!("Codec for SSRC 12345: {}", codec.mime_type);
373    /// }
374    /// # Ok(())
375    /// # }
376    /// ```
377    ///
378    /// # Specification
379    ///
380    /// See [RTCRtpCodec](https://www.w3.org/TR/webrtc/#dom-rtcrtpcodecparameters).
381    pub fn codec(&self, ssrc: SSRC) -> Option<&RTCRtpCodec> {
382        self.codings
383            .iter()
384            .find(|coding| {
385                !coding.codec.mime_type.is_empty()
386                    && coding
387                        .rtp_coding_parameters
388                        .ssrc
389                        .is_some_and(|track_ssrc| track_ssrc == ssrc)
390            })
391            .map(|coding| &coding.codec)
392    }
393
394    /// Returns an iterator over the Synchronization Source (SSRC) identifiers for this track.
395    ///
396    /// The SSRC is a 32-bit identifier used in RTP to distinguish different
397    /// media sources within a session. For simulcast tracks, this returns multiple SSRCs.
398    ///
399    /// # Returns
400    ///
401    /// An iterator that yields SSRC values (u32).
402    ///
403    /// # Specification
404    ///
405    /// See [RFC 3550 - RTP: A Transport Protocol for Real-Time Applications](https://datatracker.ietf.org/doc/html/rfc3550#section-5.1).
406    ///
407    /// # Examples
408    ///
409    /// ```
410    /// use rtc::media_stream::MediaStreamTrack;
411    /// use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind};
412    /// use rtc::rtp_transceiver::rtp_sender::{RTCRtpEncodingParameters, RTCRtpCodingParameters};
413    ///
414    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
415    /// let track = MediaStreamTrack::new(
416    ///     "stream-id".to_string(),
417    ///     "track-id".to_string(),
418    ///     "Video Track".to_string(),
419    ///     RtpCodecKind::Video,
420    ///     vec![RTCRtpEncodingParameters {
421    ///         rtp_coding_parameters: RTCRtpCodingParameters {
422    ///             ssrc: Some(12345),
423    ///             ..Default::default()
424    ///         },
425    ///         codec: RTCRtpCodec::default(),
426    ///         ..Default::default()
427    ///     }],
428    /// );
429    ///
430    /// // Get all SSRCs
431    /// let ssrcs: Vec<u32> = track.ssrcs().collect();
432    /// println!("Track SSRCs: {:?}", ssrcs);
433    /// # Ok(())
434    /// # }
435    /// ```
436    pub fn ssrcs(&self) -> impl Iterator<Item = SSRC> {
437        self.codings
438            .iter()
439            .filter(|coding| coding.rtp_coding_parameters.ssrc.is_some())
440            .map(|coding| coding.rtp_coding_parameters.ssrc.unwrap_or_default())
441    }
442
443    /// Returns whether this track is enabled.
444    ///
445    /// When a track is disabled, it produces silence (for audio) or black frames (for video),
446    /// but remains live and connected. This is useful for temporarily stopping media flow
447    /// without tearing down the connection.
448    ///
449    /// # Specification
450    ///
451    /// See [MediaStreamTrack.enabled](https://www.w3.org/TR/mediacapture-streams/#dom-mediastreamtrack-enabled).
452    ///
453    /// # Examples
454    ///
455    /// ```
456    /// # use rtc::media_stream::MediaStreamTrack;
457    /// # use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind};
458    /// # fn example(track: MediaStreamTrack) {
459    /// if track.enabled() {
460    ///     println!("Track is producing media");
461    /// } else {
462    ///     println!("Track is disabled");
463    /// }
464    /// # }
465    /// ```
466    pub fn enabled(&self) -> bool {
467        self.enabled
468    }
469
470    /// Sets whether this track is enabled.
471    ///
472    /// Disabling a track causes it to produce silence (audio) or black frames (video).
473    /// This is reversible - enabling the track again resumes normal media flow.
474    ///
475    /// # Parameters
476    ///
477    /// * `enabled` - `true` to enable the track, `false` to disable it
478    ///
479    /// # Specification
480    ///
481    /// See [MediaStreamTrack.enabled](https://www.w3.org/TR/mediacapture-streams/#dom-mediastreamtrack-enabled).
482    ///
483    /// # Examples
484    ///
485    /// ```
486    /// # use rtc::media_stream::MediaStreamTrack;
487    /// # use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind};
488    /// # fn example(mut track: MediaStreamTrack) {
489    /// // Temporarily disable the track
490    /// track.set_enabled(false);
491    ///
492    /// // Later, re-enable it
493    /// track.set_enabled(true);
494    /// # }
495    /// ```
496    pub fn set_enabled(&mut self, enabled: bool) {
497        self.enabled = enabled;
498    }
499
500    /// Returns whether this track is muted.
501    ///
502    /// A muted track is unable to provide media data due to technical limitations,
503    /// such as hardware issues or permission denials. Unlike [`enabled`](Self::enabled),
504    /// which is under application control, muting is controlled by the user agent or system.
505    ///
506    /// # Specification
507    ///
508    /// See [MediaStreamTrack.muted](https://www.w3.org/TR/mediacapture-streams/#dom-mediastreamtrack-muted).
509    ///
510    /// # Examples
511    ///
512    /// ```
513    /// # use rtc::media_stream::MediaStreamTrack;
514    /// # use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind};
515    /// # fn example(track: MediaStreamTrack) {
516    /// if track.muted() {
517    ///     println!("Track is muted by the system");
518    /// }
519    /// # }
520    /// ```
521    pub fn muted(&self) -> bool {
522        self.muted
523    }
524
525    /// Sets the muted state of the track.
526    pub fn set_muted(&mut self, muted: bool) {
527        self.muted = muted;
528    }
529
530    /// Returns MediaStreamTrackState
531    pub fn ready_state(&self) -> MediaStreamTrackState {
532        self.ready_state
533    }
534
535    /// Permanently stops this track.
536    ///
537    /// Stopping a track ends its media source and transitions the track to the "ended" state.
538    /// Once stopped, a track cannot be restarted. The track will no longer produce media,
539    /// and resources associated with it are released.
540    ///
541    /// # Specification
542    ///
543    /// See [MediaStreamTrack.stop()](https://www.w3.org/TR/mediacapture-streams/#dom-mediastreamtrack-stop).
544    ///
545    /// # Examples
546    ///
547    /// ```
548    /// # use rtc::media_stream::MediaStreamTrack;
549    /// # use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind};
550    /// # fn example(mut track: MediaStreamTrack) {
551    /// // Stop the track when done
552    /// track.stop();
553    ///
554    /// // Track is now permanently ended
555    /// # }
556    /// ```
557    pub fn stop(&mut self) {
558        self.ready_state = MediaStreamTrackState::Ended;
559    }
560
561    /// Returns the capabilities of this track.
562    ///
563    /// Capabilities represent the inherent properties of the track's source, such as
564    /// supported resolutions, frame rates, sample rates, etc. These are determined by
565    /// the underlying hardware or media source.
566    ///
567    /// # Specification
568    ///
569    /// See [MediaStreamTrack.getCapabilities()](https://www.w3.org/TR/mediacapture-streams/#dom-mediastreamtrack-getcapabilities).
570    ///
571    /// # Examples
572    ///
573    /// ```
574    /// # use rtc::media_stream::MediaStreamTrack;
575    /// # use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind};
576    /// # fn example(track: MediaStreamTrack) {
577    /// let capabilities = track.get_capabilities();
578    /// // Inspect supported capabilities
579    /// # }
580    /// ```
581    pub fn get_capabilities(&self) -> &MediaTrackCapabilities {
582        &self.capabilities
583    }
584
585    /// Returns the currently applied constraints for this track.
586    ///
587    /// Constraints define the allowed ranges or exact values for various track properties.
588    /// They are applied using [`apply_constraints()`](Self::apply_constraints).
589    ///
590    /// # Specification
591    ///
592    /// See [MediaStreamTrack.getConstraints()](https://www.w3.org/TR/mediacapture-streams/#dom-mediastreamtrack-getconstraints).
593    ///
594    /// # Examples
595    ///
596    /// ```
597    /// # use rtc::media_stream::MediaStreamTrack;
598    /// # use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind};
599    /// # fn example(track: MediaStreamTrack) {
600    /// let constraints = track.get_constraints();
601    /// // Examine current constraints
602    /// # }
603    /// ```
604    pub fn get_constraints(&self) -> &MediaTrackConstraints {
605        &self.constraints
606    }
607
608    /// Returns the actual settings currently in effect for this track.
609    ///
610    /// Settings represent the current values of track properties like resolution,
611    /// frame rate, sample rate, etc. These may differ from requested constraints
612    /// based on hardware limitations or system conditions.
613    ///
614    /// # Specification
615    ///
616    /// See [MediaStreamTrack.getSettings()](https://www.w3.org/TR/mediacapture-streams/#dom-mediastreamtrack-getsettings).
617    ///
618    /// # Examples
619    ///
620    /// ```
621    /// # use rtc::media_stream::MediaStreamTrack;
622    /// # use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind};
623    /// # fn example(track: MediaStreamTrack) {
624    /// let settings = track.get_settings();
625    /// // Check actual track settings
626    /// # }
627    /// ```
628    pub fn get_settings(&self) -> &MediaTrackSettings {
629        &self.settings
630    }
631
632    /// Applies constraints to this track.
633    ///
634    /// Constraints allow the application to specify desired values or ranges for
635    /// track properties like resolution, frame rate, etc. The user agent will
636    /// attempt to satisfy these constraints, but may not be able to meet all of them
637    /// depending on hardware capabilities and system conditions.
638    ///
639    /// If the track is in the "ended" state, this method has no effect.
640    ///
641    /// # Parameters
642    ///
643    /// * `constraints` - Optional constraints to apply. Pass `None` to remove all constraints.
644    ///
645    /// # Specification
646    ///
647    /// See [MediaStreamTrack.applyConstraints()](https://www.w3.org/TR/mediacapture-streams/#dom-mediastreamtrack-applyconstraints).
648    ///
649    /// # Examples
650    ///
651    /// ```
652    /// # use rtc::media_stream::MediaStreamTrack;
653    /// # use rtc::media_stream::MediaTrackConstraints;
654    /// # use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind};
655    /// # fn example(mut track: MediaStreamTrack) {
656    /// // Apply new constraints
657    /// let constraints = MediaTrackConstraints::default();
658    /// track.apply_constraints(Some(constraints));
659    ///
660    /// // Remove all constraints
661    /// track.apply_constraints(None);
662    /// # }
663    /// ```
664    pub fn apply_constraints(&mut self, constraints: Option<MediaTrackConstraints>) {
665        if self.ready_state == MediaStreamTrackState::Ended {
666            return;
667        }
668
669        if let Some(constraints) = constraints {
670            //TODO: https://www.w3.org/TR/mediacapture-streams/#dom-mediastreamtrack-applyconstraints
671            self.constraints = constraints;
672        }
673    }
674
675    /// Sets the codec for this track by ssrc (internal use only).
676    ///
677    /// # Parameters
678    ///
679    /// * `codec` - The new RTP codec configuration
680    ///
681    /// * `ssrc` - The new RTP SSRC
682    ///
683    /// # Return
684    ///
685    /// true: insert new entry if not found
686    ///
687    /// false: update entry when found
688    pub(crate) fn set_codec_by_ssrc(&mut self, codec: RTCRtpCodec, ssrc: SSRC) -> bool {
689        if let Some(coding) = self.codings.iter_mut().find(|coding| {
690            coding
691                .rtp_coding_parameters
692                .ssrc
693                .is_some_and(|t_ssrc| t_ssrc == ssrc)
694        }) {
695            coding.codec = codec;
696            false
697        } else {
698            self.codings.push(RTCRtpEncodingParameters {
699                rtp_coding_parameters: RTCRtpCodingParameters {
700                    rid: "".to_string(),
701                    ssrc: Some(ssrc),
702                    rtx: None,
703                    fec: None,
704                },
705                codec,
706                ..Default::default()
707            });
708            true
709        }
710    }
711
712    pub(crate) fn set_codec_ssrc_by_rid(
713        &mut self,
714        codec: RTCRtpCodec,
715        ssrc: SSRC,
716        rid: &RtpStreamId,
717    ) -> bool {
718        if let Some(coding) = self
719            .codings
720            .iter_mut()
721            .find(|coding| &coding.rtp_coding_parameters.rid == rid)
722        {
723            coding.codec = codec;
724            coding.rtp_coding_parameters.ssrc = Some(ssrc);
725            false
726        } else {
727            self.codings.push(RTCRtpEncodingParameters {
728                rtp_coding_parameters: RTCRtpCodingParameters {
729                    rid: rid.to_string(),
730                    ssrc: Some(ssrc),
731                    rtx: None,
732                    fec: None,
733                },
734                codec,
735                ..Default::default()
736            });
737            true
738        }
739    }
740
741    pub(crate) fn get_codec_by_ssrc(&self, ssrc: SSRC) -> Option<&RTCRtpCodec> {
742        self.codings
743            .iter()
744            .find(|coding| {
745                coding
746                    .rtp_coding_parameters
747                    .ssrc
748                    .is_some_and(|t_ssrc| t_ssrc == ssrc)
749            })
750            .map(|coding| &coding.codec)
751    }
752
753    /// Returns the RTP encoding parameters (codings) configured for this track.
754    pub fn codings(&self) -> &[RTCRtpEncodingParameters] {
755        &self.codings
756    }
757
758    /// Adds an RTP encoding parameter (coding) to the track.
759    pub fn add_coding(&mut self, coding: RTCRtpEncodingParameters) {
760        self.codings.push(coding);
761    }
762}