oxyromon 0.22.0

Rusty ROM OrgaNizer
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
use super::common::*;
use super::mimetype::*;
use super::progress::*;
use anyhow::{Result, anyhow, bail};
use indicatif::ProgressBar;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::fs::{File, OpenOptions};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncSeekExt, AsyncWriteExt, BufReader, SeekFrom};

#[derive(Clone)]
pub struct GdiRomfile {
    pub gdi_romfile: CommonRomfile,
    pub track_romfiles: Vec<CommonRomfile>,
}

pub trait AsGdi {
    fn as_gdi(self, track_romfiles: Vec<CommonRomfile>) -> Result<GdiRomfile>;
}

pub trait ToGdi {
    async fn to_gdi<P: AsRef<Path>>(
        &self,
        progress_bar: &ProgressBar,
        destination_directory: &P,
    ) -> Result<GdiRomfile>;
}

/// CD sector size in bytes
const SECTOR_SIZE: usize = 2352;

/// CUE sheet parser and GDI converter
#[derive(Debug, Clone)]
pub struct CueSheet {
    pub tracks: Vec<Track>,
    pub catalog: Option<String>,
    pub performer: Option<String>,
    pub songwriter: Option<String>,
    pub title: Option<String>,
    pub comments: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct Track {
    pub number: u32,
    pub data_type: DataType,
    pub data_file: AudioFile,
    pub indices: Vec<Index>,
    pub performer: Option<String>,
    pub songwriter: Option<String>,
    pub title: Option<String>,
    pub comments: Vec<String>,
    pub pregap: Option<Index>,
    pub postgap: Option<Index>,
}

#[derive(Debug, Clone)]
pub struct AudioFile {
    pub filename: String,
    // parsed for CUE sheet fidelity, not consumed by the GDI conversion
    #[allow(dead_code)]
    pub file_type: FileType,
}

#[derive(Debug, Clone)]
pub struct Index {
    // parsed for CUE sheet fidelity, not consumed by the GDI conversion
    #[allow(dead_code)]
    pub number: u32,
    pub minutes: u32,
    pub seconds: u32,
    pub frames: u32,
}

#[derive(Debug, Clone, PartialEq)]
pub enum DataType {
    Audio,
    Mode1_2048,
    Mode1_2352,
    Mode2_2336,
    Mode2_2352,
    Cdg,
    Cdi2336,
    Cdi2352,
}

#[derive(Debug, Clone)]
pub enum FileType {
    Binary,
    Motorola,
    Aiff,
    Wave,
    Mp3,
}

impl CueSheet {
    /// Parse a CUE sheet from a file
    pub async fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let file = File::open(path)
            .await
            .map_err(|e| anyhow!("Failed to open file: {}", e))?;
        let reader = BufReader::new(file);
        let mut lines = Vec::new();
        let mut line_reader = reader.lines();

        while let Some(line) = line_reader
            .next_line()
            .await
            .map_err(|e| anyhow!("Failed to read line: {}", e))?
        {
            let trimmed = line.trim().to_string();
            if !trimmed.is_empty() {
                lines.push(trimmed);
            }
        }

        Self::parse_cue(&mut lines)
    }

