oximedia-scaling 0.1.8

Professional video scaling operations 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
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
#![allow(dead_code)]
//! Content-aware scaling using seam carving for intelligent resizing.
//!
//! Implements seam carving algorithms that can resize images and video frames
//! while preserving visually important content by removing low-energy seams.

use std::fmt;

/// Energy function used to compute pixel importance.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EnergyFunction {
    /// Gradient magnitude (Sobel-like).
    Gradient,
    /// Forward energy (preserves structure better).
    ForwardEnergy,
    /// Entropy-based energy.
    Entropy,
    /// Saliency-based energy from a provided saliency map.
    Saliency,
}

impl fmt::Display for EnergyFunction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Gradient => write!(f, "Gradient"),
            Self::ForwardEnergy => write!(f, "ForwardEnergy"),
            Self::Entropy => write!(f, "Entropy"),
            Self::Saliency => write!(f, "Saliency"),
        }
    }
}

/// Direction of seam removal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SeamDirection {
    /// Vertical seams (reduces width).
    Vertical,
    /// Horizontal seams (reduces height).
    Horizontal,
}

impl fmt::Display for SeamDirection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Vertical => write!(f, "Vertical"),
            Self::Horizontal => write!(f, "Horizontal"),
        }
    }
}

/// Configuration for content-aware scaling.
#[derive(Debug, Clone)]
pub struct ContentAwareConfig {
    /// Energy function to use.
    pub energy_function: EnergyFunction,
    /// Target width (number of pixels).
    pub target_width: u32,
    /// Target height (number of pixels).
    pub target_height: u32,
    /// Whether to protect masked regions from removal.
    pub use_protection_mask: bool,
    /// Whether to remove masked regions preferentially.
    pub use_removal_mask: bool,
    /// Weight for protection mask (higher = stronger protection).
    pub protection_weight: f64,
    /// Maximum seams to remove per pass.
    pub max_seams_per_pass: u32,
}

impl ContentAwareConfig {
    /// Creates a new configuration targeting the given dimensions.
    pub fn new(target_width: u32, target_height: u32) -> Self {
        Self {
            energy_function: EnergyFunction::Gradient,
            target_width,
            target_height,
            use_protection_mask: false,
            use_removal_mask: false,
            protection_weight: 1000.0,
            max_seams_per_pass: 1,
        }
    }

    /// Sets the energy function.
    pub fn with_energy_function(mut self, func: EnergyFunction) -> Self {
        self.energy_function = func;
        self
    }

    /// Enables the protection mask.
    pub fn with_protection_mask(mut self, weight: f64) -> Self {
        self.use_protection_mask = true;
        self.protection_weight = weight;
        self
    }

    /// Enables the removal mask.
    pub fn with_removal_mask(mut self) -> Self {
        self.use_removal_mask = true;
        self
    }
}

/// Represents a single seam (a connected path through the image).
#[derive(Debug, Clone)]
pub struct Seam {
    /// Direction of this seam.
    pub direction: SeamDirection,
    /// The indices along the seam (column indices for vertical, row for horizontal).
    pub indices: Vec<u32>,
    /// Total energy of this seam (lower = less visually important).
    pub total_energy: f64,
}

impl Seam {
    /// Creates a new seam.
    pub fn new(direction: SeamDirection, indices: Vec<u32>, total_energy: f64) -> Self {
        Self {
            direction,
            indices,
            total_energy,
        }
    }

    /// Returns the length of the seam.
    pub fn len(&self) -> usize {
        self.indices.len()
    }

    /// Returns true if the seam has no indices.
    pub fn is_empty(&self) -> bool {
        self.indices.is_empty()
    }
}

/// Simple 2D energy map for seam carving computations.
#[derive(Debug, Clone)]
pub struct EnergyMap {
    /// Width of the energy map.
    width: u32,
    /// Height of the energy map.
    height: u32,
    /// Energy values stored row-major.
    data: Vec<f64>,
}

impl EnergyMap {
    /// Creates a new energy map with zero energy.
    pub fn new(width: u32, height: u32) -> Self {
        Self {
            width,
            height,
            data: vec![0.0; (width as usize) * (height as usize)],
        }
    }

