nds_cart 0.4.1

NDS file header library and utilities.
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
// SPDX-License-Identifier: LGPL-2.1-or-later OR GPL-2.0-or-later OR MPL-2.0
// SPDX-FileCopyrightText: 2026 Gabriel Marcano <gabemarcano@yahoo.com>

use crate::error::Error;

use std::fmt;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::str::from_utf8;

use byteorder::LittleEndian;
use byteorder::ReadBytesExt;

use crc::Crc;

/// Represents the destination language of the cartridge.
///
/// Determined from the last character of the [`Metadata::game_code`] field.
#[derive(Debug)]
pub enum LanguageRegion {
    Japanese,
    English,
    German,
    French,
    Italian,
    Spanish,
    NotApplicable,
    Asian,
    Chinese,
    Dutch,
    Korean,
    USA2,
    Swedish,
    Nor,
    Int,
    Europe,
    Danish,
    Russian,
    USAAUS,
    Australia,
    EURAUS,
    Europe2,
    Europe3,
    Europe4,
    Europe5,
    Unknown(char),
}

impl fmt::Display for LanguageRegion {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Japanese => write!(fmt, "Japanese")?,
            Self::English => write!(fmt, "English")?,
            Self::German => write!(fmt, "German")?,
            Self::French => write!(fmt, "French")?,
            Self::Italian => write!(fmt, "Italian")?,
            Self::Spanish => write!(fmt, "Spanish")?,
            Self::NotApplicable => write!(fmt, "not applicable")?,
            Self::Asian => write!(fmt, "Asian")?,
            Self::Chinese => write!(fmt, "Chinese")?,
            Self::Dutch => write!(fmt, "Dutch")?,
            Self::Korean => write!(fmt, "Korean")?,
            Self::USA2 => write!(fmt, "USA2")?,
            Self::Swedish => write!(fmt, "Swedish")?,
            Self::Nor => write!(fmt, "Nor")?,
            Self::Int => write!(fmt, "Int")?,
            Self::Europe => write!(fmt, "Europe")?,
            Self::Danish => write!(fmt, "Danish")?,
            Self::Russian => write!(fmt, "Russian")?,
            Self::USAAUS => write!(fmt, "USA + Australia")?,
            Self::Australia => write!(fmt, "Australia")?,
            Self::EURAUS => write!(fmt, "Europe + Australia")?,
            Self::Europe2 => write!(fmt, "Europe 2")?,
            Self::Europe3 => write!(fmt, "Europe 3")?,
            Self::Europe4 => write!(fmt, "Eurioe 4")?,
            Self::Europe5 => write!(fmt, "Europe 5")?,
            Self::Unknown(ch) => write!(fmt, "Unknown region, code {ch}")?,
        }
        Ok(())
    }
}

impl TryFrom<u8> for LanguageRegion {
    type Error = Error;
    fn try_from(data: u8) -> Result<Self, Error> {
        if !data.is_ascii() {
            return Err(Error::Parse("invalid language character".into()));
        }
        let data = data as char;
        Ok(match data {
            'J' => Self::Japanese,
            'E' => Self::English,
            'P' => Self::Europe,
            'D' => Self::German,
            'F' => Self::French,
            'I' => Self::Italian,
            'S' => Self::Spanish,
            'B' | 'G' => Self::NotApplicable,
            'A' => Self::Asian,
            'C' => Self::Chinese,
            'H' => Self::Dutch,
            'K' => Self::Korean,
            'L' => Self::USA2,
            'M' => Self::Swedish,
            'N' => Self::Nor,
            'O' => Self::Int,
            'Q' => Self::Danish,
            'R' => Self::Russian,
            'T' => Self::USAAUS,
            'U' => Self::Australia,
            'V' => Self::EURAUS,
            'W' => Self::Europe2,
            'X' => Self::Europe3,
            'Y' => Self::Europe4,
            'Z' => Self::Europe5,
            _ => Self::Unknown(data),
        })
    }
}

/// Represents the region the cartrige is designed for.
#[derive(Debug)]
pub enum Region {
    Normal,
    China,
    Korea,
    Unknown(u8),
}

