libflo-audio 0.1.3

The official encoder/decoder for the flo audio format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
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
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
#![cfg_attr(not(test), no_std)]
#![allow(clippy::needless_range_loop)]

extern crate alloc;

#[cfg(feature = "wasm")]
use alloc::format;
#[cfg(feature = "wasm")]
use alloc::string::String;
#[cfg(feature = "wasm")]
use alloc::string::ToString;
#[cfg(feature = "wasm")]
use alloc::vec;
use alloc::vec::Vec;
#[cfg(feature = "wasm")]
use messagepack_serde::{from_slice, to_vec};
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;

pub mod core;
pub mod dsp;
pub mod lossless;
pub mod lossy;
pub mod streaming;

mod reader;
pub mod seeking;
mod writer;

pub use core::{
    compute_crc32, compute_ebu_r128_loudness, extract_spectral_fingerprint, extract_waveform_peaks,
    metadata::*, rice, ChannelData, FloError, FloErrorExt, FloErrorKind, FloFile, FloResult,
    FrameType, LoudnessMetrics, ResidualEncoding, HEADER_SIZE, MAGIC, VERSION_MAJOR, VERSION_MINOR,
};
pub use lossless::{lpc, Decoder, Encoder};
pub use lossy::{
    deserialize_frame, serialize_frame, BlockSize, Mdct, PsychoacousticModel, QualityPreset,
    TransformDecoder as LossyDecoder, TransformEncoder as LossyEncoder, TransformFrame, WindowType,
    FRAME_COEFFICIENTS, LONG_BLOCK_SIZE, SHORTS_PER_GROUP, SHORT_BLOCK_SIZE, SHORT_GROUP_OFFSET,
};
pub use reader::Reader;
pub use streaming::{
    DecoderState, EncodedFrame, StreamingAudioInfo, StreamingDecoder, StreamingEncoder,
};
pub use writer::Writer;

// audio info for the info() function

/// info about a flo file
#[cfg(feature = "wasm")]
#[wasm_bindgen]
#[derive(Debug, Clone)]
pub struct AudioInfo {
    /// version string like "1.2"
    #[wasm_bindgen(skip)]
    pub version: String,
    /// Sample rate in Hz
    pub sample_rate: u32,
    /// Number of channels
    pub channels: u8,
    /// Bits per sample
    pub bit_depth: u8,
    /// Total sample-frames (samples per channel). This is the number of sample
    /// instants per channel (not interleaved samples). Use metadata.length_ms
    /// for a quick duration lookup.
    pub total_samples: u64,
    /// Duration in seconds
    pub duration_secs: f64,
    /// File size in bytes
    pub file_size: usize,
    /// Compression ratio (original / compressed)
    pub compression_ratio: f64,
    /// Is CRC valid?
    pub crc_valid: bool,
    /// Is lossy compression mode?
    pub is_lossy: bool,
    /// Lossy quality 0-4 (only valid if is_lossy)
    pub lossy_quality: u8,
}

#[cfg(feature = "wasm")]
#[wasm_bindgen]
impl AudioInfo {
    #[wasm_bindgen(getter)]
    pub fn version(&self) -> String {
        self.version.clone()
    }
}

// result helpers

/// turn an error into js
#[cfg(feature = "wasm")]
fn to_js_err(e: impl ::core::fmt::Display) -> JsValue {
    JsValue::from_str(&e.to_string())
}

// api functions

/// encode samples to flo lossless
///
/// # Arguments
/// * `samples` - Interleaved audio samples (f32, -1.0 to 1.0)
/// * `sample_rate` - Sample rate in Hz (e.g., 44100)
/// * `channels` - Number of channels (1 or 2)
/// * `bit_depth` - Bits per sample (16, 24, or 32)
/// * `metadata` - Optional MessagePack metadata
///
/// # Returns
/// flo file as byte array
///
/// # Note
/// For advanced usage with custom compression levels (0-9),
/// use the `Encoder` builder pattern directly.
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn encode(
    samples: &[f32],
    sample_rate: u32,
    channels: u8,
    bit_depth: u8,
    metadata: Option<Vec<u8>>,
) -> Result<Vec<u8>, JsValue> {
    validate_audio_format(samples, sample_rate, channels, bit_depth).map_err(to_js_err)?;

    // Auto-add analysis data if missing
    let metadata_with_waveform = add_analysis_data_if_missing(
        &metadata.unwrap_or_default(),
        samples,
        sample_rate,
        channels,
        50, // 50 peaks per second default
    )
    .map_err(to_js_err)?;

    let encoder = Encoder::new(sample_rate, channels, bit_depth);
    encoder
        .encode(samples, &metadata_with_waveform)
        .map_err(to_js_err)
}

/// encode samples to flo lossy
///
/// # Arguments
/// * `samples` - Interleaved audio samples (f32, -1.0 to 1.0)
/// * `sample_rate` - Sample rate in Hz (e.g., 44100)
/// * `channels` - Number of audio channels (1 or 2)
/// * `bit_depth` - Bits per sample (typically 16)
/// * `quality` - Quality level 0-4 (0=low/~64kbps, 4=transparent/~320kbps)
/// * `metadata` - Optional MessagePack metadata
///
/// # Returns
/// flo file as byte array
///
/// # Note
/// For advanced usage with continuous quality control (0.0-1.0) or custom settings,
/// use the `LossyEncoder` builder pattern directly.
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn encode_lossy(
    samples: &[f32],
    sample_rate: u32,
    channels: u8,
    _bit_depth: u8,
    quality: u8,
    metadata: Option<Vec<u8>>,
) -> Result<Vec<u8>, JsValue> {
    validate_audio_format(samples, sample_rate, channels, _bit_depth).map_err(to_js_err)?;

    // quality levels to 0.0-1.0
    let quality_f32 = match quality {
        0 => 0.0,
        1 => 0.35,
        2 => 0.55,
        3 => 0.75,
        _ => 1.0,
    };

    // Auto-add analysis data if missing
    let metadata_with_waveform = add_analysis_data_if_missing(
        &metadata.unwrap_or_default(),
        samples,
        sample_rate,
        channels,
        50, // 50 peaks per second default
    )
    .map_err(to_js_err)?;

    let mut encoder = lossy::TransformEncoder::new(sample_rate, channels, quality_f32);
    encoder
        .encode_to_flo(samples, &metadata_with_waveform)
        .map_err(to_js_err)
}