    /// Creates an energy map from raw data.
    pub fn from_data(width: u32, height: u32, data: Vec<f64>) -> Option<Self> {
        if data.len() == (width as usize) * (height as usize) {
            Some(Self {
                width,
                height,
                data,
            })
        } else {
            None
        }
    }

    /// Returns the width.
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Returns the height.
    pub fn height(&self) -> u32 {
        self.height
    }

    /// Gets the energy at a given position.
    pub fn get(&self, x: u32, y: u32) -> f64 {
        if x < self.width && y < self.height {
            self.data[(y as usize) * (self.width as usize) + (x as usize)]
        } else {
            f64::MAX
        }
    }

    /// Sets the energy at a given position.
    pub fn set(&mut self, x: u32, y: u32, energy: f64) {
        if x < self.width && y < self.height {
            self.data[(y as usize) * (self.width as usize) + (x as usize)] = energy;
        }
    }

    /// Returns the minimum energy value in the map.
    pub fn min_energy(&self) -> f64 {
        self.data.iter().cloned().fold(f64::MAX, f64::min)
    }

    /// Returns the maximum energy value in the map.
    pub fn max_energy(&self) -> f64 {
        self.data.iter().cloned().fold(f64::MIN, f64::max)
    }

    /// Returns the average energy value.
    #[allow(clippy::cast_precision_loss)]
    pub fn average_energy(&self) -> f64 {
        if self.data.is_empty() {
            return 0.0;
        }
        self.data.iter().sum::<f64>() / self.data.len() as f64
    }

    /// Computes the cumulative energy map for vertical seam finding (backward energy).
    pub fn compute_cumulative_vertical(&self) -> EnergyMap {
        let mut cumulative = self.clone();
        for y in 1..self.height {
            for x in 0..self.width {
                let up = cumulative.get(x, y - 1);
                let up_left = if x > 0 {
                    cumulative.get(x - 1, y - 1)
                } else {
                    f64::MAX
                };
                let up_right = if x + 1 < self.width {
                    cumulative.get(x + 1, y - 1)
                } else {
                    f64::MAX
                };
                let min_above = up.min(up_left).min(up_right);
                let current = cumulative.get(x, y);
                cumulative.set(x, y, current + min_above);
            }
        }
        cumulative
    }

    /// Computes the cumulative energy map using **forward energy** for vertical seam finding.
    ///
    /// Forward energy (Avidan & Shamir 2007, improved by Rubinstein et al.) measures
    /// the cost of *inserting* an edge after seam removal rather than the cost of the
    /// seam itself. This preserves image structure much better than backward energy,
    /// especially for images with strong edges or gradients.
    ///
    /// The three directional costs at pixel (x, y) are:
    /// - `C_U = |I(x-1, y) - I(x+1, y)|`  (cost of going straight up)
    /// - `C_L = C_U + |I(x, y-1) - I(x-1, y)|`  (cost of going up-left)
    /// - `C_R = C_U + |I(x, y-1) - I(x+1, y)|`  (cost of going up-right)
    ///
    /// `pixels` must be a grayscale buffer matching `self.width × self.height`.
    pub fn compute_cumulative_forward_energy(&self, pixels: &[u8]) -> EnergyMap {
        let w = self.width;
        let h = self.height;
        let mut cumulative = EnergyMap::new(w, h);

        // First row: use backward energy (no row above to compute forward costs).
        for x in 0..w {
            cumulative.set(x, 0, self.get(x, 0));
        }

        let pixel_at = |x: u32, y: u32| -> f64 {
            let idx = (y as usize) * (w as usize) + (x as usize);
            if idx < pixels.len() {
                pixels[idx] as f64
            } else {
                0.0
            }
        };

        for y in 1..h {
            for x in 0..w {
                // Horizontal neighbor difference
                let left_val = if x > 0 {
                    pixel_at(x - 1, y)
                } else {
                    pixel_at(x, y)
                };
                let right_val = if x + 1 < w {
                    pixel_at(x + 1, y)
                } else {
                    pixel_at(x, y)
                };
                let c_u = (left_val - right_val).abs();

                let above_val = pixel_at(x, y - 1);

                // Cost going up (straight)
                let m_up = cumulative.get(x, y - 1);
                let cost_up = if m_up < f64::MAX {
                    m_up + c_u
                } else {
                    f64::MAX
                };

                // Cost going up-left
                let cost_left = if x > 0 {
                    let m_left = cumulative.get(x - 1, y - 1);
                    let c_l = c_u + (above_val - left_val).abs();
                    if m_left < f64::MAX {
                        m_left + c_l
                    } else {
                        f64::MAX
                    }
                } else {
                    f64::MAX
                };

                // Cost going up-right
                let cost_right = if x + 1 < w {
                    let m_right = cumulative.get(x + 1, y - 1);
                    let c_r = c_u + (above_val - right_val).abs();
                    if m_right < f64::MAX {
                        m_right + c_r
                    } else {
                        f64::MAX
                    }
                } else {
                    f64::MAX
                };

                let min_cost = cost_up.min(cost_left).min(cost_right);
                cumulative.set(x, y, min_cost);
            }
        }

        cumulative
    }

