dff-meta 0.1.0

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

mod id3_display;
pub mod model;

use crate::model::*;
use id3::Tag;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt;
use std::fs::File;
use std::io;
use std::io::Read;
use std::io::SeekFrom;
use std::io::prelude::*;
use std::path::Path;
use std::u64;

#[derive(Debug)]
pub struct DffFile {
    file: File,
    frm_chunk: FormDsdChunk,
    dsd_data_offset: u64,
    dsd_audio_size: u64,
}

impl DffFile {
    /// Attempt to open and parse the metadata of DFF file in
    /// read-only mode. Sample data is not read into memory to keep
    /// the memory footprint small.
    ///
    /// # Errors
    ///
    /// This function will return an error if `path` does not exist or
    /// is not a readable and valid DFF file.
    ///
    pub fn open(path: &Path) -> Result<DffFile, Error> {
        let mut file = File::open(path)?;
        let mut chunk_buf16 = [0u8; 16];
        let mut prop_buf4 = [0u8; 4];

        // FORM (FRM8)
        file.read_exact(&mut chunk_buf16)?;
        let mut frm_chunk = FormDsdChunk::try_from(chunk_buf16)?;

        // FVER
        file.read_exact(&mut chunk_buf16)?;
        let fver_chunk = FormatVersionChunk::try_from(chunk_buf16)?;
        frm_chunk
            .chunk
            .local_chunks
            .insert(FVER_LABEL, LocalChunk::FormatVersion(fver_chunk));

        // Locate PROP (abort if DSD encountered first)
        let mut hdr_buf = scan_until(&mut file, PROP_LABEL, Some(DSD_LABEL))?;
        chunk_buf16[0..12].copy_from_slice(&hdr_buf);
        // Read property_type (4 bytes) then build 16-byte buffer
        file.read_exact(&mut prop_buf4)?;
        chunk_buf16[12..16].copy_from_slice(&prop_buf4);

        let pc = PropertyChunk::try_from(chunk_buf16)?;
        frm_chunk
            .chunk
            .local_chunks
            .insert(PROP_LABEL, LocalChunk::Property(pc));

        let prop_data_size = match frm_chunk.chunk.local_chunks.get(&PROP_LABEL) {
            Some(LocalChunk::Property(prop)) => prop.chunk.header.ck_data_size,
            _ => return Err(Error::PropChunkHeader),
        };
        let prop_data_offset = file.stream_position()? - 4;

        if let Some(LocalChunk::Property(prop_chunk_inner)) =
            frm_chunk.chunk.local_chunks.get_mut(&PROP_LABEL)
        {
            while file.stream_position()? < prop_data_offset + prop_data_size as u64
                && file.read_exact(&mut hdr_buf).is_ok()
            {
                let ck_id = u32_from_byte_buffer(&hdr_buf, 0);
                let ck_data_size = u64_from_byte_buffer(&hdr_buf, 4);

                match ck_id {
                    FS_LABEL => {
                        let mut chunk_data_buffer: [u8; 4] = [0; 4];
                        file.read_exact(&mut chunk_data_buffer)?;
                        let fs_chunk = SampleRateChunk::try_from({
                            let mut buf = [0u8; 16];
                            buf[0..12].copy_from_slice(&hdr_buf);
                            buf[12..16].copy_from_slice(&chunk_data_buffer);
                            buf
                        })?;
                        prop_chunk_inner
                            .chunk
                            .local_chunks
                            .insert(FS_LABEL, LocalChunk::SampleRate(fs_chunk));
                    }
                    CHNL_LABEL => {
                        let mut data_buf = vec![0u8; ck_data_size as usize];
                        file.read_exact(&mut data_buf)?;
                        let mut full_buf = Vec::with_capacity(12 + data_buf.len());
                        full_buf.extend_from_slice(&hdr_buf);
                        full_buf.extend_from_slice(&data_buf);
                        let chnl_chunk = ChannelsChunk::try_from(full_buf.as_slice())?;
                        prop_chunk_inner
                            .chunk
                            .local_chunks
                            .insert(CHNL_LABEL, LocalChunk::Channels(chnl_chunk));
                    }
                    COMP_LABEL => {
                        let mut data_buf = vec![0u8; ck_data_size as usize];
                        file.read_exact(&mut data_buf)?;
                        let mut full_buf = Vec::with_capacity(12 + data_buf.len());
                        full_buf.extend_from_slice(&hdr_buf);
                        full_buf.extend_from_slice(&data_buf);
                        let cmpr_chunk = CompressionTypeChunk::try_from(full_buf.as_slice())?;
                        prop_chunk_inner
                            .chunk
                            .local_chunks
                            .insert(COMP_LABEL, LocalChunk::CompressionType(cmpr_chunk));
                    }
                    ABS_TIME_LABEL => {
                        let mut data_buf = vec![0u8; ck_data_size as usize];
                        file.read_exact(&mut data_buf)?;
                        let mut full_buf = Vec::with_capacity(12 + data_buf.len());
                        full_buf.extend_from_slice(&hdr_buf);
                        full_buf.extend_from_slice(&data_buf);
                        if let Ok(abs_chunk) = AbsoluteStartTimeChunk::try_from(full_buf.as_slice())
                        {
                            prop_chunk_inner
                                .chunk
                                .local_chunks
                                .insert(ABS_TIME_LABEL, LocalChunk::AbsoluteStartTime(abs_chunk));
                        }
                    }
                    LS_CONF_LABEL => {
                        let mut data_buf = vec![0u8; ck_data_size as usize];
                        file.read_exact(&mut data_buf)?;
                        let mut full_buf = Vec::with_capacity(12 + data_buf.len());
                        full_buf.extend_from_slice(&hdr_buf);
                        full_buf.extend_from_slice(&data_buf);
                        if let Ok(lsco_chunk) =
                            LoudspeakerConfigChunk::try_from(full_buf.as_slice())
                        {
                            prop_chunk_inner
                                .chunk
                                .local_chunks
                                .insert(LS_CONF_LABEL, LocalChunk::LoudspeakerConfig(lsco_chunk));
                        }
                    }
                    _ => {
                        file.seek(SeekFrom::Current(if ck_data_size & 1 == 1 {
                            ck_data_size + 1
                        } else {
                            ck_data_size
                        } as i64))?;
                    }
                }
            }
        }

        hdr_buf = scan_until(&mut file, DSD_LABEL, None)?;
        let dsd_data_offset = file.stream_position()?;
        let dsd_chunk = DsdChunk::try_from(hdr_buf)?;
        let dsd_audio_size = dsd_chunk.chunk.header.ck_data_size;
        frm_chunk
            .chunk
            .local_chunks
            .insert(DSD_LABEL, LocalChunk::Dsd(dsd_chunk));

        // Seek past raw DSD audio data + pad byte if odd
        file.seek(SeekFrom::Current(if dsd_audio_size & 1 == 1 {
            dsd_audio_size + 1
        } else {
            dsd_audio_size
        } as i64))?;

        // If we got this far, we have enough for at least a basic dff file
        let mut dff_file = DffFile {
            file,
            frm_chunk,
            dsd_data_offset,
            dsd_audio_size,
        };

        // Now look for an ID3 tag
        hdr_buf = match scan_until(&mut dff_file.file, ID3_LABEL, None) {
            Ok(buf) => buf,
            Err(_e) => {
                return Ok(dff_file);
            }
        };

        match dff_file.add_id3_chunk(hdr_buf) {
            Ok(()) => return Ok(dff_file),
            Err(e) => return Err(Error::Id3Error(e, dff_file)),
        };
    }

