pixelflow-filters 0.1.0

Official in-repository filters for PixelFlow.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
use std::fs;
use std::path::Path;
use std::thread;

#[cfg(test)]
use std::path::PathBuf;
#[cfg(test)]
use std::sync::{Arc, Mutex};

use ffms2::{FFMS2, frame::Resizers, track::TrackType, video::SeekMode};
use pixelflow_core::{
    ErrorCategory, ErrorCode, FormatDescriptor, PixelFlowError, Rational, Result,
};
use semisafe::slice::get as semisafe_get;
use tempfile::tempdir;

pub(crate) trait BackendProgress: Send {
    fn update(&mut self, current: usize, total: usize);
}

pub(crate) trait SourceVideo {
    fn properties(&self) -> VideoProperties;
    fn frame(&mut self, frame_number: usize) -> Result<DecodedFrame>;
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct VideoProperties {
    pub width: usize,
    pub height: usize,
    pub frame_count: usize,
    pub frame_rate: Option<Rational>,
    pub variable_timestamps: bool,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct DecodedFrame {
    pub format: FormatDescriptor,
    pub width: usize,
    pub height: usize,
    pub planes: Vec<DecodedPlane>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct DecodedPlane {
    pub width: usize,
    pub height: usize,
    pub stride_bytes: usize,
    pub bytes: Vec<u8>,
}

pub(crate) trait Ffms2Backend {
    type Index: Send;
    type Video: SourceVideo + Send + 'static;

    fn read_index_from_bytes(&self, bytes: &[u8]) -> Result<Self::Index>;
    fn write_index_to_bytes(&self, source_path: &Path, index: &Self::Index) -> Result<Vec<u8>>;
    fn index(
        &self,
        source_path: &Path,
        track: Option<usize>,
        progress: &mut dyn BackendProgress,
    ) -> Result<Self::Index>;
    fn open_video(
        &self,
        source_path: &Path,
        index: &Self::Index,
        track: Option<usize>,
        threads: usize,
        format: &FormatDescriptor,
    ) -> Result<Self::Video>;
}

pub(crate) struct SystemFfms2Backend;

impl SystemFfms2Backend {
    pub(crate) const fn new() -> Self {
        Self
    }
}

pub(crate) struct SystemIndex {
    inner: ffms2::index::Index,
}

pub(crate) struct SystemVideo {
    video: ffms2::video::VideoSource,
    properties: VideoProperties,
    format: FormatDescriptor,
}

impl Ffms2Backend for SystemFfms2Backend {
    type Index = SystemIndex;
    type Video = SystemVideo;

    fn read_index_from_bytes(&self, bytes: &[u8]) -> Result<Self::Index> {
        FFMS2::Init();
        let temp = tempdir().map_err(|error| {
            ffms2_index_error(format!(
                "failed to create temporary index directory: {error}"
            ))
        })?;
        let path = temp.path().join("cache.ffindex");
        fs::write(&path, bytes).map_err(|error| {
            ffms2_index_error(format!("failed to materialize cached index: {error}"))
        })?;
        let inner = ffms2::index::Index::new(&path).map_err(|error| {
            ffms2_index_error(format!("failed to read cached index: {error:?}"))
        })?;
        Ok(SystemIndex { inner })
    }

    fn write_index_to_bytes(&self, _source_path: &Path, index: &Self::Index) -> Result<Vec<u8>> {
        let temp = tempdir().map_err(|error| {
            ffms2_index_error(format!(
                "failed to create temporary index directory: {error}"
            ))
        })?;
        let path = temp.path().join("cache.ffindex");
        index.inner.WriteIndex(&path).map_err(|error| {
            ffms2_index_error(format!("failed to write FFMS2 index: {error:?}"))
        })?;
        fs::read(&path).map_err(|error| {
            ffms2_index_error(format!("failed to read written FFMS2 index: {error}"))
        })
    }

    fn index(
        &self,
        source_path: &Path,
        track: Option<usize>,
        progress: &mut dyn BackendProgress,
    ) -> Result<Self::Index> {
        FFMS2::Init();
        let indexer = ffms2::index::Indexer::new(source_path).map_err(|error| {
            ffms2_index_error(format!("failed to create FFMS2 indexer: {error:?}"))
        })?;
        configure_indexer(&indexer, track);

        let (tx, rx) = std::sync::mpsc::channel::<Option<(usize, usize)>>();
        let mut callback_state = 0usize;
        let callback_tx = tx.clone();
        indexer.ProgressCallback(
            move |current, total, _| {
                let _ = callback_tx.send(Some((current, total)));
                0
            },
            &mut callback_state,
        );

        let inner = thread::scope(|scope| {
            let progress_handle = scope.spawn(move || {
                while let Ok(update) = rx.recv() {
                    let Some((current, total)) = update else {
                        break;
                    };
                    progress.update(current, total);
                }
            });

            let result = indexer
                .DoIndexing2(ffms2::IndexErrorHandling::IEH_ABORT)
                .map_err(|error| {
                    ffms2_index_error(format!("failed to build FFMS2 index: {error:?}"))
                });
            let _ = tx.send(None);
            let _ = progress_handle.join();
            result
        })?;

        Ok(SystemIndex { inner })
    }

    fn open_video(
        &self,
        source_path: &Path,
        index: &Self::Index,
        track: Option<usize>,
        threads: usize,
        format: &FormatDescriptor,
    ) -> Result<Self::Video> {
        FFMS2::Init();
        let track = match track {
            Some(track) => track,
            None => index
                .inner
                .FirstIndexedTrackOfType(TrackType::TYPE_VIDEO)
                .map_err(|error| {
                    ffms2_open_error(format!("failed to locate indexed video track: {error:?}"))
                })?,
        };

        let mut video = ffms2::video::VideoSource::new(
            source_path,
            track,
            &index.inner,
            threads,
            SeekMode::SEEK_NORMAL,
        )
        .map_err(|error| {
            ffms2_open_error(format!("failed to open FFMS2 video source: {error:?}"))
        })?;

        let probe = ffms2::frame::Frame::GetFrame(&mut video, 0).map_err(|error| {
            ffms2_decode_error(format!("failed to decode probe frame: {error:?}"))
        })?;
        let resolution = probe.get_frame_resolution();
        let width = usize::try_from(resolution.width)
            .map_err(|_| ffms2_decode_error("decoded frame width does not fit platform usize"))?;
        let height = usize::try_from(resolution.height)
            .map_err(|_| ffms2_decode_error("decoded frame height does not fit platform usize"))?;

        let pixel_format = ffms2::frame::Frame::GetPixFmt(ffmpeg_pixel_format_name(format)?);
        if pixel_format < 0 {
            return Err(ffms2_open_error(format!(
                "failed to resolve FFmpeg pixel format for '{}'",
                format.name()
            )));
        }
        let mut target_formats = vec![pixel_format];
        video
            .SetOutputFormatV2(&mut target_formats, width, height, Resizers::RESIZER_POINT)
            .map_err(|error| {
                ffms2_open_error(format!(
                    "failed to set FFMS2 output format '{}': {error:?}",
                    format.name()
                ))
            })?;

        let props = video.GetVideoProperties();
        let frame_rate = (props.FPSNumerator > 0 && props.FPSDenominator > 0).then(|| Rational {
            numerator: i64::from(props.FPSNumerator),
            denominator: i64::from(props.FPSDenominator),
        });
        let frame_count = usize::try_from(props.NumFrames)
            .map_err(|_| ffms2_open_error("FFMS2 reported negative frame count"))?;

        let variable_timestamps = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            is_variable_timestamps(&mut video, frame_count)
        }))
        .unwrap_or(false);

        Ok(SystemVideo {
            video,
            properties: VideoProperties {
                width,
                height,
                frame_count,
                frame_rate,
                variable_timestamps,
            },
            format: format.clone(),
        })
    }
}

