chdlady-disc 0.2.2

Disc geometries and physical media formats for chdlady
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
//! Laserdisc media image creation and extraction pipelines.
//!
//! Provides `create_ld` and `extract_ld` matching MAME `chdman createld` and `chdman extractld`.

use chdlady_av::avhuff::raw_frame_size;
use chdlady_av::avi::{AviChunk, AviInfo, AviReader, AviWriter};
use chdlady_core::{
    ChdFile, ChdWriteConfig, ChdWriter, CreateResult, MetadataItem, OperationPhase, ProgressStatus,
};
use std::collections::VecDeque;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Read, Seek};
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicBool;
use std::sync::Arc;

/// Tag for audio/video metadata: `AVAV` (0x41564156).
pub const AV_METADATA_TAG: u32 = 0x41564156;

/// Tag for Laserdisc VBI metadata: `AVLD` (0x41564c44).
pub const AV_LD_METADATA_TAG: u32 = 0x41564c44;

/// Default compression codec for Laserdisc media (`avhu`).
pub const DEFAULT_LD_CODECS: [u32; 4] = [u32::from_be_bytes(*b"avhu"), 0, 0, 0];

/// Error type for Laserdisc pipeline operations.
#[derive(Debug)]
pub enum LdError {
    /// I/O error.
    Io(std::io::Error),
    /// AVI container error.
    Avi(chdlady_av::avi::AviError),
    /// CHD error.
    Chd(chdlady_core::ChdError),
    /// Invalid parameter or metadata.
    Invalid(String),
}

impl std::fmt::Display for LdError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LdError::Io(e) => write!(f, "I/O error: {}", e),
            LdError::Avi(e) => write!(f, "AVI error: {}", e),
            LdError::Chd(e) => write!(f, "CHD error: {}", e),
            LdError::Invalid(s) => write!(f, "Invalid parameter: {}", s),
        }
    }
}

impl std::error::Error for LdError {}

impl From<std::io::Error> for LdError {
    fn from(e: std::io::Error) -> Self {
        LdError::Io(e)
    }
}

impl From<chdlady_av::avi::AviError> for LdError {
    fn from(e: chdlady_av::avi::AviError) -> Self {
        LdError::Avi(e)
    }
}

impl From<chdlady_core::ChdError> for LdError {
    fn from(e: chdlady_core::ChdError) -> Self {
        LdError::Chd(e)
    }
}

/// Options for creating a Laserdisc CHD container from an AVI file.
#[derive(Debug, Clone, Default)]
pub struct CreateLdOptions {
    /// Starting frame in input video.
    pub start_frame: Option<u64>,
    /// Number of frames or end frame index.
    pub end_frame: Option<u64>,
    /// Hunk size in bytes (defaults to raw frame size).
    pub hunk_size: Option<u32>,
    /// Up to 4 FourCC compression codecs.
    pub codecs: Option<[u32; 4]>,
    /// Optional path to parent CHD for differential container.
    pub parent_path: Option<PathBuf>,
    /// Number of parallel threads.
    pub num_processors: Option<usize>,
    /// Optional shared atomic flag for cooperative cancellation.
    pub cancel_token: Option<Arc<AtomicBool>>,
}

/// Options for extracting an AVI movie from a Laserdisc CHD container.
#[derive(Debug, Clone, Default)]
pub struct ExtractLdOptions {
    /// Starting frame to extract.
    pub start_frame: Option<u64>,
    /// Ending frame to extract.
    pub end_frame: Option<u64>,
    /// Optional path to parent CHD for differential container.
    pub parent_path: Option<PathBuf>,
}

/// Structured inspection information for Laserdisc creation.
#[derive(Debug, Clone)]
pub struct LdCreateInfo {
    /// Target CHD output path.
    pub output_path: PathBuf,
    /// Optional parent CHD path.
    pub parent_path: Option<PathBuf>,
    /// Input AVI movie path.
    pub input_path: PathBuf,
    /// Starting frame/field offset in source file.
    pub input_start: u64,
    /// Total frames/fields to encode.
    pub input_length: u64,
    /// Total frames/fields in input AVI.
    pub total_samples: u64,
    /// Scaled frame rate (FPS * 1,000,000).
    pub fps_times_1million: u64,
    /// Frame width in pixels.
    pub width: u32,
    /// Frame height in pixels.
    pub height: u32,
    /// True if video stream is interlaced.
    pub interlaced: bool,
    /// Number of audio channels.
    pub channels: u32,
    /// Audio sample rate in Hz.
    pub sample_rate: u32,
    /// CHD hunk size in bytes.
    pub hunk_size: u32,
    /// Total logical bytes.
    pub logical_bytes: u64,
    /// Compression codecs.
    pub codecs: [u32; 4],
}

