oximedia-codec 0.1.7

Video codec implementations for OxiMedia
Documentation
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
//! FFV1 encoder implementation.
//!
//! Encodes raw video frames into FFV1 lossless bitstreams as specified
//! in RFC 9043. Supports version 3 with range coder and CRC-32 error
//! detection. Supports 8/10/12-bit depth.

use crate::error::{CodecError, CodecResult};
use crate::frame::VideoFrame;
use crate::traits::{EncodedPacket, EncoderConfig, VideoEncoder};
use oximedia_core::CodecId;

use super::crc32::crc32_mpeg2;
use super::prediction::predict_median;
use super::range_coder::SimpleRangeEncoder;
use super::types::{
    Ffv1ChromaType, Ffv1Colorspace, Ffv1Config, Ffv1Version, CONTEXT_COUNT, INITIAL_STATE,
};

/// FFV1 encoder.
///
/// Implements the `VideoEncoder` trait for encoding raw video frames
/// into FFV1 lossless bitstreams. Supports 8/10/12-bit depths.
///
/// # Usage
///
/// ```ignore
/// use oximedia_codec::ffv1::Ffv1Encoder;
/// use oximedia_codec::traits::EncoderConfig;
///
/// let config = EncoderConfig::default();
/// let mut encoder = Ffv1Encoder::new(config)?;
/// encoder.send_frame(&frame)?;
/// if let Some(packet) = encoder.receive_packet()? {
///     // Write packet to container
/// }
/// ```
pub struct Ffv1Encoder {
    /// Base encoder configuration.
    config: EncoderConfig,
    /// FFV1-specific configuration.
    ffv1_config: Ffv1Config,
    /// Output packet queue.
    output_queue: Vec<EncodedPacket>,
    /// Whether the encoder is in flush mode.
    flushing: bool,
    /// Number of encoded frames.
    frame_count: u64,
    /// Per-plane context states for range coder.
    plane_states: Vec<Vec<u8>>,
}

impl Ffv1Encoder {
    /// Create a new FFV1 encoder with default FFV1 settings (8-bit, 4:2:0).
    pub fn new(config: EncoderConfig) -> CodecResult<Self> {
        let ffv1_config = Ffv1Config {
            version: Ffv1Version::V3,
            width: config.width,
            height: config.height,
            colorspace: Ffv1Colorspace::YCbCr,
            chroma_type: Ffv1ChromaType::Chroma420,
            bits_per_raw_sample: 8,
            num_h_slices: 1,
            num_v_slices: 1,
            ec: true,
            range_coder_mode: true,
            state_transition_delta: Vec::new(),
        };
        Self::with_ffv1_config(config, ffv1_config)
    }

    /// Create an FFV1 encoder with explicit FFV1 configuration.
    pub fn with_ffv1_config(config: EncoderConfig, ffv1: Ffv1Config) -> CodecResult<Self> {
        if config.width == 0 || config.height == 0 {
            return Err(CodecError::InvalidParameter(
                "frame dimensions must be nonzero".to_string(),
            ));
        }

        let mut ffv1_config = ffv1;
        ffv1_config.width = config.width;
        ffv1_config.height = config.height;
        ffv1_config.validate()?;

        let plane_count = ffv1_config.plane_count();
        let plane_states: Vec<Vec<u8>> = (0..plane_count)
            .map(|_| vec![INITIAL_STATE; CONTEXT_COUNT])
            .collect();

        Ok(Self {
            config,
            ffv1_config,
            output_queue: Vec::new(),
            flushing: false,
            frame_count: 0,
            plane_states,
        })
    }

    /// Create an FFV1 encoder with explicit bit-depth and default 4:2:0 chroma.
    ///
    /// Validates that `bits` is one of {8, 10, 12, 16}. Frame dimensions are
    /// taken from `config.width` / `config.height`.
    pub fn new_with_bit_depth(config: EncoderConfig, bits: u8) -> CodecResult<Self> {
        let ffv1_config = Ffv1Config {
            version: Ffv1Version::V3,
            width: config.width,
            height: config.height,
            colorspace: Ffv1Colorspace::YCbCr,
            chroma_type: Ffv1ChromaType::Chroma420,
            bits_per_raw_sample: bits,
            num_h_slices: 1,
            num_v_slices: 1,
            ec: true,
            range_coder_mode: true,
            state_transition_delta: Vec::new(),
        };
        Self::with_ffv1_config(config, ffv1_config)
    }