    /// Return a reference to the underlying [File](std::fs::File).
    #[must_use]
    pub fn file(&self) -> &File {
        &self.file
    }

    /// Return the byte offset in the file where the DSD audio data starts.
    pub fn get_dsd_data_offset(&self) -> u64 {
        self.dsd_data_offset
    }

    /// Return the length of the DSD audio data in bytes.
    pub fn get_audio_length(&self) -> u64 {
        self.dsd_audio_size
    }

    /// Return the number of audio channels.
    pub fn get_num_channels(&self) -> Result<usize, Error> {
        let prop_chunk = match self.frm_chunk.chunk.local_chunks.get(&PROP_LABEL) {
            Some(LocalChunk::Property(prop)) => prop,
            _ => return Err(Error::PropChunkHeader),
        };
        match prop_chunk.chunk.local_chunks.get(&CHNL_LABEL) {
            Some(LocalChunk::Channels(chnl)) => Ok(chnl.num_channels as usize),
            _ => return Err(Error::ChnlNumber),
        }
    }

    /// Return the sample rate in Hz.
    pub fn get_sample_rate(&self) -> Result<u32, Error> {
        let prop_chunk = match self.frm_chunk.chunk.local_chunks.get(&PROP_LABEL) {
            Some(LocalChunk::Property(prop)) => prop,
            _ => return Err(Error::PropChunkHeader),
        };
        match prop_chunk.chunk.local_chunks.get(&FS_LABEL) {
            Some(LocalChunk::SampleRate(fs)) => Ok(fs.sample_rate),
            _ => return Err(Error::FsChunkHeader),
        }
    }