/// Inspects and validates Laserdisc creation parameters without modifying filesystem.
pub fn inspect_create_ld(
    input_path: &Path,
    output_path: &Path,
    options: &CreateLdOptions,
) -> Result<LdCreateInfo, LdError> {
    let file = File::open(input_path)?;
    let reader = AviReader::open(BufReader::with_capacity(2 * 1024 * 1024, file))?;
    let info = reader.info.clone();

    let mut fps_times_1million = info.fps_times_1million;
    let width = info.width;
    let mut height = info.height;
    let interlaced =
        ((fps_times_1million / 1_000_000) <= 30) && height.is_multiple_of(2) && (height > 288);
    let channels = info.channels;
    let rate = info.sample_rate;

    if interlaced {
        fps_times_1million *= 2;
        height /= 2;
    }

    let max_samples_per_frame = (rate as u64 * 1_000_000).div_ceil(fps_times_1million as u64);
    let bytes_per_frame = raw_frame_size(width, height, channels, max_samples_per_frame as u32);
    let hunk_size = options.hunk_size.unwrap_or(bytes_per_frame);

    let interlace_factor: u64 = if interlaced { 2 } else { 1 };
    let total_fields = if reader.info.total_frames > 0 {
        reader.info.total_frames * interlace_factor
    } else {
        return Err(LdError::Invalid(
            "AVI file does not specify total frames in header".into(),
        ));
    };

    let input_start = options.start_frame.unwrap_or(0) * interlace_factor;
    let input_end = options
        .end_frame
        .map(|f| (f * interlace_factor).min(total_fields))
        .unwrap_or(total_fields);

    if input_start >= input_end {
        return Err(LdError::Invalid(format!(
            "start frame {} is >= end frame {}",
            input_start / interlace_factor,
            input_end / interlace_factor
        )));
    }

    let field_count = input_end - input_start;
    let logical_bytes = field_count * hunk_size as u64;
    let codecs = options.codecs.unwrap_or(DEFAULT_LD_CODECS);

    Ok(LdCreateInfo {
        output_path: output_path.to_path_buf(),
        parent_path: options.parent_path.clone(),
        input_path: input_path.to_path_buf(),
        input_start,
        input_length: field_count,
        total_samples: total_fields,
        fps_times_1million: fps_times_1million as u64,
        width,
        height,
        interlaced,
        channels,
        sample_rate: rate,
        hunk_size,
        logical_bytes,
        codecs,
    })
}

