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(pub u64);
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub struct MediaDuration(pub u64);
19
20impl MediaDuration {
21 pub fn as_seconds_f64(self) -> f64 {
23 self.0 as f64 / crate::PTS_HZ as f64
24 }
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
30#[non_exhaustive]
31pub enum EventKind {
32 BreakStart,
34 BreakEnd,
36 Chapter,
38 Unspecified,
40}
41
42impl EventKind {
43 pub fn name(&self) -> &'static str {
45 match self {
46 EventKind::BreakStart => "break_start",
47 EventKind::BreakEnd => "break_end",
48 EventKind::Chapter => "chapter",
49 EventKind::Unspecified => "unspecified",
50 }
51 }
52}
53broadcast_common::impl_spec_display!(EventKind);
54
55#[derive(Debug, Clone, PartialEq, Eq)]
57#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
58#[non_exhaustive]
59pub enum SourcePayload {
60 Scte35 { raw: Vec<u8> },
62 Emsg {
64 scheme_id_uri: String,
65 value: String,
66 raw: Vec<u8>,
67 },
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
72#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
73#[non_exhaustive]
74pub struct TimedEvent {
75 pub id: Option<u32>,
77 pub kind: EventKind,
79 pub at: Option<MediaTime>,
81 pub duration: Option<MediaDuration>,
83 pub source: SourcePayload,
85}
86
87impl TimedEvent {
88 #[must_use]
92 pub fn new(kind: EventKind, source: SourcePayload) -> Self {
93 Self {
94 id: None,
95 kind,
96 at: None,
97 duration: None,
98 source,
99 }
100 }
101
102 #[must_use]
104 pub fn with_id(mut self, id: u32) -> Self {
105 self.id = Some(id);
106 self
107 }
108
109 #[must_use]
111 pub fn with_at(mut self, at: MediaTime) -> Self {
112 self.at = Some(at);
113 self
114 }
115
116 #[must_use]
118 pub fn with_duration(mut self, duration: MediaDuration) -> Self {
119 self.duration = Some(duration);
120 self
121 }
122
123 pub fn from_scte35(section: &SpliceInfoSection, raw: &[u8]) -> Result<Self> {
131 let mut id = None;
132 let mut kind = EventKind::Unspecified;
133 let mut at = None;
134 let mut duration = None;
135
136 let adjust = |pts: broadcast_common::clock33::Clock33| {
137 MediaTime(broadcast_common::clock33::add(
138 pts.ticks(),
139 section.pts_adjustment,
140 ))
141 };
142
143 if let Some(clear) = §ion.clear {
144 match &clear.command {
145 AnyCommand::SpliceInsert(si) => {
146 id = Some(si.splice_event_id);
147 kind = if si.cancel.is_some() {
148 EventKind::Unspecified
151 } else if si.out_of_network_indicator {
152 EventKind::BreakStart
153 } else {
154 EventKind::BreakEnd
155 };
156 if let SpliceMode::Program(ProgramSplice::At(st)) = &si.mode {
157 at = st.pts_time.map(adjust);
158 }
159 if let Some(bd) = &si.break_duration {
160 duration = Some(MediaDuration(bd.duration));
161 }
162 }
163 AnyCommand::TimeSignal(ts) => {
164 at = ts.splice_time.pts_time.map(adjust);
165 for d in section.descriptors() {
171 if let Ok(AnySpliceDescriptor::Segmentation(seg)) = d {
172 if seg.segmentation_event_cancel_indicator {
173 continue;
174 }
175 id = Some(seg.segmentation_event_id);
176 kind = segmentation_kind(seg.segmentation_type_id);
177 duration = seg.segmentation_duration.map(MediaDuration);
178 break;
179 }
180 }
181 }
182 _ => {}
183 }
184 }
185
186 Ok(TimedEvent {
187 id,
188 kind,
189 at,
190 duration,
191 source: SourcePayload::Scte35 { raw: raw.to_vec() },
192 })
193 }
194}
195
196fn segmentation_kind(type_id: SegmentationTypeId) -> EventKind {
213 use SegmentationTypeId as T;
214 match type_id {
215 T::ProgramStart | T::ProgramEnd | T::ChapterStart | T::ChapterEnd => EventKind::Chapter,
216 T::BreakStart
217 | T::ProviderAdvertisementStart
218 | T::DistributorAdvertisementStart
219 | T::ProviderPlacementOpportunityStart
220 | T::DistributorPlacementOpportunityStart
221 | T::ProviderAdBlockStart
222 | T::DistributorAdBlockStart => EventKind::BreakStart,
223 T::BreakEnd
224 | T::ProviderAdvertisementEnd
225 | T::DistributorAdvertisementEnd
226 | T::ProviderPlacementOpportunityEnd
227 | T::DistributorPlacementOpportunityEnd
228 | T::ProviderAdBlockEnd
229 | T::DistributorAdBlockEnd => EventKind::BreakEnd,
230 _ => EventKind::Unspecified,
231 }
232}
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237 use alloc::vec::Vec;
238 use broadcast_common::traits::Parse;
239 use scte35_splice::SpliceInfoSection;
240
241 fn splice_2002() -> Vec<u8> {
243 test_fixtures::read("scte35/splice-insert-2002.bin")
244 }
245
246 #[test]
247 fn from_scte35_extracts_break_start_and_duration() {
248 let raw = splice_2002();
249 let section = SpliceInfoSection::parse(&raw).unwrap();
250 let ev = TimedEvent::from_scte35(§ion, &raw).unwrap();
251 assert_eq!(ev.id, Some(2002));
252 assert_eq!(ev.kind, EventKind::BreakStart); assert_eq!(ev.at, None); assert_eq!(ev.duration, Some(MediaDuration(2_160_000)));
255 assert!((ev.duration.unwrap().as_seconds_f64() - 24.0).abs() < 1e-9);
256 match &ev.source {
257 SourcePayload::Scte35 { raw: r } => assert_eq!(r, &raw), _ => panic!("expected Scte35 payload"),
259 }
260 }
261
262 #[test]
263 fn event_kind_labels() {
264 assert_eq!(EventKind::BreakStart.name(), "break_start");
265 assert_eq!(alloc::format!("{}", EventKind::BreakEnd), "break_end");
266 }
267
268 #[test]
278 fn segmentation_kind_classifies_by_group() {
279 use SegmentationTypeId as T;
280 let cases: &[(SegmentationTypeId, EventKind)] = &[
281 (T::ProgramStart, EventKind::Chapter),
283 (T::ProgramEnd, EventKind::Chapter),
284 (T::ChapterStart, EventKind::Chapter),
285 (T::ChapterEnd, EventKind::Chapter),
286 (T::BreakStart, EventKind::BreakStart),
288 (T::BreakEnd, EventKind::BreakEnd),
289 (T::ProviderAdvertisementStart, EventKind::BreakStart),
290 (T::DistributorAdvertisementEnd, EventKind::BreakEnd),
291 (T::ProviderPlacementOpportunityStart, EventKind::BreakStart),
292 (T::DistributorPlacementOpportunityEnd, EventKind::BreakEnd),
293 (T::ProviderAdBlockStart, EventKind::BreakStart),
294 (T::DistributorAdBlockEnd, EventKind::BreakEnd),
295 (T::OpeningCreditStart, EventKind::Unspecified),
297 (T::ClosingCreditEnd, EventKind::Unspecified),
298 (T::ProviderPromoStart, EventKind::Unspecified),
299 (T::DistributorPromoEnd, EventKind::Unspecified),
300 (T::UnscheduledEventStart, EventKind::Unspecified),
301 (T::AlternateContentOpportunityEnd, EventKind::Unspecified),
302 (
305 T::ProviderOverlayPlacementOpportunityStart,
306 EventKind::Unspecified,
307 ),
308 (
309 T::DistributorOverlayPlacementOpportunityEnd,
310 EventKind::Unspecified,
311 ),
312 (T::NetworkStart, EventKind::Unspecified),
314 (T::NetworkEnd, EventKind::Unspecified),
315 (T::Reserved(0x60), EventKind::Unspecified),
316 ];
317 for (type_id, want) in cases {
318 assert_eq!(
319 segmentation_kind(*type_id),
320 *want,
321 "segmentation_type_id {type_id:?} ({}) must classify as {want:?}",
322 type_id.name()
323 );
324 }
325 }
326}