impl From<u8> for Region {
    fn from(data: u8) -> Self {
        match data {
            0 => Self::Normal,
            0x80 => Self::China,
            0x40 => Self::Korea,
            _ => Self::Unknown(data),
        }
    }
}

impl fmt::Display for Region {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Normal => write!(fmt, "Normal"),
            Self::China => write!(fmt, "China"),
            Self::Korea => write!(fmt, "Korea"),
            Self::Unknown(data) => write!(fmt, "unknown region {data}"),
        }
    }
}

/// Manufacturer/Publisher(?) of the cartridge.
#[derive(Debug)]
pub enum Manufacturer {
    Nintendo,
    Capcom,
    SquareEnix,
    Thq,
    Other([u8; 2]),
}

impl fmt::Display for Manufacturer {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Nintendo => write!(fmt, "Nintendo"),
            Self::Capcom => write!(fmt, "Capcom"),
            Self::SquareEnix => write!(fmt, "Square Enix"),
            Self::Thq => write!(fmt, "THQ"),
            Self::Other(code) => write!(fmt, "Unknown {:02X}{:02X}", code[0], code[1]),
        }
    }
}

impl TryFrom<&str> for Manufacturer {
    type Error = Error;
    fn try_from(data: &str) -> Result<Self, Error> {
        if data.len() != 2 || !data.is_ascii() {
            return Err(Error::Parse("invalid  manufacturer code".into()));
        }

        let data = data.as_bytes();

        Ok(match data {
            [48, 49] => Self::Nintendo,   // == "01"
            [48, 56] => Self::Capcom,     // == "08"
            [71, 68] => Self::SquareEnix, // == "GD
            [55, 56] => Self::Thq,        // == "78"
            _ => Self::Other([data[0], data[1]]),
        })
    }
}

/// The type of device the cartridge is meant to run on.
#[derive(Debug)]
pub enum UnitCode {
    Nds,
    NdsDsi,
    Dsi,
}

impl TryFrom<u8> for UnitCode {
    type Error = Error;
    fn try_from(data: u8) -> Result<Self, Self::Error> {
        match data {
            0 => Ok(Self::Nds),
            1 => Ok(Self::NdsDsi),
            2 => Ok(Self::Dsi),
            _ => Err(Self::Error::Parse("unable to parse unit code".into())),
        }
    }
}

impl fmt::Display for UnitCode {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Nds => write!(fmt, "NDS"),
            Self::NdsDsi => write!(fmt, "NDS + DSi"),
            Self::Dsi => write!(fmt, "DSi"),
        }
    }
}