/// Creates a Laserdisc CHD container from an input AVI file.
pub fn create_ld<F>(
    input_path: &Path,
    output_path: &Path,
    options: &CreateLdOptions,
    mut progress: F,
) -> Result<CreateResult, LdError>
where
    F: FnMut(ProgressStatus) + Send,
{
    let file = File::open(input_path)?;
    let reader = AviReader::open(BufReader::with_capacity(2 * 1024 * 1024, file))?;
    let info = reader.info.clone();

    // Determine interlacing
    let mut fps_times_1million = info.fps_times_1million;
    let width = info.width;
    let mut height = info.height;
    let interlaced =
        ((fps_times_1million / 1_000_000) <= 30) && height.is_multiple_of(2) && (height > 288);
    let channels = info.channels;
    let rate = info.sample_rate;

    if interlaced {
        fps_times_1million *= 2;
        height /= 2;
    }

    let max_samples_per_frame = (rate as u64 * 1_000_000).div_ceil(fps_times_1million as u64);
    let bytes_per_frame = raw_frame_size(width, height, channels, max_samples_per_frame as u32);
    let hunk_size = options.hunk_size.unwrap_or(bytes_per_frame);

    let interlace_factor: u64 = if interlaced { 2 } else { 1 };
    let total_fields = if reader.info.total_frames > 0 {
        reader.info.total_frames * interlace_factor
    } else {
        return Err(LdError::Invalid(
            "AVI file does not specify total frames in header".into(),
        ));
    };

    let input_start = options.start_frame.unwrap_or(0) * interlace_factor;
    let input_end = options
        .end_frame
        .map(|f| (f * interlace_factor).min(total_fields))
        .unwrap_or(total_fields);

    if input_start >= input_end {
        return Err(LdError::Invalid(format!(
            "start frame {} is >= end frame {}",
            input_start / interlace_factor,
            input_end / interlace_factor
        )));
    }

    let field_count = input_end - input_start;
    let logical_bytes = field_count * hunk_size as u64;
    let compressors = options.codecs.unwrap_or(DEFAULT_LD_CODECS);

    // Parent container setup
    let mut parent_sha1 = [0u8; 20];
    let parent_map = if let Some(parent_p) = &options.parent_path {
        let parent_f = File::open(parent_p)?;
        let mut parent_file = ChdFile::open(BufReader::new(parent_f))?;
        parent_sha1 = parent_file.header().sha1;
        Some(ChdWriter::build_parent_map(
            &mut parent_file,
            hunk_size,
            bytes_per_frame,
        )?)
    } else {
        None
    };

    let config = ChdWriteConfig {
        logical_bytes,
        hunk_bytes: hunk_size,
        unit_bytes: bytes_per_frame,
        compressors,
        parent_sha1,
        num_processors: options.num_processors,
        cancel_token: options.cancel_token.clone(),
    };

    // Construct metadata
    let metadata_str = format!(
        "FPS:{}.{:06} WIDTH:{} HEIGHT:{} INTERLACED:{} CHANNELS:{} SAMPLERATE:{}",
        fps_times_1million / 1_000_000,
        fps_times_1million % 1_000_000,
        width,
        height,
        if interlaced { 1 } else { 0 },
        channels,
        rate
    );
    let metadata = vec![MetadataItem {
        tag: AV_METADATA_TAG,
        flags: 0,
        value: metadata_str.into_bytes(),
    }];

    let mut stream_reader = LdStreamReader::new(
        reader,
        input_start,
        input_end,
        interlace_factor,
        interlaced,
        width as usize,
        height as usize,
        channels as usize,
        rate,
        fps_times_1million,
        hunk_size as usize,
    );

    let output_file = File::create(output_path)?;
    let mut writer = BufWriter::with_capacity(2 * 1024 * 1024, output_file);

    let result = ChdWriter::write_chd_with_parent(
        &mut stream_reader,
        &mut writer,
        &config,
        &metadata,
        parent_map.as_ref(),
        &mut progress,
    );

    match result {
        Ok(res) => Ok(res),
        Err(e) => {
            let _ = std::fs::remove_file(output_path);
            Err(LdError::Chd(e))
        }
    }
}

