1#[cfg(feature = "filter-pattern")]
2use std::str::FromStr;
3
4use crate::error::MediaError;
5use crate::error::Result;
6use crate::pipeline::{Filter, FrameSourceRawVideoAdapter, Source};
7#[cfg(any(
8 feature = "filter-pattern",
9 feature = "filter-crop",
10 feature = "filter-scale"
11))]
12use crate::ChromaSampling;
13use crate::Frame;
14use crate::FrameInfo;
15#[cfg(any(
16 feature = "filter-pattern",
17 feature = "filter-crop",
18 feature = "filter-scale"
19))]
20use crate::PixelFormat;
21use crate::RawVideoFrameSource;
22#[cfg(feature = "filter-pattern")]
23use crate::SampleBitDepth;
24#[cfg(feature = "filter-pattern")]
25use crate::{scale_sample_bit_depth, write_planar_sample};
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum FilterStageKind {
30 Source,
32 Transform,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum FilterStatus {
39 Implemented,
41 Scaffold,
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum FilterSpecValue {
48 Choice(&'static [&'static str]),
50 PositiveInteger,
52 UnsignedInteger,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub struct FilterSpecForm {
59 pub syntax: &'static str,
61 pub summary: &'static str,
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub struct FilterSpecParameter {
68 pub name: &'static str,
70 pub value_name: &'static str,
72 pub required: bool,
74 pub value: FilterSpecValue,
76 pub summary: &'static str,
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct FilterSpecExample {
83 pub spec: &'static str,
85 pub summary: &'static str,
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub struct FilterSpecManifest {
92 pub forms: &'static [FilterSpecForm],
94 pub parameters: &'static [FilterSpecParameter],
96 pub examples: &'static [FilterSpecExample],
98 pub notes: &'static [&'static str],
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub struct FilterManifest {
105 pub name: &'static str,
107 pub stage: FilterStageKind,
109 pub feature: &'static str,
111 pub status: FilterStatus,
113 pub spec: &'static FilterSpecManifest,
115 pub summary: &'static str,
117}
118
119impl FilterManifest {
120 pub const fn implementation_status(self) -> &'static str {
122 match self.status {
123 FilterStatus::Implemented => "implemented",
124 FilterStatus::Scaffold => "scaffold",
125 }
126 }
127}
128
129pub const PATTERN_SOURCE_NAMES: &[&str] = &[
131 "black",
132 "checker",
133 "gradient",
134 "color_blocks",
135 "bitdepth_canary",
136];
137
138const PATTERN_SPEC_FORMS: &[FilterSpecForm] = &[
139 FilterSpecForm {
140 syntax: "pattern=<name>",
141 summary: "generate frames from a named deterministic pattern",
142 },
143 FilterSpecForm {
144 syntax: "pattern:<name>",
145 summary: "alternate spelling accepted by the parser",
146 },
147];
148
149const PATTERN_SPEC_PARAMETERS: &[FilterSpecParameter] = &[FilterSpecParameter {
150 name: "name",
151 value_name: "pattern",
152 required: true,
153 value: FilterSpecValue::Choice(PATTERN_SOURCE_NAMES),
154 summary: "pattern sequence to generate",
155}];
156
157const PATTERN_SPEC_EXAMPLES: &[FilterSpecExample] = &[
158 FilterSpecExample {
159 spec: "pattern=black",
160 summary: "generate black frames",
161 },
162 FilterSpecExample {
163 spec: "pattern=color_blocks",
164 summary: "generate moving color-block frames",
165 },
166];
167
168const PATTERN_SPEC_NOTES: &[&str] = &[
169 "source filters must be first and cannot be combined with an input path",
170 "source filters require --video metadata and --frames",
171 "currently generates planar YUV/gray frames across supported bit depths, gbrp8, and rgb24",
172 "blocks is accepted as a short alias for color_blocks",
173];
174
175pub const PATTERN_FILTER_SPEC: FilterSpecManifest = FilterSpecManifest {
177 forms: PATTERN_SPEC_FORMS,
178 parameters: PATTERN_SPEC_PARAMETERS,
179 examples: PATTERN_SPEC_EXAMPLES,
180 notes: PATTERN_SPEC_NOTES,
181};
182
183const IDENTITY_SPEC_FORMS: &[FilterSpecForm] = &[FilterSpecForm {
184 syntax: "identity",
185 summary: "pass frames through unchanged",
186}];
187
188const IDENTITY_SPEC_EXAMPLES: &[FilterSpecExample] = &[FilterSpecExample {
189 spec: "identity",
190 summary: "exercise the frame filter pipeline without changing pixels",
191}];
192
193pub const IDENTITY_FILTER_SPEC: FilterSpecManifest = FilterSpecManifest {
195 forms: IDENTITY_SPEC_FORMS,
196 parameters: &[],
197 examples: IDENTITY_SPEC_EXAMPLES,
198 notes: &[],
199};
200
201const CROP_SPEC_FORMS: &[FilterSpecForm] = &[FilterSpecForm {
202 syntax: "crop=x=<px>:y=<px>:w=<px>:h=<px>",
203 summary: "crop a rectangular frame region",
204}];
205
206const CROP_SPEC_PARAMETERS: &[FilterSpecParameter] = &[
207 FilterSpecParameter {
208 name: "x",
209 value_name: "px",
210 required: true,
211 value: FilterSpecValue::UnsignedInteger,
212 summary: "left coordinate of the crop rectangle",
213 },
214 FilterSpecParameter {
215 name: "y",
216 value_name: "px",
217 required: true,
218 value: FilterSpecValue::UnsignedInteger,
219 summary: "top coordinate of the crop rectangle",
220 },
221 FilterSpecParameter {
222 name: "w",
223 value_name: "px",
224 required: true,
225 value: FilterSpecValue::PositiveInteger,
226 summary: "crop width",
227 },
228 FilterSpecParameter {
229 name: "h",
230 value_name: "px",
231 required: true,
232 value: FilterSpecValue::PositiveInteger,
233 summary: "crop height",
234 },
235];
236
237const CROP_SPEC_EXAMPLES: &[FilterSpecExample] = &[FilterSpecExample {
238 spec: "crop=x=0:y=0:w=640:h=360",
239 summary: "select a 640x360 region from the top-left corner",
240}];
241
242const CROP_SPEC_NOTES: &[&str] = &[
243 "subsampled formats require crop coordinates and dimensions aligned to chroma samples",
244 "the output keeps the input pixel format",
245];
246
247pub const CROP_FILTER_SPEC: FilterSpecManifest = FilterSpecManifest {
249 forms: CROP_SPEC_FORMS,
250 parameters: CROP_SPEC_PARAMETERS,
251 examples: CROP_SPEC_EXAMPLES,
252 notes: CROP_SPEC_NOTES,
253};
254
255const SCALE_SPEC_FORMS: &[FilterSpecForm] = &[FilterSpecForm {
256 syntax: "scale=w=<px>:h=<px>",
257 summary: "resize frames to the requested output geometry",
258}];
259
260const SCALE_SPEC_PARAMETERS: &[FilterSpecParameter] = &[
261 FilterSpecParameter {
262 name: "w",
263 value_name: "px",
264 required: true,
265 value: FilterSpecValue::PositiveInteger,
266 summary: "output width",
267 },
268 FilterSpecParameter {
269 name: "h",
270 value_name: "px",
271 required: true,
272 value: FilterSpecValue::PositiveInteger,
273 summary: "output height",
274 },
275];
276
277const SCALE_SPEC_EXAMPLES: &[FilterSpecExample] = &[FilterSpecExample {
278 spec: "scale=w=1280:h=720",
279 summary: "resize frames to 1280x720",
280}];
281
282const SCALE_SPEC_NOTES: &[&str] = &[
283 "uses deterministic nearest-neighbor sampling",
284 "the output keeps the input pixel format",
285];
286
287pub const SCALE_FILTER_SPEC: FilterSpecManifest = FilterSpecManifest {
289 forms: SCALE_SPEC_FORMS,
290 parameters: SCALE_SPEC_PARAMETERS,
291 examples: SCALE_SPEC_EXAMPLES,
292 notes: SCALE_SPEC_NOTES,
293};
294
295pub const FILTERS: &[FilterManifest] = &[
297 #[cfg(feature = "filter-pattern")]
298 FilterManifest {
299 name: "pattern",
300 stage: FilterStageKind::Source,
301 feature: "filter-pattern",
302 status: FilterStatus::Implemented,
303 spec: &PATTERN_FILTER_SPEC,
304 summary: "generated raw-video pattern source",
305 },
306 #[cfg(feature = "filter-identity")]
307 FilterManifest {
308 name: "identity",
309 stage: FilterStageKind::Transform,
310 feature: "filter-identity",
311 status: FilterStatus::Implemented,
312 spec: &IDENTITY_FILTER_SPEC,
313 summary: "no-op frame pass-through transform",
314 },
315 #[cfg(feature = "filter-crop")]
316 FilterManifest {
317 name: "crop",
318 stage: FilterStageKind::Transform,
319 feature: "filter-crop",
320 status: FilterStatus::Implemented,
321 spec: &CROP_FILTER_SPEC,
322 summary: "rectangular crop transform",
323 },
324 #[cfg(feature = "filter-scale")]
325 FilterManifest {
326 name: "scale",
327 stage: FilterStageKind::Transform,
328 feature: "filter-scale",
329 status: FilterStatus::Implemented,
330 spec: &SCALE_FILTER_SPEC,
331 summary: "nearest-neighbor resize transform",
332 },
333];
334
335pub fn filter_manifest(name: &str) -> Option<FilterManifest> {
337 FILTERS.iter().copied().find(|filter| filter.name == name)
338}
339
340pub fn filter_spec_manifest(name: &str) -> Option<&'static FilterSpecManifest> {
342 filter_manifest(name).map(|filter| filter.spec)
343}
344
345#[derive(Debug, Clone, PartialEq, Eq)]
347pub struct FilterStageSpec {
348 pub name: String,
350 pub spec: String,
352}
353
354#[derive(Debug, Clone, PartialEq, Eq)]
356pub struct FilterPipelineSpec {
357 pub source: Option<FilterStageSpec>,
359 pub transforms: Vec<FilterStageSpec>,
361}
362
363#[derive(Debug, Clone, PartialEq, Eq)]
370pub struct FilterPipelineBuilder {
371 input_present: bool,
372 specs: Vec<String>,
373}
374
375impl FilterStageSpec {
376 pub fn new(spec: impl Into<String>) -> Result<Self> {
378 let spec = spec.into();
379 let name = filter_spec_name(&spec).to_string();
380 if name.is_empty() {
381 return Err(MediaError::Message(
382 "filter spec cannot be empty".to_string(),
383 ));
384 }
385 Ok(Self { name, spec })
386 }
387}
388
389impl FilterPipelineSpec {
390 pub fn from_input() -> FilterPipelineBuilder {
392 FilterPipelineBuilder::from_input()
393 }
394
395 pub fn from_source_filter() -> FilterPipelineBuilder {
397 FilterPipelineBuilder::from_source_filter()
398 }
399
400 pub fn output_info(&self, input: FrameInfo) -> Result<FrameInfo> {
402 filter_pipeline_output_info(input, &self.transforms)
403 }
404
405 pub fn build_transforms(&self) -> Result<Vec<Box<dyn Filter>>> {
407 self.transforms
408 .iter()
409 .map(build_filter_transform)
410 .collect::<Result<Vec<_>>>()
411 }
412
413 pub fn build_source(
415 &self,
416 info: FrameInfo,
417 frames: usize,
418 ) -> Result<Option<Box<dyn Source<Output = Frame>>>> {
419 self.source
420 .as_ref()
421 .map(|source| build_source_filter(source, info, frames))
422 .transpose()
423 }
424
425 pub fn build_raw_video_source(
427 &self,
428 info: FrameInfo,
429 frames: usize,
430 ) -> Result<Option<Box<dyn RawVideoFrameSource>>> {
431 self.source
432 .as_ref()
433 .map(|source| build_raw_video_source_filter(source, info, frames))
434 .transpose()
435 }
436}
437
438impl FilterPipelineBuilder {
439 pub fn from_input() -> Self {
441 Self {
442 input_present: true,
443 specs: Vec::new(),
444 }
445 }
446
447 pub fn from_source_filter() -> Self {
449 Self {
450 input_present: false,
451 specs: Vec::new(),
452 }
453 }
454
455 pub fn with_input_present(mut self, input_present: bool) -> Self {
457 self.input_present = input_present;
458 self
459 }
460
461 pub fn filter(mut self, spec: impl Into<String>) -> Result<Self> {
463 let stage = FilterStageSpec::new(spec)?;
464 self.specs.push(stage.spec);
465 Ok(self)
466 }
467
468 pub fn filters<I, S>(mut self, specs: I) -> Result<Self>
470 where
471 I: IntoIterator<Item = S>,
472 S: Into<String>,
473 {
474 for spec in specs {
475 self = self.filter(spec)?;
476 }
477 Ok(self)
478 }
479
480 pub fn build(self) -> Result<FilterPipelineSpec> {
482 parse_filter_pipeline_specs(&self.specs, self.input_present)
483 }
484}
485
486pub fn filter_spec_name(spec: &str) -> &str {
488 spec.split_once('=')
489 .or_else(|| spec.split_once(':'))
490 .map_or(spec, |(name, _)| name)
491}
492
493pub fn parse_filter_pipeline_specs(
495 specs: &[String],
496 input_present: bool,
497) -> Result<FilterPipelineSpec> {
498 let mut source = None;
499 let mut transforms = Vec::new();
500 for (index, spec) in specs.iter().enumerate() {
501 let stage = FilterStageSpec::new(spec.clone())?;
502 let Some(manifest) = filter_manifest(&stage.name) else {
503 return Err(MediaError::Message(format!(
504 "unknown filter '{}'",
505 stage.name
506 )));
507 };
508
509 match manifest.stage {
510 FilterStageKind::Source => {
511 if input_present {
512 return Err(MediaError::Message(format!(
513 "source filter '{}' cannot be used after an input path",
514 stage.name
515 )));
516 }
517 if index != 0 {
518 return Err(MediaError::Message(format!(
519 "source filter '{}' must be the first filter",
520 stage.name
521 )));
522 }
523 if source.is_some() {
524 return Err(MediaError::Message(
525 "encode accepts only one source filter".to_string(),
526 ));
527 }
528 validate_executable_filter_spec(manifest, &stage)?;
529 source = Some(stage);
530 }
531 FilterStageKind::Transform => {
532 validate_executable_filter_spec(manifest, &stage)?;
533 transforms.push(stage);
534 }
535 }
536 }
537 if !input_present && source.is_none() {
538 return Err(MediaError::Message(
539 "encode without an input requires a source filter such as --filter pattern=black"
540 .to_string(),
541 ));
542 }
543 Ok(FilterPipelineSpec { source, transforms })
544}
545
546pub fn filter_pipeline_output_info(
548 input: FrameInfo,
549 transforms: &[FilterStageSpec],
550) -> Result<FrameInfo> {
551 let mut info = input;
552 for stage in transforms {
553 let Some(manifest) = filter_manifest(&stage.name) else {
554 return Err(MediaError::Message(format!(
555 "unknown filter '{}'",
556 stage.name
557 )));
558 };
559 if manifest.stage != FilterStageKind::Transform {
560 return Err(MediaError::Message(format!(
561 "filter '{}' is not a transform filter",
562 stage.name
563 )));
564 }
565 validate_executable_filter_spec(manifest, stage)?;
566 info = filter_transform_output_info(stage, info)?;
567 }
568 Ok(info)
569}
570
571pub fn generate_source_filter_stream(
577 stage: &FilterStageSpec,
578 info: FrameInfo,
579 frames: usize,
580) -> Result<Vec<u8>> {
581 let total_len = info
582 .expected_len()
583 .checked_mul(frames)
584 .ok_or(MediaError::LengthOverflow)?;
585 let mut output = Vec::with_capacity(total_len);
586 let mut source = build_source_filter(stage, info, frames)?;
587 while let Some(frame) = source.pull()? {
588 output.extend_from_slice(frame.data());
589 }
590 Ok(output)
591}
592
593pub fn build_source_filter(
595 stage: &FilterStageSpec,
596 info: FrameInfo,
597 frames: usize,
598) -> Result<Box<dyn Source<Output = Frame>>> {
599 match stage.name.as_str() {
600 "pattern" => build_pattern_filter_source(&stage.spec, info, frames),
601 other => Err(MediaError::Message(format!(
602 "filter '{other}' is not an executable source filter"
603 ))),
604 }
605}
606
607pub fn build_raw_video_source_filter(
609 stage: &FilterStageSpec,
610 info: FrameInfo,
611 frames: usize,
612) -> Result<Box<dyn RawVideoFrameSource>> {
613 match stage.name.as_str() {
614 "pattern" => build_pattern_raw_video_source(&stage.spec, info, frames),
615 _ => {
616 let source = build_source_filter(stage, info, frames)?;
617 Ok(Box::new(FrameSourceRawVideoAdapter::new(source, info)))
618 }
619 }
620}
621
622pub fn build_filter_transform(stage: &FilterStageSpec) -> Result<Box<dyn Filter>> {
624 match stage.name.as_str() {
625 "identity" => build_identity_filter(),
626 "crop" => build_crop_filter(&stage.spec),
627 "scale" => build_scale_filter(&stage.spec),
628 other => Err(MediaError::Message(format!(
629 "filter '{other}' is not an executable transform filter"
630 ))),
631 }
632}
633
634fn filter_transform_output_info(stage: &FilterStageSpec, input: FrameInfo) -> Result<FrameInfo> {
635 match stage.name.as_str() {
636 "identity" => Ok(input),
637 "crop" => crop_filter_output_info(&stage.spec, input),
638 "scale" => scale_filter_output_info(&stage.spec, input),
639 other => Err(MediaError::Message(format!(
640 "filter '{other}' has no output metadata model wired yet"
641 ))),
642 }
643}
644
645fn validate_executable_filter_spec(
646 manifest: FilterManifest,
647 stage: &FilterStageSpec,
648) -> Result<()> {
649 if manifest.status != FilterStatus::Implemented {
650 return Err(MediaError::Message(format!(
651 "filter '{}' is available as a discovery scaffold but execution is not implemented yet",
652 stage.name
653 )));
654 }
655
656 match stage.name.as_str() {
657 "pattern" => validate_pattern_filter_spec(&stage.spec),
658 "identity" => validate_identity_filter_spec(&stage.spec),
659 "crop" => validate_crop_filter_spec(&stage.spec),
660 "scale" => validate_scale_filter_spec(&stage.spec),
661 other => Err(MediaError::Message(format!(
662 "filter '{other}' has no execution model wired yet"
663 ))),
664 }
665}
666
667fn validate_identity_filter_spec(spec: &str) -> Result<()> {
668 if spec.contains('=') || spec.contains(':') {
669 return Err(MediaError::Message(
670 "identity filter does not accept options".to_string(),
671 ));
672 }
673 Ok(())
674}
675
676#[cfg(feature = "filter-identity")]
677fn build_identity_filter() -> Result<Box<dyn Filter>> {
678 Ok(Box::new(IdentityFilter))
679}
680
681#[cfg(not(feature = "filter-identity"))]
682fn build_identity_filter() -> Result<Box<dyn Filter>> {
683 Err(MediaError::Message("unknown filter 'identity'".to_string()))
684}
685
686#[cfg(feature = "filter-crop")]
687fn validate_crop_filter_spec(spec: &str) -> Result<()> {
688 parse_crop_filter_spec(spec).map(|_| ())
689}
690
691#[cfg(not(feature = "filter-crop"))]
692fn validate_crop_filter_spec(_spec: &str) -> Result<()> {
693 Err(MediaError::Message("unknown filter 'crop'".to_string()))
694}
695
696#[cfg(feature = "filter-scale")]
697fn validate_scale_filter_spec(spec: &str) -> Result<()> {
698 parse_scale_filter_spec(spec).map(|_| ())
699}
700
701#[cfg(not(feature = "filter-scale"))]
702fn validate_scale_filter_spec(_spec: &str) -> Result<()> {
703 Err(MediaError::Message("unknown filter 'scale'".to_string()))
704}
705
706#[cfg(feature = "filter-crop")]
707fn build_crop_filter(spec: &str) -> Result<Box<dyn Filter>> {
708 parse_crop_filter_spec(spec).map(|filter| Box::new(filter) as Box<dyn Filter>)
709}
710
711#[cfg(not(feature = "filter-crop"))]
712fn build_crop_filter(_spec: &str) -> Result<Box<dyn Filter>> {
713 Err(MediaError::Message("unknown filter 'crop'".to_string()))
714}
715
716#[cfg(feature = "filter-scale")]
717fn build_scale_filter(spec: &str) -> Result<Box<dyn Filter>> {
718 parse_scale_filter_spec(spec).map(|filter| Box::new(filter) as Box<dyn Filter>)
719}
720
721#[cfg(not(feature = "filter-scale"))]
722fn build_scale_filter(_spec: &str) -> Result<Box<dyn Filter>> {
723 Err(MediaError::Message("unknown filter 'scale'".to_string()))
724}
725
726#[cfg(feature = "filter-crop")]
727fn crop_filter_output_info(spec: &str, input: FrameInfo) -> Result<FrameInfo> {
728 parse_crop_filter_spec(spec)?.output_info(input)
729}
730
731#[cfg(not(feature = "filter-crop"))]
732fn crop_filter_output_info(_spec: &str, _input: FrameInfo) -> Result<FrameInfo> {
733 Err(MediaError::Message("unknown filter 'crop'".to_string()))
734}
735
736#[cfg(feature = "filter-scale")]
737fn scale_filter_output_info(spec: &str, input: FrameInfo) -> Result<FrameInfo> {
738 parse_scale_filter_spec(spec)?.output_info(input)
739}
740
741#[cfg(not(feature = "filter-scale"))]
742fn scale_filter_output_info(_spec: &str, _input: FrameInfo) -> Result<FrameInfo> {
743 Err(MediaError::Message("unknown filter 'scale'".to_string()))
744}
745
746#[cfg(feature = "filter-pattern")]
747fn validate_pattern_filter_spec(spec: &str) -> Result<()> {
748 parse_pattern_stage_kind(spec).map(|_| ())
749}
750
751#[cfg(not(feature = "filter-pattern"))]
752fn validate_pattern_filter_spec(_spec: &str) -> Result<()> {
753 Err(MediaError::Message("unknown filter 'pattern'".to_string()))
754}
755
756#[cfg(feature = "filter-pattern")]
757fn build_pattern_filter_source(
758 spec: &str,
759 info: FrameInfo,
760 frames: usize,
761) -> Result<Box<dyn Source<Output = Frame>>> {
762 Ok(Box::new(PatternSource::new(
763 info,
764 parse_pattern_stage_kind(spec)?,
765 frames,
766 )?))
767}
768
769#[cfg(not(feature = "filter-pattern"))]
770fn build_pattern_filter_source(
771 _spec: &str,
772 _info: FrameInfo,
773 _frames: usize,
774) -> Result<Box<dyn Source<Output = Frame>>> {
775 Err(MediaError::Message("unknown filter 'pattern'".to_string()))
776}
777
778#[cfg(feature = "filter-pattern")]
779fn build_pattern_raw_video_source(
780 spec: &str,
781 info: FrameInfo,
782 frames: usize,
783) -> Result<Box<dyn RawVideoFrameSource>> {
784 Ok(Box::new(PatternSource::new(
785 info,
786 parse_pattern_stage_kind(spec)?,
787 frames,
788 )?))
789}
790
791#[cfg(not(feature = "filter-pattern"))]
792fn build_pattern_raw_video_source(
793 _spec: &str,
794 _info: FrameInfo,
795 _frames: usize,
796) -> Result<Box<dyn RawVideoFrameSource>> {
797 Err(MediaError::Message("unknown filter 'pattern'".to_string()))
798}
799
800#[cfg(feature = "filter-pattern")]
801fn parse_pattern_stage_kind(spec: &str) -> Result<PatternKind> {
802 if filter_spec_name(spec) != "pattern" {
803 return Err(MediaError::Message(
804 "source filter must be pattern=<name>".to_string(),
805 ));
806 }
807 let Some((_, value)) = spec.split_once('=').or_else(|| spec.split_once(':')) else {
808 return Err(MediaError::Message(
809 "pattern source expects --filter pattern=<name>".to_string(),
810 ));
811 };
812 PatternKind::parse(value)
813}
814
815#[derive(Debug, Clone, Copy, Default)]
817#[cfg(feature = "filter-identity")]
818pub struct IdentityFilter;
819
820#[cfg(feature = "filter-identity")]
821impl Filter for IdentityFilter {
822 fn process(&mut self, frame: Frame) -> Result<Vec<Frame>> {
823 Ok(vec![frame])
824 }
825}
826
827#[derive(Debug, Clone, Copy, PartialEq, Eq)]
829#[cfg(feature = "filter-crop")]
830pub struct CropFilter {
831 x: usize,
832 y: usize,
833 width: usize,
834 height: usize,
835}
836
837#[cfg(feature = "filter-crop")]
838impl CropFilter {
839 pub fn new(x: usize, y: usize, width: usize, height: usize) -> Result<Self> {
841 if width == 0 || height == 0 {
842 return Err(MediaError::InvalidDimensions { width, height });
843 }
844 Ok(Self {
845 x,
846 y,
847 width,
848 height,
849 })
850 }
851
852 pub const fn x(self) -> usize {
854 self.x
855 }
856
857 pub const fn y(self) -> usize {
859 self.y
860 }
861
862 pub const fn width(self) -> usize {
864 self.width
865 }
866
867 pub const fn height(self) -> usize {
869 self.height
870 }
871
872 pub fn output_info(self, input: FrameInfo) -> Result<FrameInfo> {
874 crop_output_info(input, self.x, self.y, self.width, self.height)
875 }
876}
877
878#[cfg(feature = "filter-crop")]
879impl Filter for CropFilter {
880 fn process(&mut self, frame: Frame) -> Result<Vec<Frame>> {
881 let input = frame.info();
882 let output = self.output_info(input)?;
883 let data = crop_frame_data(frame.data(), input, self.x, self.y, self.width, self.height)?;
884 Ok(vec![Frame::new(output, data)?])
885 }
886}
887
888#[derive(Debug, Clone, Copy, PartialEq, Eq)]
890#[cfg(feature = "filter-scale")]
891pub struct ScaleFilter {
892 width: usize,
893 height: usize,
894}
895
896#[cfg(feature = "filter-scale")]
897impl ScaleFilter {
898 pub fn new(width: usize, height: usize) -> Result<Self> {
900 if width == 0 || height == 0 {
901 return Err(MediaError::InvalidDimensions { width, height });
902 }
903 Ok(Self { width, height })
904 }
905
906 pub const fn width(self) -> usize {
908 self.width
909 }
910
911 pub const fn height(self) -> usize {
913 self.height
914 }
915
916 pub fn output_info(self, input: FrameInfo) -> Result<FrameInfo> {
918 FrameInfo::new(self.width, self.height, input.format)
919 }
920}
921
922#[cfg(feature = "filter-scale")]
923impl Filter for ScaleFilter {
924 fn process(&mut self, frame: Frame) -> Result<Vec<Frame>> {
925 let input = frame.info();
926 let output = self.output_info(input)?;
927 let data = scale_frame_data(frame.data(), input, self.width, self.height)?;
928 Ok(vec![Frame::new(output, data)?])
929 }
930}
931
932#[cfg(feature = "filter-crop")]
933fn parse_crop_filter_spec(spec: &str) -> Result<CropFilter> {
934 let params = parse_filter_params("crop", spec)?;
935 let mut x = None;
936 let mut y = None;
937 let mut width = None;
938 let mut height = None;
939 for (key, value) in params {
940 match key {
941 "x" => assign_usize_param("crop", "x", value, false, &mut x)?,
942 "y" => assign_usize_param("crop", "y", value, false, &mut y)?,
943 "w" => assign_usize_param("crop", "w", value, true, &mut width)?,
944 "h" => assign_usize_param("crop", "h", value, true, &mut height)?,
945 other => {
946 return Err(MediaError::Message(format!(
947 "crop filter does not accept parameter '{other}'"
948 )));
949 }
950 }
951 }
952 CropFilter::new(
953 require_param("crop", "x", x)?,
954 require_param("crop", "y", y)?,
955 require_param("crop", "w", width)?,
956 require_param("crop", "h", height)?,
957 )
958}
959
960#[cfg(feature = "filter-scale")]
961fn parse_scale_filter_spec(spec: &str) -> Result<ScaleFilter> {
962 let params = parse_filter_params("scale", spec)?;
963 let mut width = None;
964 let mut height = None;
965 for (key, value) in params {
966 match key {
967 "w" => assign_usize_param("scale", "w", value, true, &mut width)?,
968 "h" => assign_usize_param("scale", "h", value, true, &mut height)?,
969 other => {
970 return Err(MediaError::Message(format!(
971 "scale filter does not accept parameter '{other}'"
972 )));
973 }
974 }
975 }
976 ScaleFilter::new(
977 require_param("scale", "w", width)?,
978 require_param("scale", "h", height)?,
979 )
980}
981
982#[cfg(any(feature = "filter-crop", feature = "filter-scale"))]
983fn parse_filter_params<'a>(filter_name: &str, spec: &'a str) -> Result<Vec<(&'a str, &'a str)>> {
984 if filter_spec_name(spec) != filter_name {
985 return Err(MediaError::Message(format!(
986 "{filter_name} filter expects a spec starting with {filter_name}="
987 )));
988 }
989 let Some((_, body)) = spec.split_once('=') else {
990 return Err(MediaError::Message(format!(
991 "{filter_name} filter expects key=value parameters"
992 )));
993 };
994 if body.is_empty() {
995 return Err(MediaError::Message(format!(
996 "{filter_name} filter expects key=value parameters"
997 )));
998 }
999 let mut params = Vec::new();
1000 for token in body.split(':') {
1001 let Some((key, value)) = token.split_once('=') else {
1002 return Err(MediaError::Message(format!(
1003 "{filter_name} filter parameter '{token}' must use key=value syntax"
1004 )));
1005 };
1006 if key.is_empty() || value.is_empty() {
1007 return Err(MediaError::Message(format!(
1008 "{filter_name} filter parameters cannot have empty keys or values"
1009 )));
1010 }
1011 params.push((key, value));
1012 }
1013 Ok(params)
1014}
1015
1016#[cfg(any(feature = "filter-crop", feature = "filter-scale"))]
1017fn assign_usize_param(
1018 filter: &str,
1019 key: &str,
1020 value: &str,
1021 positive: bool,
1022 slot: &mut Option<usize>,
1023) -> Result<()> {
1024 if slot.is_some() {
1025 return Err(MediaError::Message(format!(
1026 "{filter} filter parameter '{key}' was provided more than once"
1027 )));
1028 }
1029 let parsed = value.parse::<usize>().map_err(|_| {
1030 MediaError::Message(format!(
1031 "{filter} filter parameter '{key}' expects an integer, got '{value}'"
1032 ))
1033 })?;
1034 if positive && parsed == 0 {
1035 return Err(MediaError::Message(format!(
1036 "{filter} filter parameter '{key}' must be greater than zero"
1037 )));
1038 }
1039 *slot = Some(parsed);
1040 Ok(())
1041}
1042
1043#[cfg(any(feature = "filter-crop", feature = "filter-scale"))]
1044fn require_param(filter: &str, key: &str, value: Option<usize>) -> Result<usize> {
1045 value.ok_or_else(|| {
1046 MediaError::Message(format!(
1047 "{filter} filter is missing required parameter '{key}'"
1048 ))
1049 })
1050}
1051
1052#[cfg(feature = "filter-crop")]
1053fn crop_output_info(
1054 input: FrameInfo,
1055 x: usize,
1056 y: usize,
1057 width: usize,
1058 height: usize,
1059) -> Result<FrameInfo> {
1060 let x_end = x.checked_add(width).ok_or(MediaError::LengthOverflow)?;
1061 let y_end = y.checked_add(height).ok_or(MediaError::LengthOverflow)?;
1062 if x_end > input.width || y_end > input.height {
1063 return Err(MediaError::IncompatibleFormat {
1064 format: input.format.name(),
1065 reason: format!(
1066 "crop rectangle x={x}:y={y}:w={width}:h={height} exceeds {}x{} input",
1067 input.width, input.height
1068 ),
1069 });
1070 }
1071 validate_crop_alignment(input.format, x, y, width, height)?;
1072 FrameInfo::new(width, height, input.format)
1073}
1074
1075#[cfg(feature = "filter-crop")]
1076fn validate_crop_alignment(
1077 format: PixelFormat,
1078 x: usize,
1079 y: usize,
1080 width: usize,
1081 height: usize,
1082) -> Result<()> {
1083 let Some(sampling) = format.chroma_sampling() else {
1084 return Ok(());
1085 };
1086 let subsample_x = sampling.subsample_x();
1087 let subsample_y = sampling.subsample_y();
1088 if !x.is_multiple_of(subsample_x)
1089 || !width.is_multiple_of(subsample_x)
1090 || !y.is_multiple_of(subsample_y)
1091 || !height.is_multiple_of(subsample_y)
1092 {
1093 return Err(MediaError::IncompatibleFormat {
1094 format: format.name(),
1095 reason: format!(
1096 "crop coordinates and dimensions must be aligned to {subsample_x}x{subsample_y} samples"
1097 ),
1098 });
1099 }
1100 Ok(())
1101}
1102
1103#[cfg(feature = "filter-crop")]
1104fn crop_frame_data(
1105 input: &[u8],
1106 info: FrameInfo,
1107 x: usize,
1108 y: usize,
1109 width: usize,
1110 height: usize,
1111) -> Result<Vec<u8>> {
1112 let output = crop_output_info(info, x, y, width, height)?;
1113 if input.len() != info.expected_len() {
1114 return Err(MediaError::BufferLength {
1115 expected: info.expected_len(),
1116 actual: input.len(),
1117 });
1118 }
1119 let mut data = vec![0; output.expected_len()];
1120 match info.format {
1121 PixelFormat::Rgb24 => crop_packed_rgb24(input, &mut data, info.width, x, y, width, height),
1122 PixelFormat::Gbrp8 => crop_full_planes(
1123 input,
1124 &mut data,
1125 info.width,
1126 info.height,
1127 1,
1128 x,
1129 y,
1130 width,
1131 height,
1132 3,
1133 ),
1134 PixelFormat::Gray { bit_depth } => crop_full_planes(
1135 input,
1136 &mut data,
1137 info.width,
1138 info.height,
1139 bit_depth.bytes_per_sample(),
1140 x,
1141 y,
1142 width,
1143 height,
1144 1,
1145 ),
1146 PixelFormat::PlanarYuv {
1147 chroma_sampling,
1148 bit_depth,
1149 } => crop_planar_yuv(
1150 input,
1151 &mut data,
1152 info.width,
1153 info.height,
1154 chroma_sampling,
1155 bit_depth,
1156 x,
1157 y,
1158 width,
1159 height,
1160 ),
1161 }
1162 Ok(data)
1163}
1164
1165#[cfg(feature = "filter-scale")]
1166fn scale_frame_data(input: &[u8], info: FrameInfo, width: usize, height: usize) -> Result<Vec<u8>> {
1167 let output = FrameInfo::new(width, height, info.format)?;
1168 if input.len() != info.expected_len() {
1169 return Err(MediaError::BufferLength {
1170 expected: info.expected_len(),
1171 actual: input.len(),
1172 });
1173 }
1174 let mut data = vec![0; output.expected_len()];
1175 match info.format {
1176 PixelFormat::Rgb24 => {
1177 scale_packed_rgb24(input, &mut data, info.width, info.height, width, height)
1178 }
1179 PixelFormat::Gbrp8 => scale_full_planes(
1180 input,
1181 &mut data,
1182 info.width,
1183 info.height,
1184 width,
1185 height,
1186 1,
1187 3,
1188 ),
1189 PixelFormat::Gray { bit_depth } => scale_full_planes(
1190 input,
1191 &mut data,
1192 info.width,
1193 info.height,
1194 width,
1195 height,
1196 bit_depth.bytes_per_sample(),
1197 1,
1198 ),
1199 PixelFormat::PlanarYuv {
1200 chroma_sampling,
1201 bit_depth,
1202 } => scale_planar_yuv(
1203 input,
1204 &mut data,
1205 info.width,
1206 info.height,
1207 width,
1208 height,
1209 chroma_sampling,
1210 bit_depth,
1211 ),
1212 }
1213 Ok(data)
1214}
1215
1216#[cfg(feature = "filter-crop")]
1217#[allow(clippy::too_many_arguments)]
1218fn crop_packed_rgb24(
1219 input: &[u8],
1220 output: &mut [u8],
1221 input_width: usize,
1222 x: usize,
1223 y: usize,
1224 width: usize,
1225 height: usize,
1226) {
1227 crop_plane_bytes(input, output, input_width, x, y, width, height, width, 3);
1228}
1229
1230#[cfg(feature = "filter-scale")]
1231fn scale_packed_rgb24(
1232 input: &[u8],
1233 output: &mut [u8],
1234 input_width: usize,
1235 input_height: usize,
1236 output_width: usize,
1237 output_height: usize,
1238) {
1239 scale_plane_bytes(
1240 input,
1241 output,
1242 input_width,
1243 input_height,
1244 output_width,
1245 output_height,
1246 3,
1247 );
1248}
1249
1250#[cfg(feature = "filter-crop")]
1251#[allow(clippy::too_many_arguments)]
1252fn crop_full_planes(
1253 input: &[u8],
1254 output: &mut [u8],
1255 input_width: usize,
1256 input_height: usize,
1257 bytes_per_sample: usize,
1258 x: usize,
1259 y: usize,
1260 width: usize,
1261 height: usize,
1262 planes: usize,
1263) {
1264 let input_plane_len = input_width * input_height * bytes_per_sample;
1265 let output_plane_len = width * height * bytes_per_sample;
1266 for plane in 0..planes {
1267 let input_start = plane * input_plane_len;
1268 let output_start = plane * output_plane_len;
1269 crop_plane_bytes(
1270 &input[input_start..input_start + input_plane_len],
1271 &mut output[output_start..output_start + output_plane_len],
1272 input_width,
1273 x,
1274 y,
1275 width,
1276 height,
1277 width,
1278 bytes_per_sample,
1279 );
1280 }
1281}
1282
1283#[cfg(feature = "filter-scale")]
1284#[allow(clippy::too_many_arguments)]
1285fn scale_full_planes(
1286 input: &[u8],
1287 output: &mut [u8],
1288 input_width: usize,
1289 input_height: usize,
1290 output_width: usize,
1291 output_height: usize,
1292 bytes_per_sample: usize,
1293 planes: usize,
1294) {
1295 let input_plane_len = input_width * input_height * bytes_per_sample;
1296 let output_plane_len = output_width * output_height * bytes_per_sample;
1297 for plane in 0..planes {
1298 let input_start = plane * input_plane_len;
1299 let output_start = plane * output_plane_len;
1300 scale_plane_bytes(
1301 &input[input_start..input_start + input_plane_len],
1302 &mut output[output_start..output_start + output_plane_len],
1303 input_width,
1304 input_height,
1305 output_width,
1306 output_height,
1307 bytes_per_sample,
1308 );
1309 }
1310}
1311
1312#[cfg(feature = "filter-crop")]
1313#[allow(clippy::too_many_arguments)]
1314fn crop_planar_yuv(
1315 input: &[u8],
1316 output: &mut [u8],
1317 input_width: usize,
1318 input_height: usize,
1319 chroma_sampling: ChromaSampling,
1320 bit_depth: SampleBitDepth,
1321 x: usize,
1322 y: usize,
1323 width: usize,
1324 height: usize,
1325) {
1326 let bytes_per_sample = bit_depth.bytes_per_sample();
1327 let input_luma_len = input_width * input_height * bytes_per_sample;
1328 let output_luma_len = width * height * bytes_per_sample;
1329 crop_plane_bytes(
1330 &input[..input_luma_len],
1331 &mut output[..output_luma_len],
1332 input_width,
1333 x,
1334 y,
1335 width,
1336 height,
1337 width,
1338 bytes_per_sample,
1339 );
1340 if chroma_sampling == ChromaSampling::Monochrome {
1341 return;
1342 }
1343
1344 let subsample_x = chroma_sampling.subsample_x();
1345 let subsample_y = chroma_sampling.subsample_y();
1346 let input_chroma_width = input_width / subsample_x;
1347 let input_chroma_height = input_height / subsample_y;
1348 let output_chroma_width = width / subsample_x;
1349 let output_chroma_height = height / subsample_y;
1350 let input_chroma_len = input_chroma_width * input_chroma_height * bytes_per_sample;
1351 let output_chroma_len = output_chroma_width * output_chroma_height * bytes_per_sample;
1352 let chroma_x = x / subsample_x;
1353 let chroma_y = y / subsample_y;
1354 for plane in 0..2 {
1355 let input_start = input_luma_len + plane * input_chroma_len;
1356 let output_start = output_luma_len + plane * output_chroma_len;
1357 crop_plane_bytes(
1358 &input[input_start..input_start + input_chroma_len],
1359 &mut output[output_start..output_start + output_chroma_len],
1360 input_chroma_width,
1361 chroma_x,
1362 chroma_y,
1363 output_chroma_width,
1364 output_chroma_height,
1365 output_chroma_width,
1366 bytes_per_sample,
1367 );
1368 }
1369}
1370
1371#[cfg(feature = "filter-scale")]
1372#[allow(clippy::too_many_arguments)]
1373fn scale_planar_yuv(
1374 input: &[u8],
1375 output: &mut [u8],
1376 input_width: usize,
1377 input_height: usize,
1378 output_width: usize,
1379 output_height: usize,
1380 chroma_sampling: ChromaSampling,
1381 bit_depth: SampleBitDepth,
1382) {
1383 let bytes_per_sample = bit_depth.bytes_per_sample();
1384 let input_luma_len = input_width * input_height * bytes_per_sample;
1385 let output_luma_len = output_width * output_height * bytes_per_sample;
1386 scale_plane_bytes(
1387 &input[..input_luma_len],
1388 &mut output[..output_luma_len],
1389 input_width,
1390 input_height,
1391 output_width,
1392 output_height,
1393 bytes_per_sample,
1394 );
1395 if chroma_sampling == ChromaSampling::Monochrome {
1396 return;
1397 }
1398
1399 let subsample_x = chroma_sampling.subsample_x();
1400 let subsample_y = chroma_sampling.subsample_y();
1401 let input_chroma_width = input_width / subsample_x;
1402 let input_chroma_height = input_height / subsample_y;
1403 let output_chroma_width = output_width / subsample_x;
1404 let output_chroma_height = output_height / subsample_y;
1405 let input_chroma_len = input_chroma_width * input_chroma_height * bytes_per_sample;
1406 let output_chroma_len = output_chroma_width * output_chroma_height * bytes_per_sample;
1407 for plane in 0..2 {
1408 let input_start = input_luma_len + plane * input_chroma_len;
1409 let output_start = output_luma_len + plane * output_chroma_len;
1410 scale_plane_bytes(
1411 &input[input_start..input_start + input_chroma_len],
1412 &mut output[output_start..output_start + output_chroma_len],
1413 input_chroma_width,
1414 input_chroma_height,
1415 output_chroma_width,
1416 output_chroma_height,
1417 bytes_per_sample,
1418 );
1419 }
1420}
1421
1422#[cfg(feature = "filter-crop")]
1423#[allow(clippy::too_many_arguments)]
1424fn crop_plane_bytes(
1425 input: &[u8],
1426 output: &mut [u8],
1427 input_width: usize,
1428 x: usize,
1429 y: usize,
1430 width: usize,
1431 height: usize,
1432 output_width: usize,
1433 bytes_per_sample: usize,
1434) {
1435 let row_bytes = width * bytes_per_sample;
1436 let input_stride = input_width * bytes_per_sample;
1437 let output_stride = output_width * bytes_per_sample;
1438 for row in 0..height {
1439 let input_start = (y + row) * input_stride + x * bytes_per_sample;
1440 let output_start = row * output_stride;
1441 output[output_start..output_start + row_bytes]
1442 .copy_from_slice(&input[input_start..input_start + row_bytes]);
1443 }
1444}
1445
1446#[cfg(feature = "filter-scale")]
1447#[allow(clippy::too_many_arguments)]
1448fn scale_plane_bytes(
1449 input: &[u8],
1450 output: &mut [u8],
1451 input_width: usize,
1452 input_height: usize,
1453 output_width: usize,
1454 output_height: usize,
1455 bytes_per_sample: usize,
1456) {
1457 let input_stride = input_width * bytes_per_sample;
1458 let output_stride = output_width * bytes_per_sample;
1459 for y in 0..output_height {
1460 let source_y = y * input_height / output_height;
1461 for x in 0..output_width {
1462 let source_x = x * input_width / output_width;
1463 let input_start = source_y * input_stride + source_x * bytes_per_sample;
1464 let output_start = y * output_stride + x * bytes_per_sample;
1465 output[output_start..output_start + bytes_per_sample]
1466 .copy_from_slice(&input[input_start..input_start + bytes_per_sample]);
1467 }
1468 }
1469}
1470
1471#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1473#[cfg(feature = "filter-pattern")]
1474pub enum PatternKind {
1475 Black,
1477 Checker,
1479 Gradient,
1481 ColorBlocks,
1483 BitdepthCanary,
1485}
1486
1487#[cfg(feature = "filter-pattern")]
1488impl PatternKind {
1489 pub const CANONICAL_NAMES: &'static [&'static str] = PATTERN_SOURCE_NAMES;
1491
1492 pub fn parse(value: &str) -> Result<Self> {
1494 value.parse()
1495 }
1496
1497 pub const fn name(self) -> &'static str {
1499 match self {
1500 Self::Black => "black",
1501 Self::Checker => "checker",
1502 Self::Gradient => "gradient",
1503 Self::ColorBlocks => "color_blocks",
1504 Self::BitdepthCanary => "bitdepth_canary",
1505 }
1506 }
1507}
1508
1509#[cfg(feature = "filter-pattern")]
1510impl FromStr for PatternKind {
1511 type Err = MediaError;
1512
1513 fn from_str(value: &str) -> Result<Self> {
1514 match value.trim() {
1515 "black" => Ok(Self::Black),
1516 "checker" => Ok(Self::Checker),
1517 "gradient" => Ok(Self::Gradient),
1518 "color_blocks" | "blocks" => Ok(Self::ColorBlocks),
1519 "bitdepth_canary" => Ok(Self::BitdepthCanary),
1520 other => Err(MediaError::Message(format!(
1521 "unknown pattern source '{other}'; accepted patterns: {}",
1522 PatternKind::CANONICAL_NAMES.join(", ")
1523 ))),
1524 }
1525 }
1526}
1527
1528#[derive(Debug, Clone)]
1530#[cfg(feature = "filter-pattern")]
1531pub struct PatternSource {
1532 info: FrameInfo,
1533 pattern: PatternKind,
1534 frames_remaining: usize,
1535 frame_index: usize,
1536}
1537
1538#[cfg(feature = "filter-pattern")]
1539impl PatternSource {
1540 pub fn new(info: FrameInfo, pattern: PatternKind, frames: usize) -> Result<Self> {
1542 validate_pattern_kind_format(info.format, pattern)?;
1543 Ok(Self {
1544 info,
1545 pattern,
1546 frames_remaining: frames,
1547 frame_index: 0,
1548 })
1549 }
1550
1551 pub const fn pattern(&self) -> PatternKind {
1553 self.pattern
1554 }
1555
1556 pub const fn info(&self) -> FrameInfo {
1558 self.info
1559 }
1560
1561 pub const fn frames_remaining(&self) -> usize {
1563 self.frames_remaining
1564 }
1565
1566 pub fn fill_frame(&mut self, output: &mut [u8]) -> Result<bool> {
1570 if self.frames_remaining == 0 {
1571 return Ok(false);
1572 }
1573 fill_pattern_frame(self.info, self.pattern, self.frame_index, output)?;
1574 self.frames_remaining -= 1;
1575 self.frame_index += 1;
1576 Ok(true)
1577 }
1578}
1579
1580#[cfg(feature = "filter-pattern")]
1581impl Source for PatternSource {
1582 type Output = Frame;
1583
1584 fn pull(&mut self) -> Result<Option<Self::Output>> {
1585 let mut data = vec![0; self.info.expected_len()];
1586 if !self.fill_frame(&mut data)? {
1587 return Ok(None);
1588 }
1589 Frame::new(self.info, data).map(Some)
1590 }
1591}
1592
1593#[cfg(feature = "filter-pattern")]
1594impl RawVideoFrameSource for PatternSource {
1595 fn read_frame(&mut self, frame: &mut [u8]) -> Result<bool> {
1596 self.fill_frame(frame)
1597 }
1598}
1599
1600#[cfg(feature = "filter-pattern")]
1601pub fn generate_pattern_stream(
1603 info: FrameInfo,
1604 pattern: PatternKind,
1605 frames: usize,
1606) -> Result<Vec<u8>> {
1607 let total_len = info
1608 .expected_len()
1609 .checked_mul(frames)
1610 .ok_or(MediaError::LengthOverflow)?;
1611 let mut output = Vec::with_capacity(total_len);
1612 let mut source = PatternSource::new(info, pattern, frames)?;
1613 while let Some(frame) = source.pull()? {
1614 output.extend_from_slice(frame.data());
1615 }
1616 Ok(output)
1617}
1618
1619#[cfg(feature = "filter-pattern")]
1620pub fn pattern_frame_data(info: FrameInfo, pattern: PatternKind, frame: usize) -> Result<Vec<u8>> {
1622 validate_pattern_kind_format(info.format, pattern)?;
1623 let mut output = vec![0; info.expected_len()];
1624 fill_pattern_frame(info, pattern, frame, &mut output)?;
1625 Ok(output)
1626}
1627
1628#[cfg(feature = "filter-pattern")]
1629fn validate_pattern_format(format: PixelFormat) -> Result<()> {
1630 match format {
1631 PixelFormat::PlanarYuv { .. }
1632 | PixelFormat::Gray { .. }
1633 | PixelFormat::Gbrp8
1634 | PixelFormat::Rgb24 => Ok(()),
1635 }
1636}
1637
1638#[cfg(feature = "filter-pattern")]
1639fn validate_pattern_kind_format(format: PixelFormat, pattern: PatternKind) -> Result<()> {
1640 validate_pattern_format(format)?;
1641 if pattern == PatternKind::BitdepthCanary {
1642 validate_bitdepth_canary_format(format)?;
1643 }
1644 Ok(())
1645}
1646
1647#[cfg(feature = "filter-pattern")]
1648fn validate_bitdepth_canary_format(format: PixelFormat) -> Result<()> {
1649 match format {
1650 PixelFormat::Gray { bit_depth } | PixelFormat::PlanarYuv { bit_depth, .. } => {
1651 validate_bitdepth_canary_depth(bit_depth)
1652 }
1653 PixelFormat::Gbrp8 | PixelFormat::Rgb24 => Err(MediaError::Message(
1654 "bitdepth_canary is only supported for high-bit-depth planar formats".to_string(),
1655 )),
1656 }
1657}
1658
1659#[cfg(feature = "filter-pattern")]
1660fn fill_pattern_frame(
1661 info: FrameInfo,
1662 pattern: PatternKind,
1663 frame: usize,
1664 output: &mut [u8],
1665) -> Result<()> {
1666 let expected = info.expected_len();
1667 if output.len() != expected {
1668 return Err(MediaError::BufferLength {
1669 expected,
1670 actual: output.len(),
1671 });
1672 }
1673 validate_pattern_kind_format(info.format, pattern)?;
1674 if pattern == PatternKind::BitdepthCanary {
1675 return fill_bitdepth_canary_frame(info, frame, output);
1676 }
1677 match info.format {
1678 PixelFormat::Rgb24 => fill_pattern_rgb24(info.width, info.height, pattern, frame, output),
1679 PixelFormat::Gbrp8 => fill_pattern_gbrp8(info.width, info.height, pattern, frame, output),
1680 PixelFormat::Gray { bit_depth } => {
1681 fill_pattern_gray(info.width, info.height, bit_depth, pattern, frame, output)
1682 }
1683 PixelFormat::PlanarYuv {
1684 chroma_sampling,
1685 bit_depth,
1686 } => fill_pattern_planar_yuv(
1687 info.width,
1688 info.height,
1689 chroma_sampling,
1690 bit_depth,
1691 pattern,
1692 frame,
1693 output,
1694 ),
1695 }
1696 Ok(())
1697}
1698
1699#[cfg(feature = "filter-pattern")]
1700fn fill_pattern_rgb24(
1701 width: usize,
1702 height: usize,
1703 pattern: PatternKind,
1704 frame: usize,
1705 output: &mut [u8],
1706) {
1707 for y in 0..height {
1708 for x in 0..width {
1709 let (r, g, b) = pattern_sample(pattern, x, y, frame);
1710 let offset = (y * width + x) * 3;
1711 output[offset] = r;
1712 output[offset + 1] = g;
1713 output[offset + 2] = b;
1714 }
1715 }
1716}
1717
1718#[cfg(feature = "filter-pattern")]
1719fn fill_pattern_gbrp8(
1720 width: usize,
1721 height: usize,
1722 pattern: PatternKind,
1723 frame: usize,
1724 output: &mut [u8],
1725) {
1726 let pixels = width * height;
1727 for y in 0..height {
1728 for x in 0..width {
1729 let idx = y * width + x;
1730 let (r, g, b) = pattern_sample(pattern, x, y, frame);
1731 output[idx] = g;
1732 output[pixels + idx] = b;
1733 output[2 * pixels + idx] = r;
1734 }
1735 }
1736}
1737
1738#[cfg(feature = "filter-pattern")]
1739fn fill_pattern_gray(
1740 width: usize,
1741 height: usize,
1742 bit_depth: SampleBitDepth,
1743 pattern: PatternKind,
1744 frame: usize,
1745 output: &mut [u8],
1746) {
1747 for y in 0..height {
1748 for x in 0..width {
1749 let (sample, _, _) = pattern_sample(pattern, x, y, frame);
1750 write_pattern_sample(output, y * width + x, sample, bit_depth);
1751 }
1752 }
1753}
1754
1755#[cfg(feature = "filter-pattern")]
1756#[allow(clippy::too_many_arguments)]
1757fn fill_pattern_planar_yuv(
1758 width: usize,
1759 height: usize,
1760 chroma_sampling: ChromaSampling,
1761 bit_depth: SampleBitDepth,
1762 pattern: PatternKind,
1763 frame: usize,
1764 output: &mut [u8],
1765) {
1766 for y in 0..height {
1767 for x in 0..width {
1768 let (luma, _, _) = pattern_sample(pattern, x, y, frame);
1769 write_pattern_sample(output, y * width + x, luma, bit_depth);
1770 }
1771 }
1772
1773 if chroma_sampling == ChromaSampling::Monochrome {
1774 return;
1775 }
1776
1777 let bytes_per_sample = bit_depth.bytes_per_sample();
1778 let luma_len = width * height * bytes_per_sample;
1779 let subsample_x = chroma_sampling.subsample_x();
1780 let subsample_y = chroma_sampling.subsample_y();
1781 let chroma_width = width / subsample_x;
1782 let chroma_height = height / subsample_y;
1783 let chroma_len = chroma_width * chroma_height * bytes_per_sample;
1784 let (u_plane, v_plane) = output[luma_len..luma_len + chroma_len * 2].split_at_mut(chroma_len);
1785
1786 for chroma_y in 0..chroma_height {
1787 for chroma_x in 0..chroma_width {
1788 let mut u_sum = 0u32;
1789 let mut v_sum = 0u32;
1790 for dy in 0..subsample_y {
1791 for dx in 0..subsample_x {
1792 let x = chroma_x * subsample_x + dx;
1793 let y = chroma_y * subsample_y + dy;
1794 let (_, u, v) = pattern_sample(pattern, x, y, frame);
1795 u_sum += u32::from(u);
1796 v_sum += u32::from(v);
1797 }
1798 }
1799 let denom = (subsample_x * subsample_y) as u32;
1800 let index = chroma_y * chroma_width + chroma_x;
1801 write_pattern_sample(u_plane, index, (u_sum / denom) as u8, bit_depth);
1802 write_pattern_sample(v_plane, index, (v_sum / denom) as u8, bit_depth);
1803 }
1804 }
1805}
1806
1807#[cfg(feature = "filter-pattern")]
1808fn fill_bitdepth_canary_frame(info: FrameInfo, frame: usize, output: &mut [u8]) -> Result<()> {
1809 match info.format {
1810 PixelFormat::Gray { bit_depth } => {
1811 fill_bitdepth_canary_plane(info.width, info.height, bit_depth, frame, 0, output);
1812 }
1813 PixelFormat::PlanarYuv {
1814 chroma_sampling,
1815 bit_depth,
1816 } => {
1817 fill_bitdepth_canary_planar_yuv(
1818 info.width,
1819 info.height,
1820 chroma_sampling,
1821 bit_depth,
1822 frame,
1823 output,
1824 );
1825 }
1826 PixelFormat::Gbrp8 | PixelFormat::Rgb24 => {
1827 unreachable!("bitdepth_canary format validation rejects RGB-family formats");
1828 }
1829 }
1830 Ok(())
1831}
1832
1833#[cfg(feature = "filter-pattern")]
1834fn validate_bitdepth_canary_depth(bit_depth: SampleBitDepth) -> Result<()> {
1835 if bit_depth.bits() <= 8 {
1836 return Err(MediaError::Message(
1837 "bitdepth_canary is intended for high-bit-depth generated vectors".to_string(),
1838 ));
1839 }
1840 Ok(())
1841}
1842
1843#[cfg(feature = "filter-pattern")]
1844fn fill_bitdepth_canary_planar_yuv(
1845 width: usize,
1846 height: usize,
1847 chroma_sampling: ChromaSampling,
1848 bit_depth: SampleBitDepth,
1849 frame: usize,
1850 output: &mut [u8],
1851) {
1852 let bytes_per_sample = bit_depth.bytes_per_sample();
1853 let luma_len = width * height * bytes_per_sample;
1854 fill_bitdepth_canary_plane(width, height, bit_depth, frame, 0, &mut output[..luma_len]);
1855
1856 if chroma_sampling == ChromaSampling::Monochrome {
1857 return;
1858 }
1859
1860 let subsample_x = chroma_sampling.subsample_x();
1861 let subsample_y = chroma_sampling.subsample_y();
1862 let chroma_width = width / subsample_x;
1863 let chroma_height = height / subsample_y;
1864 let chroma_len = chroma_width * chroma_height * bytes_per_sample;
1865 let (u_plane, v_plane) = output[luma_len..luma_len + chroma_len * 2].split_at_mut(chroma_len);
1866 fill_bitdepth_canary_plane(chroma_width, chroma_height, bit_depth, frame, 1, u_plane);
1867 fill_bitdepth_canary_plane(chroma_width, chroma_height, bit_depth, frame, 2, v_plane);
1868}
1869
1870#[cfg(feature = "filter-pattern")]
1871fn fill_bitdepth_canary_plane(
1872 width: usize,
1873 height: usize,
1874 bit_depth: SampleBitDepth,
1875 frame: usize,
1876 plane: usize,
1877 output: &mut [u8],
1878) {
1879 for y in 0..height {
1880 for x in 0..width {
1881 write_planar_sample(
1882 output,
1883 y * width + x,
1884 bitdepth_canary_sample(x, y, frame, plane, bit_depth),
1885 bit_depth,
1886 )
1887 .expect("validated pattern output must contain every sample");
1888 }
1889 }
1890}
1891
1892#[cfg(feature = "filter-pattern")]
1893fn bitdepth_canary_sample(
1894 x: usize,
1895 y: usize,
1896 frame: usize,
1897 plane: usize,
1898 bit_depth: SampleBitDepth,
1899) -> u16 {
1900 let shift = u32::from(bit_depth.bits() - 8);
1901 let block_index = ((x / 8) + (y / 8) * 2 + frame) % 4;
1902 let base = match plane {
1903 0 => [32u16, 96, 160, 224][block_index],
1904 1 => [80u16, 144, 208, 48][block_index],
1905 2 => [112u16, 176, 64, 240][block_index],
1906 _ => 0,
1907 };
1908 (base << shift) | bitdepth_canary_lower(x, y, frame, plane, shift)
1909}
1910
1911#[cfg(feature = "filter-pattern")]
1912fn bitdepth_canary_lower(x: usize, y: usize, frame: usize, plane: usize, shift: u32) -> u16 {
1913 let low_mask = (1u16 << shift) - 1;
1914 let mut lower = ((x & 3) | ((y & 3) << 2) | ((plane & 3) << 1) | frame) as u16 & low_mask;
1915 if lower == 0 {
1916 lower = low_mask;
1917 }
1918 lower
1919}
1920
1921#[cfg(feature = "filter-pattern")]
1922fn write_pattern_sample(
1923 output: &mut [u8],
1924 sample_index: usize,
1925 sample: u8,
1926 bit_depth: SampleBitDepth,
1927) {
1928 let sample = scale_sample_bit_depth(
1929 u16::from(sample),
1930 SampleBitDepth::new(8).expect("8-bit samples must be supported"),
1931 bit_depth,
1932 );
1933 write_planar_sample(output, sample_index, sample, bit_depth)
1934 .expect("validated pattern output must contain every sample");
1935}
1936
1937#[cfg(feature = "filter-pattern")]
1938fn pattern_sample(pattern: PatternKind, x: usize, y: usize, frame: usize) -> (u8, u8, u8) {
1939 match pattern {
1940 PatternKind::Black => (0, 0, 0),
1941 PatternKind::Checker => {
1942 if ((x / 8) + (y / 8) + frame) & 1 == 0 {
1943 (208, 176, 80)
1944 } else {
1945 (48, 96, 160)
1946 }
1947 }
1948 PatternKind::Gradient => (
1949 ((x * 7 + y * 5 + frame * 17) & 0xFF) as u8,
1950 ((64 + x * 3 + frame * 11) & 0xFF) as u8,
1951 ((96 + y * 4 + frame * 13) & 0xFF) as u8,
1952 ),
1953 PatternKind::ColorBlocks => {
1954 const PALETTE: [(u8, u8, u8); 4] = [
1955 (32, 128, 128),
1956 (80, 96, 176),
1957 (144, 176, 96),
1958 (224, 112, 144),
1959 ];
1960 PALETTE[((x / 8) + (y / 8) * 2 + frame) % PALETTE.len()]
1961 }
1962 PatternKind::BitdepthCanary => unreachable!("bitdepth_canary uses native-depth samples"),
1963 }
1964}
1965
1966#[cfg(test)]
1967mod tests {
1968 use super::*;
1969
1970 #[test]
1971 fn filter_manifest_reports_compiled_filters() {
1972 assert_eq!(
1973 filter_manifest("pattern").is_some(),
1974 cfg!(feature = "filter-pattern")
1975 );
1976 assert_eq!(
1977 filter_manifest("identity").is_some(),
1978 cfg!(feature = "filter-identity")
1979 );
1980 assert_eq!(
1981 filter_manifest("crop").is_some(),
1982 cfg!(feature = "filter-crop")
1983 );
1984 assert_eq!(
1985 filter_manifest("scale").is_some(),
1986 cfg!(feature = "filter-scale")
1987 );
1988 }
1989
1990 #[cfg(feature = "filter-pattern")]
1991 #[test]
1992 fn pattern_manifest_reports_source_contract() {
1993 let pattern = filter_manifest("pattern").expect("pattern manifest");
1994 assert_eq!(pattern.stage, FilterStageKind::Source);
1995 assert_eq!(pattern.status, FilterStatus::Implemented);
1996 assert_eq!(pattern.feature, "filter-pattern");
1997 assert_eq!(pattern.spec.forms[0].syntax, "pattern=<name>");
1998 assert_eq!(pattern.spec.parameters[0].name, "name");
1999 assert_eq!(
2000 pattern.spec.parameters[0].value,
2001 FilterSpecValue::Choice(PATTERN_SOURCE_NAMES)
2002 );
2003 }
2004
2005 #[cfg(feature = "filter-crop")]
2006 #[test]
2007 fn crop_manifest_reports_transform_contract() {
2008 let crop = filter_manifest("crop").expect("crop manifest");
2009 assert_eq!(crop.stage, FilterStageKind::Transform);
2010 assert_eq!(crop.status, FilterStatus::Implemented);
2011 assert_eq!(
2012 crop.spec.forms[0].syntax,
2013 "crop=x=<px>:y=<px>:w=<px>:h=<px>"
2014 );
2015 }
2016
2017 #[cfg(feature = "filter-scale")]
2018 #[test]
2019 fn scale_manifest_reports_transform_contract() {
2020 let scale = filter_manifest("scale").expect("scale manifest");
2021 assert_eq!(scale.stage, FilterStageKind::Transform);
2022 assert_eq!(scale.status, FilterStatus::Implemented);
2023 assert_eq!(scale.spec.forms[0].syntax, "scale=w=<px>:h=<px>");
2024 }
2025
2026 #[cfg(feature = "filter-pattern")]
2027 #[test]
2028 fn pattern_kind_parses_aliases_and_reports_canonical_names() {
2029 assert_eq!(PatternKind::parse("black").unwrap(), PatternKind::Black);
2030 assert_eq!(
2031 PatternKind::parse("blocks").unwrap(),
2032 PatternKind::ColorBlocks
2033 );
2034 assert_eq!(
2035 PatternKind::CANONICAL_NAMES,
2036 [
2037 "black",
2038 "checker",
2039 "gradient",
2040 "color_blocks",
2041 "bitdepth_canary"
2042 ]
2043 );
2044 }
2045
2046 #[cfg(feature = "filter-identity")]
2047 #[test]
2048 fn identity_filter_preserves_frame() {
2049 let info = FrameInfo::new(2, 2, PixelFormat::Rgb24).unwrap();
2050 let frame = Frame::new(info, vec![9; info.expected_len()]).unwrap();
2051 let mut filter = IdentityFilter;
2052 let out = filter.process(frame.clone()).unwrap();
2053 assert_eq!(out, vec![frame]);
2054 }
2055
2056 #[cfg(feature = "filter-crop")]
2057 #[test]
2058 fn crop_filter_extracts_aligned_yuv420_region() {
2059 let info = FrameInfo::new(4, 4, PixelFormat::Yuv420p8).unwrap();
2060 let input = [
2061 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 100, 101, 102, 103, 200, 201,
2062 202, 203,
2063 ];
2064 let frame = Frame::new(info, input.to_vec()).unwrap();
2065 let mut filter = CropFilter::new(2, 2, 2, 2).unwrap();
2066 let output = filter.process(frame).unwrap();
2067
2068 assert_eq!(output.len(), 1);
2069 assert_eq!(
2070 output[0].info(),
2071 FrameInfo::new(2, 2, PixelFormat::Yuv420p8).unwrap()
2072 );
2073 assert_eq!(output[0].data(), &[10, 11, 14, 15, 103, 203]);
2074 }
2075
2076 #[cfg(feature = "filter-crop")]
2077 #[test]
2078 fn crop_filter_rejects_unaligned_yuv420_region() {
2079 let info = FrameInfo::new(4, 4, PixelFormat::Yuv420p8).unwrap();
2080 let err = CropFilter::new(1, 0, 2, 2)
2081 .unwrap()
2082 .output_info(info)
2083 .unwrap_err();
2084 assert!(err.to_string().contains("aligned to 2x2"), "{err}");
2085 }
2086
2087 #[cfg(feature = "filter-scale")]
2088 #[test]
2089 fn scale_filter_resizes_yuv420_with_nearest_neighbor() {
2090 let info = FrameInfo::new(2, 2, PixelFormat::Yuv420p8).unwrap();
2091 let frame = Frame::new(info, vec![1, 2, 3, 4, 5, 6]).unwrap();
2092 let mut filter = ScaleFilter::new(4, 4).unwrap();
2093 let output = filter.process(frame).unwrap();
2094
2095 assert_eq!(output.len(), 1);
2096 assert_eq!(
2097 output[0].info(),
2098 FrameInfo::new(4, 4, PixelFormat::Yuv420p8).unwrap()
2099 );
2100 assert_eq!(
2101 output[0].data(),
2102 &[1, 1, 2, 2, 1, 1, 2, 2, 3, 3, 4, 4, 3, 3, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6,]
2103 );
2104 }
2105
2106 #[cfg(all(feature = "filter-crop", feature = "filter-scale"))]
2107 #[test]
2108 fn filter_pipeline_output_info_tracks_geometry_changes() {
2109 let input = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
2110 let transforms = [
2111 FilterStageSpec::new("crop=x=0:y=0:w=8:h=8").unwrap(),
2112 FilterStageSpec::new("scale=w=16:h=16").unwrap(),
2113 ];
2114 let output = filter_pipeline_output_info(input, &transforms).unwrap();
2115 assert_eq!(output, input);
2116 }
2117
2118 #[cfg(feature = "filter-pattern")]
2119 #[test]
2120 fn pattern_source_generates_black_yuv420_frame() {
2121 let info = FrameInfo::new(8, 8, PixelFormat::Yuv420p8).unwrap();
2122 let mut source = PatternSource::new(info, PatternKind::Black, 1).unwrap();
2123 let frame = source.pull().unwrap().expect("frame");
2124 assert_eq!(frame.data(), vec![0; info.expected_len()]);
2125 assert!(source.pull().unwrap().is_none());
2126 }
2127
2128 #[cfg(feature = "filter-pattern")]
2129 #[test]
2130 fn pattern_stream_generates_all_requested_frames() {
2131 let info = FrameInfo::new(8, 8, PixelFormat::Yuv444p8).unwrap();
2132 let data = generate_pattern_stream(info, PatternKind::Checker, 2).unwrap();
2133 assert_eq!(data.len(), info.expected_len() * 2);
2134 assert_ne!(&data[..info.expected_len()], &data[info.expected_len()..]);
2135 }
2136
2137 #[cfg(feature = "filter-pattern")]
2138 #[test]
2139 fn pattern_source_generates_rgb24_frame() {
2140 let info = FrameInfo::new(8, 8, PixelFormat::Rgb24).unwrap();
2141 let mut source = PatternSource::new(info, PatternKind::Checker, 1).unwrap();
2142 let frame = source.pull().unwrap().expect("frame");
2143 assert_eq!(frame.data().len(), info.expected_len());
2144 assert!(frame.data().chunks_exact(3).any(|pixel| pixel != [0, 0, 0]));
2145 }
2146
2147 #[cfg(feature = "filter-pattern")]
2148 #[test]
2149 fn pattern_source_generates_high_bit_depth_planar_frame() {
2150 let info = FrameInfo::new(8, 8, PixelFormat::yuv444(10).unwrap()).unwrap();
2151 let frame = pattern_frame_data(info, PatternKind::Gradient, 0).unwrap();
2152 assert_eq!(frame.len(), info.expected_len());
2153 let first = crate::read_planar_sample(&frame, 1, info.format.bit_depth()).unwrap();
2154 assert!(first > 0);
2155 }
2156
2157 #[cfg(feature = "filter-pattern")]
2158 #[test]
2159 fn pattern_source_generates_bitdepth_canary_yuv444p10_frame() {
2160 let info = FrameInfo::new(8, 8, PixelFormat::yuv444(10).unwrap()).unwrap();
2161 let frame = pattern_frame_data(info, PatternKind::BitdepthCanary, 0).unwrap();
2162
2163 assert_eq!(frame.len(), info.expected_len());
2164 assert_eq!(
2165 crate::read_planar_sample(&frame, 0, info.format.bit_depth()).unwrap(),
2166 131
2167 );
2168 assert_eq!(
2169 crate::read_planar_sample(&frame, 64, info.format.bit_depth()).unwrap(),
2170 322
2171 );
2172 assert_eq!(
2173 crate::read_planar_sample(&frame, 128, info.format.bit_depth()).unwrap(),
2174 451
2175 );
2176 }
2177
2178 #[cfg(feature = "filter-pattern")]
2179 #[test]
2180 fn pattern_source_rejects_bitdepth_canary_for_8_bit_formats() {
2181 let info = FrameInfo::new(8, 8, PixelFormat::Yuv444p8).unwrap();
2182 let err = PatternSource::new(info, PatternKind::BitdepthCanary, 1).unwrap_err();
2183 assert!(err.to_string().contains("high-bit-depth"), "{err}");
2184 }
2185}