1use super::descriptor::{
4 AudioChannels, BLOCK_FRAMES_RANGE, Descriptor, Direction, ExtractRequest, InputFrom, InputSpec,
5 MAX_EXTRACTOR_OUTPUTS, MAX_EXTRACTOR_PASSES, MAX_OUTPUT_DESCRIPTION_CHARS,
6 MAX_OUTPUT_LABEL_CHARS, OutputSpec, Pass, VideoFormat, plain_text,
7};
8use super::pixels::{luma8_from_rgba8, luma8_into};
9use alpha2_media::SourceId;
10use alpha2_model::{
11 DataAnchor, DataInterval, DataKind, DataSamples, DataSet, DataSetId, DataValues, DataWord,
12 MadeBy, MediaKind, Project,
13};
14use alpha2_time::{FrameRate, MediaTime, TICKS_PER_SECOND, TimeRange};
15use std::collections::{BTreeMap, HashSet};
16use std::fmt;
17
18#[derive(Copy, Clone, Debug, Eq, PartialEq)]
20pub enum FrameFrom {
21 Start(MediaTime),
23 After(MediaTime),
25}
26
27#[derive(Clone, Debug, Eq, PartialEq)]
29pub enum Need {
30 SourceFrame {
32 source: SourceId,
34 from: FrameFrom,
36 direction: Direction,
38 size: u32,
40 format: VideoFormat,
42 },
43 SourceAudio {
46 source: SourceId,
48 stream: u32,
50 start_sample: i64,
52 frames: u32,
54 rate: u32,
56 channels: AudioChannels,
58 },
59 TimelineFrame {
61 time: MediaTime,
63 size: u32,
65 format: VideoFormat,
67 },
68 TimelineAudio {
70 start_sample: i64,
72 frames: u32,
74 rate: u32,
76 channels: AudioChannels,
78 },
79}
80
81#[derive(Clone, Debug, PartialEq, Eq)]
83pub struct SuppliedFrame {
84 pub pts: MediaTime,
86 pub width: u32,
88 pub height: u32,
90 pub rgba: Vec<u8>,
92}
93
94#[derive(Clone, Debug, PartialEq)]
96pub struct SuppliedAudio {
97 pub channels: u32,
99 pub samples: Vec<f32>,
101}
102
103enum Placement<'a> {
104 Bytes,
105 Placed,
106 Into(&'a mut [u8]),
107}
108
109fn frame_fits(
110 frame: &SuppliedFrame,
111 size: u32,
112 format: VideoFormat,
113 placement: &Placement<'_>,
114) -> Result<(), SessionError> {
115 let placed = matches!(placement, Placement::Placed);
116 if frame.width == 0 || frame.height == 0 || frame.width.max(frame.height) > size {
117 return Err(SessionError::UnexpectedSupply(
118 "the frame's size breaks the asked size".to_owned(),
119 ));
120 }
121 if placed && (format != VideoFormat::Rgba8 || !frame.rgba.is_empty()) {
122 return Err(SessionError::UnexpectedSupply(
123 "a placed frame answers an RGBA need and carries no buffer".to_owned(),
124 ));
125 }
126 let pixels = u64::from(frame.width) * u64::from(frame.height);
127 if !placed && u64::try_from(frame.rgba.len()).ok() != pixels.checked_mul(4) {
128 return Err(SessionError::UnexpectedSupply(
129 "the buffer is not width * height * 4 bytes".to_owned(),
130 ));
131 }
132 let bytes_per_pixel = match format {
133 VideoFormat::Rgba8 => 4,
134 VideoFormat::Luma8 => 1,
135 };
136 if let Placement::Into(buffer) = placement
137 && u64::try_from(buffer.len()).ok() != pixels.checked_mul(bytes_per_pixel)
138 {
139 return Err(SessionError::UnexpectedSupply(
140 "the memory for the frame is not its delivered length".to_owned(),
141 ));
142 }
143 Ok(())
144}
145
146#[derive(Clone, Debug, PartialEq, Eq)]
148pub struct VideoInput {
149 pub time: MediaTime,
151 pub width: u32,
153 pub height: u32,
155 pub format: VideoFormat,
157 pub bytes: Vec<u8>,
159}
160
161#[derive(Clone, Debug, PartialEq)]
163pub struct AudioInput {
164 pub start_sample: i64,
166 pub start: MediaTime,
168 pub frames: u32,
170 pub rate: u32,
172 pub channels: u32,
174 pub samples: Vec<f32>,
176}
177
178#[derive(Clone, Debug, PartialEq)]
180pub enum Delivery {
181 Video(VideoInput),
183 Audio(AudioInput),
185}
186
187#[derive(Clone, Debug, PartialEq)]
189pub enum Step {
190 Need(Need),
192 Deliver(Delivery),
194 PassBoundary {
196 pass: usize,
198 direction: Direction,
200 },
201 Done,
203}
204
205#[derive(Clone, Debug, PartialEq)]
207pub enum Emit {
208 Sample {
210 output: String,
212 time: MediaTime,
214 values: Vec<Option<f32>>,
216 },
217 Word {
219 output: String,
221 word: DataWord,
223 },
224 Interval {
226 output: String,
228 interval: DataInterval,
230 },
231}
232
233impl Emit {
234 fn output(&self) -> &str {
235 match self {
236 Self::Sample { output, .. }
237 | Self::Word { output, .. }
238 | Self::Interval { output, .. } => output,
239 }
240 }
241}
242
243#[derive(Clone, Debug, Eq, PartialEq)]
245#[non_exhaustive]
246pub enum RequestError {
247 WrongExtractor,
249 InvalidDescriptor(String),
251 InvalidInput(String),
254 InvalidRange,
256 RangePastSource(i64),
258 InvalidSize,
260 InvalidAudio,
262 InvalidOutputs(String),
264}
265
266impl fmt::Display for RequestError {
267 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
268 match self {
269 Self::WrongExtractor => {
270 formatter.write_str("the request names another extractor or version")
271 }
272 Self::InvalidDescriptor(why) => write!(formatter, "invalid descriptor: {why}"),
273 Self::InvalidInput(why) => write!(formatter, "invalid input: {why}"),
274 Self::InvalidRange => {
275 formatter.write_str("the range is empty or negative, or a pass starts outside it")
276 }
277 Self::RangePastSource(duration) => write!(
278 formatter,
279 "the range ends past the source's duration of {duration} ticks"
280 ),
281 Self::InvalidSize => {
282 formatter.write_str("size is zero or above the descriptor's max_size")
283 }
284 Self::InvalidAudio => formatter.write_str(
285 "the audio rate or channels are invalid or conflict with the descriptor",
286 ),
287 Self::InvalidOutputs(why) => write!(formatter, "invalid outputs: {why}"),
288 }
289 }
290}
291
292impl std::error::Error for RequestError {}
293
294#[derive(Clone, Debug, PartialEq)]
296#[non_exhaustive]
297pub enum SessionError {
298 UnexpectedSupply(String),
300 InvalidEmit {
302 index: usize,
304 reason: String,
306 },
307 InvalidResult(String),
309}
310
311impl fmt::Display for SessionError {
312 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
313 match self {
314 Self::UnexpectedSupply(why) => write!(formatter, "unexpected supply: {why}"),
315 Self::InvalidEmit { index, reason } => {
316 write!(formatter, "invalid emit {index}: {reason}")
317 }
318 Self::InvalidResult(why) => write!(formatter, "invalid result: {why}"),
319 }
320 }
321}
322
323impl std::error::Error for SessionError {}
324
325#[derive(Copy, Clone, Debug, Eq, PartialEq)]
327pub struct PassProgress {
328 pub completed: u64,
330 pub total: Option<u64>,
332}
333
334#[derive(Clone, Debug, PartialEq)]
336pub struct RunContext {
337 pub range: TimeRange,
339 pub passes: Vec<Pass>,
341 pub from: InputFrom,
343 pub video: Option<(u32, VideoFormat)>,
345 pub audio: Option<(u32, AudioChannels, u32)>,
347 pub frame_rate: Option<FrameRate>,
349}
350
351#[derive(Clone, Debug)]
352enum Input {
353 SourceVideo {
354 source: SourceId,
355 size: u32,
356 format: VideoFormat,
357 },
358 TimelineVideo {
359 size: u32,
360 format: VideoFormat,
361 rate: FrameRate,
362 },
363 SourceAudio {
364 source: SourceId,
365 stream: u32,
366 rate: u32,
367 channels: AudioChannels,
368 block: u32,
369 },
370 TimelineAudio {
371 rate: u32,
372 channels: AudioChannels,
373 block: u32,
374 },
375}
376
377#[derive(Clone, Debug)]
379enum Phase {
380 BeforePass(usize),
382 Running(Cursor),
384 Waiting(Cursor, Need),
386 Delivering(Cursor, Delivery),
388 Done,
390 Finished,
392}
393
394#[derive(Clone, Copy, Debug)]
395struct Cursor {
396 pass: usize,
397 position: Option<i64>,
400}
401
402#[derive(Default, Debug)]
404struct Gathered {
405 samples: Vec<(MediaTime, Vec<Option<f32>>)>,
406 words: Vec<DataWord>,
407 intervals: Vec<DataInterval>,
408}
409
410impl Gathered {
411 fn len(&self) -> usize {
413 self.samples.len() + self.words.len() + self.intervals.len()
414 }
415}
416
417fn over_limit(output: &OutputSpec) -> String {
419 let (limit, what) = match output.kind {
420 DataKind::Points | DataKind::Scalars | DataKind::Similarity => {
421 (alpha2_model::MAX_DATA_VALUES, "values")
422 }
423 DataKind::Words => (alpha2_model::MAX_DATA_WORDS, "words"),
424 DataKind::Intervals => (alpha2_model::MAX_DATA_INTERVALS, "intervals"),
425 };
426 format!("output {} would hold more than {limit} {what}", output.name)
427}
428
429#[derive(Debug)]
436pub struct ExtractSession {
437 descriptor: Descriptor,
438 request: ExtractRequest,
439 input: Input,
440 anchor: DataAnchor,
441 passes: Vec<Pass>,
442 phase: Phase,
443 progress: Vec<PassProgress>,
444 delivered: Option<MediaTime>,
446 delivered_pts: HashSet<MediaTime>,
448 last_time: BTreeMap<String, MediaTime>,
450 gathered: BTreeMap<String, Gathered>,
451}
452
453pub(super) fn validate_descriptor(descriptor: &Descriptor) -> Result<(), RequestError> {
454 let invalid = |why: &str| Err(RequestError::InvalidDescriptor(why.to_owned()));
455 if descriptor.id.is_empty() {
456 return invalid("empty id");
457 }
458 if descriptor.outputs.is_empty() || descriptor.outputs.len() > MAX_EXTRACTOR_OUTPUTS {
459 return invalid("needs 1 to 32 outputs");
460 }
461 let mut names = HashSet::new();
462 for output in &descriptor.outputs {
463 if output.name.is_empty() || !names.insert(&output.name) {
464 return invalid("an output name is empty or repeated");
465 }
466 let sampled = matches!(output.kind, DataKind::Points | DataKind::Scalars);
467 if sampled == output.channels.is_empty() {
468 return invalid("points and scalars outputs need channels; others take none");
469 }
470 if output.channels.len() > alpha2_model::MAX_DATA_CHANNELS {
471 return invalid("an output has too many channels");
472 }
473 let mut channels = HashSet::new();
474 if output.channels.iter().any(|channel| {
475 channel.is_empty()
476 || channel.len() > alpha2_model::MAX_DATA_LABEL_BYTES
477 || !channels.insert(channel)
478 }) {
479 return invalid("a channel name is empty, too long or repeated");
480 }
481 if output.interpolation.is_some() && output.kind.arity().is_none() {
482 return invalid("only sampled outputs take an interpolation");
483 }
484 if output
485 .label
486 .as_deref()
487 .is_some_and(|label| !plain_text(label, 1, MAX_OUTPUT_LABEL_CHARS))
488 || output.description.as_deref().is_some_and(|description| {
489 !plain_text(description, 0, MAX_OUTPUT_DESCRIPTION_CHARS)
490 })
491 {
492 return Err(RequestError::InvalidDescriptor(format!(
493 "an output label is not 1 to {MAX_OUTPUT_LABEL_CHARS} characters, a description \
494 is longer than {MAX_OUTPUT_DESCRIPTION_CHARS}, or either has a control character"
495 )));
496 }
497 }
498 if descriptor.input.from().is_empty() {
499 return invalid("reads no input");
500 }
501 match &descriptor.input {
502 InputSpec::Video { max_size, .. } if *max_size == 0 => invalid("max_size is zero"),
503 InputSpec::Audio {
504 block_frames,
505 sample_rate,
506 ..
507 } if !BLOCK_FRAMES_RANGE.contains(block_frames)
508 || sample_rate.is_some_and(|rate| !alpha2_model::SAMPLE_RATE_RANGE.contains(&rate)) =>
509 {
510 invalid("block_frames or sample_rate out of range")
511 }
512 _ => Ok(()),
513 }
514}
515
516impl ExtractSession {
517 #[allow(clippy::too_many_lines)]
522 pub fn new(
523 project: &Project,
524 descriptor: &Descriptor,
525 request: ExtractRequest,
526 ) -> Result<Self, RequestError> {
527 validate_descriptor(descriptor)?;
528 if request.extractor != descriptor.id || request.version != descriptor.version {
529 return Err(RequestError::WrongExtractor);
530 }
531 let read = &request.input;
532 if !descriptor.input.from().contains(&read.from) {
533 return Err(RequestError::InvalidInput(
534 "the descriptor does not read this input".to_owned(),
535 ));
536 }
537 let range = read.range;
538 if range.is_empty() || range.start().ticks() < 0 {
539 return Err(RequestError::InvalidRange);
540 }
541 if read.passes.len() > MAX_EXTRACTOR_PASSES
542 || read.passes.iter().any(|pass| !range.contains(pass.start))
543 {
544 return Err(RequestError::InvalidRange);
545 }
546 let source = match read.from {
547 InputFrom::Source => {
548 let id = read.source_id.as_ref().ok_or_else(|| {
549 RequestError::InvalidInput("source input needs source_id".to_owned())
550 })?;
551 let source = project
552 .sources
553 .iter()
554 .find(|source| &source.id == id)
555 .ok_or_else(|| RequestError::InvalidInput(format!("unknown source {id}")))?;
556 let fits = match &descriptor.input {
557 InputSpec::Video { .. } => {
558 matches!(source.kind, MediaKind::Video | MediaKind::Image)
559 }
560 InputSpec::Audio { .. } => source.kind == MediaKind::Audio || source.has_audio,
561 };
562 if !fits {
563 return Err(RequestError::InvalidInput(format!(
564 "source {id} cannot feed this input"
565 )));
566 }
567 let duration = source
568 .fingerprint
569 .as_ref()
570 .and_then(|fingerprint| fingerprint.duration_ticks);
571 if let Some(duration) = duration
572 && range.end().ticks() > duration
573 {
574 return Err(RequestError::RangePastSource(duration));
575 }
576 Some(id.clone())
577 }
578 InputFrom::Timeline => {
579 if read.source_id.is_some() {
580 return Err(RequestError::InvalidInput(
581 "timeline input takes no source_id".to_owned(),
582 ));
583 }
584 None
585 }
586 };
587 let input = match (&descriptor.input, source.clone()) {
588 (
589 InputSpec::Video {
590 format, max_size, ..
591 },
592 source,
593 ) => {
594 if read.stream.is_some() || read.sample_rate.is_some() || read.channels.is_some() {
595 return Err(RequestError::InvalidInput(
596 "video input takes no audio fields".to_owned(),
597 ));
598 }
599 let size = read.size.unwrap_or(*max_size);
600 if size == 0 || size > *max_size {
601 return Err(RequestError::InvalidSize);
602 }
603 match source {
604 Some(source) => {
605 if read.frame_rate.is_some() {
606 return Err(RequestError::InvalidInput(
607 "source input takes no frame_rate".to_owned(),
608 ));
609 }
610 Input::SourceVideo {
611 source,
612 size,
613 format: *format,
614 }
615 }
616 None => Input::TimelineVideo {
617 size,
618 format: *format,
619 rate: read.frame_rate.unwrap_or(project.settings.frame_rate),
620 },
621 }
622 }
623 (
624 InputSpec::Audio {
625 sample_rate,
626 channels,
627 block_frames,
628 ..
629 },
630 source,
631 ) => {
632 if read.size.is_some() || read.frame_rate.is_some() {
633 return Err(RequestError::InvalidInput(
634 "audio input takes no video fields".to_owned(),
635 ));
636 }
637 let rate = match (sample_rate, read.sample_rate) {
638 (Some(fixed), Some(asked)) if *fixed != asked => {
639 return Err(RequestError::InvalidAudio);
640 }
641 (Some(fixed), _) => *fixed,
642 (None, Some(asked)) => asked,
643 (None, None) => project.settings.sample_rate,
644 };
645 if !alpha2_model::SAMPLE_RATE_RANGE.contains(&rate) {
646 return Err(RequestError::InvalidAudio);
647 }
648 let layout = match (channels, read.channels) {
649 (Some(fixed), Some(asked)) if *fixed != asked => {
650 return Err(RequestError::InvalidAudio);
651 }
652 (Some(fixed), _) => *fixed,
653 (None, Some(asked)) => asked,
654 (None, None) => AudioChannels::Mono,
655 };
656 if let Some(source) = source {
657 Input::SourceAudio {
658 source,
659 stream: read.stream.unwrap_or(0),
660 rate,
661 channels: layout,
662 block: *block_frames,
663 }
664 } else {
665 if read.stream.is_some() {
666 return Err(RequestError::InvalidInput(
667 "timeline input takes no stream".to_owned(),
668 ));
669 }
670 Input::TimelineAudio {
671 rate,
672 channels: layout,
673 block: *block_frames,
674 }
675 }
676 }
677 };
678 let mut ids = HashSet::new();
679 for (name, id) in &request.outputs {
680 if !descriptor.outputs.iter().any(|output| &output.name == name) {
681 return Err(RequestError::InvalidOutputs(format!(
682 "undeclared output {name}"
683 )));
684 }
685 if !ids.insert(id) {
686 return Err(RequestError::InvalidOutputs(format!(
687 "data set id {id} repeated"
688 )));
689 }
690 }
691 let passes = if read.passes.is_empty() {
692 vec![Pass {
693 start: range.start(),
694 direction: Direction::Forward,
695 }]
696 } else {
697 read.passes.clone()
698 };
699 let anchor = source.map_or(DataAnchor::Timeline, |source_id| DataAnchor::Source {
700 source_id,
701 });
702 let mut session = Self {
703 descriptor: descriptor.clone(),
704 request,
705 input,
706 anchor,
707 progress: Vec::new(),
708 passes,
709 phase: Phase::BeforePass(0),
710 delivered: None,
711 delivered_pts: HashSet::new(),
712 last_time: BTreeMap::new(),
713 gathered: BTreeMap::new(),
714 };
715 session.progress = (0..session.passes.len())
716 .map(|pass| PassProgress {
717 completed: 0,
718 total: session.pass_total(pass),
719 })
720 .collect();
721 Ok(session)
722 }
723
724 #[must_use]
726 pub fn context(&self) -> RunContext {
727 let (video, audio, frame_rate) = match &self.input {
728 Input::SourceVideo { size, format, .. } => (Some((*size, *format)), None, None),
729 Input::TimelineVideo { size, format, rate } => {
730 (Some((*size, *format)), None, Some(*rate))
731 }
732 Input::SourceAudio {
733 rate,
734 channels,
735 block,
736 ..
737 }
738 | Input::TimelineAudio {
739 rate,
740 channels,
741 block,
742 } => (None, Some((*rate, *channels, *block)), None),
743 };
744 RunContext {
745 range: self.request.input.range,
746 passes: self.passes.clone(),
747 from: self.request.input.from,
748 video,
749 audio,
750 frame_rate,
751 }
752 }
753
754 #[must_use]
756 pub const fn descriptor(&self) -> &Descriptor {
757 &self.descriptor
758 }
759
760 #[must_use]
762 pub const fn request(&self) -> &ExtractRequest {
763 &self.request
764 }
765
766 #[must_use]
768 pub fn progress(&self) -> &[PassProgress] {
769 &self.progress
770 }
771
772 fn range(&self) -> TimeRange {
773 self.request.input.range
774 }
775
776 fn sample_span(&self, rate: u32) -> (i64, i64) {
778 let range = self.range();
779 (
780 samples_ceil(range.start(), rate),
781 samples_ceil(range.end(), rate),
782 )
783 }
784
785 fn pass_total(&self, pass: usize) -> Option<u64> {
786 let Pass { start, direction } = self.passes[pass];
787 match &self.input {
788 Input::SourceVideo { .. } => None,
789 Input::TimelineVideo { rate, .. } => {
790 let (first, last) = timeline_frames(self.range(), *rate)?;
791 let at = start_frame(start, *rate, first, last)?;
792 let count = match direction {
793 Direction::Forward => last - at,
794 Direction::Backward => at - first + 1,
795 };
796 u64::try_from(count).ok()
797 }
798 Input::SourceAudio { rate, block, .. } | Input::TimelineAudio { rate, block, .. } => {
799 let (first, last) = self.sample_span(*rate);
800 let at = samples_ceil(start, *rate).clamp(first, last);
801 let span = match direction {
802 Direction::Forward => last - at,
803 Direction::Backward => at - first,
804 };
805 u64::try_from(span)
806 .ok()
807 .map(|span| span.div_ceil(u64::from(*block)))
808 }
809 }
810 }
811
812 #[allow(clippy::should_implement_trait)]
814 pub fn next(&mut self) -> Step {
815 loop {
816 match std::mem::replace(&mut self.phase, Phase::Done) {
817 Phase::BeforePass(pass) if pass >= self.passes.len() => {
818 self.phase = Phase::Done;
819 self.last_time.clear();
820 self.delivered = None;
821 return Step::Done;
822 }
823 Phase::BeforePass(pass) => {
824 self.phase = Phase::Running(Cursor {
825 pass,
826 position: None,
827 });
828 self.delivered = None;
829 self.last_time.clear();
830 return Step::PassBoundary {
831 pass,
832 direction: self.passes[pass].direction,
833 };
834 }
835 Phase::Running(cursor) => match self.need_at(cursor) {
836 Some(need) => {
837 self.phase = Phase::Waiting(cursor, need.clone());
838 return Step::Need(need);
839 }
840 None => self.phase = Phase::BeforePass(cursor.pass + 1),
841 },
842 Phase::Waiting(cursor, need) => {
843 self.phase = Phase::Waiting(cursor, need.clone());
844 return Step::Need(need);
845 }
846 Phase::Delivering(cursor, delivery) => {
847 self.progress[cursor.pass].completed += 1;
848 self.phase = Phase::Running(cursor);
849 return Step::Deliver(delivery);
850 }
851 Phase::Done => {
852 self.phase = Phase::Done;
853 return Step::Done;
854 }
855 Phase::Finished => {
856 self.phase = Phase::Finished;
857 return Step::Done;
858 }
859 }
860 }
861 }
862
863 fn need_at(&self, cursor: Cursor) -> Option<Need> {
865 let Pass { start, direction } = self.passes[cursor.pass];
866 match &self.input {
867 Input::SourceVideo {
868 source,
869 size,
870 format,
871 } => {
872 if cursor.position == Some(i64::MIN) {
873 return None;
874 }
875 let from = cursor.position.map_or(FrameFrom::Start(start), |pts| {
876 FrameFrom::After(MediaTime(pts))
877 });
878 Some(Need::SourceFrame {
879 source: source.clone(),
880 from,
881 direction,
882 size: *size,
883 format: *format,
884 })
885 }
886 Input::TimelineVideo { size, format, rate } => {
887 let (first, last) = timeline_frames(self.range(), *rate)?;
888 let frame = match cursor.position {
889 Some(frame) => frame,
890 None => start_frame(start, *rate, first, last)?,
891 };
892 if frame < first || frame >= last {
893 return None;
894 }
895 Some(Need::TimelineFrame {
896 time: rate.frame_start(frame)?,
897 size: *size,
898 format: *format,
899 })
900 }
901 Input::SourceAudio {
902 rate,
903 block,
904 channels,
905 ..
906 }
907 | Input::TimelineAudio {
908 rate,
909 block,
910 channels,
911 } => {
912 let (first, last) = self.sample_span(*rate);
913 let at = cursor
914 .position
915 .unwrap_or_else(|| samples_ceil(start, *rate).clamp(first, last));
916 let block = i64::from(*block);
917 let (start_sample, end_sample) = match direction {
918 Direction::Forward => (at, (at + block).min(last)),
919 Direction::Backward => ((at - block).max(first), at),
920 };
921 if start_sample >= end_sample {
922 return None;
923 }
924 let frames = u32::try_from(end_sample - start_sample).ok()?;
925 Some(match &self.input {
926 Input::SourceAudio { source, stream, .. } => Need::SourceAudio {
927 source: source.clone(),
928 stream: *stream,
929 start_sample,
930 frames,
931 rate: *rate,
932 channels: *channels,
933 },
934 _ => Need::TimelineAudio {
935 start_sample,
936 frames,
937 rate: *rate,
938 channels: *channels,
939 },
940 })
941 }
942 }
943 }
944
945 pub fn supply_video(&mut self, frame: SuppliedFrame) -> Result<(), SessionError> {
951 self.supply_frame(frame, Placement::Bytes)
952 }
953
954 pub fn supply_placed_video(&mut self, frame: SuppliedFrame) -> Result<(), SessionError> {
961 self.supply_frame(frame, Placement::Placed)
962 }
963
964 pub fn supply_video_into(
971 &mut self,
972 frame: SuppliedFrame,
973 buffer: &mut [u8],
974 ) -> Result<(), SessionError> {
975 self.supply_frame(frame, Placement::Into(buffer))
976 }
977
978 fn supply_frame(
979 &mut self,
980 frame: SuppliedFrame,
981 placement: Placement<'_>,
982 ) -> Result<(), SessionError> {
983 let Phase::Waiting(cursor, need) = &self.phase else {
984 return Err(SessionError::UnexpectedSupply(
985 "no frame is asked for".to_owned(),
986 ));
987 };
988 let (cursor, need) = (*cursor, need.clone());
989 let (size, format, expected_pts, from) = match &need {
990 Need::SourceFrame {
991 size, format, from, ..
992 } => (*size, *format, None, Some(*from)),
993 Need::TimelineFrame { time, size, format } => (*size, *format, Some(*time), None),
994 _ => {
995 return Err(SessionError::UnexpectedSupply(
996 "audio is asked for".to_owned(),
997 ));
998 }
999 };
1000 frame_fits(&frame, size, format, &placement)?;
1001 if expected_pts.is_some_and(|time| time != frame.pts) {
1002 return Err(SessionError::UnexpectedSupply(
1003 "the frame is not the asked time".to_owned(),
1004 ));
1005 }
1006 let Pass { direction, .. } = self.passes[cursor.pass];
1007 if let Some(FrameFrom::After(previous)) = from {
1008 let ordered = match direction {
1009 Direction::Forward => frame.pts > previous,
1010 Direction::Backward => frame.pts < previous,
1011 };
1012 if !ordered {
1013 return Err(SessionError::UnexpectedSupply(
1014 "the frame does not follow the last in the pass direction".to_owned(),
1015 ));
1016 }
1017 }
1018 let range = self.range();
1019 let (deliver, next) = match &self.input {
1021 Input::SourceVideo { .. } => match direction {
1022 Direction::Forward => {
1023 if frame.pts >= range.end() {
1024 (false, Some(i64::MIN))
1025 } else {
1026 (true, Some(frame.pts.ticks()))
1027 }
1028 }
1029 Direction::Backward => {
1030 let last = frame.pts <= range.start();
1031 (true, Some(if last { i64::MIN } else { frame.pts.ticks() }))
1032 }
1033 },
1034 Input::TimelineVideo { rate, .. } => {
1035 let frame_index = rate.frame_at_or_before(frame.pts);
1036 let step = match direction {
1037 Direction::Forward => 1,
1038 Direction::Backward => -1,
1039 };
1040 (true, frame_index.map(|index| index + step))
1041 }
1042 _ => unreachable!("a frame need comes only from video input"),
1043 };
1044 if !deliver {
1045 self.phase = Phase::Running(Cursor {
1046 pass: cursor.pass,
1047 position: next,
1048 });
1049 return Ok(());
1050 }
1051 self.delivered = Some(frame.pts);
1052 self.delivered_pts.insert(frame.pts);
1053 let bytes = match (placement, format) {
1054 (Placement::Placed, _) => Vec::new(),
1055 (Placement::Into(buffer), VideoFormat::Rgba8) => {
1056 buffer.copy_from_slice(&frame.rgba);
1057 Vec::new()
1058 }
1059 (Placement::Into(buffer), VideoFormat::Luma8) => {
1060 luma8_into(&frame.rgba, buffer);
1061 Vec::new()
1062 }
1063 (Placement::Bytes, VideoFormat::Rgba8) => frame.rgba,
1064 (Placement::Bytes, VideoFormat::Luma8) => luma8_from_rgba8(&frame.rgba),
1065 };
1066 let delivery = Delivery::Video(VideoInput {
1067 time: frame.pts,
1068 width: frame.width,
1069 height: frame.height,
1070 format,
1071 bytes,
1072 });
1073 self.phase = Phase::Delivering(
1074 Cursor {
1075 pass: cursor.pass,
1076 position: next,
1077 },
1078 delivery,
1079 );
1080 Ok(())
1081 }
1082
1083 pub fn supply_end(&mut self) -> Result<(), SessionError> {
1088 match &self.phase {
1089 Phase::Waiting(cursor, Need::SourceFrame { .. }) => {
1090 self.phase = Phase::Running(Cursor {
1091 pass: cursor.pass,
1092 position: Some(i64::MIN),
1093 });
1094 Ok(())
1095 }
1096 _ => Err(SessionError::UnexpectedSupply(
1097 "no source frame is asked for".to_owned(),
1098 )),
1099 }
1100 }
1101
1102 pub fn supply_audio(&mut self, block: SuppliedAudio) -> Result<(), SessionError> {
1108 let Phase::Waiting(cursor, need) = &self.phase else {
1109 return Err(SessionError::UnexpectedSupply(
1110 "no audio is asked for".to_owned(),
1111 ));
1112 };
1113 let (cursor, need) = (*cursor, need.clone());
1114 let (Need::SourceAudio {
1115 start_sample,
1116 frames,
1117 rate,
1118 channels,
1119 ..
1120 }
1121 | Need::TimelineAudio {
1122 start_sample,
1123 frames,
1124 rate,
1125 channels,
1126 }) = need
1127 else {
1128 return Err(SessionError::UnexpectedSupply(
1129 "a frame is asked for".to_owned(),
1130 ));
1131 };
1132 if block.channels == 0
1133 || (channels == AudioChannels::Mono && block.channels != 1)
1134 || block.channels > u32::try_from(alpha2_media::MAX_AUDIO_CHANNELS).unwrap_or(u32::MAX)
1135 {
1136 return Err(SessionError::UnexpectedSupply(
1137 "the block's channel count does not answer the need".to_owned(),
1138 ));
1139 }
1140 if block.samples.len()
1141 != usize::try_from(block.channels).unwrap_or(0) * usize::try_from(frames).unwrap_or(0)
1142 {
1143 return Err(SessionError::UnexpectedSupply(
1144 "the block is not channels * frames samples".to_owned(),
1145 ));
1146 }
1147 if block.samples.iter().any(|sample| !sample.is_finite()) {
1148 return Err(SessionError::UnexpectedSupply(
1149 "the block holds a sample that is not finite".to_owned(),
1150 ));
1151 }
1152 let end_sample = start_sample + i64::from(frames);
1153 let direction = self.passes[cursor.pass].direction;
1154 self.delivered = Some(MediaTime(match direction {
1155 Direction::Forward => samples_to_ticks_ceil(end_sample, rate),
1156 Direction::Backward => alpha2_media::sample_ticks_floor(start_sample, rate),
1157 }));
1158 let next = match direction {
1159 Direction::Forward => end_sample,
1160 Direction::Backward => start_sample,
1161 };
1162 let delivery = Delivery::Audio(AudioInput {
1163 start_sample,
1164 start: MediaTime(alpha2_media::sample_ticks_floor(start_sample, rate)),
1165 frames,
1166 rate,
1167 channels: block.channels,
1168 samples: block.samples,
1169 });
1170 self.phase = Phase::Delivering(
1171 Cursor {
1172 pass: cursor.pass,
1173 position: Some(next),
1174 },
1175 delivery,
1176 );
1177 Ok(())
1178 }
1179
1180 pub fn emit(&mut self, emits: &[Emit]) -> Result<(), SessionError> {
1191 let mut last = self.last_time.clone();
1192 let mut added = BTreeMap::<&str, usize>::new();
1193 for (index, emit) in emits.iter().enumerate() {
1194 let invalid = |reason| SessionError::InvalidEmit { index, reason };
1195 self.check_emit(emit, &mut last).map_err(invalid)?;
1196 let name = emit.output();
1197 if !self.request.outputs.contains_key(name) {
1198 continue;
1199 }
1200 let count = added.entry(name).or_default();
1201 *count += 1;
1202 let held = self.gathered.get(name).map_or(0, Gathered::len);
1203 if let Some(output) = self.output(name)
1204 && held + *count > output.max_items()
1205 {
1206 return Err(invalid(over_limit(output)));
1207 }
1208 }
1209 self.last_time = last;
1210 for emit in emits {
1211 if !self.request.outputs.contains_key(emit.output()) {
1212 continue;
1213 }
1214 let gathered = self.gathered.entry(emit.output().to_owned()).or_default();
1215 match emit {
1216 Emit::Sample { time, values, .. } => gathered.samples.push((*time, values.clone())),
1217 Emit::Word { word, .. } => gathered.words.push(word.clone()),
1218 Emit::Interval { interval, .. } => gathered.intervals.push(interval.clone()),
1219 }
1220 }
1221 Ok(())
1222 }
1223
1224 fn output(&self, name: &str) -> Option<&OutputSpec> {
1225 self.descriptor
1226 .outputs
1227 .iter()
1228 .find(|output| output.name == name)
1229 }
1230
1231 #[allow(clippy::too_many_lines)]
1232 fn check_emit(
1233 &self,
1234 emit: &Emit,
1235 latest: &mut BTreeMap<String, MediaTime>,
1236 ) -> Result<(), String> {
1237 let output = self
1238 .output(emit.output())
1239 .ok_or_else(|| format!("undeclared output {}", emit.output()))?;
1240 let range = self.range();
1241 let in_pass = match &self.phase {
1242 Phase::Running(cursor) | Phase::Waiting(cursor, _) | Phase::Delivering(cursor, _) => {
1243 Some(cursor.pass)
1244 }
1245 Phase::Done => None,
1246 Phase::BeforePass(_) | Phase::Finished => {
1247 return Err("no input has been delivered".to_owned());
1248 }
1249 };
1250 let direction = in_pass.map(|pass| self.passes[pass].direction);
1251 let delivered = self.delivered;
1252 if in_pass.is_some() && delivered.is_none() {
1253 return Err("nothing has been delivered in this pass".to_owned());
1254 }
1255 let reached = |time: MediaTime| match (direction, delivered) {
1256 (Some(Direction::Forward), Some(bound)) => time <= bound,
1257 (Some(Direction::Backward), Some(bound)) => time >= bound,
1258 _ => true,
1259 };
1260 let (time, key) = match emit {
1261 Emit::Sample { time, values, .. } => {
1262 if output.kind.arity().is_none() {
1263 return Err(format!(
1264 "output {} takes {} items, not samples",
1265 output.name, output.kind
1266 ));
1267 }
1268 if values.len() != output.sample_width() {
1269 return Err(format!(
1270 "output {} takes {} numbers a sample",
1271 output.name,
1272 output.sample_width()
1273 ));
1274 }
1275 let arity = output.kind.arity().unwrap_or(1);
1276 for (group, chunk) in values.chunks(arity).enumerate() {
1277 let lost = chunk[0].is_none();
1278 for (component, value) in chunk.iter().enumerate() {
1279 let ok = match value {
1280 None => lost,
1281 Some(number) => {
1282 !lost
1283 && alpha2_model::value_in_bounds(
1284 output.kind,
1285 component,
1286 *number,
1287 )
1288 }
1289 };
1290 if !ok {
1291 return Err(format!(
1292 "value {} is lost in part, not finite or out of bounds",
1293 group * arity + component
1294 ));
1295 }
1296 }
1297 }
1298 let inside = (range.contains(*time) || self.delivered_pts.contains(time))
1299 && time.ticks() >= 0;
1300 if !inside {
1301 return Err("the time is outside the range".to_owned());
1302 }
1303 if !reached(*time) {
1304 return Err("the time is beyond what this pass has delivered".to_owned());
1305 }
1306 (*time, true)
1307 }
1308 Emit::Word { word, .. } => {
1309 if output.kind != DataKind::Words {
1310 return Err(format!("output {} takes no words", output.name));
1311 }
1312 if !alpha2_model::valid_word(word) {
1313 return Err(
1314 "the word is empty, too long, or does not end after it starts".to_owned(),
1315 );
1316 }
1317 if word.start < range.start() || word.end > range.end() {
1318 return Err("the word lies outside the range".to_owned());
1319 }
1320 if !reached(word.start) || !reached(word.end) {
1321 return Err("the word is beyond what this pass has delivered".to_owned());
1322 }
1323 (word.start, false)
1324 }
1325 Emit::Interval { interval, .. } => {
1326 if output.kind != DataKind::Intervals {
1327 return Err(format!("output {} takes no intervals", output.name));
1328 }
1329 if !alpha2_model::valid_interval(interval) {
1330 return Err(
1331 "the interval ends before it starts, or its label or score breaks a limit"
1332 .to_owned(),
1333 );
1334 }
1335 if interval.start < range.start() || interval.end > range.end() {
1336 return Err("the interval lies outside the range".to_owned());
1337 }
1338 if !reached(interval.start) || !reached(interval.end) {
1339 return Err("the interval is beyond what this pass has delivered".to_owned());
1340 }
1341 (interval.start, false)
1342 }
1343 };
1344 if let Some(direction) = direction
1345 && let Some(previous) = latest.get(&output.name)
1346 {
1347 let ordered = match (direction, key) {
1349 (Direction::Forward, true) => time > *previous,
1350 (Direction::Backward, true) => time < *previous,
1351 (Direction::Forward, false) => time >= *previous,
1352 (Direction::Backward, false) => time <= *previous,
1353 };
1354 if !ordered {
1355 return Err("times do not move in the pass direction".to_owned());
1356 }
1357 }
1358 if direction.is_some() {
1359 latest.insert(output.name.clone(), time);
1360 }
1361 Ok(())
1362 }
1363
1364 pub fn finish(&mut self) -> Result<Vec<DataSet>, SessionError> {
1371 if !matches!(self.phase, Phase::Done) {
1372 return Err(SessionError::InvalidResult(
1373 "the run is not done".to_owned(),
1374 ));
1375 }
1376 self.phase = Phase::Finished;
1377 let made_by = MadeBy {
1378 extractor: self.descriptor.id.clone(),
1379 version: self.descriptor.version,
1380 params: self.request.params.clone(),
1381 plugin: None,
1382 };
1383 let mut sets = Vec::new();
1384 for (name, id) in &self.request.outputs {
1385 let output = self
1386 .output(name)
1387 .cloned()
1388 .ok_or_else(|| SessionError::InvalidResult(format!("undeclared output {name}")))?;
1389 let gathered = self.gathered.remove(name).unwrap_or_default();
1390 let values = Self::values_of(&output, id, gathered)?;
1391 let set = DataSet {
1392 id: id.clone(),
1393 anchor: self.anchor.clone(),
1394 values,
1395 made_by: Some(made_by.clone()),
1396 made_from: None,
1397 };
1398 set.validate().map_err(|problem| {
1399 SessionError::InvalidResult(format!("data set {id} {problem}"))
1400 })?;
1401 sets.push(set);
1402 }
1403 Ok(sets)
1404 }
1405
1406 fn values_of(
1407 output: &OutputSpec,
1408 id: &DataSetId,
1409 mut gathered: Gathered,
1410 ) -> Result<DataValues, SessionError> {
1411 Ok(match output.kind {
1412 DataKind::Points | DataKind::Scalars | DataKind::Similarity => {
1413 gathered.samples.sort_by_key(|(time, _)| *time);
1414 if let Some(pair) = gathered
1415 .samples
1416 .windows(2)
1417 .find(|pair| pair[0].0 == pair[1].0)
1418 {
1419 return Err(SessionError::InvalidResult(format!(
1420 "output {} has time {} twice (data set {id})",
1421 output.name,
1422 pair[0].0.ticks()
1423 )));
1424 }
1425 let samples = DataSamples {
1426 interpolation: output.interpolation.unwrap_or_default(),
1427 channels: output.channels.clone(),
1428 times: gathered.samples.iter().map(|(time, _)| *time).collect(),
1429 values: gathered
1430 .samples
1431 .into_iter()
1432 .flat_map(|(_, values)| values)
1433 .collect(),
1434 };
1435 match output.kind {
1436 DataKind::Points => DataValues::Points(samples),
1437 DataKind::Scalars => DataValues::Scalars(samples),
1438 _ => DataValues::Similarity(samples),
1439 }
1440 }
1441 DataKind::Words => {
1442 gathered.words.sort_by_key(|word| (word.start, word.end));
1443 DataValues::Words(gathered.words)
1444 }
1445 DataKind::Intervals => {
1446 gathered
1447 .intervals
1448 .sort_by_key(|interval| (interval.start, interval.end));
1449 DataValues::Intervals(gathered.intervals)
1450 }
1451 })
1452 }
1453}
1454
1455fn samples_ceil(time: MediaTime, rate: u32) -> i64 {
1457 let numerator = i128::from(time.ticks()) * i128::from(rate);
1458 let denominator = i128::from(TICKS_PER_SECOND);
1459 let samples =
1460 numerator.div_euclid(denominator) + i128::from(numerator.rem_euclid(denominator) != 0);
1461 i64::try_from(samples).unwrap_or(i64::MAX)
1462}
1463
1464fn samples_to_ticks_ceil(sample: i64, rate: u32) -> i64 {
1466 let numerator = i128::from(sample) * i128::from(TICKS_PER_SECOND);
1467 let denominator = i128::from(rate.max(1));
1468 let ticks =
1469 numerator.div_euclid(denominator) + i128::from(numerator.rem_euclid(denominator) != 0);
1470 i64::try_from(ticks).unwrap_or(i64::MAX)
1471}
1472
1473fn timeline_frames(range: TimeRange, rate: FrameRate) -> Option<(i64, i64)> {
1475 let first_at_or_before = rate.frame_at_or_before(range.start())?;
1476 let first = if rate.frame_start(first_at_or_before)? < range.start() {
1477 first_at_or_before + 1
1478 } else {
1479 first_at_or_before
1480 };
1481 let last = rate.frame_at_or_before(MediaTime(range.end().ticks() - 1))? + 1;
1482 Some((first, last.max(first)))
1483}
1484
1485fn start_frame(start: MediaTime, rate: FrameRate, first: i64, last: i64) -> Option<i64> {
1487 let frame = rate.frame_at_or_before(start)?;
1488 (first < last).then(|| frame.clamp(first, last - 1))
1489}