/// Represents the metadata held by the NDS internal header.
#[derive(Debug)]
pub struct Metadata {
    /// The title of the game cartridge. Up to 12 uppercase ASCII characters, padded with '\0'.
    pub title: String,
    /// The unique gamecode for the cartridge. 4 uppercase ASCII characters.
    /// The first character is some sort of class, the second and third form a unique identifier
    /// for the game, and the last is the language/region of the game.
    pub game_code: String,
    /// The manufacturer/publisher of the cartridge.
    pub manufacturer: Manufacturer,
    /// The type of unit that can play the cartridge.
    pub unit_code: UnitCode,
    pub encryption_seed_select: u8,
    /// The maximum amount of data the ROM can store, in KiB.
    pub device_capacity: u32,
    /// The language of the cartridge. Determined by the final character of the game code.
    pub language: LanguageRegion,
    /// The region the cartridge is made for.
    pub region: Region,
    /// The version of the ROM.
    pub version: u8,
    /// Whether or not to skip "Press Buttom" on the Health and Safety screen.
    pub autostart: bool,
    /// The location of the ARM9 code in the ROM.
    pub arm9_rom_offset: u32,
    /// The entry address of the ARM9 code.
    pub arm9_entry_address: u32,
    /// The location of RAM for the ARM9 code.
    pub arm9_ram_address: u32,
    /// The size of the ARM9 code in bytes.
    pub arm9_size: u32,
    /// The location of the ARM7 code in the ROM.
    pub arm7_rom_offset: u32,
    /// The entry address of the ARM7 code.
    pub arm7_entry_address: u32,
    /// The location of the RAM for the ARM7 code.
    pub arm7_ram_address: u32,
    /// The size of the ARM7 code in bytes.
    pub arm7_size: u32,
    /// The location of the File Name Table (FNT) in the ROM.
    pub file_name_table_offset: u32,
    /// The size of the FNT in bytes.
    pub file_name_table_size: u32,
    /// The location of the File Allocation Table (FAT) in the ROM.
    pub file_allocation_table_offset: u32,
    /// The size of the FAT in bytes.
    pub file_allocation_table_size: u32,
    pub arm9_overlay_offset: u32,
    pub arm9_overlay_size: u32,
    pub arm7_overlay_offset: u32,
    pub arm7_overlay_size: u32,
    /// ROM access control settings, controls the access speed to read from the cartridge.
    pub romctl_setting_normal: u32,
    /// ROM access control settings, controls the access speed to read from the cartridge.
    pub romctl_setting_key1: u32,
    /// The location of the game preview icon in the ROM.
    pub icon_offset: u32,
    /// The checksum of the Secure Area (0x20 to 0x7FFF, inclusive).
    pub secure_area_checksum: u16,
    /// The delay to access Secure Area memory (in units of a 131kHz clock ticks).
    pub secure_area_delay: u16,
    pub arm9_autoload: u32,
    pub arm7_autoload: u32,
    pub secure_area_disable: u64,
    /// The amount of ROM that is actually used, in bytes.
    pub used_rom_size: u32,
    /// The size of the header (usually/always it's 0x4000)
    pub rom_header_size: u32,
    /// The end of the read-only area of the cartridge, in 0x20000 units.
    pub nand_end_of_rom: u16, // in 0x20000 units
    /// The start of the read-write area of the cartridge, in 0x20000 units.
    pub nand_start_of_rw: u16,
    /// The compressed Nintendo logo, same as in GBA headers.
    pub nintendo_logo: [u8; 156],
    /// The checksum of the logo. For a legitimate cartridge, this should be 0xCF56.
    pub nintendo_logo_checksum: u16,
    /// The checksum of the header contents (0x000 to 0x15D, inclusive).
    pub header_checksum: u16,
    pub debug_rom_offset: u32,
    pub debug_size: u32,
    pub debug_ram_address: u32,
}

pub trait MetadataRead {
    /// Parses the NDS ROM metadata from the object provided, returning a [`Metadata`] object with the
    /// header metadata.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Parse`] if the header cannot be found or if a field in the header contains
    /// an unexpected value.
    /// Returns [`Error::Io`] if an IO error took place while reading from the file.
    fn read_nds_header(&mut self) -> Result<Metadata, Error>;
}

impl Metadata {
    /// Returns a new Metadata instance, using the provided Readable and Seekable object as the
    /// underlying data source representing the cart.
    ///
    /// # Errors
    ///
    /// See [`MetadataRead::read_nds_header`] for error deetails.
    pub fn try_from<T: Read + Seek>(io: &mut T) -> Result<Self, Error> {
        io.read_nds_header()
    }
}

/// Trims null and whitespace characters (in that order) from the given string.
fn trim(string: &str) -> &str {
    string.trim_matches('\0').trim()
}

