ff-sys 0.14.1

Low-level FFmpeg FFI bindings for Rust
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
//! SwScale wrapper functions for image scaling and pixel format conversion.
//!
//! This module provides thin wrapper functions around FFmpeg's libswscale API
//! for scaling video frames and converting between pixel formats.
//!
//! # Safety
//!
//! Callers are responsible for:
//! - Ensuring pointers are valid before passing to these functions
//! - Properly freeing resources using the corresponding free functions
//! - Not using pointers after they have been freed
//! - Ensuring source and destination buffers match the expected dimensions and formats

use std::os::raw::c_int;

use crate::{
    AVPixelFormat, SwsContext, ensure_initialized, sws_freeContext as ffi_sws_freeContext,
    sws_getContext as ffi_sws_getContext,
    sws_isSupportedEndiannessConversion as ffi_sws_isSupportedEndiannessConversion,
    sws_isSupportedInput as ffi_sws_isSupportedInput,
    sws_isSupportedOutput as ffi_sws_isSupportedOutput, sws_scale as ffi_sws_scale,
};

// ============================================================================
// Scaling algorithm flags
// ============================================================================

/// Scaling algorithm flags.
///
/// These flags can be combined with bitwise OR to specify the scaling algorithm
/// and additional options for `get_context()`.
pub mod scale_flags {
    // FFmpeg 7.x (libswscale 8.x): SWS_* are #define macros.
    // FFmpeg 8.x (libswscale 9.x): SWS_* are members of the C enum `SwsFlags`.
    // build.rs detects the version and emits `ffmpeg8` for the latter.

    /// Fast bilinear scaling (low quality, fast).
    ///
    /// Uses a simple bilinear interpolation that is faster but produces
    /// lower quality results. Good for real-time preview.
    #[cfg(ffmpeg8)]
    pub const FAST_BILINEAR: i32 = crate::SwsFlags_SWS_FAST_BILINEAR as i32;
    #[cfg(not(ffmpeg8))]
    pub const FAST_BILINEAR: i32 = crate::SWS_FAST_BILINEAR as i32;

    /// Bilinear scaling (medium quality, medium speed).
    ///
    /// Standard bilinear interpolation. Good balance between speed and quality.
    #[cfg(ffmpeg8)]
    pub const BILINEAR: i32 = crate::SwsFlags_SWS_BILINEAR as i32;
    #[cfg(not(ffmpeg8))]
    pub const BILINEAR: i32 = crate::SWS_BILINEAR as i32;

    /// Bicubic scaling (high quality, slower).
    ///
    /// Bicubic interpolation produces smoother results than bilinear,
    /// but is computationally more expensive.
    #[cfg(ffmpeg8)]
    pub const BICUBIC: i32 = crate::SwsFlags_SWS_BICUBIC as i32;
    #[cfg(not(ffmpeg8))]
    pub const BICUBIC: i32 = crate::SWS_BICUBIC as i32;

    /// Experimental algorithm.
    #[cfg(ffmpeg8)]
    pub const X: i32 = crate::SwsFlags_SWS_X as i32;
    #[cfg(not(ffmpeg8))]
    pub const X: i32 = crate::SWS_X as i32;

    /// Nearest neighbor scaling (no interpolation).
    ///
    /// Fastest algorithm but produces blocky results. Useful for pixel art
    /// or when exact pixel values must be preserved.
    #[cfg(ffmpeg8)]
    pub const POINT: i32 = crate::SwsFlags_SWS_POINT as i32;
    #[cfg(not(ffmpeg8))]
    pub const POINT: i32 = crate::SWS_POINT as i32;

    /// Area averaging scaling.
    ///
    /// Good for downscaling. Averages source pixels that map to each
    /// destination pixel.
    #[cfg(ffmpeg8)]
    pub const AREA: i32 = crate::SwsFlags_SWS_AREA as i32;
    #[cfg(not(ffmpeg8))]
    pub const AREA: i32 = crate::SWS_AREA as i32;

    /// Luma bicubic, chroma bilinear.
    ///
    /// Uses bicubic interpolation for luminance and bilinear for chrominance.
    /// Good compromise for video content.
    #[cfg(ffmpeg8)]
    pub const BICUBLIN: i32 = crate::SwsFlags_SWS_BICUBLIN as i32;
    #[cfg(not(ffmpeg8))]
    pub const BICUBLIN: i32 = crate::SWS_BICUBLIN as i32;

