Skip to content

Commit

Permalink
use native serde impl for SmolStr
Browse files Browse the repository at this point in the history
  • Loading branch information
luludotdev committed Jun 4, 2023
1 parent f8a8b6f commit 59fa7a0
Show file tree
Hide file tree
Showing 9 changed files with 43 additions and 74 deletions.
2 changes: 1 addition & 1 deletion webrtc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ bytes = "1"
thiserror = "1.0"
waitgroup = "0.1.2"
regex = "1.7.1"
smol_str = "0.2.0"
smol_str = { version = "0.2.0", features = ["serde"] }
url = "2.2"
rustls = { version = "0.19.0", features = ["dangerous_configuration"]}
rcgen = { version = "0.10.0", features = ["pem", "x509-parser"]}
Expand Down
24 changes: 0 additions & 24 deletions webrtc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ pub use rtcp;
pub use rtp;
pub use sctp;
pub use sdp;
use serde::{Deserialize, Serialize};
use smol_str::SmolStr;
pub use srtp;
pub use stun;
pub use turn;
Expand Down Expand Up @@ -45,25 +43,3 @@ pub(crate) const SDP_ATTRIBUTE_RID: &str = "rid";
pub(crate) const GENERATED_CERTIFICATE_ORIGIN: &str = "WebRTC";
pub(crate) const SDES_REPAIR_RTP_STREAM_ID_URI: &str =
"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id";

#[derive(Clone, Debug, Default, PartialEq)]
pub struct SmallStr(SmolStr);

impl Serialize for SmallStr {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self.0.as_str())
}
}

impl<'de> Deserialize<'de> for SmallStr {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Ok(SmallStr(SmolStr::new(s)))
}
}
22 changes: 9 additions & 13 deletions webrtc/src/peer_connection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ use crate::sctp_transport::RTCSctpTransport;
use crate::stats::StatsReport;
use crate::track::track_local::TrackLocal;
use crate::track::track_remote::TrackRemote;
use crate::SmallStr;