impl<T: Read + Seek> MetadataRead for T {
    fn read_nds_header(&mut self) -> Result<Metadata, Error> {
        self.seek(SeekFrom::Start(0))?;

        let mut title = [0u8; 12];
        self.read_exact(&mut title)?;
        let title = trim(from_utf8(&title)?).to_string();
        let mut game_code = [0u8; 4];
        self.read_exact(&mut game_code)?;
        let language: LanguageRegion = game_code[3].try_into()?;
        let game_code = trim(from_utf8(&game_code)?).to_string();
        let mut manufacturer_code = [0u8; 2];
        self.read_exact(&mut manufacturer_code)?;
        let manufacturer_code = trim(from_utf8(&manufacturer_code)?);
        let manufacturer = manufacturer_code.try_into()?;
        let unit_code: UnitCode = self.read_u8()?.try_into()?;

        let encryption_seed_select = self.read_u8()?;
        let device_capacity: u32 = 128 << self.read_u8()?;

        self.seek(SeekFrom::Current(8))?;
        let region: Region = self.read_u8()?.into();
        let version = self.read_u8()?;
        let autostart = self.read_u8()? != 0;
        let arm9_rom_offset = self.read_u32::<LittleEndian>()?;
        let arm9_entry_address = self.read_u32::<LittleEndian>()?;
        let arm9_ram_address = self.read_u32::<LittleEndian>()?;
        let arm9_size = self.read_u32::<LittleEndian>()?;
        let arm7_rom_offset = self.read_u32::<LittleEndian>()?;
        let arm7_entry_address = self.read_u32::<LittleEndian>()?;
        let arm7_ram_address = self.read_u32::<LittleEndian>()?;
        let arm7_size = self.read_u32::<LittleEndian>()?;
        let file_name_table_offset = self.read_u32::<LittleEndian>()?;
        let file_name_table_size = self.read_u32::<LittleEndian>()?;
        let file_allocation_table_offset = self.read_u32::<LittleEndian>()?;
        let file_allocation_table_size = self.read_u32::<LittleEndian>()?;
        let arm9_overlay_offset = self.read_u32::<LittleEndian>()?;
        let arm9_overlay_size = self.read_u32::<LittleEndian>()?;
        let arm7_overlay_offset = self.read_u32::<LittleEndian>()?;
        let arm7_overlay_size = self.read_u32::<LittleEndian>()?;
        let romctl_setting_normal = self.read_u32::<LittleEndian>()?;
        let romctl_setting_key1 = self.read_u32::<LittleEndian>()?;
        let icon_offset = self.read_u32::<LittleEndian>()?;
        let secure_area_checksum = self.read_u16::<LittleEndian>()?;
        let secure_area_delay = self.read_u16::<LittleEndian>()?; // clocked at 130.912kHz
        let arm9_autoload = self.read_u32::<LittleEndian>()?;
        let arm7_autoload = self.read_u32::<LittleEndian>()?;
        let secure_area_disable = self.read_u64::<LittleEndian>()?;
        let used_rom_size = self.read_u32::<LittleEndian>()?;
        let rom_header_size = self.read_u32::<LittleEndian>()?;
        self.seek(SeekFrom::Current(12))?;
        let nand_end_of_rom = self.read_u16::<LittleEndian>()?;
        let nand_start_of_rw = self.read_u16::<LittleEndian>()?;
        self.seek(SeekFrom::Current(0x28))?;
        let mut nintendo_logo = [0u8; 156];
        self.read_exact(&mut nintendo_logo)?;
        let nintendo_logo_checksum = self.read_u16::<LittleEndian>()?;
        let header_checksum = self.read_u16::<LittleEndian>()?;
        let debug_rom_offset = self.read_u32::<LittleEndian>()?;
        let debug_size = self.read_u32::<LittleEndian>()?;
        let debug_ram_address = self.read_u32::<LittleEndian>()?;

        Ok(Metadata {
            title,
            game_code,
            manufacturer,
            unit_code,
            encryption_seed_select,
            device_capacity,
            language,
            region,
            version,
            autostart,
            arm9_rom_offset,
            arm9_entry_address,
            arm9_ram_address,
            arm9_size,
            arm7_rom_offset,
            arm7_entry_address,
            arm7_ram_address,
            arm7_size,
            file_name_table_offset,
            file_name_table_size,
            file_allocation_table_offset,
            file_allocation_table_size,
            arm9_overlay_offset,
            arm9_overlay_size,
            arm7_overlay_offset,
            arm7_overlay_size,
            romctl_setting_normal,
            romctl_setting_key1,
            icon_offset,
            secure_area_checksum,
            secure_area_delay,
            arm9_autoload,
            arm7_autoload,
            secure_area_disable,
            used_rom_size,
            rom_header_size,
            nand_end_of_rom,
            nand_start_of_rw,
            nintendo_logo,
            nintendo_logo_checksum,
            header_checksum,
            debug_rom_offset,
            debug_size,
            debug_ram_address,
        })
    }
}