    /// Gaussian scaling.
    ///
    /// Uses a Gaussian filter for interpolation.
    #[cfg(ffmpeg8)]
    pub const GAUSS: i32 = crate::SwsFlags_SWS_GAUSS as i32;
    #[cfg(not(ffmpeg8))]
    pub const GAUSS: i32 = crate::SWS_GAUSS as i32;

    /// Sinc scaling.
    ///
    /// Uses a sinc filter. Produces high quality results but is slow.
    #[cfg(ffmpeg8)]
    pub const SINC: i32 = crate::SwsFlags_SWS_SINC as i32;
    #[cfg(not(ffmpeg8))]
    pub const SINC: i32 = crate::SWS_SINC as i32;

    /// Lanczos scaling (high quality).
    ///
    /// Uses a Lanczos windowed sinc filter. Produces very high quality
    /// results, especially for downscaling. Good for final export.
    #[cfg(ffmpeg8)]
    pub const LANCZOS: i32 = crate::SwsFlags_SWS_LANCZOS as i32;
    #[cfg(not(ffmpeg8))]
    pub const LANCZOS: i32 = crate::SWS_LANCZOS as i32;

    /// Spline scaling.
    ///
    /// Uses natural bicubic spline interpolation.
    #[cfg(ffmpeg8)]
    pub const SPLINE: i32 = crate::SwsFlags_SWS_SPLINE as i32;
    #[cfg(not(ffmpeg8))]
    pub const SPLINE: i32 = crate::SWS_SPLINE as i32;
}

// ============================================================================
// Context creation and management
// ============================================================================

/// Create a scaling context for converting and scaling video frames.
///
/// Allocates and returns a `SwsContext` configured for the specified source
/// and destination dimensions and pixel formats.
///
/// # Arguments
///
/// * `src_w` - Source width in pixels
/// * `src_h` - Source height in pixels
/// * `src_fmt` - Source pixel format
/// * `dst_w` - Destination width in pixels
/// * `dst_h` - Destination height in pixels
/// * `dst_fmt` - Destination pixel format
/// * `flags` - Scaling algorithm flags (see `scale_flags` module)
///
/// # Returns
///
/// Returns a pointer to the scaling context on success,
/// or an error code on failure (typically `ENOMEM` or `EINVAL`).
///
/// # Safety
///
/// - The returned context must be freed using `free_context()` when no longer needed.
/// - The context is not thread-safe; use separate contexts for different threads.
///
/// # Errors
///
/// Returns a negative error code if:
/// - Width or height is zero or negative
/// - The pixel format combination is not supported
/// - Memory allocation fails
///
/// # Example
///
/// ```ignore
/// use ff_sys::swscale::{get_context, scale_flags};
/// use ff_sys::AVPixelFormat_AV_PIX_FMT_YUV420P;
/// use ff_sys::AVPixelFormat_AV_PIX_FMT_RGB24;
///
/// unsafe {
///     let ctx = get_context(
///         1920, 1080, AVPixelFormat_AV_PIX_FMT_YUV420P,
///         1280, 720, AVPixelFormat_AV_PIX_FMT_RGB24,
///         scale_flags::LANCZOS,
///     )?;
///     // Use context...
///     free_context(ctx);
/// }
/// ```
pub unsafe fn get_context(
    src_w: c_int,
    src_h: c_int,
    src_fmt: AVPixelFormat,
    dst_w: c_int,
    dst_h: c_int,
    dst_fmt: AVPixelFormat,
    flags: c_int,
) -> Result<*mut SwsContext, c_int> {
    ensure_initialized();

    // Validate dimensions
    if src_w <= 0 || src_h <= 0 || dst_w <= 0 || dst_h <= 0 {
        return Err(crate::error_codes::EINVAL);
    }

    let ctx = ffi_sws_getContext(
        src_w,
        src_h,
        src_fmt,
        dst_w,
        dst_h,
        dst_fmt,
        flags,
        std::ptr::null_mut(), // srcFilter
        std::ptr::null_mut(), // dstFilter
        std::ptr::null(),     // param
    );

    if ctx.is_null() {
        Err(crate::error_codes::ENOMEM)
    } else {
        Ok(ctx)
    }
}