    /// Find the minimum-energy vertical seam using forward energy.
    ///
    /// Uses `compute_cumulative_forward_energy` which produces better seams
    /// that preserve edges and gradients in the image.
    pub fn find_vertical_seam_forward(&self, pixels: &[u8]) -> Seam {
        let cumulative = self.compute_cumulative_forward_energy(pixels);

        let mut indices = vec![0u32; self.height as usize];

        // Find minimum in last row
        let last_row = self.height - 1;
        let mut min_x = 0u32;
        let mut min_energy = f64::MAX;
        for x in 0..self.width {
            let e = cumulative.get(x, last_row);
            if e < min_energy {
                min_energy = e;
                min_x = x;
            }
        }
        indices[last_row as usize] = min_x;

        // Trace back
        for y in (0..last_row).rev() {
            let prev_x = indices[(y + 1) as usize];
            let mut best_x = prev_x;
            let mut best_e = cumulative.get(prev_x, y);

            if prev_x > 0 {
                let e = cumulative.get(prev_x - 1, y);
                if e < best_e {
                    best_e = e;
                    best_x = prev_x - 1;
                }
            }
            if prev_x + 1 < self.width {
                let e = cumulative.get(prev_x + 1, y);
                if e < best_e {
                    let _ = best_e;
                    best_x = prev_x + 1;
                }
            }

            indices[y as usize] = best_x;
        }

        Seam::new(SeamDirection::Vertical, indices, min_energy)
    }

    /// Finds the minimum-energy vertical seam using the cumulative map.
    pub fn find_vertical_seam(&self) -> Seam {
        let cumulative = self.compute_cumulative_vertical();
        let mut indices = vec![0u32; self.height as usize];

        // Find minimum in last row
        let last_row = self.height - 1;
        let mut min_x = 0u32;
        let mut min_energy = f64::MAX;
        for x in 0..self.width {
            let e = cumulative.get(x, last_row);
            if e < min_energy {
                min_energy = e;
                min_x = x;
            }
        }
        indices[last_row as usize] = min_x;

        // Trace back
        for y in (0..last_row).rev() {
            let prev_x = indices[(y + 1) as usize];
            let mut best_x = prev_x;
            let mut best_e = cumulative.get(prev_x, y);

            if prev_x > 0 {
                let e = cumulative.get(prev_x - 1, y);
                if e < best_e {
                    best_e = e;
                    best_x = prev_x - 1;
                }
            }
            if prev_x + 1 < self.width {
                let e = cumulative.get(prev_x + 1, y);
                if e < best_e {
                    let _ = best_e;
                    best_x = prev_x + 1;
                }
            }

            indices[y as usize] = best_x;
        }

        Seam::new(SeamDirection::Vertical, indices, min_energy)
    }

