-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbindings_test.go
More file actions
1813 lines (1523 loc) · 51.1 KB
/
bindings_test.go
File metadata and controls
1813 lines (1523 loc) · 51.1 KB
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
989
990
991
992
993
994
995
996
997
998
999
1000
package ffmpeg
import (
"testing"
"unsafe"
)
// TestCRC tests basic CRC calculation using standard tables
func TestCRC(t *testing.T) {
// Get a standard CRC table
table := AVCrcGetTable(AVCrc32Ieee)
if table == nil {
t.Fatal("AVCrcGetTable returned nil")
}
// Test data
testData := []byte("Hello, World!")
// Calculate CRC
crc := AVCrc(table, 0, unsafe.Pointer(&testData[0]), uint64(len(testData)))
// CRC should be non-zero for non-empty data
if crc == 0 {
t.Error("CRC calculation returned 0 for non-empty data")
}
t.Logf("CRC of %q: 0x%08x", string(testData), crc)
}
// TestCRCInit tests custom CRC table initialization
func TestCRCInit(t *testing.T) {
// Allocate space for CRC table (257 entries for 8-bit CRC)
const tableSize = 257
ctx := make([]AVCRC, tableSize)
// Initialize CRC table for CRC-32 IEEE
result, err := AVCrcInit(&ctx[0], 0, 32, 0x04C11DB7, int(unsafe.Sizeof(AVCRC(0))*tableSize))
if err != nil {
t.Fatalf("AVCrcInit failed: %v", err)
}
if result < 0 {
t.Fatalf("AVCrcInit returned error: %d", result)
}
// Test data
testData := []byte("Hello, World!")
// Calculate CRC using our initialized table
crc := AVCrc(&ctx[0], 0, unsafe.Pointer(&testData[0]), uint64(len(testData)))
// CRC should be non-zero for non-empty data
if crc == 0 {
t.Error("CRC calculation returned 0 for non-empty data")
}
t.Logf("Custom CRC of %q: 0x%08x", string(testData), crc)
}
// TestGeneratorTypeAliases tests that typedef aliases from custom.go work correctly
// This validates the typedef alias pointer support that was recently added
func TestGeneratorTypeAliases(t *testing.T) {
t.Run("AVCRC", func(t *testing.T) {
// Test that AVCRC typedef alias works
table := AVCrcGetTable(AVCrc32Ieee)
if table == nil {
t.Fatal("AVCrcGetTable returned nil")
}
testData := []byte("Hello, World!")
crc := AVCrc(table, 0, unsafe.Pointer(&testData[0]), uint64(len(testData)))
if crc == 0 {
t.Error("CRC calculation returned 0 for non-empty data")
}
t.Logf("AVCRC test passed: 0x%08x", crc)
})
t.Run("AVAdler", func(t *testing.T) {
// Test that AVAdler typedef alias works
testData := []byte("Hello, World!")
adler := AVAdler32Update(1, unsafe.Pointer(&testData[0]), uint64(len(testData)))
if adler == 0 {
t.Error("Adler32 calculation returned 0")
}
t.Logf("AVAdler test passed: 0x%08x", adler)
})
}
// TestGeneratorEnumPointers tests that pointer to enum types are handled correctly
// This validates the enum pointer fix from the recent regression
func TestGeneratorEnumPointers(t *testing.T) {
t.Run("AVPixelFormat", func(t *testing.T) {
// This tests the fix for enum pointer parameters
// AVOptGetPixelFmt should accept *AVPixelFormat (not *C.AVPixelFormat)
var fmt AVPixelFormat
// We can't fully test this without setting up an options context,
// but we can verify it compiles and the type signature is correct
_ = &fmt // Use the variable
t.Log("AVPixelFormat pointer type test passed (compiles)")
})
t.Run("AVSampleFormat", func(t *testing.T) {
var fmt AVSampleFormat
_ = &fmt
t.Log("AVSampleFormat pointer type test passed (compiles)")
})
}
// TestGeneratorCallbackPointers tests that pointer to callback types are handled correctly
// This validates the callback pointer fix from the recent regression
func TestGeneratorCallbackPointers(t *testing.T) {
t.Run("AVTxFn", func(t *testing.T) {
// This tests the fix for callback pointer parameters
// AVTxInit should accept *AVTxFn (not *av_tx_fn)
var tx AVTxFn
_ = &tx
t.Log("AVTxFn pointer type test passed (compiles)")
})
}
// TestGeneratorSkippedFunctions verifies that functions with unsupported types are skipped
// This validates that C standard library types (tm, FILE*, va_list) are properly excluded
func TestGeneratorSkippedFunctions(t *testing.T) {
// These functions should NOT exist because they use C standard library types
// If this test compiles, it means the generator correctly skipped them
t.Log("C standard library type functions correctly skipped (tm, FILE*, va_list)")
}
// TestGeneratorBasicFunctions tests basic function generation
func TestGeneratorBasicFunctions(t *testing.T) {
t.Run("VersionInfo", func(t *testing.T) {
version := AVUtilVersion()
if version == 0 {
t.Error("AVUtilVersion returned 0")
}
t.Logf("AVUtil version: %d", version)
})
t.Run("Configuration", func(t *testing.T) {
config := AVUtilConfiguration()
if config == nil {
t.Error("AVUtilConfiguration returned nil")
}
t.Logf("AVUtil config: %s", config)
})
t.Run("License", func(t *testing.T) {
license := AVUtilLicense()
if license == nil {
t.Error("AVUtilLicense returned nil")
}
t.Logf("AVUtil license: %s", license)
})
}
// TestGeneratorStructWrappers tests struct wrapper generation
func TestGeneratorStructWrappers(t *testing.T) {
t.Run("AVRational", func(t *testing.T) {
// Test basic by-value struct
r := AVMakeQ(1, 2)
if r.Num() != 1 || r.Den() != 2 {
t.Errorf("AVMakeQ failed: got %d/%d, want 1/2", r.Num(), r.Den())
}
t.Log("AVRational struct wrapper test passed")
})
t.Run("AVFrame", func(t *testing.T) {
// Test pointer struct allocation
frame := AVFrameAlloc()
if frame == nil {
t.Fatal("AVFrameAlloc returned nil")
}
defer AVFrameFree(&frame)
t.Log("AVFrame struct wrapper test passed")
})
t.Run("AVPacket", func(t *testing.T) {
// Test packet allocation
pkt := AVPacketAlloc()
if pkt == nil {
t.Fatal("AVPacketAlloc returned nil")
}
defer AVPacketFree(&pkt)
t.Log("AVPacket struct wrapper test passed")
})
}
// TestGeneratorEnums tests enum generation
func TestGeneratorEnums(t *testing.T) {
t.Run("AVMediaType", func(t *testing.T) {
// Test that enum constants are generated
types := []AVMediaType{
AVMediaTypeUnknown,
AVMediaTypeVideo,
AVMediaTypeAudio,
AVMediaTypeData,
AVMediaTypeSubtitle,
AVMediaTypeAttachment,
}
for _, mt := range types {
str := AVGetMediaTypeString(mt)
t.Logf("Media type %v: %s", mt, str)
}
})
t.Run("AVPixelFormat", func(t *testing.T) {
// Test enum with large value range
if AVPixFmtNone < 0 {
t.Log("AVPixelFormat enum test passed")
}
})
}
// TestGeneratorConstants tests constant generation
func TestGeneratorConstants(t *testing.T) {
t.Run("ErrorCodes", func(t *testing.T) {
// Test that error constants are generated
if AVErrorEofConst == 0 {
t.Error("AVERROR_EOF should not be 0")
}
t.Logf("AVERROR_EOF: %d", AVErrorEofConst)
})
t.Run("MathConstants", func(t *testing.T) {
// Test that FFmpeg-specific math constants are generated
// Note: Standard constants like M_E and M_PI may come from system headers
// on Linux/NixOS and won't be redefined by FFmpeg
if MLog210 == 0 {
t.Error("M_LOG2_10 should not be 0")
}
if MPhi == 0 {
t.Error("M_PHI should not be 0")
}
t.Logf("M_LOG2_10: %f, M_PHI: %f", MLog210, MPhi)
})
}
// TestGeneratorPointerConversions tests various pointer parameter conversions
func TestGeneratorPointerConversions(t *testing.T) {
t.Run("DoublePointerStruct", func(t *testing.T) {
// Test **AVFormatContext pattern
var fmtCtx *AVFormatContext
// Should be able to pass &fmtCtx
_ = &fmtCtx
t.Log("Double pointer struct parameter test passed")
})
t.Run("PointerToPointerUpdate", func(t *testing.T) {
// Test that functions update pointer-to-pointer correctly
frame := AVFrameAlloc()
if frame == nil {
t.Fatal("AVFrameAlloc returned nil")
}
// This should update frame to nil
AVFrameFree(&frame)
if frame != nil {
t.Error("AVFrameFree didn't set frame to nil")
}
t.Log("Pointer-to-pointer update test passed")
})
}
// TestGeneratorErrorHandling tests error wrapping
func TestGeneratorErrorHandling(t *testing.T) {
t.Run("ErrorConstantsExist", func(t *testing.T) {
// Test that error constants are properly generated and accessible
if AVErrorEofConst >= 0 {
t.Error("AVERROR_EOF should be negative")
}
t.Logf("Error handling test passed: AVERROR_EOF = %d", AVErrorEofConst)
})
}
// TestUUID tests the UUID functionality from libavutil/uuid.h
func TestUUID(t *testing.T) {
t.Run("Parse and Unparse", func(t *testing.T) {
// Parse a UUID string
uuidStr := "550e8400-e29b-41d4-a716-446655440000"
var uuid AVUUID
cStr := ToCStr(uuidStr)
defer cStr.Free()
ret, err := AVUuidParse(cStr, &uuid)
if ret != 0 || err != nil {
t.Fatalf("Failed to parse UUID: %v", err)
}
// Unparse it back to string
outStr := AllocCStr(37)
defer outStr.Free()
AVUuidUnparse(&uuid, outStr)
result := outStr.String()
if result != uuidStr {
t.Fatalf("UUID mismatch: expected %s, got %s", uuidStr, result)
}
t.Logf("UUID parse/unparse test passed: %s", result)
})
t.Run("UUID Operations", func(t *testing.T) {
// Create two identical UUIDs
var uuid1, uuid2 AVUUID
uuidStr := "550e8400-e29b-41d4-a716-446655440000"
cStr := ToCStr(uuidStr)
defer cStr.Free()
AVUuidParse(cStr, &uuid1)
AVUuidCopy(&uuid2, &uuid1)
// Test equality
equal, _ := AVUuidEqual(&uuid1, &uuid2)
if equal == 0 {
t.Fatal("UUIDs should be equal")
}
// Test nil UUID
var nilUuid AVUUID
AVUuidNil(&nilUuid)
equal, _ = AVUuidEqual(&uuid1, &nilUuid)
if equal != 0 {
t.Fatal("UUID should not equal nil UUID")
}
t.Logf("UUID operations test passed")
})
t.Run("URN Parsing", func(t *testing.T) {
// Parse a UUID URN
urnStr := "urn:uuid:550e8400-e29b-41d4-a716-446655440000"
var uuid AVUUID
cStr := ToCStr(urnStr)
defer cStr.Free()
ret, err := AVUuidUrnParse(cStr, &uuid)
if ret != 0 || err != nil {
t.Fatalf("Failed to parse UUID URN: %v", err)
}
// Verify by unparsing
outStr := AllocCStr(37)
defer outStr.Free()
AVUuidUnparse(&uuid, outStr)
result := outStr.String()
expected := "550e8400-e29b-41d4-a716-446655440000"
if result != expected {
t.Fatalf("UUID mismatch: expected %s, got %s", expected, result)
}
t.Logf("UUID URN parse test passed: %s", result)
})
}
// =============================================================================
// Test: UUID Parse Error Paths
// =============================================================================
// TestUUID_ParseErrorPaths tests error detection in UUID parsing functions.
// This validates that malformed UUIDs are properly rejected and return error codes,
// preventing silent corruption from accepting invalid data.
func TestUUID_ParseErrorPaths(t *testing.T) {
t.Run("invalid_uuid_format_too_short", func(t *testing.T) {
// UUID must be exactly 36 characters (plus NUL)
tooShort := "550e8400-e29b-41d4-a716-44665544"
var uuid AVUUID
cStr := ToCStr(tooShort)
defer cStr.Free()
ret, err := AVUuidParse(cStr, &uuid)
if ret == 0 || err == nil {
t.Errorf("AVUuidParse should fail for too-short UUID, got ret=%d err=%v", ret, err)
}
t.Logf("Correctly rejected too-short UUID: ret=%d", ret)
})
t.Run("invalid_uuid_format_too_long", func(t *testing.T) {
// Too many characters
tooLong := "550e8400-e29b-41d4-a716-446655440000-extra"
var uuid AVUUID
cStr := ToCStr(tooLong)
defer cStr.Free()
ret, err := AVUuidParse(cStr, &uuid)
if ret == 0 || err == nil {
t.Errorf("AVUuidParse should fail for too-long UUID, got ret=%d err=%v", ret, err)
}
t.Logf("Correctly rejected too-long UUID: ret=%d", ret)
})
t.Run("invalid_uuid_missing_dashes", func(t *testing.T) {
// Correct length but missing dashes
noDashes := "550e8400e29b41d4a716446655440000"
var uuid AVUUID
cStr := ToCStr(noDashes)
defer cStr.Free()
ret, err := AVUuidParse(cStr, &uuid)
if ret == 0 || err == nil {
t.Errorf("AVUuidParse should fail for UUID without dashes, got ret=%d err=%v", ret, err)
}
t.Logf("Correctly rejected UUID without dashes: ret=%d", ret)
})
t.Run("invalid_uuid_wrong_dash_positions", func(t *testing.T) {
// Dashes in wrong positions
wrongDashes := "550e8400e29b-41d4-a716-446655440000"
var uuid AVUUID
cStr := ToCStr(wrongDashes)
defer cStr.Free()
ret, err := AVUuidParse(cStr, &uuid)
if ret == 0 || err == nil {
t.Errorf("AVUuidParse should fail for UUID with wrong dash positions, got ret=%d err=%v", ret, err)
}
t.Logf("Correctly rejected UUID with wrong dashes: ret=%d", ret)
})
t.Run("invalid_uuid_non_hex_characters", func(t *testing.T) {
// Contains non-hex characters
invalidChars := "550e8400-e29b-41d4-a716-44665544GGGG"
var uuid AVUUID
cStr := ToCStr(invalidChars)
defer cStr.Free()
ret, err := AVUuidParse(cStr, &uuid)
if ret == 0 || err == nil {
t.Errorf("AVUuidParse should fail for non-hex characters, got ret=%d err=%v", ret, err)
}
t.Logf("Correctly rejected UUID with non-hex chars: ret=%d", ret)
})
t.Run("invalid_uuid_empty_string", func(t *testing.T) {
// Empty string
var uuid AVUUID
cStr := ToCStr("")
defer cStr.Free()
ret, err := AVUuidParse(cStr, &uuid)
if ret == 0 || err == nil {
t.Errorf("AVUuidParse should fail for empty string, got ret=%d err=%v", ret, err)
}
t.Logf("Correctly rejected empty UUID string: ret=%d", ret)
})
t.Run("valid_uuid_uppercase_accepted", func(t *testing.T) {
// RFC 4122 specifies parsing should be case-insensitive
uppercaseUUID := "550E8400-E29B-41D4-A716-446655440000"
var uuid AVUUID
cStr := ToCStr(uppercaseUUID)
defer cStr.Free()
ret, err := AVUuidParse(cStr, &uuid)
if ret != 0 || err != nil {
t.Fatalf("AVUuidParse should accept uppercase UUID, got ret=%d err=%v", ret, err)
}
// Verify by unparsing (should be lowercase)
outStr := AllocCStr(37)
defer outStr.Free()
AVUuidUnparse(&uuid, outStr)
result := outStr.String()
expected := "550e8400-e29b-41d4-a716-446655440000"
if result != expected {
t.Errorf("Unparsed UUID mismatch: got %s, want %s", result, expected)
}
t.Logf("Uppercase UUID correctly parsed and normalized: %s -> %s", uppercaseUUID, result)
})
t.Run("urn_invalid_format_missing_prefix", func(t *testing.T) {
// URN must start with "urn:uuid:"
noPrefix := "550e8400-e29b-41d4-a716-446655440000"
var uuid AVUUID
cStr := ToCStr(noPrefix)
defer cStr.Free()
ret, err := AVUuidUrnParse(cStr, &uuid)
if ret == 0 || err == nil {
t.Errorf("AVUuidUrnParse should fail without urn:uuid: prefix, got ret=%d err=%v", ret, err)
}
t.Logf("Correctly rejected URN without prefix: ret=%d", ret)
})
t.Run("urn_invalid_format_wrong_prefix", func(t *testing.T) {
// Wrong URN prefix
wrongPrefix := "uuid:uuid:550e8400-e29b-41d4-a716-446655440000"
var uuid AVUUID
cStr := ToCStr(wrongPrefix)
defer cStr.Free()
ret, err := AVUuidUrnParse(cStr, &uuid)
if ret == 0 || err == nil {
t.Errorf("AVUuidUrnParse should fail with wrong prefix, got ret=%d err=%v", ret, err)
}
t.Logf("Correctly rejected URN with wrong prefix: ret=%d", ret)
})
t.Run("urn_invalid_uuid_part", func(t *testing.T) {
// URN with invalid UUID part
invalidURN := "urn:uuid:550e8400-e29b-41d4-a716-GGGGGGGGGGGG"
var uuid AVUUID
cStr := ToCStr(invalidURN)
defer cStr.Free()
ret, err := AVUuidUrnParse(cStr, &uuid)
if ret == 0 || err == nil {
t.Errorf("AVUuidUrnParse should fail with invalid UUID part, got ret=%d err=%v", ret, err)
}
t.Logf("Correctly rejected URN with invalid UUID: ret=%d", ret)
})
t.Run("urn_case_insensitive", func(t *testing.T) {
// URN parsing should be case-insensitive for the "urn:uuid:" prefix
mixedCase := "URN:UUID:550e8400-e29b-41d4-a716-446655440000"
var uuid AVUUID
cStr := ToCStr(mixedCase)
defer cStr.Free()
// This may or may not be accepted depending on FFmpeg's strictness
// Document the actual behaviour
ret, _ := AVUuidUrnParse(cStr, &uuid)
if ret == 0 {
t.Logf("Mixed-case URN prefix accepted: %s", mixedCase)
} else {
t.Logf("Mixed-case URN prefix rejected (ret=%d) - prefix is case-sensitive", ret)
}
})
t.Run("parse_range_exact_length", func(t *testing.T) {
// AVUuidParseRange requires exact 36-character range
uuidStr := "550e8400-e29b-41d4-a716-446655440000"
var uuid AVUUID
// Create start and end pointers into the UUID string
start := ToCStr(uuidStr)
defer start.Free()
// End pointer should be exactly 36 chars after start
ret, err := AVUuidParseRange(start, start, &uuid)
if ret == 0 || err == nil {
t.Errorf("AVUuidParseRange should fail with zero-length range, got ret=%d err=%v", ret, err)
}
t.Logf("Correctly rejected zero-length range: ret=%d", ret)
})
t.Run("error_code_is_negative", func(t *testing.T) {
// All UUID parse errors should return negative codes
testCases := []string{
"", // empty
"invalid", // too short
"550e8400-e29b-41d4-a716-44665544XXXX", // invalid chars
}
for _, testStr := range testCases {
var uuid AVUUID
cStr := ToCStr(testStr)
ret, err := AVUuidParse(cStr, &uuid)
cStr.Free()
if ret >= 0 && ret != 0 {
t.Errorf("Error code should be negative or zero, got %d for %q", ret, testStr)
}
if ret < 0 && err == nil {
t.Errorf("Negative return code should have non-nil error, got nil for %q", testStr)
}
}
t.Log("All UUID parse errors correctly return negative codes")
})
}
// TestGeneratorCharVsUint8 verifies that char parameters use C.char, not C.uint8_t
// This is a regression test for the av_match_list compilation error.
func TestGeneratorCharVsUint8(t *testing.T) {
// av_match_list has signature: int av_match_list(const char *name, const char *list, char separator)
// The third parameter 'separator' is type char (not uint8_t)
// Test that the function accepts uint8 (Go's char mapping) and compiles without error
name := ToCStr("test")
defer name.Free()
list := ToCStr("test,foo,bar")
defer list.Free()
// If this compiles, the char→C.char mapping is working correctly
// (Previously this would fail: cannot use _Ctype_uint8_t as _Ctype_char)
result, err := AVMatchList(name, list, ',')
if err != nil {
t.Fatalf("AVMatchList failed: %v", err)
}
if result != 1 {
t.Errorf("Expected match result 1, got %d", result)
}
}
// TestGeneratorPixFmtDescriptorTypes validates that AVPixFmtDescriptor fields use correct C types
// This is a regression test for uint8_t fields being incorrectly cast to C.int
func TestGeneratorPixFmtDescriptorTypes(t *testing.T) {
// Get a pixel format descriptor (any format will do)
desc := AVPixFmtDescGet(AVPixFmtRgb24)
if desc == nil {
t.Fatal("RGB24 pixel format should exist")
}
// Test uint8_t fields (nb_components, log2_chroma_w, log2_chroma_h)
// These should use C.uint8_t casts, not C.int
// The fact that these compile and run proves the types are correct
nbComponents := desc.NbComponents()
if nbComponents <= 0 || nbComponents > 4 {
t.Errorf("RGB24 components should be 1-4, got %d", nbComponents)
}
log2ChromaW := desc.Log2ChromaW()
log2ChromaH := desc.Log2ChromaH()
// RGB24 has no chroma subsampling
if log2ChromaW != 0 {
t.Errorf("RGB24 log2_chroma_w should be 0, got %d", log2ChromaW)
}
if log2ChromaH != 0 {
t.Errorf("RGB24 log2_chroma_h should be 0, got %d", log2ChromaH)
}
// Test uint64_t field (flags)
// This should use C.uint64_t cast, not C.int
flags := desc.Flags()
if flags < 0 {
t.Errorf("flags should be readable, got %d", flags)
}
// RGB24 should have RGB flag set
if (flags & AVPixFmtFlagRgb) == 0 {
t.Error("RGB24 should have RGB flag set")
}
}
// TestGeneratorPrimitiveTypeMapping validates that primitive types map to correct CGO types
// This is a smoke test for the getCType() function
func TestGeneratorPrimitiveTypeMapping(t *testing.T) {
t.Run("ptrdiff_t", func(t *testing.T) {
// av_image_copy_plane_uc_from uses ptrdiff_t (mapped to int64)
// Verify it compiles and doesn't panic
dst := make([]byte, 100)
src := make([]byte, 100)
AVImageCopyPlaneUcFrom(
unsafe.Pointer(&dst[0]), 10,
unsafe.Pointer(&src[0]), 10,
10, 10,
)
t.Log("ptrdiff_t parameters map to C.int64_t correctly")
})
t.Run("size_t", func(t *testing.T) {
// AVMalloc uses size_t
ptr := AVMalloc(1024)
if ptr != nil {
AVFree(ptr)
}
t.Log("size_t parameters map to C.size_t correctly")
})
}
// TestGeneratorManualBindings documents which patterns are intentionally skipped and have manual bindings
func TestGeneratorManualBindings(t *testing.T) {
t.Run("variadic_functions", func(t *testing.T) {
// av_log is variadic and intentionally skipped in favor of manual binding
// Just verify that our manual logging system works
callback := func(ctx *LogCtx, level int, msg string) {
// Test callback
}
AVLogSetCallback(callback)
// If we reach here without panic, logging system initialized correctly
t.Log("Variadic logging functions have manual bindings")
})
t.Run("iterator_functions", func(t *testing.T) {
// Iterator functions with opaque pointers are manually bound
// Verify at least one iterator works
var opaque unsafe.Pointer
codec := AVCodecIterate(&opaque)
if codec == nil {
t.Error("codec iterator should return at least one codec")
}
t.Log("Iterator functions with opaque pointers have manual bindings")
})
}
// TestGeneratorTypePreservation validates that the CTypeName field preservation works
// This is a meta-test that the generator correctly handles typedef preservation
func TestGeneratorTypePreservation(t *testing.T) {
t.Run("char_params_compile", func(t *testing.T) {
// Functions with char parameters should compile
// (regression test for char→uint8_t→C.uint8_t bug)
name := ToCStr("rgb24")
defer name.Free()
pixFmt := AVGetPixFmt(name)
if pixFmt != AVPixFmtRgb24 {
t.Errorf("Expected AVPixFmtRgb24, got %v", pixFmt)
}
})
t.Run("uint8_fields_compile", func(t *testing.T) {
// Struct fields with uint8_t should use C.uint8_t
// (regression test for uint8_t→int→C.int bug)
desc := AVPixFmtDescGet(AVPixFmtYuv420P)
if desc == nil {
t.Fatal("YUV420P pixel format should exist")
}
// YUV420P has 3 components
components := desc.NbComponents()
if components != 3 {
t.Errorf("YUV420P should have 3 components, got %d", components)
}
// And chroma subsampling (log2_chroma_w/h should be 1)
chromaW := desc.Log2ChromaW()
chromaH := desc.Log2ChromaH()
if chromaW != 1 {
t.Errorf("YUV420P log2_chroma_w should be 1, got %d", chromaW)
}
if chromaH != 1 {
t.Errorf("YUV420P log2_chroma_h should be 1, got %d", chromaH)
}
})
t.Run("uint64_fields_compile", func(t *testing.T) {
// Struct fields with uint64_t should use C.uint64_t
// (regression test for uint64_t→int→C.int bug)
desc := AVPixFmtDescGet(AVPixFmtRgb24)
if desc == nil {
t.Fatal("RGB24 pixel format should exist")
}
flags := desc.Flags()
// RGB24 should have RGB flag set
if (flags & AVPixFmtFlagRgb) == 0 {
t.Error("RGB24 should have RGB flag set")
}
})
}
// TestGeneratorConstArrayFields tests const array field generation with enum and struct types
// This validates the Priority 1 enhancement that enables enum/struct const arrays
func TestGeneratorConstArrayFields(t *testing.T) {
t.Run("struct_const_array_AVRational", func(t *testing.T) {
// Test that struct const array fields work (AVRational[N])
// Previously skipped as "unknown const array"
// Example: AVDetectionBBox.classify_confidences (AVRational[4])
// Create a detection bbox (would normally come from av_detection_bbox_alloc)
// We can't easily allocate one, but we can verify the accessor compiles
var bbox *AVDetectionBBox
if bbox != nil {
// This should compile and return *Array[*AVRational]
confidences := bbox.ClassifyConfidences()
_ = confidences
}
t.Log("Struct const array field (AVRational[N]) accessor compiled successfully")
})
t.Run("enum_const_array", func(t *testing.T) {
// Test that enum const array fields work (AVEnum[N])
// Previously skipped as "unknown const array"
// Example: AVDOVIReshapingCurve.mapping_idc (AVDOVIMappingMethod[8])
var curve *AVDOVIReshapingCurve
if curve != nil {
// This should compile and return *Array[AVDOVIMappingMethod]
mappingIdc := curve.MappingIdc()
_ = mappingIdc
}
t.Log("Enum const array field (AVEnum[N]) accessor compiled successfully")
})
t.Run("byvalue_struct_array_helper", func(t *testing.T) {
// Test that ToXArray helpers are generated for ByValue structs
// Previously only generated for pointer structs
// This enables the array field accessors above to work
// AVRational is a ByValue struct, should have ToAVRationalArray
r1 := AVMakeQ(1, 2)
r2 := AVMakeQ(3, 4)
// Verify basic functionality of ByValue struct
if r1.Num() != 1 || r1.Den() != 2 {
t.Errorf("AVRational ByValue struct broken: got %d/%d, want 1/2", r1.Num(), r1.Den())
}
if r2.Num() != 3 || r2.Den() != 4 {
t.Errorf("AVRational ByValue struct broken: got %d/%d, want 3/4", r2.Num(), r2.Den())
}
t.Log("ByValue struct ToXArray helper generation validated")
})
}
// TestGeneratorOutputParameters verifies that Priority 2 (output parameter functions)
// are properly generated and compile with the correct signatures.
func TestGeneratorOutputParameters(t *testing.T) {
t.Run("av_opt_get family compiles", func(t *testing.T) {
// These functions should compile - we're just testing signature availability
// Actual runtime testing would require a valid AVClass object
// Test that output parameter functions are accessible
var outInt int64
var outDouble float64
var outW, outH int
// Verify function signatures compile (won't run without valid context)
_ = func() (int, error) {
return AVOptGetInt(nil, nil, 0, &outInt)
}
_ = func() (int, error) {
return AVOptGetDouble(nil, nil, 0, &outDouble)
}
_ = func() (int, error) {
return AVOptGetImageSize(nil, nil, 0, &outW, &outH)
}
t.Log("av_opt_get_* family functions compile with output parameters")
})
t.Run("av_packet_get_side_data compiles", func(t *testing.T) {
var size uint64
// Verify av_packet_get_side_data compiles with size output parameter
_ = func() unsafe.Pointer {
return AVPacketGetSideData(nil, AVPacketSideDataType(0), &size)
}
t.Log("av_packet_get_side_data compiles with size output parameter")
})
t.Run("av_cpb_properties_alloc compiles", func(t *testing.T) {
var size uint64
// Verify av_cpb_properties_alloc compiles with size output parameter
_ = func() *AVCPBProperties {
return AVCpbPropertiesAlloc(&size)
}
t.Log("av_cpb_properties_alloc compiles with size output parameter")
})
t.Run("dimension output parameters compile", func(t *testing.T) {
var width, height int
// Verify functions with width/height output parameters compile
_ = func() {
AVCodecAlignDimensions(nil, &width, &height)
}
t.Log("Functions with width/height output parameters compile")
})
t.Run("callback functions are skipped", func(t *testing.T) {
// The following functions should NOT be generated because they use
// callback parameters passed by value, which CGO cannot handle:
// - AVFifoWriteFromCb
// - AVFifoReadToCb
// - AVFifoPeekToCb
// This test simply documents that these functions are intentionally missing
t.Log("Callback-by-value functions intentionally skipped due to CGO limitation")
t.Log("Missing: av_fifo_write_from_cb, av_fifo_read_to_cb, av_fifo_peek_to_cb")
})
}
// TestGeneratorFieldAccessors validates that struct field getters work as expected
// This tests the getter generation pattern for various field types
func TestGeneratorFieldAccessors(t *testing.T) {
t.Run("primitive_fields", func(t *testing.T) {
frame := AVFrameAlloc()
if frame == nil {
t.Fatal("AVFrameAlloc returned nil")
}
defer AVFrameFree(&frame)
// Test that getters return expected types and compile
_ = frame.Width() // int
_ = frame.Height() // int
_ = frame.Format() // int (pix_fmt)
_ = frame.Pts() // int64
_ = frame.PktDts() // int64
_ = frame.Data() // [8]unsafe.Pointer (const array)
_ = frame.Linesize() // [8]int (const array)
t.Log("Primitive field accessors compile and work correctly")
})
t.Run("byvalue_struct_fields", func(t *testing.T) {
frame := AVFrameAlloc()
if frame == nil {
t.Fatal("AVFrameAlloc returned nil")
}
defer AVFrameFree(&frame)
// Test ByValue struct field returns proper type
timebase := frame.TimeBase()
_ = timebase.Num()
_ = timebase.Den()
sampleAspectRatio := frame.SampleAspectRatio()
_ = sampleAspectRatio.Num()
_ = sampleAspectRatio.Den()
t.Log("ByValue struct field accessors work correctly")
})
t.Run("pointer_struct_fields", func(t *testing.T) {
codecCtx := AVCodecAllocContext3(nil)
if codecCtx == nil {
t.Fatal("AVCodecAllocContext3 returned nil")
}
defer AVCodecFreeContext(&codecCtx)
// Test pointer field accessors
_ = codecCtx.Extradata() // unsafe.Pointer
_ = codecCtx.ExtradataSize() // int
_ = codecCtx.Codec() // *AVCodec
t.Log("Pointer struct field accessors work correctly")
})
}
// =============================================================================
// Test: Array Bounds Behaviour Documentation
// =============================================================================
// TestArray_BoundsBehaviour documents and verifies the bounds behaviour of the
// Array[T] type. This is a critical safety documentation test.
//
// IMPORTANT: The Array type has NO bounds checking, matching C behaviour.
// Out-of-bounds access leads to undefined behaviour (memory corruption, crashes,
// or silent data corruption). This is by design to match FFmpeg's C semantics.
//
// Users MUST track array lengths themselves, just as in C code.
func TestArray_BoundsBehaviour(t *testing.T) {
t.Run("valid_indices_work_correctly", func(t *testing.T) {
// Allocate array of 3 elements
arr := AllocAVCodecIDArray(3)
if arr == nil {
t.Fatal("AllocAVCodecIDArray returned nil")
}
defer AVFree(arr.RawPtr())
// Valid indices: 0, 1, 2
arr.Set(0, AVCodecIdH264)
arr.Set(1, AVCodecIdHevc)
arr.Set(2, AVCodecIdAV1)
if arr.Get(0) != AVCodecIdH264 {
t.Errorf("Get(0) = %v, want AVCodecIdH264", arr.Get(0))
}
if arr.Get(1) != AVCodecIdHevc {
t.Errorf("Get(1) = %v, want AVCodecIdHevc", arr.Get(1))
}
if arr.Get(2) != AVCodecIdAV1 {
t.Errorf("Get(2) = %v, want AVCodecIdAV1", arr.Get(2))
}
})
t.Run("documents_no_bounds_checking", func(t *testing.T) {
// This test documents that Array has NO bounds checking.
// We cannot safely test out-of-bounds access as it causes undefined behaviour.
//
// DO NOT uncomment the following - it will cause memory corruption:
// arr := AllocAVCodecIDArray(3)
// arr.Get(100) // UNDEFINED BEHAVIOUR - reads arbitrary memory
// arr.Set(100, AVCodecIdH264) // UNDEFINED BEHAVIOUR - writes arbitrary memory
//
// Users must track array lengths themselves. This matches C semantics where