ines-parser 1.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,346 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Split iNES ROM files into PRG and CHR components.
4
+
5
+ This script extracts PRG ROM and CHR ROM from iNES format files,
6
+ supporting both plain .nes files and .7z archives.
7
+ """
8
+
9
+ import argparse
10
+ import io
11
+ import os
12
+ import sys
13
+ from pathlib import Path
14
+ from typing import BinaryIO, Tuple
15
+
16
+ # Repo root on path when running this file directly (not via pip console_scripts)
17
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
18
+
19
+ # Try to import libarchive - make it optional
20
+ try:
21
+ import libarchive
22
+ LIBARCHIVE_AVAILABLE = True
23
+ except ImportError:
24
+ LIBARCHIVE_AVAILABLE = False
25
+
26
+ # Import from ines_parser package
27
+ from ines_parser import parse_ines_header, INES_HEADER_SIZE, INES_TRAINER_SIZE
28
+
29
+ # Constants
30
+ SUPPORTED_EXTENSIONS = {'.nes'}
31
+ ALL_ARCHIVE_EXTENSIONS = {'.7z', '.zip', '.rar'}
32
+ ARCHIVE_EXTENSIONS = ALL_ARCHIVE_EXTENSIONS if LIBARCHIVE_AVAILABLE else set()
33
+
34
+
35
+ class ROMExtractionError(Exception):
36
+ """Exception raised when ROM extraction fails."""
37
+ pass
38
+
39
+
40
+ def generate_output_filenames(input_filename: str) -> Tuple[str, str]:
41
+ """
42
+ Generate output filenames for PRG and CHR ROM files.
43
+
44
+ Args:
45
+ input_filename: Input file name
46
+
47
+ Returns:
48
+ Tuple of (prg_filename, chr_filename)
49
+ """
50
+ path = Path(input_filename)
51
+
52
+ if path.suffix in SUPPORTED_EXTENSIONS:
53
+ base_name = path.stem
54
+ else:
55
+ base_name = path.name
56
+
57
+ prg_fname = f"{base_name}.prg.bin"
58
+ chr_fname = f"{base_name}.chr.bin"
59
+
60
+ return prg_fname, chr_fname
61
+
62
+
63
+ def check_overwrite_permission(prg_fname: str, chr_fname: str, force: bool,
64
+ write_prg: bool = True, write_chr: bool = True) -> bool:
65
+ """
66
+ Check if output files exist and get user permission to overwrite.
67
+
68
+ Args:
69
+ prg_fname: PRG output filename
70
+ chr_fname: CHR output filename
71
+ force: If True, skip confirmation and allow overwrite
72
+ write_prg: If True, PRG output file will be written
73
+ write_chr: If True, CHR output file will be written
74
+
75
+ Returns:
76
+ True if overwrite is allowed, False otherwise
77
+ """
78
+ prg_exists = write_prg and Path(prg_fname).exists()
79
+ chr_exists = write_chr and Path(chr_fname).exists()
80
+
81
+ if not (prg_exists or chr_exists):
82
+ return True # No files to overwrite
83
+
84
+ if force:
85
+ return True # Force overwrite
86
+
87
+ # Check if we're in an interactive terminal
88
+ if not sys.stdin.isatty():
89
+ # Not interactive, print error and exit
90
+ existing_files = []
91
+ if prg_exists:
92
+ existing_files.append(prg_fname)
93
+ if chr_exists:
94
+ existing_files.append(chr_fname)
95
+ print(f"Error: Output files already exist: {', '.join(existing_files)}", file=sys.stderr)
96
+ print("Use --force to overwrite existing files", file=sys.stderr)
97
+ return False
98
+
99
+ # Interactive mode - ask for confirmation
100
+ existing_files = []
101
+ if prg_exists:
102
+ existing_files.append(prg_fname)
103
+ if chr_exists:
104
+ existing_files.append(chr_fname)
105
+
106
+ print(f"Warning: Output files already exist: {', '.join(existing_files)}", file=sys.stderr)
107
+ try:
108
+ response = input("Overwrite existing files? [y/N]: ").strip().lower()
109
+ except KeyboardInterrupt:
110
+ # User pressed Ctrl-C, exit gracefully
111
+ print(file=sys.stderr) # New line after ^C
112
+ sys.exit(130) # Standard exit code for SIGINT
113
+
114
+ return response in ('y', 'yes')
115
+
116
+
117
+ def extract_rom_data(file_name: str, nes_file: BinaryIO, force: bool = False) -> None:
118
+ """
119
+ Extract PRG and CHR ROM data from an iNES file.
120
+
121
+ Args:
122
+ file_name: Name of the ROM file (for output naming)
123
+ nes_file: File-like object containing the ROM data
124
+ force: If True, overwrite existing files without confirmation
125
+
126
+ Raises:
127
+ ROMExtractionError: If extraction fails or overwrite denied
128
+ """
129
+ # Parse header
130
+ header_data = nes_file.read(INES_HEADER_SIZE)
131
+ if len(header_data) < INES_HEADER_SIZE:
132
+ raise ROMExtractionError(f"File too short: only {len(header_data)} bytes")
133
+
134
+ header = parse_ines_header(header_data)
135
+ if not header or not header.is_valid():
136
+ raise ROMExtractionError(f"Not a valid iNES file")
137
+
138
+ # Generate output filenames
139
+ prg_fname, chr_fname = generate_output_filenames(file_name)
140
+
141
+ # Check if files exist and get permission to overwrite
142
+ if not check_overwrite_permission(
143
+ prg_fname,
144
+ chr_fname,
145
+ force,
146
+ write_prg=header.prg_rom_size > 0,
147
+ write_chr=header.chr_rom_size > 0
148
+ ):
149
+ raise ROMExtractionError("Overwrite cancelled by user")
150
+
151
+ # Calculate expected file size from header
152
+ trainer_size = INES_TRAINER_SIZE if header.has_trainer else 0
153
+ expected_file_size = INES_HEADER_SIZE + trainer_size + header.prg_rom_size + header.chr_rom_size
154
+
155
+ # Seek to start of ROM data (skip header and optional trainer)
156
+ nes_file.seek(INES_HEADER_SIZE + trainer_size, 0)
157
+
158
+ # Extract PRG ROM
159
+ if header.prg_rom_size > 0:
160
+ prg_data = nes_file.read(header.prg_rom_size)
161
+ if len(prg_data) < header.prg_rom_size:
162
+ raise ROMExtractionError(
163
+ f"EOF reached while reading PRG part: expected {header.prg_rom_size} bytes, got {len(prg_data)}"
164
+ )
165
+ with open(prg_fname, 'wb') as prg:
166
+ prg.write(prg_data)
167
+ print(f"Extracted PRG ROM: {prg_fname} ({header.prg_rom_size} bytes)")
168
+
169
+ # Extract CHR ROM
170
+ if header.chr_rom_size > 0:
171
+ chr_data = nes_file.read(header.chr_rom_size)
172
+ if len(chr_data) < header.chr_rom_size:
173
+ raise ROMExtractionError(
174
+ f"EOF reached while reading CHR part: expected {header.chr_rom_size} bytes, got {len(chr_data)}"
175
+ )
176
+ with open(chr_fname, 'wb') as chr_file:
177
+ chr_file.write(chr_data)
178
+ print(f"Extracted CHR ROM: {chr_fname} ({header.chr_rom_size} bytes)")
179
+
180
+ # Verify we've read at least the expected amount of data.
181
+ # Extra trailing data is allowed, but we report it for visibility.
182
+ actual_position = nes_file.tell()
183
+ if actual_position < expected_file_size:
184
+ raise ROMExtractionError(
185
+ f"File ended early: expected to read {expected_file_size} bytes, read {actual_position} bytes"
186
+ )
187
+ extra_data = nes_file.read(1)
188
+ if extra_data:
189
+ print(
190
+ "Warning: Required ROM data was read successfully, "
191
+ "but file contains additional trailing bytes",
192
+ file=sys.stderr
193
+ )
194
+
195
+
196
+ def process_archive(filename: str, force: bool = False) -> None:
197
+ """
198
+ Process an archive (.7z, .zip, or .rar) and extract the first .nes ROM file.
199
+
200
+ Args:
201
+ filename: Path to the archive
202
+ force: If True, overwrite existing files without confirmation
203
+
204
+ Raises:
205
+ ROMExtractionError: If processing fails or libarchive not available
206
+ """
207
+ if not LIBARCHIVE_AVAILABLE:
208
+ raise ROMExtractionError("libarchive not available - archive support disabled")
209
+
210
+ with open(filename, 'rb') as f:
211
+ with libarchive.fd_reader(f.fileno()) as archive:
212
+ # First pass: collect all .nes files
213
+ nes_files = []
214
+ for entry in archive:
215
+ if entry.isfile:
216
+ entry_path = Path(entry.name)
217
+ if entry_path.suffix.lower() == '.nes':
218
+ nes_files.append(entry.name)
219
+
220
+ if not nes_files:
221
+ raise ROMExtractionError("No .nes files found in archive")
222
+
223
+ # Warn if multiple .nes files found
224
+ if len(nes_files) > 1:
225
+ print(f"Warning: Found {len(nes_files)} .nes files in archive:", file=sys.stderr)
226
+ for nes_file in nes_files:
227
+ print(f" - {nes_file}", file=sys.stderr)
228
+ print(f"Processing only the first file: {nes_files[0]}", file=sys.stderr)
229
+ print(file=sys.stderr) # Empty line for readability
230
+
231
+ # Second pass: extract the first .nes file
232
+ with open(filename, 'rb') as f:
233
+ with libarchive.fd_reader(f.fileno()) as archive:
234
+ for entry in archive:
235
+ if entry.isfile:
236
+ entry_path = Path(entry.name)
237
+ if entry_path.suffix.lower() == '.nes':
238
+ # Read all data from the entry efficiently
239
+ blocks = []
240
+ for block in entry.get_blocks():
241
+ blocks.append(block)
242
+ data = b''.join(blocks)
243
+
244
+ # Create BytesIO object and extract
245
+ bio = io.BytesIO(data)
246
+ extract_rom_data(entry.name, bio, force)
247
+ return
248
+
249
+
250
+ def process_nes_file(filename: str, force: bool = False) -> None:
251
+ """
252
+ Process a plain .nes file.
253
+
254
+ Args:
255
+ filename: Path to the .nes file
256
+ force: If True, overwrite existing files without confirmation
257
+ """
258
+ with open(filename, "rb") as nes_file:
259
+ extract_rom_data(filename, nes_file, force)
260
+
261
+
262
+ def parse_arguments() -> argparse.Namespace:
263
+ """Parse command-line arguments."""
264
+ # Build supported formats string from constants
265
+ all_extensions = SUPPORTED_EXTENSIONS | ARCHIVE_EXTENSIONS
266
+ supported_formats = ", ".join(sorted(all_extensions))
267
+ if not LIBARCHIVE_AVAILABLE:
268
+ supported_formats += " (libarchive not available - archive support disabled)"
269
+
270
+ parser = argparse.ArgumentParser(
271
+ prog='ines_split_rom.py',
272
+ description='Split iNES ROM files into PRG and CHR components',
273
+ epilog=f"Supported formats: {supported_formats}"
274
+ )
275
+ parser.add_argument(
276
+ 'filename',
277
+ help='Input file (.nes or archive)'
278
+ )
279
+ parser.add_argument(
280
+ '--force',
281
+ '-f',
282
+ action='store_true',
283
+ help='Overwrite existing output files without confirmation'
284
+ )
285
+ return parser.parse_args()
286
+
287
+
288
+ def main() -> int:
289
+ """
290
+ Main entry point for the script.
291
+
292
+ Returns:
293
+ Exit code (0 for success, 1 for error)
294
+ """
295
+ args = parse_arguments()
296
+
297
+ # Validate input file
298
+ input_path = Path(args.filename)
299
+
300
+ if not input_path.exists():
301
+ print(f"Error: File does not exist: {args.filename}", file=sys.stderr)
302
+ return 1
303
+
304
+ if not input_path.is_file():
305
+ print(f"Error: Not a file: {args.filename}", file=sys.stderr)
306
+ return 1
307
+
308
+ if not os.access(input_path, os.R_OK):
309
+ print(f"Error: File is not readable: {args.filename}", file=sys.stderr)
310
+ return 1
311
+
312
+ # Process file based on extension
313
+ try:
314
+ file_ext = input_path.suffix.lower()
315
+
316
+ if file_ext in ALL_ARCHIVE_EXTENSIONS:
317
+ if not LIBARCHIVE_AVAILABLE:
318
+ print(f"Error: Unsupported file extension: {file_ext}", file=sys.stderr)
319
+ print("For archive format support, install libarchive-c: pip install libarchive-c", file=sys.stderr)
320
+ return 1
321
+ process_archive(args.filename, force=args.force)
322
+ elif file_ext == '.nes':
323
+ process_nes_file(args.filename, force=args.force)
324
+ else:
325
+ print(f"Error: Unsupported file extension: {file_ext}", file=sys.stderr)
326
+ all_extensions = SUPPORTED_EXTENSIONS | ARCHIVE_EXTENSIONS
327
+ supported_formats = ", ".join(sorted(all_extensions))
328
+ print(f"Supported formats: {supported_formats}", file=sys.stderr)
329
+ return 1
330
+
331
+ return 0
332
+
333
+ except KeyboardInterrupt:
334
+ # User pressed Ctrl-C, exit gracefully
335
+ print(file=sys.stderr) # New line after ^C
336
+ return 130 # Standard exit code for SIGINT
337
+ except ROMExtractionError as e:
338
+ print(f"Error: {e}", file=sys.stderr)
339
+ return 1
340
+ except Exception as e:
341
+ print(f"Unexpected error: {e}", file=sys.stderr)
342
+ return 1
343
+
344
+
345
+ if __name__ == '__main__':
346
+ sys.exit(main())
ines_parser/mappers.py ADDED
@@ -0,0 +1,147 @@
1
+ """
2
+ Mapper information database
3
+
4
+ Provides lookup tables for mapper names and additional information.
5
+ Based on NESdev Wiki mapper list.
6
+ """
7
+
8
+ from typing import Dict, Optional, List, Any
9
+
10
+ # Mapper database: mapper_number -> (primary_name, [alternate_names], notes)
11
+ MAPPER_DATABASE: Dict[int, tuple] = {
12
+ 0: ("NROM", [], ""),
13
+ 1: ("MMC1", ["SxROM"], ""),
14
+ 2: ("UxROM", [], ""),
15
+ 3: ("CNROM", [], ""),
16
+ 4: ("MMC3", ["TxROM", "MMC6"], ""),
17
+ 5: ("MMC5", ["ExROM"], "Contains expansion sound"),
18
+ 7: ("AxROM", [], ""),
19
+ 9: ("MMC2", ["PxROM"], ""),
20
+ 10: ("MMC4", ["FxROM"], ""),
21
+ 11: ("Color Dreams", [], ""),
22
+ 13: ("CPROM", [], ""),
23
+ 15: ("100-in-1 Contra Function 16", [], "Multicart"),
24
+ 16: ("Bandai EPROM (24C02)", [], ""),
25
+ 18: ("Jaleco SS8806", [], ""),
26
+ 19: ("Namco 163", [], "Contains expansion sound"),
27
+ 21: ("VRC4", ["VRC4a", "VRC4c"], ""),
28
+ 22: ("VRC2", ["VRC2a"], ""),
29
+ 23: ("VRC2/VRC4", ["VRC2b", "VRC4e"], ""),
30
+ 24: ("VRC6", ["VRC6a"], "Contains expansion sound"),
31
+ 25: ("VRC4", ["VRC4b", "VRC4d"], ""),
32
+ 26: ("VRC6", ["VRC6b"], "Contains expansion sound"),
33
+ 34: ("BNROM", ["NINA-001"], ""),
34
+ 64: ("RAMBO-1", [], "MMC3 clone with extra features"),
35
+ 66: ("GxROM", ["MxROM"], ""),
36
+ 68: ("After Burner", [], "ROM-based nametables"),
37
+ 69: ("Sunsoft FME-7", ["Sunsoft 5B"], "The 5B is the FME-7 with expansion sound"),
38
+ 71: ("Camerica/Codemasters", [], "Similar to UNROM"),
39
+ 73: ("VRC3", [], ""),
40
+ 74: ("Pirate MMC3 derivative", [], "Has both CHR ROM and CHR RAM (2k)"),
41
+ 75: ("VRC1", [], ""),
42
+ 76: ("Namco 109 variant", [], ""),
43
+ 79: ("NINA-03/NINA-06", [], "It's either 003 or 006, we don't know right now"),
44
+ 85: ("VRC7", [], "Contains expansion sound"),
45
+ 86: ("JALECO-JF-13", [], ""),
46
+ 94: ("Senjou no Ookami", [], ""),
47
+ 105: ("NES-EVENT", [], "Similar to MMC1"),
48
+ 113: ("NINA-03/NINA-06??", [], "For multicarts including mapper 79 games"),
49
+ 118: ("TxSROM", ["MMC3"], "MMC3 with independent mirroring control"),
50
+ 119: ("TQROM", ["MMC3"], "Has both CHR ROM and CHR RAM"),
51
+ 159: ("Bandai EPROM (24C01)", [], ""),
52
+ 166: ("SUBOR", [], ""),
53
+ 167: ("SUBOR", [], ""),
54
+ 180: ("Crazy Climber", [], "Variation of UNROM, fixed first bank at $8000"),
55
+ 185: ("CNROM with protection diodes", [], ""),
56
+ 192: ("Pirate MMC3 derivative", [], "Has both CHR ROM and CHR RAM (4k)"),
57
+ 206: ("DxROM", ["Namco 118", "MIMIC-1"], "Simplified MMC3 predecessor lacking some features"),
58
+ 210: ("Namco 175 and 340", [], "Namco 163 with different mirroring"),
59
+ 228: ("Action 52", [], ""),
60
+ 232: ("Camerica/Codemasters Quattro", [], "Multicarts"),
61
+ }
62
+
63
+
64
+ def get_mapper_name(mapper_number: int) -> str:
65
+ """
66
+ Get the primary name for a mapper number.
67
+
68
+ Args:
69
+ mapper_number: The mapper number
70
+
71
+ Returns:
72
+ Primary mapper name, or "Unknown" if not found
73
+ """
74
+ if mapper_number in MAPPER_DATABASE:
75
+ return MAPPER_DATABASE[mapper_number][0]
76
+ return f"Unknown ({mapper_number})"
77
+
78
+
79
+ def get_mapper_alternate_names(mapper_number: int) -> List[str]:
80
+ """
81
+ Get alternate names for a mapper.
82
+
83
+ Args:
84
+ mapper_number: The mapper number
85
+
86
+ Returns:
87
+ List of alternate names, empty list if none
88
+ """
89
+ if mapper_number in MAPPER_DATABASE:
90
+ return MAPPER_DATABASE[mapper_number][1]
91
+ return []
92
+
93
+
94
+ def get_mapper_notes(mapper_number: int) -> str:
95
+ """
96
+ Get notes/information about a mapper.
97
+
98
+ Args:
99
+ mapper_number: The mapper number
100
+
101
+ Returns:
102
+ Notes string, empty if none
103
+ """
104
+ if mapper_number in MAPPER_DATABASE:
105
+ return MAPPER_DATABASE[mapper_number][2]
106
+ return ""
107
+
108
+
109
+ def get_mapper_info(mapper_number: int) -> Dict[str, Any]:
110
+ """
111
+ Get complete mapper information.
112
+
113
+ Args:
114
+ mapper_number: The mapper number
115
+
116
+ Returns:
117
+ Dictionary with 'name', 'alternates', and 'notes'
118
+ """
119
+ if mapper_number in MAPPER_DATABASE:
120
+ name, alternates, notes = MAPPER_DATABASE[mapper_number]
121
+ return {
122
+ 'name': name,
123
+ 'alternates': alternates,
124
+ 'notes': notes,
125
+ 'all_names': [name] + alternates,
126
+ }
127
+
128
+ return {
129
+ 'name': f"Unknown ({mapper_number})",
130
+ 'alternates': [],
131
+ 'notes': '',
132
+ 'all_names': [f"Unknown ({mapper_number})"],
133
+ }
134
+
135
+
136
+ def is_known_mapper(mapper_number: int) -> bool:
137
+ """
138
+ Check if a mapper number is in the database.
139
+
140
+ Args:
141
+ mapper_number: The mapper number
142
+
143
+ Returns:
144
+ True if mapper is known, False otherwise
145
+ """
146
+ return mapper_number in MAPPER_DATABASE
147
+