    /// Return the size of the FORM chunk in bytes
    pub fn get_form_chunk_size(&self) -> u64 {
        self.frm_chunk.chunk.header.ck_data_size + CHUNK_HEADER_SIZE
    }

    /// Return the total size of the DFF file in bytes
    pub fn get_file_size(&self) -> Result<u64, io::Error> {
        let metadata = self.file.metadata()?;
        Ok(metadata.len())
    }

    /// Return a reference to the optional `ID3v2` [Tag](id3::Tag).
    pub fn id3_tag(&self) -> &Option<Tag> {
        match self.frm_chunk.chunk.local_chunks.get(&ID3_LABEL) {
            Some(LocalChunk::Id3(id3_chunk)) => &id3_chunk.tag,
            _ => &None,
        }
    }

    /// Return the DFF format version number.
    pub fn get_dff_version(&self) -> Result<u32, Error> {
        let fver_chunk = match self.frm_chunk.chunk.local_chunks.get(&FVER_LABEL) {
            Some(LocalChunk::FormatVersion(fver)) => fver,
            _ => return Err(Error::FverChunkHeader),
        };
        Ok(fver_chunk.format_version)
    }

    /// Add the read ID3 chunk to the DFF file's FORM chunk.
    fn add_id3_chunk(
        &mut self,
        hdr_buf: [u8; CHUNK_HEADER_SIZE as usize],
    ) -> Result<(), id3::Error> {
        let ck_id = u32_from_byte_buffer(&hdr_buf, 0);
        let ck_data_size = u64_from_byte_buffer(&hdr_buf, std::mem::size_of::<ID>());
        let mut data = vec![0u8; ck_data_size as usize];
        let mut tag_read_err: Option<id3::Error> = None;

        if let Err(_e) = self.file.read_exact(&mut data) {
            tag_read_err = Some(id3::Error::new(
                id3::ErrorKind::Io(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    "Failed to read complete ID3 chunk data",
                )),
                "Couldn't fill buffer",
            ));
        }

        let mut cursor = std::io::Cursor::new(&data);
        let tag = match id3::Tag::read_from2(&mut cursor) {
            Ok(t) => Some(t),
            Err(e) => {
                let partial_tag = e.partial_tag.clone();
                tag_read_err = Some(e);
                partial_tag
            }
        };

        if tag.is_some() {
            let id3_chunk = Id3Chunk {
                chunk: Chunk::new(ChunkHeader {
                    ck_id,
                    ck_data_size,
                }),
                tag,
            };

            self.frm_chunk
                .chunk
                .local_chunks
                .insert(ID3_LABEL, LocalChunk::Id3(id3_chunk));
        }

        if tag_read_err.is_some() {
            return Err(tag_read_err.unwrap());
        }
        Ok(())
    }
}