use ::ice::candidate::candidate_base::unmarshal_candidate;
use ::ice::candidate::Candidate;
Expand Down Expand Up @@ -458,7 +457,7 @@ impl RTCPeerConnection {
let mid = t.mid();
let m = mid
.as_ref()
.and_then(|mid| get_by_mid(mid.0.as_str(), local_desc));
.and_then(|mid| get_by_mid(mid.as_str(), local_desc));
// Step 5.2
if !t.stopped.load(Ordering::SeqCst) {
if m.is_none() {
Expand Down Expand Up @@ -499,7 +498,7 @@ impl RTCPeerConnection {
if let Some(remote_desc) = &current_remote_description {
if let Some(rm) = t
.mid()
.and_then(|mid| get_by_mid(mid.0.as_str(), remote_desc))
.and_then(|mid| get_by_mid(mid.as_str(), remote_desc))
{
if get_peer_direction(m) != t.direction()
&& get_peer_direction(rm) != t.direction().reverse()
Expand All @@ -518,7 +517,7 @@ impl RTCPeerConnection {
};
let offered_direction = match t
.mid()
.and_then(|mid| get_by_mid(mid.0.as_str(), remote_desc))
.and_then(|mid| get_by_mid(mid.as_str(), remote_desc))
{
Some(d) => {
let dir = get_peer_direction(d);
Expand Down Expand Up @@ -551,8 +550,8 @@ impl RTCPeerConnection {
};

if let Some(remote_desc) = &*params.current_remote_description.lock().await {
return get_by_mid(search_mid.0.as_str(), local_desc).is_some()
|| get_by_mid(search_mid.0.as_str(), remote_desc).is_some();
return get_by_mid(search_mid.as_str(), local_desc).is_some()
|| get_by_mid(search_mid.as_str(), remote_desc).is_some();
}
}
}
Expand Down Expand Up @@ -802,13 +801,10 @@ impl RTCPeerConnection {
}
}

t.set_mid(crate::SmallStr(SmolStr::from(mid)))?;
t.set_mid(SmolStr::from(mid))?;
} else {
let greater_mid = self.internal.greater_mid.fetch_add(1, Ordering::SeqCst);
t.set_mid(crate::SmallStr(SmolStr::from(format!(
"{}",
greater_mid + 1
))))?;
t.set_mid(SmolStr::from(format!("{}", greater_mid + 1)))?;
}
}

Expand Down Expand Up @@ -1368,7 +1364,7 @@ impl RTCPeerConnection {

if let Some(t) = t {
if t.mid().is_none() {
t.set_mid(crate::SmallStr(SmolStr::from(mid_value)))?;
t.set_mid(SmolStr::from(mid_value))?;
}
} else {
let local_direction =
Expand Down Expand Up @@ -1414,7 +1410,7 @@ impl RTCPeerConnection {
self.internal.add_rtp_transceiver(Arc::clone(&t)).await;

if t.mid().is_none() {
t.set_mid(SmallStr(SmolStr::from(mid_value)))?;
t.set_mid(SmolStr::from(mid_value))?;
}
}
}
Expand Down
20 changes: 10 additions & 10 deletions webrtc/src/peer_connection/peer_connection_internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::stats::{
StatsReportType,
};
use crate::track::TrackStream;
use crate::{SmallStr, SDES_REPAIR_RTP_STREAM_ID_URI, SDP_ATTRIBUTE_RID};
use crate::{SDES_REPAIR_RTP_STREAM_ID_URI, SDP_ATTRIBUTE_RID};
use arc_swap::ArcSwapOption;
use std::collections::VecDeque;
use std::sync::atomic::AtomicIsize;
Expand Down Expand Up @@ -178,7 +178,7 @@ impl PeerConnectionInternal {
for t in tracks {
if !t.rid().is_empty() {
if let Some(details) =
track_details_for_rid(&track_details, SmallStr(SmolStr::from(t.rid())))
track_details_for_rid(&track_details, SmolStr::from(t.rid()))
{
t.set_id(details.id.clone());
t.set_stream_id(details.stream_id.clone());
Expand Down Expand Up @@ -669,7 +669,7 @@ impl PeerConnectionInternal {
// TODO: This is dubious because of rollbacks.
t.sender().await.set_negotiated();
media_sections.push(MediaSection {
id: t.mid().unwrap().0.to_string(),
id: t.mid().unwrap().to_string(),
transceivers: vec![Arc::clone(t)],
..Default::default()
});
Expand Down Expand Up @@ -783,7 +783,7 @@ impl PeerConnectionInternal {
for t in &local_transceivers {
t.sender().await.set_negotiated();
media_sections.push(MediaSection {
id: t.mid().unwrap().0.to_string(),
id: t.mid().unwrap().to_string(),
transceivers: vec![Arc::clone(t)],
..Default::default()
});
Expand Down Expand Up @@ -1004,7 +1004,7 @@ impl PeerConnectionInternal {

let transceivers = self.rtp_transceivers.lock().await;
for t in &*transceivers {
if t.mid().as_ref() != Some(&SmallStr(SmolStr::from(&mid))) {
if t.mid().as_ref() != Some(&SmolStr::from(&mid)) {
continue;
}

Expand All @@ -1028,7 +1028,7 @@ impl PeerConnectionInternal {

let track = receiver
.receive_for_rid(
SmallStr(SmolStr::from(rid)),
SmolStr::from(rid),
params,
TrackStream {
stream_info: Some(stream_info.clone()),
Expand Down Expand Up @@ -1167,7 +1167,7 @@ impl PeerConnectionInternal {
pub(super) async fn has_local_description_changed(&self, desc: &RTCSessionDescription) -> bool {
let rtp_transceivers = self.rtp_transceivers.lock().await;
for t in &*rtp_transceivers {
let m = match t.mid().and_then(|mid| get_by_mid(mid.0.as_str(), desc)) {
let m = match t.mid().and_then(|mid| get_by_mid(mid.as_str(), desc)) {
Some(m) => m,
None => return true,
};
Expand Down Expand Up @@ -1204,7 +1204,7 @@ impl PeerConnectionInternal {
// TODO: There's a lot of await points here that could run concurrently with `futures::join_all`.
struct TrackInfo {
ssrc: SSRC,
mid: SmallStr,
mid: SmolStr,
track_id: String,
kind: &'static str,
}
Expand Down Expand Up @@ -1329,8 +1329,8 @@ impl PeerConnectionInternal {
struct TrackInfo {
track_id: String,
ssrc: SSRC,
mid: SmallStr,
rid: Option<SmallStr>,
mid: SmolStr,
rid: Option<SmolStr>,
kind: &'static str,
}
let mut track_infos = vec![];
Expand Down
17 changes: 8 additions & 9 deletions webrtc/src/peer_connection/sdp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub mod sdp_type;
pub mod session_description;

use crate::peer_connection::MEDIA_SECTION_APPLICATION;
use crate::{SmallStr, SDP_ATTRIBUTE_RID};
use crate::SDP_ATTRIBUTE_RID;
use ice::candidate::candidate_base::unmarshal_candidate;
use ice::candidate::Candidate;
use sdp::description::common::{Address, ConnectionInformation};
Expand All @@ -38,13 +38,13 @@ use url::Url;
/// This isn't keyed by SSRC because it also needs to support rid based sources
#[derive(Default, Debug, Clone)]
pub(crate) struct TrackDetails {
pub(crate) mid: SmallStr,
pub(crate) mid: SmolStr,
pub(crate) kind: RTPCodecType,
pub(crate) stream_id: String,
pub(crate) id: String,
pub(crate) ssrcs: Vec<SSRC>,
pub(crate) repair_ssrc: SSRC,
pub(crate) rids: Vec<SmallStr>,
pub(crate) rids: Vec<SmolStr>,
}

pub(crate) fn track_details_for_ssrc(
Expand All @@ -56,7 +56,7 @@ pub(crate) fn track_details_for_ssrc(

pub(crate) fn track_details_for_rid(
track_details: &[TrackDetails],
rid: SmallStr,
rid: SmolStr,
) -> Option<&TrackDetails> {
track_details.iter().find(|x| x.rids.contains(&rid))
}
Expand Down Expand Up @@ -186,16 +186,15 @@ pub(crate) fn track_details_from_sdp(
}

if track_idx < tracks_in_media_section.len() {
tracks_in_media_section[track_idx].mid =
SmallStr(SmolStr::from(mid_value));
tracks_in_media_section[track_idx].mid = SmolStr::from(mid_value);
tracks_in_media_section[track_idx].kind = codec_type;
tracks_in_media_section[track_idx].stream_id = stream_id.to_owned();
tracks_in_media_section[track_idx].id = track_id.to_owned();
tracks_in_media_section[track_idx].ssrcs = vec![ssrc];
tracks_in_media_section[track_idx].repair_ssrc = repair_ssrc;
} else {
let track_details = TrackDetails {
mid: SmallStr(SmolStr::from(mid_value)),
mid: SmolStr::from(mid_value),
kind: codec_type,
stream_id: stream_id.to_owned(),
id: track_id.to_owned(),
Expand All @@ -214,15 +213,15 @@ pub(crate) fn track_details_from_sdp(
let rids = get_rids(media);
if !rids.is_empty() && !track_id.is_empty() && !stream_id.is_empty() {
let mut simulcast_track = TrackDetails {
mid: SmallStr(SmolStr::from(mid_value)),
mid: SmolStr::from(mid_value),
kind: codec_type,
stream_id: stream_id.to_owned(),
id: track_id.to_owned(),
rids: vec![],
..Default::default()
};
for rid in rids.keys() {
simulcast_track.rids.push(SmallStr(SmolStr::from(rid)));
simulcast_track.rids.push(SmolStr::from(rid));
}
if simulcast_track.rids.len() == tracks_in_media_section.len() {
for track in &tracks_in_media_section {
Expand Down
11 changes: 5 additions & 6 deletions webrtc/src/rtp_transceiver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use interceptor::{
};
use smol_str::SmolStr;

use crate::SmallStr;
use log::trace;
use serde::{Deserialize, Serialize};
use std::fmt;
Expand Down Expand Up @@ -96,7 +95,7 @@ pub struct RTCRtpRtxParameters {
/// <http://draft.ortc.org/#dom-rtcrtpcodingparameters>
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RTCRtpCodingParameters {
pub rid: SmallStr,
pub rid: SmolStr,
pub ssrc: SSRC,
pub payload_type: PayloadType,
pub rtx: RTCRtpRtxParameters,
Expand Down Expand Up @@ -175,7 +174,7 @@ pub type TriggerNegotiationNeededFnOption =

/// RTPTransceiver represents a combination of an RTPSender and an RTPReceiver that share a common mid.
pub struct RTCRtpTransceiver {
mid: OnceCell<SmallStr>, //atomic.Value
mid: OnceCell<SmolStr>, //atomic.Value
sender: Mutex<Arc<RTCRtpSender>>, //atomic.Value
receiver: Mutex<Arc<RTCRtpReceiver>>, //atomic.Value

Expand Down Expand Up @@ -296,14 +295,14 @@ impl RTCRtpTransceiver {
}

/// set_mid sets the RTPTransceiver's mid. If it was already set, will return an error.
pub(crate) fn set_mid(&self, mid: SmallStr) -> Result<()> {
pub(crate) fn set_mid(&self, mid: SmolStr) -> Result<()> {
self.mid
.set(mid)
.map_err(|_| Error::ErrRTPTransceiverCannotChangeMid)
}

/// mid gets the Transceiver's mid value. When not already set, this value will be set in CreateOffer or create_answer.
pub fn mid(&self) -> Option<SmallStr> {
pub fn mid(&self) -> Option<SmolStr> {
self.mid.get().map(Clone::clone)
}

Expand Down Expand Up @@ -482,7 +481,7 @@ pub(crate) async fn find_by_mid(
local_transceivers: &mut Vec<Arc<RTCRtpTransceiver>>,
) -> Option<Arc<RTCRtpTransceiver>> {
for (i, t) in local_transceivers.iter().enumerate() {
if t.mid() == Some(SmallStr(SmolStr::from(mid))) {
if t.mid() == Some(SmolStr::from(mid)) {
return Some(local_transceivers.remove(i));
}
}
Expand Down
5 changes: 2 additions & 3 deletions webrtc/src/rtp_transceiver/rtp_receiver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use crate::rtp_transceiver::{
};
use crate::track::track_remote::TrackRemote;
use crate::track::{TrackStream, TrackStreams};
use crate::SmallStr;

use arc_swap::ArcSwapOption;
use interceptor::stream_info::RTPHeaderExtension;
Expand Down Expand Up @@ -760,13 +759,13 @@ impl RTCRtpReceiver {
/// It populates all the internal state for the given RID
pub(crate) async fn receive_for_rid(
&self,
rid: SmallStr,
rid: SmolStr,
params: RTCRtpParameters,
stream: TrackStream,
) -> Result<Arc<TrackRemote>> {
let mut tracks = self.internal.tracks.write().await;
for t in &mut *tracks {
if SmallStr(SmolStr::from(t.track.rid())) == rid {
if SmolStr::from(t.track.rid()) == rid {
t.track.set_kind(self.kind);
if let Some(codec) = params.codecs.first() {
t.track.set_codec(codec.clone());
Expand Down
8 changes: 4 additions & 4 deletions webrtc/src/stats/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ use crate::peer_connection::certificate::RTCCertificate;
use crate::rtp_transceiver::rtp_codec::RTCRtpCodecParameters;
use crate::rtp_transceiver::{PayloadType, SSRC};
use crate::sctp_transport::RTCSctpTransport;
use crate::SmallStr;

use ice::agent::agent_stats::{CandidatePairStats, CandidateStats};
use ice::agent::Agent;
use ice::candidate::{CandidatePairState, CandidateType};
use ice::network_type::NetworkType;
use smol_str::SmolStr;
use stats_collector::StatsCollector;

use serde::{Serialize, Serializer};
Expand Down Expand Up @@ -460,7 +460,7 @@ pub struct InboundRTPStats {

// RTCInboundRtpStreamStats
pub track_identifier: String,
pub mid: SmallStr,
pub mid: SmolStr,
// TODO: `remoteId`
// NB: `framesDecoded`, `frameWidth`, frameHeight`, `framesPerSecond`, `qpSum`,
// `totalDecodeTime`, `totalInterFrameDelay`, and `totalSquaredInterFrameDelay` are all decoder
Expand Down Expand Up @@ -505,9 +505,9 @@ pub struct OutboundRTPStats {
// RTCOutboundRtpStreamStats
// NB: non-canon in browsers this is available via `RTCMediaSourceStats` which we are unlikely to implement
pub track_identifier: String,
pub mid: SmallStr,
pub mid: SmolStr,
// TODO: `mediaSourceId` and `remoteId`
pub rid: Option<SmallStr>,
pub rid: Option<SmolStr>,
pub header_bytes_sent: u64,
// TODO: `retransmittedPacketsSent` and `retransmittedPacketsSent`
// NB: `targetBitrate`, `totalEncodedBytesTarget`, `frameWidth` `frameHeight`, `framesPerSecond`, `framesSent`,
Expand Down
Loading

0 comments on commit 59fa7a0

Please sign in to comment.