/// encode to flo lossy with target bitrate
///
/// # Arguments
/// * `samples` - Interleaved audio samples (f32, -1.0 to 1.0)
/// * `sample_rate` - Sample rate in Hz (e.g., 44100)
/// * `channels` - Number of audio channels
/// * `bit_depth` - Bits per sample (16, 24, or 32)
/// * `target_bitrate_kbps` - Target bitrate in kbps (e.g., 128, 192, 256, 320)
/// * `metadata` - Optional MessagePack metadata
///
/// # Returns
/// flo file as byte array
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn encode_with_bitrate(
    samples: &[f32],
    sample_rate: u32,
    channels: u8,
    _bit_depth: u8,
    target_bitrate_kbps: u32,
    metadata: Option<Vec<u8>>,
) -> Result<Vec<u8>, JsValue> {
    validate_audio_format(samples, sample_rate, channels, _bit_depth).map_err(to_js_err)?;

    // bitrate to quality
    let quality =
        lossy::QualityPreset::from_bitrate(target_bitrate_kbps, sample_rate, channels).as_f32();

    // Auto-add analysis data if missing
    let metadata_with_waveform = add_analysis_data_if_missing(
        &metadata.unwrap_or_default(),
        samples,
        sample_rate,
        channels,
        50, // 50 peaks per second default
    )
    .map_err(to_js_err)?;

    let mut encoder = lossy::TransformEncoder::new(sample_rate, channels, quality);
    encoder
        .encode_to_flo(samples, &metadata_with_waveform)
        .map_err(to_js_err)
}

/// Add analysis data to metadata if not present
///
/// # Arguments
/// * `metadata` - MessagePack metadata bytes
/// * `samples` - Audio samples (interleaved)
/// * `sample_rate` - Sample rate in Hz
/// * `channels` - Number of audio channels
/// * `peaks_per_second` - Number of peaks per second (default: 50)
///
/// # Returns
/// Updated metadata with analysis data (waveform, spectrum, loudness)
#[cfg(feature = "wasm")]
fn validate_audio_format(
    samples: &[f32],
    sample_rate: u32,
    channels: u8,
    bit_depth: u8,
) -> Result<(), String> {
    if sample_rate == 0 {
        return Err("Sample rate must be greater than zero".to_string());
    }
    if channels == 0 {
        return Err("Channel count must be greater than zero".to_string());
    }
    if !matches!(bit_depth, 8 | 16 | 24 | 32) {
        return Err("Bit depth must be 8, 16, 24, or 32".to_string());
    }
    if !samples.len().is_multiple_of(channels as usize) {
        return Err("Interleaved samples must contain a complete final frame".to_string());
    }
    Ok(())
}

#[cfg(feature = "wasm")]
fn add_analysis_data_if_missing(
    metadata: &[u8],
    samples: &[f32],
    sample_rate: u32,
    channels: u8,
    peaks_per_second: u32,
) -> Result<Vec<u8>, String> {
    // Try to parse existing metadata
    let mut flo_metadata: FloMetadata = if !metadata.is_empty() {
        from_slice(metadata).map_err(|e| format!("Invalid metadata: {}", e))?
    } else {
        FloMetadata::default()
    };

    // Add waveform data if not present
    if flo_metadata.waveform_data.is_none() {
        let waveform = core::analysis::extract_waveform_peaks(
            samples,
            channels,
            sample_rate,
            peaks_per_second,
        );
        flo_metadata.waveform_data = Some(waveform);
    }

    // Add spectral fingerprint if not present
    if flo_metadata.spectrum_fingerprint.is_none() {
        let spectral_fingerprint = core::analysis::extract_spectral_fingerprint(
            samples,
            channels,
            sample_rate,
            Some(2048), // Default FFT size
            Some(1024), // Default hop size for 50% overlap
        );

        // Convert spectral data to bytes for storage
        if let Ok(spectral_bytes) = messagepack_serde::to_vec(&spectral_fingerprint) {
            flo_metadata.spectrum_fingerprint = Some(spectral_bytes);
        }
    }

    // Add loudness metrics if not present
    if flo_metadata.loudness_profile.is_empty() {
        let loudness_metrics =
            core::ebu_r128::compute_ebu_r128_loudness(samples, channels, sample_rate);

        // Convert loudness metrics to LoudnessPoint format
        let loudness_point = core::metadata::LoudnessPoint {
            timestamp_ms: 0,
            lufs: loudness_metrics.integrated_lufs as f32,
        };

        flo_metadata.loudness_profile = vec![loudness_point];
    }

    // Always set length_ms (duration in milliseconds).
    // `samples` is interleaved (L,R,L,R...)
    let interleaved_len = samples.len() as u64;
    let samples_per_channel = interleaved_len / (channels as u64);
    let length_ms = (((samples_per_channel as f64) / (sample_rate as f64)) * 1000.0) as u64;
    flo_metadata.length_ms = Some(length_ms);

    // Serialize back to bytes
    to_vec(&flo_metadata).map_err(|e| format!("Failed to serialize metadata: {}", e))
}

/// decode flo file to samples
///
/// This automatically detects whether the file uses lossless or lossy encoding
/// and dispatches to the appropriate decoder.
///
/// # Arguments
/// * `data` - flo file bytes
///
/// # Returns
/// Interleaved audio samples (f32, -1.0 to 1.0)
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn decode(data: &[u8]) -> Result<Vec<f32>, JsValue> {
    // figure out if its transform/lossy
    let reader = Reader::new();
    let file = reader.read(data).map_err(to_js_err)?;

    // any transform frames means lossy
    let is_transform = file
        .frames
        .iter()
        .any(|f| f.frame_type == (FrameType::Transform as u8));

    if is_transform {
        // lossy
        decode_transform_file(&file).map_err(to_js_err)
    } else {
        // lossless
        let decoder = Decoder::new();
        decoder.decode_file(&file).map_err(to_js_err)
    }
}

/// Decode a lossy flo file that uses transform-based compression
///
/// # Arguments
/// * `file` - Parsed flo file
///
/// # Returns
/// Interleaved audio samples (f32, -1.0 to 1.0)
/// Decode a transform-based lossy file
#[cfg(feature = "wasm")]
fn decode_transform_file(file: &FloFile) -> FloResult<Vec<f32>> {
    let mut decoder = lossy::TransformDecoder::new(file.header.sample_rate, file.header.channels);
    let mut all_samples = Vec::new();
    let mut frame_count = 0;

    for frame in &file.frames {
        if frame.channels.is_empty() {
            continue;
        }

        // transform data is in first channels residuals
        let frame_data = &frame.channels[0].residuals;

        if let Some(transform_frame) = lossy::deserialize_frame(frame_data) {
            let samples = decoder.decode_frame(&transform_frame);

            // skip first frame (pre-roll for overlap-add)
            if frame_count > 0 {
                all_samples.extend(samples);
            }
            frame_count += 1;
        } else {
            return Err(crate::core::FloError::from(
                "Failed to deserialize transform frame",
            ));
        }
    }

    Ok(all_samples)
}

