cf335804d7e76524231bf65ddee4173704b76762
[picodrive.git] / Pico / Cart.c
1 // This is part of Pico Library\r
2 \r
3 // (c) Copyright 2004 Dave, All rights reserved.\r
4 // (c) Copyright 2006-2007, Grazvydas "notaz" Ignotas\r
5 // Free for non-commercial use.\r
6 \r
7 // For commercial use, separate licencing terms must be obtained.\r
8 \r
9 \r
10 #include "PicoInt.h"\r
11 #include "../zlib/zlib.h"\r
12 #include "../unzip/unzip.h"\r
13 #include "../unzip/unzip_stream.h"\r
14 \r
15 \r
16 static char *rom_exts[] = { "bin", "gen", "smd", "iso" };\r
17 \r
18 void (*PicoCartLoadProgressCB)(int percent) = NULL;\r
19 \r
20 \r
21 pm_file *pm_open(const char *path)\r
22 {\r
23   pm_file *file = NULL;\r
24   const char *ext;\r
25   FILE *f;\r
26 \r
27   if (path == NULL) return NULL;\r
28 \r
29   if (strlen(path) < 5) ext = NULL; // no ext\r
30   else ext = path + strlen(path) - 3;\r
31 \r
32   if (ext && strcasecmp(ext, "zip") == 0)\r
33   {\r
34     struct zipent *zipentry;\r
35     gzFile gzf = NULL;\r
36     ZIP *zipfile;\r
37     int i;\r
38 \r
39     zipfile = openzip(path);\r
40 \r
41     if (zipfile != NULL)\r
42     {\r
43       /* search for suitable file (right extension or large enough file) */\r
44       while ((zipentry = readzip(zipfile)) != NULL)\r
45       {\r
46         if (zipentry->uncompressed_size >= 128*1024) goto found_rom_zip;\r
47         if (strlen(zipentry->name) < 5) continue;\r
48 \r
49         ext = zipentry->name+strlen(zipentry->name)-3;\r
50         for (i = 0; i < sizeof(rom_exts)/sizeof(rom_exts[0]); i++)\r
51           if (!strcasecmp(ext, rom_exts[i]) == 0) goto found_rom_zip;\r
52       }\r
53 \r
54       /* zipfile given, but nothing found suitable for us inside */\r
55       goto zip_failed;\r
56 \r
57 found_rom_zip:\r
58       /* try to convert to gzip stream, so we could use standard gzio functions from zlib */\r
59       gzf = zip2gz(zipfile, zipentry);\r
60       if (gzf == NULL)  goto zip_failed;\r
61 \r
62       file = malloc(sizeof(*file));\r
63       if (file == NULL) goto zip_failed;\r
64       file->file  = zipfile;\r
65       file->param = gzf;\r
66       file->size  = zipentry->uncompressed_size;\r
67       file->type  = PMT_ZIP;\r
68       return file;\r
69 \r
70 zip_failed:\r
71       if (gzf) {\r
72         gzclose(gzf);\r
73         zipfile->fp = NULL; // gzclose() closed it\r
74       }\r
75       closezip(zipfile);\r
76       return NULL;\r
77     }\r
78   }\r
79 \r
80   /* not a zip, treat as uncompressed file */\r
81   f = fopen(path, "rb");\r
82   if (f == NULL) return NULL;\r
83 \r
84   /* we use our own buffering */\r
85   setvbuf(f, NULL, _IONBF, 0);\r
86 \r
87   file = malloc(sizeof(*file));\r
88   if (file == NULL) {\r
89     fclose(f);\r
90     return NULL;\r
91   }\r
92   fseek(f, 0, SEEK_END);\r
93   file->file  = f;\r
94   file->param = NULL;\r
95   file->size  = ftell(f);\r
96   file->type  = PMT_UNCOMPRESSED;\r
97   fseek(f, 0, SEEK_SET);\r
98   return file;\r
99 }\r
100 \r
101 size_t pm_read(void *ptr, size_t bytes, pm_file *stream)\r
102 {\r
103   int ret;\r
104 \r
105   if (stream->type == PMT_UNCOMPRESSED)\r
106   {\r
107     ret = fread(ptr, 1, bytes, stream->file);\r
108   }\r
109   else if (stream->type == PMT_ZIP)\r
110   {\r
111     gzFile gf = stream->param;\r
112     int err;\r
113     ret = gzread(gf, ptr, bytes);\r
114     err = gzerror2(gf);\r
115     if (ret > 0 && (err == Z_DATA_ERROR || err == Z_STREAM_END))\r
116       /* we must reset stream pointer or else next seek/read fails */\r
117       gzrewind(gf);\r
118   }\r
119   else\r
120     ret = 0;\r
121 \r
122   return ret;\r
123 }\r
124 \r
125 int pm_seek(pm_file *stream, long offset, int whence)\r
126 {\r
127   if (stream->type == PMT_UNCOMPRESSED)\r
128   {\r
129     fseek(stream->file, offset, whence);\r
130     return ftell(stream->file);\r
131   }\r
132   else if (stream->type == PMT_ZIP)\r
133   {\r
134     if (PicoMessage != NULL && offset > 6*1024*1024) {\r
135       long pos = gztell((gzFile) stream->param);\r
136       if (offset < pos || offset - pos > 6*1024*1024)\r
137         PicoMessage("Decompressing data...");\r
138     }\r
139     return gzseek((gzFile) stream->param, offset, whence);\r
140   }\r
141   else\r
142     return -1;\r
143 }\r
144 \r
145 int pm_close(pm_file *fp)\r
146 {\r
147   int ret = 0;\r
148 \r
149   if (fp == NULL) return EOF;\r
150 \r
151   if (fp->type == PMT_UNCOMPRESSED)\r
152   {\r
153     fclose(fp->file);\r
154   }\r
155   else if (fp->type == PMT_ZIP)\r
156   {\r
157     ZIP *zipfile = fp->file;\r
158     gzclose((gzFile) fp->param);\r
159     zipfile->fp = NULL; // gzclose() closed it\r
160     closezip(zipfile);\r
161   }\r
162   else\r
163     ret = EOF;\r
164 \r
165   free(fp);\r
166   return ret;\r
167 }\r
168 \r
169 \r
170 void Byteswap(unsigned char *data,int len)\r
171 {\r
172   int i=0;\r
173 \r
174   if (len<2) return; // Too short\r
175 \r
176   do\r
177   {\r
178     unsigned short *pd=(unsigned short *)(data+i);\r
179     int value=*pd; // Get 2 bytes\r
180 \r
181     value=(value<<8)|(value>>8); // Byteswap it\r
182     *pd=(unsigned short)value; // Put 2b ytes\r
183     i+=2;\r
184   }\r
185   while (i+2<=len);\r
186 }\r
187 \r
188 // Interleve a 16k block and byteswap\r
189 static int InterleveBlock(unsigned char *dest,unsigned char *src)\r
190 {\r
191   int i=0;\r
192   for (i=0;i<0x2000;i++) dest[(i<<1)  ]=src[       i]; // Odd\r
193   for (i=0;i<0x2000;i++) dest[(i<<1)+1]=src[0x2000+i]; // Even\r
194   return 0;\r
195 }\r
196 \r
197 // Decode a SMD file\r
198 static int DecodeSmd(unsigned char *data,int len)\r
199 {\r
200   unsigned char *temp=NULL;\r
201   int i=0;\r
202 \r
203   temp=(unsigned char *)malloc(0x4000);\r
204   if (temp==NULL) return 1;\r
205   memset(temp,0,0x4000);\r
206 \r
207   // Interleve each 16k block and shift down by 0x200:\r
208   for (i=0; i+0x4200<=len; i+=0x4000)\r
209   {\r
210     InterleveBlock(temp,data+0x200+i); // Interleve 16k to temporary buffer\r
211     memcpy(data+i,temp,0x4000); // Copy back in\r
212   }\r
213 \r
214   free(temp);\r
215   return 0;\r
216 }\r
217 \r
218 static unsigned char *cd_realloc(void *old, int filesize)\r
219 {\r
220   unsigned char *rom;\r
221   dprintf("sizeof(mcd_state): %i", sizeof(mcd_state));\r
222   rom=realloc(old, sizeof(mcd_state));\r
223   if (rom) memset(rom+0x20000, 0, sizeof(mcd_state)-0x20000);\r
224   return rom;\r
225 }\r
226 \r
227 static unsigned char *PicoCartAlloc(int filesize)\r
228 {\r
229   int alloc_size;\r
230   unsigned char *rom;\r
231 \r
232   if (PicoMCD & 1) return cd_realloc(NULL, filesize);\r
233 \r
234   alloc_size=filesize+0x7ffff;\r
235   if((filesize&0x3fff)==0x200) alloc_size-=0x200;\r
236   alloc_size&=~0x7ffff; // use alloc size of multiples of 512K, so that memhandlers could be set up more efficiently\r
237   if((filesize&0x3fff)==0x200) alloc_size+=0x200;\r
238   else if(alloc_size-filesize < 4) alloc_size+=4; // padding for out-of-bound exec protection\r
239   //dprintf("alloc_size: %x\n",  alloc_size);\r
240 \r
241   // Allocate space for the rom plus padding\r
242   rom=(unsigned char *)malloc(alloc_size);\r
243   if(rom) memset(rom+alloc_size-0x80000,0,0x80000);\r
244   return rom;\r
245 }\r
246 \r
247 int PicoCartLoad(pm_file *f,unsigned char **prom,unsigned int *psize)\r
248 {\r
249   unsigned char *rom=NULL; int size, bytes_read;\r
250   if (f==NULL) return 1;\r
251 \r
252   size=f->size;\r
253   if (size <= 0) return 1;\r
254   size=(size+3)&~3; // Round up to a multiple of 4\r
255 \r
256   // Allocate space for the rom plus padding\r
257   rom=PicoCartAlloc(size);\r
258   if (rom==NULL) {\r
259     printf("out of memory (wanted %i)\n", size);\r
260     return 1;\r
261   }\r
262 \r
263   if (PicoCartLoadProgressCB != NULL)\r
264   {\r
265     // read ROM in blocks, just for fun\r
266     int ret;\r
267     unsigned char *p = rom;\r
268     bytes_read=0;\r
269     do\r
270     {\r
271       int todo = size - bytes_read;\r
272       if (todo > 256*1024) todo = 256*1024;\r
273       ret = pm_read(p,todo,f);\r
274       bytes_read += ret;\r
275       p += ret;\r
276       PicoCartLoadProgressCB(bytes_read * 100 / size);\r
277     }\r
278     while (ret > 0);\r
279   }\r
280   else\r
281     bytes_read = pm_read(rom,size,f); // Load up the rom\r
282   if (bytes_read <= 0) {\r
283     printf("read failed\n");\r
284     free(rom);\r
285     return 1;\r
286   }\r
287 \r
288   // maybe we are loading MegaCD BIOS?\r
289   if (!(PicoMCD&1) && size == 0x20000 && (!strncmp((char *)rom+0x124, "BOOT", 4) || !strncmp((char *)rom+0x128, "BOOT", 4))) {\r
290     PicoMCD |= 1;\r
291     rom = cd_realloc(rom, size);\r
292   }\r
293 \r
294   // Check for SMD:\r
295   if ((size&0x3fff)==0x200) { DecodeSmd(rom,size); size-=0x200; } // Decode and byteswap SMD\r
296   else Byteswap(rom,size); // Just byteswap\r
297 \r
298   if (prom)  *prom=rom;\r
299   if (psize) *psize=size;\r
300 \r
301   return 0;\r
302 }\r
303 \r
304 // Insert/remove a cartridge:\r
305 int PicoCartInsert(unsigned char *rom,unsigned int romsize)\r
306 {\r
307   // notaz: add a 68k "jump one op back" opcode to the end of ROM.\r
308   // This will hang the emu, but will prevent nasty crashes.\r
309   // note: 4 bytes are padded to every ROM\r
310   if(rom != NULL)\r
311     *(unsigned long *)(rom+romsize) = 0xFFFE4EFA; // 4EFA FFFE byteswapped\r
312 \r
313   Pico.rom=rom;\r
314   Pico.romsize=romsize;\r
315 \r
316   // setup correct memory map for loaded ROM\r
317   if (PicoMCD & 1)\r
318        PicoMemSetupCD();\r
319   else PicoMemSetup();\r
320   PicoMemReset();\r
321 \r
322   if (!(PicoMCD & 1))\r
323     PicoCartDetect();\r
324 \r
325   return PicoReset(1);\r
326 }\r
327 \r
328 int PicoUnloadCart(unsigned char* romdata)\r
329 {\r
330   free(romdata);\r
331   return 0;\r
332 }\r
333 \r
334 static int name_cmp(const char *name)\r
335 {\r
336   int i, len = strlen(name);\r
337   const char *name_rom = (const char *)Pico.rom+0x150;\r
338   for (i = 0; i < len; i++)\r
339     if (name[i] != name_rom[i^1])\r
340       return 1;\r
341   return 0;\r
342 }\r
343 \r
344 /* various cart-specific things, which can't be handled by generic code */\r
345 void PicoCartDetect(void)\r
346 {\r
347   int sram_size = 0, csum;\r
348   if(SRam.data) free(SRam.data); SRam.data=0;\r
349   Pico.m.sram_reg = 0;\r
350 \r
351   csum = PicoRead32(0x18c) & 0xffff;\r
352 \r
353   if (Pico.rom[0x1B1] == 'R' && Pico.rom[0x1B0] == 'A')\r
354   {\r
355     if (Pico.rom[0x1B2] & 0x40)\r
356     {\r
357       // EEPROM\r
358       SRam.start = PicoRead32(0x1B4) & ~1; // zero address is used for clock by some games\r
359       SRam.end   = PicoRead32(0x1B8);\r
360       sram_size  = 0x2000;\r
361       Pico.m.sram_reg |= 4;\r
362     } else {\r
363       // normal SRAM\r
364       SRam.start = PicoRead32(0x1B4) & 0xFFFF00;\r
365       SRam.end   = PicoRead32(0x1B8) | 1;\r
366       sram_size  = SRam.end - SRam.start + 1;\r
367     }\r
368     Pico.m.sram_reg |= 0x10; // SRAM was detected\r
369   }\r
370   if (sram_size <= 0)\r
371   {\r
372     // some games may have bad headers, like S&K and Sonic3\r
373     // note: majority games use 0x200000 as starting address, but there are some which\r
374     // use something else (0x300000 by HardBall '95). Luckily they have good headers.\r
375     SRam.start = 0x200000;\r
376     SRam.end   = 0x203FFF;\r
377     sram_size  = 0x004000;\r
378   }\r
379 \r
380   if (sram_size)\r
381   {\r
382     SRam.data = (unsigned char *) calloc(sram_size, 1);\r
383     if(!SRam.data) return;\r
384   }\r
385   SRam.changed = 0;\r
386 \r
387   // set EEPROM defaults, in case it gets detected\r
388   SRam.eeprom_type   = 0; // 7bit (24C01)\r
389   SRam.eeprom_abits  = 3; // eeprom access must be odd addr for: bit0 ~ cl, bit1 ~ in\r
390   SRam.eeprom_bit_cl = 1;\r
391   SRam.eeprom_bit_in = 0;\r
392   SRam.eeprom_bit_out= 0;\r
393 \r
394   // some known EEPROM data (thanks to EkeEke)\r
395   if (name_cmp("COLLEGE SLAM") == 0 ||\r
396       name_cmp("FRANK THOMAS BIGHURT BASEBAL") == 0)\r
397   {\r
398     SRam.eeprom_type = 3;\r
399     SRam.eeprom_abits = 2;\r
400     SRam.eeprom_bit_cl = 0;\r
401   }\r
402   else if (name_cmp("NBA JAM TOURNAMENT EDITION") == 0 ||\r
403            name_cmp("NFL QUARTERBACK CLUB") == 0)\r
404   {\r
405     SRam.eeprom_type = 2;\r
406     SRam.eeprom_abits = 2;\r
407     SRam.eeprom_bit_cl = 0;\r
408   }\r
409   else if (name_cmp("NBA JAM") == 0)\r
410   {\r
411     SRam.eeprom_type = 2;\r
412     SRam.eeprom_bit_out = 1;\r
413     SRam.eeprom_abits = 0;\r
414   }\r
415   else if (name_cmp("NHLPA HOCKEY '93") == 0 ||\r
416            name_cmp("NHLPA Hockey '93") == 0 ||\r
417            name_cmp("RINGS OF POWER") == 0)\r
418   {\r
419     SRam.start = SRam.end = 0x200000;\r
420     Pico.m.sram_reg = 0x14;\r
421     SRam.eeprom_abits = 0;\r
422     SRam.eeprom_bit_cl = 6;\r
423     SRam.eeprom_bit_in = 7;\r
424     SRam.eeprom_bit_out= 7;\r
425   }\r
426   else if ( name_cmp("MICRO MACHINES II") == 0 ||\r
427            (name_cmp("        ") == 0 && // Micro Machines {Turbo Tournament '96, Military - It's a Blast!}\r
428             (csum == 0x165e || csum == 0x168b || csum == 0xCEE0 || csum == 0x2C41)))\r
429   {\r
430     SRam.start = 0x300000;\r
431     SRam.end   = 0x380001;\r
432     Pico.m.sram_reg = 0x14;\r
433     SRam.eeprom_type = 2;\r
434     SRam.eeprom_abits = 0;\r
435     SRam.eeprom_bit_cl = 1;\r
436     SRam.eeprom_bit_in = 0;\r
437     SRam.eeprom_bit_out= 7;\r
438   }\r
439 \r
440   // Some games malfunction if SRAM is not filled with 0xff\r
441   if (name_cmp("DINO DINI'S SOCCER") == 0 ||\r
442       name_cmp("MICRO MACHINES II") == 0)\r
443     memset(SRam.data, 0xff, sram_size);\r
444 }\r
445 \r