/// Free a scaling context.
///
/// # Arguments
///
/// * `ctx` - The scaling context to free
///
/// # Safety
///
/// - The context must have been allocated by `get_context()`.
/// - The context pointer must not be used after this call.
///
/// # Null Safety
///
/// This function safely handles a null pointer.
pub unsafe fn free_context(ctx: *mut SwsContext) {
    if !ctx.is_null() {
        ffi_sws_freeContext(ctx);
    }
}

// ============================================================================
// Scaling operations
// ============================================================================

/// Scale/convert an image using the given context.
///
/// Converts and scales source image data to the destination format and size.
///
/// # Arguments
///
/// * `ctx` - The scaling context created by `get_context()`
/// * `src` - Array of pointers to source image planes
/// * `src_stride` - Array of source image plane strides (line sizes in bytes)
/// * `src_slice_y` - Y position of the source slice (usually 0)
/// * `src_slice_h` - Height of the source slice (usually source height)
/// * `dst` - Array of pointers to destination image planes
/// * `dst_stride` - Array of destination image plane strides
///
/// # Returns
///
/// Returns the height of the output slice on success,
/// or a negative error code on failure.
///
/// # Safety
///
/// - All pointers must be valid and properly aligned.
/// - Source and destination buffers must be large enough for the configured
///   dimensions and pixel formats.
/// - The context must be valid and configured for the source/destination formats.
///
/// # Errors
///
/// Returns a negative error code if:
/// - Context is null (`error_codes::EINVAL`)
/// - Source or destination pointers are null (`error_codes::EINVAL`)
/// - Scaling fails due to internal error
///
/// # Example
///
/// ```ignore
/// unsafe {
///     let height = scale(
///         ctx,
///         src_data.as_ptr(),
///         src_linesize.as_ptr(),
///         0,          // Start at top
///         src_height, // Process entire image
///         dst_data.as_ptr(),
///         dst_linesize.as_ptr(),
///     )?;
/// }
/// ```
pub unsafe fn scale(
    ctx: *mut SwsContext,
    src: *const *const u8,
    src_stride: *const c_int,
    src_slice_y: c_int,
    src_slice_h: c_int,
    dst: *const *mut u8,
    dst_stride: *const c_int,
) -> Result<c_int, c_int> {
    if ctx.is_null() || src.is_null() || dst.is_null() {
        return Err(crate::error_codes::EINVAL);
    }

    if src_stride.is_null() || dst_stride.is_null() {
        return Err(crate::error_codes::EINVAL);
    }

    let ret = ffi_sws_scale(
        ctx,
        src,
        src_stride,
        src_slice_y,
        src_slice_h,
        dst,
        dst_stride,
    );

    if ret < 0 { Err(ret) } else { Ok(ret) }
}

// ============================================================================
// Format support queries
// ============================================================================

/// Check if a pixel format is supported as input.
///
/// # Arguments
///
/// * `pix_fmt` - The pixel format to check
///
/// # Returns
///
/// Returns `true` if the format can be used as a source format for scaling.
pub unsafe fn is_supported_input(pix_fmt: AVPixelFormat) -> bool {
    ensure_initialized();
    ffi_sws_isSupportedInput(pix_fmt) != 0
}

/// Check if a pixel format is supported as output.
///
/// # Arguments
///
/// * `pix_fmt` - The pixel format to check
///
/// # Returns
///
/// Returns `true` if the format can be used as a destination format for scaling.
pub unsafe fn is_supported_output(pix_fmt: AVPixelFormat) -> bool {
    ensure_initialized();
    ffi_sws_isSupportedOutput(pix_fmt) != 0
}