/// Extracts an AVI movie from a Laserdisc CHD container.
pub fn extract_ld<F>(
    input_path: &Path,
    output_path: &Path,
    options: &ExtractLdOptions,
    mut progress: F,
) -> Result<(), LdError>
where
    F: FnMut(ProgressStatus) + Send,
{
    let chd_f = File::open(input_path)?;
    let mut chd = ChdFile::open(BufReader::with_capacity(1024 * 1024, chd_f))?;

    // Read A/V metadata
    let metadata_entries = chd.read_all_metadata()?;
    let av_entry = metadata_entries
        .into_iter()
        .find(|e| e.metatag == AV_METADATA_TAG)
        .ok_or_else(|| LdError::Invalid("Unable to find A/V metadata in the input CHD".into()))?;
    let metadata_str = std::str::from_utf8(&av_entry.value)
        .map_err(|_| LdError::Invalid("Improperly formatted A/V metadata".into()))?;

    // Parse: FPS:%d.%06d WIDTH:%d HEIGHT:%d INTERLACED:%d CHANNELS:%d RATE:%d
    let (fps_times_1million, width, height, interlaced, channels, rate) =
        parse_av_metadata(metadata_str)?;
    let interlace_factor = if interlaced { 2 } else { 1 };

    let avi_info = AviInfo {
        fps_times_1million: fps_times_1million / (interlace_factor as u32),
        width,
        height: height * (interlace_factor as u32),
        channels,
        sample_rate: rate,
        audio_samples: 0,
        total_frames: chd.header().hunk_count() / interlace_factor,
    };

    let out_file = File::create(output_path)?;
    let mut writer = AviWriter::new(
        BufWriter::with_capacity(2 * 1024 * 1024, out_file),
        avi_info,
    )?;

    let input_start = options.start_frame.unwrap_or(0) * interlace_factor;
    let total_hunks = chd.header().hunk_count();
    let input_end = options
        .end_frame
        .map(|f| (f * interlace_factor).min(total_hunks))
        .unwrap_or(total_hunks);

    let full_frame_height = height * (interlace_factor as u32);
    let mut full_frame = vec![0u8; (width * full_frame_height * 2) as usize];
    let row_bytes = (width * 2) as usize;
    let mut samples: Vec<i16> = Vec::new();

    let count = (input_end - input_start) as usize;
    let mut last_framenum: Option<u64> = None;

    progress(ProgressStatus {
        phase: OperationPhase::Extracting,
        current: 0,
        total: count as u64,
        ratio: None,
    });

    chd.read_hunks_parallel(input_start, count as u64, |framenum, hunk_buffer| {
        if let Some(prev) = last_framenum {
            debug_assert_eq!(
                framenum,
                prev + 1,
                "hunks must be processed in sequential order"
            );
        }
        last_framenum = Some(framenum);

        let step = (framenum - input_start) as usize;
        progress(ProgressStatus {
            phase: OperationPhase::Extracting,
            current: step as u64,
            total: count as u64,
            ratio: None,
        });

        // Validate chav header
        if hunk_buffer.len() < 12 || &hunk_buffer[0..4] != b"chav" {
            return Err(chdlady_core::ChdError::InvalidData(
                "Hunk missing chav header".into(),
            ));
        }

        let metasize = hunk_buffer[4] as usize;
        let num_samples = u16::from_be_bytes([hunk_buffer[6], hunk_buffer[7]]) as usize;
        let field_idx = (framenum % interlace_factor) as usize;

        // Audio extraction
        let mut audio_offset = 12 + metasize;
        for ch in 0..channels as usize {
            samples.clear();
            samples.reserve(num_samples);
            for _ in 0..num_samples {
                let s =
                    i16::from_be_bytes([hunk_buffer[audio_offset], hunk_buffer[audio_offset + 1]]);
                samples.push(s);
                audio_offset += 2;
            }
            writer
                .append_audio_samples(ch, &samples)
                .map_err(|e| chdlady_core::ChdError::InvalidData(e.to_string()))?;
        }

        // Video extraction
        let video_offset = audio_offset;
        let field_video = &hunk_buffer[video_offset..video_offset + (width * height * 2) as usize];

        if interlaced {
            // Write into full_frame: field 0 into even lines, field 1 into odd lines
            for y in 0..height as usize {
                let dst_row = (y * 2 + field_idx) * row_bytes;
                let src_row = y * row_bytes;
                full_frame[dst_row..dst_row + row_bytes]
                    .copy_from_slice(&field_video[src_row..src_row + row_bytes]);
            }
            if (framenum + 1) % 2 == 0 {
                writer
                    .append_video_frame(&full_frame)
                    .map_err(|e| chdlady_core::ChdError::InvalidData(e.to_string()))?;
            }
        } else {
            writer
                .append_video_frame(field_video)
                .map_err(|e| chdlady_core::ChdError::InvalidData(e.to_string()))?;
        }

        Ok(())
    })?;

    progress(ProgressStatus {
        phase: OperationPhase::Extracting,
        current: count as u64,
        total: count as u64,
        ratio: None,
    });
    writer.finish()?;
    Ok(())
}