    /// Reset all context states (done at keyframes).
    fn reset_states(&mut self) {
        for states in &mut self.plane_states {
            for s in states.iter_mut() {
                *s = INITIAL_STATE;
            }
        }
    }

    /// Generate the FFV1 extradata (configuration record) for the container.
    ///
    /// This must be stored in the container's codec private data so the
    /// decoder can initialize correctly.
    #[must_use]
    pub fn extradata(&self) -> Vec<u8> {
        let c = &self.ffv1_config;
        let mut data = Vec::with_capacity(16);
        data.push(c.version.as_u8());
        data.push(c.colorspace.as_u8());
        data.push(c.chroma_type.h_shift() as u8);
        data.push(c.chroma_type.v_shift() as u8);
        data.push(c.bits_per_raw_sample);
        data.push(if c.ec { 1 } else { 0 });
        data.push(c.num_h_slices as u8);
        data.push(c.num_v_slices as u8);
        data.extend_from_slice(&c.width.to_le_bytes());
        data.extend_from_slice(&c.height.to_le_bytes());
        data
    }

    /// Read a single sample from a plane's byte buffer, respecting bit depth.
    ///
    /// For 8-bit: reads one byte at `[y * stride + x]`.
    /// For >8-bit: reads two bytes (little-endian) at `[y * stride_bytes + x * 2]`.
    /// `stride` here is the stride in *bytes* (as stored in `Plane::stride`).
    fn read_sample(
        plane_data: &[u8],
        stride: usize,
        y: usize,
        x: usize,
        bps: u8,
    ) -> CodecResult<i32> {
        if bps <= 8 {
            let idx = y * stride + x;
            if idx >= plane_data.len() {
                return Err(CodecError::InvalidBitstream(
                    "plane data too short for 8-bit sample".to_string(),
                ));
            }
            Ok(i32::from(plane_data[idx]))
        } else {
            // stride is in bytes; each sample occupies 2 bytes
            let base = y * stride + x * 2;
            if base + 1 >= plane_data.len() {
                return Err(CodecError::InvalidBitstream(
                    "plane data too short for 16-bit sample".to_string(),
                ));
            }
            let lo = plane_data[base] as i32;
            let hi = plane_data[base + 1] as i32;
            Ok(lo | (hi << 8))
        }
    }

    /// Encode a single frame into a compressed bitstream.
    fn encode_frame(&mut self, frame: &VideoFrame) -> CodecResult<Vec<u8>> {
        // Extract all needed config values upfront to avoid borrow conflicts.
        let plane_count = self.ffv1_config.plane_count();
        let cfg_width = self.ffv1_config.width;
        let cfg_height = self.ffv1_config.height;
        let ec = self.ffv1_config.ec;
        let version = self.ffv1_config.version;
        let bps = self.ffv1_config.bits_per_raw_sample;
        let is_keyframe = self.frame_count % u64::from(self.config.keyint) == 0;

        // Collect plane dimensions
        let plane_dims: Vec<(u32, u32)> = (0..plane_count)
            .map(|i| self.ffv1_config.plane_dimensions(i))
            .collect();

        if is_keyframe {
            self.reset_states();
        }

        // Validate frame dimensions
        if frame.width != cfg_width || frame.height != cfg_height {
            return Err(CodecError::InvalidParameter(format!(
                "frame dimensions {}x{} do not match encoder config {}x{}",
                frame.width, frame.height, cfg_width, cfg_height
            )));
        }

        if frame.planes.len() < plane_count {
            return Err(CodecError::InvalidParameter(format!(
                "frame has {} planes, need at least {}",
                frame.planes.len(),
                plane_count
            )));
        }

        // Encode all planes into a single range-coded bitstream.
        let mut encoder = SimpleRangeEncoder::new();

        for plane_idx in 0..plane_count {
            let (pw, ph) = plane_dims[plane_idx];
            let plane = &frame.planes[plane_idx];
            let stride = plane.stride; // bytes

            let states = &mut self.plane_states[plane_idx];
            let mut prev_line = vec![0i32; pw as usize];

            for y in 0..ph as usize {
                for x in 0..pw as usize {
                    // Read current sample
                    let sample = if y < plane.height as usize && x < plane.width as usize {
                        Self::read_sample(&plane.data, stride, y, x, bps)?
                    } else {
                        0
                    };

                    // Read left neighbor for prediction
                    let left = if x > 0 && y < plane.height as usize && x - 1 < plane.width as usize
                    {
                        Self::read_sample(&plane.data, stride, y, x - 1, bps)?
                    } else {
                        0
                    };

                    let top = prev_line[x];
                    let top_left = if x > 0 { prev_line[x - 1] } else { 0 };

                    let pred = predict_median(left, top, top_left);
                    let residual = sample - pred;

                    encoder.put_symbol(states, residual);
                }

                // Update prev_line with actual samples for next row's prediction
                for x in 0..pw as usize {
                    prev_line[x] = if y < plane.height as usize && x < plane.width as usize {
                        Self::read_sample(&plane.data, stride, y, x, bps).unwrap_or_default()
                    } else {
                        0
                    };
                }
            }
        }

        let mut payload = encoder.finish();

        // Append CRC-32 for v3 with EC enabled
        if ec && version == Ffv1Version::V3 {
            let crc = crc32_mpeg2(&payload);
            payload.extend_from_slice(&crc.to_le_bytes());
        }

        Ok(payload)
    }
}