impl fmt::Display for DffFile {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "File size: {} bytes\nForm Chunk Size: {} bytes\nDSD Audio Offset: {} bytes\nAudio Length: {} bytes\nChannels: {}\nSample Rate: {} Hz\nDFF Version: {}\nID3 Tag:\n{}",
            self.get_file_size().unwrap_or(0),
            self.get_form_chunk_size(),
            self.get_dsd_data_offset(),
            self.get_audio_length(),
            self.get_num_channels().unwrap_or(0),
            self.get_sample_rate().unwrap_or(0),
            self.get_dff_version().unwrap_or(0),
            if let Some(tag) = &self.id3_tag() {
                id3_display::id3_tag_to_string(tag)
            } else {
                String::from("No ID3 tag present.")
            }
        )
    }
}

/// Helper: scan forward for a chunk header matching `want_label`, error if `abort_label` appears first.
/// Returns the 12-byte header (ID + size). Skips payload (and pad byte if size is odd) of non-matching chunks.
fn scan_until(
    file: &mut File,
    want_label: u32,
    abort_label: Option<u32>,
) -> Result<[u8; CHUNK_HEADER_SIZE as usize], Error> {
    loop {
        let mut hdr = [0u8; CHUNK_HEADER_SIZE as usize];
        match file.read_exact(&mut hdr) {
            Ok(_) => {}
            Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
                return Err(Error::Eof);
            }
            Err(e) => return Err(Error::IoError(e)),
        }
        let ck_id = u32_from_byte_buffer(&hdr, 0);
        let ck_data_size = u64_from_byte_buffer(&hdr, std::mem::size_of::<ID>());
        if ck_id == want_label {
            return Ok(hdr);
        } else if Some(ck_id) == abort_label {
            return Err(Error::PrematureTagFound(
                String::from_utf8_lossy(&ck_id.to_be_bytes()).to_string(),
            ));
        } else {
            // Skip payload + pad if odd
            file.seek(SeekFrom::Current(ck_data_size as i64))?;
            if ck_data_size & 1 == 1 {
                file.seek(SeekFrom::Current(1))?;
            }
        }
    }
}

/// Return a `u64` which starts from `index` in the specified byte
/// buffer, interpretting the bytes as little-endian.
fn u64_from_byte_buffer(buffer: &[u8], index: usize) -> u64 {
    let mut byte_array: [u8; 8] = [0; 8];
    byte_array.copy_from_slice(&buffer[index..index + 8]);

    u64::from_be_bytes(byte_array)
}

/// Return a `u32` which starts from `index` in the specified byte
/// buffer, interpretting the bytes as little-endian.
fn u32_from_byte_buffer(buffer: &[u8], index: usize) -> u32 {
    let mut byte_array: [u8; 4] = [0; 4];
    byte_array.copy_from_slice(&buffer[index..index + 4]);

    u32::from_be_bytes(byte_array)
}

impl Chunk {
    pub fn new(header: ChunkHeader) -> Chunk {
        Chunk {
            header,
            local_chunks: HashMap::new(),
        }
    }
}

impl FormDsdChunk {
    #[inline]
    pub fn is_valid(&self) -> bool {
        self.chunk.header.ck_id == u32::from_be_bytes(*b"FRM8") && self.form_type == DSD_LABEL
    }
}

/// IMPLEMENTATION: Convert 16‑byte header into FormDsdChunk
impl TryFrom<[u8; 16]> for FormDsdChunk {
    type Error = Error;

    fn try_from(buf: [u8; 16]) -> Result<Self, Self::Error> {
        // Big‑endian helpers
        let be_u32 = |i: usize| {
            let mut a = [0u8; 4];
            a.copy_from_slice(&buf[i..i + 4]);
            u32::from_be_bytes(a)
        };
        let be_u64 = |i: usize| {
            let mut a = [0u8; 8];
            a.copy_from_slice(&buf[i..i + 8]);
            u64::from_be_bytes(a)
        };

        let ck_id = be_u32(0);
        let ck_data_size = be_u64(4);
        let form_type = be_u32(12);
        let header = ChunkHeader {
            ck_id,
            ck_data_size,
        };
        let chunk = FormDsdChunk {
            chunk: Chunk::new(header),
            form_type,
        };

        if !chunk.is_valid() {
            return Err(Error::FormChunkHeader);
        }
        if chunk.form_type != DSD_LABEL {
            return Err(Error::FormTypeMismatch);
        }

        Ok(chunk)
    }
}