    /// Computes gradient energy from pixel brightness values.
    #[allow(clippy::cast_precision_loss)]
    pub fn compute_gradient_energy(pixels: &[u8], width: u32, height: u32) -> Self {
        let mut map = Self::new(width, height);
        for y in 0..height {
            for x in 0..width {
                let idx = (y as usize) * (width as usize) + (x as usize);
                let left = if x > 0 { pixels[idx - 1] } else { pixels[idx] };
                let right = if x + 1 < width {
                    pixels[idx + 1]
                } else {
                    pixels[idx]
                };
                let up = if y > 0 {
                    pixels[idx - width as usize]
                } else {
                    pixels[idx]
                };
                let down = if y + 1 < height {
                    pixels[idx + width as usize]
                } else {
                    pixels[idx]
                };
                let dx = (right as f64) - (left as f64);
                let dy = (down as f64) - (up as f64);
                let energy = (dx * dx + dy * dy).sqrt();
                map.set(x, y, energy);
            }
        }
        map
    }
}

/// Content-aware scaler engine.
#[derive(Debug)]
pub struct ContentAwareScaler {
    /// Configuration.
    config: ContentAwareConfig,
}

impl ContentAwareScaler {
    /// Creates a new content-aware scaler.
    pub fn new(config: ContentAwareConfig) -> Self {
        Self { config }
    }

    /// Returns the configuration.
    pub fn config(&self) -> &ContentAwareConfig {
        &self.config
    }

    /// Computes the number of vertical seams to remove.
    pub fn vertical_seams_to_remove(&self, current_width: u32) -> u32 {
        if current_width > self.config.target_width {
            current_width - self.config.target_width
        } else {
            0
        }
    }

    /// Computes the number of horizontal seams to remove.
    pub fn horizontal_seams_to_remove(&self, current_height: u32) -> u32 {
        if current_height > self.config.target_height {
            current_height - self.config.target_height
        } else {
            0
        }
    }

    /// Performs content-aware scaling on an RGB image.
    ///
    /// The image is provided as packed 3-byte RGB pixels in row-major order.
    /// Vertical seams are removed first (reducing width), then horizontal
    /// seams (reducing height). Returns the resized pixel buffer together
    /// with the final `(width, height)`.
    ///
    /// When `EnergyFunction::ForwardEnergy` is configured, the seam-finding
    /// algorithm uses forward energy which produces better results by
    /// measuring the cost of *inserting* an edge after removal rather than
    /// the cost of the seam pixels themselves.
    ///
    /// If the target dimensions are larger than the source, those axes are
    /// left unchanged (seam carving only shrinks).
    #[allow(clippy::cast_precision_loss)]
    pub fn scale_rgb(&self, pixels: &[u8], width: u32, height: u32) -> Option<(Vec<u8>, u32, u32)> {
        if pixels.len() < (width as usize) * (height as usize) * 3 {
            return None;
        }

        let use_forward = self.config.energy_function == EnergyFunction::ForwardEnergy;

        let mut buf = pixels.to_vec();
        let mut w = width;
        let mut h = height;

        // --- Remove vertical seams (reduce width) ---
        let v_seams = self.vertical_seams_to_remove(w);
        for _ in 0..v_seams {
            let luma = rgb_to_luma(&buf, w, h);
            let energy = EnergyMap::compute_gradient_energy(&luma, w, h);
            let seam = if use_forward {
                energy.find_vertical_seam_forward(&luma)
            } else {
                energy.find_vertical_seam()
            };
            buf = remove_vertical_seam_rgb(&buf, w, h, &seam);
            w -= 1;
        }

        // --- Remove horizontal seams (reduce height) ---
        let h_seams = self.horizontal_seams_to_remove(h);
        for _ in 0..h_seams {
            // Transpose, remove vertical seam, transpose back
            let transposed = transpose_rgb(&buf, w, h);
            let luma = rgb_to_luma(&transposed, h, w);
            let energy = EnergyMap::compute_gradient_energy(&luma, h, w);
            let seam = if use_forward {
                energy.find_vertical_seam_forward(&luma)
            } else {
                energy.find_vertical_seam()
            };
            let carved = remove_vertical_seam_rgb(&transposed, h, w, &seam);
            h -= 1;
            buf = transpose_rgb(&carved, h, w);
        }

        Some((buf, w, h))
    }
}