    /// Parse CUE sheet from lines
    fn parse_cue(lines: &mut [String]) -> Result<Self> {
        let mut cue_sheet = CueSheet {
            tracks: Vec::new(),
            catalog: None,
            performer: None,
            songwriter: None,
            title: None,
            comments: Vec::new(),
        };

        let mut current_track: Option<Track> = None;
        let mut current_file = AudioFile {
            filename: String::new(),
            file_type: FileType::Binary,
        };

        for line in lines {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.is_empty() {
                continue;
            }

            match parts[0].to_uppercase().as_str() {
                "CATALOG" => {
                    if parts.len() > 1 {
                        cue_sheet.catalog = Some(parts[1].to_string());
                    }
                }
                "PERFORMER" => {
                    let performer = Self::extract_quoted_string(line);
                    if let Some(track) = current_track.as_mut() {
                        track.performer = Some(performer);
                    } else {
                        cue_sheet.performer = Some(performer);
                    }
                }
                "SONGWRITER" => {
                    let songwriter = Self::extract_quoted_string(line);
                    if let Some(track) = current_track.as_mut() {
                        track.songwriter = Some(songwriter);
                    } else {
                        cue_sheet.songwriter = Some(songwriter);
                    }
                }
                "TITLE" => {
                    let title = Self::extract_quoted_string(line);
                    if let Some(track) = current_track.as_mut() {
                        track.title = Some(title);
                    } else {
                        cue_sheet.title = Some(title);
                    }
                }
                "FILE" => {
                    current_file = Self::parse_file(line)?;
                }
                "TRACK" => {
                    // Save previous track
                    if let Some(track) = current_track.take() {
                        cue_sheet.tracks.push(track);
                    }

                    // Create new track
                    if parts.len() >= 3 {
                        let track_number: u32 = parts[1]
                            .parse()
                            .map_err(|e| anyhow!("Failed to parse track number: {}", e))?;
                        let data_type = Self::parse_data_type(parts[2])?;

                        current_track = Some(Track {
                            number: track_number,
                            data_type,
                            data_file: current_file.clone(),
                            indices: Vec::new(),
                            performer: None,
                            songwriter: None,
                            title: None,
                            comments: Vec::new(),
                            pregap: None,
                            postgap: None,
                        });
                    }
                }
                "INDEX" => {
                    if let Some(ref mut track) = current_track
                        && parts.len() >= 3
                    {
                        let index = Self::parse_index(parts[1], parts[2])?;
                        track.indices.push(index);
                    }
                }
                "PREGAP" => {
                    if let Some(ref mut track) = current_track
                        && parts.len() >= 2
                    {
                        let index = Self::parse_index("0", parts[1])?;
                        track.pregap = Some(index);
                    }
                }
                "POSTGAP" => {
                    if let Some(ref mut track) = current_track
                        && parts.len() >= 2
                    {
                        let index = Self::parse_index("0", parts[1])?;
                        track.postgap = Some(index);
                    }
                }
                "REM" => {
                    let comment = line.strip_prefix("REM").unwrap_or("").trim().to_string();
                    if !comment.is_empty() {
                        if let Some(ref mut track) = current_track {
                            track.comments.push(comment);
                        } else {
                            cue_sheet.comments.push(comment);
                        }
                    }
                }
                _ => {} // Ignore unknown commands
            }
        }

        // Save last track
        if let Some(track) = current_track {
            cue_sheet.tracks.push(track);
        }

        Ok(cue_sheet)
    }

    fn extract_quoted_string(line: &str) -> String {
        if let Some(start) = line.find('"')
            && let Some(end) = line.rfind('"')
            && start < end
        {
            return line[start + 1..end].to_string();
        }
        // Fallback: take everything after the first space
        line.split_whitespace()
            .skip(1)
            .collect::<Vec<_>>()
            .join(" ")
    }

    fn parse_file(line: &str) -> Result<AudioFile> {
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() < 3 {
            bail!("Invalid FILE command: {}", line);
        }

        let filename = Self::extract_quoted_string(line);
        let file_type = match parts.last().unwrap().to_uppercase().as_str() {
            "BINARY" => FileType::Binary,
            "MOTOROLA" => FileType::Motorola,
            "AIFF" => FileType::Aiff,
            "WAVE" => FileType::Wave,
            "MP3" => FileType::Mp3,
            _ => FileType::Binary,
        };

        Ok(AudioFile {
            filename,
            file_type,
        })
    }

    fn parse_data_type(data_type_str: &str) -> Result<DataType> {
        match data_type_str.to_uppercase().as_str() {
            "AUDIO" => Ok(DataType::Audio),
            "MODE1/2048" => Ok(DataType::Mode1_2048),
            "MODE1/2352" => Ok(DataType::Mode1_2352),
            "MODE2/2336" => Ok(DataType::Mode2_2336),
            "MODE2/2352" => Ok(DataType::Mode2_2352),
            "CDG" => Ok(DataType::Cdg),
            "CDI/2336" => Ok(DataType::Cdi2336),
            "CDI/2352" => Ok(DataType::Cdi2352),
            _ => Ok(DataType::Audio), // Default
        }
    }