/// Check if endianness conversion is supported for a pixel format.
///
/// # Arguments
///
/// * `pix_fmt` - The pixel format to check
///
/// # Returns
///
/// Returns `true` if endianness conversion is supported for the format.
pub unsafe fn is_supported_endianness_conversion(pix_fmt: AVPixelFormat) -> bool {
    ensure_initialized();
    ffi_sws_isSupportedEndiannessConversion(pix_fmt) != 0
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        AVPixelFormat_AV_PIX_FMT_RGB24, AVPixelFormat_AV_PIX_FMT_RGBA,
        AVPixelFormat_AV_PIX_FMT_YUV420P,
    };

    #[test]
    fn test_scale_flags_values() {
        // Verify scaling flags are non-zero and distinct
        assert!(scale_flags::FAST_BILINEAR > 0);
        assert!(scale_flags::BILINEAR > 0);
        assert!(scale_flags::BICUBIC > 0);
        assert!(scale_flags::LANCZOS > 0);

        // Common flags should be different values
        assert_ne!(scale_flags::BILINEAR, scale_flags::BICUBIC);
        assert_ne!(scale_flags::BILINEAR, scale_flags::LANCZOS);
        assert_ne!(scale_flags::BICUBIC, scale_flags::LANCZOS);
    }

    #[test]
    fn test_get_context_and_free() {
        unsafe {
            // Create a simple RGB to RGB scaling context
            let ctx_result = get_context(
                640,
                480,
                AVPixelFormat_AV_PIX_FMT_RGB24,
                320,
                240,
                AVPixelFormat_AV_PIX_FMT_RGB24,
                scale_flags::BILINEAR,
            );

            assert!(ctx_result.is_ok(), "Context creation should succeed");

            let ctx = ctx_result.unwrap();
            assert!(!ctx.is_null());

            // Free the context
            free_context(ctx);
        }
    }

    #[test]
    fn test_get_context_yuv_to_rgb() {
        unsafe {
            // Create YUV420P to RGB24 conversion context
            let ctx_result = get_context(
                1920,
                1080,
                AVPixelFormat_AV_PIX_FMT_YUV420P,
                1920,
                1080,
                AVPixelFormat_AV_PIX_FMT_RGB24,
                scale_flags::BICUBIC,
            );

            assert!(ctx_result.is_ok(), "YUV to RGB context should succeed");

            let ctx = ctx_result.unwrap();
            free_context(ctx);
        }
    }

    #[test]
    fn test_get_context_with_lanczos() {
        unsafe {
            // Test with Lanczos scaling (high quality downscale)
            let ctx_result = get_context(
                3840,
                2160,
                AVPixelFormat_AV_PIX_FMT_YUV420P,
                1920,
                1080,
                AVPixelFormat_AV_PIX_FMT_YUV420P,
                scale_flags::LANCZOS,
            );

            assert!(ctx_result.is_ok(), "Lanczos context should succeed");

            let ctx = ctx_result.unwrap();
            free_context(ctx);
        }
    }

    #[test]
    fn test_get_context_invalid_dimensions() {
        unsafe {
            // Zero width should fail
            let result = get_context(
                0,
                480,
                AVPixelFormat_AV_PIX_FMT_RGB24,
                320,
                240,
                AVPixelFormat_AV_PIX_FMT_RGB24,
                scale_flags::BILINEAR,
            );
            assert!(result.is_err());
            assert_eq!(result.unwrap_err(), crate::error_codes::EINVAL);

            // Zero height should fail
            let result = get_context(
                640,
                0,
                AVPixelFormat_AV_PIX_FMT_RGB24,
                320,
                240,
                AVPixelFormat_AV_PIX_FMT_RGB24,
                scale_flags::BILINEAR,
            );
            assert!(result.is_err());
            assert_eq!(result.unwrap_err(), crate::error_codes::EINVAL);

            // Negative dimensions should fail
            let result = get_context(
                -640,
                480,
                AVPixelFormat_AV_PIX_FMT_RGB24,
                320,
                240,
                AVPixelFormat_AV_PIX_FMT_RGB24,
                scale_flags::BILINEAR,
            );
            assert!(result.is_err());
            assert_eq!(result.unwrap_err(), crate::error_codes::EINVAL);
        }
    }

    #[test]
    fn test_free_context_null() {
        // Freeing a null pointer should not crash
        unsafe {
            free_context(std::ptr::null_mut());
        }
    }

    #[test]
    fn test_scale_null_context() {
        unsafe {
            let src: [*const u8; 4] = [std::ptr::null(); 4];
            let dst: [*mut u8; 4] = [std::ptr::null_mut(); 4];
            let src_stride: [c_int; 4] = [0; 4];
            let dst_stride: [c_int; 4] = [0; 4];

            let result = scale(
                std::ptr::null_mut(),
                src.as_ptr(),
                src_stride.as_ptr(),
                0,
                480,
                dst.as_ptr(),
                dst_stride.as_ptr(),
            );

            assert!(result.is_err());
            assert_eq!(result.unwrap_err(), crate::error_codes::EINVAL);
        }
    }

    #[test]
    fn test_scale_null_src() {
        unsafe {
            // Create a valid context first
            let ctx = get_context(
                640,
                480,
                AVPixelFormat_AV_PIX_FMT_RGB24,
                320,
                240,
                AVPixelFormat_AV_PIX_FMT_RGB24,
                scale_flags::BILINEAR,
            )
            .unwrap();

            let dst: [*mut u8; 4] = [std::ptr::null_mut(); 4];
            let dst_stride: [c_int; 4] = [0; 4];

            // Null src pointer should fail
            let result = scale(
                ctx,
                std::ptr::null(),
                std::ptr::null(),
                0,
                480,
                dst.as_ptr(),
                dst_stride.as_ptr(),
            );

            assert!(result.is_err());
            assert_eq!(result.unwrap_err(), crate::error_codes::EINVAL);

            free_context(ctx);
        }
    }

    #[test]
    fn test_scale_null_dst() {
        unsafe {
            let ctx = get_context(
                640,
                480,
                AVPixelFormat_AV_PIX_FMT_RGB24,
                320,
                240,
                AVPixelFormat_AV_PIX_FMT_RGB24,
                scale_flags::BILINEAR,
            )
            .unwrap();

            let src: [*const u8; 4] = [std::ptr::null(); 4];
            let src_stride: [c_int; 4] = [0; 4];

            // Null dst pointer should fail
            let result = scale(
                ctx,
                src.as_ptr(),
                src_stride.as_ptr(),
                0,
                480,
                std::ptr::null(),
                std::ptr::null(),
            );

            assert!(result.is_err());
            assert_eq!(result.unwrap_err(), crate::error_codes::EINVAL);

            free_context(ctx);
        }
    }

    #[test]
    fn test_is_supported_input() {
        unsafe {
            // Common formats should be supported as input
            assert!(
                is_supported_input(AVPixelFormat_AV_PIX_FMT_YUV420P),
                "YUV420P should be supported as input"
            );
            assert!(
                is_supported_input(AVPixelFormat_AV_PIX_FMT_RGB24),
                "RGB24 should be supported as input"
            );
        }
    }

    #[test]
    fn test_is_supported_output() {
        unsafe {
            // Common formats should be supported as output
            assert!(
                is_supported_output(AVPixelFormat_AV_PIX_FMT_YUV420P),
                "YUV420P should be supported as output"
            );
            assert!(
                is_supported_output(AVPixelFormat_AV_PIX_FMT_RGB24),
                "RGB24 should be supported as output"
            );
        }
    }

    #[test]
    fn test_is_supported_endianness_conversion() {
        unsafe {
            // Just verify the function doesn't crash
            // Endianness conversion support varies by format
            let _rgb24 = is_supported_endianness_conversion(AVPixelFormat_AV_PIX_FMT_RGB24);
            let _yuv420p = is_supported_endianness_conversion(AVPixelFormat_AV_PIX_FMT_YUV420P);
        }
    }

    #[test]
    fn test_context_multiple_algorithms() {
        unsafe {
            let algorithms = [
                scale_flags::FAST_BILINEAR,
                scale_flags::BILINEAR,
                scale_flags::BICUBIC,
                scale_flags::POINT,
                scale_flags::AREA,
                scale_flags::LANCZOS,
            ];

            for &algo in &algorithms {
                let ctx_result = get_context(
                    640,
                    480,
                    AVPixelFormat_AV_PIX_FMT_YUV420P,
                    320,
                    240,
                    AVPixelFormat_AV_PIX_FMT_YUV420P,
                    algo,
                );

                assert!(
                    ctx_result.is_ok(),
                    "Algorithm {algo} should create valid context"
                );

                free_context(ctx_result.unwrap());
            }
        }
    }

    // ========================================================================
    // Integration tests with actual image data
    // ========================================================================

    /// Load test image from assets directory.
    /// Returns (width, height, RGBA pixel data).
    fn load_test_image() -> (u32, u32, Vec<u8>) {
        let manifest_dir = env!("CARGO_MANIFEST_DIR");
        let image_path = format!("{}/../../assets/img/hello-triangle.png", manifest_dir);

        let img = image::open(&image_path)
            .unwrap_or_else(|e| panic!("Failed to load test image at {}: {}", image_path, e));
        let rgba = img.to_rgba8();
        let (width, height) = rgba.dimensions();
        (width, height, rgba.into_raw())
    }

    #[test]
    fn test_scale_actual_image_downscale() {
        let (src_width, src_height, src_data) = load_test_image();

        // Downscale to half size
        let dst_width = src_width / 2;
        let dst_height = src_height / 2;

        unsafe {
            let ctx = get_context(
                src_width as c_int,
                src_height as c_int,
                AVPixelFormat_AV_PIX_FMT_RGBA,
                dst_width as c_int,
                dst_height as c_int,
                AVPixelFormat_AV_PIX_FMT_RGBA,
                scale_flags::BILINEAR,
            )
            .unwrap_or_else(|e| panic!("Context creation failed with error code: {}", e));

            // Setup source buffer (RGBA has 1 plane)
            let src_stride: [c_int; 4] = [(src_width * 4) as c_int, 0, 0, 0];
            let src_ptrs: [*const u8; 4] = [
                src_data.as_ptr(),
                std::ptr::null(),
                std::ptr::null(),
                std::ptr::null(),
            ];

            // Allocate destination buffer
            let dst_size = (dst_width * dst_height * 4) as usize;
            let mut dst_data: Vec<u8> = vec![0u8; dst_size];
            let dst_stride: [c_int; 4] = [(dst_width * 4) as c_int, 0, 0, 0];
            let dst_ptrs: [*mut u8; 4] = [
                dst_data.as_mut_ptr(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            ];

            // Perform scaling
            let result = scale(
                ctx,
                src_ptrs.as_ptr(),
                src_stride.as_ptr(),
                0,
                src_height as c_int,
                dst_ptrs.as_ptr(),
                dst_stride.as_ptr(),
            );

            assert!(result.is_ok(), "Scaling should succeed");
            assert_eq!(
                result.unwrap(),
                dst_height as c_int,
                "Should process all output rows"
            );

            // Verify output has non-zero data (image was actually processed)
            let non_zero_count = dst_data.iter().filter(|&&b| b != 0).count();
            assert!(
                non_zero_count > dst_size / 2,
                "Output image should contain significant data"
            );

            free_context(ctx);
        }
    }

    #[test]
    fn test_scale_actual_image_upscale() {
        let (src_width, src_height, src_data) = load_test_image();

        // Upscale by 1.5x
        let dst_width = (src_width as f32 * 1.5) as u32;
        let dst_height = (src_height as f32 * 1.5) as u32;

        unsafe {
            let ctx = get_context(
                src_width as c_int,
                src_height as c_int,
                AVPixelFormat_AV_PIX_FMT_RGBA,
                dst_width as c_int,
                dst_height as c_int,
                AVPixelFormat_AV_PIX_FMT_RGBA,
                scale_flags::LANCZOS,
            )
            .unwrap_or_else(|e| panic!("Context creation failed with error code: {}", e));

            let src_stride: [c_int; 4] = [(src_width * 4) as c_int, 0, 0, 0];
            let src_ptrs: [*const u8; 4] = [
                src_data.as_ptr(),
                std::ptr::null(),
                std::ptr::null(),
                std::ptr::null(),
            ];

            let dst_size = (dst_width * dst_height * 4) as usize;
            let mut dst_data: Vec<u8> = vec![0u8; dst_size];
            let dst_stride: [c_int; 4] = [(dst_width * 4) as c_int, 0, 0, 0];
            let dst_ptrs: [*mut u8; 4] = [
                dst_data.as_mut_ptr(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            ];

            let result = scale(
                ctx,
                src_ptrs.as_ptr(),
                src_stride.as_ptr(),
                0,
                src_height as c_int,
                dst_ptrs.as_ptr(),
                dst_stride.as_ptr(),
            );

            assert!(result.is_ok(), "Upscaling should succeed");
            assert_eq!(
                result.unwrap(),
                dst_height as c_int,
                "Should process all output rows"
            );

            free_context(ctx);
        }
    }

    #[test]
    fn test_scale_rgba_to_rgb24_conversion() {
        let (src_width, src_height, src_data) = load_test_image();

        // Convert RGBA to RGB24 (same dimensions)
        unsafe {
            let ctx = get_context(
                src_width as c_int,
                src_height as c_int,
                AVPixelFormat_AV_PIX_FMT_RGBA,
                src_width as c_int,
                src_height as c_int,
                AVPixelFormat_AV_PIX_FMT_RGB24,
                scale_flags::POINT,
            )
            .unwrap_or_else(|e| panic!("Context creation failed with error code: {}", e));

            let src_stride: [c_int; 4] = [(src_width * 4) as c_int, 0, 0, 0];
            let src_ptrs: [*const u8; 4] = [
                src_data.as_ptr(),
                std::ptr::null(),
                std::ptr::null(),
                std::ptr::null(),
            ];

            // RGB24 uses 3 bytes per pixel
            let dst_size = (src_width * src_height * 3) as usize;
            let mut dst_data: Vec<u8> = vec![0u8; dst_size];
            let dst_stride: [c_int; 4] = [(src_width * 3) as c_int, 0, 0, 0];
            let dst_ptrs: [*mut u8; 4] = [
                dst_data.as_mut_ptr(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            ];

            let result = scale(
                ctx,
                src_ptrs.as_ptr(),
                src_stride.as_ptr(),
                0,
                src_height as c_int,
                dst_ptrs.as_ptr(),
                dst_stride.as_ptr(),
            );

            assert!(result.is_ok(), "Format conversion should succeed");
            assert_eq!(
                result.unwrap(),
                src_height as c_int,
                "Should process all output rows"
            );

            // Verify RGB values match first pixel (ignoring alpha)
            // Source RGBA pixel
            let src_r = src_data[0];
            let src_g = src_data[1];
            let src_b = src_data[2];

            // Destination RGB pixel
            let dst_r = dst_data[0];
            let dst_g = dst_data[1];
            let dst_b = dst_data[2];

            assert_eq!(src_r, dst_r, "Red channel should match");
            assert_eq!(src_g, dst_g, "Green channel should match");
            assert_eq!(src_b, dst_b, "Blue channel should match");

            free_context(ctx);
        }
    }

    #[test]
    fn test_scale_multiple_algorithms_on_image() {
        let (src_width, src_height, src_data) = load_test_image();

        // Use smaller output for faster tests
        let dst_width = 256;
        let dst_height = 256;

        let algorithms = [
            ("FAST_BILINEAR", scale_flags::FAST_BILINEAR),
            ("BILINEAR", scale_flags::BILINEAR),
            ("BICUBIC", scale_flags::BICUBIC),
            ("POINT", scale_flags::POINT),
            ("AREA", scale_flags::AREA),
            ("LANCZOS", scale_flags::LANCZOS),
        ];

        for (name, algo) in algorithms {
            unsafe {
                let ctx = get_context(
                    src_width as c_int,
                    src_height as c_int,
                    AVPixelFormat_AV_PIX_FMT_RGBA,
                    dst_width,
                    dst_height,
                    AVPixelFormat_AV_PIX_FMT_RGBA,
                    algo,
                )
                .unwrap_or_else(|e| panic!("{} context creation failed: {}", name, e));

                let src_stride: [c_int; 4] = [(src_width * 4) as c_int, 0, 0, 0];
                let src_ptrs: [*const u8; 4] = [
                    src_data.as_ptr(),
                    std::ptr::null(),
                    std::ptr::null(),
                    std::ptr::null(),
                ];

                let dst_size = (dst_width * dst_height * 4) as usize;
                let mut dst_data: Vec<u8> = vec![0u8; dst_size];
                let dst_stride: [c_int; 4] = [(dst_width * 4) as c_int, 0, 0, 0];
                let dst_ptrs: [*mut u8; 4] = [
                    dst_data.as_mut_ptr(),
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                ];

                let result = scale(
                    ctx,
                    src_ptrs.as_ptr(),
                    src_stride.as_ptr(),
                    0,
                    src_height as c_int,
                    dst_ptrs.as_ptr(),
                    dst_stride.as_ptr(),
                );

                assert!(result.is_ok(), "{} scaling should succeed", name);
                assert_eq!(
                    result.unwrap(),
                    dst_height,
                    "{} should process all output rows",
                    name
                );

                free_context(ctx);
            }
        }
    }
}