impl VideoEncoder for Ffv1Encoder {
    fn codec(&self) -> CodecId {
        CodecId::Ffv1
    }

    fn send_frame(&mut self, frame: &VideoFrame) -> CodecResult<()> {
        if self.flushing {
            return Err(CodecError::InvalidParameter(
                "encoder is flushing, cannot accept new frames".to_string(),
            ));
        }

        let pts = frame.timestamp.pts;
        let is_keyframe = self.frame_count % u64::from(self.config.keyint) == 0;

        let data = self.encode_frame(frame)?;

        let packet = EncodedPacket {
            data,
            pts,
            dts: pts,
            keyframe: is_keyframe,
            duration: None,
        };

        self.output_queue.push(packet);
        self.frame_count += 1;
        Ok(())
    }

    fn receive_packet(&mut self) -> CodecResult<Option<EncodedPacket>> {
        if self.output_queue.is_empty() {
            Ok(None)
        } else {
            Ok(Some(self.output_queue.remove(0)))
        }
    }

    fn flush(&mut self) -> CodecResult<()> {
        self.flushing = true;
        Ok(())
    }

    fn config(&self) -> &EncoderConfig {
        &self.config
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::frame::Plane;
    use crate::traits::VideoDecoder;
    use oximedia_core::{PixelFormat, Rational, Timestamp};

    fn make_encoder_config(width: u32, height: u32) -> EncoderConfig {
        EncoderConfig {
            codec: CodecId::Ffv1,
            width,
            height,
            pixel_format: PixelFormat::Yuv420p,
            framerate: Rational::new(30, 1),
            bitrate: crate::traits::BitrateMode::Lossless,
            preset: crate::traits::EncoderPreset::Medium,
            profile: None,
            keyint: 1,
            threads: 1,
            timebase: Rational::new(1, 1000),
        }
    }

    fn make_test_frame(width: u32, height: u32) -> VideoFrame {
        let mut frame = VideoFrame::new(PixelFormat::Yuv420p, width, height);
        frame.timestamp = Timestamp::new(0, Rational::new(1, 1000));

        // Y plane
        let y_size = (width * height) as usize;
        let mut y_data = vec![0u8; y_size];
        for y in 0..height as usize {
            for x in 0..width as usize {
                y_data[y * width as usize + x] = ((x + y) % 256) as u8;
            }
        }
        frame.planes.push(Plane::with_dimensions(
            y_data,
            width as usize,
            width,
            height,
        ));

        // U plane (half resolution for 4:2:0)
        let cw = (width + 1) / 2;
        let ch = (height + 1) / 2;
        let u_data = vec![128u8; (cw * ch) as usize];
        frame
            .planes
            .push(Plane::with_dimensions(u_data, cw as usize, cw, ch));

        // V plane
        let v_data = vec![128u8; (cw * ch) as usize];
        frame
            .planes
            .push(Plane::with_dimensions(v_data, cw as usize, cw, ch));

        frame
    }

    #[test]
    #[ignore]
    fn test_encoder_creation() {
        let config = make_encoder_config(320, 240);
        let enc = Ffv1Encoder::new(config).expect("valid config");
        assert_eq!(enc.codec(), CodecId::Ffv1);
    }

    #[test]
    #[ignore]
    fn test_encoder_invalid_dimensions() {
        let config = make_encoder_config(0, 240);
        assert!(Ffv1Encoder::new(config).is_err());
    }

    #[test]
    #[ignore]
    fn test_encoder_extradata() {
        let config = make_encoder_config(320, 240);
        let enc = Ffv1Encoder::new(config).expect("valid");
        let extra = enc.extradata();
        assert!(extra.len() >= 13);
        assert_eq!(extra[0], 3); // version V3
    }

    #[test]
    #[ignore]
    fn test_encode_single_frame() {
        let config = make_encoder_config(16, 16);
        let mut enc = Ffv1Encoder::new(config).expect("valid");
        let frame = make_test_frame(16, 16);

        enc.send_frame(&frame).expect("encode ok");
        let packet = enc.receive_packet().expect("ok");
        assert!(packet.is_some());
        let pkt = packet.expect("packet");
        assert!(pkt.keyframe);
        assert!(!pkt.data.is_empty());
    }

    #[test]
    #[ignore]
    fn test_encode_wrong_dimensions() {
        let config = make_encoder_config(16, 16);
        let mut enc = Ffv1Encoder::new(config).expect("valid");
        let frame = make_test_frame(32, 32); // wrong size
        assert!(enc.send_frame(&frame).is_err());
    }

    #[test]
    #[ignore]
    fn test_encoder_flush() {
        let config = make_encoder_config(16, 16);
        let mut enc = Ffv1Encoder::new(config).expect("valid");
        enc.flush().expect("flush ok");
        let frame = make_test_frame(16, 16);
        assert!(enc.send_frame(&frame).is_err());
    }

    #[test]
    #[ignore]
    fn test_lossless_roundtrip() {
        // Encode a frame, then decode it, verify pixel-perfect roundtrip
        let width = 16u32;
        let height = 16u32;

        let enc_config = make_encoder_config(width, height);
        let mut encoder = Ffv1Encoder::new(enc_config).expect("enc init");
        let frame = make_test_frame(width, height);

        encoder.send_frame(&frame).expect("encode");
        let packet = encoder.receive_packet().expect("ok").expect("has packet");

        // Now decode
        let extradata = encoder.extradata();
        let mut decoder =
            super::super::decoder::Ffv1Decoder::with_extradata(&extradata).expect("dec init");

        decoder
            .send_packet(&packet.data, packet.pts)
            .expect("decode");
        let decoded_frame = decoder.receive_frame().expect("ok").expect("has frame");

        // Verify lossless: all planes must match exactly
        assert_eq!(decoded_frame.planes.len(), frame.planes.len());
        for (pi, (orig_plane, dec_plane)) in frame
            .planes
            .iter()
            .zip(decoded_frame.planes.iter())
            .enumerate()
        {
            assert_eq!(
                orig_plane.width, dec_plane.width,
                "plane {pi} width mismatch"
            );
            assert_eq!(
                orig_plane.height, dec_plane.height,
                "plane {pi} height mismatch"
            );

            for y in 0..orig_plane.height as usize {
                for x in 0..orig_plane.width as usize {
                    let orig_sample = orig_plane.data[y * orig_plane.stride + x];
                    let dec_sample = dec_plane.data[y * dec_plane.stride + x];
                    assert_eq!(
                        orig_sample, dec_sample,
                        "plane {pi} sample mismatch at ({x}, {y}): orig={orig_sample}, decoded={dec_sample}"
                    );
                }
            }
        }
    }

    #[test]
    #[ignore]
    fn test_lossless_roundtrip_constant_frame() {
        let width = 8u32;
        let height = 8u32;
        let enc_config = make_encoder_config(width, height);
        let mut encoder = Ffv1Encoder::new(enc_config).expect("enc init");

        // Create a constant frame (all 100)
        let mut frame = VideoFrame::new(PixelFormat::Yuv420p, width, height);
        frame.timestamp = Timestamp::new(0, Rational::new(1, 1000));
        let y_data = vec![100u8; (width * height) as usize];
        frame.planes.push(Plane::with_dimensions(
            y_data,
            width as usize,
            width,
            height,
        ));
        let cw = (width + 1) / 2;
        let ch = (height + 1) / 2;
        frame.planes.push(Plane::with_dimensions(
            vec![128u8; (cw * ch) as usize],
            cw as usize,
            cw,
            ch,
        ));
        frame.planes.push(Plane::with_dimensions(
            vec![128u8; (cw * ch) as usize],
            cw as usize,
            cw,
            ch,
        ));

        encoder.send_frame(&frame).expect("encode");
        let packet = encoder.receive_packet().expect("ok").expect("packet");

        let extradata = encoder.extradata();
        let mut decoder =
            super::super::decoder::Ffv1Decoder::with_extradata(&extradata).expect("dec");

        decoder.send_packet(&packet.data, 0).expect("decode");
        let decoded = decoder.receive_frame().expect("ok").expect("frame");

        for (pi, (orig, dec)) in frame.planes.iter().zip(decoded.planes.iter()).enumerate() {
            for y in 0..orig.height as usize {
                for x in 0..orig.width as usize {
                    assert_eq!(
                        orig.data[y * orig.stride + x],
                        dec.data[y * dec.stride + x],
                        "mismatch at plane {pi} ({x}, {y})"
                    );
                }
            }
        }
    }

    #[test]
    #[ignore]
    fn test_lossless_roundtrip_random_pattern() {
        let width = 32u32;
        let height = 32u32;
        let enc_config = make_encoder_config(width, height);
        let mut encoder = Ffv1Encoder::new(enc_config).expect("enc init");

        let mut frame = VideoFrame::new(PixelFormat::Yuv420p, width, height);
        frame.timestamp = Timestamp::new(1000, Rational::new(1, 1000));

        // Create a more complex pattern
        let y_size = (width * height) as usize;
        let mut y_data = vec![0u8; y_size];
        for i in 0..y_size {
            // Pseudo-random but deterministic pattern
            y_data[i] = ((i * 37 + 13) % 256) as u8;
        }
        frame.planes.push(Plane::with_dimensions(
            y_data,
            width as usize,
            width,
            height,
        ));
        let cw = (width + 1) / 2;
        let ch = (height + 1) / 2;
        let uv_size = (cw * ch) as usize;
        let mut u_data = vec![0u8; uv_size];
        let mut v_data = vec![0u8; uv_size];
        for i in 0..uv_size {
            u_data[i] = ((i * 53 + 7) % 256) as u8;
            v_data[i] = ((i * 71 + 23) % 256) as u8;
        }
        frame
            .planes
            .push(Plane::with_dimensions(u_data, cw as usize, cw, ch));
        frame
            .planes
            .push(Plane::with_dimensions(v_data, cw as usize, cw, ch));

        encoder.send_frame(&frame).expect("encode");
        let packet = encoder.receive_packet().expect("ok").expect("packet");

        let extradata = encoder.extradata();
        let mut decoder =
            super::super::decoder::Ffv1Decoder::with_extradata(&extradata).expect("dec");

        decoder.send_packet(&packet.data, 1000).expect("decode");
        let decoded = decoder.receive_frame().expect("ok").expect("frame");

        for (pi, (orig, dec)) in frame.planes.iter().zip(decoded.planes.iter()).enumerate() {
            for y in 0..orig.height as usize {
                for x in 0..orig.width as usize {
                    assert_eq!(
                        orig.data[y * orig.stride + x],
                        dec.data[y * dec.stride + x],
                        "mismatch at plane {pi} ({x}, {y})"
                    );
                }
            }
        }
    }
}