impl SourceVideo for SystemVideo {
    fn properties(&self) -> VideoProperties {
        self.properties
    }

    fn frame(&mut self, frame_number: usize) -> Result<DecodedFrame> {
        let frame =
            ffms2::frame::Frame::GetFrame(&mut self.video, frame_number).map_err(|error| {
                ffms2_decode_error(format!("failed to decode frame {frame_number}: {error:?}"))
            })?;
        let plane_bytes = frame.get_pixel_data().ok_or_else(|| {
            ffms2_decode_error(format!(
                "failed to inspect decoded pixel planes for frame {frame_number}"
            ))
        })?;

        let mut planes = Vec::with_capacity(self.format.planes().len());
        for (index, descriptor) in self.format.planes().iter().enumerate() {
            let bytes = plane_bytes
                .get(index)
                .and_then(|plane| plane.as_ref())
                .ok_or_else(|| {
                    ffms2_decode_error(format!(
                        "decoded frame {frame_number} is missing plane {index}"
                    ))
                })?;
            let stride_bytes =
                usize::try_from(*semisafe_get(&frame.Linesize, index)).map_err(|_| {
                    ffms2_decode_error(format!(
                        "decoded frame {frame_number} plane {index} has negative stride"
                    ))
                })?;
            let width = self.properties.width.div_ceil(descriptor.width_divisor);
            let height = self.properties.height.div_ceil(descriptor.height_divisor);

            planes.push(DecodedPlane {
                width,
                height,
                stride_bytes,
                bytes: bytes.to_vec(),
            });
        }

        Ok(DecodedFrame {
            format: self.format.clone(),
            width: self.properties.width,
            height: self.properties.height,
            planes,
        })
    }
}

