Skip to content

Commit f57676f

Browse files
gautamprikshit1rainliu
authored andcommitted
Switched mid and rid to SmolStr
1 parent 7bf1438 commit f57676f

File tree

9 files changed

+96
-52
lines changed

9 files changed

+96
-52
lines changed

webrtc/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ bytes = "1"
4040
thiserror = "1.0"
4141
waitgroup = "0.1.2"
4242
regex = "1.7.1"
43+
smol_str = "0.2.0"
4344
url = "2.2"
4445
rustls = { version = "0.19.0", features = ["dangerous_configuration"]}
4546
rcgen = { version = "0.10.0", features = ["pem", "x509-parser"]}

webrtc/src/lib.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ pub use rtcp;
1212
pub use rtp;
1313
pub use sctp;
1414
pub use sdp;
15+
use serde::{Deserialize, Serialize};
16+
use smol_str::SmolStr;
1517
pub use srtp;
1618
pub use stun;
1719
pub use turn;
@@ -43,3 +45,25 @@ pub(crate) const SDP_ATTRIBUTE_RID: &str = "rid";
4345
pub(crate) const GENERATED_CERTIFICATE_ORIGIN: &str = "WebRTC";
4446
pub(crate) const SDES_REPAIR_RTP_STREAM_ID_URI: &str =
4547
"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id";
48+
49+
#[derive(Clone, Debug, Default, PartialEq)]
50+
pub struct SmallStr(SmolStr);
51+
52+
impl Serialize for SmallStr {
53+
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
54+
where
55+
S: serde::Serializer,
56+
{
57+
serializer.serialize_str(self.0.as_str())
58+
}
59+
}
60+
61+
impl<'de> Deserialize<'de> for SmallStr {
62+
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
63+
where
64+
D: serde::Deserializer<'de>,
65+
{
66+
let s = String::deserialize(deserializer)?;
67+
Ok(SmallStr(SmolStr::new(s)))
68+
}
69+
}

webrtc/src/peer_connection/mod.rs

Lines changed: 30 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ use crate::sctp_transport::RTCSctpTransport;
6666
use crate::stats::StatsReport;
6767
use crate::track::track_local::TrackLocal;
6868
use crate::track::track_remote::TrackRemote;
69+
use crate::SmallStr;
6970

