1
0
Fork 0
mirror of https://github.com/sile/hls_m3u8.git synced 2024-05-18 16:28:20 +00:00

minor changes + more tests #25

This commit is contained in:
Luro02 2019-10-06 16:39:18 +02:00
parent 3dad1277ca
commit b1c1ea8bdc
11 changed files with 281 additions and 42 deletions

View file

@ -36,10 +36,10 @@
//! assert!(m3u8.parse::<MediaPlaylist>().is_ok());
//! ```
pub use error::{Error, ErrorKind};
pub use master_playlist::{MasterPlaylist, MasterPlaylistBuilder};
pub use media_playlist::{MediaPlaylist, MediaPlaylistBuilder};
pub use media_segment::{MediaSegment, MediaSegmentBuilder};
pub use error::Error;
pub use master_playlist::MasterPlaylist;
pub use media_playlist::MediaPlaylist;
pub use media_segment::MediaSegment;
pub mod tags;
pub mod types;

View file

@ -22,40 +22,40 @@ impl FromStr for Lines {
let mut stream_inf_line = None;
for l in input.lines() {
let line = l.trim();
let raw_line = l.trim();
if line.is_empty() {
if raw_line.is_empty() {
continue;
}
let pline = {
if line.starts_with(tags::ExtXStreamInf::PREFIX) {
let line = {
if raw_line.starts_with(tags::ExtXStreamInf::PREFIX) {
stream_inf = true;
stream_inf_line = Some(line);
stream_inf_line = Some(raw_line);
continue;
} else if line.starts_with("#EXT") {
Line::Tag(line.parse()?)
} else if line.starts_with('#') {
} else if raw_line.starts_with("#EXT") {
Line::Tag(raw_line.parse()?)
} else if raw_line.starts_with('#') {
continue; // ignore comments
} else {
// stream inf line needs special treatment
if stream_inf {
stream_inf = false;
if let Some(first_line) = stream_inf_line {
let res = Line::Tag(format!("{}\n{}", first_line, line).parse()?);
let res = Line::Tag(format!("{}\n{}", first_line, raw_line).parse()?);
stream_inf_line = None;
res
} else {
continue;
}
} else {
Line::Uri(line.trim().to_string())
Line::Uri(raw_line.to_string())
}
}
};
result.push(pline);
result.push(line);
}
Ok(result)

View file

@ -38,6 +38,8 @@ pub struct MediaSegment {
impl MediaSegment {
/// Returns a Builder for a [`MasterPlaylist`].
///
/// [`MasterPlaylist`]: crate::MasterPlaylist
pub fn builder() -> MediaSegmentBuilder { MediaSegmentBuilder::default() }
/// Returns the `URI` of the media segment.
@ -161,7 +163,7 @@ impl fmt::Display for MediaSegment {
if let Some(value) = &self.program_date_time_tag {
writeln!(f, "{}", value)?;
}
writeln!(f, "{},", self.inf_tag)?;
writeln!(f, "{}", self.inf_tag)?; // TODO: there might be a `,` missing
writeln!(f, "{}", self.uri)?;
Ok(())
}
@ -186,3 +188,33 @@ impl Encrypted for MediaSegment {
fn keys_mut(&mut self) -> &mut Vec<ExtXKey> { &mut self.keys }
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn test_display() {
assert_eq!(
MediaSegment::builder()
.keys(vec![ExtXKey::empty()])
.map_tag(ExtXMap::new("https://www.example.com/"))
.byte_range_tag(ExtXByteRange::new(20, Some(5)))
//.date_range_tag() // TODO!
.discontinuity_tag(ExtXDiscontinuity)
.inf_tag(ExtInf::new(Duration::from_secs(4)))
.uri("http://www.uri.com/")
.build()
.unwrap()
.to_string(),
"#EXT-X-KEY:METHOD=NONE\n\
#EXT-X-MAP:URI=\"https://www.example.com/\"\n\
#EXT-X-BYTERANGE:20@5\n\
#EXT-X-DISCONTINUITY\n\
#EXTINF:4,\n\
http://www.uri.com/\n"
.to_string()
);
}
}

View file

@ -191,6 +191,33 @@ impl DerefMut for ExtXIFrameStreamInf {
mod test {
use super::*;
#[test]
fn test_builder() {
let mut i_frame_stream_inf =
ExtXIFrameStreamInf::new("http://example.com/audio-only.m3u8", 200_000);
i_frame_stream_inf
.set_average_bandwidth(Some(100_000))
.set_codecs(Some("mp4a.40.5"))
.set_resolution(1920, 1080)
.set_hdcp_level(Some(HdcpLevel::None))
.set_video(Some("video"));
assert_eq!(
ExtXIFrameStreamInf::builder()
.uri("http://example.com/audio-only.m3u8")
.bandwidth(200_000)
.average_bandwidth(100_000)
.codecs("mp4a.40.5")
.resolution((1920, 1080))
.hdcp_level(HdcpLevel::None)
.video("video")
.build()
.unwrap(),
i_frame_stream_inf
);
}
#[test]
fn test_display() {
assert_eq!(

View file

@ -32,7 +32,7 @@ pub struct ExtXMedia {
/// # Note
/// This attribute is **required**.
media_type: MediaType,
#[builder(setter(strip_option, into), default)]
#[builder(setter(strip_option), default)]
/// Sets the `URI` that identifies the [`Media Playlist`].
///
/// # Note
@ -49,7 +49,7 @@ pub struct ExtXMedia {
/// # Note
/// This attribute is **required**.
group_id: String,
#[builder(setter(strip_option, into), default)]
#[builder(setter(strip_option), default)]
/// Sets the name of the primary language used in the rendition.
/// The value has to conform to [`RFC5646`].
///
@ -58,7 +58,7 @@ pub struct ExtXMedia {
///
/// [`RFC5646`]: https://tools.ietf.org/html/rfc5646
language: Option<String>,
#[builder(setter(strip_option, into), default)]
#[builder(setter(strip_option), default)]
/// Sets the name of a language associated with the rendition.
///
/// # Note
@ -93,14 +93,14 @@ pub struct ExtXMedia {
#[builder(default)]
/// Sets the value of the `forced` flag.
is_forced: bool,
#[builder(setter(strip_option, into), default)]
#[builder(setter(strip_option), default)]
/// Sets the identifier that specifies a rendition within the segments in
/// the media playlist.
instream_id: Option<InStreamId>,
#[builder(setter(strip_option, into), default)]
#[builder(setter(strip_option), default)]
/// Sets the string that represents uniform type identifiers (UTI).
characteristics: Option<String>,
#[builder(setter(strip_option, into), default)]
#[builder(setter(strip_option), default)]
/// Sets the parameters of the rendition.
channels: Option<Channels>,
}

View file

@ -226,6 +226,9 @@ mod test {
"#EXTINF:5,title".parse::<ExtInf>().unwrap(),
ExtInf::with_title(Duration::from_secs(5), "title")
);
assert!("#EXTINF:".parse::<ExtInf>().is_err());
assert!("#EXTINF:garbage".parse::<ExtInf>().is_err());
}
#[test]
@ -248,4 +251,12 @@ mod test {
ProtocolVersion::V3
);
}
#[test]
fn test_from() {
assert_eq!(
ExtInf::from(Duration::from_secs(1)),
ExtInf::new(Duration::from_secs(1))
);
}
}

View file

@ -7,13 +7,13 @@ use crate::types::{ByteRange, ProtocolVersion};
use crate::utils::{quote, tag, unquote};
use crate::{Encrypted, Error, RequiredVersion};
/// # [4.4.2.5. EXT-X-MAP]
/// The [`ExtXMap`] tag specifies how to obtain the Media Initialization
/// Section, required to parse the applicable [Media Segment]s.
/// # [4.3.2.5. EXT-X-MAP]
///
/// [Media Segment]: crate::MediaSegment
/// [4.4.2.5. EXT-X-MAP]:
/// https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-04#section-4.4.2.5
/// The [`ExtXMap`] tag specifies how to obtain the Media Initialization
/// Section, required to parse the applicable [`MediaSegment`]s.
///
/// [`MediaSegment`]: crate::MediaSegment
/// [4.3.2.5. EXT-X-MAP]: https://tools.ietf.org/html/rfc8216#section-4.3.2.5
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExtXMap {
uri: String,
@ -25,6 +25,12 @@ impl ExtXMap {
pub(crate) const PREFIX: &'static str = "#EXT-X-MAP:";
/// Makes a new [`ExtXMap`] tag.
///
/// # Example
/// ```
/// # use hls_m3u8::tags::ExtXMap;
/// let map = ExtXMap::new("https://prod.mediaspace.com/init.bin");
/// ```
pub fn new<T: ToString>(uri: T) -> Self {
Self {
uri: uri.to_string(),
@ -34,6 +40,17 @@ impl ExtXMap {
}
/// Makes a new [`ExtXMap`] tag with the given range.
///
/// # Example
/// ```
/// # use hls_m3u8::tags::ExtXMap;
/// use hls_m3u8::types::ByteRange;
///
/// let map = ExtXMap::with_range(
/// "https://prod.mediaspace.com/init.bin",
/// ByteRange::new(9, Some(2)),
/// );
/// ```
pub fn with_range<T: ToString>(uri: T, range: ByteRange) -> Self {
Self {
uri: uri.to_string(),
@ -42,12 +59,75 @@ impl ExtXMap {
}
}
/// Returns the `URI` that identifies a resource,
/// that contains the media initialization section.
/// Returns the `URI` that identifies a resource, that contains the media
/// initialization section.
///
/// # Example
/// ```
/// # use hls_m3u8::tags::ExtXMap;
/// let map = ExtXMap::new("https://prod.mediaspace.com/init.bin");
///
/// assert_eq!(
/// map.uri(),
/// &"https://prod.mediaspace.com/init.bin".to_string()
/// );
/// ```
pub const fn uri(&self) -> &String { &self.uri }
/// Sets the `URI` that identifies a resource, that contains the media
/// initialization section.
///
/// # Example
/// ```
/// # use hls_m3u8::tags::ExtXMap;
/// let mut map = ExtXMap::new("https://prod.mediaspace.com/init.bin");
///
/// map.set_uri("https://dev.mediaspace.com/init.bin");
/// assert_eq!(
/// map.uri(),
/// &"https://dev.mediaspace.com/init.bin".to_string()
/// );
/// ```
pub fn set_uri<T: ToString>(&mut self, value: T) -> &mut Self {
self.uri = value.to_string();
self
}
/// Returns the range of the media initialization section.
///
/// # Example
/// ```
/// # use hls_m3u8::tags::ExtXMap;
/// use hls_m3u8::types::ByteRange;
///
/// let map = ExtXMap::with_range(
/// "https://prod.mediaspace.com/init.bin",
/// ByteRange::new(9, Some(2)),
/// );
///
/// assert_eq!(map.range(), Some(ByteRange::new(9, Some(2))));
/// ```
pub const fn range(&self) -> Option<ByteRange> { self.range }
/// Sets the range of the media initialization section.
///
/// # Example
/// ```
/// # use hls_m3u8::tags::ExtXMap;
/// use hls_m3u8::types::ByteRange;
///
/// let mut map = ExtXMap::with_range(
/// "https://prod.mediaspace.com/init.bin",
/// ByteRange::new(9, Some(2)),
/// );
///
/// map.set_range(Some(ByteRange::new(1, None)));
/// assert_eq!(map.range(), Some(ByteRange::new(1, None)));
/// ```
pub fn set_range(&mut self, value: Option<ByteRange>) -> &mut Self {
self.range = value;
self
}
}
impl Encrypted for ExtXMap {
@ -87,7 +167,7 @@ impl FromStr for ExtXMap {
match key.as_str() {
"URI" => uri = Some(unquote(value)),
"BYTERANGE" => {
range = Some((unquote(value).parse())?);
range = Some(unquote(value).parse()?);
}
_ => {
// [6.3.1. General Client Responsibilities]
@ -134,6 +214,12 @@ mod test {
ExtXMap::with_range("foo", ByteRange::new(9, Some(2))),
"#EXT-X-MAP:URI=\"foo\",BYTERANGE=\"9@2\"".parse().unwrap()
);
assert_eq!(
ExtXMap::with_range("foo", ByteRange::new(9, Some(2))),
"#EXT-X-MAP:URI=\"foo\",BYTERANGE=\"9@2\",UNKNOWN=IGNORED"
.parse()
.unwrap()
);
}
#[test]
@ -144,4 +230,10 @@ mod test {
ProtocolVersion::V6
);
}
#[test]
fn test_encrypted() {
assert_eq!(ExtXMap::new("foo").keys(), &vec![]);
assert_eq!(ExtXMap::new("foo").keys_mut(), &mut vec![]);
}
}

View file

@ -2,7 +2,7 @@ use std::fmt;
use std::ops::{Deref, DerefMut};
use std::str::FromStr;
use chrono::{DateTime, FixedOffset};
use chrono::{DateTime, FixedOffset, SecondsFormat};
use crate::types::ProtocolVersion;
use crate::utils::tag;
@ -24,8 +24,8 @@ impl ExtXProgramDateTime {
///
/// # Example
/// ```
/// # use hls_m3u8::tags::ExtXProgramDateTime;
/// use chrono::{FixedOffset, TimeZone};
/// use hls_m3u8::tags::ExtXProgramDateTime;
///
/// const HOURS_IN_SECS: i32 = 3600; // 1 hour = 3600 seconds
///
@ -39,22 +39,71 @@ impl ExtXProgramDateTime {
/// Returns the date-time of the first sample of the associated media
/// segment.
///
/// # Example
/// ```
/// # use hls_m3u8::tags::ExtXProgramDateTime;
/// use chrono::{FixedOffset, TimeZone};
///
/// const HOURS_IN_SECS: i32 = 3600; // 1 hour = 3600 seconds
///
/// let program_date_time = ExtXProgramDateTime::new(
/// FixedOffset::east(8 * HOURS_IN_SECS)
/// .ymd(2010, 2, 19)
/// .and_hms_milli(14, 54, 23, 31),
/// );
///
/// assert_eq!(
/// program_date_time.date_time(),
/// FixedOffset::east(8 * HOURS_IN_SECS)
/// .ymd(2010, 2, 19)
/// .and_hms_milli(14, 54, 23, 31)
/// );
/// ```
pub const fn date_time(&self) -> DateTime<FixedOffset> { self.0 }
/// Sets the date-time of the first sample of the associated media segment.
///
/// # Example
/// ```
/// # use hls_m3u8::tags::ExtXProgramDateTime;
/// use chrono::{FixedOffset, TimeZone};
///
/// const HOURS_IN_SECS: i32 = 3600; // 1 hour = 3600 seconds
///
/// let mut program_date_time = ExtXProgramDateTime::new(
/// FixedOffset::east(8 * HOURS_IN_SECS)
/// .ymd(2010, 2, 19)
/// .and_hms_milli(14, 54, 23, 31),
/// );
///
/// program_date_time.set_date_time(
/// FixedOffset::east(8 * HOURS_IN_SECS)
/// .ymd(2010, 10, 10)
/// .and_hms_milli(10, 10, 10, 10),
/// );
///
/// assert_eq!(
/// program_date_time.date_time(),
/// FixedOffset::east(8 * HOURS_IN_SECS)
/// .ymd(2010, 10, 10)
/// .and_hms_milli(10, 10, 10, 10)
/// );
/// ```
pub fn set_date_time(&mut self, value: DateTime<FixedOffset>) -> &mut Self {
self.0 = value;
self
}
}
/// This tag requires [`ProtocolVersion::V1`].
impl RequiredVersion for ExtXProgramDateTime {
fn required_version(&self) -> ProtocolVersion { ProtocolVersion::V1 }
}
impl fmt::Display for ExtXProgramDateTime {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let date_time = self.0.to_rfc3339();
let date_time = self.0.to_rfc3339_opts(SecondsFormat::Millis, true);
write!(f, "{}{}", Self::PREFIX, date_time)
}
}
@ -83,7 +132,7 @@ impl DerefMut for ExtXProgramDateTime {
#[cfg(test)]
mod test {
use super::*;
use chrono::TimeZone;
use chrono::{Datelike, TimeZone};
const HOURS_IN_SECS: i32 = 3600; // 1 hour = 3600 seconds
@ -126,4 +175,32 @@ mod test {
ProtocolVersion::V1
);
}
#[test]
fn test_deref() {
assert_eq!(
ExtXProgramDateTime::new(
FixedOffset::east(8 * HOURS_IN_SECS)
.ymd(2010, 2, 19)
.and_hms_milli(14, 54, 23, 31),
)
.year(),
2010
);
}
#[test]
fn test_deref_mut() {
assert_eq!(
ExtXProgramDateTime::new(
FixedOffset::east(8 * HOURS_IN_SECS)
.ymd(2010, 2, 19)
.and_hms_milli(14, 54, 23, 31),
)
.deref_mut(),
&mut FixedOffset::east(8 * HOURS_IN_SECS)
.ymd(2010, 2, 19)
.and_hms_milli(14, 54, 23, 31),
);
}
}

View file

@ -23,7 +23,7 @@ impl DecimalFloatingPoint {
/// otherwise this function will return an error that has the kind
/// `ErrorKind::InvalidInput`.
pub fn new(value: f64) -> crate::Result<Self> {
if value.is_sign_negative() || value.is_infinite() {
if value.is_sign_negative() || value.is_infinite() || value.is_nan() {
return Err(Error::invalid_input());
}
Ok(Self(value))
@ -54,7 +54,7 @@ impl From<f64> for DecimalFloatingPoint {
let mut result = value;
// guard against the unlikely case of an infinite value...
if result.is_infinite() {
if result.is_infinite() || result.is_nan() {
result = 0.0;
}

View file

@ -7,7 +7,7 @@ use crate::types::ProtocolVersion;
use crate::utils::{quote, unquote};
use crate::RequiredVersion;
/// A list of [usize], that can be used to indicate which version(s)
/// A list of [`usize`], that can be used to indicate which version(s)
/// this instance complies with, if more than one version of a particular
/// [`KeyFormat`] is defined.
///

View file

@ -10,20 +10,20 @@ use derive_more::{Display, FromStr};
pub(crate) struct SignedDecimalFloatingPoint(f64);
impl SignedDecimalFloatingPoint {
/// Makes a new [SignedDecimalFloatingPoint] instance.
/// Makes a new [`SignedDecimalFloatingPoint`] instance.
///
/// # Panics
/// The given value must be finite, otherwise this function will panic!
pub fn new(value: f64) -> Self {
if value.is_infinite() {
panic!("Floating point value must be finite!");
if value.is_infinite() || value.is_nan() {
panic!("Floating point value must be finite and not NaN!");
}
Self(value)
}
pub(crate) const fn from_f64_unchecked(value: f64) -> Self { Self(value) }
/// Converts [DecimalFloatingPoint] to [f64].
/// Converts [`DecimalFloatingPoint`] to [`f64`].
pub const fn as_f64(self) -> f64 { self.0 }
}