fn parse_av_metadata(s: &str) -> Result<(u32, u32, u32, bool, u32, u32), LdError> {
    // Format: "FPS:29.970030 WIDTH:720 HEIGHT:240 INTERLACED:1 CHANNELS:2 RATE:48000"
    let mut fps_val = 0u32;
    let mut width = 0u32;
    let mut height = 0u32;
    let mut interlaced = false;
    let mut channels = 0u32;
    let mut rate = 0u32;

    for part in s.split_whitespace() {
        let part = part.trim_matches(|c: char| c.is_whitespace() || c == '\0');
        if let Some(val) = part.strip_prefix("FPS:") {
            let val = val.trim_matches(|c: char| c.is_whitespace() || c == '\0');
            if let Some((int_part, frac_part)) = val.split_once('.') {
                let int_num: u32 = int_part
                    .parse()
                    .map_err(|_| LdError::Invalid(format!("invalid FPS int: {}", int_part)))?;
                let mut frac_str = frac_part.to_string();
                while frac_str.len() < 6 {
                    frac_str.push('0');
                }
                frac_str.truncate(6);
                let frac_num: u32 = frac_str
                    .parse()
                    .map_err(|_| LdError::Invalid(format!("invalid FPS frac: {}", frac_str)))?;
                fps_val = int_num * 1_000_000 + frac_num;
            } else {
                let int_num: u32 = val
                    .parse()
                    .map_err(|_| LdError::Invalid(format!("invalid FPS: {}", val)))?;
                fps_val = int_num * 1_000_000;
            }
        } else if let Some(val) = part.strip_prefix("WIDTH:") {
            let val = val.trim_matches(|c: char| c.is_whitespace() || c == '\0');
            width = val
                .parse()
                .map_err(|_| LdError::Invalid(format!("invalid WIDTH: {}", val)))?;
        } else if let Some(val) = part.strip_prefix("HEIGHT:") {
            let val = val.trim_matches(|c: char| c.is_whitespace() || c == '\0');
            height = val
                .parse()
                .map_err(|_| LdError::Invalid(format!("invalid HEIGHT: {}", val)))?;
        } else if let Some(val) = part.strip_prefix("INTERLACED:") {
            let val = val.trim_matches(|c: char| c.is_whitespace() || c == '\0');
            let i: u32 = val
                .parse()
                .map_err(|_| LdError::Invalid(format!("invalid INTERLACED: {}", val)))?;
            interlaced = i != 0;
        } else if let Some(val) = part.strip_prefix("CHANNELS:") {
            let val = val.trim_matches(|c: char| c.is_whitespace() || c == '\0');
            channels = val
                .parse()
                .map_err(|_| LdError::Invalid(format!("invalid CHANNELS: {}", val)))?;
        } else if let Some(val) = part
            .strip_prefix("SAMPLERATE:")
            .or_else(|| part.strip_prefix("RATE:"))
        {
            let val = val.trim_matches(|c: char| c.is_whitespace() || c == '\0');
            rate = val
                .parse()
                .map_err(|_| LdError::Invalid(format!("invalid SAMPLERATE: {}", val)))?;
        }
    }

    if width == 0 || height == 0 || fps_val == 0 {
        return Err(LdError::Invalid("Incomplete A/V metadata".into()));
    }

    Ok((fps_val, width, height, interlaced, channels, rate))
}

struct LdStreamReader<R: Read + Seek> {
    reader: AviReader<R>,
    framenum: u64,
    input_end: u64,
    interlace_factor: u64,
    interlaced: bool,
    width: usize,
    height: usize,
    channels: usize,
    rate: u32,
    fps_times_1million: u32,
    hunk_size: usize,
    current_frame: Option<Vec<u8>>,
    current_frame_idx: i64,
    next_frames: VecDeque<Vec<u8>>,
    audio_queues: Vec<VecDeque<i16>>,
    audio_samples_popped: u64,
    current_hunk: Vec<u8>,
    hunk_offset: usize,
}

impl<R: Read + Seek> LdStreamReader<R> {
    #[allow(clippy::too_many_arguments)]
    fn new(
        reader: AviReader<R>,
        input_start: u64,
        input_end: u64,
        interlace_factor: u64,
        interlaced: bool,
        width: usize,
        height: usize,
        channels: usize,
        rate: u32,
        fps_times_1million: u32,
        hunk_size: usize,
    ) -> Self {
        Self {
            reader,
            framenum: input_start,
            input_end,
            interlace_factor,
            interlaced,
            width,
            height,
            channels,
            rate,
            fps_times_1million,
            hunk_size,
            current_frame: None,
            current_frame_idx: -1,
            next_frames: VecDeque::new(),
            audio_queues: (0..channels).map(|_| VecDeque::new()).collect(),
            audio_samples_popped: 0,
            current_hunk: Vec::new(),
            hunk_offset: 0,
        }
    }