/// Scale a 5 bit value to 8 bits
#[allow(clippy::cast_possible_truncation)]
const fn scale_5bits_to_8bits(data: u16) -> u8 {
    ((data & 0x1F) * 0xFF / 0x1F) as u8
}

/// Represents an RGBA pixel, with values in that order.
struct RGBAPixel(u8, u8, u8, u8);

impl Metadata {
    /// Computes the checksum of the NDS header.
    ///
    /// # Errors
    /// Returns [`Error::Io`] if there are any issues reading or seeking the underlying data.
    pub fn header_checksum<T: Read + Seek>(&mut self, io: &mut T) -> Result<u16, Error> {
        let crc = Crc::<u16>::new(&crc::CRC_16_MODBUS);
        io.seek(SeekFrom::Start(0))?;
        //let mut checksum = 0u8;
        let mut data = [0u8; 0x15E];
        // It's faster to read in the entire header
        io.read_exact(&mut data)?;
        Ok(crc.checksum(&data))
    }

    /// Returns the NDS icon a 32x32 RGBA8888 image.
    ///
    /// # Errors
    /// Returns [`Error::Io`] if there are any issues reading or seeking the underlying data.
    pub fn extract_rgba_icon<T: Read + Seek>(&mut self, io: &mut T) -> Result<Vec<u8>, Error> {
        let width = 32;
        let height = 32;
        let tile_w = 8;
        let tile_h = 8;
        let mut index = 0;
        let mut output = vec![0u8; width * height * 4];
        let icon_offset = self.icon_offset;
        let bitmap_offset = 0x20;
        io.seek(SeekFrom::Start(u64::from(icon_offset + bitmap_offset)))?;
        let mut bitmap = vec![0u8; 0x200];
        io.read_exact(&mut bitmap)?;
        let mut palette = vec![0u16; 0x10];
        io.read_u16_into::<LittleEndian>(&mut palette)?;

        // https://problemkaputt.de/gbatek-ds-cartridge-icon-title.htm
        // 0020h 200h  Icon Bitmap  (32x32 pix) (4x4 tiles, 4bit depth) (4x8 bytes/tile)
        //
        // To be much, much clearer, the full picture is 32x32. It consists of
        // 16 tiles, or 4 tiles by 4 tiles. Each tile is 8x8 pixels. In memory,
        // they're stored in rows. Each nibble corresponds to a pixel. The low
        // nibble of a byte corresponds to an earlier/left pixel.

        // 8x8 tiles
        for y in (0..height).step_by(tile_h) {
            for x in (0..width).step_by(tile_w) {
                // Iterate through each pixel in the tile
                for ty in 0..tile_h {
                    for tx in 0..tile_w {
                        let pixel: u8 = (bitmap[index] >> (4 * (tx % 2))) & 0xF;
                        if (tx % 2) == 1 {
                            index += 1;
                        }
                        let pixel = if pixel == 0 {
                            RGBAPixel(0xFF, 0xFF, 0xFF, 0)
                        } else {
                            let color16 = palette[usize::from(pixel)];
                            RGBAPixel(
                                scale_5bits_to_8bits(color16),
                                scale_5bits_to_8bits(color16 >> 5),
                                scale_5bits_to_8bits(color16 >> 10),
                                0xFF,
                            )
                        };

                        output[4 * ((y + ty) * 32 + (x + tx))] = pixel.0;
                        output[4 * ((y + ty) * 32 + (x + tx)) + 1] = pixel.1;
                        output[4 * ((y + ty) * 32 + (x + tx)) + 2] = pixel.2;
                        output[4 * ((y + ty) * 32 + (x + tx)) + 3] = pixel.3;
                    }
                }
            }
        }
        Ok(output)
    }
}