impl TryFrom<[u8; 16]> for FormatVersionChunk {
    type Error = Error;

    fn try_from(buf: [u8; 16]) -> Result<Self, Self::Error> {
        let be_u32 = |i: usize| {
            let mut a = [0u8; 4];
            a.copy_from_slice(&buf[i..i + 4]);
            u32::from_be_bytes(a)
        };
        let be_u64 = |i: usize| {
            let mut a = [0u8; 8];
            a.copy_from_slice(&buf[i..i + 8]);
            u64::from_be_bytes(a)
        };

        let ck_id = be_u32(0);
        let ck_data_size = be_u64(4);
        let version = be_u32(12);
        let header = ChunkHeader {
            ck_id,
            ck_data_size,
        };
        let chunk = FormatVersionChunk {
            chunk: Chunk::new(header),
            format_version: version,
        };

        if chunk.chunk.header.ck_id != FVER_LABEL {
            return Err(Error::FverChunkHeader);
        }
        if chunk.chunk.header.ck_data_size != 4 {
            return Err(Error::FverChunkSize);
        }

        Ok(chunk)
    }
}

impl TryFrom<[u8; 16]> for PropertyChunk {
    type Error = Error;
    fn try_from(buf: [u8; 16]) -> Result<Self, Self::Error> {
        let be_u32 = |i: usize| {
            let mut a = [0u8; 4];
            a.copy_from_slice(&buf[i..i + 4]);
            u32::from_be_bytes(a)
        };
        let be_u64 = |i: usize| {
            let mut a = [0u8; 8];
            a.copy_from_slice(&buf[i..i + 8]);
            u64::from_be_bytes(a)
        };

        let ck_id = be_u32(0);
        let ck_data_size = be_u64(4);
        // Must at least contain 4 bytes for property_type.
        if ck_data_size < 4 {
            return Err(Error::ChnlChunkSize); // reuse generic size error not ideal; kept minimal
        }
        let property_type = be_u32(12);

        let header = ChunkHeader {
            ck_id,
            ck_data_size,
        };
        let chunk = PropertyChunk {
            chunk: Chunk::new(header),
            property_type,
        };

        if chunk.chunk.header.ck_id != PROP_LABEL {
            return Err(Error::PropChunkHeader);
        }
        if chunk.property_type != SND_LABEL {
            return Err(Error::PropChunkType);
        }
        Ok(chunk)
    }
}

impl TryFrom<[u8; 16]> for SampleRateChunk {
    type Error = Error;
    fn try_from(buf: [u8; 16]) -> Result<Self, Self::Error> {
        let be_u32 = |i: usize| {
            let mut a = [0u8; 4];
            a.copy_from_slice(&buf[i..i + 4]);
            u32::from_be_bytes(a)
        };
        let be_u64 = |i: usize| {
            let mut a = [0u8; 8];
            a.copy_from_slice(&buf[i..i + 8]);
            u64::from_be_bytes(a)
        };

        let ck_id = be_u32(0);
        let ck_data_size = be_u64(4);
        let sample_rate = be_u32(12);

        let header = ChunkHeader {
            ck_id,
            ck_data_size,
        };
        let chunk = SampleRateChunk {
            chunk: Chunk::new(header),
            sample_rate,
        };

        if chunk.chunk.header.ck_id != FS_LABEL {
            return Err(Error::FsChunkHeader);
        }
        if chunk.chunk.header.ck_data_size != 4 {
            return Err(Error::FsChunkSize);
        }
        Ok(chunk)
    }
}