fn configure_indexer(indexer: &ffms2::index::Indexer, track: Option<usize>) {
    for current_track in 0..indexer.NumTracksI() {
        let index_flag = match indexer.TrackTypeI(current_track) {
            TrackType::TYPE_VIDEO => usize::from(track.is_none_or(|track| track == current_track)),
            _ => 0,
        };
        indexer.TrackIndexSettings(current_track, index_flag);
    }
}

fn is_variable_timestamps(video: &mut ffms2::video::VideoSource, frame_count: usize) -> bool {
    if frame_count < 3 {
        return false;
    }

    let track = ffms2::track::Track::TrackFromVideo(video);
    let mut previous_pts = None;
    let mut previous_delta = None;
    for frame_number in 0..frame_count.min(32) {
        let pts = track.FrameInfo(frame_number).PTS;
        if let Some(previous_pts) = previous_pts {
            let delta = pts - previous_pts;
            if let Some(previous_delta) = previous_delta {
                if delta != previous_delta {
                    return true;
                }
            } else {
                previous_delta = Some(delta);
            }
        }
        previous_pts = Some(pts);
    }

    false
}

fn ffmpeg_pixel_format_name(format: &FormatDescriptor) -> Result<&'static str> {
    match format.name() {
        "gray8" => Ok("gray"),
        "gray10" => Ok("gray10le"),
        "gray12" => Ok("gray12le"),
        "gray16" => Ok("gray16le"),
        "yuv420p8" => Ok("yuv420p"),
        "yuv420p10" => Ok("yuv420p10le"),
        "yuv420p12" => Ok("yuv420p12le"),
        "yuv420p16" => Ok("yuv420p16le"),
        "yuv422p8" => Ok("yuv422p"),
        "yuv422p10" => Ok("yuv422p10le"),
        "yuv422p12" => Ok("yuv422p12le"),
        "yuv422p16" => Ok("yuv422p16le"),
        "yuv444p8" => Ok("yuv444p"),
        "yuv444p10" => Ok("yuv444p10le"),
        "yuv444p12" => Ok("yuv444p12le"),
        "yuv444p16" => Ok("yuv444p16le"),
        other => Err(PixelFlowError::new(
            ErrorCategory::Format,
            ErrorCode::new("format.unsupported_alias"),
            format!("FFMS2 source cannot output format '{other}'"),
        )),
    }
}

fn ffms2_index_error(message: impl Into<String>) -> PixelFlowError {
    PixelFlowError::new(
        ErrorCategory::Source,
        ErrorCode::new("source.ffms2_index"),
        message,
    )
}