/// Validate flo file integrity
///
/// # Arguments
/// * `data` - flo file bytes
///
/// # Returns
/// true if file is valid and CRC matches
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn validate(data: &[u8]) -> Result<bool, JsValue> {
    let reader = Reader::new();
    match reader.read(data) {
        Ok(file) => {
            let start = (4 + file.header.header_size + file.header.toc_size) as usize;
            let end = start + (file.header.data_size as usize);
            if end <= data.len() {
                let computed = core::crc32::compute(&data[start..end]);
                Ok(computed == file.header.data_crc32)
            } else {
                Ok(false)
            }
        }
        Err(_) => Ok(false),
    }
}

/// Get information about a flo file
///
/// # Arguments
/// * `data` - flo file bytes
///
/// # Returns
/// AudioInfo struct with file details
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn info(data: &[u8]) -> Result<AudioInfo, JsValue> {
    let reader = Reader::new();
    let file = reader.read(data).map_err(to_js_err)?;

    // Use length_ms from metadata for duration
    let metadata = FloMetadata::from_msgpack(&file.metadata).unwrap_or_default();
    let duration_secs = metadata
        .length_ms
        .map(|ms| (ms as f64) / 1000.0)
        .unwrap_or_else(|| {
            // Fallback: calculate from total_samples / sample_rate
            (file.header.total_samples as f64) / (file.header.sample_rate as f64)
        });

    // Calculate original size from total_samples (actual sample count in header)
    let original_size = ((file.header.total_samples as f64)
        * (file.header.channels as f64)
        * ((file.header.bit_depth as f64) / 8.0)) as usize;
    let compression_ratio = if !data.is_empty() {
        (original_size as f64) / (data.len() as f64)
    } else {
        0.0
    };

    // check crc
    let start = (4 + file.header.header_size + file.header.toc_size) as usize;
    let end = start + (file.header.data_size as usize);
    let crc_valid = if end <= data.len() {
        core::crc32::compute(&data[start..end]) == file.header.data_crc32
    } else {
        false
    };

    // lossy mode from flags
    let is_lossy = (file.header.flags & 0x01) != 0;
    let lossy_quality = ((file.header.flags >> 8) & 0x0f) as u8;

    Ok(AudioInfo {
        version: format!(
            "{}.{}",
            file.header.version_major, file.header.version_minor
        ),
        sample_rate: file.header.sample_rate,
        channels: file.header.channels,
        bit_depth: file.header.bit_depth,
        total_samples: file.header.total_samples,
        duration_secs,
        file_size: data.len(),
        compression_ratio,
        crc_valid,
        is_lossy,
        lossy_quality,
    })
}

/// get lib version
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn version() -> String {
    format!("{}.{}", VERSION_MAJOR, VERSION_MINOR)
}

/// Format time in seconds to MM:SS or H:MM:SS string
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn format_time(seconds: f64) -> String {
    if !seconds.is_finite() || seconds < 0.0 {
        return "0:00".to_string();
    }

    let total_secs = seconds.floor() as u64;
    let hours = total_secs / 3600;
    let mins = (total_secs % 3600) / 60;
    let secs = total_secs % 60;

    if hours > 0 {
        format!("{}:{:02}:{:02}", hours, mins, secs)
    } else {
        format!("{}:{:02}", mins, secs)
    }
}

/// Format time in milliseconds to MM:SS or H:MM:SS string
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn format_time_ms(milliseconds: f64) -> String {
    format_time(milliseconds / 1000.0)
}

/// Extract TOC (Table of Contents) entries from a flo file
///
/// # Returns
/// Array of TOC entries with frame indices, byte offsets, and timestamps
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn get_toc(flo_data: &[u8]) -> Result<Vec<JsValue>, JsValue> {
    let toc = seeking::get_toc(flo_data).map_err(to_js_err)?;
    let result = toc
        .into_iter()
        .map(|entry| {
            let obj = js_sys::Object::new();
            js_sys::Reflect::set(&obj, &"frame_index".into(), &entry.frame_index.into()).ok();
            js_sys::Reflect::set(
                &obj,
                &"byte_offset".into(),
                &(entry.byte_offset as f64).into(),
            )
            .ok();
            js_sys::Reflect::set(&obj, &"frame_size".into(), &entry.frame_size.into()).ok();
            js_sys::Reflect::set(&obj, &"timestamp_ms".into(), &entry.timestamp_ms.into()).ok();
            obj.into()
        })
        .collect();
    Ok(result)
}

/// Decode a single frame by index without decoding the entire file
///
/// # Arguments
/// * `flo_data` - Complete flo file bytes
/// * `frame_index` - Zero-based frame index
///
/// # Returns
/// Interleaved audio samples for that frame (f32, -1.0 to 1.0)
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn decode_frame_at(flo_data: &[u8], frame_index: u32) -> Result<Vec<f32>, JsValue> {
    seeking::decode_frame_at(flo_data, frame_index).map_err(to_js_err)
}

/// Seek to a specific time in milliseconds
///
/// # Arguments
/// * `flo_data` - Complete flo file bytes
/// * `time_ms` - Target time in milliseconds
///
/// # Returns
/// Seek result object containing frame index, byte offset, timestamp, sample offset, and next timestamp.
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn seek_to_time(flo_data: &[u8], time_ms: u32) -> Result<JsValue, JsValue> {
    let result = seeking::seek_to_time(flo_data, time_ms).map_err(to_js_err)?;

    let obj = js_sys::Object::new();
    js_sys::Reflect::set(&obj, &"frame_index".into(), &result.frame_index.into())?;
    js_sys::Reflect::set(
        &obj,
        &"byte_offset".into(),
        &(result.byte_offset as f64).into(),
    )?;
    js_sys::Reflect::set(&obj, &"timestamp_ms".into(), &result.timestamp_ms.into())?;
    js_sys::Reflect::set(&obj, &"sample_offset".into(), &result.sample_offset.into())?;
    js_sys::Reflect::set(
        &obj,
        &"next_timestamp_ms".into(),
        &result.next_timestamp_ms.into(),
    )?;

    Ok(obj.into())
}

// streaming decoder wasm api

#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub struct WasmStreamingDecoder {
    inner: StreamingDecoder,
}

#[cfg(feature = "wasm")]
#[wasm_bindgen]
impl WasmStreamingDecoder {
    /// new streaming decoder
    #[wasm_bindgen(constructor)]
    pub fn new() -> Self {
        Self {
            inner: StreamingDecoder::new(),
        }
    }

    /// feed data to the decoder, call as bytes come in from network
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn feed(&mut self, data: &[u8]) -> Result<bool, JsValue> {
        self.inner.feed(data).map_err(to_js_err)
    }

