cdrom: sync with upstream
[pcsx_rearmed.git] / libpcsxcore / cdrom.c
1 /***************************************************************************
2  *   Copyright (C) 2007 Ryan Schultz, PCSX-df Team, PCSX team              *
3  *                                                                         *
4  *   This program is free software; you can redistribute it and/or modify  *
5  *   it under the terms of the GNU General Public License as published by  *
6  *   the Free Software Foundation; either version 2 of the License, or     *
7  *   (at your option) any later version.                                   *
8  *                                                                         *
9  *   This program is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU General Public License for more details.                          *
13  *                                                                         *
14  *   You should have received a copy of the GNU General Public License     *
15  *   along with this program; if not, write to the                         *
16  *   Free Software Foundation, Inc.,                                       *
17  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.           *
18  ***************************************************************************/
19
20 /*
21 * Handles all CD-ROM registers and functions.
22 */
23
24 #include "cdrom.h"
25 #include "ppf.h"
26 #include "psxdma.h"
27 #include "arm_features.h"
28
29 /* logging */
30 #if 0
31 #define CDR_LOG SysPrintf
32 #else
33 #define CDR_LOG(...)
34 #endif
35 #if 0
36 #define CDR_LOG_I SysPrintf
37 #else
38 #define CDR_LOG_I(...)
39 #endif
40 #if 0
41 #define CDR_LOG_IO SysPrintf
42 #else
43 #define CDR_LOG_IO(...)
44 #endif
45 //#define CDR_LOG_CMD_IRQ
46
47 cdrStruct cdr;
48 static unsigned char *pTransfer;
49 static s16 read_buf[CD_FRAMESIZE_RAW/2];
50
51 /* CD-ROM magic numbers */
52 #define CdlSync        0  /* nocash documentation : "Uh, actually, returns error code 40h = Invalid Command...?" */
53 #define CdlNop         1
54 #define CdlSetloc      2
55 #define CdlPlay        3
56 #define CdlForward     4
57 #define CdlBackward    5
58 #define CdlReadN       6
59 #define CdlStandby     7
60 #define CdlStop        8
61 #define CdlPause       9
62 #define CdlReset       10
63 #define CdlMute        11
64 #define CdlDemute      12
65 #define CdlSetfilter   13
66 #define CdlSetmode     14
67 #define CdlGetparam    15
68 #define CdlGetlocL     16
69 #define CdlGetlocP     17
70 #define CdlReadT       18
71 #define CdlGetTN       19
72 #define CdlGetTD       20
73 #define CdlSeekL       21
74 #define CdlSeekP       22
75 #define CdlSetclock    23
76 #define CdlGetclock    24
77 #define CdlTest        25
78 #define CdlID          26
79 #define CdlReadS       27
80 #define CdlInit        28
81 #define CdlGetQ        29
82 #define CdlReadToc     30
83
84 char *CmdName[0x100]= {
85     "CdlSync",     "CdlNop",       "CdlSetloc",  "CdlPlay",
86     "CdlForward",  "CdlBackward",  "CdlReadN",   "CdlStandby",
87     "CdlStop",     "CdlPause",     "CdlReset",    "CdlMute",
88     "CdlDemute",   "CdlSetfilter", "CdlSetmode", "CdlGetparam",
89     "CdlGetlocL",  "CdlGetlocP",   "CdlReadT",   "CdlGetTN",
90     "CdlGetTD",    "CdlSeekL",     "CdlSeekP",   "CdlSetclock",
91     "CdlGetclock", "CdlTest",      "CdlID",      "CdlReadS",
92     "CdlInit",     NULL,           "CDlReadToc", NULL
93 };
94
95 unsigned char Test04[] = { 0 };
96 unsigned char Test05[] = { 0 };
97 unsigned char Test20[] = { 0x98, 0x06, 0x10, 0xC3 };
98 unsigned char Test22[] = { 0x66, 0x6F, 0x72, 0x20, 0x45, 0x75, 0x72, 0x6F };
99 unsigned char Test23[] = { 0x43, 0x58, 0x44, 0x32, 0x39 ,0x34, 0x30, 0x51 };
100
101 // cdr.Stat:
102 #define NoIntr          0
103 #define DataReady       1
104 #define Complete        2
105 #define Acknowledge     3
106 #define DataEnd         4
107 #define DiskError       5
108
109 /* Modes flags */
110 #define MODE_SPEED       (1<<7) // 0x80
111 #define MODE_STRSND      (1<<6) // 0x40 ADPCM on/off
112 #define MODE_SIZE_2340   (1<<5) // 0x20
113 #define MODE_SIZE_2328   (1<<4) // 0x10
114 #define MODE_SIZE_2048   (0<<4) // 0x00
115 #define MODE_SF          (1<<3) // 0x08 channel on/off
116 #define MODE_REPORT      (1<<2) // 0x04
117 #define MODE_AUTOPAUSE   (1<<1) // 0x02
118 #define MODE_CDDA        (1<<0) // 0x01
119
120 /* Status flags */
121 #define STATUS_PLAY      (1<<7) // 0x80
122 #define STATUS_SEEK      (1<<6) // 0x40
123 #define STATUS_READ      (1<<5) // 0x20
124 #define STATUS_SHELLOPEN (1<<4) // 0x10
125 #define STATUS_UNKNOWN3  (1<<3) // 0x08
126 #define STATUS_UNKNOWN2  (1<<2) // 0x04
127 #define STATUS_ROTATING  (1<<1) // 0x02
128 #define STATUS_ERROR     (1<<0) // 0x01
129
130 /* Errors */
131 #define ERROR_NOTREADY   (1<<7) // 0x80
132 #define ERROR_INVALIDCMD (1<<6) // 0x40
133 #define ERROR_INVALIDARG (1<<5) // 0x20
134
135 // 1x = 75 sectors per second
136 // PSXCLK = 1 sec in the ps
137 // so (PSXCLK / 75) = cdr read time (linuzappz)
138 #define cdReadTime (PSXCLK / 75)
139
140 enum drive_state {
141         DRIVESTATE_STANDBY = 0,
142         DRIVESTATE_LID_OPEN,
143         DRIVESTATE_RESCAN_CD,
144         DRIVESTATE_PREPARE_CD,
145         DRIVESTATE_STOPPED,
146 };
147
148 // for cdr.Seeked
149 enum seeked_state {
150         SEEK_PENDING = 0,
151         SEEK_DONE = 1,
152 };
153
154 static struct CdrStat stat;
155
156 static unsigned int msf2sec(const u8 *msf) {
157         return ((msf[0] * 60 + msf[1]) * 75) + msf[2];
158 }
159
160 // for that weird psemu API..
161 static unsigned int fsm2sec(const u8 *msf) {
162         return ((msf[2] * 60 + msf[1]) * 75) + msf[0];
163 }
164
165 static void sec2msf(unsigned int s, u8 *msf) {
166         msf[0] = s / 75 / 60;
167         s = s - msf[0] * 75 * 60;
168         msf[1] = s / 75;
169         s = s - msf[1] * 75;
170         msf[2] = s;
171 }
172
173 // cdrInterrupt
174 #define CDR_INT(eCycle) { \
175         psxRegs.interrupt |= (1 << PSXINT_CDR); \
176         psxRegs.intCycle[PSXINT_CDR].cycle = eCycle; \
177         psxRegs.intCycle[PSXINT_CDR].sCycle = psxRegs.cycle; \
178         new_dyna_set_event(PSXINT_CDR, eCycle); \
179 }
180
181 // cdrReadInterrupt
182 #define CDREAD_INT(eCycle) { \
183         psxRegs.interrupt |= (1 << PSXINT_CDREAD); \
184         psxRegs.intCycle[PSXINT_CDREAD].cycle = eCycle; \
185         psxRegs.intCycle[PSXINT_CDREAD].sCycle = psxRegs.cycle; \
186         new_dyna_set_event(PSXINT_CDREAD, eCycle); \
187 }
188
189 // cdrLidSeekInterrupt
190 #define CDRLID_INT(eCycle) { \
191         psxRegs.interrupt |= (1 << PSXINT_CDRLID); \
192         psxRegs.intCycle[PSXINT_CDRLID].cycle = eCycle; \
193         psxRegs.intCycle[PSXINT_CDRLID].sCycle = psxRegs.cycle; \
194         new_dyna_set_event(PSXINT_CDRLID, eCycle); \
195 }
196
197 // cdrPlayInterrupt
198 #define CDRMISC_INT(eCycle) { \
199         psxRegs.interrupt |= (1 << PSXINT_CDRPLAY); \
200         psxRegs.intCycle[PSXINT_CDRPLAY].cycle = eCycle; \
201         psxRegs.intCycle[PSXINT_CDRPLAY].sCycle = psxRegs.cycle; \
202         new_dyna_set_event(PSXINT_CDRPLAY, eCycle); \
203 }
204
205 #define StopReading() { \
206         if (cdr.Reading) { \
207                 cdr.Reading = 0; \
208                 psxRegs.interrupt &= ~(1 << PSXINT_CDREAD); \
209         } \
210         cdr.StatP &= ~(STATUS_READ|STATUS_SEEK);\
211 }
212
213 #define StopCdda() { \
214         if (cdr.Play) { \
215                 if (!Config.Cdda) CDR_stop(); \
216                 cdr.StatP &= ~STATUS_PLAY; \
217                 cdr.Play = FALSE; \
218                 cdr.FastForward = 0; \
219                 cdr.FastBackward = 0; \
220                 /*SPU_registerCallback( SPUirq );*/ \
221         } \
222 }
223
224 #define SetResultSize(size) { \
225         cdr.ResultP = 0; \
226         cdr.ResultC = size; \
227         cdr.ResultReady = 1; \
228 }
229
230 static void setIrq(void)
231 {
232         if (cdr.Stat & cdr.Reg2)
233                 psxHu32ref(0x1070) |= SWAP32((u32)0x4);
234 }
235
236 // timing used in this function was taken from tests on real hardware
237 // (yes it's slow, but you probably don't want to modify it)
238 void cdrLidSeekInterrupt()
239 {
240         switch (cdr.DriveState) {
241         default:
242         case DRIVESTATE_STANDBY:
243                 cdr.StatP &= ~STATUS_SEEK;
244
245                 if (CDR_getStatus(&stat) == -1)
246                         return;
247
248                 if (stat.Status & STATUS_SHELLOPEN)
249                 {
250                         StopCdda();
251                         cdr.DriveState = DRIVESTATE_LID_OPEN;
252                         CDRLID_INT(0x800);
253                 }
254                 break;
255
256         case DRIVESTATE_LID_OPEN:
257                 if (CDR_getStatus(&stat) == -1)
258                         stat.Status &= ~STATUS_SHELLOPEN;
259
260                 // 02, 12, 10
261                 if (!(cdr.StatP & STATUS_SHELLOPEN)) {
262                         StopReading();
263                         cdr.StatP |= STATUS_SHELLOPEN;
264
265                         // could generate error irq here, but real hardware
266                         // only sometimes does that
267                         // (not done when lots of commands are sent?)
268
269                         CDRLID_INT(cdReadTime * 30);
270                         break;
271                 }
272                 else if (cdr.StatP & STATUS_ROTATING) {
273                         cdr.StatP &= ~STATUS_ROTATING;
274                 }
275                 else if (!(stat.Status & STATUS_SHELLOPEN)) {
276                         // closed now
277                         CheckCdrom();
278
279                         // cdr.StatP STATUS_SHELLOPEN is "sticky"
280                         // and is only cleared by CdlNop
281
282                         cdr.DriveState = DRIVESTATE_RESCAN_CD;
283                         CDRLID_INT(cdReadTime * 105);
284                         break;
285                 }
286
287                 // recheck for close
288                 CDRLID_INT(cdReadTime * 3);
289                 break;
290
291         case DRIVESTATE_RESCAN_CD:
292                 cdr.StatP |= STATUS_ROTATING;
293                 cdr.DriveState = DRIVESTATE_PREPARE_CD;
294
295                 // this is very long on real hardware, over 6 seconds
296                 // make it a bit faster here...
297                 CDRLID_INT(cdReadTime * 150);
298                 break;
299
300         case DRIVESTATE_PREPARE_CD:
301                 cdr.StatP |= STATUS_SEEK;
302
303                 cdr.DriveState = DRIVESTATE_STANDBY;
304                 CDRLID_INT(cdReadTime * 26);
305                 break;
306         }
307 }
308
309 static void Find_CurTrack(const u8 *time)
310 {
311         int current, sect;
312
313         current = msf2sec(time);
314
315         for (cdr.CurTrack = 1; cdr.CurTrack < cdr.ResultTN[1]; cdr.CurTrack++) {
316                 CDR_getTD(cdr.CurTrack + 1, cdr.ResultTD);
317                 sect = fsm2sec(cdr.ResultTD);
318                 if (sect - current >= 150)
319                         break;
320         }
321 }
322
323 static void generate_subq(const u8 *time)
324 {
325         unsigned char start[3], next[3];
326         unsigned int this_s, start_s, next_s, pregap;
327         int relative_s;
328
329         CDR_getTD(cdr.CurTrack, start);
330         if (cdr.CurTrack + 1 <= cdr.ResultTN[1]) {
331                 pregap = 150;
332                 CDR_getTD(cdr.CurTrack + 1, next);
333         }
334         else {
335                 // last track - cd size
336                 pregap = 0;
337                 next[0] = cdr.SetSectorEnd[2];
338                 next[1] = cdr.SetSectorEnd[1];
339                 next[2] = cdr.SetSectorEnd[0];
340         }
341
342         this_s = msf2sec(time);
343         start_s = fsm2sec(start);
344         next_s = fsm2sec(next);
345
346         cdr.TrackChanged = FALSE;
347
348         if (next_s - this_s < pregap) {
349                 cdr.TrackChanged = TRUE;
350                 cdr.CurTrack++;
351                 start_s = next_s;
352         }
353
354         cdr.subq.Index = 1;
355
356         relative_s = this_s - start_s;
357         if (relative_s < 0) {
358                 cdr.subq.Index = 0;
359                 relative_s = -relative_s;
360         }
361         sec2msf(relative_s, cdr.subq.Relative);
362
363         cdr.subq.Track = itob(cdr.CurTrack);
364         cdr.subq.Relative[0] = itob(cdr.subq.Relative[0]);
365         cdr.subq.Relative[1] = itob(cdr.subq.Relative[1]);
366         cdr.subq.Relative[2] = itob(cdr.subq.Relative[2]);
367         cdr.subq.Absolute[0] = itob(time[0]);
368         cdr.subq.Absolute[1] = itob(time[1]);
369         cdr.subq.Absolute[2] = itob(time[2]);
370 }
371
372 static void ReadTrack(const u8 *time) {
373         unsigned char tmp[3];
374         struct SubQ *subq;
375         u16 crc;
376
377         tmp[0] = itob(time[0]);
378         tmp[1] = itob(time[1]);
379         tmp[2] = itob(time[2]);
380
381         if (memcmp(cdr.Prev, tmp, 3) == 0)
382                 return;
383
384         CDR_LOG("ReadTrack *** %02x:%02x:%02x\n", tmp[0], tmp[1], tmp[2]);
385
386         cdr.NoErr = CDR_readTrack(tmp);
387         memcpy(cdr.Prev, tmp, 3);
388
389         if (CheckSBI(time))
390                 return;
391
392         subq = (struct SubQ *)CDR_getBufferSub();
393         if (subq != NULL && cdr.CurTrack == 1) {
394                 crc = calcCrc((u8 *)subq + 12, 10);
395                 if (crc == (((u16)subq->CRC[0] << 8) | subq->CRC[1])) {
396                         cdr.subq.Track = subq->TrackNumber;
397                         cdr.subq.Index = subq->IndexNumber;
398                         memcpy(cdr.subq.Relative, subq->TrackRelativeAddress, 3);
399                         memcpy(cdr.subq.Absolute, subq->AbsoluteAddress, 3);
400                 }
401                 else {
402                         CDR_LOG_I("subq bad crc @%02x:%02x:%02x\n",
403                                 tmp[0], tmp[1], tmp[2]);
404                 }
405         }
406         else {
407                 generate_subq(time);
408         }
409
410         CDR_LOG(" -> %02x,%02x %02x:%02x:%02x %02x:%02x:%02x\n",
411                 cdr.subq.Track, cdr.subq.Index,
412                 cdr.subq.Relative[0], cdr.subq.Relative[1], cdr.subq.Relative[2],
413                 cdr.subq.Absolute[0], cdr.subq.Absolute[1], cdr.subq.Absolute[2]);
414 }
415
416 static void AddIrqQueue(unsigned short irq, unsigned long ecycle) {
417         if (cdr.Irq != 0) {
418                 if (irq == cdr.Irq || irq + 0x100 == cdr.Irq) {
419                         cdr.IrqRepeated = 1;
420                         CDR_INT(ecycle);
421                         return;
422                 }
423
424                 CDR_LOG_I("cdr: override cmd %02x -> %02x\n", cdr.Irq, irq);
425         }
426
427         cdr.Irq = irq;
428         cdr.eCycle = ecycle;
429
430         CDR_INT(ecycle);
431 }
432
433 static void cdrPlayInterrupt_Autopause()
434 {
435         u32 abs_lev_max = 0;
436         boolean abs_lev_chselect;
437         u32 i;
438
439         if ((cdr.Mode & MODE_AUTOPAUSE) && cdr.TrackChanged) {
440                 CDR_LOG( "CDDA STOP\n" );
441
442                 // Magic the Gathering
443                 // - looping territory cdda
444
445                 // ...?
446                 //cdr.ResultReady = 1;
447                 //cdr.Stat = DataReady;
448                 cdr.Stat = DataEnd;
449                 setIrq();
450
451                 StopCdda();
452         }
453         else if (((cdr.Mode & MODE_REPORT) || cdr.FastForward || cdr.FastBackward)) {
454                 cdr.Result[0] = cdr.StatP;
455                 cdr.Result[1] = cdr.subq.Track;
456                 cdr.Result[2] = cdr.subq.Index;
457                 
458                 abs_lev_chselect = cdr.subq.Absolute[1] & 0x01;
459                 
460                 /* 8 is a hack. For accuracy, it should be 588. */
461                 for (i = 0; i < 8; i++)
462                 {
463                         abs_lev_max = MAX_VALUE(abs_lev_max, abs(read_buf[i * 2 + abs_lev_chselect]));
464                 }
465                 abs_lev_max = MIN_VALUE(abs_lev_max, 32767);
466                 abs_lev_max |= abs_lev_chselect << 15;
467
468                 if (cdr.subq.Absolute[2] & 0x10) {
469                         cdr.Result[3] = cdr.subq.Relative[0];
470                         cdr.Result[4] = cdr.subq.Relative[1] | 0x80;
471                         cdr.Result[5] = cdr.subq.Relative[2];
472                 }
473                 else {
474                         cdr.Result[3] = cdr.subq.Absolute[0];
475                         cdr.Result[4] = cdr.subq.Absolute[1];
476                         cdr.Result[5] = cdr.subq.Absolute[2];
477                 }
478
479                 cdr.Result[6] = abs_lev_max >> 0;
480                 cdr.Result[7] = abs_lev_max >> 8;
481
482                 // Rayman: Logo freeze (resultready + dataready)
483                 cdr.ResultReady = 1;
484                 cdr.Stat = DataReady;
485
486                 SetResultSize(8);
487                 setIrq();
488         }
489 }
490
491 // also handles seek
492 void cdrPlayInterrupt()
493 {
494         if (cdr.Seeked == SEEK_PENDING) {
495                 if (cdr.Stat) {
496                         CDR_LOG_I("cdrom: seek stat hack\n");
497                         CDRMISC_INT(0x1000);
498                         return;
499                 }
500                 SetResultSize(1);
501                 cdr.StatP |= STATUS_ROTATING;
502                 cdr.StatP &= ~STATUS_SEEK;
503                 cdr.Result[0] = cdr.StatP;
504                 cdr.Seeked = SEEK_DONE;
505                 if (cdr.Irq == 0) {
506                         cdr.Stat = Complete;
507                         setIrq();
508                 }
509
510                 if (cdr.SetlocPending) {
511                         memcpy(cdr.SetSectorPlay, cdr.SetSector, 4);
512                         cdr.SetlocPending = 0;
513                         cdr.m_locationChanged = TRUE;
514                 }
515                 Find_CurTrack(cdr.SetSectorPlay);
516                 ReadTrack(cdr.SetSectorPlay);
517                 cdr.TrackChanged = FALSE;
518         }
519
520         if (!cdr.Play) return;
521
522         CDR_LOG( "CDDA - %d:%d:%d\n",
523                 cdr.SetSectorPlay[0], cdr.SetSectorPlay[1], cdr.SetSectorPlay[2] );
524
525         if (memcmp(cdr.SetSectorPlay, cdr.SetSectorEnd, 3) == 0) {
526                 StopCdda();
527                 cdr.TrackChanged = TRUE;
528         }
529         else {
530                 CDR_readCDDA(cdr.SetSectorPlay[0], cdr.SetSectorPlay[1], cdr.SetSectorPlay[2], (u8 *)read_buf);
531         }
532
533         if (!cdr.Irq && !cdr.Stat && (cdr.Mode & (MODE_AUTOPAUSE|MODE_REPORT)))
534                 cdrPlayInterrupt_Autopause();
535
536         if (CDR_readCDDA && !cdr.Muted && !Config.Cdda) {
537                 cdrAttenuate(read_buf, CD_FRAMESIZE_RAW / 4, 1);
538                 if (SPU_playCDDAchannel)
539                         SPU_playCDDAchannel(read_buf, CD_FRAMESIZE_RAW);
540         }
541
542         cdr.SetSectorPlay[2]++;
543         if (cdr.SetSectorPlay[2] == 75) {
544                 cdr.SetSectorPlay[2] = 0;
545                 cdr.SetSectorPlay[1]++;
546                 if (cdr.SetSectorPlay[1] == 60) {
547                         cdr.SetSectorPlay[1] = 0;
548                         cdr.SetSectorPlay[0]++;
549                 }
550         }
551
552         if (cdr.m_locationChanged)
553         {
554                 CDRMISC_INT(cdReadTime * 30);
555                 cdr.m_locationChanged = FALSE;
556         }
557         else
558         {
559                 CDRMISC_INT(cdReadTime);
560         }
561
562         // update for CdlGetlocP/autopause
563         generate_subq(cdr.SetSectorPlay);
564 }
565
566 void cdrInterrupt() {
567         u16 Irq = cdr.Irq;
568         int no_busy_error = 0;
569         int start_rotating = 0;
570         int error = 0;
571         int delay;
572         unsigned int seekTime = 0;
573         u8 set_loc[3];
574         int i;
575
576         // Reschedule IRQ
577         if (cdr.Stat) {
578                 CDR_LOG_I("cdrom: stat hack: %02x %x\n", cdr.Irq, cdr.Stat);
579                 CDR_INT(0x1000);
580                 return;
581         }
582
583         cdr.Ctrl &= ~0x80;
584
585         // default response
586         SetResultSize(1);
587         cdr.Result[0] = cdr.StatP;
588         cdr.Stat = Acknowledge;
589
590         if (cdr.IrqRepeated) {
591                 cdr.IrqRepeated = 0;
592                 if (cdr.eCycle > psxRegs.cycle) {
593                         CDR_INT(cdr.eCycle);
594                         goto finish;
595                 }
596         }
597
598         cdr.Irq = 0;
599
600         switch (Irq) {
601                 case CdlNop:
602                         if (cdr.DriveState != DRIVESTATE_LID_OPEN)
603                                 cdr.StatP &= ~STATUS_SHELLOPEN;
604                         no_busy_error = 1;
605                         break;
606
607                 case CdlSetloc:
608                         CDR_LOG("CDROM setloc command (%02X, %02X, %02X)\n", cdr.Param[0], cdr.Param[1], cdr.Param[2]);
609
610                         // MM must be BCD, SS must be BCD and <0x60, FF must be BCD and <0x75
611                         if (((cdr.Param[0] & 0x0F) > 0x09) || (cdr.Param[0] > 0x99) || ((cdr.Param[1] & 0x0F) > 0x09) || (cdr.Param[1] >= 0x60) || ((cdr.Param[2] & 0x0F) > 0x09) || (cdr.Param[2] >= 0x75))
612                         {
613                                 CDR_LOG("Invalid/out of range seek to %02X:%02X:%02X\n", cdr.Param[0], cdr.Param[1], cdr.Param[2]);
614                                 error = ERROR_INVALIDARG;
615                                 goto set_error;
616                         }
617                         else
618                         {
619                                 for (i = 0; i < 3; i++)
620                                 {
621                                         set_loc[i] = btoi(cdr.Param[i]);
622                                 }
623
624                                 i = msf2sec(cdr.SetSectorPlay);
625                                 i = abs(i - msf2sec(set_loc));
626                                 if (i > 16)
627                                         cdr.Seeked = SEEK_PENDING;
628
629                                 memcpy(cdr.SetSector, set_loc, 3);
630                                 cdr.SetSector[3] = 0;
631                                 cdr.SetlocPending = 1;
632                         }
633                         break;
634
635                 do_CdlPlay:
636                 case CdlPlay:
637                         StopCdda();
638                         if (cdr.Seeked == SEEK_PENDING) {
639                                 // XXX: wrong, should seek instead..
640                                 cdr.Seeked = SEEK_DONE;
641                         }
642                         
643                         cdr.FastBackward = 0;
644                         cdr.FastForward = 0;
645
646                         if (cdr.SetlocPending) {
647                                 memcpy(cdr.SetSectorPlay, cdr.SetSector, 4);
648                                 cdr.SetlocPending = 0;
649                                 cdr.m_locationChanged = TRUE;
650                         }
651
652                         // BIOS CD Player
653                         // - Pause player, hit Track 01/02/../xx (Setloc issued!!)
654
655                         if (cdr.ParamC == 0 || cdr.Param[0] == 0) {
656                                 CDR_LOG("PLAY Resume @ %d:%d:%d\n",
657                                         cdr.SetSectorPlay[0], cdr.SetSectorPlay[1], cdr.SetSectorPlay[2]);
658                         }
659                         else
660                         {
661                                 int track = btoi( cdr.Param[0] );
662
663                                 if (track <= cdr.ResultTN[1])
664                                         cdr.CurTrack = track;
665
666                                 CDR_LOG("PLAY track %d\n", cdr.CurTrack);
667
668                                 if (CDR_getTD((u8)cdr.CurTrack, cdr.ResultTD) != -1) {
669                                         cdr.SetSectorPlay[0] = cdr.ResultTD[2];
670                                         cdr.SetSectorPlay[1] = cdr.ResultTD[1];
671                                         cdr.SetSectorPlay[2] = cdr.ResultTD[0];
672                                 }
673                         }
674
675                         /*
676                         Rayman: detect track changes
677                         - fixes logo freeze
678
679                         Twisted Metal 2: skip PREGAP + starting accurate SubQ
680                         - plays tracks without retry play
681
682                         Wild 9: skip PREGAP + starting accurate SubQ
683                         - plays tracks without retry play
684                         */
685                         Find_CurTrack(cdr.SetSectorPlay);
686                         ReadTrack(cdr.SetSectorPlay);
687                         cdr.TrackChanged = FALSE;
688
689                         StopReading();
690                         if (!Config.Cdda)
691                                 CDR_play(cdr.SetSectorPlay);
692
693                         // Vib Ribbon: gameplay checks flag
694                         cdr.StatP &= ~STATUS_SEEK;
695                         cdr.Result[0] = cdr.StatP;
696
697                         cdr.StatP |= STATUS_PLAY;
698                         
699                         // BIOS player - set flag again
700                         cdr.Play = TRUE;
701
702                         CDRMISC_INT( cdReadTime );
703                         start_rotating = 1;
704                         break;
705
706                 case CdlForward:
707                         // TODO: error 80 if stopped
708                         cdr.Stat = Complete;
709
710                         // GameShark CD Player: Calls 2x + Play 2x
711                         cdr.FastForward = 1;
712                         cdr.FastBackward = 0;
713                         break;
714
715                 case CdlBackward:
716                         cdr.Stat = Complete;
717
718                         // GameShark CD Player: Calls 2x + Play 2x
719                         cdr.FastBackward = 1;
720                         cdr.FastForward = 0;
721                         break;
722
723                 case CdlStandby:
724                         if (cdr.DriveState != DRIVESTATE_STOPPED) {
725                                 error = ERROR_INVALIDARG;
726                                 goto set_error;
727                         }
728                         AddIrqQueue(CdlStandby + 0x100, cdReadTime * 125 / 2);
729                         start_rotating = 1;
730                         break;
731
732                 case CdlStandby + 0x100:
733                         cdr.Stat = Complete;
734                         break;
735
736                 case CdlStop:
737                         if (cdr.Play) {
738                                 // grab time for current track
739                                 CDR_getTD((u8)(cdr.CurTrack), cdr.ResultTD);
740
741                                 cdr.SetSectorPlay[0] = cdr.ResultTD[2];
742                                 cdr.SetSectorPlay[1] = cdr.ResultTD[1];
743                                 cdr.SetSectorPlay[2] = cdr.ResultTD[0];
744                         }
745
746                         StopCdda();
747                         StopReading();
748
749                         delay = 0x800;
750                         if (cdr.DriveState == DRIVESTATE_STANDBY)
751                                 delay = cdReadTime * 30 / 2;
752
753                         cdr.DriveState = DRIVESTATE_STOPPED;
754                         AddIrqQueue(CdlStop + 0x100, delay);
755                         break;
756
757                 case CdlStop + 0x100:
758                         cdr.StatP &= ~STATUS_ROTATING;
759                         cdr.Result[0] = cdr.StatP;
760                         cdr.Stat = Complete;
761                         break;
762
763                 case CdlPause:
764                         /*
765                         Gundam Battle Assault 2: much slower (*)
766                         - Fixes boot, gameplay
767
768                         Hokuto no Ken 2: slower
769                         - Fixes intro + subtitles
770
771                         InuYasha - Feudal Fairy Tale: slower
772                         - Fixes battles
773                         */
774                         /* Gameblabla - Tightening the timings (as taken from Duckstation). 
775                          * The timings from Duckstation are based upon hardware tests.
776                          * Mednafen's timing don't work for Gundam Battle Assault 2 in PAL/50hz mode,
777                          * seems to be timing sensitive as it can depend on the CPU's clock speed.
778                          * */
779                         if (cdr.DriveState == DRIVESTATE_STANDBY)
780                         {
781                                 delay = 7000;
782                         }
783                         else
784                         {
785                                 delay = (((cdr.Mode & MODE_SPEED) ? 2 : 1) * (1000000));
786                                 CDRMISC_INT((cdr.Mode & MODE_SPEED) ? cdReadTime / 2 : cdReadTime);
787                         }
788                         AddIrqQueue(CdlPause + 0x100, delay);
789                         cdr.Ctrl |= 0x80;
790                         break;
791
792                 case CdlPause + 0x100:
793                         cdr.StatP &= ~STATUS_READ;
794                         cdr.Result[0] = cdr.StatP;
795                         cdr.Stat = Complete;
796                         break;
797
798                 case CdlReset:
799                         cdr.Muted = FALSE;
800                         cdr.Mode = 0x20; /* This fixes This is Football 2, Pooh's Party lockups */
801                         AddIrqQueue(CdlReset + 0x100, 4100000);
802                         no_busy_error = 1;
803                         start_rotating = 1;
804                         break;
805
806                 case CdlReset + 0x100:
807                         cdr.Stat = Complete;
808                         break;
809
810                 case CdlMute:
811                         cdr.Muted = TRUE;
812                         break;
813
814                 case CdlDemute:
815                         cdr.Muted = FALSE;
816                         break;
817
818                 case CdlSetfilter:
819                         cdr.File = cdr.Param[0];
820                         cdr.Channel = cdr.Param[1];
821                         break;
822
823                 case CdlSetmode:
824                         no_busy_error = 1;
825                         break;
826
827                 case CdlGetparam:
828                         /* Gameblabla : According to mednafen, Result size should be 5 and done this way. */
829                         SetResultSize(5);
830                         cdr.Result[1] = cdr.Mode;
831                         cdr.Result[2] = 0;
832                         cdr.Result[3] = cdr.File;
833                         cdr.Result[4] = cdr.Channel;
834                         no_busy_error = 1;
835                         break;
836
837                 case CdlGetlocL:
838                         SetResultSize(8);
839                         memcpy(cdr.Result, cdr.Transfer, 8);
840                         break;
841
842                 case CdlGetlocP:
843                         SetResultSize(8);
844                         memcpy(&cdr.Result, &cdr.subq, 8);
845                         break;
846
847                 case CdlReadT: // SetSession?
848                         // really long
849                         AddIrqQueue(CdlReadT + 0x100, cdReadTime * 290 / 4);
850                         start_rotating = 1;
851                         break;
852
853                 case CdlReadT + 0x100:
854                         cdr.Stat = Complete;
855                         break;
856
857                 case CdlGetTN:
858                         SetResultSize(3);
859                         if (CDR_getTN(cdr.ResultTN) == -1) {
860                                 cdr.Stat = DiskError;
861                                 cdr.Result[0] |= STATUS_ERROR;
862                         } else {
863                                 cdr.Stat = Acknowledge;
864                                 cdr.Result[1] = itob(cdr.ResultTN[0]);
865                                 cdr.Result[2] = itob(cdr.ResultTN[1]);
866                         }
867                         break;
868
869                 case CdlGetTD:
870                         cdr.Track = btoi(cdr.Param[0]);
871                         SetResultSize(4);
872                         if (CDR_getTD(cdr.Track, cdr.ResultTD) == -1) {
873                                 cdr.Stat = DiskError;
874                                 cdr.Result[0] |= STATUS_ERROR;
875                         } else {
876                                 cdr.Stat = Acknowledge;
877                                 cdr.Result[0] = cdr.StatP;
878                                 cdr.Result[1] = itob(cdr.ResultTD[2]);
879                                 cdr.Result[2] = itob(cdr.ResultTD[1]);
880                                 /* According to Nocash's documentation, the function doesn't care about ff.
881                                  * This can be seen also in Mednafen's implementation. */
882                                 //cdr.Result[3] = itob(cdr.ResultTD[0]);
883                         }
884                         break;
885
886                 case CdlSeekL:
887                 case CdlSeekP:
888                         StopCdda();
889                         StopReading();
890                         cdr.StatP |= STATUS_SEEK;
891
892                         /*
893                         Crusaders of Might and Magic = 0.5x-4x
894                         - fix cutscene speech start
895
896                         Eggs of Steel = 2x-?
897                         - fix new game
898
899                         Medievil = ?-4x
900                         - fix cutscene speech
901
902                         Rockman X5 = 0.5-4x
903                         - fix capcom logo
904                         */
905                         CDRMISC_INT(cdr.Seeked == SEEK_DONE ? 0x800 : cdReadTime * 4);
906                         cdr.Seeked = SEEK_PENDING;
907                         start_rotating = 1;
908                         break;
909
910                 case CdlTest:
911                         switch (cdr.Param[0]) {
912                                 case 0x20: // System Controller ROM Version
913                                         SetResultSize(4);
914                                         memcpy(cdr.Result, Test20, 4);
915                                         break;
916                                 case 0x22:
917                                         SetResultSize(8);
918                                         memcpy(cdr.Result, Test22, 4);
919                                         break;
920                                 case 0x23: case 0x24:
921                                         SetResultSize(8);
922                                         memcpy(cdr.Result, Test23, 4);
923                                         break;
924                         }
925                         no_busy_error = 1;
926                         break;
927
928                 case CdlID:
929                         AddIrqQueue(CdlID + 0x100, 20480);
930                         break;
931
932                 case CdlID + 0x100:
933                         SetResultSize(8);
934                         cdr.Result[0] = cdr.StatP;
935                         cdr.Result[1] = 0;
936                         cdr.Result[2] = 0;
937                         cdr.Result[3] = 0;
938
939                         // 0x10 - audio | 0x40 - disk missing | 0x80 - unlicensed
940                         if (CDR_getStatus(&stat) == -1 || stat.Type == 0 || stat.Type == 0xff) {
941                                 cdr.Result[1] = 0xc0;
942                         }
943                         else {
944                                 if (stat.Type == 2)
945                                         cdr.Result[1] |= 0x10;
946                                 if (CdromId[0] == '\0')
947                                         cdr.Result[1] |= 0x80;
948                         }
949                         cdr.Result[0] |= (cdr.Result[1] >> 4) & 0x08;
950
951                         /* This adds the string "PCSX" in Playstation bios boot screen */
952                         memcpy((char *)&cdr.Result[4], "PCSX", 4);
953                         cdr.Stat = Complete;
954                         break;
955
956                 case CdlInit:
957                         // yes, it really sets STATUS_SHELLOPEN
958                         cdr.StatP |= STATUS_SHELLOPEN;
959                         cdr.DriveState = DRIVESTATE_RESCAN_CD;
960                         CDRLID_INT(20480);
961                         no_busy_error = 1;
962                         start_rotating = 1;
963                         break;
964
965                 case CdlGetQ:
966                         no_busy_error = 1;
967                         break;
968
969                 case CdlReadToc:
970                         AddIrqQueue(CdlReadToc + 0x100, cdReadTime * 180 / 4);
971                         no_busy_error = 1;
972                         start_rotating = 1;
973                         break;
974
975                 case CdlReadToc + 0x100:
976                         cdr.Stat = Complete;
977                         no_busy_error = 1;
978                         break;
979
980                 case CdlReadN:
981                 case CdlReadS:
982                         if (cdr.SetlocPending) {
983                                 seekTime = abs(msf2sec(cdr.SetSectorPlay) - msf2sec(cdr.SetSector)) * (cdReadTime / 200);
984                                 /*
985                                 * Gameblabla :
986                                 * It was originally set to 1000000 for Driver, however it is not high enough for Worms Pinball
987                                 * and was unreliable for that game.
988                                 * I also tested it against Mednafen and Driver's titlescreen music starts 25 frames later, not immediatly.
989                                 * 
990                                 * Obviously, this isn't perfect but right now, it should be a bit better.
991                                 * Games to test this against if you change that setting :
992                                 * - Driver (titlescreen music delay and retry mission)
993                                 * - Worms Pinball (Will either not boot or crash in the memory card screen)
994                                 * - Viewpoint (short pauses if the delay in the ingame music is too long)
995                                 * 
996                                 * It seems that 3386880 * 5 is too much for Driver's titlescreen and it starts skipping.
997                                 * However, 1000000 is not enough for Worms Pinball to reliably boot.
998                                 */
999                                 if(seekTime > 3386880 * 2) seekTime = 3386880 * 2;
1000                                 memcpy(cdr.SetSectorPlay, cdr.SetSector, 4);
1001                                 cdr.SetlocPending = 0;
1002                                 cdr.m_locationChanged = TRUE;
1003                         }
1004                         Find_CurTrack(cdr.SetSectorPlay);
1005
1006                         if ((cdr.Mode & MODE_CDDA) && cdr.CurTrack > 1)
1007                                 // Read* acts as play for cdda tracks in cdda mode
1008                                 goto do_CdlPlay;
1009
1010                         cdr.Reading = 1;
1011                         cdr.FirstSector = 1;
1012
1013                         // Fighting Force 2 - update subq time immediately
1014                         // - fixes new game
1015                         ReadTrack(cdr.SetSectorPlay);
1016
1017
1018                         // Crusaders of Might and Magic - update getlocl now
1019                         // - fixes cutscene speech
1020                         {
1021                                 u8 *buf = CDR_getBuffer();
1022                                 if (buf != NULL)
1023                                         memcpy(cdr.Transfer, buf, 8);
1024                         }
1025
1026                         /*
1027                         Duke Nukem: Land of the Babes - seek then delay read for one frame
1028                         - fixes cutscenes
1029                         C-12 - Final Resistance - doesn't like seek
1030                         */
1031                         
1032                         /*      
1033                                 By nicolasnoble from PCSX Redux :
1034                                 "It LOOKS like this logic is wrong, therefore disabling it with `&& false` for now.
1035                                 For "PoPoLoCrois Monogatari II", the game logic will soft lock and will never issue GetLocP to detect
1036                                 the end of its XA streams, as it seems to assume ReadS will not return a status byte with the SEEK
1037                                 flag set. I think the reasonning is that since it's invalid to call GetLocP while seeking, the game
1038                                 tries to protect itself against errors by preventing from issuing a GetLocP while it knows the
1039                                 last status was "seek". But this makes the logic just softlock as it'll never get a notification
1040                                 about the fact the drive is done seeking and the read actually started.
1041
1042                                 In other words, this state machine here is probably wrong in assuming the response to ReadS/ReadN is
1043                                 done right away. It's rather when it's done seeking, and the read has actually started. This probably
1044                                 requires a bit more work to make sure seek delays are processed properly.
1045                                 Checked with a few games, this seems to work fine."
1046                                 
1047                                 Gameblabla additional notes :
1048                                 This still needs the "+ seekTime" that PCSX Redux doesn't have for the Driver "retry" mission error.
1049                         */
1050                         cdr.StatP |= STATUS_READ;
1051                         cdr.StatP &= ~STATUS_SEEK;
1052
1053                         CDREAD_INT(((cdr.Mode & 0x80) ? (cdReadTime) : cdReadTime * 2) + seekTime);
1054
1055                         cdr.Result[0] = cdr.StatP;
1056                         start_rotating = 1;
1057                         break;
1058                 case CdlSync:
1059                 default:
1060                         CDR_LOG_I("Invalid command: %02x\n", Irq);
1061                         error = ERROR_INVALIDCMD;
1062                         // FALLTHROUGH
1063
1064                 set_error:
1065                         SetResultSize(2);
1066                         cdr.Result[0] = cdr.StatP | STATUS_ERROR;
1067                         cdr.Result[1] = error;
1068                         cdr.Stat = DiskError;
1069                         break;
1070         }
1071
1072         if (cdr.DriveState == DRIVESTATE_STOPPED && start_rotating) {
1073                 cdr.DriveState = DRIVESTATE_STANDBY;
1074                 cdr.StatP |= STATUS_ROTATING;
1075         }
1076
1077         if (!no_busy_error) {
1078                 switch (cdr.DriveState) {
1079                 case DRIVESTATE_LID_OPEN:
1080                 case DRIVESTATE_RESCAN_CD:
1081                 case DRIVESTATE_PREPARE_CD:
1082                         SetResultSize(2);
1083                         cdr.Result[0] = cdr.StatP | STATUS_ERROR;
1084                         cdr.Result[1] = ERROR_NOTREADY;
1085                         cdr.Stat = DiskError;
1086                         break;
1087                 }
1088         }
1089
1090 finish:
1091         setIrq();
1092         cdr.ParamC = 0;
1093
1094 #ifdef CDR_LOG_CMD_IRQ
1095         {
1096                 int i;
1097                 SysPrintf("CDR IRQ %d cmd %02x stat %02x: ",
1098                         !!(cdr.Stat & cdr.Reg2), Irq, cdr.Stat);
1099                 for (i = 0; i < cdr.ResultC; i++)
1100                         SysPrintf("%02x ", cdr.Result[i]);
1101                 SysPrintf("\n");
1102         }
1103 #endif
1104 }
1105
1106 #ifdef HAVE_ARMV7
1107  #define ssat32_to_16(v) \
1108   asm("ssat %0,#16,%1" : "=r" (v) : "r" (v))
1109 #else
1110  #define ssat32_to_16(v) do { \
1111   if (v < -32768) v = -32768; \
1112   else if (v > 32767) v = 32767; \
1113  } while (0)
1114 #endif
1115
1116 void cdrAttenuate(s16 *buf, int samples, int stereo)
1117 {
1118         int i, l, r;
1119         int ll = cdr.AttenuatorLeftToLeft;
1120         int lr = cdr.AttenuatorLeftToRight;
1121         int rl = cdr.AttenuatorRightToLeft;
1122         int rr = cdr.AttenuatorRightToRight;
1123
1124         if (lr == 0 && rl == 0 && 0x78 <= ll && ll <= 0x88 && 0x78 <= rr && rr <= 0x88)
1125                 return;
1126
1127         if (!stereo && ll == 0x40 && lr == 0x40 && rl == 0x40 && rr == 0x40)
1128                 return;
1129
1130         if (stereo) {
1131                 for (i = 0; i < samples; i++) {
1132                         l = buf[i * 2];
1133                         r = buf[i * 2 + 1];
1134                         l = (l * ll + r * rl) >> 7;
1135                         r = (r * rr + l * lr) >> 7;
1136                         ssat32_to_16(l);
1137                         ssat32_to_16(r);
1138                         buf[i * 2] = l;
1139                         buf[i * 2 + 1] = r;
1140                 }
1141         }
1142         else {
1143                 for (i = 0; i < samples; i++) {
1144                         l = buf[i];
1145                         l = l * (ll + rl) >> 7;
1146                         //r = r * (rr + lr) >> 7;
1147                         ssat32_to_16(l);
1148                         //ssat32_to_16(r);
1149                         buf[i] = l;
1150                 }
1151         }
1152 }
1153
1154 void cdrReadInterrupt() {
1155         u8 *buf;
1156
1157         if (!cdr.Reading)
1158                 return;
1159
1160         if (cdr.Irq || cdr.Stat) {
1161                 CDR_LOG_I("cdrom: read stat hack %02x %x\n", cdr.Irq, cdr.Stat);
1162                 CDREAD_INT(0x1000);
1163                 return;
1164         }
1165
1166         cdr.OCUP = 1;
1167         SetResultSize(1);
1168         cdr.StatP |= STATUS_READ|STATUS_ROTATING;
1169         cdr.StatP &= ~STATUS_SEEK;
1170         cdr.Result[0] = cdr.StatP;
1171         cdr.Seeked = SEEK_DONE;
1172
1173         ReadTrack(cdr.SetSectorPlay);
1174
1175         buf = CDR_getBuffer();
1176         if (buf == NULL)
1177                 cdr.NoErr = 0;
1178
1179         if (!cdr.NoErr) {
1180                 CDR_LOG_I("cdrReadInterrupt() Log: err\n");
1181                 memset(cdr.Transfer, 0, DATA_SIZE);
1182                 cdr.Stat = DiskError;
1183                 cdr.Result[0] |= STATUS_ERROR;
1184                 CDREAD_INT((cdr.Mode & 0x80) ? (cdReadTime / 2) : cdReadTime);
1185                 return;
1186         }
1187
1188         memcpy(cdr.Transfer, buf, DATA_SIZE);
1189         CheckPPFCache(cdr.Transfer, cdr.Prev[0], cdr.Prev[1], cdr.Prev[2]);
1190
1191
1192         CDR_LOG("cdrReadInterrupt() Log: cdr.Transfer %x:%x:%x\n", cdr.Transfer[0], cdr.Transfer[1], cdr.Transfer[2]);
1193
1194         if ((!cdr.Muted) && (cdr.Mode & MODE_STRSND) && (!Config.Xa) && (cdr.FirstSector != -1)) { // CD-XA
1195                 // Firemen 2: Multi-XA files - briefings, cutscenes
1196                 if( cdr.FirstSector == 1 && (cdr.Mode & MODE_SF)==0 ) {
1197                         cdr.File = cdr.Transfer[4 + 0];
1198                         cdr.Channel = cdr.Transfer[4 + 1];
1199                 }
1200
1201                 /* Gameblabla 
1202                  * Skips playing on channel 255.
1203                  * Fixes missing audio in Blue's Clues : Blue's Big Musical. (Should also fix Taxi 2)
1204                  * TODO : Check if this is the proper behaviour.
1205                  * */
1206                 if((cdr.Transfer[4 + 2] & 0x4) &&
1207                          (cdr.Transfer[4 + 1] == cdr.Channel) &&
1208                          (cdr.Transfer[4 + 0] == cdr.File) && cdr.Channel != 255) {
1209                         int ret = xa_decode_sector(&cdr.Xa, cdr.Transfer+4, cdr.FirstSector);
1210                         if (!ret) {
1211                                 cdrAttenuate(cdr.Xa.pcm, cdr.Xa.nsamples, cdr.Xa.stereo);
1212                                 /*
1213                                  * Gameblabla -
1214                                  * This is a hack for Megaman X4, Castlevania etc...
1215                                  * that regressed from the new m_locationChanged and CDROM timings changes.
1216                                  * It is mostly noticeable in Castevania however and the stuttering can be very jarring.
1217                                  * 
1218                                  * According to PCSX redux authors, we shouldn't cause a location change if
1219                                  * the sector difference is too small. 
1220                                  * I attempted to go with that approach but came empty handed.
1221                                  * So for now, let's just set cdr.m_locationChanged to false when playing back any ADPCM samples.
1222                                  * This does not regress Crash Team Racing's intro at least.
1223                                 */
1224                                 cdr.m_locationChanged = FALSE;
1225                                 SPU_playADPCMchannel(&cdr.Xa);
1226                                 cdr.FirstSector = 0;
1227                         }
1228                         else cdr.FirstSector = -1;
1229                 }
1230         }
1231
1232         cdr.SetSectorPlay[2]++;
1233         if (cdr.SetSectorPlay[2] == 75) {
1234                 cdr.SetSectorPlay[2] = 0;
1235                 cdr.SetSectorPlay[1]++;
1236                 if (cdr.SetSectorPlay[1] == 60) {
1237                         cdr.SetSectorPlay[1] = 0;
1238                         cdr.SetSectorPlay[0]++;
1239                 }
1240         }
1241
1242         cdr.Readed = 0;
1243
1244         uint32_t delay = (cdr.Mode & MODE_SPEED) ? (cdReadTime / 2) : cdReadTime;
1245         if (cdr.m_locationChanged) {
1246                 CDREAD_INT(delay * 30);
1247                 cdr.m_locationChanged = FALSE;
1248         } else {
1249                 CDREAD_INT(delay);
1250         }
1251
1252         /*
1253         Croc 2: $40 - only FORM1 (*)
1254         Judge Dredd: $C8 - only FORM1 (*)
1255         Sim Theme Park - no adpcm at all (zero)
1256         */
1257
1258         if (!(cdr.Mode & MODE_STRSND) || !(cdr.Transfer[4+2] & 0x4)) {
1259                 cdr.Stat = DataReady;
1260                 setIrq();
1261         }
1262
1263         // update for CdlGetlocP
1264         ReadTrack(cdr.SetSectorPlay);
1265 }
1266
1267 /*
1268 cdrRead0:
1269         bit 0,1 - mode
1270         bit 2 - unknown
1271         bit 3 - unknown
1272         bit 4 - unknown
1273         bit 5 - 1 result ready
1274         bit 6 - 1 dma ready
1275         bit 7 - 1 command being processed
1276 */
1277
1278 unsigned char cdrRead0(void) {
1279         if (cdr.ResultReady)
1280                 cdr.Ctrl |= 0x20;
1281         else
1282                 cdr.Ctrl &= ~0x20;
1283
1284         if (cdr.OCUP)
1285                 cdr.Ctrl |= 0x40;
1286 //  else
1287 //              cdr.Ctrl &= ~0x40;
1288
1289         // What means the 0x10 and the 0x08 bits? I only saw it used by the bios
1290         cdr.Ctrl |= 0x18;
1291
1292         CDR_LOG_IO("cdr r0: %02x\n", cdr.Ctrl);
1293
1294         return psxHu8(0x1800) = cdr.Ctrl;
1295 }
1296
1297 void cdrWrite0(unsigned char rt) {
1298         CDR_LOG_IO("cdr w0: %02x\n", rt);
1299
1300         cdr.Ctrl = (rt & 3) | (cdr.Ctrl & ~3);
1301 }
1302
1303 unsigned char cdrRead1(void) {
1304         if ((cdr.ResultP & 0xf) < cdr.ResultC)
1305                 psxHu8(0x1801) = cdr.Result[cdr.ResultP & 0xf];
1306         else
1307                 psxHu8(0x1801) = 0;
1308         cdr.ResultP++;
1309         if (cdr.ResultP == cdr.ResultC)
1310                 cdr.ResultReady = 0;
1311
1312         CDR_LOG_IO("cdr r1: %02x\n", psxHu8(0x1801));
1313
1314         return psxHu8(0x1801);
1315 }
1316
1317 void cdrWrite1(unsigned char rt) {
1318         CDR_LOG_IO("cdr w1: %02x\n", rt);
1319
1320         switch (cdr.Ctrl & 3) {
1321         case 0:
1322                 break;
1323         case 3:
1324                 cdr.AttenuatorRightToRightT = rt;
1325                 return;
1326         default:
1327                 return;
1328         }
1329
1330         cdr.Cmd = rt;
1331         cdr.OCUP = 0;
1332
1333 #ifdef CDR_LOG_CMD_IRQ
1334         SysPrintf("CD1 write: %x (%s)", rt, CmdName[rt]);
1335         if (cdr.ParamC) {
1336                 SysPrintf(" Param[%d] = {", cdr.ParamC);
1337                 for (i = 0; i < cdr.ParamC; i++)
1338                         SysPrintf(" %x,", cdr.Param[i]);
1339                 SysPrintf("}\n");
1340         } else {
1341                 SysPrintf("\n");
1342         }
1343 #endif
1344
1345         cdr.ResultReady = 0;
1346         cdr.Ctrl |= 0x80;
1347         // cdr.Stat = NoIntr; 
1348         AddIrqQueue(cdr.Cmd, 0x800);
1349
1350         switch (cdr.Cmd) {
1351
1352         case CdlReadN:
1353         case CdlReadS:
1354         case CdlPause:
1355                 StopCdda();
1356                 StopReading();
1357                 break;
1358
1359         case CdlInit:
1360         case CdlReset:
1361                 cdr.Seeked = SEEK_DONE;
1362                 StopCdda();
1363                 StopReading();
1364                 break;
1365
1366         case CdlSetmode:
1367                 CDR_LOG("cdrWrite1() Log: Setmode %x\n", cdr.Param[0]);
1368
1369                 cdr.Mode = cdr.Param[0];
1370
1371                 // Squaresoft on PlayStation 1998 Collector's CD Vol. 1
1372                 // - fixes choppy movie sound
1373                 if( cdr.Play && (cdr.Mode & MODE_CDDA) == 0 )
1374                         StopCdda();
1375                 break;
1376         }
1377 }
1378
1379 unsigned char cdrRead2(void) {
1380         unsigned char ret;
1381
1382         if (cdr.Readed == 0) {
1383                 ret = 0;
1384         } else {
1385                 ret = *pTransfer++;
1386         }
1387
1388         CDR_LOG_IO("cdr r2: %02x\n", ret);
1389         return ret;
1390 }
1391
1392 void cdrWrite2(unsigned char rt) {
1393         CDR_LOG_IO("cdr w2: %02x\n", rt);
1394
1395         switch (cdr.Ctrl & 3) {
1396         case 0:
1397                 if (cdr.ParamC < 8) // FIXME: size and wrapping
1398                         cdr.Param[cdr.ParamC++] = rt;
1399                 return;
1400         case 1:
1401                 cdr.Reg2 = rt;
1402                 setIrq();
1403                 return;
1404         case 2:
1405                 cdr.AttenuatorLeftToLeftT = rt;
1406                 return;
1407         case 3:
1408                 cdr.AttenuatorRightToLeftT = rt;
1409                 return;
1410         }
1411 }
1412
1413 unsigned char cdrRead3(void) {
1414         if (cdr.Ctrl & 0x1)
1415                 psxHu8(0x1803) = cdr.Stat | 0xE0;
1416         else
1417                 psxHu8(0x1803) = cdr.Reg2 | 0xE0;
1418
1419         CDR_LOG_IO("cdr r3: %02x\n", psxHu8(0x1803));
1420         return psxHu8(0x1803);
1421 }
1422
1423 void cdrWrite3(unsigned char rt) {
1424         CDR_LOG_IO("cdr w3: %02x\n", rt);
1425
1426         switch (cdr.Ctrl & 3) {
1427         case 0:
1428                 break; // transfer
1429         case 1:
1430                 cdr.Stat &= ~rt;
1431
1432                 if (rt & 0x40)
1433                         cdr.ParamC = 0;
1434                 return;
1435         case 2:
1436                 cdr.AttenuatorLeftToRightT = rt;
1437                 return;
1438         case 3:
1439                 if (rt & 0x20) {
1440                         memcpy(&cdr.AttenuatorLeftToLeft, &cdr.AttenuatorLeftToLeftT, 4);
1441                         CDR_LOG_I("CD-XA Volume: %02x %02x | %02x %02x\n",
1442                                 cdr.AttenuatorLeftToLeft, cdr.AttenuatorLeftToRight,
1443                                 cdr.AttenuatorRightToLeft, cdr.AttenuatorRightToRight);
1444                 }
1445                 return;
1446         }
1447
1448         if ((rt & 0x80) && cdr.Readed == 0) {
1449                 cdr.Readed = 1;
1450                 pTransfer = cdr.Transfer;
1451
1452                 switch (cdr.Mode & 0x30) {
1453                         case MODE_SIZE_2328:
1454                         case 0x00:
1455                                 pTransfer += 12;
1456                                 break;
1457
1458                         case MODE_SIZE_2340:
1459                                 pTransfer += 0;
1460                                 break;
1461
1462                         default:
1463                                 break;
1464                 }
1465         }
1466 }
1467
1468 void psxDma3(u32 madr, u32 bcr, u32 chcr) {
1469         u32 cdsize;
1470         int size;
1471         u8 *ptr;
1472
1473         CDR_LOG("psxDma3() Log: *** DMA 3 *** %x addr = %x size = %x\n", chcr, madr, bcr);
1474
1475         switch (chcr) {
1476                 case 0x11000000:
1477                 case 0x11400100:
1478                         if (cdr.Readed == 0) {
1479                                 CDR_LOG("psxDma3() Log: *** DMA 3 *** NOT READY\n");
1480                                 break;
1481                         }
1482
1483                         cdsize = (bcr & 0xffff) * 4;
1484
1485                         // Ape Escape: bcr = 0001 / 0000
1486                         // - fix boot
1487                         if( cdsize == 0 )
1488                         {
1489                                 switch (cdr.Mode & (MODE_SIZE_2340|MODE_SIZE_2328)) {
1490                                         case MODE_SIZE_2340: cdsize = 2340; break;
1491                                         case MODE_SIZE_2328: cdsize = 2328; break;
1492                                         default:
1493                                         case MODE_SIZE_2048: cdsize = 2048; break;
1494                                 }
1495                         }
1496
1497
1498                         ptr = (u8 *)PSXM(madr);
1499                         if (ptr == INVALID_PTR) {
1500                                 CDR_LOG("psxDma3() Log: *** DMA 3 *** NULL Pointer!\n");
1501                                 break;
1502                         }
1503
1504                         /*
1505                         GS CDX: Enhancement CD crash
1506                         - Setloc 0:0:0
1507                         - CdlPlay
1508                         - Spams DMA3 and gets buffer overrun
1509                         */
1510                         size = CD_FRAMESIZE_RAW - (pTransfer - cdr.Transfer);
1511                         if (size > cdsize)
1512                                 size = cdsize;
1513                         if (size > 0)
1514                         {
1515                                 memcpy(ptr, pTransfer, size);
1516                         }
1517
1518                         psxCpu->Clear(madr, cdsize / 4);
1519                         pTransfer += cdsize;
1520
1521                         if( chcr == 0x11400100 ) {
1522                                 HW_DMA3_MADR = SWAPu32(madr + cdsize);
1523                                 CDRDMA_INT( (cdsize/4) / 4 );
1524                         }
1525                         else if( chcr == 0x11000000 ) {
1526                                 // CDRDMA_INT( (cdsize/4) * 1 );
1527                                 // halted
1528                                 psxRegs.cycle += (cdsize/4) * 24/2;
1529                                 CDRDMA_INT(16);
1530                         }
1531                         return;
1532
1533                 default:
1534                         CDR_LOG("psxDma3() Log: Unknown cddma %x\n", chcr);
1535                         break;
1536         }
1537
1538         HW_DMA3_CHCR &= SWAP32(~0x01000000);
1539         DMA_INTERRUPT(3);
1540 }
1541
1542 void cdrDmaInterrupt()
1543 {
1544         if (HW_DMA3_CHCR & SWAP32(0x01000000))
1545         {
1546                 HW_DMA3_CHCR &= SWAP32(~0x01000000);
1547                 DMA_INTERRUPT(3);
1548         }
1549 }
1550
1551 static void getCdInfo(void)
1552 {
1553         u8 tmp;
1554
1555         CDR_getTN(cdr.ResultTN);
1556         CDR_getTD(0, cdr.SetSectorEnd);
1557         tmp = cdr.SetSectorEnd[0];
1558         cdr.SetSectorEnd[0] = cdr.SetSectorEnd[2];
1559         cdr.SetSectorEnd[2] = tmp;
1560 }
1561
1562 void cdrReset() {
1563         memset(&cdr, 0, sizeof(cdr));
1564         cdr.CurTrack = 1;
1565         cdr.File = 1;
1566         cdr.Channel = 1;
1567         cdr.Reg2 = 0x1f;
1568         cdr.Stat = NoIntr;
1569         cdr.DriveState = DRIVESTATE_STANDBY;
1570         cdr.StatP = STATUS_ROTATING;
1571         pTransfer = cdr.Transfer;
1572         
1573         // BIOS player - default values
1574         cdr.AttenuatorLeftToLeft = 0x80;
1575         cdr.AttenuatorLeftToRight = 0x00;
1576         cdr.AttenuatorRightToLeft = 0x00;
1577         cdr.AttenuatorRightToRight = 0x80;
1578
1579         getCdInfo();
1580 }
1581
1582 int cdrFreeze(void *f, int Mode) {
1583         u32 tmp;
1584         u8 tmpp[3];
1585
1586         if (Mode == 0 && !Config.Cdda)
1587                 CDR_stop();
1588         
1589         cdr.freeze_ver = 0x63647202;
1590         gzfreeze(&cdr, sizeof(cdr));
1591         
1592         if (Mode == 1) {
1593                 cdr.ParamP = cdr.ParamC;
1594                 tmp = pTransfer - cdr.Transfer;
1595         }
1596
1597         gzfreeze(&tmp, sizeof(tmp));
1598
1599         if (Mode == 0) {
1600                 getCdInfo();
1601
1602                 pTransfer = cdr.Transfer + tmp;
1603
1604                 // read right sub data
1605                 tmpp[0] = btoi(cdr.Prev[0]);
1606                 tmpp[1] = btoi(cdr.Prev[1]);
1607                 tmpp[2] = btoi(cdr.Prev[2]);
1608                 cdr.Prev[0]++;
1609                 ReadTrack(tmpp);
1610
1611                 if (cdr.Play) {
1612                         if (cdr.freeze_ver < 0x63647202)
1613                                 memcpy(cdr.SetSectorPlay, cdr.SetSector, 3);
1614
1615                         Find_CurTrack(cdr.SetSectorPlay);
1616                         if (!Config.Cdda)
1617                                 CDR_play(cdr.SetSectorPlay);
1618                 }
1619
1620                 if ((cdr.freeze_ver & 0xffffff00) != 0x63647200) {
1621                         // old versions did not latch Reg2, have to fixup..
1622                         if (cdr.Reg2 == 0) {
1623                                 SysPrintf("cdrom: fixing up old savestate\n");
1624                                 cdr.Reg2 = 7;
1625                         }
1626                         // also did not save Attenuator..
1627                         if ((cdr.AttenuatorLeftToLeft | cdr.AttenuatorLeftToRight
1628                              | cdr.AttenuatorRightToLeft | cdr.AttenuatorRightToRight) == 0)
1629                         {
1630                                 cdr.AttenuatorLeftToLeft = cdr.AttenuatorRightToRight = 0x80;
1631                         }
1632                 }
1633         }
1634
1635         return 0;
1636 }
1637
1638 void LidInterrupt() {
1639         getCdInfo();
1640         StopCdda();
1641         cdrLidSeekInterrupt();
1642 }