fn ffms2_open_error(message: impl Into<String>) -> PixelFlowError {
    PixelFlowError::new(
        ErrorCategory::Source,
        ErrorCode::new("source.ffms2_open"),
        message,
    )
}

fn ffms2_decode_error(message: impl Into<String>) -> PixelFlowError {
    PixelFlowError::new(
        ErrorCategory::Source,
        ErrorCode::new("source.ffms2_decode"),
        message,
    )
}

#[cfg(test)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct FakeVideoProperties {
    pub width: usize,
    pub height: usize,
    pub frame_count: usize,
    pub frame_rate: Option<Rational>,
    pub variable_timestamps: bool,
}

#[cfg(test)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct FakeIndex {
    path: PathBuf,
}

#[cfg(test)]
#[derive(Clone)]
pub(crate) struct FakeBackend {
    state: Arc<Mutex<FakeBackendState>>,
}

#[cfg(test)]
#[derive(Debug)]
struct FakeBackendState {
    properties: FakeVideoProperties,
    index_count: usize,
    read_index_count: usize,
    indexed_paths: Vec<PathBuf>,
}

#[cfg(test)]
impl FakeBackend {
    pub(crate) fn new(properties: FakeVideoProperties) -> Self {
        Self {
            state: Arc::new(Mutex::new(FakeBackendState {
                properties,
                index_count: 0,
                read_index_count: 0,
                indexed_paths: Vec::new(),
            })),
        }
    }

    pub(crate) fn default_with_cfr() -> Self {
        Self::new(FakeVideoProperties {
            width: 4,
            height: 2,
            frame_count: 2,
            frame_rate: Some(Rational {
                numerator: 24,
                denominator: 1,
            }),
            variable_timestamps: false,
        })
    }

    pub(crate) fn default_with_unknown_rate() -> Self {
        Self::new(FakeVideoProperties {
            width: 4,
            height: 2,
            frame_count: 2,
            frame_rate: None,
            variable_timestamps: false,
        })
    }

    pub(crate) fn default_with_vfr() -> Self {
        Self::new(FakeVideoProperties {
            width: 4,
            height: 2,
            frame_count: 2,
            frame_rate: Some(Rational {
                numerator: 24,
                denominator: 1,
            }),
            variable_timestamps: true,
        })
    }

    pub(crate) fn indexed_paths(&self) -> Vec<PathBuf> {
        self.state
            .lock()
            .expect("state lock poisoned")
            .indexed_paths
            .clone()
    }

    pub(crate) fn index_count(&self) -> usize {
        self.state.lock().expect("state lock poisoned").index_count
    }

    pub(crate) fn read_index_count(&self) -> usize {
        self.state
            .lock()
            .expect("state lock poisoned")
            .read_index_count
    }

    pub(crate) fn reset_counts(&self) {
        let mut state = self.state.lock().expect("state lock poisoned");
        state.index_count = 0;
        state.read_index_count = 0;
        state.indexed_paths.clear();
    }
}

#[cfg(test)]
impl Ffms2Backend for FakeBackend {
    type Index = FakeIndex;
    type Video = FakeVideo;

    fn read_index_from_bytes(&self, bytes: &[u8]) -> Result<Self::Index> {
        let mut state = self.state.lock().expect("state lock poisoned");
        state.read_index_count += 1;
        Ok(FakeIndex {
            path: PathBuf::from(String::from_utf8_lossy(bytes).into_owned()),
        })
    }

    fn write_index_to_bytes(&self, source_path: &Path, _index: &Self::Index) -> Result<Vec<u8>> {
        Ok(source_path.to_string_lossy().as_bytes().to_vec())
    }

    fn index(
        &self,
        source_path: &Path,
        _track: Option<usize>,
        progress: &mut dyn BackendProgress,
    ) -> Result<Self::Index> {
        progress.update(1, 2);
        progress.update(2, 2);

        let mut state = self.state.lock().expect("state lock poisoned");
        state.index_count += 1;
        state.indexed_paths.push(source_path.to_path_buf());
        Ok(FakeIndex {
            path: source_path.to_path_buf(),
        })
    }