impl TryFrom<&[u8]> for ChannelsChunk {
    type Error = Error;
    fn try_from(buf: &[u8]) -> Result<Self, Self::Error> {
        if buf.len() < 14 {
            return Err(Error::ChnlChunkSize);
        }

        let ck_id = {
            let mut a = [0u8; 4];
            a.copy_from_slice(&buf[0..4]);
            u32::from_be_bytes(a)
        };

        let ck_data_size = {
            let mut a = [0u8; 8];
            a.copy_from_slice(&buf[4..12]);
            u64::from_be_bytes(a)
        };

        // Total expected length = 12(header) + ck_data_size
        if buf.len() as u64 != 12 + ck_data_size {
            return Err(Error::ChnlChunkSize);
        }

        let num_channels = {
            let mut a = [0u8; 2];
            a.copy_from_slice(&buf[12..14]);
            u16::from_be_bytes(a)
        };

        if num_channels != 1 && num_channels != 2 {
            return Err(Error::ChnlNumber);
        }

        // Each channel id is 4 bytes
        let expected_ids_bytes = (num_channels as usize) * 4;
        if 14 + expected_ids_bytes != buf.len() {
            return Err(Error::ChnlChunkSize);
        }

        let mut channel_ids = Vec::with_capacity(num_channels as usize);
        let mut idx = 14;
        for _ in 0..num_channels {
            let mut a = [0u8; 4];
            a.copy_from_slice(&buf[idx..idx + 4]);
            channel_ids.push(u32::from_be_bytes(a));
            idx += 4;
        }

        let header = ChunkHeader {
            ck_id,
            ck_data_size,
        };

        let chunk = ChannelsChunk {
            chunk: Chunk::new(header),
            num_channels,
            ch_id: channel_ids,
        };

        if chunk.chunk.header.ck_id != CHNL_LABEL {
            return Err(Error::ChnlChunkHeader);
        }
        if expected_ids_bytes != chunk.ch_id.len() * 4 {
            return Err(Error::ChnlChunkSize);
        }
        Ok(chunk)
    }
}

impl TryFrom<&[u8]> for CompressionTypeChunk {
    type Error = Error;
    fn try_from(buf: &[u8]) -> Result<Self, Self::Error> {
        // Need at least 12 (header) + 4 (compression type)
        if buf.len() < 16 {
            return Err(Error::CmprChunkSize);
        }

        // Header
        let ck_id = {
            let mut a = [0u8; 4];
            a.copy_from_slice(&buf[0..4]);
            u32::from_be_bytes(a)
        };

        let ck_data_size = {
            let mut a = [0u8; 8];
            a.copy_from_slice(&buf[4..12]);
            u64::from_be_bytes(a)
        };

        if buf.len() as u64 != 12 + ck_data_size || ck_data_size < 4 {
            return Err(Error::CmprChunkSize);
        }

        let compression_type = {
            let mut a = [0u8; 4];
            a.copy_from_slice(&buf[12..16]);
            u32::from_be_bytes(a)
        };

        // Remaining bytes (if any) are a UTF-8 / ASCII name, often null terminated
        let name_bytes = if ck_data_size > 4 {
            &buf[16..(12 + ck_data_size as usize)]
        } else {
            &[]
        };

        let compression_name = match std::str::from_utf8(name_bytes) {
            Ok(inner_str) => inner_str.to_string(),
            Err(_) => String::new(),
        };

        let chunk = CompressionTypeChunk {
            chunk: Chunk::new(ChunkHeader {
                ck_id,
                ck_data_size,
            }),
            compression_type,
            compression_name,
        };

        if chunk.chunk.header.ck_id != COMP_LABEL {
            return Err(Error::CmprChunkHeader);
        }
        // New check: must be 'DSD '
        // DST not yet implemented
        if chunk.compression_type != DSD_LABEL || chunk.compression_name == "DST Encoded" {
            return Err(Error::CmprTypeMismatch);
        }
        Ok(chunk)
    }
}

