1use crate::error::Result;
3use alloc::{string::String, vec::Vec};
4use scte35_splice::{
5 SpliceInfoSection,
6 commands::{AnyCommand, ProgramSplice, SpliceMode},
7 descriptors::{AnySpliceDescriptor, SegmentationTypeId},
8};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
13pub struct MediaTime(u64);
14
15impl MediaTime {
16 #[must_use]
18 pub const fn from_90khz_ticks(ticks: u64) -> Self {
19 Self(ticks)
20 }
21
22 #[must_use]
24 pub const fn ticks_90khz(self) -> u64 {
25 self.0
26 }
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
32pub struct MediaDuration(u64);
33
34impl MediaDuration {
35 #[must_use]
37 pub const fn from_90khz_ticks(ticks: u64) -> Self {
38 Self(ticks)
39 }
40
41 #[must_use]
43 pub const fn ticks_90khz(self) -> u64 {
44 self.0
45 }
46
47 pub fn as_seconds_f64(self) -> f64 {
49 self.0 as f64 / broadcast_common::clock33::PTS_HZ as f64
50 }
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
56#[non_exhaustive]
57pub enum EventKind {
58 BreakStart,
60 BreakEnd,
62 Chapter,
64 Unspecified,
66}
67
68impl EventKind {
69 pub fn name(&self) -> &'static str {
71 match self {
72 EventKind::BreakStart => "break_start",
73 EventKind::BreakEnd => "break_end",
74 EventKind::Chapter => "chapter",
75 EventKind::Unspecified => "unspecified",
76 }
77 }
78}
79broadcast_core::impl_spec_display!(EventKind);
80
81#[derive(Debug, Clone, PartialEq, Eq)]
83#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
84#[non_exhaustive]
85pub enum SourcePayload {
86 Scte35 {
88 raw: Vec<u8>,
90 },
91 Emsg {
93 scheme_id_uri: String,
95 value: String,
97 raw: Vec<u8>,
99 },
100}
101
102#[derive(Debug, Clone, PartialEq, Eq)]
104#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
105#[non_exhaustive]
106pub struct TimedEvent {
107 pub id: Option<u32>,
109 pub kind: EventKind,
111 pub at: Option<MediaTime>,
113 pub duration: Option<MediaDuration>,
115 pub source: SourcePayload,
117}
118
119impl TimedEvent {
120 #[must_use]
124 pub fn new(kind: EventKind, source: SourcePayload) -> Self {
125 Self {
126 id: None,
127 kind,
128 at: None,
129 duration: None,
130 source,
131 }
132 }
133
134 #[must_use]
136 pub fn with_id(mut self, id: u32) -> Self {
137 self.id = Some(id);
138 self
139 }
140
141 #[must_use]
143 pub fn with_at(mut self, at: MediaTime) -> Self {
144 self.at = Some(at);
145 self
146 }
147
148 #[must_use]
150 pub fn with_duration(mut self, duration: MediaDuration) -> Self {
151 self.duration = Some(duration);
152 self
153 }
154
155 pub fn from_scte35(section: &SpliceInfoSection, raw: &[u8]) -> Result<Self> {
163 let mut id = None;
164 let mut kind = EventKind::Unspecified;
165 let mut at = None;
166 let mut duration = None;
167
168 let adjust = |pts: broadcast_common::clock33::Clock33| {
169 MediaTime::from_90khz_ticks(broadcast_common::clock33::add(
170 pts.ticks(),
171 section.pts_adjustment,
172 ))
173 };
174
175 if let Some(clear) = §ion.clear {
176 match &clear.command {
177 AnyCommand::SpliceInsert(si) => {
178 id = Some(si.splice_event_id);
179 kind = if si.cancel.is_some() {
180 EventKind::Unspecified
183 } else if si.out_of_network_indicator {
184 EventKind::BreakStart
185 } else {
186 EventKind::BreakEnd
187 };
188 if let SpliceMode::Program(ProgramSplice::At(st)) = &si.mode {
189 at = st.pts_time.map(adjust);
190 }
191 if let Some(bd) = &si.break_duration {
192 duration = Some(MediaDuration::from_90khz_ticks(bd.duration));
193 }
194 }
195 AnyCommand::TimeSignal(ts) => {
196 at = ts.splice_time.pts_time.map(adjust);
197 for d in section.descriptors() {
203 if let Ok(AnySpliceDescriptor::Segmentation(seg)) = d {
204 if seg.segmentation_event_cancel_indicator {
205 continue;
206 }
207 id = Some(seg.segmentation_event_id);
208 kind = segmentation_kind(seg.segmentation_type_id);
209 duration = seg.segmentation_duration.map(MediaDuration);
210 break;
211 }
212 }
213 }
214 _ => {}
215 }
216 }
217
218 Ok(TimedEvent {
219 id,
220 kind,
221 at,
222 duration,
223 source: SourcePayload::Scte35 { raw: raw.to_vec() },
224 })
225 }
226}
227
228fn segmentation_kind(type_id: SegmentationTypeId) -> EventKind {
245 use SegmentationTypeId as T;
246 match type_id {
247 T::ProgramStart | T::ProgramEnd | T::ChapterStart | T::ChapterEnd => EventKind::Chapter,
248 T::BreakStart
249 | T::ProviderAdvertisementStart
250 | T::DistributorAdvertisementStart
251 | T::ProviderPlacementOpportunityStart
252 | T::DistributorPlacementOpportunityStart
253 | T::ProviderAdBlockStart
254 | T::DistributorAdBlockStart => EventKind::BreakStart,
255 T::BreakEnd
256 | T::ProviderAdvertisementEnd
257 | T::DistributorAdvertisementEnd
258 | T::ProviderPlacementOpportunityEnd
259 | T::DistributorPlacementOpportunityEnd
260 | T::ProviderAdBlockEnd
261 | T::DistributorAdBlockEnd => EventKind::BreakEnd,
262 _ => EventKind::Unspecified,
263 }
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269 use alloc::vec::Vec;
270 use broadcast_core::traits::Parse;
271 use scte35_splice::SpliceInfoSection;
272
273 fn splice_2002() -> Vec<u8> {
275 test_fixtures::read("scte35/splice-insert-2002.bin")
276 }
277
278 #[test]
279 fn from_scte35_extracts_break_start_and_duration() {
280 let raw = splice_2002();
281 let section = SpliceInfoSection::parse(&raw).unwrap();
282 let ev = TimedEvent::from_scte35(§ion, &raw).unwrap();
283 assert_eq!(ev.id, Some(2002));
284 assert_eq!(ev.kind, EventKind::BreakStart); assert_eq!(ev.at, None); assert_eq!(
287 ev.duration,
288 Some(MediaDuration::from_90khz_ticks(2_160_000))
289 );
290 assert!((ev.duration.unwrap().as_seconds_f64() - 24.0).abs() < 1e-9);
291 match &ev.source {
292 SourcePayload::Scte35 { raw: r } => assert_eq!(r, &raw), _ => panic!("expected Scte35 payload"),
294 }
295 }
296
297 #[test]
298 fn event_kind_labels() {
299 assert_eq!(EventKind::BreakStart.name(), "break_start");
300 assert_eq!(alloc::format!("{}", EventKind::BreakEnd), "break_end");
301 }
302
303 #[test]
313 fn segmentation_kind_classifies_by_group() {
314 use SegmentationTypeId as T;
315 let cases: &[(SegmentationTypeId, EventKind)] = &[
316 (T::ProgramStart, EventKind::Chapter),
318 (T::ProgramEnd, EventKind::Chapter),
319 (T::ChapterStart, EventKind::Chapter),
320 (T::ChapterEnd, EventKind::Chapter),
321 (T::BreakStart, EventKind::BreakStart),
323 (T::BreakEnd, EventKind::BreakEnd),
324 (T::ProviderAdvertisementStart, EventKind::BreakStart),
325 (T::DistributorAdvertisementEnd, EventKind::BreakEnd),
326 (T::ProviderPlacementOpportunityStart, EventKind::BreakStart),
327 (T::DistributorPlacementOpportunityEnd, EventKind::BreakEnd),
328 (T::ProviderAdBlockStart, EventKind::BreakStart),
329 (T::DistributorAdBlockEnd, EventKind::BreakEnd),
330 (T::OpeningCreditStart, EventKind::Unspecified),
332 (T::ClosingCreditEnd, EventKind::Unspecified),
333 (T::ProviderPromoStart, EventKind::Unspecified),
334 (T::DistributorPromoEnd, EventKind::Unspecified),
335 (T::UnscheduledEventStart, EventKind::Unspecified),
336 (T::AlternateContentOpportunityEnd, EventKind::Unspecified),
337 (
340 T::ProviderOverlayPlacementOpportunityStart,
341 EventKind::Unspecified,
342 ),
343 (
344 T::DistributorOverlayPlacementOpportunityEnd,
345 EventKind::Unspecified,
346 ),
347 (T::NetworkStart, EventKind::Unspecified),
349 (T::NetworkEnd, EventKind::Unspecified),
350 (T::Reserved(0x60), EventKind::Unspecified),
351 ];
352 for (type_id, want) in cases {
353 assert_eq!(
354 segmentation_kind(*type_id),
355 *want,
356 "segmentation_type_id {type_id:?} ({}) must classify as {want:?}",
357 type_id.name()
358 );
359 }
360 }
361}