7071
use ::ice::candidate::candidate_base::unmarshal_candidate;
7172
use ::ice::candidate::Candidate;
@@ -77,6 +78,7 @@ use interceptor::{stats, Attributes, Interceptor, RTCPWriter};
7778
use peer_connection_internal::*;
7879
use rand::{thread_rng, Rng};
7980
use rcgen::KeyPair;
81+
use smol_str::SmolStr;
8082
use srtp::stream::Stream;
8183
use std::future::Future;
8284
use std::pin::Pin;
@@ -454,7 +456,9 @@ impl RTCPeerConnection {
454456
// return true
455457
// }
456458
let mid = t.mid();
457-
let m = mid.as_ref().and_then(|mid| get_by_mid(mid, local_desc));
459+
let m = mid
460+
.as_ref()
461+
.and_then(|mid| get_by_mid(mid.0.as_str(), local_desc));
458462
// Step 5.2
459463
if !t.stopped.load(Ordering::SeqCst) {
460464
if m.is_none() {
@@ -493,8 +497,9 @@ impl RTCPeerConnection {
493497
RTCSdpType::Offer => {
494498
// Step 5.3.2
495499
if let Some(remote_desc) = &current_remote_description {
496-
if let Some(rm) =
497-
t.mid().and_then(|mid| get_by_mid(&mid, remote_desc))
500+
if let Some(rm) = t
501+
.mid()
502+
.and_then(|mid| get_by_mid(mid.0.as_str(), remote_desc))
498503
{
499504
if get_peer_direction(m) != t.direction()
500505
&& get_peer_direction(rm) != t.direction().reverse()
@@ -511,18 +516,20 @@ impl RTCPeerConnection {
511516
Some(d) => d,
512517
None => return true,
513518
};
514-
let offered_direction =
515-
match t.mid().and_then(|mid| get_by_mid(&mid, remote_desc)) {
516-
Some(d) => {
517-
let dir = get_peer_direction(d);
518-
if dir == RTCRtpTransceiverDirection::Unspecified {
519-
RTCRtpTransceiverDirection::Inactive
520-
} else {
521-
dir
522-
}
519+
let offered_direction = match t
520+
.mid()
521+
.and_then(|mid| get_by_mid(mid.0.as_str(), remote_desc))
522+
{
523+
Some(d) => {
524+
let dir = get_peer_direction(d);
525+
if dir == RTCRtpTransceiverDirection::Unspecified {
526+
RTCRtpTransceiverDirection::Inactive
527+
} else {
528+
dir
523529
}
524-
None => RTCRtpTransceiverDirection::Inactive,
525-
};
530+
}
531+
None => RTCRtpTransceiverDirection::Inactive,
532+
};
526533

527534
let current_direction = get_peer_direction(m);
528535
// Step 5.3.3
@@ -544,8 +551,8 @@ impl RTCPeerConnection {
544551
};
545552

546553
if let Some(remote_desc) = &*params.current_remote_description.lock().await {
547-
return get_by_mid(&search_mid, local_desc).is_some()
548-
|| get_by_mid(&search_mid, remote_desc).is_some();
554+
return get_by_mid(search_mid.0.as_str(), local_desc).is_some()
555+
|| get_by_mid(search_mid.0.as_str(), remote_desc).is_some();
549556
}
550557
}
551558
}
@@ -795,10 +802,13 @@ impl RTCPeerConnection {
795802
}
796803
}
797804

798-
t.set_mid(mid)?;
805+
t.set_mid(crate::SmallStr(SmolStr::from(mid)))?;
799806
} else {
800807
let greater_mid = self.internal.greater_mid.fetch_add(1, Ordering::SeqCst);
801-
t.set_mid(format!("{}", greater_mid + 1))?;
808+
t.set_mid(crate::SmallStr(SmolStr::from(format!(
809+
"{}",
810+
greater_mid + 1
811+
))))?;
802812
}
803813
}
804814

@@ -1358,7 +1368,7 @@ impl RTCPeerConnection {
13581368

13591369
if let Some(t) = t {
13601370
if t.mid().is_none() {
1361-
t.set_mid(mid_value.to_owned())?;
1371+
t.set_mid(crate::SmallStr(SmolStr::from(mid_value)))?;
13621372
}
13631373
} else {
13641374
let local_direction =
@@ -1404,7 +1414,7 @@ impl RTCPeerConnection {
14041414
self.internal.add_rtp_transceiver(Arc::clone(&t)).await;
14051415

14061416
if t.mid().is_none() {
1407-
t.set_mid(mid_value.to_owned())?;
1417+
t.set_mid(SmallStr(SmolStr::from(mid_value)))?;
14081418
}
14091419
}
14101420
}

webrtc/src/peer_connection/peer_connection_internal.rs

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use bytes::Bytes;
2+
use smol_str::SmolStr;
23
use tokio::time::Instant;
34

45
use super::*;
@@ -9,7 +10,7 @@ use crate::stats::{
910
StatsReportType,
1011
};
1112
use crate::track::TrackStream;
12-
use crate::{SDES_REPAIR_RTP_STREAM_ID_URI, SDP_ATTRIBUTE_RID};
13+
use crate::{SmallStr, SDES_REPAIR_RTP_STREAM_ID_URI, SDP_ATTRIBUTE_RID};
1314
use arc_swap::ArcSwapOption;
1415
use std::collections::VecDeque;
1516
use std::sync::atomic::AtomicIsize;
@@ -177,7 +178,7 @@ impl PeerConnectionInternal {
177178
for t in tracks {
178179
if !t.rid().is_empty() {
179180
if let Some(details) =
180-
track_details_for_rid(&track_details, t.rid().to_owned())
181+
track_details_for_rid(&track_details, SmallStr(SmolStr::from(t.rid())))
181182
{
182183
t.set_id(details.id.clone());
183184
t.set_stream_id(details.stream_id.clone());
@@ -668,7 +669,7 @@ impl PeerConnectionInternal {
668669
// TODO: This is dubious because of rollbacks.
669670
t.sender().set_negotiated();
670671
media_sections.push(MediaSection {
671-
id: t.mid().unwrap(),
672+
id: t.mid().unwrap().0.to_string(),
672673
transceivers: vec![Arc::clone(t)],
673674
..Default::default()
674675
});
@@ -782,7 +783,7 @@ impl PeerConnectionInternal {
782783
for t in &local_transceivers {
783784
t.sender().set_negotiated();
784785
media_sections.push(MediaSection {
785-
id: t.mid().unwrap(),
786+
id: t.mid().unwrap().0.to_string(),
786787
transceivers: vec![Arc::clone(t)],
787788
..Default::default()
788789
});
@@ -1000,7 +1001,7 @@ impl PeerConnectionInternal {
10001001

10011002
let transceivers = self.rtp_transceivers.lock().await;
10021003
for t in &*transceivers {
1003-
if t.mid().as_ref() != Some(&mid) {
1004+
if t.mid().as_ref() != Some(&SmallStr(SmolStr::from(&mid))) {
10041005
continue;
10051006
}
10061007

@@ -1024,7 +1025,7 @@ impl PeerConnectionInternal {
10241025

10251026
let track = receiver
10261027
.receive_for_rid(
1027-
rid,
1028+
SmallStr(SmolStr::from(rid)),
10281029
params,
10291030
TrackStream {
10301031
stream_info: Some(stream_info.clone()),
@@ -1163,7 +1164,7 @@ impl PeerConnectionInternal {
11631164
pub(super) async fn has_local_description_changed(&self, desc: &RTCSessionDescription) -> bool {
11641165
let rtp_transceivers = self.rtp_transceivers.lock().await;
11651166
for t in &*rtp_transceivers {
1166-
let m = match t.mid().and_then(|mid| get_by_mid(&mid, desc)) {
1167+
let m = match t.mid().and_then(|mid| get_by_mid(mid.0.as_str(), desc)) {
11671168
Some(m) => m,
11681169
None => return true,
11691170
};
@@ -1200,7 +1201,7 @@ impl PeerConnectionInternal {
12001201
// TODO: There's a lot of await points here that could run concurrently with `futures::join_all`.
12011202
struct TrackInfo {
12021203
ssrc: SSRC,
1203-
mid: String,
1204+
mid: SmallStr,
12041205
track_id: String,
12051206
kind: &'static str,
12061207
}
@@ -1325,8 +1326,8 @@ impl PeerConnectionInternal {
13251326
struct TrackInfo {
13261327
track_id: String,
13271328
ssrc: SSRC,
1328-
mid: String,
1329-
rid: Option<String>,
1329+
mid: SmallStr,
1330+
rid: Option<SmallStr>,
13301331
kind: &'static str,
13311332
}
13321333
let mut track_infos = vec![];
@@ -1353,7 +1354,7 @@ impl PeerConnectionInternal {
13531354
track_infos.push(TrackInfo {
13541355
track_id,
13551356
ssrc: sender.ssrc,
1356-
mid: mid.clone(),
1357+
mid,
13571358
rid: None,
13581359
kind,
13591360
});

webrtc/src/peer_connection/sdp/mod.rs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,15 @@ pub mod sdp_type;
1919
pub mod session_description;
2020

2121
use crate::peer_connection::MEDIA_SECTION_APPLICATION;
22-
use crate::SDP_ATTRIBUTE_RID;
22+
use crate::{SmallStr, SDP_ATTRIBUTE_RID};
2323
use ice::candidate::candidate_base::unmarshal_candidate;
2424
use ice::candidate::Candidate;
2525
use sdp::description::common::{Address, ConnectionInformation};
2626
use sdp::description::media::{MediaDescription, MediaName, RangedPort};
2727
use sdp::description::session::*;
2828
use sdp::extmap::ExtMap;
2929
use sdp::util::ConnectionRole;
30+
use smol_str::SmolStr;
3031
use std::collections::HashMap;
3132
use std::convert::From;
3233
use std::io::BufReader;
@@ -37,13 +38,13 @@ use url::Url;
3738
/// This isn't keyed by SSRC because it also needs to support rid based sources
3839
#[derive(Default, Debug, Clone)]
3940
pub(crate) struct TrackDetails {
40-
pub(crate) mid: String,
41+
pub(crate) mid: SmallStr,
4142
pub(crate) kind: RTPCodecType,
4243
pub(crate) stream_id: String,
4344
pub(crate) id: String,
4445
pub(crate) ssrcs: Vec<SSRC>,
4546
pub(crate) repair_ssrc: SSRC,
46-
pub(crate) rids: Vec<String>,
47+
pub(crate) rids: Vec<SmallStr>,
4748
}
4849

4950
pub(crate) fn track_details_for_ssrc(
@@ -55,7 +56,7 @@ pub(crate) fn track_details_for_ssrc(
5556

5657
pub(crate) fn track_details_for_rid(
5758
track_details: &[TrackDetails],
58-
rid: String,
59+
rid: SmallStr,
5960
) -> Option<&TrackDetails> {
6061
track_details.iter().find(|x| x.rids.contains(&rid))
6162
}
@@ -185,15 +186,16 @@ pub(crate) fn track_details_from_sdp(
185186
}
186187

187188
if track_idx < tracks_in_media_section.len() {
188-
tracks_in_media_section[track_idx].mid = mid_value.to_owned();
189+
tracks_in_media_section[track_idx].mid =
190+
SmallStr(SmolStr::from(mid_value));
189191
tracks_in_media_section[track_idx].kind = codec_type;
190192
tracks_in_media_section[track_idx].stream_id = stream_id.to_owned();
191193
tracks_in_media_section[track_idx].id = track_id.to_owned();
192194
tracks_in_media_section[track_idx].ssrcs = vec![ssrc];
193195
tracks_in_media_section[track_idx].repair_ssrc = repair_ssrc;
194196
} else {
195197
let track_details = TrackDetails {
196-
mid: mid_value.to_owned(),
198+
mid: SmallStr(SmolStr::from(mid_value)),
197199
kind: codec_type,
198200
stream_id: stream_id.to_owned(),
199201
id: track_id.to_owned(),
@@ -212,15 +214,15 @@ pub(crate) fn track_details_from_sdp(
212214
let rids = get_rids(media);
213215
if !rids.is_empty() && !track_id.is_empty() && !stream_id.is_empty() {
214216
let mut simulcast_track = TrackDetails {
215-
mid: mid_value.to_owned(),
217+
mid: SmallStr(SmolStr::from(mid_value)),
216218
kind: codec_type,
217219
stream_id: stream_id.to_owned(),
218220
id: track_id.to_owned(),
219221
rids: vec![],
220222
..Default::default()
221223
};
222224
for rid in rids.keys() {
223-
simulcast_track.rids.push(rid.to_owned());
225+
simulcast_track.rids.push(SmallStr(SmolStr::from(rid)));
224226
}
225227
if simulcast_track.rids.len() == tracks_in_media_section.len() {
226228
for track in &tracks_in_media_section {

webrtc/src/rtp_transceiver/mod.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ use interceptor::{
1313
stream_info::{RTPHeaderExtension, StreamInfo},
1414
Attributes,
1515
};
16+
use smol_str::SmolStr;
1617

18+
use crate::SmallStr;
1719
use log::trace;
1820
use serde::{Deserialize, Serialize};
1921
use std::fmt;
@@ -95,7 +97,7 @@ pub struct RTCRtpRtxParameters {
9597
/// <http://draft.ortc.org/#dom-rtcrtpcodingparameters>
9698
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
9799
pub struct RTCRtpCodingParameters {
98-
pub rid: String,
100+
pub rid: SmallStr,
99101
pub ssrc: SSRC,
100102
pub payload_type: PayloadType,
101103
pub rtx: RTCRtpRtxParameters,
@@ -174,7 +176,7 @@ pub type TriggerNegotiationNeededFnOption =
174176

175177
/// RTPTransceiver represents a combination of an RTPSender and an RTPReceiver that share a common mid.
176178
pub struct RTCRtpTransceiver {
177-
mid: OnceCell<String>, //atomic.Value
179+
mid: OnceCell<SmallStr>, //atomic.Value
178180
sender: SyncMutex<Arc<RTCRtpSender>>, //atomic.Value
179181
receiver: SyncMutex<Arc<RTCRtpReceiver>>, //atomic.Value
180182

@@ -293,14 +295,14 @@ impl RTCRtpTransceiver {
293295
}
294296

295297
/// set_mid sets the RTPTransceiver's mid. If it was already set, will return an error.
296-
pub(crate) fn set_mid(&self, mid: String) -> Result<()> {
298+
pub(crate) fn set_mid(&self, mid: SmallStr) -> Result<()> {
297299
self.mid
298300
.set(mid)
299301
.map_err(|_| Error::ErrRTPTransceiverCannotChangeMid)
300302
}
301303

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

@@ -479,7 +481,7 @@ pub(crate) async fn find_by_mid(
479481
local_transceivers: &mut Vec<Arc<RTCRtpTransceiver>>,
480482
) -> Option<Arc<RTCRtpTransceiver>> {
481483
for (i, t) in local_transceivers.iter().enumerate() {
482-
if t.mid().as_deref() == Some(mid) {
484+
if t.mid() == Some(SmallStr(SmolStr::from(mid))) {
483485
return Some(local_transceivers.remove(i));
484486
}
485487
}

0 commit comments

Comments
 (0)