/// Convert packed RGB buffer to single-channel luma (BT.709 weights).
#[allow(
    clippy::cast_precision_loss,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss
)]
fn rgb_to_luma(pixels: &[u8], width: u32, height: u32) -> Vec<u8> {
    let count = (width as usize) * (height as usize);
    let mut luma = vec![0u8; count];
    for i in 0..count {
        let base = i * 3;
        if base + 2 < pixels.len() {
            let r = pixels[base] as f32;
            let g = pixels[base + 1] as f32;
            let b = pixels[base + 2] as f32;
            // BT.709 luma
            luma[i] = (0.2126 * r + 0.7152 * g + 0.0722 * b)
                .round()
                .clamp(0.0, 255.0) as u8;
        }
    }
    luma
}

/// Remove a single vertical seam from a packed RGB buffer.
///
/// The seam indices give the column to remove at each row.
/// Returns a buffer whose width is `width - 1`.
fn remove_vertical_seam_rgb(pixels: &[u8], width: u32, height: u32, seam: &Seam) -> Vec<u8> {
    let w = width as usize;
    let new_w = w - 1;
    let h = height as usize;
    let mut out = Vec::with_capacity(new_w * h * 3);

    for y in 0..h {
        let seam_x = if y < seam.indices.len() {
            seam.indices[y] as usize
        } else {
            w // skip nothing
        };
        for x in 0..w {
            if x == seam_x {
                continue;
            }
            let base = (y * w + x) * 3;
            if base + 2 < pixels.len() {
                out.push(pixels[base]);
                out.push(pixels[base + 1]);
                out.push(pixels[base + 2]);
            }
        }
    }

    out
}