impl TryFrom<&[u8]> for AbsoluteStartTimeChunk {
    type Error = Error;
    fn try_from(buf: &[u8]) -> Result<Self, Self::Error> {
        // Need full header (12) + payload (8)
        if buf.len() < 20 {
            return Err(Error::AbssChunkSize);
        }
        // Chunk ID
        let ck_id = {
            let mut a = [0u8; 4];
            a.copy_from_slice(&buf[0..4]);
            u32::from_be_bytes(a)
        };
        // Data size (must be 8 bytes for: hours(2) + minutes(1) + seconds(1) + samples(4))
        let ck_data_size = {
            let mut a = [0u8; 8];
            a.copy_from_slice(&buf[4..12]);
            u64::from_be_bytes(a)
        };
        if ck_data_size != 8 || buf.len() as u64 != 12 + ck_data_size {
            return Err(Error::AbssChunkSize);
        }

        // Payload layout (big-endian):
        // bytes 12..14 : U16 hours
        // byte  14     : U8 minutes
        // byte  15     : U8 seconds
        // bytes 16..20 : U32 samples (sample offset within that second)
        let hours = {
            let mut a = [0u8; 2];
            a.copy_from_slice(&buf[12..14]);
            u16::from_be_bytes(a)
        };
        let minutes = buf[14];
        let seconds = buf[15];
        let samples = {
            let mut a = [0u8; 4];
            a.copy_from_slice(&buf[16..20]);
            u32::from_be_bytes(a)
        };

        let chunk = AbsoluteStartTimeChunk {
            chunk: Chunk::new(ChunkHeader {
                ck_id,
                ck_data_size,
            }),
            hours,
            minutes,
            seconds,
            samples,
        };

        if chunk.chunk.header.ck_id != ABS_TIME_LABEL {
            return Err(Error::AbssChunkHeader);
        }
        Ok(chunk)
    }
}

impl TryFrom<&[u8]> for LoudspeakerConfigChunk {
    type Error = Error;
    fn try_from(buf: &[u8]) -> Result<Self, Self::Error> {
        // Need header (12) + 2 bytes payload
        if buf.len() < 14 {
            return Err(Error::LscoChunkSize);
        }
        let ck_id = {
            let mut a = [0u8; 4];
            a.copy_from_slice(&buf[0..4]);
            u32::from_be_bytes(a)
        };
        if ck_id != LS_CONF_LABEL {
            return Err(Error::LscoChunkHeader);
        }
        let ck_data_size = {
            let mut a = [0u8; 8];
            a.copy_from_slice(&buf[4..12]);
            u64::from_be_bytes(a)
        };

        if buf.len() as u64 != 12 + ck_data_size {
            return Err(Error::LscoChunkSize);
        }

        let ls_config = {
            let mut a = [0u8; 2];
            a.copy_from_slice(&buf[12..14]);
            u16::from_be_bytes(a)
        };

        let chunk = LoudspeakerConfigChunk {
            chunk: Chunk::new(ChunkHeader {
                ck_id,
                ck_data_size,
            }),
            ls_config,
        };

        // LSCO payload is exactly 2 bytes (U16 loudspeaker configuration code)
        if chunk.chunk.header.ck_data_size != 2 {
            return Err(Error::LscoChunkSize);
        }
        Ok(chunk)
    }
}

impl fmt::Display for DsdChunk {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Copy packed field to a local to avoid unaligned reference.
        let size = self.chunk.header.ck_data_size;
        write!(f, "Audio Length = {} bytes", size)
    }
}

impl TryFrom<[u8; CHUNK_HEADER_SIZE as usize]> for DsdChunk {
    type Error = Error;