    fn open_video(
        &self,
        _source_path: &Path,
        _index: &Self::Index,
        _track: Option<usize>,
        _threads: usize,
        format: &FormatDescriptor,
    ) -> Result<Self::Video> {
        let state = self.state.lock().expect("state lock poisoned");
        Ok(FakeVideo::new(
            VideoProperties {
                width: state.properties.width,
                height: state.properties.height,
                frame_count: state.properties.frame_count,
                frame_rate: state.properties.frame_rate,
                variable_timestamps: state.properties.variable_timestamps,
            },
            build_fake_frames(
                format,
                state.properties.width,
                state.properties.height,
                state.properties.frame_count,
            ),
        ))
    }
}

#[cfg(test)]
pub(crate) struct FakeVideo {
    properties: VideoProperties,
    frames: Vec<DecodedFrame>,
}

#[cfg(test)]
impl FakeVideo {
    pub(crate) fn new(properties: VideoProperties, frames: Vec<DecodedFrame>) -> Self {
        Self { properties, frames }
    }
}

#[cfg(test)]
impl SourceVideo for FakeVideo {
    fn properties(&self) -> VideoProperties {
        self.properties
    }

    fn frame(&mut self, frame_number: usize) -> Result<DecodedFrame> {
        self.frames.get(frame_number).cloned().ok_or_else(|| {
            PixelFlowError::new(
                ErrorCategory::Source,
                ErrorCode::new("source.ffms2_decode"),
                format!("missing fake frame {frame_number}"),
            )
        })
    }
}

#[cfg(test)]
fn build_fake_frames(
    format: &FormatDescriptor,
    width: usize,
    height: usize,
    frame_count: usize,
) -> Vec<DecodedFrame> {
    let mut frames = Vec::with_capacity(frame_count);
    for frame_number in 0..frame_count {
        let planes = format
            .planes()
            .iter()
            .enumerate()
            .map(|(plane_index, descriptor)| {
                let plane_width = width.div_ceil(descriptor.width_divisor);
                let plane_height = height.div_ceil(descriptor.height_divisor);
                let bytes_per_sample = descriptor.sample_type.bytes_per_sample();
                let stride_bytes = plane_width * bytes_per_sample;
                let fill = u8::try_from(frame_number + plane_index).unwrap_or(u8::MAX);
                DecodedPlane {
                    width: plane_width,
                    height: plane_height,
                    stride_bytes,
                    bytes: vec![fill; stride_bytes * plane_height],
                }
            })
            .collect();
        frames.push(DecodedFrame {
            format: format.clone(),
            width,
            height,
            planes,
        });
    }
    frames
}

#[cfg(test)]
#[derive(Default)]
pub(crate) struct NoopProgress;

#[cfg(test)]
impl BackendProgress for NoopProgress {
    fn update(&mut self, _current: usize, _total: usize) {}
}

#[cfg(test)]
mod tests {
    #![expect(clippy::indexing_slicing, reason = "allow in tests")]

    use std::path::Path;

    use pixelflow_core::resolve_format_alias;

    use super::{FakeBackend, FakeVideoProperties, Ffms2Backend, NoopProgress, SourceVideo};

    #[test]
    fn fake_backend_reports_properties_and_mutable_internal_frames() {
        let backend = FakeBackend::new(FakeVideoProperties {
            width: 4,
            height: 2,
            frame_count: 2,
            frame_rate: Some(pixelflow_core::Rational {
                numerator: 24,
                denominator: 1,
            }),
            variable_timestamps: false,
        });

        let index = backend
            .index(Path::new("input.mkv"), None, &mut NoopProgress)
            .expect("index");
        let mut video = backend
            .open_video(
                Path::new("input.mkv"),
                &index,
                None,
                1,
                &resolve_format_alias("gray8").expect("gray8 format"),
            )
            .expect("video");
        let frame = video.frame(0).expect("frame");

        assert_eq!(video.properties().frame_count, 2);
        assert_eq!(frame.width, 4);
        assert_eq!(frame.planes[0].bytes, vec![0; 8]);
    }
}