    /// Check if the decoder is ready to produce audio
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn is_ready(&self) -> bool {
        self.inner.state() == DecoderState::Ready
    }

    /// stream done?
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn is_finished(&self) -> bool {
        self.inner.state() == DecoderState::Finished
    }

    /// Check if there was an error
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn has_error(&self) -> bool {
        self.inner.state() == DecoderState::Error
    }

    /// Get the current state as a string
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn state(&self) -> String {
        match self.inner.state() {
            DecoderState::WaitingForHeader => "waiting_for_header".into(),
            DecoderState::WaitingForToc => "waiting_for_toc".into(),
            DecoderState::Ready => "ready".into(),
            DecoderState::Finished => "finished".into(),
            DecoderState::Error => "error".into(),
        }
    }

    /// Get audio information (available after header is parsed)
    ///
    /// Returns null if header hasn't been parsed yet.
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn get_info(&self) -> Result<JsValue, JsValue> {
        match self.inner.info() {
            Some(info) => {
                let obj = js_sys::Object::new();
                js_sys::Reflect::set(&obj, &"sample_rate".into(), &info.sample_rate.into())?;
                js_sys::Reflect::set(&obj, &"channels".into(), &info.channels.into())?;
                js_sys::Reflect::set(&obj, &"bit_depth".into(), &info.bit_depth.into())?;
                js_sys::Reflect::set(
                    &obj,
                    &"total_samples".into(),
                    &(info.total_samples as f64).into(),
                )?;
                js_sys::Reflect::set(&obj, &"is_lossy".into(), &info.is_lossy.into())?;
                Ok(obj.into())
            }
            None => Ok(JsValue::NULL),
        }
    }

    /// decode all currently available samples
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn decode_available(&mut self) -> Result<Vec<f32>, JsValue> {
        self.inner.decode_available().map_err(to_js_err)
    }

    /// Decode the next available frame
    ///
    /// Returns interleaved f32 samples for one frame, or null if no frame is ready.
    /// This enables true streaming: decode and play frames as they arrive.
    ///
    /// Usage pattern:
    /// ```js
    /// while (true) {
    ///     const samples = decoder.next_frame();
    ///     if (samples === null) break; // No more frames ready
    ///     playAudio(samples);
    /// }
    /// ```
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn next_frame(&mut self) -> Result<JsValue, JsValue> {
        match self.inner.next_frame() {
            Ok(Some(samples)) => {
                let array = js_sys::Float32Array::new_with_length(samples.len() as u32);
                array.copy_from(&samples);
                Ok(array.into())
            }
            Ok(None) => Ok(JsValue::NULL),
            Err(e) => Err(to_js_err(e)),
        }
    }

    /// how many frames ready to decode
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn available_frames(&self) -> usize {
        self.inner.available_frames()
    }

    /// current frame index
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn current_frame_index(&self) -> usize {
        self.inner.current_frame_index()
    }

    /// Reset the decoder to initial state
    ///
    /// Use this to start decoding a new stream.
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn reset(&mut self) {
        self.inner.reset();
    }

    /// bytes currently buffered
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn buffered_bytes(&self) -> usize {
        self.inner.buffered_bytes()
    }
}

#[cfg(feature = "wasm")]
impl Default for WasmStreamingDecoder {
    fn default() -> Self {
        Self::new()
    }
}

/// Encodes samples frame-by-frame as they arrive, returning encoded frames ready for transmission.
/// Use this for low-latency streaming encoding where you push samples and pull frames.
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub struct WasmStreamingEncoder {
    inner: StreamingEncoder,
}

#[cfg(feature = "wasm")]
#[wasm_bindgen]
impl WasmStreamingEncoder {
    /// Create a new streaming encoder
    ///
    /// # Arguments
    /// * `sample_rate` - Sample rate in Hz (e.g., 44100)
    /// * `channels` - Number of channels (1 or 2)
    /// * `bit_depth` - Bits per sample (16, 24, or 32)
    ///
    /// # Returns
    /// New encoder instance
    #[wasm_bindgen(constructor)]
    pub fn new(sample_rate: u32, channels: u8, bit_depth: u8) -> Self {
        Self {
            inner: StreamingEncoder::new(sample_rate, channels, bit_depth),
        }
    }

    /// Set compression level (0-9)
    ///
    /// # Arguments
    /// * `level` - Compression level (0=fast/large, 9=slow/small)
    ///
    /// # Returns
    /// Self for method chaining
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn with_compression(mut self, level: u8) -> Self {
        self.inner = self.inner.with_compression(level);
        self
    }

    /// Push audio samples to the encoder
    ///
    /// Samples should be interleaved if multi-channel (e.g., [L0, R0, L1, R1, ...] for stereo).
    /// Frames are encoded automatically when enough samples accumulate.
    ///
    /// # Arguments
    /// * `samples` - Interleaved f32 audio samples (-1.0 to 1.0)
    ///
    /// # Returns
    /// Error if encoding fails
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn push_samples(&mut self, samples: &[f32]) -> Result<(), JsValue> {
        self.inner.push_samples(samples).map_err(to_js_err)
    }

    /// Get the next encoded frame if available
    ///
    /// Returns an object with: index, timestamp_ms, data (Uint8Array), samples
    /// Returns null if no frames are ready yet.
    ///
    /// # Returns
    /// Encoded frame object or null
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn next_frame(&mut self) -> JsValue {
        match self.inner.next_frame() {
            Some(frame) => {
                let obj = js_sys::Object::new();
                let _ = js_sys::Reflect::set(&obj, &"index".into(), &frame.index.into());
                let _ =
                    js_sys::Reflect::set(&obj, &"timestamp_ms".into(), &frame.timestamp_ms.into());
                let _ = js_sys::Reflect::set(
                    &obj,
                    &"data".into(),
                    &js_sys::Uint8Array::from(&frame.data[..]).into(),
                );
                let _ = js_sys::Reflect::set(&obj, &"samples".into(), &frame.samples.into());
                obj.into()
            }
            None => JsValue::NULL,
        }
    }

    /// Get number of samples currently buffered
    ///
    /// # Returns
    /// Number of sample frames in buffer
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn pending_samples(&self) -> usize {
        self.inner.pending_samples()
    }

    /// Get number of encoded frames ready for transmission
    ///
    /// # Returns
    /// Number of ready frames
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn pending_frames(&self) -> usize {
        self.inner.pending_frames()
    }

    /// Flush remaining samples and finalize encoding
    ///
    /// Call this when done pushing samples. Encodes any remaining partial frame.
    /// After this, call finalize() to get the complete flo file.
    ///
    /// # Returns
    /// Error if encoding fails
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn flush(&mut self) -> Result<(), JsValue> {
        self.inner.flush_into_frames().map_err(to_js_err)?;
        Ok(())
    }

