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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
//! RIFF container format reader (WebP, AVI, WAV).
//!
//! Parses RIFF chunks to extract metadata from WebP (EXIF, XMP, ICC),
//! AVI (video/audio info, INFO chunks), and WAV (audio format, INFO).
//! Mirrors ExifTool's RIFF.pm.
use crate::error::{Error, Result};
use crate::metadata::exif::ByteOrderMark;
use crate::metadata::{ExifReader, XmpReader};
use crate::tag::{Tag, TagGroup, TagId};
use crate::value::Value;
/// Read metadata from a RIFF-based file (WebP, AVI, WAV).
pub fn read_riff(data: &[u8]) -> Result<Vec<Tag>> {
if data.len() < 12 || !data.starts_with(b"RIFF") {
return Err(Error::InvalidData("not a RIFF file".into()));
}
let _file_size = u32::from_le_bytes([data[4], data[5], data[6], data[7]]);
let form_type = &data[8..12];
let mut tags = Vec::new();
match form_type {
b"WEBP" => read_webp_chunks(data, 12, &mut tags)?,
b"AVI " => read_avi_chunks(data, 12, &mut tags)?,
b"WAVE" => read_wav_chunks(data, 12, &mut tags)?,
_ => {
return Err(Error::InvalidData(format!(
"unknown RIFF type: {}",
crate::encoding::decode_utf8_or_latin1(form_type)
)));
}
}
Ok(tags)
}
// ============================================================================
// WebP
// ============================================================================
fn read_webp_chunks(data: &[u8], start: usize, tags: &mut Vec<Tag>) -> Result<()> {
let mut pos = start;
while pos + 8 <= data.len() {
let chunk_id = &data[pos..pos + 4];
let chunk_size =
u32::from_le_bytes([data[pos + 4], data[pos + 5], data[pos + 6], data[pos + 7]])
as usize;
let chunk_data_start = pos + 8;
let chunk_data_end = chunk_data_start + chunk_size;
if chunk_data_end > data.len() {
break;
}
let chunk_data = &data[chunk_data_start..chunk_data_end];
match chunk_id {
// VP8 lossy bitstream
b"VP8 " => {
if chunk_data.len() >= 10 {
// VP8 frame header: 3 bytes frame tag, then dimensions
let frame_tag =
u32::from_le_bytes([chunk_data[0], chunk_data[1], chunk_data[2], 0]);
let is_keyframe = (frame_tag & 1) == 0;
if is_keyframe && chunk_data.len() >= 10 {
// Check for VP8 signature 0x9D012A
if chunk_data[3] == 0x9D && chunk_data[4] == 0x01 && chunk_data[5] == 0x2A {
// VP8Version: bits 1-3 of first byte
let version = (chunk_data[0] >> 1) & 0x07;
let version_str = match version {
0 => "0 (bicubic reconstruction, normal loop)",
1 => "1 (bilinear reconstruction, simple loop)",
2 => "2 (bilinear reconstruction, no loop)",
3 => "3 (no reconstruction, no loop)",
v => {
return {
// fallback: just use number
let width =
u16::from_le_bytes([chunk_data[6], chunk_data[7]])
& 0x3FFF;
let height =
u16::from_le_bytes([chunk_data[8], chunk_data[9]])
& 0x3FFF;
let hscale =
(u16::from_le_bytes([chunk_data[6], chunk_data[7]])
>> 14)
& 0x3;
let vscale =
(u16::from_le_bytes([chunk_data[8], chunk_data[9]])
>> 14)
& 0x3;
tags.push(mk_webp(
"VP8Version",
"VP8 Version",
Value::String(format!("{}", v)),
));
tags.push(mk_webp(
"ImageWidth",
"Image Width",
Value::U16(width),
));
tags.push(mk_webp(
"HorizontalScale",
"Horizontal Scale",
Value::U16(hscale),
));
tags.push(mk_webp(
"ImageHeight",
"Image Height",
Value::U16(height),
));
tags.push(mk_webp(
"VerticalScale",
"Vertical Scale",
Value::U16(vscale),
));
Ok(())
};
}
};
let width = u16::from_le_bytes([chunk_data[6], chunk_data[7]]) & 0x3FFF;
let height =
u16::from_le_bytes([chunk_data[8], chunk_data[9]]) & 0x3FFF;
let hscale =
(u16::from_le_bytes([chunk_data[6], chunk_data[7]]) >> 14) & 0x3;
let vscale =
(u16::from_le_bytes([chunk_data[8], chunk_data[9]]) >> 14) & 0x3;
tags.push(mk_webp(
"VP8Version",
"VP8 Version",
Value::String(version_str.into()),
));
tags.push(mk_webp("ImageWidth", "Image Width", Value::U16(width)));
tags.push(mk_webp(
"HorizontalScale",
"Horizontal Scale",
Value::U16(hscale),
));
tags.push(mk_webp("ImageHeight", "Image Height", Value::U16(height)));
tags.push(mk_webp(
"VerticalScale",
"Vertical Scale",
Value::U16(vscale),
));
}
}
}
}
// VP8L lossless bitstream
b"VP8L" => {
if chunk_data.len() >= 5 && chunk_data[0] == 0x2F {
// Bits are packed: width is bits 1..14 (14 bits), height is bits 15..28
// The spec: read 32 bits starting at byte 1
let bits = u32::from_le_bytes([
chunk_data[1],
chunk_data[2],
chunk_data[3],
chunk_data[4],
]);
let width = (bits & 0x3FFF) + 1;
let height = ((bits >> 14) & 0x3FFF) + 1;
let alpha = (bits >> 28) & 1;
tags.push(mk_webp("ImageWidth", "Image Width", Value::U32(width)));
tags.push(mk_webp("ImageHeight", "Image Height", Value::U32(height)));
tags.push(mk_webp(
"AlphaIsUsed",
"Alpha Is Used",
Value::String(if alpha != 0 {
"Yes".into()
} else {
"No".into()
}),
));
}
}
// VP8X extended format
b"VP8X" => {
if chunk_data.len() >= 10 {
// Flags (32-bit little-endian)
let flags = u32::from_le_bytes([
chunk_data[0],
chunk_data[1],
chunk_data[2],
chunk_data[3],
]);
// Width/Height are 24-bit LE at offsets 4 and 7
let width = (chunk_data[4] as u32)
| ((chunk_data[5] as u32) << 8)
| ((chunk_data[6] as u32) << 16);
let height = (chunk_data[7] as u32)
| ((chunk_data[8] as u32) << 8)
| ((chunk_data[9] as u32) << 16);
// Build WebP_Flags string (matching Perl ExifTool bitmask output)
// Perl bit positions: 1=Animation, 2=XMP, 3=EXIF, 4=Alpha, 5=ICC Profile
let mut flag_parts = Vec::new();
if flags & (1 << 1) != 0 {
flag_parts.push("Animation");
}
if flags & (1 << 2) != 0 {
flag_parts.push("XMP");
}
if flags & (1 << 3) != 0 {
flag_parts.push("EXIF");
}
if flags & (1 << 4) != 0 {
flag_parts.push("Alpha");
}
if flags & (1 << 5) != 0 {
flag_parts.push("ICC Profile");
}
if !flag_parts.is_empty() {
tags.push(mk_webp(
"WebP_Flags",
"WebP Flags",
Value::String(flag_parts.join(", ")),
));
}
tags.push(mk_webp("ImageWidth", "Image Width", Value::U32(width + 1)));
tags.push(mk_webp(
"ImageHeight",
"Image Height",
Value::U32(height + 1),
));
}
}
// ALPH chunk (WebP alpha)
b"ALPH" => {
if !chunk_data.is_empty() {
let byte0 = chunk_data[0];
let preprocessing = byte0 & 0x03;
let filtering = (byte0 >> 2) & 0x03;
let compression = (byte0 >> 4) & 0x03;
let preprocessing_str = match preprocessing {
0 => "none",
1 => "Level Reduction",
_ => "Unknown",
};
let filtering_str = match filtering {
0 => "none",
1 => "Horizontal",
2 => "Vertical",
3 => "Gradient",
_ => "Unknown",
};
let compression_str = match compression {
0 => "none",
1 => "Lossless",
_ => "Unknown",
};
tags.push(mk_webp(
"AlphaPreprocessing",
"Alpha Preprocessing",
Value::String(preprocessing_str.into()),
));
tags.push(mk_webp(
"AlphaFiltering",
"Alpha Filtering",
Value::String(filtering_str.into()),
));
tags.push(mk_webp(
"AlphaCompression",
"Alpha Compression",
Value::String(compression_str.into()),
));
}
}
// EXIF data
b"EXIF" => {
// May start with "Exif\0\0" header or directly with TIFF header
let exif_data = if chunk_data.len() > 6 && chunk_data.starts_with(b"Exif\0\0") {
&chunk_data[6..]
} else {
chunk_data
};
if let Ok(exif_tags) = ExifReader::read(exif_data) {
tags.extend(exif_tags);
}
}
// XMP data
b"XMP " => {
if let Ok(xmp_tags) = XmpReader::read(chunk_data) {
tags.extend(xmp_tags);
}
}
// ICC Profile
b"ICCP" => {
tags.push(mk_webp(
"ICC_Profile",
"ICC Profile",
Value::Binary(chunk_data.to_vec()),
));
}
// Animation
b"ANIM" => {
if chunk_data.len() >= 6 {
let bg_color = u32::from_le_bytes([
chunk_data[0],
chunk_data[1],
chunk_data[2],
chunk_data[3],
]);
let loop_count = u16::from_le_bytes([chunk_data[4], chunk_data[5]]);
tags.push(mk_webp(
"BackgroundColor",
"Background Color",
Value::U32(bg_color),
));
tags.push(mk_webp(
"AnimationLoopCount",
"Animation Loop Count",
Value::U16(loop_count),
));
}
}
_ => {}
}
// Advance (pad to even boundary)
pos = chunk_data_end + (chunk_size & 1);
}
Ok(())
}
// ============================================================================
// AVI
// ============================================================================
fn read_avi_chunks(data: &[u8], start: usize, tags: &mut Vec<Tag>) -> Result<()> {
let mut state = AviState::new();
read_riff_chunks(data, start, data.len(), tags, "AVI", &mut state)
}
// ============================================================================
// WAV
// ============================================================================
fn read_wav_chunks(data: &[u8], start: usize, tags: &mut Vec<Tag>) -> Result<()> {
let mut state = AviState::new();
state.file_size = data.len() as u64;
read_riff_chunks(data, start, data.len(), tags, "WAV", &mut state)
}
/// State for AVI stream tracking (stream type changes between strh/strf pairs)
struct AviState {
/// Type of current stream: "vids", "auds", etc.
current_stream_type: Option<String>,
/// Accumulated data chunk size for duration calculation (WAV)
data_len: u64,
/// Total file size (for WAV duration fallback when data chunk is empty)
file_size: u64,
/// AvgBytesPerSec from fmt chunk (WAV duration)
avg_bytes_per_sec: u32,
/// Frame rate (microseconds per frame from avih)
us_per_frame: u32,
/// Total frames from avih
total_frames: u32,
/// Video frame count from strh
video_frame_count: u32,
/// Video frame rate (from strh, rational: scale/rate -> rate/scale fps)
video_frame_rate: Option<f64>,
/// Recursion depth — Duration is only emitted at depth 0
depth: usize,
/// Number of streams seen so far (StreamType/Quality/SampleSize only from first stream)
stream_count_seen: u32,
}
impl AviState {
fn new() -> Self {
AviState {
current_stream_type: None,
data_len: 0,
file_size: 0,
avg_bytes_per_sec: 0,
us_per_frame: 0,
total_frames: 0,
video_frame_count: 0,
video_frame_rate: None,
depth: 0,
stream_count_seen: 0,
}
}
}
/// Generic RIFF chunk iterator used by both AVI and WAV.
fn read_riff_chunks(
data: &[u8],
start: usize,
end: usize,
tags: &mut Vec<Tag>,
family: &str,
state: &mut AviState,
) -> Result<()> {
let mut pos = start;
while pos + 8 <= end {
let chunk_id = &data[pos..pos + 4];
let chunk_size =
u32::from_le_bytes([data[pos + 4], data[pos + 5], data[pos + 6], data[pos + 7]])
as usize;
let chunk_data_start = pos + 8;
let chunk_data_end = (chunk_data_start + chunk_size).min(end);
if chunk_data_start > end {
break;
}
match chunk_id {
// LIST chunk: contains a type + sub-chunks
b"LIST" => {
if chunk_data_end >= chunk_data_start + 4 {
let list_type = &data[chunk_data_start..chunk_data_start + 4];
match list_type {
b"INFO" => {
read_info_chunks(
data,
chunk_data_start + 4,
chunk_data_end,
tags,
family,
)?;
}
b"INF0" => {
// Some files use '0' instead of 'O'
read_info_chunks(
data,
chunk_data_start + 4,
chunk_data_end,
tags,
family,
)?;
}
b"hdrl" => {
// AVI header list - contains avih and strl
state.depth += 1;
read_riff_chunks(
data,
chunk_data_start + 4,
chunk_data_end,
tags,
family,
state,
)?;
state.depth -= 1;
}
b"strl" => {
state.depth += 1;
read_riff_chunks(
data,
chunk_data_start + 4,
chunk_data_end,
tags,
family,
state,
)?;
state.depth -= 1;
}
b"odml" => {
// OpenDML extended AVI header
state.depth += 1;
read_riff_chunks(
data,
chunk_data_start + 4,
chunk_data_end,
tags,
family,
state,
)?;
state.depth -= 1;
}
b"exif" => {
// EXIF data in AVI/WAV LIST exif chunk
read_exif_list_chunks(
data,
chunk_data_start + 4,
chunk_data_end,
tags,
family,
)?;
}
b"adtl" => {
// Associated data list
state.depth += 1;
read_riff_chunks(
data,
chunk_data_start + 4,
chunk_data_end,
tags,
family,
state,
)?;
state.depth -= 1;
}
b"hydt" | b"pntx" => {
// Pentax metadata LIST (LIST hydt / LIST pntx)
read_pentax_avi_chunks(
data,
chunk_data_start + 4,
chunk_data_end,
tags,
)?;
}
_ => {}
}
}
}
// AVI Main Header
b"avih" => {
if chunk_size >= 40 {
let cd = &data[chunk_data_start..chunk_data_end];
let us_per_frame = u32::from_le_bytes([cd[0], cd[1], cd[2], cd[3]]);
let max_data_rate = u32::from_le_bytes([cd[4], cd[5], cd[6], cd[7]]);
// cd[8..11] = PaddingGranularity, cd[12..15] = Flags
let total_frames = u32::from_le_bytes([cd[16], cd[17], cd[18], cd[19]]);
// cd[20..23] = InitialFrames
let stream_count = u32::from_le_bytes([cd[24], cd[25], cd[26], cd[27]]);
// cd[28..31] = SuggestedBufferSize
let width = u32::from_le_bytes([cd[32], cd[33], cd[34], cd[35]]);
let height = u32::from_le_bytes([cd[36], cd[37], cd[38], cd[39]]);
state.us_per_frame = us_per_frame;
state.total_frames = total_frames;
if us_per_frame > 0 {
let fps = 1_000_000.0_f64 / us_per_frame as f64;
// ExifTool prints as int($val * 1000 + 0.5) / 1000
let fps_rounded = (fps * 1000.0 + 0.5).floor() / 1000.0;
tags.push(mk_riff(
family,
"FrameRate",
"Frame Rate",
Value::String(format!("{}", fps_rounded)),
));
}
// MaxDataRate: ExifTool prints as "X kB/s" (sprintf("%.4g %s", $tmp, $unit))
let kbps = max_data_rate as f64 / 1000.0;
let max_data_rate_str = format_sig4(kbps, "kB/s");
tags.push(mk_riff(
family,
"MaxDataRate",
"Max Data Rate",
Value::String(max_data_rate_str),
));
tags.push(mk_riff(
family,
"FrameCount",
"Frame Count",
Value::U32(total_frames),
));
tags.push(mk_riff(
family,
"StreamCount",
"Stream Count",
Value::U32(stream_count),
));
tags.push(mk_riff(
family,
"ImageWidth",
"Image Width",
Value::U32(width),
));
tags.push(mk_riff(
family,
"ImageHeight",
"Image Height",
Value::U32(height),
));
}
}
// Stream Header (strh)
b"strh" => {
if chunk_size >= 4 {
let cd = &data[chunk_data_start..chunk_data_end];
let fcc_type = crate::encoding::decode_utf8_or_latin1(&cd[0..4]).to_string();
state.current_stream_type = Some(fcc_type.clone());
state.stream_count_seen += 1;
let is_first_stream = state.stream_count_seen == 1;
// StreamType — Perl uses PRIORITY=>0 so only first stream wins
if is_first_stream {
let stream_type_str = match fcc_type.as_str() {
"auds" => "Audio",
"mids" => "MIDI",
"txts" => "Text",
"vids" => "Video",
"iavs" => "Interleaved Audio+Video",
_ => &fcc_type,
};
tags.push(mk_riff(
family,
"StreamType",
"Stream Type",
Value::String(stream_type_str.to_string()),
));
}
if chunk_size >= 8 {
let fcc_handler = crate::encoding::decode_utf8_or_latin1(&cd[4..8])
.trim_end_matches('\0')
.to_string();
if fcc_type == "vids" {
tags.push(mk_riff(
family,
"VideoCodec",
"Video Codec",
Value::String(fcc_handler),
));
} else if fcc_type == "auds" {
tags.push(mk_riff(
family,
"AudioCodec",
"Audio Codec",
Value::String(fcc_handler),
));
}
}
// Scale (offset 20) and Rate (offset 24) for frame rate (both int32u)
if chunk_size >= 28 {
let scale = u32::from_le_bytes([cd[20], cd[21], cd[22], cd[23]]);
let rate = u32::from_le_bytes([cd[24], cd[25], cd[26], cd[27]]);
if fcc_type == "auds" && scale > 0 {
// AudioSampleRate = rate/scale
let audio_rate = rate as f64 / scale as f64;
let audio_rate_rounded = (audio_rate * 100.0 + 0.5).floor() / 100.0;
tags.push(mk_riff(
family,
"AudioSampleRate",
"Audio Sample Rate",
Value::String(format!("{}", audio_rate_rounded)),
));
} else if fcc_type == "vids" && scale > 0 {
// VideoFrameRate = rate/scale
let vfr = rate as f64 / scale as f64;
let vfr_rounded = (vfr * 1000.0 + 0.5).floor() / 1000.0;
state.video_frame_rate = Some(vfr);
tags.push(mk_riff(
family,
"VideoFrameRate",
"Video Frame Rate",
Value::String(format!("{}", vfr_rounded)),
));
}
}
// Length (offset 32) = sample count / frame count
if chunk_size >= 36 {
let length = u32::from_le_bytes([cd[32], cd[33], cd[34], cd[35]]);
if fcc_type == "auds" {
tags.push(mk_riff(
family,
"AudioSampleCount",
"Audio Sample Count",
Value::U32(length),
));
} else if fcc_type == "vids" {
state.video_frame_count = length;
tags.push(mk_riff(
family,
"VideoFrameCount",
"Video Frame Count",
Value::U32(length),
));
}
}
// Quality (offset 40) and SampleSize (offset 44)
// Perl uses PRIORITY=>0 so only first stream's values are kept
if chunk_size >= 48 && is_first_stream {
let quality = u32::from_le_bytes([cd[40], cd[41], cd[42], cd[43]]);
let sample_size = u32::from_le_bytes([cd[44], cd[45], cd[46], cd[47]]);
let quality_str = if quality == 0xFFFFFFFF {
"Default".to_string()
} else {
format!("{}", quality)
};
tags.push(mk_riff(
family,
"Quality",
"Quality",
Value::String(quality_str),
));
let sample_size_str = if sample_size == 0 {
"Variable".to_string()
} else if sample_size == 1 {
"1 byte".to_string()
} else {
format!("{} bytes", sample_size)
};
tags.push(mk_riff(
family,
"SampleSize",
"Sample Size",
Value::String(sample_size_str),
));
}
}
}
// Stream Format (strf)
b"strf" => {
match state.current_stream_type.as_deref() {
Some("auds") => {
// WAVEFORMATEX
parse_wave_format(data, chunk_data_start, chunk_data_end, tags, family);
}
Some("vids") => {
// BITMAPINFOHEADER
parse_bitmapinfoheader(
data,
chunk_data_start,
chunk_data_end,
tags,
family,
);
}
_ => {}
}
}
// Stream Data (strd) - may contain EXIF
b"strd" => {
// Try AVIF (EXIF in AVI stream data)
if chunk_data_end >= chunk_data_start + 4 {
let tag = &data[chunk_data_start..chunk_data_start + 4];
if tag == b"AVIF" && chunk_data_end >= chunk_data_start + 8 {
// EXIF data starts at offset 8 in strd
if let Ok(exif_tags) =
ExifReader::read(&data[chunk_data_start + 8..chunk_data_end])
{
tags.extend(exif_tags);
}
}
}
}
// OpenDML extended AVI header (dmlh)
b"dmlh" => {
if chunk_size >= 4 {
let cd = &data[chunk_data_start..chunk_data_end];
let total_frame_count = u32::from_le_bytes([cd[0], cd[1], cd[2], cd[3]]);
tags.push(mk_riff(
family,
"TotalFrameCount",
"Total Frame Count",
Value::U32(total_frame_count),
));
}
}
// Audio Format (WAV fmt chunk at top level)
b"fmt " => {
parse_wave_format(data, chunk_data_start, chunk_data_end, tags, family);
// Also capture AvgBytesPerSec for WAV duration calculation
if chunk_size >= 12 {
let cd = &data[chunk_data_start..chunk_data_end];
state.avg_bytes_per_sec = u32::from_le_bytes([cd[8], cd[9], cd[10], cd[11]]);
}
}
// WAV data chunk (for duration calculation)
b"data" => {
state.data_len += chunk_size as u64;
}
// IDIT - DateTimeOriginal (top-level or in hdrl)
b"IDIT" => {
let s =
crate::encoding::decode_utf8_or_latin1(&data[chunk_data_start..chunk_data_end])
.trim_end_matches('\0')
.to_string();
if !s.is_empty() {
let converted = convert_riff_date(&s);
tags.push(mk_riff(
family,
"DateTimeOriginal",
"Date/Time Original",
Value::String(converted),
));
}
}
// EXIF chunk
b"EXIF" => {
let exif_data = &data[chunk_data_start..chunk_data_end];
let exif_data = if exif_data.starts_with(b"Exif\0\0") {
&exif_data[6..]
} else {
exif_data
};
if let Ok(exif_tags) = ExifReader::read(exif_data) {
tags.extend(exif_tags);
}
}
// XMP
b"_PMX" | b"XMP " => {
if let Ok(xmp_tags) = XmpReader::read(&data[chunk_data_start..chunk_data_end]) {
tags.extend(xmp_tags);
}
}
// Broadcast extension (WAV bext)
b"bext" => {
parse_bext(
data,
chunk_data_start,
chunk_data_end,
chunk_size,
tags,
family,
);
}
_ => {}
}
pos = chunk_data_end + (chunk_size & 1);
}
// After processing all chunks, compute Duration — only at the top level (depth == 0)
// to avoid emitting Duration once per recursive sub-list call.
if state.depth > 0 {
return Ok(());
}
// After processing all chunks, compute Duration for WAV
// Use data chunk size, or fall back to file size (like Perl ExifTool)
if family == "WAV" && state.avg_bytes_per_sec > 0 {
let effective_len = if state.data_len > 0 {
state.data_len
} else {
state.file_size
};
if effective_len > 0 {
let duration = effective_len as f64 / state.avg_bytes_per_sec as f64;
tags.push(mk_riff(
family,
"Duration",
"Duration",
Value::String(format_duration(duration)),
));
}
}
// After processing all chunks, compute Duration for AVI
if family == "AVI" && state.us_per_frame > 0 {
let fps = 1_000_000.0_f64 / state.us_per_frame as f64;
// Use video frame count/rate if available and ~2-3x difference suggests multi-track
let dur = if let (Some(vfr), vc) = (state.video_frame_rate, state.video_frame_count) {
if vc > 0 && vfr > 0.0 {
let dur1 = state.total_frames as f64 / fps;
let dur2 = vc as f64 / vfr;
let rat = dur1 / dur2;
if rat > 1.9 && rat < 3.1 {
dur2
} else {
dur1
}
} else if state.total_frames > 0 {
state.total_frames as f64 / fps
} else {
0.0
}
} else if state.total_frames > 0 {
state.total_frames as f64 / fps
} else {
0.0
};
if dur > 0.0 {
tags.push(mk_riff(
family,
"Duration",
"Duration",
Value::String(format_duration(dur)),
));
}
}
Ok(())
}
/// Parse WAVEFORMATEX / AudioFormat chunk
fn parse_wave_format(data: &[u8], start: usize, end: usize, tags: &mut Vec<Tag>, family: &str) {
let chunk_size = end - start;
if chunk_size < 14 {
return;
}
let cd = &data[start..end];
let format_tag = u16::from_le_bytes([cd[0], cd[1]]);
let channels = u16::from_le_bytes([cd[2], cd[3]]);
let sample_rate = u32::from_le_bytes([cd[4], cd[5], cd[6], cd[7]]);
let avg_bytes = u32::from_le_bytes([cd[8], cd[9], cd[10], cd[11]]);
let encoding = audio_encoding_name(format_tag);
tags.push(mk_riff(
family,
"Encoding",
"Encoding",
Value::String(encoding.into()),
));
tags.push(mk_riff(
family,
"NumChannels",
"Num Channels",
Value::U16(channels),
));
tags.push(mk_riff(
family,
"SampleRate",
"Sample Rate",
Value::U32(sample_rate),
));
tags.push(mk_riff(
family,
"AvgBytesPerSec",
"Avg Bytes Per Sec",
Value::U32(avg_bytes),
));
if chunk_size >= 16 {
let bits_per_sample = u16::from_le_bytes([cd[14], cd[15]]);
tags.push(mk_riff(
family,
"BitsPerSample",
"Bits Per Sample",
Value::U16(bits_per_sample),
));
}
}
/// Parse BITMAPINFOHEADER (strf for video streams)
fn parse_bitmapinfoheader(
data: &[u8],
start: usize,
end: usize,
tags: &mut Vec<Tag>,
family: &str,
) {
let chunk_size = end - start;
if chunk_size < 40 {
return;
}
let cd = &data[start..end];
// Size of structure = BMPVersion indicator
let bmp_size = u32::from_le_bytes([cd[0], cd[1], cd[2], cd[3]]);
let bmp_version = match bmp_size {
40 => "Windows V3",
68 => "AVI BMP structure?",
108 => "Windows V4",
124 => "Windows V5",
_ => "Unknown",
};
tags.push(mk_riff(
family,
"BMPVersion",
"BMP Version",
Value::String(bmp_version.into()),
));
// Width/Height are at offsets 4/8 but avih already emitted them; skip redundant ImageWidth/Height here
// (ExifTool does emit them from strf too via BMP::Main, but they're the same values)
// Planes at offset 12 (int16u)
let planes = u16::from_le_bytes([cd[12], cd[13]]);
tags.push(mk_riff(family, "Planes", "Planes", Value::U16(planes)));
// BitDepth at offset 14 (int16u)
let bit_depth = u16::from_le_bytes([cd[14], cd[15]]);
tags.push(mk_riff(
family,
"BitDepth",
"Bit Depth",
Value::U16(bit_depth),
));
// Compression at offset 16 (int32u, but often a FourCC)
let compression_raw = u32::from_le_bytes([cd[16], cd[17], cd[18], cd[19]]);
let compression_str = if compression_raw > 256 {
// FourCC: stored as little-endian, display as string
let bytes = [cd[16], cd[17], cd[18], cd[19]];
crate::encoding::decode_utf8_or_latin1(&bytes).to_uppercase()
} else {
match compression_raw {
0 => "None".into(),
1 => "8-Bit RLE".into(),
2 => "4-Bit RLE".into(),
3 => "Bitfields".into(),
4 => "JPEG".into(),
5 => "PNG".into(),
_ => format!("{}", compression_raw),
}
};
tags.push(mk_riff(
family,
"Compression",
"Compression",
Value::String(compression_str),
));
// ImageLength at offset 20 (int32u)
let image_length = u32::from_le_bytes([cd[20], cd[21], cd[22], cd[23]]);
tags.push(mk_riff(
family,
"ImageLength",
"Image Length",
Value::U32(image_length),
));
// PixelsPerMeterX at offset 24
let ppm_x = u32::from_le_bytes([cd[24], cd[25], cd[26], cd[27]]);
tags.push(mk_riff(
family,
"PixelsPerMeterX",
"Pixels Per Meter X",
Value::U32(ppm_x),
));
// PixelsPerMeterY at offset 28
let ppm_y = u32::from_le_bytes([cd[28], cd[29], cd[30], cd[31]]);
tags.push(mk_riff(
family,
"PixelsPerMeterY",
"Pixels Per Meter Y",
Value::U32(ppm_y),
));
// NumColors at offset 32
let num_colors = u32::from_le_bytes([cd[32], cd[33], cd[34], cd[35]]);
let num_colors_str = if num_colors == 0 {
"Use BitDepth".to_string()
} else {
format!("{}", num_colors)
};
tags.push(mk_riff(
family,
"NumColors",
"Num Colors",
Value::String(num_colors_str),
));
// NumImportantColors at offset 36
let num_important = u32::from_le_bytes([cd[36], cd[37], cd[38], cd[39]]);
let num_important_str = if num_important == 0 {
"All".to_string()
} else {
format!("{}", num_important)
};
tags.push(mk_riff(
family,
"NumImportantColors",
"Num Important Colors",
Value::String(num_important_str),
));
}
/// Parse broadcast audio extension chunk (bext)
fn parse_bext(
data: &[u8],
start: usize,
end: usize,
chunk_size: usize,
tags: &mut Vec<Tag>,
family: &str,
) {
if chunk_size < 256 {
return;
}
let cd = &data[start..end];
// Description: 256 bytes at offset 0
let description = crate::encoding::decode_utf8_or_latin1(&cd[..256.min(cd.len())])
.trim_end_matches('\0')
.to_string();
if !description.is_empty() {
tags.push(mk_riff(
family,
"Description",
"Description",
Value::String(description),
));
}
if cd.len() >= 288 {
// Originator: 32 bytes at offset 256
let originator = crate::encoding::decode_utf8_or_latin1(&cd[256..288])
.trim_end_matches('\0')
.to_string();
if !originator.is_empty() {
tags.push(mk_riff(
family,
"Originator",
"Originator",
Value::String(originator),
));
}
}
if cd.len() >= 320 {
// OriginatorReference: 32 bytes at offset 288
let orig_ref = crate::encoding::decode_utf8_or_latin1(&cd[288..320])
.trim_end_matches('\0')
.to_string();
if !orig_ref.is_empty() {
tags.push(mk_riff(
family,
"OriginatorReference",
"Originator Reference",
Value::String(orig_ref),
));
}
}
if cd.len() >= 338 {
// DateTimeOriginal: 18 bytes at offset 320 (format: "YYYY-MM-DD HH:MM:SS")
let dt_str = crate::encoding::decode_utf8_or_latin1(&cd[320..338])
.trim_end_matches('\0')
.to_string();
if !dt_str.is_empty() {
// Convert YYYY-MM-DD to YYYY:MM:DD
let converted = dt_str.replace('-', ":");
let converted = if converted.len() >= 10 {
format!("{} {}", &converted[..10], &converted[10..].trim())
} else {
converted
};
tags.push(mk_riff(
family,
"DateTimeOriginal",
"Date/Time Original",
Value::String(converted.trim().to_string()),
));
}
}
}
/// Read Pentax AVI sub-chunks from LIST hydt or LIST pntx.
/// Contains hymn or mknt chunks with Pentax MakerNotes (Pentax::Main IFD).
/// Mirrors Perl: LIST_hydt => PentaxData => TagTable Pentax::AVI => hymn => MakerNotes.
fn read_pentax_avi_chunks(
data: &[u8],
start: usize,
end: usize,
tags: &mut Vec<Tag>,
) -> Result<()> {
let mut pos = start;
while pos + 8 <= end {
let chunk_id = &data[pos..pos + 4];
let chunk_size =
u32::from_le_bytes([data[pos + 4], data[pos + 5], data[pos + 6], data[pos + 7]])
as usize;
let data_start = pos + 8;
let data_end = (data_start + chunk_size).min(end);
if data_start > end {
break;
}
match chunk_id {
b"hymn" | b"mknt" => {
// Pentax MakerNotes: data starts with "PENTAX \0" header (8 bytes),
// then byte-order mark (MM or II, 2 bytes), IFD at offset 10.
// Base = start of chunk data (all pointers relative to chunk start).
let mn_data = &data[data_start..data_end];
if mn_data.len() >= 12 && mn_data.starts_with(b"PENTAX \0") {
// Detect byte order from bytes 8-9 (MM = big-endian, II = little-endian)
let bo = if mn_data[8] == b'M' && mn_data[9] == b'M' {
ByteOrderMark::BigEndian
} else {
ByteOrderMark::LittleEndian
};
let mn_tags = crate::metadata::makernotes::parse_makernotes(
mn_data,
0,
mn_data.len(),
"PENTAX",
"",
bo,
);
tags.extend(mn_tags);
}
}
_ => {}
}
pos = data_end + (chunk_size & 1);
}
Ok(())
}
/// Read LIST exif sub-chunks (EXIF 2.3 WAV metadata)
fn read_exif_list_chunks(
data: &[u8],
start: usize,
end: usize,
tags: &mut Vec<Tag>,
family: &str,
) -> Result<()> {
let mut pos = start;
while pos + 8 <= end {
let chunk_id = std::str::from_utf8(&data[pos..pos + 4]).unwrap_or("????");
let chunk_size =
u32::from_le_bytes([data[pos + 4], data[pos + 5], data[pos + 6], data[pos + 7]])
as usize;
pos += 8;
if pos + chunk_size > end {
break;
}
let raw_bytes = &data[pos..pos + chunk_size];
let value = crate::encoding::decode_utf8_or_latin1(raw_bytes)
.trim_end_matches('\0')
.to_string();
if !value.is_empty() {
match chunk_id {
"ever" => tags.push(mk_riff(
family,
"ExifVersion",
"Exif Version",
Value::String(value),
)),
"erel" => tags.push(mk_riff(
family,
"RelatedImageFile",
"Related Image File",
Value::String(value),
)),
"etim" => tags.push(mk_riff(
family,
"TimeCreated",
"Time Created",
Value::String(value),
)),
"ecor" => tags.push(mk_riff(family, "Make", "Make", Value::String(value))),
"emdl" => tags.push(mk_riff(
family,
"Model",
"Camera Model Name",
Value::String(value),
)),
"emnt" => tags.push(mk_riff(
family,
"MakerNotes",
"Maker Notes",
Value::Binary(raw_bytes.to_vec()),
)),
"eucm" => tags.push(mk_riff(
family,
"UserComment",
"User Comment",
Value::String(value),
)),
_ => {}
}
}
pos += chunk_size + (chunk_size & 1);
}
Ok(())
}
/// Read INFO list chunks (RIFF metadata: IART, INAM, ICRD, etc.)
fn read_info_chunks(
data: &[u8],
start: usize,
end: usize,
tags: &mut Vec<Tag>,
family: &str,
) -> Result<()> {
let mut pos = start;
while pos + 8 <= end {
let chunk_id = std::str::from_utf8(&data[pos..pos + 4]).unwrap_or("????");
let chunk_size =
u32::from_le_bytes([data[pos + 4], data[pos + 5], data[pos + 6], data[pos + 7]])
as usize;
pos += 8;
if pos + chunk_size > end {
break;
}
let value = crate::encoding::decode_utf8_or_latin1(&data[pos..pos + chunk_size])
.trim_end_matches('\0')
.to_string();
if !value.is_empty() {
let (name, description) = info_chunk_name(chunk_id);
// ICRD: convert date separators from '-' to ':' (like Perl ExifTool ValueConv)
let value = if chunk_id == "ICRD" {
value.replace('-', ":")
} else {
value
};
tags.push(mk_riff(family, name, description, Value::String(value)));
}
pos += chunk_size + (chunk_size & 1);
}
Ok(())
}
/// Map RIFF INFO chunk IDs to tag names.
fn info_chunk_name(id: &str) -> (&str, &str) {
match id {
"IARL" => ("ArchivalLocation", "Archival Location"),
"IART" => ("Artist", "Artist"),
"ICMS" => ("Commissioned", "Commissioned"),
"ICMT" => ("Comment", "Comment"),
"ICOP" => ("Copyright", "Copyright"),
"ICRD" => ("DateCreated", "Date Created"),
"ICRP" => ("Cropped", "Cropped"),
"IDIM" => ("Dimensions", "Dimensions"),
"IDPI" => ("DotsPerInch", "Dots Per Inch"),
"IENG" => ("Engineer", "Engineer"),
"IGNR" => ("Genre", "Genre"),
"IKEY" => ("Keywords", "Keywords"),
"ILGT" => ("Lightness", "Lightness"),
"IMED" => ("Medium", "Medium"),
"INAM" => ("Title", "Title"),
"ITRK" => ("TrackNumber", "Track Number"),
"IPLT" => ("NumColors", "Num Colors"),
"IPRD" => ("Product", "Product"),
"ISBJ" => ("Subject", "Subject"),
"ISFT" => ("Software", "Software"),
"ISHP" => ("Sharpness", "Sharpness"),
"ISRC" => ("Source", "Source"),
"ISRF" => ("SourceForm", "Source Form"),
"ITCH" => ("Technician", "Technician"),
"ISGN" => ("SecondaryGenre", "Secondary Genre"),
"IWRI" => ("WrittenBy", "Written By"),
"IPRO" => ("ProducedBy", "Produced By"),
"ICNM" => ("Cinematographer", "Cinematographer"),
"IPDS" => ("ProductionDesigner", "Production Designer"),
"IEDT" => ("EditedBy", "Edited By"),
"ICDS" => ("CostumeDesigner", "Costume Designer"),
"IMUS" => ("MusicBy", "Music By"),
"ISTD" => ("ProductionStudio", "Production Studio"),
"IDST" => ("DistributedBy", "Distributed By"),
"ICNT" => ("Country", "Country"),
"ILNG" => ("Language", "Language"),
"IRTD" => ("Rating", "Rating"),
"ISTR" => ("Starring", "Starring"),
"TITL" => ("Title", "Title"),
"DIRC" => ("Directory", "Directory"),
"YEAR" => ("Year", "Year"),
"GENR" => ("Genre", "Genre"),
"COMM" => ("Comments", "Comments"),
"LANG" => ("Language", "Language"),
"AGES" => ("Rated", "Rated"),
"STAR" => ("Starring", "Starring"),
"CODE" => ("EncodedBy", "Encoded By"),
"PRT1" => ("Part", "Part"),
"PRT2" => ("NumberOfParts", "Number Of Parts"),
"IDIT" => ("DateTimeOriginal", "Date/Time Original"),
"ISMP" => ("TimeCode", "Time Code"),
"DISP" => ("SoundSchemeTitle", "Sound Scheme Title"),
"TLEN" => ("Length", "Length"),
"TRCK" => ("TrackNumber", "Track Number"),
"TURL" => ("URL", "URL"),
"TVER" => ("Version", "Version"),
"LOCA" => ("Location", "Location"),
"TORG" => ("Organization", "Organization"),
"TAPE" => ("TapeName", "Tape Name"),
"CMNT" => ("Comment", "Comment"),
"RATE" => ("Rate", "Rate"),
"IENC" => ("EncodedBy", "Encoded By"),
"IRIP" => ("RippedBy", "Ripped By"),
_ => (id, id),
}
}
/// Map audio format tag to encoding name (TwoCC)
fn audio_encoding_name(format_tag: u16) -> &'static str {
match format_tag {
0x0001 => "Microsoft PCM",
0x0002 => "Microsoft ADPCM",
0x0003 => "Microsoft IEEE float",
0x0004 => "Compaq VSELP",
0x0005 => "IBM CVSD",
0x0006 => "Microsoft a-Law",
0x0007 => "Microsoft u-Law",
0x0008 => "Microsoft DTS",
0x0009 => "DRM",
0x000a => "WMA 9 Speech",
0x000b => "Microsoft Windows Media RT Voice",
0x0010 => "OKI-ADPCM",
0x0011 => "Intel IMA/DVI-ADPCM",
0x0050 => "Microsoft MPEG",
0x0055 => "MP3",
0x00ff => "AAC",
0x0161 => "Windows Media Audio V2 V7 V8 V9 / DivX audio (WMA) / Alex AC3 Audio",
0x0162 => "Windows Media Audio Professional V9",
0x0163 => "Windows Media Audio Lossless V9",
0xfffe => "Extensible",
0xffff => "Development",
_ => "Unknown",
}
}
/// Convert RIFF date string to EXIF format (YYYY:MM:DD HH:MM:SS)
fn convert_riff_date(val: &str) -> String {
let months = [
"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
];
let parts: Vec<&str> = val.split_whitespace().collect();
// Format: "Mon Mar 10 15:04:43 2003"
if parts.len() >= 5 {
let month_lower = parts[1].to_lowercase();
if let Some(mon_idx) = months.iter().position(|&m| m == month_lower) {
if let (Ok(day), Ok(year)) = (parts[2].parse::<u32>(), parts[4].parse::<u32>()) {
return format!("{:04}:{:02}:{:02} {}", year, mon_idx + 1, day, parts[3]);
}
}
}
// Format: "YYYY/MM/DD HH:MM" or "YYYY/MM/DD/ HH:MM"
if let Some(cap) = parse_casio_date(val) {
return cap;
}
// Format: "YYYY-MM-DD HH:MM:SS" or "YYYY/MM/DD HH:MM:SS"
let normalized = val.replace(['/', '-'], ":");
if let Some(colon_pos) = normalized.find(' ') {
let date_part = &normalized[..colon_pos];
let time_part = normalized[colon_pos + 1..].trim();
if date_part.len() == 10 {
return format!("{} {}", date_part, time_part);
}
}
val.to_string()
}
fn parse_casio_date(val: &str) -> Option<String> {
// Perl pattern: m{(\d{4})/\s*(\d+)/\s*(\d+)/?\s+(\d+):\s*(\d+)\s*(P?)}
// Casio/Pentax AVI format: "YYYY/MM/DD HH:MM:SS" — only HH:MM is captured (seconds dropped)
// e.g. "2009/10/27 12:14:34" → "2009:10:27 12:14:00"
// e.g. "2001/ 1/27 1:42PM" → "2001:01:27 13:42:00"
// e.g. "2005/11/28/ 09:19" → "2005:11:28 09:19:00"
let bytes = val.as_bytes();
let len = bytes.len();
// Parse YYYY
if len < 4 || !bytes[0..4].iter().all(|b| b.is_ascii_digit()) {
return None;
}
let year: u32 = val[0..4].parse().ok()?;
let mut pos = 4;
if pos >= len || bytes[pos] != b'/' {
return None;
}
pos += 1;
// Skip optional spaces
while pos < len && bytes[pos] == b' ' {
pos += 1;
}
// Parse MM
let month_start = pos;
while pos < len && bytes[pos].is_ascii_digit() {
pos += 1;
}
if pos == month_start {
return None;
}
let month: u32 = val[month_start..pos].parse().ok()?;
if pos >= len || bytes[pos] != b'/' {
return None;
}
pos += 1;
// Skip optional spaces
while pos < len && bytes[pos] == b' ' {
pos += 1;
}
// Parse DD
let day_start = pos;
while pos < len && bytes[pos].is_ascii_digit() {
pos += 1;
}
if pos == day_start {
return None;
}
let day: u32 = val[day_start..pos].parse().ok()?;
// Skip optional trailing '/'
if pos < len && bytes[pos] == b'/' {
pos += 1;
}
// Skip whitespace
while pos < len && bytes[pos] == b' ' {
pos += 1;
}
if pos >= len {
return None;
}
// Parse HH
let hh_start = pos;
while pos < len && bytes[pos].is_ascii_digit() {
pos += 1;
}
if pos == hh_start {
return None;
}
let hh: u32 = val[hh_start..pos].parse().ok()?;
if pos >= len || bytes[pos] != b':' {
return None;
}
pos += 1;
// Skip optional spaces
while pos < len && bytes[pos] == b' ' {
pos += 1;
}
// Parse MM (minutes)
let mm_start = pos;
while pos < len && bytes[pos].is_ascii_digit() {
pos += 1;
}
if pos == mm_start {
return None;
}
let mm: u32 = val[mm_start..pos].parse().ok()?;
// Skip optional spaces and check for PM
while pos < len && bytes[pos] == b' ' {
pos += 1;
}
let pm = pos < len && (bytes[pos] == b'P' || bytes[pos] == b'p');
let hh_final = if pm { hh + 12 } else { hh };
Some(format!(
"{:04}:{:02}:{:02} {:02}:{:02}:00",
year, month, day, hh_final, mm
))
}
/// Format duration in seconds like ExifTool's ConvertDuration
fn format_duration(seconds: f64) -> String {
// ExifTool uses ConvertDuration which formats as "H:MM:SS" or fractional seconds
// For small values, it may output "0.03 s" style.
// Looking at the test output: "15.53 s" for AVI, "0.03 s" for WAV
// ExifTool PrintConv for Duration composite calls ConvertDuration()
// which outputs "H:MM:SS.ss" format for values >= 60s, else "S.ss s"
if seconds < 60.0 {
// round to 2 decimal places
let rounded = (seconds * 100.0 + 0.5).floor() / 100.0;
format!("{:.2} s", rounded)
} else {
let hours = (seconds / 3600.0).floor() as u64;
let remaining = seconds - hours as f64 * 3600.0;
let minutes = (remaining / 60.0).floor() as u64;
let secs = remaining - minutes as f64 * 60.0;
if hours > 0 {
format!("{}:{:02}:{:05.2}", hours, minutes, secs)
} else {
format!("{}:{:05.2}", minutes, secs)
}
}
}
/// Format a float value with ~4 significant digits followed by a unit (like Perl's sprintf("%.4g %s"))
fn format_sig4(val: f64, unit: &str) -> String {
// Implement %.4g: use at most 4 significant figures, no trailing zeros
if val == 0.0 {
return format!("0 {}", unit);
}
let magnitude = val.abs().log10().floor() as i32;
let decimals = if magnitude >= 3 {
0
} else {
(3 - magnitude).max(0) as usize
};
let s = format!("{:.prec$}", val, prec = decimals);
// Remove trailing zeros after decimal point
let s = if s.contains('.') {
s.trim_end_matches('0').trim_end_matches('.').to_string()
} else {
s
};
format!("{} {}", s, unit)
}
fn mk_webp(name: &str, description: &str, value: Value) -> Tag {
let print_value = value.to_display_string();
Tag {
id: TagId::Text(name.to_string()),
name: name.to_string(),
description: description.to_string(),
group: TagGroup {
family0: "RIFF".into(),
family1: "WebP".into(),
family2: "Image".into(),
},
raw_value: value,
print_value,
priority: 0,
}
}
fn mk_riff(family: &str, name: &str, description: &str, value: Value) -> Tag {
let print_value = value.to_display_string();
Tag {
id: TagId::Text(name.to_string()),
name: name.to_string(),
description: description.to_string(),
group: TagGroup {
family0: "RIFF".into(),
family1: family.into(),
family2: if family == "AVI" {
"Video".into()
} else {
"Audio".into()
},
},
raw_value: value,
print_value,
priority: 0,
}
}