    fn try_from(buf: [u8; CHUNK_HEADER_SIZE as usize]) -> Result<Self, Self::Error> {
        let ck_id = {
            let mut a = [0u8; 4];
            a.copy_from_slice(&buf[0..4]);
            u32::from_be_bytes(a)
        };
        if ck_id != DSD_LABEL {
            return Err(Error::DsdChunkHeader);
        }

        let ck_data_size = {
            let mut a = [0u8; 8];
            a.copy_from_slice(&buf[4..12]);
            u64::from_be_bytes(a)
        };
        if ck_data_size == 0 {
            return Err(Error::DsdChunkSize);
        }
        Ok(DsdChunk {
            chunk: Chunk::new(ChunkHeader {
                ck_id,
                ck_data_size,
            }),
        })
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::DsdChunkHeader => f.write_str("A DSD chunk must start with the bytes 'DSD '."),
            Error::DsdChunkSize => f.write_str("A DSD chunk must not have size 0."),
            Error::Id3Error(id3_error, dff_file) => {
                write!(f, "Id3 error: {} in file: {}", id3_error, dff_file)
            }
            Error::IoError(io_error) => {
                write!(f, "IO error: {}", io_error)
            }
            Error::PrematureTagFound(e) => {
                write!(f, "Chunk {} was found before it should have been.", e)
            }
            Error::FormChunkHeader => f.write_str("FORM chunk must start with 'FRM8'."),
            Error::FormTypeMismatch => f.write_str("FORM chunk form type must be 'DSD '."),
            Error::FverChunkHeader => f.write_str("Format Version chunk must start with 'FVER'."),
            Error::FverChunkSize => f.write_str("FVER chunk data size must be 4."),
            Error::FverUnsupportedVersion => {
                f.write_str("Unsupported format version in FVER chunk.")
            }
            Error::PropChunkHeader => f.write_str("Property chunk must start with 'PROP'."),
            Error::PropChunkType => f.write_str("Property chunk type must be 'SND '."),
            Error::FsChunkHeader => f.write_str("Sample rate chunk must start with 'FS  '."),
            Error::FsChunkSize => f.write_str("FS chunk size must be 4."),
            Error::ChnlChunkHeader => f.write_str("Channels chunk must start with 'CHNL'."),
            Error::ChnlChunkSize => f.write_str("CHNL chunk size does not match channel data."),
            Error::ChnlNumber => f.write_str("CHNL number not found or is unsupported."),
            Error::CmprChunkHeader => f.write_str("Compression type chunk must start with 'CMPR'."),
            Error::CmprChunkSize => f.write_str("CMPR chunk size invalid or inconsistent."),
            Error::AbssChunkHeader => {
                f.write_str("Absolute start time chunk must start with 'ABSS'.")
            }
            Error::AbssChunkSize => f.write_str("ABSS chunk size invalid."),
            Error::LscoChunkHeader => {
                f.write_str("Loudspeaker config chunk must start with 'LSCO'.")
            }
            Error::LscoChunkSize => f.write_str("LSCO chunk size invalid or inconsistent."),
            Error::CmprTypeMismatch => {
                f.write_str("Compression type must be 'DSD '. DST not supported.")
            }
            Error::Eof => f.write_str("Unexpected end of file."),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::IoError(io_error) => Some(io_error),
            _ => None,
        }
    }
}

impl From<io::Error> for Error {
    fn from(error: io::Error) -> Self {
        Error::IoError(error)
    }
}

#[cfg(test)]
mod tests {
    use id3::TagLike;

    use super::*;

    #[test]
    fn read_file() {
        let filename = "1kHz.dff";
        let path = Path::new(filename);
        let dff_file = DffFile::open(path).unwrap();

        assert_eq!(dff_file.get_file_size().unwrap(), 36592);
        assert_eq!(dff_file.get_form_chunk_size(), 71872);
        assert_eq!(dff_file.get_dsd_data_offset(), 130);
        assert_eq!(dff_file.get_audio_length(), 35280);
        assert_eq!(dff_file.get_num_channels().unwrap(), 2);
        assert_eq!(dff_file.get_sample_rate().unwrap(), 2822400);
        assert_eq!(dff_file.get_dff_version().unwrap(), 17104896);

        let tag = dff_file.id3_tag().clone().unwrap();

        assert_eq!(tag.title().unwrap(), ".05 sec 1kHz");
        assert_eq!(tag.artist().unwrap(), "dff");
        assert_eq!(tag.album().unwrap(), "Test Tones");
        assert_eq!(tag.year().unwrap(), 2025);
        assert_eq!(tag.genre().unwrap(), "Test");
        assert_eq!(tag.track().unwrap(), 1);
    }
}