/// Transpose a packed RGB image (swap width and height).
fn transpose_rgb(pixels: &[u8], width: u32, height: u32) -> Vec<u8> {
    let w = width as usize;
    let h = height as usize;
    let mut out = vec![0u8; w * h * 3];

    for y in 0..h {
        for x in 0..w {
            let src_base = (y * w + x) * 3;
            let dst_base = (x * h + y) * 3;
            if src_base + 2 < pixels.len() && dst_base + 2 < out.len() {
                out[dst_base] = pixels[src_base];
                out[dst_base + 1] = pixels[src_base + 1];
                out[dst_base + 2] = pixels[src_base + 2];
            }
        }
    }

    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_energy_function_display() {
        assert_eq!(EnergyFunction::Gradient.to_string(), "Gradient");
        assert_eq!(EnergyFunction::ForwardEnergy.to_string(), "ForwardEnergy");
        assert_eq!(EnergyFunction::Entropy.to_string(), "Entropy");
        assert_eq!(EnergyFunction::Saliency.to_string(), "Saliency");
    }

    #[test]
    fn test_seam_direction_display() {
        assert_eq!(SeamDirection::Vertical.to_string(), "Vertical");
        assert_eq!(SeamDirection::Horizontal.to_string(), "Horizontal");
    }

    #[test]
    fn test_config_builder() {
        let config = ContentAwareConfig::new(640, 480)
            .with_energy_function(EnergyFunction::ForwardEnergy)
            .with_protection_mask(500.0)
            .with_removal_mask();
        assert_eq!(config.target_width, 640);
        assert_eq!(config.target_height, 480);
        assert_eq!(config.energy_function, EnergyFunction::ForwardEnergy);
        assert!(config.use_protection_mask);
        assert!(config.use_removal_mask);
        assert!((config.protection_weight - 500.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_seam_new() {
        let seam = Seam::new(SeamDirection::Vertical, vec![1, 2, 1, 0], 10.5);
        assert_eq!(seam.direction, SeamDirection::Vertical);
        assert_eq!(seam.len(), 4);
        assert!(!seam.is_empty());
        assert!((seam.total_energy - 10.5).abs() < f64::EPSILON);
    }

    #[test]
    fn test_seam_empty() {
        let seam = Seam::new(SeamDirection::Horizontal, vec![], 0.0);
        assert!(seam.is_empty());
        assert_eq!(seam.len(), 0);
    }

    #[test]
    fn test_energy_map_new() {
        let map = EnergyMap::new(4, 3);
        assert_eq!(map.width(), 4);
        assert_eq!(map.height(), 3);
        assert!((map.get(0, 0)).abs() < f64::EPSILON);
    }

    #[test]
    fn test_energy_map_set_get() {
        let mut map = EnergyMap::new(3, 3);
        map.set(1, 2, 42.5);
        assert!((map.get(1, 2) - 42.5).abs() < f64::EPSILON);
    }

    #[test]
    fn test_energy_map_out_of_bounds() {
        let map = EnergyMap::new(2, 2);
        assert_eq!(map.get(5, 5), f64::MAX);
    }

    #[test]
    fn test_energy_map_from_data() {
        let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
        let map = EnergyMap::from_data(3, 2, data).expect("should succeed in test");
        assert!((map.get(2, 1) - 6.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_energy_map_from_data_invalid() {
        let data = vec![1.0, 2.0];
        assert!(EnergyMap::from_data(3, 2, data).is_none());
    }

    #[test]
    fn test_energy_map_statistics() {
        let data = vec![1.0, 5.0, 3.0, 7.0];
        let map = EnergyMap::from_data(2, 2, data).expect("should succeed in test");
        assert!((map.min_energy() - 1.0).abs() < f64::EPSILON);
        assert!((map.max_energy() - 7.0).abs() < f64::EPSILON);
        assert!((map.average_energy() - 4.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_find_vertical_seam() {
        // 3x3 energy map where center column has lowest energy
        let data = vec![10.0, 1.0, 10.0, 10.0, 1.0, 10.0, 10.0, 1.0, 10.0];
        let map = EnergyMap::from_data(3, 3, data).expect("should succeed in test");
        let seam = map.find_vertical_seam();
        assert_eq!(seam.direction, SeamDirection::Vertical);
        assert_eq!(seam.len(), 3);
        // The seam should go through column 1 (lowest energy)
        for &idx in &seam.indices {
            assert_eq!(idx, 1);
        }
    }

    #[test]
    fn test_compute_gradient_energy() {
        let pixels = vec![10, 20, 30, 40, 50, 60, 70, 80, 90];
        let map = EnergyMap::compute_gradient_energy(&pixels, 3, 3);
        assert_eq!(map.width(), 3);
        assert_eq!(map.height(), 3);
        // Center pixel should have non-zero energy
        assert!(map.get(1, 1) > 0.0);
    }

    #[test]
    fn test_content_aware_scaler_seam_counts() {
        let config = ContentAwareConfig::new(640, 360);
        let scaler = ContentAwareScaler::new(config);
        assert_eq!(scaler.vertical_seams_to_remove(800), 160);
        assert_eq!(scaler.horizontal_seams_to_remove(480), 120);
        assert_eq!(scaler.vertical_seams_to_remove(320), 0);
        assert_eq!(scaler.horizontal_seams_to_remove(200), 0);
    }

    #[test]
    fn test_rgb_to_luma_basic() {
        // Pure white pixel
        let pixels = vec![255u8, 255, 255, 0, 0, 0];
        let luma = rgb_to_luma(&pixels, 2, 1);
        assert_eq!(luma.len(), 2);
        assert!(luma[0] > 250); // white -> high luma
        assert_eq!(luma[1], 0); // black -> 0 luma
    }

    #[test]
    fn test_remove_vertical_seam_rgb() {
        // 3x2 image with known pixels
        let pixels = vec![
            10, 20, 30, 40, 50, 60, 70, 80, 90, // row 0: 3 pixels
            100, 110, 120, 130, 140, 150, 160, 170, 180, // row 1: 3 pixels
        ];
        let seam = Seam::new(SeamDirection::Vertical, vec![1, 1], 0.0);
        let result = remove_vertical_seam_rgb(&pixels, 3, 2, &seam);
        // Should remove column 1 from each row -> 2x2 image
        assert_eq!(result.len(), 2 * 2 * 3);
        // Row 0: pixel 0 and pixel 2
        assert_eq!(&result[0..3], &[10, 20, 30]);
        assert_eq!(&result[3..6], &[70, 80, 90]);
        // Row 1: pixel 0 and pixel 2
        assert_eq!(&result[6..9], &[100, 110, 120]);
        assert_eq!(&result[9..12], &[160, 170, 180]);
    }

    #[test]
    fn test_transpose_rgb_roundtrip() {
        let pixels = vec![
            1, 2, 3, 4, 5, 6, // row 0
            7, 8, 9, 10, 11, 12, // row 1
            13, 14, 15, 16, 17, 18, // row 2
        ];
        let transposed = transpose_rgb(&pixels, 2, 3);
        // transposed dimensions: width=3, height=2
        let back = transpose_rgb(&transposed, 3, 2);
        assert_eq!(pixels, back);
    }

    #[test]
    fn test_scale_rgb_reduces_width() {
        // 4x4 uniform grey image
        let pixels = vec![128u8; 4 * 4 * 3];
        let config = ContentAwareConfig::new(2, 4);
        let scaler = ContentAwareScaler::new(config);
        let result = scaler.scale_rgb(&pixels, 4, 4);
        assert!(result.is_some());
        let (buf, w, h) = result.expect("should succeed");
        assert_eq!(w, 2);
        assert_eq!(h, 4);
        assert_eq!(buf.len(), (w as usize) * (h as usize) * 3);
    }

    #[test]
    fn test_scale_rgb_reduces_height() {
        let pixels = vec![128u8; 4 * 4 * 3];
        let config = ContentAwareConfig::new(4, 2);
        let scaler = ContentAwareScaler::new(config);
        let result = scaler.scale_rgb(&pixels, 4, 4);
        assert!(result.is_some());
        let (buf, w, h) = result.expect("should succeed");
        assert_eq!(w, 4);
        assert_eq!(h, 2);
        assert_eq!(buf.len(), (w as usize) * (h as usize) * 3);
    }

    #[test]
    fn test_scale_rgb_invalid_input() {
        let config = ContentAwareConfig::new(2, 2);
        let scaler = ContentAwareScaler::new(config);
        // Buffer too small
        assert!(scaler.scale_rgb(&[0u8; 5], 4, 4).is_none());
    }

    #[test]
    fn test_scale_rgb_no_change_when_target_larger() {
        let pixels = vec![128u8; 4 * 4 * 3];
        let config = ContentAwareConfig::new(8, 8); // larger than source
        let scaler = ContentAwareScaler::new(config);
        let result = scaler.scale_rgb(&pixels, 4, 4);
        assert!(result.is_some());
        let (buf, w, h) = result.expect("should succeed");
        assert_eq!(w, 4);
        assert_eq!(h, 4);
        assert_eq!(buf.len(), pixels.len());
    }

    // ── Forward energy tests ────────────────────────────────────────────────

    #[test]
    fn test_forward_energy_cumulative_basic() {
        // 3x3 uniform image: forward energy should produce low-cost seams
        let pixels = vec![128u8; 9];
        let energy = EnergyMap::compute_gradient_energy(&pixels, 3, 3);
        let cumulative = energy.compute_cumulative_forward_energy(&pixels);
        // All energies should be finite
        for y in 0..3 {
            for x in 0..3 {
                assert!(
                    cumulative.get(x, y) < f64::MAX,
                    "cumulative({x},{y}) should be finite"
                );
            }
        }
    }

    #[test]
    fn test_forward_energy_seam_finds_low_cost_path() {
        // Image with a clear vertical stripe of low energy in center
        let mut pixels = vec![200u8; 5 * 5];
        for y in 0..5 {
            pixels[y * 5 + 2] = 0; // center column has distinct value
        }
        let energy = EnergyMap::compute_gradient_energy(&pixels, 5, 5);
        let seam = energy.find_vertical_seam_forward(&pixels);
        assert_eq!(seam.len(), 5);
        assert_eq!(seam.direction, SeamDirection::Vertical);
        // Seam should stay near the center (column 2) where gradient contrast is
        for &idx in &seam.indices {
            assert!(
                (idx as i32 - 2).unsigned_abs() <= 2,
                "seam index {idx} too far from center"
            );
        }
    }

    #[test]
    fn test_forward_energy_seam_has_valid_connectivity() {
        // Seam indices should differ by at most 1 between adjacent rows
        let pixels: Vec<u8> = (0..36).map(|i| (i * 7) as u8).collect();
        let energy = EnergyMap::compute_gradient_energy(&pixels, 6, 6);
        let seam = energy.find_vertical_seam_forward(&pixels);
        for pair in seam.indices.windows(2) {
            let diff = (pair[0] as i32 - pair[1] as i32).unsigned_abs();
            assert!(
                diff <= 1,
                "seam connectivity violation: {} -> {}",
                pair[0],
                pair[1]
            );
        }
    }

    #[test]
    fn test_scale_rgb_forward_energy_reduces_width() {
        let pixels = vec![128u8; 6 * 4 * 3];
        let config =
            ContentAwareConfig::new(4, 4).with_energy_function(EnergyFunction::ForwardEnergy);
        let scaler = ContentAwareScaler::new(config);
        let result = scaler.scale_rgb(&pixels, 6, 4);
        assert!(result.is_some());
        let (buf, w, h) = result.expect("forward energy scale should succeed");
        assert_eq!(w, 4);
        assert_eq!(h, 4);
        assert_eq!(buf.len(), 4 * 4 * 3);
    }

    #[test]
    fn test_scale_rgb_forward_energy_reduces_height() {
        let pixels = vec![128u8; 4 * 6 * 3];
        let config =
            ContentAwareConfig::new(4, 4).with_energy_function(EnergyFunction::ForwardEnergy);
        let scaler = ContentAwareScaler::new(config);
        let result = scaler.scale_rgb(&pixels, 4, 6);
        assert!(result.is_some());
        let (buf, w, h) = result.expect("forward energy scale should succeed");
        assert_eq!(w, 4);
        assert_eq!(h, 4);
        assert_eq!(buf.len(), 4 * 4 * 3);
    }

    #[test]
    fn test_scale_rgb_forward_energy_both_axes() {
        let pixels = vec![100u8; 6 * 6 * 3];
        let config =
            ContentAwareConfig::new(4, 4).with_energy_function(EnergyFunction::ForwardEnergy);
        let scaler = ContentAwareScaler::new(config);
        let result = scaler.scale_rgb(&pixels, 6, 6);
        assert!(result.is_some());
        let (buf, w, h) = result.expect("should succeed");
        assert_eq!(w, 4);
        assert_eq!(h, 4);
        assert_eq!(buf.len(), 4 * 4 * 3);
    }

    #[test]
    fn test_forward_vs_backward_energy_different_seams() {
        // With a structured image, forward and backward energy may find different seams
        let mut pixels = vec![128u8; 8 * 8];
        // Create a diagonal gradient
        for y in 0..8u32 {
            for x in 0..8u32 {
                pixels[(y as usize) * 8 + (x as usize)] =
                    ((x as f64 + y as f64) / 14.0 * 255.0) as u8;
            }
        }
        let energy = EnergyMap::compute_gradient_energy(&pixels, 8, 8);
        let backward_seam = energy.find_vertical_seam();
        let forward_seam = energy.find_vertical_seam_forward(&pixels);

        // Both should be valid seams of length 8
        assert_eq!(backward_seam.len(), 8);
        assert_eq!(forward_seam.len(), 8);
        // Energy values should be finite and positive
        assert!(backward_seam.total_energy > 0.0);
        assert!(forward_seam.total_energy > 0.0);
    }

    #[test]
    fn test_forward_energy_edge_preservation() {
        // Image with a strong vertical edge: forward energy should avoid cutting through it
        let mut pixels = vec![0u8; 8 * 4];
        for y in 0..4u32 {
            for x in 4..8u32 {
                pixels[(y as usize) * 8 + (x as usize)] = 255;
            }
        }
        let energy = EnergyMap::compute_gradient_energy(&pixels, 8, 4);
        let seam = energy.find_vertical_seam_forward(&pixels);
        assert_eq!(seam.len(), 4);
        // The seam should avoid the strong edge at column 3-4
        // It should tend toward the uniform regions (columns 0-2 or 5-7)
        let avg_col: f64 = seam.indices.iter().map(|&x| x as f64).sum::<f64>() / seam.len() as f64;
        // Should not be exactly at the edge (columns 3 or 4)
        assert!(
            avg_col < 3.5 || avg_col > 4.5,
            "forward energy seam at avg column {avg_col} should avoid the edge at 3-4"
        );
    }
}