    /// Build a complete flo file from all accumulated frames
    ///
    /// Call flush() first, then this method to generate the complete file.
    /// The file will contain all encoded frames with proper table-of-contents.
    ///
    /// # Arguments
    /// * `metadata` - Optional metadata bytes (MessagePack encoded, use create_metadata())
    ///
    /// # Returns
    /// Complete flo file as byte array
    #[cfg(feature = "wasm")]
    #[wasm_bindgen]
    pub fn finalize(&mut self, metadata: Option<Vec<u8>>) -> Result<Vec<u8>, JsValue> {
        let meta = metadata.unwrap_or_default();
        self.inner.finalize(&meta).map_err(to_js_err)
    }
}

#[cfg(feature = "wasm")]
impl Default for WasmStreamingEncoder {
    fn default() -> Self {
        Self {
            inner: StreamingEncoder::new(44100, 2, 16),
        }
    }
}

/// Create metadata from basic fields and serialize to MessagePack
///
/// # Arguments
/// * `title` - Optional title
/// * `artist` - Optional artist
/// * `album` - Optional album
///
/// # Returns
/// MessagePack bytes containing metadata
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn create_metadata(
    title: Option<String>,
    artist: Option<String>,
    album: Option<String>,
) -> Result<Vec<u8>, JsValue> {
    let meta = FloMetadata::with_basic(title, artist, album);
    meta.to_msgpack()
        .map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Create metadata from a JavaScript object
///
/// Accepts an object with any of the supported metadata fields.
/// See FloMetadata for available fields.
///
/// # Returns
/// MessagePack bytes containing metadata
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn create_metadata_from_object(obj: JsValue) -> Result<Vec<u8>, JsValue> {
    let meta: FloMetadata = serde_wasm_bindgen::from_value(obj)
        .map_err(|e| JsValue::from_str(&format!("Invalid metadata: {}", e)))?;
    meta.to_msgpack()
        .map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Extract metadata from a flo file
///
/// # Arguments
/// * `data` - flo file bytes
///
/// # Returns
/// JavaScript object with metadata fields (or null if no metadata)
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn get_metadata(data: &[u8]) -> Result<JsValue, JsValue> {
    let reader = Reader::new();
    let file = reader.read(data).map_err(to_js_err)?;

    if file.metadata.is_empty() {
        return Ok(JsValue::NULL);
    }

    let meta = FloMetadata::from_msgpack(&file.metadata)
        .map_err(|e| JsValue::from_str(&format!("Invalid metadata: {}", e)))?;

    serde_wasm_bindgen::to_value(&meta)
        .map_err(|e| JsValue::from_str(&format!("Serialization error: {}", e)))
}

/// Get cover art from a flo file
///
/// # Arguments
/// * `data` - flo file bytes
///
/// # Returns
/// Object with `mime_type` and `data` (Uint8Array) or null if no cover
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn get_cover_art(data: &[u8]) -> Result<JsValue, JsValue> {
    let reader = Reader::new();
    let file = reader.read(data).map_err(to_js_err)?;

    if file.metadata.is_empty() {
        return Ok(JsValue::NULL);
    }

    let meta = FloMetadata::from_msgpack(&file.metadata)
        .map_err(|e| JsValue::from_str(&format!("Invalid metadata: {}", e)))?;

    // try front cover first
    if let Some(pic) = meta.front_cover().or_else(|| meta.any_picture()) {
        let obj = js_sys::Object::new();
        js_sys::Reflect::set(&obj, &"mime_type".into(), &pic.mime_type.clone().into())?;
        js_sys::Reflect::set(
            &obj,
            &"data".into(),
            &js_sys::Uint8Array::from(&pic.data[..]).into(),
        )?;
        if let Some(ref desc) = pic.description {
            js_sys::Reflect::set(&obj, &"description".into(), &desc.clone().into())?;
        }
        Ok(obj.into())
    } else {
        Ok(JsValue::NULL)
    }
}

/// Set a single field in existing metadata bytes
///
/// Uses serde to dynamically set fields - field names match FloMetadata struct.
/// For complex fields (pictures, synced_lyrics, etc.) use create_metadata_from_object.
///
/// # Arguments
/// * `metadata` - Existing MessagePack metadata bytes (or empty for new)
/// * `field` - Field name (e.g., "title", "artist", "bpm")
/// * `value` - Field value (string, number, or null)
///
/// # Returns
/// Updated MessagePack metadata bytes
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn set_metadata_field(
    metadata: Option<Vec<u8>>,
    field: &str,
    value: JsValue,
) -> Result<Vec<u8>, JsValue> {
    // parse or create new
    let meta = match &metadata {
        Some(data) if !data.is_empty() => FloMetadata::from_msgpack(data)
            .map_err(|e| JsValue::from_str(&format!("Invalid metadata: {}", e)))?,
        _ => FloMetadata::new(),
    };

    // modify via serde
    let mut obj: serde_json::Value = serde_json::to_value(&meta)
        .map_err(|e| JsValue::from_str(&format!("Serialization error: {}", e)))?;

    // jsvalue to serde
    let json_value = if value.is_null() || value.is_undefined() {
        serde_json::Value::Null
    } else if let Some(s) = value.as_string() {
        serde_json::Value::String(s)
    } else if let Some(n) = value.as_f64() {
        serde_json::json!(n)
    } else if let Some(b) = value.as_bool() {
        serde_json::Value::Bool(b)
    } else {
        // try json for complex stuff
        let js_json = js_sys::JSON::stringify(&value)
            .map_err(|_| JsValue::from_str("Cannot serialize value"))?;
        serde_json::from_str(&js_json.as_string().unwrap_or_default())
            .map_err(|e| JsValue::from_str(&format!("Invalid JSON: {}", e)))?
    };

    // do it
    if let serde_json::Value::Object(ref mut map) = obj {
        map.insert(field.to_string(), json_value);
    } else {
        return Err(JsValue::from_str("Internal error: metadata not an object"));
    }

    // back to struct
    let updated: FloMetadata = serde_json::from_value(obj)
        .map_err(|e| JsValue::from_str(&format!("Invalid field '{}': {}", field, e)))?;

    updated
        .to_msgpack()
        .map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Get synced lyrics from a flo file
///
/// # Returns
/// Array of synced lyrics objects or null if none
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn get_synced_lyrics(data: &[u8]) -> Result<JsValue, JsValue> {
    let reader = Reader::new();
    let file = reader.read(data).map_err(to_js_err)?;

    if file.metadata.is_empty() {
        return Ok(JsValue::NULL);
    }

    let meta = FloMetadata::from_msgpack(&file.metadata)
        .map_err(|e| JsValue::from_str(&format!("Invalid metadata: {}", e)))?;

    if meta.synced_lyrics.is_empty() {
        return Ok(JsValue::NULL);
    }

    serde_wasm_bindgen::to_value(&meta.synced_lyrics)
        .map_err(|e| JsValue::from_str(&format!("Serialization error: {}", e)))
}

/// Get waveform data from a flo file for instant visualization
///
/// # Returns
/// WaveformData object or null if not present
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn get_waveform_data(data: &[u8]) -> Result<JsValue, JsValue> {
    let reader = Reader::new();
    let file = reader.read(data).map_err(to_js_err)?;

    if file.metadata.is_empty() {
        return Ok(JsValue::NULL);
    }

    let meta = FloMetadata::from_msgpack(&file.metadata)
        .map_err(|e| JsValue::from_str(&format!("Invalid metadata: {}", e)))?;

    match meta.waveform_data {
        Some(ref waveform) => serde_wasm_bindgen::to_value(waveform)
            .map_err(|e| JsValue::from_str(&format!("Serialization error: {}", e))),
        None => Ok(JsValue::NULL),
    }
}

/// Get section markers from a flo file
///
/// # Returns
/// Array of section markers or null if none
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn get_section_markers(data: &[u8]) -> Result<JsValue, JsValue> {
    let reader = Reader::new();
    let file = reader.read(data).map_err(to_js_err)?;

    if file.metadata.is_empty() {
        return Ok(JsValue::NULL);
    }

    let meta = FloMetadata::from_msgpack(&file.metadata)
        .map_err(|e| JsValue::from_str(&format!("Invalid metadata: {}", e)))?;

    if meta.section_markers.is_empty() {
        return Ok(JsValue::NULL);
    }

    serde_wasm_bindgen::to_value(&meta.section_markers)
        .map_err(|e| JsValue::from_str(&format!("Serialization error: {}", e)))
}

// zero-copy metadata editing

/// update metadata without re-encoding audio
///
/// # Arguments
/// * `flo_data` - Original flo file bytes
/// * `new_metadata` - New MessagePack metadata bytes (use create_metadata_*)
///
/// # Returns
/// New flo file with updated metadata
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn update_metadata(flo_data: &[u8], new_metadata: &[u8]) -> Result<Vec<u8>, JsValue> {
    update_metadata_bytes(flo_data, new_metadata).map_err(to_js_err)
}

/// update metadata without re-encoding (native)
pub fn update_metadata_bytes(flo_data: &[u8], new_metadata: &[u8]) -> FloResult<Vec<u8>> {
    // basic checks
    if flo_data.len() < (HEADER_SIZE as usize) {
        return Err(crate::core::FloError::from(
            "File too small to be valid flo",
        ));
    }

    // check magic
    if flo_data[0..4] != MAGIC {
        return Err(crate::core::FloError::from("Invalid flo file: bad magic"));
    }

    // read header for chunk sizes
    let reader = Reader::new();
    let file = reader.read(flo_data)?;

    // find where metadata starts
    // layout: magic(4) + header + toc + data + extra + metadata
    let meta_offset = 4
        + (file.header.header_size as usize)
        + (file.header.toc_size as usize)
        + (file.header.data_size as usize)
        + (file.header.extra_size as usize);

    // copy up to metadata
    let mut result = Vec::with_capacity(meta_offset + new_metadata.len());
    result.extend_from_slice(&flo_data[..meta_offset]);

    // add new metadata
    result.extend_from_slice(new_metadata);

    // fix meta_size in header
    // header layout: version(2) + flags(2) + sample_rate(4) + ...
    // meta_size is at offset: 4 + 58 = 62
    let meta_size_offset = 4 + 2 + 2 + 4 + 1 + 1 + 8 + 1 + 3 + 4 + 8 + 8 + 8 + 8;
    let new_meta_size = new_metadata.len() as u64;
    result[meta_size_offset..meta_size_offset + 8].copy_from_slice(&new_meta_size.to_le_bytes());

    Ok(result)
}

/// Replace just the metadata in a flo file (convenience function)
///
/// Takes a metadata object directly instead of MessagePack bytes.
///
/// # Arguments
/// * `flo_data` - Original flo file bytes
/// * `metadata` - JavaScript metadata object
///
/// # Returns
/// New flo file with updated metadata
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn set_metadata(flo_data: &[u8], metadata: JsValue) -> Result<Vec<u8>, JsValue> {
    let new_meta_bytes = create_metadata_from_object(metadata)?;
    update_metadata(flo_data, &new_meta_bytes)
}

/// Remove all metadata from a flo file
///
/// # Arguments
/// * `flo_data` - Original flo file bytes
///
/// # Returns
/// New flo file with no metadata
pub fn strip_metadata_bytes(flo_data: &[u8]) -> FloResult<Vec<u8>> {
    update_metadata_bytes(flo_data, &[])
}

/// Remove all metadata from a flo file
///
/// # Arguments
/// * `flo_data` - Original flo file bytes
///
/// # Returns
/// New flo file with no metadata
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn strip_metadata(flo_data: &[u8]) -> Result<Vec<u8>, JsValue> {
    strip_metadata_bytes(flo_data).map_err(to_js_err)
}

/// Get just the metadata bytes from a flo file
///
/// # Arguments
/// * `flo_data` - flo file bytes
///
/// # Returns
/// Raw MessagePack metadata bytes (or empty array)
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn get_metadata_bytes(flo_data: &[u8]) -> Result<Vec<u8>, JsValue> {
    get_metadata_bytes_native(flo_data).map_err(to_js_err)
}

/// Get just the metadata bytes from a flo file
///
/// # Arguments
/// * `flo_data` - flo file bytes
///
/// # Returns
/// Raw MessagePack metadata bytes (or empty array)
pub fn get_metadata_bytes_native(flo_data: &[u8]) -> FloResult<Vec<u8>> {
    if flo_data.len() < (HEADER_SIZE as usize) {
        return Err(crate::core::FloError::from("File too small"));
    }

    // just read header for metadata location
    let reader = Reader::new();
    let file = reader.read(flo_data)?;

    Ok(file.metadata)
}

/// does the file have metadata? (wasm binding)
#[cfg(feature = "wasm")]
#[wasm_bindgen(js_name = has_metadata)]
pub fn has_metadata_wasm(flo_data: &[u8]) -> bool {
    has_metadata(flo_data)
}

/// does the file have metadata? (native)
pub fn has_metadata(flo_data: &[u8]) -> bool {
    if flo_data.len() < (HEADER_SIZE as usize) {
        return false;
    }

    // fast path, just read meta_size from header
    let meta_size_offset = 4 + 2 + 2 + 4 + 1 + 1 + 8 + 1 + 3 + 4 + 8 + 8 + 8 + 8;
    if flo_data.len() < meta_size_offset + 8 {
        return false;
    }

    let meta_size = u64::from_le_bytes(
        flo_data[meta_size_offset..meta_size_offset + 8]
            .try_into()
            .unwrap_or([0; 8]),
    );

    meta_size > 0
}

/// Extract waveform peaks from audio samples (native version)
///
/// # Arguments
/// * `samples` - Interleaved audio samples (f32, -1.0 to 1.0)
/// * `sample_rate` - Sample rate in Hz (e.g., 44100)
/// * `channels` - Number of audio channels (1 or 2)
/// * `peaks_per_second` - Number of peak values per second (default: 50)
///
/// # Returns
/// WaveformData struct containing extracted peaks
pub fn extract_waveform_peaks_to_struct(
    samples: &[f32],
    sample_rate: u32,
    channels: u8,
    peaks_per_second: Option<u32>,
) -> core::metadata::WaveformData {
    let peaks_per_second = peaks_per_second.unwrap_or(50);
    core::analysis::extract_waveform_peaks(samples, channels, sample_rate, peaks_per_second)
}

/// Extract waveform RMS from audio samples
///
/// # Arguments
/// * `samples` - Interleaved audio samples (f32, -1.0 to 1.0)
/// * `sample_rate` - Sample rate in Hz (e.g., 44100)
/// * `channels` - Number of audio channels (1 or 2)
/// * `peaks_per_second` - Number of RMS values per second (default: 50)
///
/// # Returns
/// WaveformData struct containing extracted RMS values
pub fn extract_waveform_rms_to_struct(
    samples: &[f32],
    sample_rate: u32,
    channels: u8,
    peaks_per_second: Option<u32>,
) -> core::metadata::WaveformData {
    let peaks_per_second = peaks_per_second.unwrap_or(50);
    core::analysis::extract_waveform_rms(samples, channels, sample_rate, peaks_per_second)
}

/// Extract spectral fingerprint from audio samples
///
/// # Arguments
/// * `samples` - Audio samples (interleaved if multi-channel)
/// * `channels` - Number of audio channels
/// * `sample_rate` - Sample rate in Hz
/// * `fft_size` - FFT window size (must be power of 2)
/// * `hop_size` - Hop size between consecutive frames
///
/// # Returns
/// SpectralFingerprint object with frequency analysis
#[cfg(target_arch = "wasm32")]
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn extract_spectral_fingerprint_wasm(
    samples: &[f32],
    channels: u32,
    sample_rate: u32,
    fft_size: Option<usize>,
    hop_size: Option<usize>,
) -> Result<JsValue, JsValue> {
    use crate::core::extract_spectral_fingerprint;
    let fingerprint =
        extract_spectral_fingerprint(samples, channels as u8, sample_rate, fft_size, hop_size);
    serde_wasm_bindgen::to_value(&fingerprint)
        .map_err(|e| JsValue::from_str(&format!("Serialization error: {}", e)))
}

/// Extract dominant frequencies from spectral fingerprint
#[cfg(target_arch = "wasm32")]
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn extract_dominant_frequencies_wasm(
    fingerprint_js: JsValue,
    num_frequencies: usize,
) -> Result<JsValue, JsValue> {
    use crate::core::analysis::{extract_dominant_frequencies, SpectralFingerprint};

    let fingerprint: SpectralFingerprint = serde_wasm_bindgen::from_value(fingerprint_js)
        .map_err(|e| JsValue::from_str(&format!("Deserialization error: {}", e)))?;

    let dominant_freqs = extract_dominant_frequencies(&fingerprint, num_frequencies);
    serde_wasm_bindgen::to_value(&dominant_freqs)
        .map_err(|e| JsValue::from_str(&format!("Serialization error: {}", e)))
}

/// Extract dominant frequencies from spectral fingerprint
///
/// # Arguments
/// * `fingerprint` - SpectralFingerprint struct
/// * `num_frequencies` - Number of dominant frequencies to extract per frame
///
/// # Returns
/// Vector of vectors containing dominant frequencies (Hz) for each frame
pub fn extract_dominant_frequencies_to_vec(
    fingerprint: &core::analysis::SpectralFingerprint,
    num_frequencies: usize,
) -> Vec<Vec<f64>> {
    core::analysis::extract_dominant_frequencies(fingerprint, num_frequencies)
}

/// Extract dominant frequencies from audio samples (convenience function)
///
/// # Arguments
/// * `samples` - Audio samples (interleaved if multi-channel)
/// * `sample_rate` - Sample rate in Hz
/// * `channels` - Number of audio channels
/// * `num_frequencies` - Number of dominant frequencies to extract per frame
/// * `fft_size` - FFT window size (optional, will auto-select if None)
/// * `hop_size` - Hop size between frames (optional, will auto-select if None)
///
/// # Returns
/// JavaScript array of arrays containing dominant frequencies (Hz) for each frame
#[cfg(target_arch = "wasm32")]
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn extract_dominant_frequencies_from_samples_wasm(
    samples: &[f32],
    sample_rate: u32,
    channels: u8,
    num_frequencies: usize,
    fft_size: Option<usize>,
    hop_size: Option<usize>,
) -> Result<JsValue, JsValue> {
    let fingerprint =
        extract_spectral_fingerprint(samples, channels, sample_rate, fft_size, hop_size);
    let dominant_freqs = extract_dominant_frequencies_to_vec(&fingerprint, num_frequencies);

    // Convert to JavaScript arrays
    let js_result = js_sys::Array::new();
    for frame_freqs in &dominant_freqs {
        let frame_array = js_sys::Float64Array::from(&frame_freqs[..]);
        js_result.push(&frame_array);
    }

    Ok(js_result.into())
}

/// Extract dominant frequencies from spectral fingerprint
///
/// # Arguments
/// * `fingerprint_js` - SpectralFingerprint JavaScript object
/// * `num_frequencies` - Number of dominant frequencies to extract per frame
///
/// # Returns
/// JavaScript array of arrays containing dominant frequencies (Hz) for each frame
#[cfg(target_arch = "wasm32")]
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn extract_dominant_frequencies_from_fingerprint_wasm(
    fingerprint_js: JsValue,
    num_frequencies: usize,
) -> Result<JsValue, JsValue> {
    use crate::core::analysis::{extract_dominant_frequencies, SpectralFingerprint};

    let fingerprint: SpectralFingerprint = serde_wasm_bindgen::from_value(fingerprint_js)
        .map_err(|e| JsValue::from_str(&format!("Deserialization error: {}", e)))?;

    let dominant_freqs = extract_dominant_frequencies(&fingerprint, num_frequencies);
    serde_wasm_bindgen::to_value(&dominant_freqs)
        .map_err(|e| JsValue::from_str(&format!("Serialization error: {}", e)))
}

/// Compute spectral similarity between two fingerprints
///
/// # Arguments
/// * `fingerprint1` - First spectral fingerprint
/// * `fingerprint2` - Second spectral fingerprint
///
/// # Returns
/// Similarity score between 0.0 (completely different) and 1.0 (identical)
pub fn spectral_similarity_score(
    fingerprint1: &core::analysis::SpectralFingerprint,
    fingerprint2: &core::analysis::SpectralFingerprint,
) -> f32 {
    core::analysis::spectral_similarity(fingerprint1, fingerprint2)
}

/// Compute spectral similarity between two fingerprints
///
/// # Arguments
/// * `samples1` - First audio samples
/// * `samples2` - Second audio samples
/// * `sample_rate` - Sample rate in Hz
/// * `channels` - Number of audio channels (1 or 2)
/// * `fft_size` - FFT window size (default: 2048)
/// * `hop_size` - Hop size between frames (default: fft_size/2)
///
/// # Returns
/// Similarity score between 0.0 (completely different) and 1.0 (identical)
#[cfg(target_arch = "wasm32")]
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn spectral_similarity(
    samples1: &[f32],
    samples2: &[f32],
    sample_rate: u32,
    channels: u8,
    fft_size: Option<usize>,
    hop_size: Option<usize>,
) -> Result<JsValue, JsValue> {
    let fingerprint1 =
        extract_spectral_fingerprint(samples1, channels, sample_rate, fft_size, hop_size);
    let fingerprint2 =
        extract_spectral_fingerprint(samples2, channels, sample_rate, fft_size, hop_size);

    let similarity = spectral_similarity_score(&fingerprint1, &fingerprint2);
    Ok(JsValue::from_f64(similarity as f64))
}

/// Compute EBU R128 loudness metrics from audio samples
///
/// # Arguments
/// * `samples` - Audio samples (interleaved if multi-channel)
/// * `channels` - Number of audio channels
/// * `sample_rate` - Sample rate in Hz
///
/// # Returns
/// LoudnessMetrics object with integrated LUFS, loudness range LU, and true peak dBTP
#[cfg(target_arch = "wasm32")]
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn compute_loudness_metrics(
    samples: &[f32],
    channels: u32,
    sample_rate: u32,
) -> Result<JsValue, JsValue> {
    use crate::core::compute_ebu_r128_loudness;
    let metrics = compute_ebu_r128_loudness(samples, channels as u8, sample_rate);
    serde_wasm_bindgen::to_value(&metrics)
        .map_err(|e| JsValue::from_str(&format!("Serialization error: {}", e)))
}

/// Extract waveform peaks from audio samples
///
/// # Arguments
/// * `samples` - Audio samples (interleaved if multi-channel)
/// * `channels` - Number of audio channels
/// * `sample_rate` - Sample rate in Hz
/// * `peaks_per_second` - Number of peak values to extract per second
///
/// # Returns
/// WaveformData object with extracted peaks
#[cfg(target_arch = "wasm32")]
#[cfg(feature = "wasm")]
#[wasm_bindgen]
pub fn extract_waveform_peaks_wasm(
    samples: &[f32],
    channels: u32,
    sample_rate: u32,
    peaks_per_second: Option<u32>,
) -> Result<JsValue, JsValue> {
    use crate::core::extract_waveform_peaks;
    let waveform = extract_waveform_peaks(
        samples,
        channels as u8,
        sample_rate,
        peaks_per_second.unwrap_or(50),
    );
    serde_wasm_bindgen::to_value(&waveform)
        .map_err(|e| JsValue::from_str(&format!("Serialization error: {}", e)))
}

// tests
#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;
    use alloc::vec::Vec;

    #[test]
    fn test_frame_type_conversion() {
        assert_eq!(FrameType::from(0), FrameType::Silence);
        assert_eq!(FrameType::from(8), FrameType::Alpc8);
        assert_eq!(FrameType::from(254), FrameType::Raw);
        assert!(FrameType::Alpc8.is_alpc());
        assert!(!FrameType::Silence.is_alpc());
        assert_eq!(FrameType::Alpc8.lpc_order(), Some(8));
    }

    #[test]
    #[cfg(feature = "wasm")]
    fn test_version() {
        assert_eq!(version(), "1.2");
    }

    #[test]
    fn test_update_metadata_preserves_audio() {
        // Create a simple flo file with metadata
        let samples: Vec<f32> = (0..4410).map(|i| ((i as f32) * 0.01).sin() * 0.5).collect();
        let encoder = Encoder::new(44100, 1, 16);
        let original_meta = b"original metadata";
        let flo_data = encoder.encode(&samples, original_meta).unwrap();

        // Update metadata
        let new_meta = b"new metadata that is longer!";
        let updated = update_metadata_bytes(&flo_data, new_meta).unwrap();

        // Verify the new file is valid
        let reader = Reader::new();
        let file = reader.read(&updated).unwrap();

        // Check metadata was updated
        assert_eq!(file.metadata, new_meta);
        assert_eq!(file.header.meta_size, new_meta.len() as u64);

        // Check audio data CRC is unchanged (proves audio wasn't touched)
        let original_file = reader.read(&flo_data).unwrap();
        assert_eq!(file.header.data_crc32, original_file.header.data_crc32);

        // Decode and verify audio is identical
        let decoder = Decoder::new();
        let original_samples = decoder.decode(&flo_data).unwrap();
        let updated_samples = decoder.decode(&updated).unwrap();
        assert_eq!(original_samples, updated_samples);
    }

    #[test]
    fn test_strip_metadata() {
        let samples: Vec<f32> = vec![0.5; 1000];
        let encoder = Encoder::new(44100, 1, 16);
        let flo_with_meta = encoder.encode(&samples, b"some metadata here").unwrap();

        // Strip metadata using empty bytes (simulates strip)
        let stripped = update_metadata_bytes(&flo_with_meta, &[]).unwrap();

        // Verify
        let reader = Reader::new();
        let file = reader.read(&stripped).unwrap();
        assert!(file.metadata.is_empty());
        assert_eq!(file.header.meta_size, 0);

        // File should be smaller
        assert!(stripped.len() < flo_with_meta.len());
    }

    #[test]
    fn test_has_metadata() {
        let samples: Vec<f32> = vec![0.5; 1000];
        let encoder = Encoder::new(44100, 1, 16);

        let with_meta = encoder.encode(&samples, b"metadata").unwrap();
        let without_meta = encoder.encode(&samples, &[]).unwrap();

        assert!(has_metadata(&with_meta));
        assert!(!has_metadata(&without_meta));
    }
}