├── .github ├── FUNDING.yml └── workflows │ ├── build.yml │ └── docs.yml ├── .gitignore ├── Crc32.cs ├── Doxyfile ├── FdsBlockDiskInfo.cs ├── FdsBlockFileAmount.cs ├── FdsBlockFileData.cs ├── FdsBlockFileHeader.cs ├── FdsDiskFile.cs ├── FdsDiskSide.cs ├── FdsFile.cs ├── IFdsBlock.cs ├── LICENSE ├── MirroringType.cs ├── NesContainers.csproj ├── NesFile.cs ├── README.md ├── Timing.cs └── UnifFile.cs /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [ClusterM] 2 | custom: ["https://www.buymeacoffee.com/cluster", "https://boosty.to/cluster"] 3 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build and pack 2 | 3 | on: 4 | # Runs on pushes targeting the default branch 5 | push: 6 | branches: ["master"] 7 | pull_request: 8 | branches: ["master"] 9 | 10 | # Allows you to run this workflow manually from the Actions tab 11 | workflow_dispatch: 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | env: 17 | APP_NAME: nes-containers 18 | OUTPUT_DIR: output 19 | CONFIGURATION: Release 20 | steps: 21 | - name: Checkout 22 | uses: actions/checkout@v3 23 | - name: Setup .NET 24 | uses: actions/setup-dotnet@v2 25 | with: 26 | dotnet-version: 6.0.x 27 | - name: Build 28 | run: dotnet build -c ${{ env.CONFIGURATION }} 29 | - name: Pack 30 | run: dotnet pack -c ${{ env.CONFIGURATION }} -o ${{ env.OUTPUT_DIR }} 31 | - name: Upload artifact 32 | uses: actions/upload-artifact@v3 33 | with: 34 | name: ${{ env.APP_NAME }} 35 | path: ${{ env.OUTPUT_DIR }} 36 | -------------------------------------------------------------------------------- /.github/workflows/docs.yml: -------------------------------------------------------------------------------- 1 | name: Deploy documentation 2 | 3 | on: 4 | # Runs on pushes targeting the default branch 5 | push: 6 | branches: ["master"] 7 | 8 | # Allows you to run this workflow manually from the Actions tab 9 | workflow_dispatch: 10 | 11 | # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages 12 | permissions: 13 | contents: read 14 | pages: write 15 | id-token: write 16 | 17 | # Allow one concurrent deployment 18 | concurrency: 19 | group: "pages" 20 | cancel-in-progress: true 21 | 22 | jobs: 23 | # Single deploy job since we're just deploying 24 | deploy: 25 | environment: 26 | name: github-pages 27 | url: ${{ steps.deployment.outputs.page_url }} 28 | runs-on: ubuntu-latest 29 | steps: 30 | - name: Checkout 31 | uses: actions/checkout@v3 32 | - name: Install Doxygen 33 | run: sudo apt-get install doxygen -y 34 | - name: Generate docs 35 | run: doxygen Doxyfile 36 | - name: Setup Pages 37 | uses: actions/configure-pages@v2 38 | - name: Upload artifact 39 | uses: actions/upload-pages-artifact@v1 40 | with: 41 | # Upload entire repository 42 | path: 'docs/html' 43 | - name: Deploy to GitHub Pages 44 | id: deployment 45 | uses: actions/deploy-pages@v1 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | NesContainers.xml 7 | 8 | # User-specific files 9 | *.rsuser 10 | *.suo 11 | *.user 12 | *.userosscache 13 | *.sln.docstates 14 | 15 | # User-specific files (MonoDevelop/Xamarin Studio) 16 | *.userprefs 17 | 18 | # Mono auto generated files 19 | mono_crash.* 20 | 21 | # Build results 22 | [Dd]ebug/ 23 | [Dd]ebugPublic/ 24 | [Rr]elease/ 25 | [Rr]eleases/ 26 | x64/ 27 | x86/ 28 | [Aa][Rr][Mm]/ 29 | [Aa][Rr][Mm]64/ 30 | bld/ 31 | [Bb]in/ 32 | [Oo]bj/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # StyleCop 67 | StyleCopReport.xml 68 | 69 | # Files built by Visual Studio 70 | *_i.c 71 | *_p.c 72 | *_h.h 73 | *.ilk 74 | *.meta 75 | *.obj 76 | *.iobj 77 | *.pch 78 | *.pdb 79 | *.ipdb 80 | *.pgc 81 | *.pgd 82 | *.rsp 83 | *.sbr 84 | *.tlb 85 | *.tli 86 | *.tlh 87 | *.tmp 88 | *.tmp_proj 89 | *_wpftmp.csproj 90 | *.log 91 | *.vspscc 92 | *.vssscc 93 | .builds 94 | *.pidb 95 | *.svclog 96 | *.scc 97 | 98 | # Chutzpah Test files 99 | _Chutzpah* 100 | 101 | # Visual C++ cache files 102 | ipch/ 103 | *.aps 104 | *.ncb 105 | *.opendb 106 | *.opensdf 107 | *.sdf 108 | *.cachefile 109 | *.VC.db 110 | *.VC.VC.opendb 111 | 112 | # Visual Studio profiler 113 | *.psess 114 | *.vsp 115 | *.vspx 116 | *.sap 117 | 118 | # Visual Studio Trace Files 119 | *.e2e 120 | 121 | # TFS 2012 Local Workspace 122 | $tf/ 123 | 124 | # Guidance Automation Toolkit 125 | *.gpState 126 | 127 | # ReSharper is a .NET coding add-in 128 | _ReSharper*/ 129 | *.[Rr]e[Ss]harper 130 | *.DotSettings.user 131 | 132 | # TeamCity is a build add-in 133 | _TeamCity* 134 | 135 | # DotCover is a Code Coverage Tool 136 | *.dotCover 137 | 138 | # AxoCover is a Code Coverage Tool 139 | .axoCover/* 140 | !.axoCover/settings.json 141 | 142 | # Visual Studio code coverage results 143 | *.coverage 144 | *.coveragexml 145 | 146 | # NCrunch 147 | _NCrunch_* 148 | .*crunch*.local.xml 149 | nCrunchTemp_* 150 | 151 | # MightyMoose 152 | *.mm.* 153 | AutoTest.Net/ 154 | 155 | # Web workbench (sass) 156 | .sass-cache/ 157 | 158 | # Installshield output folder 159 | [Ee]xpress/ 160 | 161 | # DocProject is a documentation generator add-in 162 | DocProject/buildhelp/ 163 | DocProject/Help/*.HxT 164 | DocProject/Help/*.HxC 165 | DocProject/Help/*.hhc 166 | DocProject/Help/*.hhk 167 | DocProject/Help/*.hhp 168 | DocProject/Help/Html2 169 | DocProject/Help/html 170 | 171 | # Click-Once directory 172 | publish/ 173 | 174 | # Publish Web Output 175 | *.[Pp]ublish.xml 176 | *.azurePubxml 177 | # Note: Comment the next line if you want to checkin your web deploy settings, 178 | # but database connection strings (with potential passwords) will be unencrypted 179 | *.pubxml 180 | *.publishproj 181 | 182 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 183 | # checkin your Azure Web App publish settings, but sensitive information contained 184 | # in these scripts will be unencrypted 185 | PublishScripts/ 186 | 187 | # NuGet Packages 188 | *.nupkg 189 | # NuGet Symbol Packages 190 | *.snupkg 191 | # The packages folder can be ignored because of Package Restore 192 | **/[Pp]ackages/* 193 | # except build/, which is used as an MSBuild target. 194 | !**/[Pp]ackages/build/ 195 | # Uncomment if necessary however generally it will be regenerated when needed 196 | #!**/[Pp]ackages/repositories.config 197 | # NuGet v3's project.json files produces more ignorable files 198 | *.nuget.props 199 | *.nuget.targets 200 | 201 | # Microsoft Azure Build Output 202 | csx/ 203 | *.build.csdef 204 | 205 | # Microsoft Azure Emulator 206 | ecf/ 207 | rcf/ 208 | 209 | # Windows Store app package directories and files 210 | AppPackages/ 211 | BundleArtifacts/ 212 | Package.StoreAssociation.xml 213 | _pkginfo.txt 214 | *.appx 215 | *.appxbundle 216 | *.appxupload 217 | 218 | # Visual Studio cache files 219 | # files ending in .cache can be ignored 220 | *.[Cc]ache 221 | # but keep track of directories ending in .cache 222 | !?*.[Cc]ache/ 223 | 224 | # Others 225 | ClientBin/ 226 | ~$* 227 | *~ 228 | *.dbmdl 229 | *.dbproj.schemaview 230 | *.jfm 231 | *.pfx 232 | *.publishsettings 233 | orleans.codegen.cs 234 | 235 | # Including strong name files can present a security risk 236 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 237 | #*.snk 238 | 239 | # Since there are multiple workflows, uncomment next line to ignore bower_components 240 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 241 | #bower_components/ 242 | 243 | # RIA/Silverlight projects 244 | Generated_Code/ 245 | 246 | # Backup & report files from converting an old project file 247 | # to a newer Visual Studio version. Backup files are not needed, 248 | # because we have git ;-) 249 | _UpgradeReport_Files/ 250 | Backup*/ 251 | UpgradeLog*.XML 252 | UpgradeLog*.htm 253 | ServiceFabricBackup/ 254 | *.rptproj.bak 255 | 256 | # SQL Server files 257 | *.mdf 258 | *.ldf 259 | *.ndf 260 | 261 | # Business Intelligence projects 262 | *.rdl.data 263 | *.bim.layout 264 | *.bim_*.settings 265 | *.rptproj.rsuser 266 | *- [Bb]ackup.rdl 267 | *- [Bb]ackup ([0-9]).rdl 268 | *- [Bb]ackup ([0-9][0-9]).rdl 269 | 270 | # Microsoft Fakes 271 | FakesAssemblies/ 272 | 273 | # GhostDoc plugin setting file 274 | *.GhostDoc.xml 275 | 276 | # Node.js Tools for Visual Studio 277 | .ntvs_analysis.dat 278 | node_modules/ 279 | 280 | # Visual Studio 6 build log 281 | *.plg 282 | 283 | # Visual Studio 6 workspace options file 284 | *.opt 285 | 286 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 287 | *.vbw 288 | 289 | # Visual Studio LightSwitch build output 290 | **/*.HTMLClient/GeneratedArtifacts 291 | **/*.DesktopClient/GeneratedArtifacts 292 | **/*.DesktopClient/ModelManifest.xml 293 | **/*.Server/GeneratedArtifacts 294 | **/*.Server/ModelManifest.xml 295 | _Pvt_Extensions 296 | 297 | # Paket dependency manager 298 | .paket/paket.exe 299 | paket-files/ 300 | 301 | # FAKE - F# Make 302 | .fake/ 303 | 304 | # CodeRush personal settings 305 | .cr/personal 306 | 307 | # Python Tools for Visual Studio (PTVS) 308 | __pycache__/ 309 | *.pyc 310 | 311 | # Cake - Uncomment if you are using it 312 | # tools/** 313 | # !tools/packages.config 314 | 315 | # Tabs Studio 316 | *.tss 317 | 318 | # Telerik's JustMock configuration file 319 | *.jmconfig 320 | 321 | # BizTalk build output 322 | *.btp.cs 323 | *.btm.cs 324 | *.odx.cs 325 | *.xsd.cs 326 | 327 | # OpenCover UI analysis results 328 | OpenCover/ 329 | 330 | # Azure Stream Analytics local run output 331 | ASALocalRun/ 332 | 333 | # MSBuild Binary and Structured Log 334 | *.binlog 335 | 336 | # NVidia Nsight GPU debugger configuration file 337 | *.nvuser 338 | 339 | # MFractors (Xamarin productivity tool) working folder 340 | .mfractor/ 341 | 342 | # Local History for Visual Studio 343 | .localhistory/ 344 | 345 | # BeatPulse healthcheck temp database 346 | healthchecksdb 347 | 348 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 349 | MigrationBackup/ 350 | 351 | # Ionide (cross platform F# VS Code tools) working folder 352 | .ionide/ 353 | -------------------------------------------------------------------------------- /Crc32.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Security.Cryptography; 4 | 5 | namespace com.clusterrr.Famicom.Containers 6 | { 7 | /// 8 | /// CRC32 calculator 9 | /// 10 | internal class Crc32 : HashAlgorithm 11 | { 12 | private readonly uint[] table = new uint[256]; 13 | private uint crc = 0xFFFFFFFF; 14 | 15 | public Crc32() 16 | { 17 | // Calculate table 18 | uint poly = 0xedb88320; 19 | uint temp; 20 | for (uint i = 0; i < table.Length; ++i) 21 | { 22 | temp = i; 23 | for (int j = 8; j > 0; --j) 24 | { 25 | if ((temp & 1) == 1) 26 | { 27 | temp = (uint)((temp >> 1) ^ poly); 28 | } 29 | else 30 | { 31 | temp >>= 1; 32 | } 33 | } 34 | table[i] = temp; 35 | } 36 | } 37 | 38 | public override void Initialize() 39 | { 40 | } 41 | 42 | public override bool CanReuseTransform => false; 43 | 44 | protected override void HashCore(byte[] array, int ibStart, int cbSize) 45 | { 46 | while (cbSize > 0) 47 | { 48 | var pos = ibStart; 49 | byte index = (byte)(((crc) & 0xff) ^ array[pos]); 50 | crc = (crc >> 8) ^ table[index]; 51 | ibStart++; 52 | cbSize--; 53 | } 54 | } 55 | 56 | protected override byte[] HashFinal() => BitConverter.GetBytes(~crc).Reverse().ToArray(); 57 | public override bool CanTransformMultipleBlocks => true; 58 | public override byte[] Hash => BitConverter.GetBytes(~crc).Reverse().ToArray(); 59 | public override int HashSize => 32; 60 | 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /FdsBlockDiskInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Runtime.InteropServices; 5 | using System.Text; 6 | 7 | namespace com.clusterrr.Famicom.Containers 8 | { 9 | /// 10 | /// Disk info FDS block (block type 1) 11 | /// 12 | [StructLayout(LayoutKind.Sequential, Size = 56, Pack = 1)] 13 | public class FdsBlockDiskInfo : IFdsBlock, IEquatable 14 | { 15 | static Encoding textEncoding = Encoding.GetEncoding("ISO-8859-1"); 16 | 17 | /// 18 | /// Disk side 19 | /// 20 | public enum DiskSides 21 | { 22 | /// 23 | /// Side A 24 | /// 25 | A = 0, 26 | /// 27 | /// Side B 28 | /// 29 | B = 1, 30 | } 31 | 32 | /// 33 | /// Disk type (FMC) 34 | /// 35 | public enum DiskTypes 36 | { 37 | /// 38 | /// Normal/other 39 | /// 40 | FMS = 0, 41 | /// 42 | /// FMC blue-disk releases 43 | /// 44 | FSC = 1, 45 | } 46 | 47 | /// 48 | /// Country 49 | /// 50 | public enum Country 51 | { 52 | /// 53 | /// Japan 54 | /// 55 | Japan = 0x49, 56 | } 57 | 58 | /// 59 | /// Company name, source: https://www.nesdev.org/wiki/Licensee_codes 60 | /// 61 | public enum Company 62 | { 63 | /// 64 | /// Nintendo 65 | /// 66 | Nintendo = 0x01, 67 | /// 68 | /// Nomura Securities? (unverified) 69 | /// 70 | NomuraSecurities = 0x07, 71 | /// 72 | /// Capcom 73 | /// 74 | Capcom = 0x08, 75 | /// 76 | /// Hot-B 77 | /// 78 | HotB = 0x09, 79 | /// 80 | /// Jaleco 81 | /// 82 | Jaleco = 0x0A, 83 | /// 84 | /// Coconuts Japan Entertainment 85 | /// 86 | CoconutsJapanEntertainment = 0x0B, 87 | /// 88 | /// Electronic Arts (Japan) 89 | /// 90 | ElectronicArtsJap = 0x13, 91 | /// 92 | /// Hudson Soft 93 | /// 94 | HudsonSoft = 0x18, 95 | /// 96 | /// Tokai Engineering 97 | /// 98 | TokaiEngineering = 0x21, 99 | /// 100 | /// Kemco (Japan) 101 | /// 102 | KemcoJap = 0x28, 103 | /// 104 | /// SETA (Japan) 105 | /// 106 | SetaJap = 0x29, 107 | /// 108 | /// Tamtex 109 | /// 110 | Tamtex = 0x2B, 111 | /// 112 | /// Hector Playing Interface (Hect) 113 | /// 114 | HectorPlayingInterface = 0x35, 115 | /// 116 | /// Loriciel 117 | /// 118 | Loriciel = 0x3D, 119 | /// 120 | /// Gremlin 121 | /// 122 | Gremlin = 0x3E, 123 | /// 124 | /// Seika Corporation 125 | /// 126 | SeikaCorporation = 0x40, 127 | /// 128 | /// Ubisoft 129 | /// 130 | Ubisoft = 0x41, 131 | /// 132 | /// System 3 133 | /// 134 | System3 = 0x46, 135 | /// 136 | /// Irem 137 | /// 138 | Irem = 0x49, 139 | /// 140 | /// Gakken 141 | /// 142 | Gakken = 0x4A, 143 | /// 144 | /// Absolute 145 | /// 146 | Absolute = 0x50, 147 | /// 148 | /// Acclaim (NA) 149 | /// 150 | AcclaimNA = 0x51, 151 | /// 152 | /// Activision 153 | /// 154 | Activision = 0x52, 155 | /// 156 | /// American Sammy 157 | /// 158 | AmericanSammy = 0x53, 159 | /// 160 | /// GameTek 161 | /// 162 | Gametek = 0x54, 163 | /// 164 | /// Hi Tech Expressions 165 | /// 166 | HITechExpressions = 0x55, 167 | /// 168 | /// LJN 169 | /// 170 | Ljn = 0x56, 171 | /// 172 | /// Matchbox Toys 173 | /// 174 | MatchboxToys = 0x57, 175 | /// 176 | /// Mattel 177 | /// 178 | Mattel = 0x58, 179 | /// 180 | /// Milton Bradley 181 | /// 182 | MiltonBradley = 0x59, 183 | /// 184 | /// Mindscape / Software Toolworks 185 | /// 186 | MindscapeSoftwareToolworks = 0x5A, 187 | /// 188 | /// SETA (NA) 189 | /// 190 | SetaNA = 0x5B, 191 | /// 192 | /// Taxan 193 | /// 194 | Taxan = 0x5C, 195 | /// 196 | /// Tradewest 197 | /// 198 | Tradewest = 0x5D, 199 | /// 200 | /// INTV Corporation 201 | /// 202 | IntvCorporation = 0x5E, 203 | /// 204 | /// Titus 205 | /// 206 | Titus = 0x60, 207 | /// 208 | /// Virgin Games 209 | /// 210 | VirginGames = 0x61, 211 | /// 212 | /// Ocean 213 | /// 214 | Ocean = 0x67, 215 | /// 216 | /// Electronic Arts (NA) 217 | /// 218 | ElectronicArtsNA = 0x69, 219 | /// 220 | /// Beam Software 221 | /// 222 | BeamSoftware = 0x6B, 223 | /// 224 | /// Elite Systems 225 | /// 226 | EliteSystems = 0x6E, 227 | /// 228 | /// Electro Brain 229 | /// 230 | ElectroBrain = 0x6F, 231 | /// 232 | /// Infogrames 233 | /// 234 | Infogrames = 0x70, 235 | /// 236 | /// JVC 237 | /// 238 | Jvc = 0x72, 239 | /// 240 | /// Parker Brothers 241 | /// 242 | ParkerBrothers = 0x73, 243 | /// 244 | /// The Sales Curve / SCi 245 | /// 246 | TheSalesCurveSci = 0x75, 247 | /// 248 | /// THQ 249 | /// 250 | Thq = 0x78, 251 | /// 252 | /// Accolade 253 | /// 254 | Accolade = 0x79, 255 | /// 256 | /// Triffix 257 | /// 258 | Triffix = 0x7A, 259 | /// 260 | /// Microprose Software 261 | /// 262 | MicroproseSoftware = 0x7C, 263 | /// 264 | /// Kemco (NA) 265 | /// 266 | KemcoNA = 0x7F, 267 | /// 268 | /// Misawa Entertainment 269 | /// 270 | MisawaEntertainment = 0x80, 271 | /// 272 | /// G. Amusements Co. 273 | /// 274 | GAmusementsCO = 0x83, 275 | /// 276 | /// G.O 1 277 | /// 278 | GO1 = 0x85, 279 | /// 280 | /// Tokuma Shoten Intermedia 281 | /// 282 | TokumaShotenIntermedia = 0x86, 283 | /// 284 | /// Nihon Maicom Kaihatsu (NMK) 285 | /// 286 | NihonMaicomKaihatsu = 0x89, 287 | /// 288 | /// BulletProof Software (BPS) 289 | /// 290 | BulletproofSoftware = 0x8B, 291 | /// 292 | /// VIC Tokai 293 | /// 294 | VicTokai = 0x8C, 295 | /// 296 | /// Sanritsu 297 | /// 298 | Sanritsu = 0x8D, 299 | /// 300 | /// Character Soft 301 | /// 302 | CharacterSoft = 0x8E, 303 | /// 304 | /// I'Max 305 | /// 306 | IMax = 0x8F, 307 | /// 308 | /// Toaplan 309 | /// 310 | Toaplan = 0x94, 311 | /// 312 | /// Varie 313 | /// 314 | Varie = 0x95, 315 | /// 316 | /// Yonezawa Party Room 21 / S'Pal 317 | /// 318 | YonezawaPartyRoom21SPal = 0x96, 319 | /// 320 | /// Pack-In-Video 321 | /// 322 | PackINVideo = 0x99, 323 | /// 324 | /// Nihon Bussan 325 | /// 326 | NihonBussan = 0x9A, 327 | /// 328 | /// Tecmo 329 | /// 330 | Tecmo = 0x9B, 331 | /// 332 | /// Imagineer 333 | /// 334 | Imagineer = 0x9C, 335 | /// 336 | /// Face 337 | /// 338 | Face = 0x9E, 339 | /// 340 | /// Scorpion Soft 341 | /// 342 | ScorpionSoft = 0xA2, 343 | /// 344 | /// Broderbund 345 | /// 346 | Broderbund = 0xA3, 347 | /// 348 | /// Konami 349 | /// 350 | Konami = 0xA4, 351 | /// 352 | /// K. Amusement Leasing Co. (KAC) 353 | /// 354 | KAmusementLeasingCO = 0xA5, 355 | /// 356 | /// Kawada Co., Ltd. 357 | /// 358 | KawadaCOLtd = 0xA6, 359 | /// 360 | /// Takara 361 | /// 362 | Takara = 0xA7, 363 | /// 364 | /// Royal Industries 365 | /// 366 | RoyalIndustries = 0xA8, 367 | /// 368 | /// Tecnos 369 | /// 370 | Tecnos = 0xA9, 371 | /// 372 | /// Victor Musical Industries 373 | /// 374 | VictorMusicalIndustries = 0xAA, 375 | /// 376 | /// Hi-Score Media Work 377 | /// 378 | HIScoreMediaWork = 0xAB, 379 | /// 380 | /// Toei Animation 381 | /// 382 | ToeiAnimation = 0xAC, 383 | /// 384 | /// Toho (Japan) 385 | /// 386 | TohoJap = 0xAD, 387 | /// 388 | /// TSS 389 | /// 390 | Tss = 0xAE, 391 | /// 392 | /// Namco 393 | /// 394 | Namco = 0xAF, 395 | /// 396 | /// Acclaim (Japan) 397 | /// 398 | AcclaimJap = 0xB0, 399 | /// 400 | /// ASCII Corporation / Nexoft 401 | /// 402 | AsciiCorporationNexoft = 0xB1, 403 | /// 404 | /// Bandai 405 | /// 406 | Bandai = 0xB2, 407 | /// 408 | /// Soft Pro Inc. 409 | /// 410 | SoftProInc = 0xB3, 411 | /// 412 | /// Enix 413 | /// 414 | Enix = 0xB4, 415 | /// 416 | /// dB-SOFT 417 | /// 418 | DBSoft = 0xB5, 419 | /// 420 | /// HAL Laboratory 421 | /// 422 | HalLaboratory = 0xB6, 423 | /// 424 | /// SNK 425 | /// 426 | Snk = 0xB7, 427 | /// 428 | /// Pony Canyon 429 | /// 430 | PonyCanyon = 0xB9, 431 | /// 432 | /// Culture Brain 433 | /// 434 | CultureBrain = 0xBA, 435 | /// 436 | /// Sunsoft 437 | /// 438 | Sunsoft = 0xBB, 439 | /// 440 | /// Toshiba EMI 441 | /// 442 | ToshibaEmi = 0xBC, 443 | /// 444 | /// CBS/Sony Group 445 | /// 446 | CbsSonyGroup = 0xBD, 447 | /// 448 | /// Sammy Corporation 449 | /// 450 | SammyCorporation = 0xBF, 451 | /// 452 | /// Taito 453 | /// 454 | Taito = 0xC0, 455 | /// 456 | /// Sunsoft / Ask Co., Ltd. 457 | /// 458 | SunsoftAskCOLtd = 0xC1, 459 | /// 460 | /// Kemco 461 | /// 462 | Kemco = 0xC2, 463 | /// 464 | /// Square / Disk Original Group (DOG) 465 | /// 466 | SquareDiskOriginalGroup = 0xC3, 467 | /// 468 | /// Tokuma Shoten 469 | /// 470 | TokumaShoten = 0xC4, 471 | /// 472 | /// Data East 473 | /// 474 | DataEast = 0xC5, 475 | /// 476 | /// Tonkin House / Tokyo Shoseki 477 | /// 478 | TonkinHouseTokyoShoseki = 0xC6, 479 | /// 480 | /// East Cube / Toho (NA) 481 | /// 482 | EastCubeTohoNA = 0xC7, 483 | /// 484 | /// Koei 485 | /// 486 | Koei = 0xC8, 487 | /// 488 | /// UPL 489 | /// 490 | Upl = 0xC9, 491 | /// 492 | /// Konami / Ultra / Palcom 493 | /// 494 | KonamiUltraPalcom = 0xCA, 495 | /// 496 | /// NTVIC / VAP 497 | /// 498 | NtvicVap = 0xCB, 499 | /// 500 | /// Use Co., Ltd. 501 | /// 502 | UseCOLtd = 0xCC, 503 | /// 504 | /// Meldac 505 | /// 506 | Meldac = 0xCD, 507 | /// 508 | /// Pony Canyon / FCI 509 | /// 510 | PonyCanyonFci = 0xCE, 511 | /// 512 | /// Angel 513 | /// 514 | Angel = 0xCF, 515 | /// 516 | /// Disco 517 | /// 518 | Disco = 0xD0, 519 | /// 520 | /// Sofel 521 | /// 522 | Sofel = 0xD1, 523 | /// 524 | /// Bothtec, Inc. / Quest 525 | /// 526 | BothtecIncQuest = 0xD2, 527 | /// 528 | /// Sigma Enterprises 529 | /// 530 | SigmaEnterprises = 0xD3, 531 | /// 532 | /// Ask Corp. 533 | /// 534 | AskCorp = 0xD4, 535 | /// 536 | /// Kyugo Trading Co. 537 | /// 538 | KyugoTradingCO = 0xD5, 539 | /// 540 | /// Naxat Soft / Kaga Tech 541 | /// 542 | NaxatSoftKagaTech = 0xD6, 543 | /// 544 | /// Status 545 | /// 546 | Status = 0xD8, 547 | /// 548 | /// Banpresto 549 | /// 550 | Banpresto = 0xD9, 551 | /// 552 | /// Tomy 553 | /// 554 | Tomy = 0xDA, 555 | /// 556 | /// Hiro Co., Ltd. 557 | /// 558 | HiroCOLtd = 0xDB, 559 | /// 560 | /// Nippon Computer Systems (NCS) / Masaya Games 561 | /// 562 | NipponComputerSystemsMasayaGames = 0xDD, 563 | /// 564 | /// Human Creative 565 | /// 566 | HumanCreative = 0xDE, 567 | /// 568 | /// Altron 569 | /// 570 | Altron = 0xDF, 571 | /// 572 | /// K.K. DCE 573 | /// 574 | KKDce = 0xE0, 575 | /// 576 | /// Towa Chiki 577 | /// 578 | TowaChiki = 0xE1, 579 | /// 580 | /// Yutaka 581 | /// 582 | Yutaka = 0xE2, 583 | /// 584 | /// Kaken Corporation 585 | /// 586 | KakenCorporation = 0xE3, 587 | /// 588 | /// Epoch 589 | /// 590 | Epoch = 0xE5, 591 | /// 592 | /// Athena 593 | /// 594 | Athena = 0xE7, 595 | /// 596 | /// Asmik 597 | /// 598 | Asmik = 0xE8, 599 | /// 600 | /// Natsume 601 | /// 602 | Natsume = 0xE9, 603 | /// 604 | /// King Records 605 | /// 606 | KingRecords = 0xEA, 607 | /// 608 | /// Atlus 609 | /// 610 | Atlus = 0xEB, 611 | /// 612 | /// Sony Music Entertainment 613 | /// 614 | SonyMusicEntertainment = 0xEC, 615 | /// 616 | /// Pixel Corporation 617 | /// 618 | PixelCorporation = 0xED, 619 | /// 620 | /// Information Global Service (IGS) 621 | /// 622 | InformationGlobalService = 0xEE, 623 | /// 624 | /// Fujimic 625 | /// 626 | Fujimic = 0xEF, 627 | /// 628 | /// A-Wave 629 | /// 630 | AWave = 0xF0, 631 | } 632 | 633 | /// 634 | /// Disk type (other) 635 | /// 636 | public enum DiskTypesOther 637 | { 638 | /// 639 | /// Yellow disk 640 | /// 641 | YellowDisk = 0x00, 642 | /// 643 | /// Prototype, sample, or internal-use (white or pink) disk 644 | /// 645 | PrototypeSample = 0xFE, 646 | /// 647 | /// Blue disk 648 | /// 649 | BlueDisk = 0xFF 650 | } 651 | 652 | [MarshalAs(UnmanagedType.U1)] 653 | // Raw byte: 0x01 654 | private readonly byte blockType = 1; 655 | 656 | /// 657 | /// Valid block type ID 658 | /// 659 | public byte ValidTypeID { get => 1; } 660 | 661 | /// 662 | /// True if block type ID is valid 663 | /// 664 | public bool IsValid { get => blockType == ValidTypeID; } 665 | 666 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 14)] 667 | readonly byte[] diskVerification = textEncoding.GetBytes("*NINTENDO-HVC*"); 668 | /// 669 | /// Literal ASCII string: *NINTENDO-HVC* 670 | /// 671 | public string DiskVerification => textEncoding.GetString(diskVerification).Trim(new char[] { '\0', ' ' }); /*set => diskVerification = value.PadRight(14).ToCharArray(0, value.Length > 14 ? 14 : value.Length);*/ 672 | 673 | [MarshalAs(UnmanagedType.U1)] 674 | private byte manufacturerCode; 675 | /// 676 | /// Manufacturer code. 0x00 = Unlicensed, 0x01 = Nintendo 677 | /// 678 | public Company LicenseeCode { get => (Company)manufacturerCode; set => manufacturerCode = (byte)value; } 679 | 680 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] 681 | byte[] gameName = new byte[3]; 682 | /// 683 | /// 3-letter ASCII code per game (e.g. ZEL for The Legend of Zelda) 684 | /// 685 | public string? GameName 686 | { 687 | get 688 | { 689 | if (gameName.Where(b => b != 0).Any()) 690 | return textEncoding.GetString(gameName).TrimEnd(new char[] { '\0' }); 691 | else 692 | return null; 693 | } 694 | set 695 | { 696 | if (value?.Length > 3) throw new InvalidDataException($"Game name \"{value}\" too long, must be <= 3"); 697 | if (value != null) 698 | gameName = textEncoding.GetBytes(value.PadRight(3, '\0')).Take(3).ToArray(); 699 | else 700 | gameName = new byte[3]; 701 | } 702 | } 703 | 704 | [MarshalAs(UnmanagedType.U1)] 705 | byte gameType; 706 | /// 707 | /// 0x20 = " " — Normal disk 708 | /// 0x45 = "E" — Event(e.g.Japanese national DiskFax tournaments) 709 | /// 0x52 = "R" — Reduction in price via advertising 710 | /// 711 | public char GameType { get => (char)gameType; set => gameType = (byte)value; } 712 | 713 | [MarshalAs(UnmanagedType.U1)] 714 | byte gameVersion; 715 | /// 716 | /// Game version/revision number. Starts at 0x00, increments per revision 717 | /// 718 | public byte GameVersion { get => gameVersion; set => gameVersion = value; } 719 | 720 | [MarshalAs(UnmanagedType.U1)] 721 | byte diskSide; 722 | /// 723 | /// Side number. Single-sided disks use A 724 | /// 725 | public DiskSides DiskSide { get => (DiskSides)diskSide; set => diskSide = (byte)value; } 726 | 727 | [MarshalAs(UnmanagedType.U1)] 728 | byte diskNumber; 729 | /// 730 | /// Disk number. First disk is 0x00, second is 0x01, etc. 731 | /// 732 | public byte DiskNumber { get => diskNumber; set => diskNumber = value; } 733 | 734 | [MarshalAs(UnmanagedType.U1)] 735 | byte diskType; 736 | /// 737 | /// Disk type. 0x00 = FMC ("normal card"), 0x01 = FSC ("card with shutter"). May correlate with FMC and FSC product codes 738 | /// 739 | public DiskTypes DiskType { get => (DiskTypes)diskType; set => diskType = (byte)value; } 740 | 741 | [MarshalAs(UnmanagedType.U1)] 742 | byte unknown01 = 0x00; 743 | /// 744 | /// Unknown, offset 0x18. 745 | /// Always 0x00 746 | /// 747 | public byte Unknown01 { get => unknown01; set => unknown01 = value; } 748 | 749 | [MarshalAs(UnmanagedType.U1)] 750 | byte bootFile; 751 | /// 752 | /// Boot read file code. Refers to the file code/file number to load upon boot/start-up 753 | /// 754 | public byte BootFile { get => bootFile; set => bootFile = value; } 755 | 756 | [MarshalAs(UnmanagedType.U1)] 757 | byte unknown02 = 0xFF; 758 | /// 759 | /// Unknown, offset 0x1A. 760 | /// Always 0xFF 761 | /// 762 | public byte Unknown02 { get => unknown02; set => unknown02 = value; } 763 | 764 | [MarshalAs(UnmanagedType.U1)] 765 | byte unknown03 = 0xFF; 766 | /// 767 | /// Unknown, offset 0x1B. 768 | /// Always 0xFF 769 | /// 770 | public byte Unknown03 { get => unknown03; set => unknown03 = value; } 771 | 772 | [MarshalAs(UnmanagedType.U1)] 773 | byte unknown04 = 0xFF; 774 | /// 775 | /// Unknown, offset 0x1C. 776 | /// Always 0xFF 777 | /// 778 | public byte Unknown04 { get => unknown04; set => unknown04 = value; } 779 | 780 | [MarshalAs(UnmanagedType.U1)] 781 | byte unknown05 = 0xFF; 782 | /// 783 | /// Unknown, offset 0x1D. 784 | /// Always 0xFF 785 | /// 786 | public byte Unknown05 { get => unknown05; set => unknown05 = value; } 787 | 788 | [MarshalAs(UnmanagedType.U1)] 789 | byte unknown06 = 0xFF; 790 | /// 791 | /// Unknown, offset 0x1E. 792 | /// Always 0xFF 793 | /// 794 | public byte Unknown06 { get => unknown06; set => unknown06 = value; } 795 | 796 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] 797 | byte[] manufacturingDate = { 0, 0, 0 }; 798 | /// 799 | /// Manufacturing date 800 | /// 801 | public DateTime? ManufacturingDate 802 | { 803 | get 804 | { 805 | try 806 | { 807 | if (manufacturingDate.Where(b => b != 0).Any()) 808 | return new DateTime( 809 | ((manufacturingDate[0] & 0x0F) + ((manufacturingDate[0] >> 4) & 0x0F) * 10) + 1925, 810 | ((manufacturingDate[1] & 0x0F) + ((manufacturingDate[1] >> 4) & 0x0F) * 10), 811 | ((manufacturingDate[2] & 0x0F) + ((manufacturingDate[2] >> 4) & 0x0F) * 10) 812 | ); 813 | else 814 | return null; 815 | } 816 | catch 817 | { 818 | return null; 819 | } 820 | } 821 | set 822 | { 823 | if (value != null) 824 | { 825 | manufacturingDate = new byte[] 826 | { 827 | (byte)(((value.Value.Year - 1925) % 10) | (((value.Value.Year - 1925) / 10) << 4)), 828 | (byte)(((value.Value.Month) % 10) | (((value.Value.Month) / 10) << 4)), 829 | (byte)(((value.Value.Day) % 10) | (((value.Value.Day) / 10) << 4)) 830 | }; 831 | } 832 | else 833 | { 834 | manufacturingDate = new byte[3]; 835 | } 836 | } 837 | } 838 | 839 | [MarshalAs(UnmanagedType.U1)] 840 | byte countryCode = (byte)Country.Japan; 841 | /// 842 | /// Country code. 0x49 = Japan 843 | /// 844 | public Country CountryCode { get => (Country)countryCode; set => countryCode = (byte)value; } 845 | 846 | [MarshalAs(UnmanagedType.U1)] 847 | byte unknown07 = 0x61; 848 | /// 849 | /// Unknown, offset 0x23. 850 | /// Always 0x61. 851 | /// Speculative: Region code? 852 | /// 853 | public byte Unknown07 { get => unknown07; set => unknown07 = value; } 854 | 855 | [MarshalAs(UnmanagedType.U1)] 856 | byte unknown08 = 0x00; 857 | /// 858 | /// Unknown, offset 0x24. 859 | /// Always 0x00. 860 | /// Speculative: Location/site? 861 | /// 862 | public byte Unknown08 { get => unknown08; set => unknown08 = value; } 863 | 864 | [MarshalAs(UnmanagedType.U1)] 865 | byte unknown09 = 0x00; 866 | /// 867 | /// Unknown, offset 0x25. 868 | /// Always 0x00 869 | /// 870 | public byte Unknown09 { get => unknown09; set => unknown09 = value; } 871 | 872 | [MarshalAs(UnmanagedType.U1)] 873 | byte unknown10 = 0x02; 874 | /// 875 | /// Unknown, offset 0x26. 876 | /// Always 0x02 877 | /// 878 | public byte Unknown10 { get => unknown10; set => unknown10 = value; } 879 | 880 | [MarshalAs(UnmanagedType.U1)] 881 | byte unknown11 = 0; 882 | /// 883 | /// Unknown, offset 0x27. Speculative: some kind of game information representation? 884 | /// 885 | public byte Unknown11 { get => unknown11; set => unknown11 = value; } 886 | 887 | [MarshalAs(UnmanagedType.U1)] 888 | // Speculative: some kind of game information representation? 889 | byte unknown12 = 0; 890 | /// 891 | /// Unknown, offset 0x28. Speculative: some kind of game information representation? 892 | /// 893 | public byte Unknown12 { get => unknown12; set => unknown12 = value; } 894 | 895 | [MarshalAs(UnmanagedType.U1)] 896 | byte unknown13 = 0; 897 | /// 898 | /// Unknown, offset 0x29. Speculative: some kind of game information representation? 899 | /// 900 | public byte Unknown13 { get => unknown13; set => unknown13 = value; } 901 | 902 | [MarshalAs(UnmanagedType.U1)] 903 | byte unknown14 = 0; 904 | /// 905 | /// Unknown, offset 0x2A. Speculative: some kind of game information representation? 906 | /// 907 | public byte Unknown14 { get => unknown14; set => unknown14 = value; } 908 | 909 | [MarshalAs(UnmanagedType.U1)] 910 | byte unknown15 = 0; 911 | /// 912 | /// Unknown, offset 0x2B. Speculative: some kind of game information representation? 913 | /// 914 | public byte Unknown15 { get => unknown15; set => unknown15 = value; } 915 | 916 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)] 917 | byte[] rewrittenDate = { 0, 0, 0 }; 918 | /// 919 | /// "Rewritten disk" date. It's speculated this refers to the date the disk was formatted and rewritten by something like a Disk Writer kiosk. 920 | /// In the case of an original (non-copied) disk, this should be the same as Manufacturing date 921 | /// 922 | public DateTime? RewrittenDate 923 | { 924 | get 925 | { 926 | try 927 | { 928 | if (rewrittenDate.Where(b => b != 0).Any()) 929 | return new DateTime( 930 | ((rewrittenDate[0] & 0x0F) + ((rewrittenDate[0] >> 4) & 0x0F) * 10) + 1925, 931 | ((rewrittenDate[1] & 0x0F) + ((rewrittenDate[1] >> 4) & 0x0F) * 10), 932 | ((rewrittenDate[2] & 0x0F) + ((rewrittenDate[2] >> 4) & 0x0F) * 10) 933 | ); 934 | else 935 | return null; 936 | } 937 | catch 938 | { 939 | return null; 940 | } 941 | } 942 | set 943 | { 944 | if (value != null) 945 | { 946 | rewrittenDate = new byte[] 947 | { 948 | (byte)(((value.Value.Year - 1925) % 10) | (((value.Value.Year - 1925) / 10) << 4)), 949 | (byte)(((value.Value.Month) % 10) | (((value.Value.Month) / 10) << 4)), 950 | (byte)(((value.Value.Day) % 10) | (((value.Value.Day) / 10) << 4)) 951 | }; 952 | } 953 | else 954 | { 955 | rewrittenDate = new byte[3]; 956 | } 957 | } 958 | } 959 | 960 | [MarshalAs(UnmanagedType.U1)] 961 | byte unknown16 = 0x00; 962 | /// 963 | /// Unknown, offset 0x2F 964 | /// 965 | public byte Unknown16 { get => unknown16; set => unknown16 = value; } 966 | 967 | [MarshalAs(UnmanagedType.U1)] 968 | byte unknown17 = 0x80; 969 | /// 970 | /// Unknown, offset 0x30. 971 | /// Always 0x80 972 | /// 973 | public byte Unknown17 { get => unknown17; set => unknown17 = value; } 974 | 975 | ushort diskWriterSerialNumber; 976 | /// 977 | /// Disk Writer serial number 978 | /// 979 | public ushort DiskWriterSerialNumber { get => diskWriterSerialNumber; set => diskWriterSerialNumber = value; } 980 | 981 | [MarshalAs(UnmanagedType.U1)] 982 | byte unknown18 = 0x07; 983 | /// 984 | /// Unknown, offset 0x33, unknown. 985 | /// Always 0x07 986 | /// 987 | public byte Unknown18 { get => unknown18; set => unknown18 = value; } 988 | 989 | [MarshalAs(UnmanagedType.U1)] 990 | byte diskRewriteCount = 0x00; 991 | /// 992 | /// Disk rewrite count. 993 | /// 0x00 = Original (no copies) 994 | /// 995 | public byte DiskRewriteCount 996 | { 997 | get 998 | { 999 | return (diskRewriteCount == 0xFF) ? (byte)0 : (byte)((diskRewriteCount & 0x0F) + ((diskRewriteCount >> 4) & 0x0F) * 10); 1000 | } 1001 | set 1002 | { 1003 | diskRewriteCount = (byte)(((value) % 10) | (((value) / 10) << 4)); 1004 | } 1005 | } 1006 | 1007 | [MarshalAs(UnmanagedType.U1)] 1008 | byte actualDiskSide = 0x00; 1009 | /// 1010 | /// Actual disk side 1011 | /// 1012 | public DiskSides ActualDiskSide { get => (DiskSides)actualDiskSide; set => actualDiskSide = (byte)value; } 1013 | 1014 | [MarshalAs(UnmanagedType.U1)] 1015 | byte diskTypeOther = 0x00; 1016 | /// 1017 | /// Disk type (other) 1018 | /// 1019 | public DiskTypesOther DiskTypeOther { get => (DiskTypesOther)diskType; set => diskType = (byte)value; } 1020 | 1021 | [MarshalAs(UnmanagedType.U1)] 1022 | byte price = 0x00; 1023 | /// 1024 | /// Price code (deprecated, no backing) 1025 | /// 1026 | [Obsolete("Use \"DiskVersion\" property")] 1027 | public byte Price { get => price; set => price = value; } 1028 | 1029 | /// 1030 | /// Unknown how this differs from GameVersion. Disk version numbers indicate different software revisions. 1031 | /// Speculation is that disk version incremented with each disk received from a licensee 1032 | /// 1033 | public byte DiskVersion { get => price; set => price = value; } 1034 | 1035 | /// 1036 | /// Length of the block 1037 | /// 1038 | public uint Length { get => 56; } 1039 | 1040 | /// 1041 | /// Create FdsBlockDiskInfo object from raw data 1042 | /// 1043 | /// Data 1044 | /// Data offset 1045 | /// FdsBlockDiskInfo object 1046 | /// 1047 | public static FdsBlockDiskInfo FromBytes(byte[] data, int offset = 0) 1048 | { 1049 | int rawsize = Marshal.SizeOf(typeof(FdsBlockDiskInfo)); 1050 | if (rawsize > data.Length - offset) 1051 | throw new InvalidDataException("Not enough data to fill FdsDiskInfoBlock class. Array length from position: " + (data.Length - offset) + ", struct length: " + rawsize); 1052 | IntPtr buffer = Marshal.AllocHGlobal(rawsize); 1053 | Marshal.Copy(data, offset, buffer, rawsize); 1054 | FdsBlockDiskInfo retobj = (FdsBlockDiskInfo)Marshal.PtrToStructure(buffer, typeof(FdsBlockDiskInfo)); 1055 | Marshal.FreeHGlobal(buffer); 1056 | return retobj; 1057 | } 1058 | 1059 | /// 1060 | /// Returns raw data 1061 | /// 1062 | /// Data 1063 | public byte[] ToBytes() 1064 | { 1065 | int rawSize = Marshal.SizeOf(this); 1066 | IntPtr buffer = Marshal.AllocHGlobal(rawSize); 1067 | Marshal.StructureToPtr(this, buffer, false); 1068 | byte[] data = new byte[rawSize]; 1069 | Marshal.Copy(buffer, data, 0, rawSize); 1070 | Marshal.FreeHGlobal(buffer); 1071 | return data; 1072 | } 1073 | 1074 | /// 1075 | /// String representation 1076 | /// 1077 | /// Game name 1078 | public override string ToString() => GameName ?? "---"; 1079 | 1080 | /// 1081 | /// Equality comparer 1082 | /// 1083 | /// Other FdsBlockDiskInfo object 1084 | /// True if objects are equal 1085 | public bool Equals(FdsBlockDiskInfo other) 1086 | { 1087 | return Enumerable.SequenceEqual(this.ToBytes(), other.ToBytes()); 1088 | } 1089 | } 1090 | } 1091 | -------------------------------------------------------------------------------- /FdsBlockFileAmount.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | 5 | namespace com.clusterrr.Famicom.Containers 6 | { 7 | /// 8 | /// File amount FDS block (block type 2) 9 | /// 10 | public class FdsBlockFileAmount : IFdsBlock, IEquatable 11 | { 12 | private byte blockType = 2; 13 | /// 14 | /// Valid block type ID 15 | /// 16 | public byte ValidTypeID { get => 2; } 17 | /// 18 | /// True if block type ID is valid 19 | /// 20 | public bool IsValid { get => blockType == ValidTypeID; } 21 | 22 | private byte fileAmount; 23 | /// 24 | /// Amount of files 25 | /// 26 | public byte FileAmount { get => fileAmount; set => fileAmount = value; } 27 | 28 | /// 29 | /// Length of the block 30 | /// 31 | public uint Length { get => 2; } 32 | 33 | /// 34 | /// Create FdsBlockFileAmount object from raw data 35 | /// 36 | /// Data 37 | /// Data offset 38 | /// FdsBlockFileAmount object 39 | public static FdsBlockFileAmount FromBytes(byte[] data, int offset = 0) 40 | { 41 | if (data.Length - offset < 2) 42 | throw new InvalidDataException("Not enough data to fill FdsBlockFileAmount class. Array length from position: " + (data.Length - offset) + ", struct length: 2"); 43 | return new FdsBlockFileAmount 44 | { 45 | blockType = data[offset], 46 | fileAmount = data[offset + 1] 47 | }; 48 | } 49 | 50 | /// 51 | /// Returns raw data 52 | /// 53 | /// Data 54 | public byte[] ToBytes() => new byte[] { blockType, fileAmount }; 55 | 56 | /// 57 | /// String representation 58 | /// 59 | /// File amount as string 60 | public override string ToString() => $"{FileAmount}"; 61 | 62 | /// 63 | /// Equality comparer 64 | /// 65 | /// Other FdsBlockFileAmount object 66 | /// True if objects are equal 67 | public bool Equals(FdsBlockFileAmount other) 68 | { 69 | return Enumerable.SequenceEqual(this.ToBytes(), other.ToBytes()); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /FdsBlockFileData.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace com.clusterrr.Famicom.Containers 6 | { 7 | /// 8 | /// File data FDS block (block type 4) 9 | /// 10 | public class FdsBlockFileData : IFdsBlock, IEquatable 11 | { 12 | private byte blockType = 4; 13 | /// 14 | /// Valid block type ID 15 | /// 16 | public byte ValidTypeID { get => 4; } 17 | /// 18 | /// True if block type ID is valid 19 | /// 20 | public bool IsValid { get => blockType == ValidTypeID; } 21 | 22 | private byte[] data = Array.Empty(); 23 | /// 24 | /// File data 25 | /// 26 | public IEnumerable Data 27 | { 28 | get => Array.AsReadOnly(data); 29 | set => data = value.ToArray(); 30 | } 31 | 32 | /// 33 | /// Length of the block 34 | /// 35 | public uint Length => (uint)(data.Length + 1); 36 | 37 | /// 38 | /// Create FdsBlockFileData object from raw data 39 | /// 40 | /// Data 41 | /// Offset 42 | /// Length 43 | /// FdsBlockFileData object 44 | public static FdsBlockFileData FromBytes(byte[] data, int offset = 0, int length = -1) 45 | { 46 | var retobj = new FdsBlockFileData 47 | { 48 | blockType = data[offset], 49 | data = new byte[length < 0 ? data.Length - offset - 1 : length - 1] 50 | }; 51 | Array.Copy(data, offset + 1, retobj.data, 0, retobj.data.Length); 52 | return retobj; 53 | } 54 | 55 | /// 56 | /// Returns raw data 57 | /// 58 | /// Data 59 | public byte[] ToBytes() => Enumerable.Concat(new[] { blockType }, data).ToArray(); 60 | 61 | /// 62 | /// String representation 63 | /// 64 | /// Number of bytes as string 65 | public override string ToString() => $"{data.Length} bytes"; 66 | 67 | /// 68 | /// Equality comparer 69 | /// 70 | /// Other FdsBlockFileData object 71 | /// True if objects are equal 72 | public bool Equals(FdsBlockFileData other) 73 | { 74 | return Enumerable.SequenceEqual(this.ToBytes(), other.ToBytes()); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /FdsBlockFileHeader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Runtime.InteropServices; 5 | using System.Text; 6 | 7 | namespace com.clusterrr.Famicom.Containers 8 | { 9 | /// 10 | /// File header FDS block (block type 3) 11 | /// 12 | [StructLayout(LayoutKind.Sequential, Size = 16, Pack = 1)] 13 | public class FdsBlockFileHeader : IFdsBlock, IEquatable 14 | { 15 | static Encoding textEncoding = Encoding.GetEncoding("ISO-8859-1"); 16 | 17 | /// 18 | /// Kind of the file 19 | /// 20 | public enum Kind 21 | { 22 | /// 23 | /// PRG data 24 | /// 25 | Program = 0, 26 | /// 27 | /// CHR data 28 | /// 29 | Character = 1, 30 | /// 31 | /// Nametable data 32 | /// 33 | NameTable = 2 34 | } 35 | 36 | [MarshalAs(UnmanagedType.U1)] 37 | private readonly byte blockType = 3; 38 | /// 39 | /// Valid block type ID 40 | /// 41 | public byte ValidTypeID { get => 3; } 42 | /// 43 | /// True if block type ID is valid 44 | /// 45 | public bool IsValid { get => blockType == 3; } 46 | 47 | [MarshalAs(UnmanagedType.U1)] 48 | private byte fileNumber; 49 | /// 50 | /// File number 51 | /// 52 | public byte FileNumber { get => fileNumber; set => fileNumber = value; } 53 | 54 | [MarshalAs(UnmanagedType.U1)] 55 | private byte fileIndicateCode; 56 | /// 57 | /// File indicate code (ID specified at disk-read function call) 58 | /// 59 | public byte FileIndicateCode { get => fileIndicateCode; set => fileIndicateCode = value; } 60 | 61 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] 62 | private byte[] fileName = textEncoding.GetBytes("FILENAME"); 63 | /// 64 | /// Filename 65 | /// 66 | public string FileName 67 | { 68 | get => textEncoding.GetString(fileName).TrimEnd(new char[] { '\0' }); set 69 | { 70 | if (value.Length > 8) throw new InvalidDataException($"Filename \"{value}\" too long, must be <= 8"); 71 | fileName = textEncoding.GetBytes(value.PadRight(8, '\0')).Take(8).ToArray(); 72 | } 73 | } 74 | 75 | [MarshalAs(UnmanagedType.U2)] 76 | // the destination address when loading 77 | private ushort fileAddress; 78 | /// 79 | /// File address - the destination address when loading 80 | /// 81 | public ushort FileAddress { get => fileAddress; set => fileAddress = value; } 82 | 83 | [MarshalAs(UnmanagedType.U2)] 84 | private ushort fileSize; 85 | /// 86 | /// File size 87 | /// 88 | public ushort FileSize { get => fileSize; set => fileSize = value; } 89 | 90 | [MarshalAs(UnmanagedType.U1)] 91 | private byte fileKind; 92 | /// 93 | /// Kind of the file: program, character or nametable 94 | /// 95 | public Kind FileKind { get => (Kind)fileKind; set => fileKind = (byte)value; } 96 | 97 | /// 98 | /// Length of the block 99 | /// 100 | public uint Length { get => 16; } 101 | 102 | /// 103 | /// Create FdsBlockFileHeader object from raw data 104 | /// 105 | /// Data 106 | /// Offset 107 | /// 108 | /// 109 | public static FdsBlockFileHeader FromBytes(byte[] data, int offset = 0) 110 | { 111 | int rawsize = Marshal.SizeOf(typeof(FdsBlockFileHeader)); 112 | if (rawsize > data.Length - offset) 113 | { 114 | if (rawsize <= data.Length - offset + 2) 115 | { 116 | var newRawData = new byte[rawsize]; 117 | Array.Copy(data, offset, newRawData, 0, rawsize - 2); 118 | data = newRawData; 119 | offset = 0; 120 | } 121 | else 122 | { 123 | throw new InvalidDataException("Not enough data to fill FdsFileHeaderBlock class. Array length from position: " + (data.Length - offset) + ", struct length: " + rawsize); 124 | } 125 | } 126 | IntPtr buffer = Marshal.AllocHGlobal(rawsize); 127 | Marshal.Copy(data, offset, buffer, rawsize); 128 | FdsBlockFileHeader retobj = (FdsBlockFileHeader)Marshal.PtrToStructure(buffer, typeof(FdsBlockFileHeader)); 129 | Marshal.FreeHGlobal(buffer); 130 | return retobj; 131 | } 132 | 133 | /// 134 | /// Returns raw data 135 | /// 136 | /// Data 137 | public byte[] ToBytes() 138 | { 139 | int rawSize = Marshal.SizeOf(this); 140 | IntPtr buffer = Marshal.AllocHGlobal(rawSize); 141 | Marshal.StructureToPtr(this, buffer, false); 142 | byte[] data = new byte[rawSize]; 143 | Marshal.Copy(buffer, data, 0, rawSize); 144 | Marshal.FreeHGlobal(buffer); 145 | return data; 146 | } 147 | 148 | /// 149 | /// String representation 150 | /// 151 | /// File name and file kind as string 152 | public override string ToString() => $"{FileName} ({FileKind})"; 153 | 154 | /// 155 | /// Equality comparer 156 | /// 157 | /// Other FdsBlockFileHeader object 158 | /// True if objects are equal 159 | public bool Equals(FdsBlockFileHeader other) 160 | { 161 | return Enumerable.SequenceEqual(this.ToBytes(), other.ToBytes()); 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /FdsDiskFile.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace com.clusterrr.Famicom.Containers 5 | { 6 | /// 7 | /// File on FDS disk - header and data 8 | /// 9 | public class FdsDiskFile 10 | { 11 | private FdsBlockFileHeader headerBlock; 12 | private FdsBlockFileData dataBlock; 13 | /// 14 | /// FDS block with file header 15 | /// 16 | public FdsBlockFileHeader HeaderBlock { get => headerBlock; set => headerBlock = value; } 17 | /// 18 | /// FDS block with file contents 19 | /// 20 | public FdsBlockFileData DataBlock { get => dataBlock; set => dataBlock = value; } 21 | 22 | /// 23 | /// File number 24 | /// 25 | public byte FileNumber { get => HeaderBlock.FileNumber; set => HeaderBlock.FileNumber = value; } 26 | /// 27 | /// File indicate code (ID specified at disk-read function call) 28 | /// 29 | public byte FileIndicateCode { get => HeaderBlock.FileIndicateCode; set => HeaderBlock.FileIndicateCode = value; } 30 | /// 31 | /// Filename 32 | /// 33 | public string FileName { get => HeaderBlock.FileName; set => HeaderBlock.FileName = value; } 34 | /// 35 | /// File address - the destination address when loading 36 | /// 37 | public ushort FileAddress { get => HeaderBlock.FileAddress; set => HeaderBlock.FileAddress = value; } 38 | /// 39 | /// File size 40 | /// 41 | public ushort FileSize { get => (ushort)DataBlock.Data.Count(); } 42 | /// 43 | /// Kind of the file: program, character or nametable 44 | /// 45 | public FdsBlockFileHeader.Kind FileKind { get => HeaderBlock.FileKind; set => HeaderBlock.FileKind = value; } 46 | /// 47 | /// File contents 48 | /// 49 | public IEnumerable Data 50 | { 51 | get => DataBlock.Data; 52 | set 53 | { 54 | DataBlock.Data = value; 55 | HeaderBlock.FileSize = (ushort)DataBlock.Data.Count(); 56 | } 57 | } 58 | 59 | /// 60 | /// Construcor 61 | /// 62 | /// File header block 63 | /// File data block 64 | public FdsDiskFile(FdsBlockFileHeader headerBlock, FdsBlockFileData dataBlock) 65 | { 66 | this.headerBlock = headerBlock; 67 | this.dataBlock = dataBlock; 68 | headerBlock.FileSize = (ushort)dataBlock.Data.Count(); 69 | } 70 | 71 | /// 72 | /// Construcor for empty FdsDiskFile object 73 | /// 74 | public FdsDiskFile() 75 | { 76 | this.headerBlock = new FdsBlockFileHeader(); 77 | this.dataBlock = new FdsBlockFileData(); 78 | HeaderBlock.FileSize = (ushort)DataBlock.Data.Count(); 79 | } 80 | 81 | /// 82 | /// Returns raw file contents 83 | /// 84 | /// Raw file contents 85 | public byte[] ToBytes() => Enumerable.Concat(HeaderBlock.ToBytes(), DataBlock.ToBytes()).ToArray(); 86 | 87 | /// 88 | /// String representation: filename, file kind, data block info 89 | /// 90 | /// String representation of the file 91 | public override string ToString() => $"{FileName} ({FileKind}, {dataBlock})"; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /FdsDiskSide.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using static com.clusterrr.Famicom.Containers.FdsBlockDiskInfo; 5 | using System.Runtime.InteropServices; 6 | using System.Text; 7 | 8 | namespace com.clusterrr.Famicom.Containers 9 | { 10 | /// 11 | /// Single FDS disk side: disk info block, file amount block and file blocks 12 | /// 13 | public class FdsDiskSide 14 | { 15 | readonly FdsBlockDiskInfo diskInfoBlock; 16 | /// 17 | /// Disk info block 18 | /// 19 | public FdsBlockDiskInfo DiskInfoBlock { get => diskInfoBlock; } 20 | 21 | /// 22 | /// Literal ASCII string: *NINTENDO-HVC* 23 | /// 24 | public string DiskVerification => diskInfoBlock.DiskVerification; 25 | 26 | /// 27 | /// Manufacturer code. 0x00 = Unlicensed, 0x01 = Nintendo 28 | /// 29 | public Company LicenseeCode { get => diskInfoBlock.LicenseeCode; set => diskInfoBlock.LicenseeCode = value; } 30 | 31 | /// 32 | /// 3-letter ASCII code per game (e.g. ZEL for The Legend of Zelda) 33 | /// 34 | public string? GameName { get => diskInfoBlock.GameName; set => diskInfoBlock.GameName = value; } 35 | 36 | /// 37 | /// 0x20 = " " — Normal disk 38 | /// 0x45 = "E" — Event(e.g.Japanese national DiskFax tournaments) 39 | /// 0x52 = "R" — Reduction in price via advertising 40 | /// 41 | public char GameType { get => diskInfoBlock.GameType; set => diskInfoBlock.GameType = value; } 42 | 43 | /// 44 | /// Game version/revision number. Starts at 0x00, increments per revision 45 | /// 46 | public byte GameVersion { get => diskInfoBlock.GameVersion; set => diskInfoBlock.GameVersion = value; } 47 | 48 | /// 49 | /// Side number. Single-sided disks use A 50 | /// 51 | public DiskSides DiskSide { get => diskInfoBlock.DiskSide; set => diskInfoBlock.DiskSide = value; } 52 | 53 | /// 54 | /// Disk number. First disk is 0x00, second is 0x01, etc. 55 | /// 56 | public byte DiskNumber { get => diskInfoBlock.DiskNumber; set => diskInfoBlock.DiskNumber = value; } 57 | 58 | /// 59 | /// Disk type. 0x00 = FMC ("normal card"), 0x01 = FSC ("card with shutter"). May correlate with FMC and FSC product codes 60 | /// 61 | public DiskTypes DiskType { get => diskInfoBlock.DiskType; set => diskInfoBlock.DiskType = value; } 62 | 63 | /// 64 | /// Unknown, offset 0x18. 65 | /// Always 0x00 66 | /// 67 | public byte Unknown01 { get => diskInfoBlock.Unknown01; set => diskInfoBlock.Unknown01 = value; } 68 | 69 | /// 70 | /// Boot read file code. Refers to the file code/file number to load upon boot/start-up 71 | /// 72 | public byte BootFile { get => diskInfoBlock.BootFile; set => diskInfoBlock.BootFile = value; } 73 | 74 | /// 75 | /// Unknown, offset 0x1A. 76 | /// Always 0xFF 77 | /// 78 | public byte Unknown02 { get => diskInfoBlock.Unknown02; set => diskInfoBlock.Unknown02 = value; } 79 | 80 | /// 81 | /// Unknown, offset 0x1B. 82 | /// Always 0xFF 83 | /// 84 | public byte Unknown03 { get => diskInfoBlock.Unknown03; set => diskInfoBlock.Unknown03 = value; } 85 | 86 | /// 87 | /// Unknown, offset 0x1C. 88 | /// Always 0xFF 89 | /// 90 | public byte Unknown04 { get => diskInfoBlock.Unknown04; set => diskInfoBlock.Unknown04 = value; } 91 | 92 | /// 93 | /// Unknown, offset 0x1D. 94 | /// Always 0xFF 95 | /// 96 | public byte Unknown05 { get => diskInfoBlock.Unknown05; set => diskInfoBlock.Unknown05 = value; } 97 | 98 | /// 99 | /// Unknown, offset 0x1E. 100 | /// Always 0xFF 101 | /// 102 | public byte Unknown06 { get => diskInfoBlock.Unknown06; set => diskInfoBlock.Unknown06 = value; } 103 | 104 | /// 105 | /// Manufacturing date 106 | /// 107 | public DateTime? ManufacturingDate { get => diskInfoBlock.ManufacturingDate; set => diskInfoBlock.ManufacturingDate = value; } 108 | 109 | /// 110 | /// Country code. 0x49 = Japan 111 | /// 112 | public Country CountryCode { get => diskInfoBlock.CountryCode; set => diskInfoBlock.CountryCode = value; } 113 | 114 | /// 115 | /// Unknown, offset 0x23. 116 | /// Always 0x61. 117 | /// Speculative: Region code? 118 | /// 119 | public byte Unknown07 { get => diskInfoBlock.Unknown07; set => diskInfoBlock.Unknown07 = value; } 120 | 121 | /// 122 | /// Unknown, offset 0x24. 123 | /// Always 0x00. 124 | /// Speculative: Location/site? 125 | /// 126 | public byte Unknown08 { get => diskInfoBlock.Unknown08; set => diskInfoBlock.Unknown08 = value; } 127 | 128 | /// 129 | /// Unknown, offset 0x25. 130 | /// Always 0x00 131 | /// 132 | public byte Unknown09 { get => diskInfoBlock.Unknown09; set => diskInfoBlock.Unknown09 = value; } 133 | 134 | /// 135 | /// Unknown, offset 0x26. 136 | /// Always 0x02 137 | /// 138 | public byte Unknown10 { get => diskInfoBlock.Unknown10; set => diskInfoBlock.Unknown10 = value; } 139 | 140 | /// 141 | /// Unknown, offset 0x27. Speculative: some kind of game information representation? 142 | /// 143 | public byte Unknown11 { get => diskInfoBlock.Unknown11; set => diskInfoBlock.Unknown11 = value; } 144 | 145 | /// 146 | /// Unknown, offset 0x28. Speculative: some kind of game information representation? 147 | /// 148 | public byte Unknown12 { get => diskInfoBlock.Unknown12; set => diskInfoBlock.Unknown12 = value; } 149 | 150 | /// 151 | /// Unknown, offset 0x29. Speculative: some kind of game information representation? 152 | /// 153 | public byte Unknown13 { get => diskInfoBlock.Unknown13; set => diskInfoBlock.Unknown13 = value; } 154 | 155 | /// 156 | /// Unknown, offset 0x2A. Speculative: some kind of game information representation? 157 | /// 158 | public byte Unknown14 { get => diskInfoBlock.Unknown14; set => diskInfoBlock.Unknown14 = value; } 159 | 160 | /// 161 | /// Unknown, offset 0x2B. Speculative: some kind of game information representation? 162 | /// 163 | public byte Unknown15 { get => diskInfoBlock.Unknown15; set => diskInfoBlock.Unknown15 = value; } 164 | 165 | /// 166 | /// "Rewritten disk" date. It's speculated this refers to the date the disk was formatted and rewritten by something like a Disk Writer kiosk. 167 | /// In the case of an original (non-copied) disk, this should be the same as Manufacturing date 168 | /// 169 | public DateTime? RewrittenDate { get => diskInfoBlock.RewrittenDate; set => diskInfoBlock.RewrittenDate = value; } 170 | 171 | /// 172 | /// Unknown, offset 0x2F 173 | /// 174 | public byte Unknown16 { get => diskInfoBlock.Unknown16; set => diskInfoBlock.Unknown16 = value; } 175 | 176 | /// 177 | /// Unknown, offset 0x30. 178 | /// Always 0x80 179 | /// 180 | public byte Unknown17 { get => diskInfoBlock.Unknown17; set => diskInfoBlock.Unknown17 = value; } 181 | 182 | /// 183 | /// Disk Writer serial number 184 | /// 185 | public ushort DiskWriterSerialNumber { get => diskInfoBlock.DiskWriterSerialNumber; set => diskInfoBlock.DiskWriterSerialNumber = value; } 186 | 187 | /// 188 | /// Unknown, offset 0x33, unknown. 189 | /// Always 0x07 190 | /// 191 | public byte Unknown18 { get => diskInfoBlock.Unknown18; set => diskInfoBlock.Unknown18 = value; } 192 | 193 | /// 194 | /// Disk rewrite count. 195 | /// 0x00 = Original (no copies) 196 | /// 197 | public byte DiskRewriteCount { get => diskInfoBlock.DiskRewriteCount; set => diskInfoBlock.DiskRewriteCount = value; } 198 | 199 | /// 200 | /// Actual disk side 201 | /// 202 | public DiskSides ActualDiskSide { get => diskInfoBlock.ActualDiskSide; set => diskInfoBlock.ActualDiskSide = value; } 203 | 204 | /// 205 | /// Disk type (other) 206 | /// 207 | public DiskTypesOther DiskTypeOther { get => diskInfoBlock.DiskTypeOther; set => diskInfoBlock.DiskTypeOther = value; } 208 | 209 | /// 210 | /// Price code (deprecated, no backing) 211 | /// 212 | [Obsolete("Use \"DiskVersion\" property")] 213 | public byte Price { get => diskInfoBlock.DiskVersion; set => diskInfoBlock.DiskVersion = value; } 214 | 215 | /// 216 | /// Unknown how this differs from GameVersion. Disk version numbers indicate different software revisions. 217 | /// Speculation is that disk version incremented with each disk received from a licensee 218 | /// 219 | public byte DiskVersion { get => diskInfoBlock.DiskVersion; set => diskInfoBlock.DiskVersion = value; } 220 | 221 | readonly FdsBlockFileAmount fileAmountBlock; 222 | /// 223 | /// Non-hidden file amount 224 | /// 225 | public byte FileAmount { get => fileAmountBlock.FileAmount; set => fileAmountBlock.FileAmount = value; } 226 | 227 | readonly IList files; 228 | /// 229 | /// Files on disk 230 | /// 231 | public IList Files { get => files; } 232 | 233 | /// 234 | /// Constructor to create empty FdsDiskSide object 235 | /// 236 | public FdsDiskSide() 237 | { 238 | diskInfoBlock = new FdsBlockDiskInfo(); 239 | fileAmountBlock = new FdsBlockFileAmount(); 240 | files = new List(); 241 | } 242 | 243 | /// 244 | /// Constructor to create FdsDiskSide object from blocks and files 245 | /// 246 | /// Disk info block 247 | /// File amount block 248 | /// Files 249 | public FdsDiskSide(FdsBlockDiskInfo diskInfoBlock, FdsBlockFileAmount fileAmountBlock, IEnumerable files) 250 | { 251 | this.diskInfoBlock = diskInfoBlock; 252 | this.fileAmountBlock = fileAmountBlock; 253 | this.files = files.ToList(); 254 | } 255 | 256 | /// 257 | /// Constructor to create FdsDiskSide object from blocks 258 | /// 259 | /// 260 | public FdsDiskSide(IEnumerable blocks) 261 | { 262 | this.diskInfoBlock = (FdsBlockDiskInfo)blocks.First(); 263 | this.fileAmountBlock = (FdsBlockFileAmount)blocks.Skip(1).First(); 264 | files = new List(); 265 | var fileBlocks = blocks.Skip(2).ToArray(); 266 | for (int i = 0; i < fileBlocks.Length / 2; i++) 267 | { 268 | files.Add(new FdsDiskFile((FdsBlockFileHeader)fileBlocks[i * 2], (FdsBlockFileData)fileBlocks[i * 2 + 1])); 269 | } 270 | } 271 | 272 | /// 273 | /// Constructor to create FdsDiskSide object from raw data 274 | /// 275 | /// 276 | public FdsDiskSide(byte[] data) : this() 277 | { 278 | int pos = 0; 279 | this.diskInfoBlock = FdsBlockDiskInfo.FromBytes(data.Take(56).ToArray()); 280 | pos += 56; 281 | this.fileAmountBlock = FdsBlockFileAmount.FromBytes(data.Skip(pos).Take(2).ToArray()); 282 | pos += 2; 283 | while (pos < data.Length) 284 | { 285 | try 286 | { 287 | var fileHeaderBlock = FdsBlockFileHeader.FromBytes(data.Skip(pos).Take(16).ToArray()); 288 | if (!fileHeaderBlock.IsValid) 289 | break; 290 | pos += 16; 291 | var fileDataBlock = FdsBlockFileData.FromBytes(data.Skip(pos).Take(fileHeaderBlock.FileSize + 1).ToArray()); 292 | if (!fileDataBlock.IsValid) 293 | break; 294 | pos += fileHeaderBlock.FileSize + 1; 295 | files.Add(new FdsDiskFile(fileHeaderBlock, fileDataBlock)); 296 | } 297 | catch 298 | { 299 | // just break on out of range 300 | break; 301 | } 302 | } 303 | } 304 | 305 | /// 306 | /// Change file's "file number" fields orderly 307 | /// 308 | public void FixFileNumbers() 309 | { 310 | for (var i = 0; i < files.Count; i++) 311 | files[i].FileNumber = (byte)i; 312 | } 313 | 314 | /// 315 | /// Get FDS blocks 316 | /// 317 | /// 318 | public IEnumerable GetBlocks() 319 | { 320 | var blocks = new List 321 | { 322 | diskInfoBlock, 323 | fileAmountBlock 324 | }; 325 | blocks.AddRange(files.SelectMany(f => new IFdsBlock[] { f.HeaderBlock, f.DataBlock })); 326 | return blocks; 327 | } 328 | 329 | /// 330 | /// Create FdsDiskSide object from raw data 331 | /// 332 | /// Data 333 | /// FdsDiskSide object 334 | 335 | public static FdsDiskSide FromBytes(byte[] data) 336 | { 337 | return new FdsDiskSide(data); 338 | } 339 | 340 | /// 341 | /// Return raw data 342 | /// 343 | /// 344 | public byte[] ToBytes() 345 | { 346 | var data = Enumerable.Concat(Enumerable.Concat(diskInfoBlock.ToBytes(), fileAmountBlock.ToBytes()), files.SelectMany(f => f.ToBytes())).ToArray(); 347 | return Enumerable.Concat(data, new byte[65500 - data.Count()]).ToArray(); 348 | } 349 | 350 | /// 351 | /// String representation 352 | /// 353 | /// Game name, disk number, side number as string 354 | public override string ToString() => $"{GameName ?? "---"} - disk {DiskNumber + 1}, side {DiskSide}"; 355 | } 356 | } 357 | -------------------------------------------------------------------------------- /FdsFile.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using System.Linq; 4 | 5 | namespace com.clusterrr.Famicom.Containers 6 | { 7 | /// 8 | /// File container for FDS games, disk sides collection 9 | /// 10 | public class FdsFile 11 | { 12 | IList sides; 13 | /// 14 | /// Disk Side Images 15 | /// 16 | public IList Sides { get => sides; set => sides = value ?? new List(); } 17 | 18 | /// 19 | /// Constructor to create empty FdsFile object 20 | /// 21 | public FdsFile() 22 | { 23 | sides = new List(); 24 | } 25 | 26 | /// 27 | /// Create FdsFile object from the specified .nes file 28 | /// 29 | /// Path to the .fds file 30 | public FdsFile(string filename) : this(File.ReadAllBytes(filename)) 31 | { 32 | } 33 | 34 | /// 35 | /// Create FdsFile object from raw .fds file data 36 | /// 37 | /// 38 | public FdsFile(byte[] data) : this() 39 | { 40 | if (data[0] == (byte)'F' && data[1] == (byte)'D' && data[2] == (byte)'S' && data[3] == 0x1A) 41 | data = data.Skip(16).ToArray(); // skip header 42 | if (data.Length % 65500 != 0) throw new InvalidDataException("Invalid FDS image: the size must be divisible by 65500"); 43 | for (int i = 0; i < data.Length; i += 65500) 44 | { 45 | var sideData = data.Skip(i).Take(66500).ToArray(); 46 | sides.Add(FdsDiskSide.FromBytes(sideData)); 47 | } 48 | } 49 | 50 | /// 51 | /// Create FdsFile object from set of FdsDiskSide objects 52 | /// 53 | /// 54 | public FdsFile(IEnumerable sides) 55 | { 56 | this.sides = new List(sides); 57 | } 58 | 59 | /// 60 | /// Create FdsFile object from raw .fds file contents 61 | /// 62 | /// 63 | /// FdsFile object 64 | public static FdsFile FromBytes(byte[] data) =>new FdsFile(data); 65 | 66 | /// 67 | /// Create FileFile object from the specified .nes file 68 | /// 69 | /// Path to the .fds file 70 | /// FdsFile object 71 | public static FdsFile FromFile(string filename) => new FdsFile(filename); 72 | 73 | /// 74 | /// Returns .fds file contents 75 | /// 76 | /// Option to add .fds file header (ignored by most emulators) 77 | /// FDS file contents 78 | public byte[] ToBytes(bool useHeader = false) 79 | { 80 | var data = sides.SelectMany(s => s.ToBytes()); 81 | if (useHeader) 82 | { 83 | var header = new byte[16]; 84 | header[0] = (byte)'F'; 85 | header[1] = (byte)'D'; 86 | header[2] = (byte)'S'; 87 | header[3] = 0x1A; 88 | header[4] = (byte)sides.Count(); 89 | data = Enumerable.Concat(header, data); 90 | } 91 | return data.ToArray(); 92 | } 93 | 94 | /// 95 | /// Save as .fds file 96 | /// 97 | /// Target filename 98 | /// Option to add .fds file header (ignored by most emulators) 99 | public void Save(string filename, bool useHeader = false) => File.WriteAllBytes(filename, ToBytes(useHeader)); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /IFdsBlock.cs: -------------------------------------------------------------------------------- 1 | namespace com.clusterrr.Famicom.Containers 2 | { 3 | /// 4 | /// FDS block interface 5 | /// 6 | public interface IFdsBlock 7 | { 8 | /// 9 | /// Returns the valid block type ID 10 | /// 11 | byte ValidTypeID { get; } 12 | /// 13 | /// Returns true if the block type ID is valid 14 | /// 15 | bool IsValid { get; } 16 | /// 17 | /// Length of raw block data 18 | /// 19 | uint Length { get; } 20 | /// 21 | /// Return raw data 22 | /// 23 | /// 24 | byte[] ToBytes(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MirroringType.cs: -------------------------------------------------------------------------------- 1 | namespace com.clusterrr.Famicom.Containers 2 | { 3 | /// 4 | /// What CIRAM A10 is connected to 5 | /// 6 | public enum MirroringType 7 | { 8 | /// 9 | /// PPU A11 (horizontal mirroring) 10 | /// 11 | Horizontal = 0, 12 | /// 13 | /// PPU A10 (vertical mirroring) 14 | /// 15 | Vertical = 1, 16 | /// 17 | /// Ground (one-screen A) 18 | /// 19 | OneScreenA = 2, 20 | /// 21 | /// Vcc (one-screen B) 22 | /// 23 | OneScreenB = 3, 24 | /// 25 | /// Extra memory has been added (four-screen) 26 | /// 27 | FourScreenVram = 4, 28 | /// 29 | /// Mapper controlled 30 | /// 31 | MapperControlled = 5, // for UNIF 32 | /// 33 | /// Unknown value 34 | /// 35 | Unknown = 0xff 36 | }; 37 | } 38 | -------------------------------------------------------------------------------- /NesContainers.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | NesContainers 6 | com.clusterrr.Famicom.Containers 7 | 10.0 8 | embedded 9 | True 10 | NesContainers.xml 11 | LICENSE 12 | README.md 13 | enable 14 | NesContainers 15 | Alexey Cluster 16 | https://github.com/ClusterM/nes-containers 17 | Alexey Cluster, 2023 18 | A simple .NET Standard 2.0 library for reading and modifying NES/Famicom ROM containers: .nes (iNES, NES 2.0), .unf (UNIF), and .fds (Famicom Disk System images). 19 | 1.1.9 20 | https://github.com/ClusterM/nes-containers 21 | git 22 | NES;Famicom;FamicomDiskSystem 23 | 1.1.9 24 | 1.1.9 25 | Alexey Cluster 26 | 27 | 28 | 29 | none 30 | false 31 | 32 | 33 | 34 | 35 | True 36 | \ 37 | 38 | 39 | True 40 | \ 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /NesFile.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Security.Cryptography; 6 | 7 | namespace com.clusterrr.Famicom.Containers 8 | { 9 | /// 10 | /// iNES / NES 2.0 file container for NES/Famicom games 11 | /// 12 | public partial class NesFile 13 | { 14 | private byte[] prg = Array.Empty(); 15 | private byte[] chr = Array.Empty(); 16 | private byte[] trainer = Array.Empty(); 17 | private byte[] miscellaneousROM = Array.Empty(); 18 | /// 19 | /// PRG data 20 | /// 21 | public byte[] PRG 22 | { 23 | get => prg; 24 | set => prg = (value ?? Array.Empty()).ToArray(); 25 | } 26 | /// 27 | /// CHR data 28 | /// 29 | public byte[] CHR 30 | { 31 | get => chr; 32 | set => chr = (value ?? Array.Empty()).ToArray(); 33 | } 34 | /// 35 | /// Trainer 36 | /// 37 | public byte[] Trainer 38 | { 39 | get => trainer; 40 | set 41 | { 42 | if (value != null && value.Count() != 0 && value.Count() > 512) 43 | throw new ArgumentOutOfRangeException("Trainer size must be 512 bytes or less"); 44 | chr = value ?? Array.Empty(); 45 | } 46 | } 47 | /// 48 | /// Miscellaneous ROM (NES 2.0 only) 49 | /// 50 | public byte[] MiscellaneousROM 51 | { 52 | get => miscellaneousROM; 53 | set => miscellaneousROM = value ?? Array.Empty(); 54 | } 55 | /// 56 | /// Mapper number 57 | /// 58 | public ushort Mapper { get; set; } = 0; 59 | /// 60 | /// Submapper number (NES 2.0 only) 61 | /// 62 | public byte Submapper { get; set; } = 0; 63 | /// 64 | /// Battery-backed (or other non-volatile memory) memory is present 65 | /// 66 | public bool Battery { get; set; } = false; 67 | private iNesVersion version = NesFile.iNesVersion.iNES; 68 | /// 69 | /// Version of .nes file format: iNES or NES 2.0 70 | /// 71 | public iNesVersion Version 72 | { 73 | get => version; 74 | set 75 | { 76 | if (value != iNesVersion.iNES && value != iNesVersion.NES20) 77 | throw new ArgumentException("Only version 1 and 2 allowed", nameof(Version)); 78 | version = value; 79 | } 80 | } 81 | private byte prgRamSize = 0; 82 | /// 83 | /// PRG RAM Size (NES 2.0 only) 84 | /// 85 | public uint PrgRamSize 86 | { 87 | get => prgRamSize > 0 ? (uint)(64 << prgRamSize) : 0; 88 | set 89 | { 90 | byte newValue = (byte)(value > 0 ? Math.Max(1, (int)Math.Ceiling(Math.Log(value, 2)) - 6) : 0); 91 | if (value != (newValue > 0 ? (uint)(64 << newValue) : 0)) 92 | throw new InvalidDataException("Invalid PRG RAM size value, must be power of 2"); 93 | prgRamSize = newValue; 94 | } 95 | } 96 | private byte prgNvRamSize = 0; 97 | /// 98 | /// PRG NVRAM Size (NES 2.0 only) 99 | /// 100 | public uint PrgNvRamSize 101 | { 102 | get => prgNvRamSize > 0 ? (uint)(64 << prgNvRamSize) : 0; 103 | set 104 | { 105 | byte newValue = (byte)(value > 0 ? Math.Max(1, (int)Math.Ceiling(Math.Log(value, 2)) - 6) : 0); 106 | if (value != (newValue > 0 ? (uint)(64 << newValue) : 0)) 107 | throw new InvalidDataException("Invalid PRG NVRAM size value, must be power of 2"); 108 | prgNvRamSize = newValue; 109 | } 110 | } 111 | private byte chrRamSize = 0; 112 | /// 113 | /// CHR RAM Size (NES 2.0 only) 114 | /// 115 | public uint ChrRamSize 116 | { 117 | get => chrRamSize > 0 ? (uint)(64 << chrRamSize) : 0; 118 | set 119 | { 120 | byte newValue = (byte)(value > 0 ? Math.Max(1, (int)Math.Ceiling(Math.Log(value, 2)) - 6) : 0); 121 | if (value != (newValue > 0 ? (uint)(64 << newValue) : 0)) 122 | throw new InvalidDataException("Invalid CHR RAM size value, must be power of 2"); 123 | chrRamSize = newValue; 124 | } 125 | } 126 | private byte chrNvRamSize = 0; 127 | /// 128 | /// CHR NVRAM Size (NES 2.0 only) 129 | /// 130 | public uint ChrNvRamSize 131 | { 132 | get => chrNvRamSize > 0 ? (uint)(64 << chrNvRamSize) : 0; 133 | set 134 | { 135 | byte newValue = (byte)(value > 0 ? Math.Max(1, (int)Math.Ceiling(Math.Log(value, 2)) - 6) : 0); 136 | if (value != (newValue > 0 ? (uint)(64 << newValue) : 0)) 137 | throw new InvalidDataException("Invalid CHR NVRAM size value, must be power of 2"); 138 | chrNvRamSize = newValue; 139 | } 140 | } 141 | /// 142 | /// Mirroring type 143 | /// 144 | public MirroringType Mirroring { get; set; } = MirroringType.Horizontal; 145 | /// 146 | /// For non-homebrew NES/Famicom games, this field's value is always a function of the region in which a game was released (NES 2.0 only) 147 | /// 148 | public Timing Region { get; set; } = Timing.Ntsc; 149 | /// 150 | /// Console type (NES 2.0 only) 151 | /// 152 | public ConsoleType Console { get; set; } = ConsoleType.Normal; 153 | /// 154 | /// Vs. System PPU type (used when Console is ConsoleType.VsSystem) 155 | /// 156 | public VsPpuType VsPpu { get; set; } = VsPpuType.RP2C03B; 157 | /// 158 | /// Vs. System hardware type (used when Console is ConsoleType.VsSystem) 159 | /// 160 | public VsHardwareType VsHardware { get; set; } = VsHardwareType.VsUnisystemNormal; 161 | /// 162 | /// Extended console type (used when Console is ConsoleType.Extended) 163 | /// 164 | public ExtendedConsoleType ExtendedConsole { get; set; } = ExtendedConsoleType.RegularNES; 165 | /// 166 | /// Default expansion device (NES 2.0 only) 167 | /// 168 | public ExpansionDevice DefaultExpansionDevice { get; set; } = ExpansionDevice.Unspecified; 169 | /// 170 | /// Miscellaneous ROMs сount (NES 2.0 only) 171 | /// 172 | public byte MiscellaneousROMsCount { get; set; } = 0; 173 | 174 | /// 175 | /// Version of iNES format 176 | /// 177 | public enum iNesVersion 178 | { 179 | /// 180 | /// Classic iNES format 181 | /// 182 | iNES = 1, 183 | /// 184 | /// NES 2.0 format 185 | /// 186 | NES20 = 2 187 | } 188 | 189 | /// 190 | /// Console type 191 | /// 192 | public enum ConsoleType 193 | { 194 | /// 195 | /// Nintendo Entertainment System/Family Computer 196 | /// 197 | Normal = 0, 198 | /// 199 | /// Nintendo Vs. System 200 | /// 201 | VsSystem = 1, 202 | /// 203 | /// Nintendo Playchoice 10 204 | /// 205 | Playchoice10 = 2, 206 | /// 207 | /// Extended Console Type 208 | /// 209 | Extended = 3 210 | } 211 | 212 | /// 213 | /// Vs. System PPU type 214 | /// 215 | public enum VsPpuType 216 | { 217 | /// 218 | /// RP2C03B 219 | /// 220 | RP2C03B = 0x00, 221 | /// 222 | /// RP2C03G 223 | /// 224 | RP2C03G = 0x01, 225 | /// 226 | /// RP2C04-0001 227 | /// 228 | RP2C04_0001 = 0x02, 229 | /// 230 | /// RP2C04-0002 231 | /// 232 | RP2C04_0002 = 0x03, 233 | /// 234 | /// RP2C04-0003 235 | /// 236 | RP2C04_0003 = 0x04, 237 | /// 238 | /// RP2C04-0004 239 | /// 240 | RP2C04_0004 = 0x05, 241 | /// 242 | /// RC2C03B 243 | /// 244 | RC2C03B = 0x06, 245 | /// 246 | /// RC2C03C 247 | /// 248 | RC2C03C = 0x07, 249 | /// 250 | /// RC2C05-01 ($2002 AND $?? =$1B) 251 | /// 252 | RC2C05_01 = 0x08, 253 | /// 254 | /// RC2C05-02 ($2002 AND $3F =$3D) 255 | /// 256 | RC2C05_02 = 0x09, 257 | /// 258 | /// RC2C05-03 ($2002 AND $1F =$1C) 259 | /// 260 | RC2C05_03 = 0x0A, 261 | /// 262 | /// RC2C05-04 ($2002 AND $1F =$1B) 263 | /// 264 | RC2C05_04 = 0x0B, 265 | /// 266 | /// RC2C05-05 ($2002 AND $1F =unknown) 267 | /// 268 | RC2C05_05 = 0x0C 269 | }; 270 | 271 | /// 272 | /// Vs. System hardware type 273 | /// 274 | public enum VsHardwareType 275 | { 276 | /// 277 | /// Vs. Unisystem (normal) 278 | /// 279 | VsUnisystemNormal = 0x00, 280 | /// 281 | /// Vs. Unisystem (RBI Baseball protection) 282 | /// 283 | VsUnisystemRBIBaseballProtection = 0x01, 284 | /// 285 | /// Vs. Unisystem (TKO Boxing protection) 286 | /// 287 | VsUnisystemTKOBoxingProtection = 0x02, 288 | /// 289 | /// Vs. Unisystem (Super Xevious protection) 290 | /// 291 | VsUnisystemSuperXeviousProtection = 0x03, 292 | /// 293 | /// Vs. Unisystem (Vs. Ice Climber Japan protection) 294 | /// 295 | VsUnisystemVsIceClimberJapanProtection = 0x04, 296 | /// 297 | /// Vs. Dual System (normal) 298 | /// 299 | VsDualSystemNormal = 0x05, 300 | /// 301 | /// Vs. Dual System (Raid on Bungeling Bay protection) 302 | /// 303 | VsDualSystemRaidOnBungelingBayProtection = 0x06 304 | } 305 | 306 | /// 307 | /// Extended console type 308 | /// 309 | public enum ExtendedConsoleType 310 | { 311 | /// 312 | /// Regular NES/Famicom/Dendy 313 | /// 314 | RegularNES = 0x00, 315 | /// 316 | /// Nintendo Vs. System 317 | /// 318 | NintendoVsSystem = 0x01, 319 | /// 320 | /// Playchoice 10 321 | /// 322 | Playchoice10 = 0x02, 323 | /// 324 | /// Regular Famiclone, but with CPU that supports Decimal Mode (e.g. Bit Corporation Creator) 325 | /// 326 | FamicloneWithDecimalMode = 0x03, 327 | /// 328 | /// V.R. Technology VT01 with monochrome palette 329 | /// 330 | VRTechnologyVT01Monochrome = 0x04, 331 | /// 332 | /// V.R. Technology VT01 with red/cyan STN palette 333 | /// 334 | VRTechnologyVT01WithRedCyanSTNPalette = 0x05, 335 | /// 336 | /// V.R. Technology VT02 337 | /// 338 | VRTechnologyVT02 = 0x06, 339 | /// 340 | /// V.R. Technology VT03 341 | /// 342 | VRTechnologyVT03 = 0x07, 343 | /// 344 | /// V.R. Technology VT09 345 | /// 346 | VRTechnologyVT09 = 0x08, 347 | /// 348 | /// V.R. Technology VT32 349 | /// 350 | VRTechnologyVT32 = 0x09, 351 | /// 352 | /// V.R. Technology VT369 353 | /// 354 | VRTechnologyVT369 = 0x0A, 355 | /// 356 | /// UMC UM6578 357 | /// 358 | UMC_UM6578 = 0x0B 359 | } 360 | 361 | /// 362 | /// Type of expansion device connected to console, source: https://www.nesdev.org/wiki/NES_2.0#Default_Expansion_Device 363 | /// 364 | public enum ExpansionDevice 365 | { 366 | /// 367 | /// Expansion device is not specified 368 | /// 369 | Unspecified = 0x00, 370 | /// 371 | /// Standard NES/Famicom controllers 372 | /// 373 | Standard = 0x01, 374 | /// 375 | /// NES Four Score/Satellite with two additional standard controllers 376 | /// 377 | NesFourScore = 0x02, 378 | /// 379 | /// Famicom Four Players Adapter with two additional standard controllers 380 | /// 381 | FamicomFourPlayersAdapter = 0x03, 382 | /// 383 | /// Vs. System 384 | /// 385 | VsSystem = 0x04, 386 | /// 387 | /// Vs. System with reversed inputs 388 | /// 389 | VsSystemWithReversedInputs = 0x05, 390 | /// 391 | /// Vs. Pinball (Japan) 392 | /// 393 | VsPinball = 0x06, 394 | /// 395 | /// Vs. Zapper 396 | /// 397 | VsZapper = 0x07, 398 | /// 399 | /// Zapper ($4017) 400 | /// 401 | Zapper = 0x08, 402 | /// 403 | /// Two Zappers 404 | /// 405 | TwoZappers = 0x09, 406 | /// 407 | /// Bandai Hyper Shot Lightgun 408 | /// 409 | BandaiHyperShotLightgun = 0x0A, 410 | /// 411 | /// Power Pad Side A 412 | /// 413 | PowerPadSideA = 0x0B, 414 | /// 415 | /// Power Pad Side B 416 | /// 417 | PowerPadSideB = 0x0C, 418 | /// 419 | /// Family Trainer Side A 420 | /// 421 | FamilyTrainerSideA = 0x0D, 422 | /// 423 | /// Family Trainer Side B 424 | /// 425 | FamilyTrainerSideB = 0x0E, 426 | /// 427 | /// Arkanoid Vaus Controller (NES) 428 | /// 429 | ArkanoidVausControllerNES = 0x0F, 430 | /// 431 | /// Arkanoid Vaus Controller (Famicom) 432 | /// 433 | ArkanoidVausControllerFamicom = 0x10, 434 | /// 435 | /// Two Vaus Controllers plus Famicom Data Recorder 436 | /// 437 | TwoVausControllersPlusFamicomDataRecorder = 0x11, 438 | /// 439 | /// Konami Hyper Shot Controller 440 | /// 441 | KonamiHyperShotController = 0x12, 442 | /// 443 | /// Coconuts Pachinko Controller 444 | /// 445 | CoconutsPachinkoController = 0x13, 446 | /// 447 | /// Exciting Boxing Punching Bag (Blowup Doll) 448 | /// 449 | ExcitingBoxingPunchingBag = 0x14, 450 | /// 451 | /// Jissen Mahjong Controller 452 | /// 453 | JissenMahjongController = 0x15, 454 | /// 455 | /// Party Tap 456 | /// 457 | PartyTap = 0x16, 458 | /// 459 | /// Oeka Kids Tablet 460 | /// 461 | OekaKidsTablet = 0x17, 462 | /// 463 | /// Sunsoft Barcode Battler 464 | /// 465 | SunsoftBarcodeBattler = 0x18, 466 | /// 467 | /// Miracle Piano Keyboard 468 | /// 469 | MiraclePianoKeyboard = 0x19, 470 | /// 471 | /// Pokkun Moguraa (Whack-a-Mole Mat and Mallet) 472 | /// 473 | PokkunMoguraa = 0x1A, 474 | /// 475 | /// Top Rider(Inflatable Bicycle) 476 | /// 477 | TopRider = 0x1B, 478 | /// 479 | /// Double-Fisted (Requires or allows use of two controllers by one player) 480 | /// 481 | DoubleFisted = 0x1C, 482 | /// 483 | /// Famicom 3D System 484 | /// 485 | Famicom3DSystem = 0x1D, 486 | /// 487 | /// Doremikko Keyboard 488 | /// 489 | DoremikkoKeyboard = 0x1E, 490 | /// 491 | /// R.O.B. Gyro Set 492 | /// 493 | RobGyroSet = 0x1F, 494 | /// 495 | /// Famicom Data Recorder (don't emulate keyboard) 496 | /// 497 | FamicomDataRecorder = 0x20, 498 | /// 499 | /// ASCII Turbo File 500 | /// 501 | ASCIITurboFile = 0x21, 502 | /// 503 | /// IGS Storage Battle Box 504 | /// 505 | IGSStorageBattleBox = 0x22, 506 | /// 507 | /// Family BASIC Keyboard plus Famicom Data Recorder 508 | /// 509 | FamilyBasicKeyboardPlusFamicomDataRecorder = 0x23, 510 | /// 511 | /// Dongda PEC-586 Keyboard 512 | /// 513 | DongdaPEC586Keyboard = 0x24, 514 | /// 515 | /// Bit Corp. Bit-79 Keyboard 516 | /// 517 | BitCorpBit79Keyboard = 0x25, 518 | /// 519 | /// Subor Keyboard 520 | /// 521 | SuborKeyboard = 0x26, 522 | /// 523 | /// Subor Keyboard plus mouse (3x8-bit protocol) 524 | /// 525 | SuborKeyboardPlusMouse3x8 = 0x27, 526 | /// 527 | /// Subor Keyboard plus mouse (24-bit protocol) 528 | /// 529 | SuborKeyboardPlusMouse24 = 0x28, 530 | /// 531 | /// SNES Mouse ($4017.d0) 532 | /// 533 | SnesMouse4017 = 0x29, 534 | /// 535 | /// Multicart 536 | /// 537 | Multicart = 0x2A, 538 | /// 539 | /// Two SNES controllers replacing the two standard NES controllers 540 | /// 541 | TwoSnesControllers = 0x2B, 542 | /// 543 | /// RacerMate Bicycle 544 | /// 545 | RacerMateBicycle = 0x2C, 546 | /// 547 | /// U-Force 548 | /// 549 | UForce = 0x2D, 550 | /// 551 | /// R.O.B. Stack-Up 552 | /// 553 | RobStackUp = 0x2E, 554 | /// 555 | /// City Patrolman Lightgun 556 | /// 557 | CityPatrolmanLightgun = 0x2F, 558 | /// 559 | /// Sharp C1 Cassette Interface 560 | /// 561 | SharpC1CassetteInterface = 0x30, 562 | /// 563 | /// Standard Controller with swapped Left-Right/Up-Down/B-A 564 | /// 565 | StandardControllerWithSwapped = 0x31, 566 | /// 567 | /// Excalibor Sudoku Pad 568 | /// 569 | ExcaliborSudokuPad = 0x32, 570 | /// 571 | /// ABL Pinball 572 | /// 573 | AblPinball = 0x33, 574 | /// 575 | /// Golden Nugget Casino extra buttons 576 | /// 577 | GoldenNuggetCasinoExtraButtons = 0x34, 578 | } 579 | 580 | /// 581 | /// Constructor to create empty NesFile object 582 | /// 583 | public NesFile() 584 | { 585 | } 586 | 587 | /// 588 | /// Create NesFile object from raw .nes file contents 589 | /// 590 | /// Raw .nes file data 591 | public NesFile(byte[] data) 592 | { 593 | var header = new byte[16]; 594 | Array.Copy(data, header, header.Length); 595 | if (header[0] != 'N' || 596 | header[1] != 'E' || 597 | header[2] != 'S' || 598 | header[3] != 0x1A) throw new InvalidDataException("Invalid iNES header"); 599 | 600 | if ((header[7] & 0x0C) == 0x08) 601 | Version = iNesVersion.NES20; 602 | else if (!(header[12] == 0 && header[13] == 0 && header[14] == 0 && header[15] == 0)) 603 | { 604 | // archaic iNES 605 | header[7] = header[8] = header[9] = header[10] = header[11] = header[12] = header[13] = header[14] = header[15] = 0; 606 | } 607 | 608 | uint prgSize = 0; 609 | uint chrSize = 0; 610 | Mirroring = (MirroringType)(header[6] & 1); 611 | Battery = (header[6] & (1 << 1)) != 0; 612 | if ((header[6] & (1 << 2)) != 0) 613 | trainer = new byte[512]; 614 | else 615 | trainer = Array.Empty(); 616 | if ((header[6] & (1 << 3)) != 0) 617 | Mirroring = MirroringType.FourScreenVram; 618 | if (Version == iNesVersion.iNES) 619 | { 620 | prgSize = (uint)(header[4] * 0x4000); 621 | chrSize = (uint)(header[5] * 0x2000); 622 | Mapper = (byte)((header[6] >> 4) | (header[7] & 0xF0)); 623 | Console = (ConsoleType)(header[7] & 3); 624 | //PrgRamSize = (uint)(header[8] == 0 ? 0x2000 : header[8] * 0x2000); 625 | } 626 | else if (Version == iNesVersion.NES20) // NES 2.0 627 | { 628 | if ((header[9] & 0x0F) != 0x0F) 629 | prgSize = (uint)((((header[9] & 0x0F) << 8) | header[4]) * 0x4000); 630 | else 631 | prgSize = (uint)((1 << (header[4] >> 2)) * ((header[4] & 3) * 2 + 1)); // omg 632 | if ((header[9] & 0xF0) != 0xF0) 633 | chrSize = (uint)((((header[9] & 0xF0) << 4) | header[5]) * 0x2000); 634 | else 635 | chrSize = (uint)((1 << (header[5] >> 2)) * ((header[5] & 3) * 2 + 1)); 636 | Mapper = (ushort)((header[6] >> 4) | (header[7] & 0xF0) | ((header[8] & 0x0F) << 8)); 637 | Submapper = (byte)(header[8] >> 4); 638 | Console = (ConsoleType)(header[7] & 3); 639 | prgRamSize = (byte)(header[10] & 0x0F); 640 | prgNvRamSize = (byte)((header[10] & 0xF0) >> 4); 641 | chrRamSize = (byte)(header[11] & 0x0F); 642 | chrNvRamSize = (byte)((header[11] & 0xF0) >> 4); 643 | Region = (Timing)header[12]; 644 | switch (Console) 645 | { 646 | case ConsoleType.VsSystem: 647 | VsPpu = (VsPpuType)(header[13] & 0x0F); 648 | VsHardware = (VsHardwareType)(header[13] >> 4); 649 | break; 650 | case ConsoleType.Extended: 651 | ExtendedConsole = (ExtendedConsoleType)(header[13] & 0x0F); 652 | break; 653 | } 654 | MiscellaneousROMsCount = (byte)(header[14] & 3); 655 | DefaultExpansionDevice = (ExpansionDevice)(header[15] & 0x3F); 656 | } 657 | 658 | uint offset = (uint)header.Length; 659 | if (trainer.Length > 0) 660 | { 661 | if (offset < data.Length) 662 | Array.Copy(data, offset, trainer, 0, Math.Max(0, Math.Min(trainer.Length, data.Length - offset))); 663 | offset += (uint)trainer.Length; 664 | } 665 | 666 | prg = new byte[prgSize]; 667 | if (offset < data.Length) 668 | Array.Copy(data, offset, prg, 0, Math.Max(0, Math.Min(prgSize, data.Length - offset))); // Ignore end for some bad ROMs 669 | offset += prgSize; 670 | 671 | chr = new byte[chrSize]; 672 | if (offset < data.Length) 673 | Array.Copy(data, offset, chr, 0, Math.Max(0, Math.Min(chrSize, data.Length - offset))); 674 | offset += chrSize; 675 | 676 | if (MiscellaneousROMsCount > 0) 677 | { 678 | MiscellaneousROM = new byte[data.Length - offset]; 679 | Array.Copy(data, offset, miscellaneousROM, 0, miscellaneousROM.Length); 680 | } 681 | else 682 | { 683 | MiscellaneousROM = Array.Empty(); 684 | } 685 | } 686 | 687 | /// 688 | /// Create NesFile object from the specified .nes file 689 | /// 690 | /// Path to the .nes file 691 | public NesFile(string fileName) 692 | : this(File.ReadAllBytes(fileName)) 693 | { 694 | } 695 | 696 | /// 697 | /// Create NesFile object from raw .nes file contents 698 | /// 699 | /// Raw ROM data 700 | /// NesFile object 701 | public static NesFile FromBytes(byte[] data) => new NesFile(data); 702 | 703 | /// 704 | /// Create NesFile object from the specified .nes file 705 | /// 706 | /// Path to the .nes file 707 | /// NesFile object 708 | public static NesFile FromFile(string filename) => new NesFile(filename); 709 | 710 | /// 711 | /// Returns .nes file contents (header + PRG + CHR) 712 | /// 713 | /// .nes file contents 714 | public byte[] ToBytes() 715 | { 716 | var data = new List(); 717 | var header = new byte[16]; 718 | header[0] = (byte)'N'; 719 | header[1] = (byte)'E'; 720 | header[2] = (byte)'S'; 721 | header[3] = 0x1A; 722 | ulong prgSizePadded, chrSizePadded; 723 | if (Version == iNesVersion.iNES) 724 | { 725 | if (Console == ConsoleType.Extended) 726 | throw new InvalidDataException("Extended console type is supported by NES 2.0 only"); 727 | if (Mapper > 255) 728 | throw new InvalidDataException("Mapper number > 255 is supported by NES 2.0 only"); 729 | if (Submapper != 0) 730 | throw new InvalidDataException("Submapper number is supported by NES 2.0 only"); 731 | if (prgRamSize > 0) 732 | throw new InvalidDataException("PRG RAM size is supported by NES 2.0 only"); 733 | if (prgNvRamSize > 0) 734 | throw new InvalidDataException("PRG NVRAM size is supported by NES 2.0 only"); 735 | if (chrRamSize > 0) 736 | throw new InvalidDataException("CHR RAM size is supported by NES 2.0 only"); 737 | if (chrNvRamSize > 0) 738 | throw new InvalidDataException("CHR NVRAM size is supported by NES 2.0 only"); 739 | var length16k = prg.Length / 0x4000; 740 | if (length16k > 0xFF) throw new ArgumentOutOfRangeException("PRG size is too big for iNES, use NES 2.0 instead"); 741 | header[4] = (byte)Math.Ceiling((double)prg.Length / 0x4000); 742 | prgSizePadded = header[4] * 0x4000UL; 743 | var length8k = chr.Length / 0x2000; 744 | if (length8k > 0xFF) throw new ArgumentOutOfRangeException("CHR size is too big for iNES, use NES 2.0 instead"); 745 | header[5] = (byte)Math.Ceiling((double)chr.Length / 0x2000); 746 | chrSizePadded = header[5] * 0x2000UL; 747 | switch (Mirroring) 748 | { 749 | case MirroringType.Unknown: // mirroring field ignored 750 | case MirroringType.Horizontal: 751 | case MirroringType.Vertical: 752 | case MirroringType.FourScreenVram: 753 | case MirroringType.MapperControlled: // mirroring field ignored 754 | break; 755 | default: 756 | throw new InvalidDataException($"{Mirroring} mirroring is not supported by iNES"); 757 | } 758 | // Hard-wired nametable mirroring type 759 | if (Mirroring == MirroringType.Vertical) 760 | header[6] |= 1; 761 | // "Battery" and other non-volatile memory 762 | if (Battery) 763 | header[6] |= (1 << 1); 764 | // 512-byte Trainer 765 | if (trainer.Length > 0) 766 | header[6] |= (1 << 2); 767 | // Hard-wired four-screen mode 768 | if (Mirroring == MirroringType.FourScreenVram) 769 | header[6] |= (1 << 3); 770 | // Mapper Number D0..D3 771 | header[6] |= (byte)(Mapper << 4); 772 | // Console type 773 | header[7] |= (byte)((byte)Console & 3); 774 | // Mapper Number D4..D7 775 | header[7] |= (byte)(Mapper & 0xF0); 776 | 777 | data.AddRange(header); 778 | if (trainer.Length > 0) 779 | { 780 | data.AddRange(trainer); 781 | if (trainer.Length < 512) data.AddRange(Enumerable.Repeat(0xFF, (int)512 - trainer.Length)); 782 | } 783 | data.AddRange(prg); 784 | data.AddRange(Enumerable.Repeat(byte.MaxValue, (int)prgSizePadded - prg.Length)); 785 | data.AddRange(chr); 786 | data.AddRange(Enumerable.Repeat(byte.MaxValue, (int)chrSizePadded - chr.Length)); 787 | } 788 | else if (Version == iNesVersion.NES20) 789 | { 790 | var length16k = (uint)Math.Ceiling((double)prg.Length / 0x4000); 791 | if (length16k <= 0xEFF) 792 | { 793 | header[4] = (byte)(length16k & 0xFF); 794 | header[9] |= (byte)(length16k >> 8); 795 | prgSizePadded = length16k * 0x4000; 796 | } 797 | else 798 | { 799 | byte exponent, multiplier; 800 | (exponent, multiplier, prgSizePadded) = SizeToExponent((ulong)prg.Length); 801 | header[4] = (byte)((exponent << 2) | (multiplier & 3)); 802 | header[9] |= 0x0F; 803 | } 804 | var length8k = (uint)Math.Ceiling((double)chr.Length / 0x2000); 805 | if (length8k <= 0xEFF) 806 | { 807 | header[5] = (byte)(length8k & 0xFF); 808 | header[9] |= (byte)((length8k >> 4) & 0xF0); 809 | chrSizePadded = length8k * 0x2000; 810 | } 811 | else 812 | { 813 | byte exponent, multiplier; 814 | (exponent, multiplier, chrSizePadded) = SizeToExponent((ulong)chr.Length); 815 | header[5] = (byte)((exponent << 2) | (multiplier & 3)); 816 | header[9] |= 0xF0; 817 | } 818 | // Hard-wired nametable mirroring type 819 | if (Mirroring == MirroringType.Vertical) 820 | header[6] |= 1; 821 | // "Battery" and other non-volatile memory 822 | if (Battery) 823 | header[6] |= (1 << 1); 824 | // 512-byte Trainer 825 | if (trainer.Length > 0) 826 | header[6] |= (1 << 2); 827 | // Hard-wired four-screen mode 828 | if (Mirroring == MirroringType.FourScreenVram) 829 | header[6] |= (1 << 3); 830 | // Mapper Number D0..D3 831 | header[6] |= (byte)(Mapper << 4); 832 | // Console type 833 | header[7] |= (byte)((byte)Console & 3); 834 | // NES 2.0 identifier 835 | header[7] |= 1 << 3; 836 | // Mapper Number D4..D7 837 | header[7] |= (byte)(Mapper & 0xF0); 838 | // Mapper number D8..D11 839 | header[8] |= (byte)((Mapper >> 8) & 0x0F); 840 | // Submapper 841 | header[8] |= (byte)(Submapper << 4); 842 | // Check battery value 843 | if ((prgNvRamSize > 0 || chrNvRamSize > 0) && !Battery) 844 | throw new InvalidDataException("Battery flag must be set when PRG NVRAM size or CHR NVRAM size is non-zero"); 845 | // PRG RAM (volatile) shift count 846 | header[10] |= (byte)(prgRamSize & 0x0F); 847 | // PRG-NVRAM/EEPROM (non-volatile) shift count 848 | header[10] |= (byte)((prgNvRamSize << 4) & 0xF0); 849 | // CHR-RAM size (volatile) shift count 850 | header[11] |= (byte)(chrRamSize & 0x0F); 851 | // CHR-NVRAM size (non-volatile) shift count 852 | header[11] |= (byte)((chrNvRamSize << 4) & 0xF0); 853 | // CPU/PPU timing mode 854 | header[12] |= (byte)((byte)Region & 3); 855 | switch (Console) 856 | { 857 | // When Byte 7 AND 3 =1: Vs. System Type 858 | case ConsoleType.VsSystem: 859 | // Vs. PPU Type 860 | header[13] |= (byte)((byte)VsPpu & 0x0F); 861 | // Vs. Hardware Type 862 | header[13] |= (byte)(((byte)VsHardware << 4) & 0xF0); 863 | break; 864 | // When Byte 7 AND 3 =3: Extended Console Type 865 | case ConsoleType.Extended: 866 | // Extended Console Type 867 | header[13] = (byte)ExtendedConsole; 868 | break; 869 | } 870 | // Miscellaneous ROMs 871 | header[14] |= (byte)(MiscellaneousROMsCount & 3); 872 | // Default Expansion Device 873 | header[15] |= (byte)((byte)DefaultExpansionDevice & 0x3F); 874 | 875 | data.AddRange(header); 876 | if (trainer.Length > 0) 877 | { 878 | data.AddRange(trainer); 879 | if (trainer.Length < 512) data.AddRange(Enumerable.Repeat(byte.MaxValue, (int)512 - trainer.Length)); 880 | } 881 | data.AddRange(prg); 882 | data.AddRange(Enumerable.Repeat(byte.MaxValue, (int)prgSizePadded - prg.Length)); 883 | data.AddRange(chr); 884 | data.AddRange(Enumerable.Repeat(byte.MaxValue, (int)chrSizePadded - chr.Length)); 885 | if (MiscellaneousROMsCount > 0 || miscellaneousROM.Length > 0) 886 | { 887 | if (MiscellaneousROMsCount == 0) 888 | throw new InvalidDataException("MiscellaneousROMsCount is zero while MiscellaneousROM is not empty"); 889 | if (MiscellaneousROM.Length == 0) 890 | throw new InvalidDataException("MiscellaneousROM is empty while MiscellaneousROMsCount is not zero"); 891 | data.AddRange(miscellaneousROM); 892 | } 893 | } 894 | return data.ToArray(); 895 | } 896 | 897 | /// 898 | /// Save as .nes file 899 | /// 900 | /// Target filename 901 | public void Save(string filename) => File.WriteAllBytes(filename, ToBytes()); 902 | 903 | private static ulong ExponentToSize(byte exponent, byte multiplier) 904 | => (1UL << exponent) * (ulong)(multiplier * 2 + 1); 905 | 906 | private static (byte Exponent, byte Multiplier, ulong Padded) SizeToExponent(ulong value) 907 | { 908 | if (value == 0) return (0, 0, 1); 909 | if (value < 8) 910 | { 911 | var r = SizeToExponent(value << 3); 912 | return ((byte)(r.Exponent - 3), r.Multiplier, r.Padded >> 3); 913 | } 914 | 915 | // Calculate bits required to store number 916 | byte bitsize = 0; 917 | while (value >> bitsize > 0) bitsize++; 918 | 919 | // Split it into two parts 920 | var major = value >> (bitsize - 3); 921 | var minor = value & (ulong)~(0b111 << (bitsize - 3)); 922 | 923 | // Round up 924 | if (minor != 0) major++; 925 | 926 | byte e, m; 927 | switch (major) 928 | { 929 | case 0b100: 930 | e = (byte)(bitsize - 1); 931 | m = 0; // 0*2+1=1 932 | break; 933 | case 0b101: 934 | e = (byte)(bitsize - 3); 935 | m = 2; // 2*2+1=5 936 | break; 937 | case 0b110: 938 | e = (byte)(bitsize - 2); 939 | m = 1; // 1*2+1=3 940 | break; 941 | case 0b111: 942 | e = (byte)(bitsize - 3); 943 | m = 3; // 3*2+1=7 944 | break; 945 | case 0b1000: 946 | e = (byte)bitsize; 947 | m = 0; // 0*2+1=1 948 | break; 949 | default: 950 | throw new InvalidProgramException(); 951 | } 952 | 953 | return (e, m, ExponentToSize(e, m)); 954 | } 955 | 956 | /// 957 | /// Calculate MD5 checksum of ROM (CHR+PRG without header) 958 | /// 959 | /// MD5 checksum for all PRG and CHR data 960 | public byte[] CalculateMD5() 961 | { 962 | int prgSizeUpPow2 = 1; 963 | int chrSizeUpPow2 = 1; 964 | if (PRG.Length == 0) 965 | prgSizeUpPow2 = 0; // Is it possible? 966 | else 967 | while (prgSizeUpPow2 < PRG.Length) prgSizeUpPow2 <<= 1; 968 | if (CHR.Length == 0) 969 | chrSizeUpPow2 = 0; 970 | else 971 | while (chrSizeUpPow2 < CHR.Length) chrSizeUpPow2 <<= 1; 972 | using (var md5 = MD5.Create()) 973 | { 974 | md5.TransformBlock(prg, 0, prg.Length, null, 0); 975 | md5.TransformBlock(Enumerable.Repeat(byte.MaxValue, prgSizeUpPow2 - prg.Length).ToArray(), 0, prgSizeUpPow2 - prg.Length, null, 0); 976 | md5.TransformBlock(chr, 0, chr.Length, null, 0); 977 | md5.TransformBlock(Enumerable.Repeat(byte.MaxValue, chrSizeUpPow2 - chr.Length).ToArray(), 0, chrSizeUpPow2 - chr.Length, null, 0); 978 | md5.TransformFinalBlock(new byte[0], 0, 0); 979 | return md5.Hash; 980 | } 981 | } 982 | 983 | /// 984 | /// Calculate CRC32 checksum of ROM (CHR+PRG without header) 985 | /// 986 | /// CRC32 checksum for all PRG and CHR data 987 | public uint CalculateCRC32() 988 | { 989 | int prgSizeUpPow2 = 1; 990 | int chrSizeUpPow2 = 1; 991 | if (PRG.Length == 0) 992 | prgSizeUpPow2 = 0; // Is it possible? 993 | else 994 | while (prgSizeUpPow2 < PRG.Length) prgSizeUpPow2 <<= 1; 995 | if (CHR.Length == 0) 996 | chrSizeUpPow2 = 0; 997 | else 998 | while (chrSizeUpPow2 < CHR.Length) chrSizeUpPow2 <<= 1; 999 | using (var crc32 = new Crc32()) 1000 | { 1001 | crc32.TransformBlock(prg, 0, prg.Length, null, 0); 1002 | crc32.TransformBlock(Enumerable.Repeat(byte.MaxValue, prgSizeUpPow2 - prg.Length).ToArray(), 0, prgSizeUpPow2 - prg.Length, null, 0); 1003 | crc32.TransformBlock(chr, 0, chr.Length, null, 0); 1004 | crc32.TransformBlock(Enumerable.Repeat(byte.MaxValue, chrSizeUpPow2 - chr.Length).ToArray(), 0, chrSizeUpPow2 - chr.Length, null, 0); 1005 | crc32.TransformFinalBlock(new byte[0], 0, 0); 1006 | return BitConverter.ToUInt32(crc32.Hash.Reverse().ToArray(), 0); 1007 | } 1008 | } 1009 | } 1010 | } 1011 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NesContainers 2 | A simple .NET Standard 2.0 library for reading and modifying NES/Famicom ROM containers: .nes (iNES, NES 2.0), .unf (UNIF), and .fds (Famicom Disk System images). 3 | 4 | Full documentation: https://clusterm.github.io/nes-containers/ 5 | 6 | ## Usage 7 | 8 | There are three classes for different type of containers. 9 | 10 | ### .nes (iNES, NES 2.0) 11 | 12 | Most popular ROM container. Most older ROMs are stored in the iNES format, but most modern dumps usually use the newer version: NES 2.0. This class supports both. 13 | 14 | Load ROM: `var nesfile = new NesFile(filename)` or `var nesfile = NesFile.FromFile(filename)` 15 | 16 | Access fields: 17 | 18 | Set mapper: `nesfile.Mapper = 4;` 19 | 20 | Set version to NES 2.0: `nes.Version = NesFile.iNesVersion.NES20;` 21 | 22 | Set PRG data: `nesfile.PRG = new byte[32768] { ... };` 23 | 24 | Set CHR data: `nesfile.CHR = new byte[8192] { ... };` 25 | 26 | Enable battery saves: `nesfile.Battery = true;` 27 | 28 | Save ROM as .nes file: `nesfile.Save(filename);` 29 | 30 | Check [documentation](https://clusterm.github.io/nes-containers/classcom_1_1clusterrr_1_1_famicom_1_1_containers_1_1_nes_file.html) for all available properties. 31 | 32 | Full format specifications: https://www.nesdev.org/wiki/INES 33 | 34 | ### .unf (UNIF) 35 | 36 | UNIF (Universal NES Image Format) is an alternative format for holding NES and Famicom ROM images. Its motivation was to offer more description of the mapper board than the popular iNES format, but it suffered from other limiting constraints and a lack of popularity. The format is considered deprecated, replaced by the NES 2.0 revision of the iNES format, which better addresses the issues it had hoped to solve. There are a small number of game rips that currently only exist as UNIF. UNIF is currently considered a deprecated standard. 37 | 38 | UNIF uses key-value format fields. Key is four character string and value is binary data. In theory you can save data as any field but there are several standard fields. 39 | 40 | Load ROM: `var uniffile = new UnifFile(filename)` or `var uniffile = UnifFile.FromFile(filename)` 41 | 42 | You can assess fields like dictionary: 43 | 44 | Set mapper name: `uniffile["MAPR"] = "COOLGIRL";` 45 | 46 | Set PRG data: `uniffile["PRG0"] = new byte[...] {...};` 47 | 48 | But all standatd fields also available as properties: 49 | 50 | Set mapper name: `uniffile.Mapper = "COOLGIRL";` 51 | 52 | Set mirroring: `uniffile.Mirroring = MirroringType.MapperControlled;` 53 | 54 | Save ROM as .unf file: `unif.Save(filename);` 55 | 56 | Check [documentation](https://clusterm.github.io/nes-containers/classcom_1_1clusterrr_1_1_famicom_1_1_containers_1_1_unif_file.html) for all available properties. 57 | 58 | Full format specifications: https://www.nesdev.org/wiki/UNIF 59 | 60 | ### .fds (Famicom Disk System images) 61 | 62 | The FDS format is a way to store Famicom Disk System disk data. It's much more complex format as it can contain multiple disks/sides and each disk/side contains a disk header and files. 63 | 64 | ``` 65 | /-- File header block 66 | /-- Disk header block /- File #1 -- 67 | /- Disk 1, side A ----- File amount block / \-- File data block 68 | / \-- File blocks------------ 69 | FDS file ----- Disk 1, side B \ /-- File header block 70 | \ \- File #2 -- 71 | \- Disk 2, side A \-- File data block 72 | ``` 73 | 74 | Load ROM: `var fdsfile = new FdsFile(filename)` or `var fdsfile = FdsFile.FromFile(filename)` 75 | 76 | Get disk(s) sides: `IList sides = fdsfile.Sides;` 77 | 78 | Get game name code: `var name = fdsfile.sides[0].GameName;` 79 | 80 | Get file name: `var filename = fdsfile.sides[0].Files[0].FileName;` 81 | 82 | Get file data: `var filedata = fdsfile.sides[0].Files[0].Data;` 83 | 84 | Save ROM as .fds file: `fdsfile.Save(filename);` 85 | 86 | Check [documentation](https://clusterm.github.io/nes-containers/classcom_1_1clusterrr_1_1_famicom_1_1_containers_1_1_fds_file.html) for all available classes and properties. 87 | 88 | Full format specifications: https://www.nesdev.org/wiki/FDS_file_format 89 | 90 | ## Get it on NuGet 91 | https://www.nuget.org/packages/NesContainers/ 92 | 93 | ## Donate 94 | * [Buy Me A Coffee](https://www.buymeacoffee.com/cluster) 95 | * [Donation Alerts](https://www.donationalerts.com/r/clustermeerkat) 96 | * [Boosty](https://boosty.to/cluster) 97 | * BTC: 1MBYsGczwCypXhMBocoDQWxx7KZT2iiwzJ 98 | * PayPal is not available in Armenia :( 99 | -------------------------------------------------------------------------------- /Timing.cs: -------------------------------------------------------------------------------- 1 | namespace com.clusterrr.Famicom.Containers 2 | { 3 | /// 4 | /// Timing type, depends on region 5 | /// 6 | public enum Timing 7 | { 8 | /// 9 | /// NTSC, RP2C02, North America, Japan, South Korea, Taiwan 10 | /// 11 | Ntsc = 0, 12 | /// 13 | /// PAL, RP2C07, Western Europe, Australia 14 | /// 15 | Pal = 1, 16 | /// 17 | /// Used either if a game was released with identical ROM content in both NTSC and PAL countries, such as Nintendo's early games, or if the game detects the console's timing and adjusts itself 18 | /// 19 | Multiple = 2, 20 | /// 21 | /// Dendy, UMC 6527P and clones, Eastern Europe, Russia, Mainland China, India, Africa 22 | /// 23 | Dendy = 3 24 | }; 25 | } 26 | -------------------------------------------------------------------------------- /UnifFile.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Drawing; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Runtime.ConstrainedExecution; 8 | using System.Security.Cryptography; 9 | using System.Text; 10 | using System.Xml.Linq; 11 | 12 | namespace com.clusterrr.Famicom.Containers 13 | { 14 | /// 15 | /// UNIF file container for NES/Famicom games 16 | /// 17 | public class UnifFile : IEnumerable> 18 | { 19 | private const string FIELD_CTRL = "CTRL"; 20 | private const string FIELD_TVCI = "TVCI"; 21 | private const string FIELD_DINF = "DINF"; 22 | private const string FIELD_NAME = "NAME"; 23 | private const string FIELD_BATR = "BATR"; 24 | private const string FIELD_MAPR = "MAPR"; 25 | private const string FIELD_MIRR = "MIRR"; 26 | private const string FIELD_PRG0 = "PRG0"; 27 | private const string FIELD_PRG1 = "PRG1"; 28 | private const string FIELD_PRG2 = "PRG2"; 29 | private const string FIELD_PRG3 = "PRG3"; 30 | private const string FIELD_CHR0 = "CHR0"; 31 | private const string FIELD_CHR1 = "CHR1"; 32 | private const string FIELD_CHR2 = "CHR2"; 33 | private const string FIELD_CHR3 = "CHR3"; 34 | private const string PREFIX_PRG = "PRG"; 35 | private const string PREFIX_CHR = "CHR"; 36 | 37 | /// 38 | /// UNIF fields 39 | /// 40 | private Dictionary fields = new Dictionary(); 41 | 42 | /// 43 | /// UNIF version 44 | /// 45 | public uint Version { get; set; } = 5; 46 | 47 | /// 48 | /// Get/set UNIF field 49 | /// 50 | /// UNIF data block key 51 | /// 52 | public byte[] this[string key] 53 | { 54 | get 55 | { 56 | if (key.Length != 4) throw new ArgumentException("UNIF data block key must be 4 characters long"); 57 | if (!ContainsField(key)) throw new IndexOutOfRangeException($"There is no {key} field"); 58 | return fields[key]; 59 | } 60 | set 61 | { 62 | if (key.Length != 4) throw new ArgumentException("UNIF data block key must be 4 characters long"); 63 | if (value == null) 64 | this.RemoveField(key); 65 | else 66 | fields[key] = value; 67 | } 68 | } 69 | 70 | /// 71 | /// Returns true if field exists in the UNIF 72 | /// 73 | /// Field code 74 | /// True if field exists in the UNIF 75 | public bool ContainsField(string fieldName) => fields.ContainsKey(fieldName); 76 | 77 | /// 78 | /// Remove field from the UNIF 79 | /// 80 | /// 81 | public void RemoveField(string fieldName) => fields.Remove(fieldName); 82 | 83 | /// 84 | /// Returns enumerator that iterates throught fields 85 | /// 86 | /// IEnumerable object 87 | public IEnumerator> GetEnumerator() 88 | => fields.Select(kv => new KeyValuePair(kv.Key, kv.Value)).GetEnumerator(); 89 | 90 | IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); 91 | 92 | /// 93 | /// Constructor to create empty UnifFile object 94 | /// 95 | public UnifFile() 96 | { 97 | DumpDate = DateTime.Now; 98 | } 99 | 100 | /// 101 | /// Create UnifFile object from raw .unf file contents 102 | /// 103 | /// Raw UNIF data 104 | public UnifFile(byte[] data) 105 | { 106 | var header = new byte[32]; 107 | Array.Copy(data, header, 32); 108 | if (header[0] != 'U' || header[1] != 'N' || header[2] != 'I' || header[3] != 'F') 109 | throw new InvalidDataException("Invalid UNIF header"); 110 | Version = BitConverter.ToUInt32(header, 4); 111 | int pos = 32; 112 | while (pos < data.Length) 113 | { 114 | var type = Encoding.UTF8.GetString(data, pos, 4); 115 | pos += 4; 116 | int length = BitConverter.ToInt32(data, pos); 117 | pos += 4; 118 | var fieldData = new byte[length]; 119 | Array.Copy(data, pos, fieldData, 0, length); 120 | this[type] = fieldData; 121 | pos += length; 122 | } 123 | } 124 | 125 | /// 126 | /// Create UnifFile object from specified file 127 | /// 128 | /// Path to the .unf file 129 | public UnifFile(string fileName) : this(File.ReadAllBytes(fileName)) 130 | { 131 | } 132 | 133 | /// 134 | /// Create UnifFile object from raw .unf file contents 135 | /// 136 | /// 137 | /// UnifFile object 138 | public static UnifFile FromBytes(byte[] data) => new UnifFile(data); 139 | 140 | /// 141 | /// Create UnifFile object from specified file 142 | /// 143 | /// Path to the .unf file 144 | /// UnifFile object 145 | public static UnifFile FromFile(string filename) => new UnifFile(filename); 146 | 147 | /// 148 | /// Returns .unf file contents 149 | /// 150 | /// 151 | public byte[] ToBytes() 152 | { 153 | // Some checks 154 | if (ContainsField(FIELD_CTRL) && Version < 7) 155 | throw new InvalidDataException("CTRL (controllers) field requires UNIF version 7 or greater"); 156 | if (ContainsField(FIELD_TVCI) && Version < 6) 157 | throw new InvalidDataException("TVCI (controllers) field requires UNIF version 6 or greater"); 158 | 159 | var data = new List(); 160 | // Header 161 | data.AddRange(Encoding.UTF8.GetBytes("UNIF")); 162 | data.AddRange(BitConverter.GetBytes(Version)); 163 | data.AddRange(Enumerable.Repeat(0, 24).ToArray()); 164 | // Fields 165 | foreach (var kv in this) 166 | { 167 | data.AddRange(Encoding.UTF8.GetBytes(kv.Key)); 168 | var value = kv.Value; 169 | int len = value.Length; 170 | data.AddRange(BitConverter.GetBytes(len)); 171 | data.AddRange(value); 172 | } 173 | return data.ToArray(); 174 | } 175 | 176 | /// 177 | /// Save as .unf file 178 | /// 179 | /// Target filename 180 | public void Save(string filename) => File.WriteAllBytes(filename, ToBytes()); 181 | 182 | /// 183 | /// Convert string to null-terminated UTF string 184 | /// 185 | /// Input text 186 | /// Output byte[] array 187 | private static byte[] StringToUTF8N(string text) 188 | { 189 | var str = Encoding.UTF8.GetBytes(text); 190 | var result = new byte[str.Length + 1]; 191 | Array.Copy(str, result, str.Length); 192 | return result; 193 | } 194 | 195 | /// 196 | /// Convert null-terminated UTF string to string 197 | /// 198 | /// Input array of bytes 199 | /// Maximum number of bytes to parse 200 | /// Start offset 201 | /// 202 | private static string UTF8NToString(byte[] data, int maxLength = int.MaxValue, int offset = 0) 203 | { 204 | int length = 0; 205 | while ((data[length + offset] != 0) && (length + offset < data.Length) && (length < maxLength)) 206 | length++; 207 | return Encoding.UTF8.GetString(data, offset, length); 208 | } 209 | 210 | /// 211 | /// Mapper name (null if none) 212 | /// 213 | public string? Mapper 214 | { 215 | get => ContainsField(FIELD_MAPR) ? UTF8NToString(this[FIELD_MAPR]) : null; 216 | set 217 | { 218 | if (value == null) 219 | RemoveField(FIELD_MAPR); 220 | else 221 | this[FIELD_MAPR] = StringToUTF8N(value); 222 | } 223 | } 224 | 225 | /// 226 | /// The dumper name (null if none) 227 | /// 228 | /// 229 | public string? DumperName 230 | { 231 | get 232 | { 233 | if (!ContainsField(FIELD_DINF)) 234 | return null; 235 | var data = this[FIELD_DINF]; 236 | if (data.Length >= 204 && data[0] != 0) 237 | return UTF8NToString(data, 100); 238 | else 239 | return null; 240 | } 241 | set 242 | { 243 | if (value != null || DumpingSoftware != null || DumpDate != null) 244 | { 245 | if (!ContainsField(FIELD_DINF)) 246 | this[FIELD_DINF] = new byte[204]; 247 | var data = this[FIELD_DINF]; 248 | for (int i = 0; i < 100; i++) 249 | data[i] = 0; 250 | if (value != null) 251 | { 252 | var name = StringToUTF8N(value); 253 | Array.Copy(name, 0, data, 0, Math.Min(100, name!.Length)); 254 | } 255 | this[FIELD_DINF] = data; 256 | } 257 | else RemoveField(FIELD_DINF); 258 | } 259 | } 260 | 261 | /// 262 | /// The name of the dumping software or mechanism (null if none) 263 | /// 264 | public string? DumpingSoftware 265 | { 266 | get 267 | { 268 | if (!ContainsField(FIELD_DINF)) 269 | return null; 270 | var data = this[FIELD_DINF]; 271 | if (data.Length >= 204 && data[0] != 0) 272 | return UTF8NToString(data, 100, 104); 273 | else 274 | return null; 275 | } 276 | set 277 | { 278 | if (value != null || DumperName != null || DumpDate != null) 279 | { 280 | if (!ContainsField(FIELD_DINF)) 281 | this[FIELD_DINF] = new byte[204]; 282 | var data = this[FIELD_DINF]; 283 | for (int i = 104; i < 104 + 100; i++) 284 | data[i] = 0; 285 | if (value != null) 286 | { 287 | var name = StringToUTF8N(value); 288 | Array.Copy(name, 0, data, 104, Math.Min(100, name!.Length)); 289 | } 290 | this[FIELD_DINF] = data; 291 | } 292 | else RemoveField(FIELD_DINF); 293 | } 294 | } 295 | 296 | /// 297 | /// Date of the dump (null if none) 298 | /// 299 | public DateTime? DumpDate 300 | { 301 | get 302 | { 303 | if (!ContainsField(FIELD_DINF)) return null; 304 | var data = this[FIELD_DINF]; 305 | if (data[0] == 0 && data[1] == 0 && data[2] == 0 && data[3] == 0) 306 | return null; 307 | return new DateTime( 308 | year: data[102] | (data[103] << 8), 309 | month: data[101], 310 | day: data[100] 311 | ); 312 | } 313 | set 314 | { 315 | if (value != null || DumperName != null || DumpingSoftware != null) 316 | { 317 | if (!ContainsField(FIELD_DINF)) 318 | this[FIELD_DINF] = new byte[204]; 319 | var data = this[FIELD_DINF]; 320 | if (value != null) 321 | { 322 | data[100] = (byte)value.Value.Day; 323 | data[101] = (byte)value.Value.Month; 324 | data[102] = (byte)(value.Value.Year & 0xFF); 325 | data[103] = (byte)(value.Value.Year >> 8); 326 | } 327 | else 328 | { 329 | // Is it valid? 330 | data[100] = data[101] = data[102] = data[103] = 0; 331 | } 332 | this[FIELD_DINF] = data; 333 | } 334 | else RemoveField(FIELD_DINF); 335 | } 336 | } 337 | 338 | /// 339 | /// Name of the game (null if none) 340 | /// 341 | public string? GameName 342 | { 343 | get => ContainsField(FIELD_NAME) ? UTF8NToString(this[FIELD_NAME]) : null; 344 | set 345 | { 346 | if (value == null) 347 | RemoveField(FIELD_NAME); 348 | else 349 | this[FIELD_NAME] = StringToUTF8N(value!); 350 | } 351 | } 352 | 353 | /// 354 | /// For non-homebrew NES/Famicom games, this field's value is always a function of the region in which a game was released (null if none) 355 | /// 356 | public Timing? Region 357 | { 358 | get 359 | { 360 | if (ContainsField(FIELD_TVCI) && this[FIELD_TVCI].Any()) 361 | return (Timing)this[FIELD_TVCI].First(); 362 | else 363 | return null; 364 | } 365 | set 366 | { 367 | if (value != null) 368 | this[FIELD_TVCI] = new byte[] { (byte)value }; 369 | else 370 | RemoveField(FIELD_TVCI); 371 | } 372 | } 373 | 374 | /// 375 | /// Controllers usable by this game, bitmask (null if none) 376 | /// 377 | public Controller? Controllers 378 | { 379 | get 380 | { 381 | if (ContainsField(FIELD_CTRL) && this[FIELD_CTRL].Any()) 382 | return (Controller)this[FIELD_CTRL].First(); 383 | else 384 | return Controller.None; 385 | } 386 | set 387 | { 388 | if (value != null) 389 | fields[FIELD_CTRL] = new byte[] { (byte)value }; 390 | else 391 | RemoveField(FIELD_CTRL); 392 | } 393 | } 394 | 395 | /// 396 | /// Battery-backed (or other non-volatile memory) memory is present (null if none) 397 | /// 398 | public bool? Battery 399 | { 400 | get 401 | { 402 | if (ContainsField(FIELD_BATR) && this[FIELD_BATR].Any()) 403 | return this[FIELD_BATR].First() != 0; 404 | else 405 | return false; 406 | } 407 | set 408 | { 409 | if (value != null) 410 | fields[FIELD_BATR] = new byte[] { (byte)((bool)value ? 1 : 0) }; 411 | else 412 | RemoveField(FIELD_BATR); 413 | } 414 | } 415 | 416 | /// 417 | /// Mirroring type (null if none) 418 | /// 419 | public MirroringType? Mirroring 420 | { 421 | get 422 | { 423 | if (ContainsField(FIELD_MIRR) && this[FIELD_MIRR].Any()) 424 | return (MirroringType)this[FIELD_MIRR].First(); 425 | else 426 | return null; 427 | } 428 | set 429 | { 430 | if (value != null && value != MirroringType.Unknown) 431 | this[FIELD_MIRR] = new byte[] { (byte)value }; 432 | else 433 | this.RemoveField(FIELD_MIRR); 434 | } 435 | } 436 | 437 | /// 438 | /// PRG0 field (null if none) 439 | /// 440 | public byte[]? PRG0 441 | { 442 | get 443 | { 444 | if (ContainsField(FIELD_PRG0)) 445 | return this[FIELD_PRG0]; 446 | else 447 | return null; 448 | } 449 | set 450 | { 451 | if (value != null) 452 | this[FIELD_PRG0] = value; 453 | else 454 | RemoveField(FIELD_PRG0); 455 | } 456 | } 457 | 458 | /// 459 | /// PRG1 field (null if none) 460 | /// 461 | public byte[]? PRG1 462 | { 463 | get 464 | { 465 | if (ContainsField(FIELD_PRG1)) 466 | return this[FIELD_PRG1]; 467 | else 468 | return null; 469 | } 470 | set 471 | { 472 | if (value != null) 473 | this[FIELD_PRG1] = value; 474 | else 475 | RemoveField(FIELD_PRG1); 476 | } 477 | } 478 | 479 | /// 480 | /// PRG2 field (null if none) 481 | /// 482 | public byte[]? PRG2 483 | { 484 | get 485 | { 486 | if (ContainsField(FIELD_PRG2)) 487 | return this[FIELD_PRG2]; 488 | else 489 | return null; 490 | } 491 | set 492 | { 493 | if (value != null) 494 | this[FIELD_PRG2] = value; 495 | else 496 | RemoveField(FIELD_PRG2); 497 | } 498 | } 499 | 500 | /// 501 | /// PRG3 field (null if none) 502 | /// 503 | public byte[]? PRG3 504 | { 505 | get 506 | { 507 | if (ContainsField(FIELD_PRG3)) 508 | return this[FIELD_PRG3]; 509 | else 510 | return null; 511 | } 512 | set 513 | { 514 | if (value != null) 515 | this[FIELD_PRG3] = value; 516 | else 517 | RemoveField(FIELD_PRG3); 518 | } 519 | } 520 | 521 | /// 522 | /// CHR0 field (null if none) 523 | /// 524 | public byte[]? CHR0 525 | { 526 | get 527 | { 528 | if (ContainsField(FIELD_CHR0)) 529 | return this[FIELD_CHR0]; 530 | else 531 | return null; 532 | } 533 | set 534 | { 535 | if (value != null) 536 | this[FIELD_CHR0] = value; 537 | else 538 | RemoveField(FIELD_CHR0); 539 | } 540 | } 541 | 542 | /// 543 | /// CHR1 field (null if none) 544 | /// 545 | public byte[]? CHR1 546 | { 547 | get 548 | { 549 | if (ContainsField(FIELD_CHR1)) 550 | return this[FIELD_CHR1]; 551 | else 552 | return null; 553 | } 554 | set 555 | { 556 | if (value != null) 557 | this[FIELD_CHR1] = value; 558 | else 559 | RemoveField(FIELD_CHR1); 560 | } 561 | } 562 | 563 | /// 564 | /// CHR2 field (null if none) 565 | /// 566 | public byte[]? CHR2 567 | { 568 | get 569 | { 570 | if (ContainsField(FIELD_CHR2)) 571 | return this[FIELD_CHR2]; 572 | else 573 | return null; 574 | } 575 | set 576 | { 577 | if (value != null) 578 | this[FIELD_CHR2] = value; 579 | else 580 | RemoveField(FIELD_CHR2); 581 | } 582 | } 583 | 584 | /// 585 | /// CHR3 field (null if none) 586 | /// 587 | public byte[]? CHR3 588 | { 589 | get 590 | { 591 | if (ContainsField(FIELD_CHR3)) 592 | return this[FIELD_CHR3]; 593 | else 594 | return null; 595 | } 596 | set 597 | { 598 | if (value != null) 599 | this[FIELD_CHR3] = value; 600 | else 601 | RemoveField(FIELD_CHR3); 602 | } 603 | } 604 | 605 | /// 606 | /// Calculate CRC32 for PRG and CHR fields and store it into PCKx and CCKx fields 607 | /// 608 | public void CalculateAndStoreCRCs() 609 | { 610 | foreach (var kv in this.Where(kv => kv.Key.StartsWith(PREFIX_PRG))) 611 | { 612 | var num = kv.Key[3]; 613 | using var crc32 = new Crc32(); 614 | var crc32sum = crc32.ComputeHash(kv.Value); 615 | this[$"PCK{num}"] = crc32sum; 616 | } 617 | foreach (var kv in this.Where(kv => kv.Key.StartsWith(PREFIX_CHR))) 618 | { 619 | var num = kv.Key[3]; 620 | using var crc32 = new Crc32(); 621 | var crc32sum = crc32.ComputeHash(kv.Value); 622 | this[$"CCK{num}"] = crc32sum; 623 | } 624 | } 625 | 626 | /// 627 | /// Calculate MD5 checksum of ROM (all PRG fields + all CHR fields) 628 | /// 629 | /// MD5 checksum for all PRG and CHR data 630 | public byte[] CalculateMD5() 631 | { 632 | using var md5 = MD5.Create(); 633 | foreach(var kv in fields.Where(k => k.Key.StartsWith(PREFIX_PRG)).OrderBy(k => k.Key) 634 | .Concat(fields.Where(k => k.Key.StartsWith(PREFIX_CHR)).OrderBy(k => k.Key))) 635 | { 636 | var v = kv.Value; 637 | int sizeUpPow2 = 0; 638 | if (v.Length > 0) 639 | { 640 | sizeUpPow2 = 1; 641 | while (sizeUpPow2 < v.Length) sizeUpPow2 <<= 1; 642 | } 643 | md5.TransformBlock(v, 0, v.Length, null, 0); 644 | md5.TransformBlock(Enumerable.Repeat(byte.MaxValue, sizeUpPow2 - v.Length).ToArray(), 0, sizeUpPow2 - v.Length, null, 0); 645 | } 646 | md5.TransformFinalBlock(new byte[0], 0, 0); 647 | return md5.Hash; 648 | } 649 | 650 | /// 651 | /// Calculate CRC32 checksum of ROM (all PRG fields + all CHR fields) 652 | /// 653 | /// CRC32 checksum for all PRG and CHR data 654 | public uint CalculateCRC32() 655 | { 656 | using var crc32 = new Crc32(); 657 | foreach (var kv in fields.Where(k => k.Key.StartsWith(PREFIX_PRG)).OrderBy(k => k.Key) 658 | .Concat(fields.Where(k => k.Key.StartsWith(PREFIX_CHR)).OrderBy(k => k.Key))) 659 | { 660 | var v = kv.Value; 661 | int sizeUpPow2 = 0; 662 | if (v.Length > 0) 663 | { 664 | sizeUpPow2 = 1; 665 | while (sizeUpPow2 < v.Length) sizeUpPow2 <<= 1; 666 | } 667 | crc32.TransformBlock(v, 0, v.Length, null, 0); 668 | crc32.TransformBlock(Enumerable.Repeat(byte.MaxValue, sizeUpPow2 - v.Length).ToArray(), 0, sizeUpPow2 - v.Length, null, 0); 669 | } 670 | crc32.TransformFinalBlock(new byte[0], 0, 0); 671 | return BitConverter.ToUInt32(crc32.Hash.Reverse().ToArray(), 0); 672 | } 673 | 674 | /// 675 | /// Default game controller(s) 676 | /// 677 | [Flags] 678 | public enum Controller 679 | { 680 | /// 681 | /// None 682 | /// 683 | None = 0, 684 | /// 685 | /// Standatd Controller 686 | /// 687 | StandardController = 1, 688 | /// 689 | /// Zapper 690 | /// 691 | Zapper = 2, 692 | /// 693 | /// R.O.B. 694 | /// 695 | ROB = 4, 696 | /// 697 | /// Arkanoid Controller 698 | /// 699 | ArkanoidController = 8, 700 | /// 701 | /// Power Pad 702 | /// 703 | PowerPad = 16, 704 | /// 705 | /// Four Score 706 | /// 707 | FourScore = 32, 708 | } 709 | } 710 | } 711 | --------------------------------------------------------------------------------