    fn fill_next_hunk(&mut self) -> io::Result<()> {
        let target_frame_idx = (self.framenum / self.interlace_factor) as i64;
        let field_idx = (self.framenum % self.interlace_factor) as usize;

        // Advance to the target video frame
        while self.current_frame.is_none() || self.current_frame_idx < target_frame_idx {
            if let Some(next) = self.next_frames.pop_front() {
                self.current_frame = Some(next);
                self.current_frame_idx += 1;
                continue;
            }
            match self
                .reader
                .next_chunk()
                .map_err(|e| io::Error::other(e.to_string()))?
            {
                Some(AviChunk::Video(vf)) => {
                    self.current_frame = Some(vf.data);
                    self.current_frame_idx += 1;
                }
                Some(AviChunk::Audio(ab)) => {
                    if ab.channel < self.channels {
                        self.audio_queues[ab.channel].extend(ab.samples);
                    }
                }
                None => break,
            }
        }

        // Determine required audio sample indices for this field
        let first_sample =
            (self.rate as u64 * self.framenum * 1_000_000).div_ceil(self.fps_times_1million as u64);
        let next_sample = (self.rate as u64 * (self.framenum + 1) * 1_000_000)
            .div_ceil(self.fps_times_1million as u64);
        let num_samples = (next_sample - first_sample) as usize;

        // Drop obsolete audio if seeking forward from a non-zero start_frame
        let old_samples = first_sample.saturating_sub(self.audio_samples_popped);
        if old_samples > 0 {
            for q in &mut self.audio_queues {
                let drop_len = (old_samples as usize).min(q.len());
                q.drain(0..drop_len);
            }
            self.audio_samples_popped += old_samples;
        }

        // Ensure we have enough audio samples in the queues up to next_sample
        while self
            .audio_queues
            .iter()
            .any(|q| self.audio_samples_popped + (q.len() as u64) < next_sample)
        {
            match self
                .reader
                .next_chunk()
                .map_err(|e| io::Error::other(e.to_string()))?
            {
                Some(AviChunk::Audio(ab)) => {
                    if ab.channel < self.channels {
                        self.audio_queues[ab.channel].extend(ab.samples);
                    }
                }
                Some(AviChunk::Video(vf)) => {
                    self.next_frames.push_back(vf.data);
                }
                None => break,
            }
        }

        // Build raw frame hunk: 'chav' header (12 bytes) + audio + video
        if self.current_hunk.len() != self.hunk_size {
            self.current_hunk.resize(self.hunk_size, 0);
        } else {
            self.current_hunk.fill(0);
        }

        self.current_hunk[0..4].copy_from_slice(b"chav");
        self.current_hunk[4] = 0; // metasize
        self.current_hunk[5] = self.channels as u8;
        self.current_hunk[6..8].copy_from_slice(&(num_samples as u16).to_be_bytes());
        self.current_hunk[8..10].copy_from_slice(&(self.width as u16).to_be_bytes());
        self.current_hunk[10..12].copy_from_slice(&(self.height as u16).to_be_bytes());

        let mut audio_offset = 12usize;
        for ch in 0..self.channels {
            for s in 0..num_samples {
                let sample_abs = first_sample + s as u64;
                let sample_val = if sample_abs >= self.audio_samples_popped {
                    let rel_idx = (sample_abs - self.audio_samples_popped) as usize;
                    self.audio_queues[ch].get(rel_idx).copied().unwrap_or(0)
                } else {
                    0
                };
                let be_bytes = sample_val.to_be_bytes();
                self.current_hunk[audio_offset] = be_bytes[0];
                self.current_hunk[audio_offset + 1] = be_bytes[1];
                audio_offset += 2;
            }
        }

        // Video data
        let video_offset = audio_offset;
        let row_bytes = self.width * 2;
        if self.interlaced {
            if let Some(ref full_frame) = self.current_frame {
                for y in 0..self.height {
                    let src_row = (y * 2 + field_idx) * row_bytes;
                    let dst_row = video_offset + y * row_bytes;
                    if src_row + row_bytes <= full_frame.len() {
                        self.current_hunk[dst_row..dst_row + row_bytes]
                            .copy_from_slice(&full_frame[src_row..src_row + row_bytes]);
                    }
                }
            }
        } else if let Some(ref full_frame) = self.current_frame {
            let field_len = self.width * self.height * 2;
            let copy_len = field_len.min(full_frame.len());
            self.current_hunk[video_offset..video_offset + copy_len]
                .copy_from_slice(&full_frame[..copy_len]);
        }

        // Drain consumed audio up to next_sample
        let to_pop = next_sample.saturating_sub(self.audio_samples_popped);
        for q in &mut self.audio_queues {
            let pop_len = (to_pop as usize).min(q.len());
            q.drain(0..pop_len);
        }
        self.audio_samples_popped += to_pop;

        self.framenum += 1;
        self.hunk_offset = 0;
        Ok(())
    }
}

impl<R: Read + Seek> Read for LdStreamReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }
        while self.hunk_offset >= self.current_hunk.len() {
            if self.framenum >= self.input_end {
                return Ok(0);
            }
            self.fill_next_hunk()?;
        }
        let available = &self.current_hunk[self.hunk_offset..];
        let to_copy = buf.len().min(available.len());
        buf[..to_copy].copy_from_slice(&available[..to_copy]);
        self.hunk_offset += to_copy;
        Ok(to_copy)
    }
}