    fn parse_index(number_str: &str, time_str: &str) -> Result<Index> {
        let number: u32 = number_str
            .parse()
            .map_err(|e| anyhow!("Failed to parse index number: {}", e))?;
        let time_parts: Vec<&str> = time_str.split(':').collect();

        if time_parts.len() != 3 {
            bail!("Invalid time format: {}", time_str);
        }

        let minutes: u32 = time_parts[0]
            .parse()
            .map_err(|e| anyhow!("Failed to parse minutes: {}", e))?;
        let seconds: u32 = time_parts[1]
            .parse()
            .map_err(|e| anyhow!("Failed to parse seconds: {}", e))?;
        let frames: u32 = time_parts[2]
            .parse()
            .map_err(|e| anyhow!("Failed to parse frames: {}", e))?;

        Ok(Index {
            number,
            minutes,
            seconds,
            frames,
        })
    }

    /// Convert CUE/BIN to GDI format
    pub async fn convert_to_gdi<P: AsRef<Path>>(
        &self,
        working_directory: P,
        destination_directory: P,
    ) -> Result<(String, Vec<PathBuf>)> {
        let mut current_sector = 0;
        let mut gdi_output = String::new();
        let mut track_paths = Vec::new();

        // Write track count
        gdi_output.push_str(&format!("{}\n", self.tracks.len()));

        for track in &self.tracks {
            let input_track_path = working_directory.as_ref().join(&track.data_file.filename);
            let can_perform_full_copy = track.indices.len() == 1;

            let input_filename = Path::new(&track.data_file.filename)
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("track");

            let extension = if track.data_type == DataType::Audio {
                RAW_EXTENSION
            } else {
                BIN_EXTENSION
            };

            let output_filename = format!("{}.{}", input_filename, extension);
            let output_track_path = destination_directory.as_ref().join(&output_filename);

            let sector_amount = if can_perform_full_copy {
                self.copy_full_file(&input_track_path, &output_track_path)
                    .await?
            } else {
                let gap_offset = if track.indices.len() > 1 {
                    self.count_index_frames(&track.indices[1])
                } else {
                    0
                };
                let sectors = self
                    .copy_file_with_gap_offset(&input_track_path, &output_track_path, gap_offset)
                    .await?;
                current_sector += gap_offset;
                sectors
            };

            let gap = 0; // Placeholder for gap value
            let track_type = if track.data_type == DataType::Audio {
                "0"
            } else {
                "4"
            };

            gdi_output.push_str(&format!(
                "{} {} {} {} \"{}\" {}\n",
                track.number, current_sector, track_type, SECTOR_SIZE, output_filename, gap
            ));

            current_sector += sector_amount;

            // Check for HIGH-DENSITY AREA comment
            if track
                .comments
                .iter()
                .any(|c| c.contains("HIGH-DENSITY AREA"))
                && current_sector < 45000
            {
                current_sector = 45000;
            }

            track_paths.push(output_track_path);
        }

        Ok((gdi_output, track_paths))
    }

    async fn copy_full_file<P: AsRef<Path>>(&self, input_path: P, output_path: P) -> Result<u32> {
        tokio::fs::copy(&input_path, &output_path)
            .await
            .map_err(|e| anyhow!("Failed to copy file: {}", e))?;
        let metadata = tokio::fs::metadata(&input_path)
            .await
            .map_err(|e| anyhow!("Failed to get metadata: {}", e))?;
        let file_size = metadata.len();
        Ok((file_size / SECTOR_SIZE as u64) as u32)
    }

    async fn copy_file_with_gap_offset<P: AsRef<Path>>(
        &self,
        input_path: P,
        output_path: P,
        frames: u32,
    ) -> Result<u32> {
        let mut input_file = File::open(&input_path)
            .await
            .map_err(|e| anyhow!("Failed to open input file: {}", e))?;
        let mut output_file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&output_path)
            .await
            .map_err(|e| anyhow!("Failed to open output file: {}", e))?;

        // Skip gap frames
        let skip_bytes = frames as u64 * SECTOR_SIZE as u64;
        input_file
            .seek(SeekFrom::Start(skip_bytes))
            .await
            .map_err(|e| anyhow!("Failed to seek: {}", e))?;

        // Calculate remaining sectors
        let metadata = input_file
            .metadata()
            .await
            .map_err(|e| anyhow!("Failed to get metadata: {}", e))?;
        let total_size = metadata.len();
        let remaining_size = total_size - skip_bytes;
        let sector_count = (remaining_size / SECTOR_SIZE as u64) as u32;

        // Copy data in sector-sized chunks
        let mut buffer = vec![0u8; SECTOR_SIZE];
        let mut _copied_sectors = 0;

        loop {
            let bytes_read = input_file
                .read(&mut buffer)
                .await
                .map_err(|e| anyhow!("Failed to read: {}", e))?;
            if bytes_read == 0 {
                break;
            }
            output_file
                .write_all(&buffer[..bytes_read])
                .await
                .map_err(|e| anyhow!("Failed to write: {}", e))?;
            if bytes_read == SECTOR_SIZE {
                _copied_sectors += 1;
            }
        }

        output_file
            .flush()
            .await
            .map_err(|e| anyhow!("Failed to flush: {}", e))?;
        Ok(sector_count)
    }

    fn count_index_frames(&self, index: &Index) -> u32 {
        index.frames + (index.seconds * 75) + (index.minutes * 60 * 75)
    }
}

// === GDI TRAIT IMPLEMENTATIONS ===

impl AsGdi for CommonRomfile {
    fn as_gdi(self, track_romfiles: Vec<CommonRomfile>) -> Result<GdiRomfile> {
        if self
            .path
            .extension()
            .unwrap()
            .to_str()
            .unwrap()
            .to_lowercase()
            != GDI_EXTENSION
        {
            bail!("Not a valid gdi");
        }
        // Validate track files (can be .bin, .raw, or other valid extensions)
        for track_romfile in &track_romfiles {
            let extension = track_romfile
                .path
                .extension()
                .unwrap()
                .to_str()
                .unwrap()
                .to_lowercase();
            if extension != BIN_EXTENSION && extension != RAW_EXTENSION {
                bail!("Not a valid track file extension: {}", extension);
            }
        }
        Ok(GdiRomfile {
            gdi_romfile: self,
            track_romfiles,
        })
    }
}

impl ToGdi for CueBinRomfile {
    async fn to_gdi<P: AsRef<Path>>(
        &self,
        progress_bar: &ProgressBar,
        destination_directory: &P,
    ) -> Result<GdiRomfile> {
        progress_bar.set_message("Converting CUE/BIN to GDI");
        progress_bar.set_style(get_none_progress_style());
        progress_bar.enable_steady_tick(Duration::from_millis(100));

        // Parse the CUE file to understand the track structure
        let cue_sheet = CueSheet::from_file(&self.cue_romfile.path).await?;

        // Convert to GDI format
        let (gdi_content, track_paths) = cue_sheet
            .convert_to_gdi(
                self.cue_romfile.path.parent().unwrap(),
                destination_directory.as_ref(),
            )
            .await?;

        // Create the GDI file
        let gdi_path = destination_directory
            .as_ref()
            .join(self.cue_romfile.path.file_name().unwrap())
            .with_extension(GDI_EXTENSION);
        tokio::fs::write(&gdi_path, gdi_content)
            .await
            .map_err(|e| anyhow!("Failed to write GDI file: {}", e))?;

        // Collect the track romfiles that were created by the conversion
        let track_romfiles = track_paths
            .into_iter()
            .map(|path| CommonRomfile::from_path(&path))
            .collect::<Result<Vec<CommonRomfile>>>()?;

        progress_bar.set_message("");
        progress_bar.disable_steady_tick();

        Ok(GdiRomfile {
            gdi_romfile: CommonRomfile::from_path(&gdi_path)?,
            track_romfiles,
        })
    }
}