OSDN Git Service

[General] Completely merge upstream 2019-01-11.
[csp-qt/common_source_project-fm7.git] / source / src / vm / scsi_cdrom.cpp
1 /*
2         Skelton for retropc emulator
3
4         Author : Takeda.Toshiya
5         Date   : 2016.03.06-
6
7         [ SCSI CD-ROM drive ]
8 */
9
10 #include "scsi_cdrom.h"
11 #include "../fifo.h"
12
13 #include <algorithm>
14 #include <cctype> 
15
16 #define CDDA_OFF        0
17 #define CDDA_PLAYING    1
18 #define CDDA_PAUSED     2
19
20 #define _SCSI_DEBUG_LOG
21 #define _CDROM_DEBUG_LOG
22
23 // 0-99 is reserved for SCSI_DEV class
24 #define EVENT_CDDA                                              100
25 #define EVENT_CDDA_DELAY_PLAY                   101
26 #define EVENT_CDROM_SEEK_SCSI                   102
27 #define EVENT_CDROM_DELAY_INTERRUPT_ON  103
28 #define EVENT_CDROM_DELAY_INTERRUPT_OFF 104
29 #define EVENT_CDDA_DELAY_STOP                   105
30
31 void SCSI_CDROM::initialize()
32 {
33         SCSI_DEV::initialize();
34         fio_img = new FILEIO();
35         
36         if(44100 % emu->get_sound_rate() == 0) {
37                 mix_loop_num = 44100 / emu->get_sound_rate();
38         } else {
39                 mix_loop_num = 0;
40         }
41         event_cdda = -1;
42         event_cdda_delay_play = -1;
43         event_delay_interrupt = -1;
44         cdda_status = CDDA_OFF;
45         is_cue = false;
46         current_track = 0;
47         read_sectors = 0;
48         for(int i = 0; i < 99; i++) {
49                 memset(track_data_path[i], 0x00, _MAX_PATH * sizeof(_TCHAR));
50         }
51 }
52
53 void SCSI_CDROM::release()
54 {
55         if(fio_img->IsOpened()) {
56                 fio_img->Fclose();
57         }
58         delete fio_img;
59         SCSI_DEV::release();
60 }
61
62 void SCSI_CDROM::reset()
63 {
64         touch_sound();
65         if(event_delay_interrupt != -1) cancel_event(this, event_delay_interrupt);
66         if(event_cdda_delay_play != -1) cancel_event(this, event_cdda_delay_play);
67         if(event_cdda != -1) cancel_event(this, event_cdda);
68         event_cdda = -1;
69         event_cdda_delay_play = -1;
70         event_delay_interrupt = -1;
71         SCSI_DEV::reset();
72         read_mode = false;
73         set_cdda_status(CDDA_OFF);
74         read_sectors = 0;
75         // Q: Does not seek to track 0? 20181118 K.O
76         //current_track = 0;
77
78 }
79
80 void SCSI_CDROM::write_signal(int id, uint32_t data, uint32_t mask)
81 {
82         bool _b = ((data & mask) != 0);
83         switch(id) {
84         case SIG_SCSI_CDROM_CDDA_STOP:
85                 if(cdda_status != CDDA_OFF) {
86                         if(_b) set_cdda_status(CDDA_OFF);
87                 }
88                 break;
89         case SIG_SCSI_CDROM_CDDA_PLAY:
90                 if(cdda_status != CDDA_PLAYING) {
91                         if(_b) set_cdda_status(CDDA_PLAYING);
92                 }
93                 break;
94         case SIG_SCSI_CDROM_CDDA_PAUSE:
95                 if(cdda_status != CDDA_PAUSED) {
96                         if(_b) set_cdda_status(CDDA_PAUSED);
97                 }
98                 break;
99         default:
100                 SCSI_DEV::write_signal(id, data, mask);
101                 break;
102         }
103 }
104
105 uint32_t SCSI_CDROM::read_signal(int id)
106 {
107         switch(id) {
108         case SIG_SCSI_CDROM_PLAYING:
109                 return (cdda_status == CDDA_PLAYING && cdda_interrupt) ? 0xffffffff : 0;
110                 
111         case SIG_SCSI_CDROM_SAMPLE_L:
112                 return (uint32_t)abs(cdda_sample_l);
113                 
114         case SIG_SCSI_CDROM_SAMPLE_R:
115                 return (uint32_t)abs(cdda_sample_r);
116         }
117         return SCSI_DEV::read_signal(id);
118 }
119
120 void SCSI_CDROM::event_callback(int event_id, int err)
121 {
122         switch (event_id) {
123         case EVENT_CDROM_DELAY_INTERRUPT_ON:
124                 write_signals(&outputs_done, 0xffffffff);
125                 event_delay_interrupt = -1;
126                 break;
127         case EVENT_CDROM_DELAY_INTERRUPT_OFF:
128                 write_signals(&outputs_done, 0x00000000);
129                 event_delay_interrupt = -1;
130                 break;
131         case EVENT_CDDA_DELAY_PLAY:
132                 if(cdda_status != CDDA_PLAYING) {
133                         set_cdda_status(CDDA_PLAYING);
134                 }
135                 event_cdda_delay_play = -1;
136                 break;
137         case EVENT_CDROM_SEEK_SCSI:
138                 seek_time = 10.0;
139                 event_cdda_delay_play = -1;
140                 SCSI_DEV::start_command();
141                 break;
142         case EVENT_CDDA:
143                 if(event_cdda_delay_play > -1) return; // WAIT for SEEK COMPLETED
144                 // read 16bit 2ch samples in the cd-da buffer, called 44100 times/sec
145                 
146                 cdda_sample_l = (int)(int16_t)(cdda_buffer[cdda_buffer_ptr + 0] + cdda_buffer[cdda_buffer_ptr + 1] * 0x100);
147                 cdda_sample_r = (int)(int16_t)(cdda_buffer[cdda_buffer_ptr + 2] + cdda_buffer[cdda_buffer_ptr + 3] * 0x100);
148                 // ToDo: CLEAR IRQ Line (for PCE)
149                 if((cdda_buffer_ptr += 4) % 2352 == 0) {
150                         // one frame finished
151                         if(++cdda_playing_frame == cdda_end_frame) {
152                                 // reached to end frame
153                                 #ifdef _CDROM_DEBUG_LOG
154                                 this->out_debug_log(_T("Reaches to the end of track.(FRAME %d). START_FRAME=%d END_FRAME=%d REPEAT=%s INTERRUPT=%s\n"),
155                                                                         cdda_playing_frame, cdda_start_frame, cdda_end_frame, 
156                                                                         (cdda_repeat) ? _T("YES") : _T("NO"), (cdda_interrupt) ? _T("YES") : _T("NO"));
157                                 #endif
158                                 if(cdda_repeat) {
159                                         // reload buffer
160                                         if(is_cue) {
161                                                 fio_img->Fclose();
162                                                 //current_track = 0;
163                                                 //int trk = get_track(cdda_start_frame);
164                                                 int trk = current_track;
165                                                 fio_img->Fseek((cdda_start_frame - toc_table[trk].lba_offset) * 2352, FILEIO_SEEK_SET);
166                                         } else {
167                                                 fio_img->Fseek(cdda_start_frame * 2352, FILEIO_SEEK_SET);
168                                         }
169                                         read_sectors = fio_img->Fread(cdda_buffer, 2352 * sizeof(uint8_t) , array_length(cdda_buffer) / 2352);
170                                         cdda_buffer_ptr = 0;
171                                         cdda_playing_frame = cdda_start_frame;
172                                         access = true;
173                                 } else {
174                                         // Stop
175                                         //if(event_cdda_delay_play >= 0) cancel_event(this, event_cdda_delay_play);
176                                         set_cdda_status(CDDA_OFF);
177                                         //register_event(this, EVENT_CDDA_DELAY_STOP, 1000.0, false, &event_cdda_delay_play);
178                                 }
179                         } else if((cdda_buffer_ptr % 2352) == 0) {
180                                 // refresh buffer
181                                 read_sectors--;
182                                 if(read_sectors <= 0) {
183                                         read_sectors = fio_img->Fread(cdda_buffer, 2352 * sizeof(uint8_t), array_length(cdda_buffer) / 2352);
184                                         cdda_buffer_ptr = 0;
185                                         access = true;
186                                 } else {
187                                 }
188                         }
189                 }
190                 break;
191         case EVENT_CDDA_DELAY_STOP:
192                 if(cdda_interrupt) {
193                         write_signals(&outputs_done, 0xffffffff);
194                 }
195                 set_cdda_status(CDDA_OFF);
196                 event_cdda_delay_play = -1;
197                 break;                  
198         default:
199                 SCSI_DEV::event_callback(event_id, err);
200                 break;
201         }
202 }
203
204 void SCSI_CDROM::set_cdda_status(uint8_t status)
205 {
206         if(status == CDDA_PLAYING) {
207                 if(mix_loop_num == 0) {
208                         if(event_cdda == -1) {
209                                 register_event(this, EVENT_CDDA, 1000000.0 / 44100.0, true, &event_cdda);
210                         }
211                 }
212                 if(cdda_status != CDDA_PLAYING) {
213                         //// Notify to release bus.
214                         write_signals(&outputs_done, 0x00000000);
215                         if(cdda_status == CDDA_OFF) {
216                                 //get_track_by_track_num(current_track); // Re-Play
217                                 //memset(cdda_buffer, 0x00, sizeof(cdda_buffer));
218                                 cdda_playing_frame = cdda_start_frame;
219                                 get_track(cdda_playing_frame);
220                                 cdda_buffer_ptr = 0;
221                         } else if(cdda_status == CDDA_PAUSED) {
222                                 // Unpause
223                                 access = true;
224                         }
225                         touch_sound();
226                         set_realtime_render(this, true);
227                         #ifdef _CDROM_DEBUG_LOG
228                                 this->out_debug_log(_T("Play CDDA from %s.\n"), (cdda_status == CDDA_PAUSED) ? _T("PAUSED") : _T("STOPPED"));
229                         #endif
230                 }
231         } else {
232                 if(event_cdda != -1) {
233                         cancel_event(this, event_cdda);
234                         event_cdda = -1;
235                 }
236                 if(cdda_status == CDDA_PLAYING) {
237                         // Notify to release bus.
238                         write_signals(&outputs_done, 0x00000000);
239                         //if(event_delay_interrupt >= 0) cancel_event(this, event_delay_interrupt);
240                         //register_event(this, EVENT_CDROM_DELAY_INTERRUPT_OFF, 1.0e6 / (44100.0 * 2352), false, &event_delay_interrupt);
241                         if(status == CDDA_OFF) {
242                                 memset(cdda_buffer, 0x00, sizeof(cdda_buffer));
243                                 cdda_buffer_ptr = 0;
244                                 read_sectors = 0;
245                                 //if(is_cue) {
246                                 //      if(fio_img->IsOpened()) fio_img->Fclose();
247                                 //}
248                                 //current_track = 0;
249                         }
250                         touch_sound();
251                         set_realtime_render(this, false);
252                         #ifdef _CDROM_DEBUG_LOG
253                                 this->out_debug_log(_T("%s playing CDDA.\n"), (status == CDDA_PAUSED) ? _T("PAUSE") : _T("STOP"));
254                         #endif
255                 }
256         }
257         cdda_status = status;
258 }
259
260 void SCSI_CDROM::reset_device()
261 {
262         set_cdda_status(CDDA_OFF);
263         SCSI_DEV::reset_device();
264 }
265
266 bool SCSI_CDROM::is_device_ready()
267 {
268         return mounted();
269 }
270
271 int SCSI_CDROM::get_command_length(int value)
272 {
273         switch(value) {
274         case 0xd8:
275         case 0xd9:
276         case 0xda:
277         case 0xdd:
278         case 0xde:
279                 return 10;
280         }
281         return SCSI_DEV::get_command_length(value);
282 }
283
284 void SCSI_CDROM::get_track_by_track_num(int track)
285 {
286         if((track <= 0) || (track >= track_num)) {
287                 if(is_cue) {
288                         if(fio_img->IsOpened()) fio_img->Fclose();
289                 }
290                 //if(track <= 0) current_track = 0;
291                 //if(track >= track_num)current_track = track_num;
292                 current_track = 0;
293                 return;
294         }
295         if(is_cue) {
296                 // ToDo: Apply audio with some codecs.
297                 if((current_track != track) || !(fio_img->IsOpened())){
298                         if(fio_img->IsOpened()) {
299                                 fio_img->Fclose();
300                         }
301                 #ifdef _CDROM_DEBUG_LOG
302                         this->out_debug_log(_T("LOAD TRK #%02d from %s\n"), track, track_data_path[track - 1]);
303                 #endif
304                         
305                         if((track > 0) && (track < 100) && (track < track_num)) {
306                                 if((strlen(track_data_path[track - 1]) <= 0) ||
307                                    !(fio_img->Fopen(track_data_path[track - 1], FILEIO_READ_BINARY))) {
308                                         track = 0;
309                                 }       
310                         } else {
311                                 track = 0;
312                         }
313                 }
314         }
315         current_track = track;
316 }
317
318 // Detect only track num.
319 int SCSI_CDROM::get_track_noop(uint32_t lba)
320 {
321         int track = 0;
322         for(int i = 0; i < track_num; i++) {
323                 if(lba >= toc_table[i].index0) {
324                         track = i;
325                 } else {
326                         break;
327                 }
328         }
329         return track;
330 }       
331
332 int SCSI_CDROM::get_track(uint32_t lba)
333 {
334         int track = 0;
335         track = get_track_noop(lba);
336         if(is_cue) {
337                 get_track_by_track_num(track);
338         } else {
339                 current_track = track;
340         }
341         return track;
342 }
343
344 double SCSI_CDROM::get_seek_time(uint32_t lba)
345 {
346         if(fio_img->IsOpened()) {
347                 uint32_t cur_position = (uint32_t)fio_img->Ftell();
348                 int distance;
349                 if(is_cue) {
350                         int track = 0;
351                         for(int i = 0; i < track_num; i++) {
352                                 if(lba >= toc_table[i].index0) {
353                                         track = i;
354                                 } else {
355                                         break;
356                                 }
357                         }
358                         distance = abs((int)(lba * physical_block_size()) - (int)(cur_position + toc_table[current_track].lba_offset * physical_block_size()));
359                         if(track != current_track) {
360                                 current_track = get_track(lba);
361                         }
362                 } else {
363                         distance = abs((int)(lba * physical_block_size()) - (int)cur_position);
364                 }
365                 double ratio = ((double)distance / 333000.0) / physical_block_size(); // 333000: sectors in media
366                 return max(10, (int)(400000 * 2 * ratio));
367         } else {
368                 return 400000; // 400msec
369         }
370 }
371
372 uint32_t SCSI_CDROM::lba_to_msf(uint32_t lba)
373 {
374         uint8_t m = lba / (60 * 75);
375         lba -= m * (60 * 75);
376         uint8_t s = lba / 75;
377         uint8_t f = lba % 75;
378
379         return ((m / 10) << 20) | ((m % 10) << 16) | ((s / 10) << 12) | ((s % 10) << 8) | ((f / 10) << 4) | ((f % 10) << 0);
380 }
381
382 uint32_t SCSI_CDROM::lba_to_msf_alt(uint32_t lba)
383 {
384         uint32_t ret = 0;
385         ret |= ((lba / (60 * 75)) & 0xff) << 16;
386         ret |= (((lba / 75) % 60) & 0xff) <<  8;
387         ret |= ((lba % 75)        & 0xff) <<  0;
388         return ret;
389 }
390
391 void SCSI_CDROM::start_command()
392 {
393         touch_sound();
394         #ifdef _SCSI_DEBUG_LOG
395 //      this->out_debug_log(_T("[SCSI_DEV:ID=%d] Command: #%02x %02x %02x %02x %02x %02x\n"), scsi_id, command[0], command[1], command[2], command[3], command[4], command[5]);
396         #endif
397         switch(command[0]) {
398         case SCSI_CMD_READ6:
399                 //seek_time = 10;//get_seek_time((command[1] & 0x1f) * 0x10000 + command[2] * 0x100 + command[3]);
400                 seek_time = get_seek_time((command[1] & 0x1f) * 0x10000 + command[2] * 0x100 + command[3]);
401                 set_cdda_status(CDDA_OFF);
402                 if(seek_time > 10.0) {
403                         if(event_cdda_delay_play >= 0) {
404                                 cancel_event(this, event_cdda_delay_play);
405                                 event_cdda_delay_play = -1;
406                         }
407                         register_event(this, EVENT_CDROM_SEEK_SCSI, seek_time - 10.0, false, &event_cdda_delay_play);
408                         return;
409                 } else {
410                         seek_time = 10.0;
411                 }
412                 break;
413         case SCSI_CMD_READ10:
414         case SCSI_CMD_READ12:
415                 seek_time = get_seek_time((command[1] & 0x1f) * 0x10000 + command[2] * 0x100 + command[3]);
416                 set_cdda_status(CDDA_OFF);
417                 if(seek_time > 10.0) {
418                         if(event_cdda_delay_play >= 0) {
419                                 cancel_event(this, event_cdda_delay_play);
420                                 event_cdda_delay_play = -1;
421                         }
422                         register_event(this, EVENT_CDROM_SEEK_SCSI, seek_time - 10.0, false, &event_cdda_delay_play);
423                         return;
424                 } else {
425                         seek_time = 10.0;
426                 }
427                 break;
428                 
429         case SCSI_CMD_MODE_SEL6:
430                 #ifdef _SCSI_DEBUG_LOG
431                         this->out_debug_log(_T("[SCSI_DEV:ID=%d] Command: NEC Read Mode Select 6-byte\n"), scsi_id);
432                 #endif
433                 // start position
434 //              position = (command[1] & 0x1f) * 0x10000 + command[2] * 0x100 + command[3];
435 //              position *= physical_block_size();
436                 position = 0;
437                 // transfer length
438 //              remain = command[4];// * logical_block_size();
439                 remain = 11;
440                 if(remain != 0) {
441                         // clear data buffer
442                         buffer->clear();
443                         // change to data in phase
444                         set_phase_delay(SCSI_PHASE_DATA_OUT, seek_time);
445                 } else {
446                         // transfer length is zero, change to status phase
447                         set_dat(SCSI_STATUS_GOOD);
448                         set_sense_code(SCSI_SENSE_NOSENSE);
449                         set_phase_delay(SCSI_PHASE_STATUS, 10.0);
450                 }
451                 return;
452                 
453         case 0xd8:
454                 #ifdef _SCSI_DEBUG_LOG
455                 this->out_debug_log(_T("[SCSI_DEV:ID=%d] Command: NEC Set Audio Playback Start Position CMD=%02x ARG=%02x %02x %02x %02x\n"), scsi_id, command[9], command[2], command[3], command[4], command[5]);
456                 #endif
457                 if(is_device_ready()) {
458                         if(command[2] == 0 && command[3] == 0 && command[4] == 0) {
459                                 // stop cd-da if all params are zero
460                                 cdda_start_frame = 0;
461                                 cdda_end_frame = toc_table[track_num].index0; // end of disc
462                                 double seek_time = get_seek_time(cdda_end_frame);
463                                 if(is_cue) {
464                                         get_track_by_track_num(track_num);
465                                 }
466                                 //set_cdda_status(CDDA_OFF);
467                                 if(event_cdda_delay_play >= 0) cancel_event(this, event_cdda_delay_play);
468                                 register_event(this, EVENT_CDDA_DELAY_STOP, (seek_time > 10.0) ? seek_time : 10.0, false, &event_cdda_delay_play);
469                         } else {
470                                 uint32_t seek_offset = 0;
471                                 switch(command[9] & 0xc0) {
472                                 case 0x00:
473                                         cdda_start_frame = (command[2] << 16) | (command[3] << 8) | command[4];
474                                         break;
475                                 case 0x40:
476                                         {
477                                                 uint8_t m = FROM_BCD(command[2]);
478                                                 uint8_t s = FROM_BCD(command[3]);
479                                                 uint8_t f = FROM_BCD(command[4]);
480                                                 cdda_start_frame = f + 75 * (s + m * 60);
481                                                 
482                                                 // PCE tries to be clever here and set (start of track + track pregap size) to skip the pregap
483                                                 // (I guess it wants the TOC to have the real start sector for data tracks and the start of the pregap for audio?)
484                                                 int track = get_track(cdda_start_frame);
485                                                 if(cdda_start_frame >= toc_table[track].pregap) {
486                                                         cdda_start_frame -= toc_table[track].pregap;
487                                                 }
488                                                 if(cdda_start_frame < toc_table[track].index0) {
489                                                         cdda_start_frame = toc_table[track].index0; // don't play pregap
490                                                 } else if(cdda_start_frame > max_logical_block) {
491                                                         cdda_start_frame = 0;
492                                                 }
493                                         }
494                                         break;
495                                 case 0x80:
496                                         {
497                                                 int8_t track = FROM_BCD(command[2] - 1);
498                                                 cdda_start_frame = toc_table[track].index1;
499                                                 if(cdda_start_frame >= toc_table[track].pregap) {
500                                                         cdda_start_frame -= toc_table[track].pregap;
501                                                 }
502                                         }
503                                         break;
504                                 default:
505                                         cdda_start_frame = 0;
506                                         break;
507                                 }
508 //                              if(cdda_status == CDDA_PAUSED) {
509 //                                      cdda_end_frame = toc_table[track_num].index0; // end of disc
510 //                                      set_cdda_status(CDDA_OFF);
511 //                              } else
512                                 double delay_time = get_seek_time(cdda_start_frame);
513                                 if((command[1] & 3) != 0) {
514                                         if((is_cue) && (current_track != track_num)){
515                                                 get_track_by_track_num(track_num);
516                                         }
517                                         cdda_end_frame = toc_table[track_num].index0; // end of disc
518                                         double seek_time = get_seek_time(cdda_start_frame);
519                                         if(event_cdda_delay_play >= 0) {
520                                                 cancel_event(this, event_cdda_delay_play);
521                                                 event_cdda_delay_play = -1;
522                                         }
523                                         //set_cdda_status(CDDA_PLAYING);
524                                         register_event(this, EVENT_CDROM_SEEK_SCSI, seek_time, false, &event_cdda_delay_play);
525                                 } else {
526                                         uint32_t _sframe = cdda_start_frame;
527                                         //cdda_end_frame = toc_table[get_track(_sframe) + 1].index1; // end of this track
528                                         //cdda_end_frame = toc_table[get_track(_sframe)].index1; // end of this track
529                                         set_cdda_status(CDDA_PAUSED);
530                                 }
531                                 cdda_repeat = false;
532                                 cdda_interrupt = ((command[1] & 3) == 2);
533                                 
534                                 // read buffer
535                                 //double delay_time = 10.0;
536 #if 1
537                                 if(is_cue) {
538                                         //if(cdda_start_frame > 150) cdda_start_frame = cdda_start_frame - 150;
539                                         fio_img->Fseek((cdda_start_frame - toc_table[current_track].index0) * 2352, FILEIO_SEEK_SET);
540                                 } else {
541                                         fio_img->Fseek(cdda_start_frame * 2352, FILEIO_SEEK_SET);
542                                 }
543 #endif
544                                 read_sectors = fio_img->Fread(cdda_buffer, 2352 * sizeof(uint8_t), array_length(cdda_buffer) / 2352);
545                                 cdda_buffer_ptr = 0;
546                                 cdda_playing_frame = cdda_start_frame;
547                                 access = true;
548                                 
549                                 // change to status phase
550                                 set_dat(SCSI_STATUS_GOOD);
551                                 // From Mame 0.203
552                                 if(event_delay_interrupt >= 0) cancel_event(this, event_delay_interrupt);
553                                 register_event(this, EVENT_CDROM_DELAY_INTERRUPT_ON, delay_time, false, &event_delay_interrupt);
554                                 //set_phase_delay(SCSI_PHASE_STATUS, delay_time + 10.0);
555                                 //write_signals(&outputs_done, 0xffffffff);
556                                 set_phase_delay(SCSI_PHASE_STATUS, 10.0);
557                                 return;
558                         }
559                 }
560                 // change to status phase
561                 set_dat(is_device_ready() ? SCSI_STATUS_GOOD : SCSI_STATUS_CHKCOND);
562                 // From Mame 0.203
563                 //if(is_device_ready()) write_signals(&outputs_done, 0xffffffff);
564                 set_phase_delay(SCSI_PHASE_STATUS, 10.0);
565
566                 return;
567                 
568         case 0xd9:
569                 #ifdef _SCSI_DEBUG_LOG
570                 this->out_debug_log(_T("[SCSI_DEV:ID=%d] Command: NEC Set Audio Playback End Position CMD=%02x ARG=%02x %02x %02x %02x\n"), scsi_id, command[9], command[2], command[3], command[4], command[5]);
571                 #endif
572                 if(is_device_ready()) {
573                         
574                         switch(command[9] & 0xc0) {
575                         case 0x00:
576                                 cdda_end_frame = (command[3] << 16) | (command[4] << 8) | command[5];
577                                 break;
578                         case 0x40:
579                                 {
580                                         uint8_t m = FROM_BCD(command[2]);
581                                         uint8_t s = FROM_BCD(command[3]);
582                                         uint8_t f = FROM_BCD(command[4]);
583                                         cdda_end_frame = f + 75 * (s + m * 60);
584                                         
585                                         // PCE tries to be clever here and set (start of track + track pregap size) to skip the pregap
586                                         // (I guess it wants the TOC to have the real start sector for data tracks and the start of the pregap for audio?)
587                                         
588 //                                      int track = get_track(cdda_start_frame);
589                                         int track = current_track;
590                                         cdda_playing_frame = cdda_start_frame;
591 //                                      if(is_cue) {
592 //                                              fio_img->Fseek((cdda_start_frame - toc_table[current_track].lba_offset) * 2352, FILEIO_SEEK_SET);
593 //                                      } else {
594 //                                              fio_img->Fseek(cdda_start_frame * 2352, FILEIO_SEEK_SET);
595 //                                      }
596                                         //read_sectors = fio_img->Fread(cdda_buffer, 2352 * sizeof(uint8_t), array_length(cdda_buffer) / 2352);
597
598                                         if(cdda_end_frame > toc_table[track + 1].index1 && (cdda_end_frame - toc_table[track].pregap) <= toc_table[track + 1].index1) {
599                                                 cdda_end_frame = toc_table[track + 1].index1;
600                                         }
601                                         cdda_buffer_ptr = 0;
602                                 }
603                                 break;
604                         case 0x80:
605                                 {
606                                         int _track = FROM_BCD(command[2]) - 1;
607                                         if(_track >= 0) {
608                                                 cdda_end_frame = toc_table[_track].index0;
609                                                 if(is_cue) {
610                                                         if(current_track != _track) {
611                                                                 get_track_by_track_num(_track);
612                                                                 cdda_start_frame = toc_table[_track].index0;
613                                                                 cdda_end_frame = toc_table[_track].lba_size + toc_table[_track].lba_offset;
614                                                                 cdda_playing_frame = cdda_start_frame;
615                                                                 if(is_cue) {
616                                                                         fio_img->Fseek((cdda_start_frame - toc_table[current_track].lba_offset) * 2352, FILEIO_SEEK_SET);
617                                                                 } else {
618                                                                         fio_img->Fseek(cdda_start_frame * 2352, FILEIO_SEEK_SET);
619                                                                 }
620                                                                 read_sectors = fio_img->Fread(cdda_buffer, 2352 * sizeof(uint8_t), array_length(cdda_buffer) / 2352);
621                                                                 cdda_buffer_ptr = 0;
622                                                         }
623                                                 }
624                                         }
625                                 }
626                                 break;
627                         default:
628                                 break; // ToDo
629                         }
630                         if((command[1] & 3) != 0) {
631                                 cdda_repeat = ((command[1] & 3) == 1);
632                                 cdda_interrupt = ((command[1] & 3) == 2);
633                                 
634                                 if(event_cdda_delay_play >= 0) cancel_event(this, event_cdda_delay_play);
635                                 register_event(this, EVENT_CDDA_DELAY_PLAY, 10.0, false, &event_cdda_delay_play);
636                                 //set_cdda_status(CDDA_PLAYING);
637                         } else {
638                                 set_cdda_status(CDDA_OFF);
639                                 cdda_start_frame = toc_table[track_num].index0;;
640                                 cdda_end_frame = toc_table[track_num].index1; // end of disc
641                                 double seek_time = get_seek_time(cdda_start_frame);
642                                 //double seek_time = 10.0;
643                                 get_track_by_track_num(track_num); // END OF DISC
644
645                                 set_dat(is_device_ready() ? SCSI_STATUS_GOOD : SCSI_STATUS_CHKCOND);
646 //                              if(event_cdda_delay_play >= 0) cancel_event(this, event_cdda_delay_play);
647 //                              register_event(this, EVENT_CDDA_DELAY_STOP, (seek_time > 10.0) ? seek_time : 10.0, false, &event_cdda_delay_play);
648                                 if(is_device_ready()) {
649                                         if(event_delay_interrupt >= 0) {
650                                                 cancel_event(this, event_delay_interrupt);
651                                                 event_delay_interrupt = -1;
652                                         }
653                                         register_event(this, EVENT_CDROM_DELAY_INTERRUPT_ON, (seek_time > 10.0) ? (seek_time + 10.0) : (10.0 + 10.0), false, &event_delay_interrupt);
654                                 }
655                                 set_phase_delay(SCSI_PHASE_STATUS, (seek_time > 10.0) ? (seek_time + 10.0) : (10.0 + 10.0));
656                                 return;
657                         }
658                 }
659                 // change to status phase
660                 set_dat(is_device_ready() ? SCSI_STATUS_GOOD : SCSI_STATUS_CHKCOND);
661                 if(is_device_ready()) {
662                         write_signals(&outputs_done, 0xffffffff);
663                         //if(event_delay_interrupt >= 0) cancel_event(this, event_delay_interrupt);
664                         //register_event(this, EVENT_CDROM_DELAY_INTERRUPT_ON, 10.0, false, &event_delay_interrupt);
665
666                 }
667                 set_phase_delay(SCSI_PHASE_STATUS, 10.0);
668                 return;
669                 
670         case 0xda:
671                 #ifdef _SCSI_DEBUG_LOG
672                         this->out_debug_log(_T("[SCSI_DEV:ID=%d] Command: NEC Pause\n"), scsi_id);
673                 #endif
674                 if(is_device_ready()) {
675                         if(cdda_status == CDDA_PLAYING) {
676                                 set_cdda_status(CDDA_PAUSED);
677                         }
678                 }
679                 // change to status phase
680                 set_dat(is_device_ready() ? SCSI_STATUS_GOOD : SCSI_STATUS_CHKCOND);
681                 if(is_device_ready()) write_signals(&outputs_done, 0xffffffff);
682                 set_phase_delay(SCSI_PHASE_STATUS, 10.0);
683                 return;
684                 
685         case 0xdd:
686                 #ifdef _SCSI_DEBUG_LOG
687                         this->out_debug_log(_T("[SCSI_DEV:ID=%d] Command: NEC Read Sub Channel Q\n"), scsi_id);
688                 #endif
689                 if(is_device_ready()) {
690                         // create track info
691                         uint32_t frame = (cdda_status == CDDA_OFF) ? cdda_start_frame : cdda_playing_frame;
692                         uint32_t msf_abs = lba_to_msf_alt(frame);
693                         int track;
694                         double delay_time = 10.0;
695                         track = current_track;
696                         if((cdda_status == CDDA_OFF) && (toc_table[track].is_audio)) { // OK? (or force ERROR) 20181120 K.O
697                                 //set_cdda_status(CDDA_PLAYING);
698                                 delay_time = get_seek_time(frame);
699                                 //delay_time = 10.0;
700                                 if(event_cdda_delay_play >= 0) {
701                                         cancel_event(this, event_cdda_delay_play);
702                                         event_cdda_delay_play = -1;
703                                 }
704                                 register_event(this, EVENT_CDDA_DELAY_PLAY, delay_time, false, &event_cdda_delay_play);
705                         }
706                         uint32_t msf_rel = lba_to_msf_alt(frame - toc_table[track].index0);
707                         buffer->clear();
708                         buffer->write((cdda_status == CDDA_PLAYING) ? 0x00 : (cdda_status == CDDA_PAUSED) ? 0x02 : 0x03);
709                         buffer->write(0x01 | (toc_table[track].is_audio ? 0x00 : 0x40));
710                         buffer->write(TO_BCD(track + 1));               // Track
711                         buffer->write(0x01);                            // Index
712                         buffer->write(TO_BCD((msf_rel >> 16) & 0xff));  // M (relative)
713                         buffer->write(TO_BCD((msf_rel >>  8) & 0xff));  // S (relative)
714                         buffer->write(TO_BCD((msf_rel >>  0) & 0xff));  // F (relative)
715                         buffer->write(TO_BCD((msf_abs >> 16) & 0xff));  // M (absolute)
716                         buffer->write(TO_BCD((msf_abs >>  8) & 0xff));  // S (absolute)
717                         buffer->write(TO_BCD((msf_abs >>  0) & 0xff));  // F (absolute)
718                         // transfer length
719                         remain = buffer->count();
720                         // set first data
721                         set_dat(buffer->read());
722                         // change to data in phase
723                         set_phase_delay(SCSI_PHASE_DATA_IN, 10.0);
724                 } else {
725                         // change to status phase
726                         set_dat(is_device_ready() ? SCSI_STATUS_GOOD : SCSI_STATUS_CHKCOND);
727                         set_phase_delay(SCSI_PHASE_STATUS, 10.0);
728                 }
729                 return;
730                 
731         case 0xde:
732                 #ifdef _SCSI_DEBUG_LOG
733                         this->out_debug_log(_T("[SCSI_DEV:ID=%d] Command: NEC Get Dir Info\n"), scsi_id);
734                 #endif
735                 if(is_device_ready()) {
736                         buffer->clear();
737                 #ifdef _SCSI_DEBUG_LOG
738                         this->out_debug_log(_T("[SCSI_DEV:ID=%d] CMD=%02x ARG=%02x \n"), scsi_id, command[1], command[2]);
739                 #endif
740                         switch(command[1]) {
741                         case 0x00:      /* Get first and last track numbers */
742                                 buffer->write(TO_BCD(1));
743                                 buffer->write(TO_BCD(track_num));
744                                 // PC-8801 CD BIOS invites 4 bytes ?
745                                 buffer->write(0);
746                                 buffer->write(0);
747                                 break;
748                         case 0x01:      /* Get total disk size in MSF format */
749                                 {
750                                         uint32_t msf = lba_to_msf(toc_table[track_num].index0 + 150);
751                                         buffer->write((msf >> 16) & 0xff);
752                                         buffer->write((msf >>  8) & 0xff);
753                                         buffer->write((msf >>  0) & 0xff);
754                                         // PC-8801 CD BIOS invites 4 bytes ?
755                                         buffer->write(0);
756                                 }
757                                 break;
758                         case 0x02:      /* Get track information */
759                                 if(command[2] == 0xaa) {
760                                         uint32_t msf = lba_to_msf(toc_table[track_num].index0 + 150);
761                                         buffer->write((msf >> 16) & 0xff);
762                                         buffer->write((msf >>  8) & 0xff);
763                                         buffer->write((msf >>  0) & 0xff);
764                                         buffer->write(0x04); // correct ?
765                                 } else {
766                                         int track = max(FROM_BCD(command[2]), 1);
767                                         uint32_t frame = toc_table[track].index0;
768                                         // PCE wants the start sector for data tracks to *not* include the pregap
769                                         if(!toc_table[track].is_audio) {
770                                                 frame += toc_table[track].pregap;
771                                         }
772                                         get_track_by_track_num(track);
773                                         
774                                         uint32_t msf = lba_to_msf(toc_table[track].index1 + 150);
775                                         buffer->write((msf >> 16) & 0xff); // M
776                                         buffer->write((msf >>  8) & 0xff); // S
777                                         buffer->write((msf >>  0) & 0xff); // F
778                                         buffer->write(toc_table[track].is_audio ? 0x00 : 0x04);
779                                 }
780                                 break;
781                         }
782                         // transfer length
783                         remain = buffer->count();
784                         // set first data
785                         set_dat(buffer->read());
786                         // change to data in phase
787                         set_phase_delay(SCSI_PHASE_DATA_IN, 10.0);
788                 } else {
789                         // change to status phase
790                         set_dat(is_device_ready() ? SCSI_STATUS_GOOD : SCSI_STATUS_CHKCOND);
791                         set_phase_delay(SCSI_PHASE_STATUS, 10.0);
792                 }
793                 return;
794         case 0xff:
795                 // End of List
796                 set_dat(SCSI_STATUS_CHKCOND);
797                 return;
798         }
799         
800         // start standard command
801         SCSI_DEV::start_command();
802 }
803
804 bool SCSI_CDROM::read_buffer(int length)
805 {
806         if(!fio_img->IsOpened()) {
807                 set_sense_code(SCSI_SENSE_NOTREADY);
808                 return false;
809         }
810         uint32_t offset = (uint32_t)(position % 2352);
811
812         if(is_cue) {
813                 // ToDo: Need seek wait.
814                 #ifdef _CDROM_DEBUG_LOG
815                         this->out_debug_log(_T("Seek to LBA %d\n"), position / 2352);
816                 #endif
817                 if(fio_img->Fseek(((long)position - (long)(toc_table[current_track].lba_offset * 2352)), FILEIO_SEEK_SET) != 0) {
818                         set_sense_code(SCSI_SENSE_ILLGLBLKADDR); //SCSI_SENSE_SEEKERR
819                         #ifdef _SCSI_DEBUG_LOG
820                                 this->out_debug_log(_T("[SCSI_DEV:ID=%d] Error on reading (ILLGLBLKADDR) at line %d\n"), scsi_id, __LINE__);
821                         #endif
822                         return false;
823                 }
824         } else {
825                 if(fio_img->Fseek((long)position, FILEIO_SEEK_SET) != 0) {
826                         set_sense_code(SCSI_SENSE_ILLGLBLKADDR); //SCSI_SENSE_SEEKERR
827                         #ifdef _SCSI_DEBUG_LOG
828                                 this->out_debug_log(_T("[SCSI_DEV:ID=%d] Error on reading (ILLGLBLKADDR) at line %d\n"), scsi_id, __LINE__);
829                         #endif
830                         return false;
831                 }
832         }
833         while(length > 0) {
834                 uint8_t tmp_buffer[2352];
835 //              int tmp_length = min(length, (int)sizeof(tmp_buffer));
836                 int tmp_length = 2352 - offset;
837                 
838                 if(fio_img->Fread(tmp_buffer, tmp_length, 1) != 1) {
839                         #ifdef _SCSI_DEBUG_LOG
840                         this->out_debug_log(_T("[SCSI_DEV:ID=%d] Error on reading (ILLGLBLKADDR) at line %d\n"), scsi_id, __LINE__);
841                         #endif
842                         
843                         set_sense_code(SCSI_SENSE_ILLGLBLKADDR); //SCSI_SENSE_NORECORDFND
844                         return false;
845                 }
846                 for(int i = 0; i < tmp_length; i++) {
847                         if(offset >= 16 && offset < 16 + logical_block_size()) {
848                                 int value = tmp_buffer[i];
849                                 buffer->write(value);
850                                 length--;
851                         }
852                         position++;
853                         offset = (offset + 1) % 2352;
854                 }
855                 access = true;
856         }
857         // Is This right? 20181120 K.O
858         //write_signals(&outputs_done, 0xffffffff); // Maybe don't need "DONE SIGNAL" with reading DATA TRACK. 20181207 K.O
859         set_sense_code(SCSI_SENSE_NOSENSE);
860         return true;
861 }
862
863 bool SCSI_CDROM::write_buffer(int length)
864 {
865         for(int i = 0; i < length; i++) {
866                 int value = buffer->read();
867                 if(command[0] == SCSI_CMD_MODE_SEL6) {
868                         if(i == 4) {
869                                 #ifdef _SCSI_DEBUG_LOG
870                                         this->out_debug_log(_T("[SCSI_DEV:ID=%d] NEC Read Mode = %02X\n"), scsi_id, value);
871                                 #endif
872                                 read_mode = (value != 0);
873                         } else if(i == 10) {
874                                 #ifdef _SCSI_DEBUG_LOG
875                                         this->out_debug_log(_T("[SCSI_DEV:ID=%d] NEC Retry Count = %02X\n"), scsi_id, value);
876                                 #endif
877                         }
878                 }
879                 position++;
880         }
881         set_sense_code(SCSI_SENSE_NOSENSE);
882         return true;
883 }
884
885 int get_frames_from_msf(const char *string)
886 {
887         const char *ptr = string;
888         int frames[3] = {0};
889         int index = 0;
890         
891         while(1) {
892                 if(*ptr >= '0' && *ptr <= '9') {
893                         frames[index] = frames[index] * 10 + (*ptr - '0');
894                 } else if(*ptr == ':') {
895                         if(++index == 3) {
896                                 // abnormal data
897                                 break;
898                         }
899                 } else if(*ptr == '\r' || *ptr == '\n' || *ptr == '\0') {
900                         // end of line
901                         break;
902                 }
903                 ptr++;
904         }
905         return (frames[0] * 60 + frames[1]) * 75 + frames[2]; // 75frames/sec
906 }
907
908 int hexatoi(const char *string)
909 {
910         const char *ptr = string;
911         int value = 0;
912         
913         while(1) {
914                 if(*ptr >= '0' && *ptr <= '9') {
915                         value = value * 16 + (*ptr - '0');
916                 } else if(*ptr >= 'a' && *ptr <= 'f') {
917                         value = value * 16 + (*ptr - 'a' + 10);
918                 } else if(*ptr >= 'A' && *ptr <= 'F') {
919                         value = value * 16 + (*ptr - 'A' + 10);
920                 } else if(*ptr == '\r' || *ptr == '\n' || *ptr == '\0') {
921                         break;
922                 }
923                 ptr++;
924         }
925         return value;
926 }
927
928 #include <string>
929
930 bool SCSI_CDROM::open_cue_file(const _TCHAR* file_path)
931 {
932         std::string line_buf;
933         std::string line_buf_shadow;
934         std::string image_tmp_data_path;
935
936         _TCHAR full_path_cue[_MAX_PATH];
937         size_t ptr;
938         int line_count = 0;
939         int slen;
940         int nr_current_track = 0;
941         FILEIO* fio = new FILEIO();
942         if(fio == NULL) return false;
943
944         memset(full_path_cue, 0x00, sizeof(full_path_cue));
945         image_tmp_data_path.clear();
946
947         get_long_full_path_name(file_path, full_path_cue, sizeof(full_path_cue));
948         
949         _TCHAR *parent_dir = get_parent_dir(full_path_cue);
950
951         size_t _arg1_ptr;
952         size_t _arg2_ptr;
953         size_t _arg2_ptr_s;
954         size_t _arg3_ptr;
955         size_t _arg3_ptr_s;
956
957         std::string _arg1;
958         std::string _arg2;
959         std::string _arg3;
960         
961         if(fio->Fopen(file_path, FILEIO_READ_ASCII)) { // ToDo: Support not ASCII cue file (i.e. SJIS/UTF8).20181118 K.O
962                 line_buf.clear();
963                 for(int i = 0; i < 100; i++) {
964                         memset(&(track_data_path[i][0]), 0x00, _MAX_PATH * sizeof(_TCHAR));
965                 }
966                 int _c;
967                 bool is_eof = false;
968                 int sptr = 0;
969                 while(1) {
970                         line_buf.clear();
971                         int _np = 0;
972                         _c = EOF;
973                         do {
974                                 _c = fio->Fgetc();
975                                 if((_c == '\0') || (_c == '\n') || (_c == EOF)) break;;
976                                 if(_c != '\r') line_buf.push_back((char)_c);
977                         } while(1);
978                         if(_c == EOF) is_eof = true;
979                         slen = (int)line_buf.length();
980                         if(slen <= 0) goto _n_continue;
981                         // Trim head of Space or TAB
982                         ptr = 0;
983                         sptr = 0;
984                         // Tokenize
985                         _arg1.clear();
986                         _arg2.clear();
987                         _arg3.clear();
988                         
989                         ptr = line_buf.find_first_not_of((const char*)" \t");
990                         if(ptr == std::string::npos) {
991                                 goto _n_continue;
992                         }
993                         // Token1
994                         line_buf_shadow = line_buf.substr(ptr);
995
996                         _arg1_ptr = line_buf_shadow.find_first_of((const char *)" \t");
997                         _arg1 = line_buf_shadow.substr(0, _arg1_ptr);
998                         _arg2 = line_buf_shadow.substr(_arg1_ptr);
999                         std::transform(_arg1.begin(), _arg1.end(), _arg1.begin(),
1000                                                    [](unsigned char c) -> unsigned char{ return std::toupper(c); });
1001
1002                         _arg2_ptr = _arg2.find_first_not_of((const char *)" \t");
1003
1004                         if(_arg2_ptr != std::string::npos) {
1005                                 _arg2 = _arg2.substr(_arg2_ptr);
1006                         }
1007
1008                         if(_arg1 == "REM") {
1009                                 // REM
1010                                 goto _n_continue;
1011                         } else if(_arg1 == "FILE") {
1012                                 _arg2_ptr = _arg2.find_first_of((const char *)"\"") + 1;
1013                                 if(_arg2_ptr == std::string::npos) goto _n_continue;
1014                                 
1015                                 _arg2 = _arg2.substr(_arg2_ptr);
1016                                 _arg3_ptr = _arg2.find_first_of((const char *)"\"");
1017                                 if(_arg3_ptr == std::string::npos) goto _n_continue;
1018                                 _arg2 = _arg2.substr(0, _arg3_ptr);
1019                                 
1020                                 image_tmp_data_path.clear();
1021                                 image_tmp_data_path = std::string(parent_dir);
1022                                 image_tmp_data_path.append(_arg2);
1023                                 
1024                                 #ifdef _CDROM_DEBUG_LOG
1025                                         this->out_debug_log(_T("**FILE %s\n"), image_tmp_data_path.c_str());
1026                                 #endif
1027                                 goto _n_continue; // ToDo: Check ARG2 (BINARY etc..) 20181118 K.O
1028                         } else if(_arg1 == "TRACK") {
1029                                 _arg2_ptr_s = _arg2.find_first_of((const char *)" \t");
1030                                 
1031                                 _arg3 = _arg2.substr(_arg2_ptr_s);
1032                                 _arg2 = _arg2.substr(0, _arg2_ptr_s);
1033                                 _arg3_ptr = _arg3.find_first_not_of((const char *)" \t");
1034                                 int _nr_num = atoi(_arg2.c_str());
1035                                 
1036                                 // Set image file
1037                                 if((_nr_num > 0) && (_nr_num < 100) && (_arg3_ptr != std::string::npos)) {
1038                                         nr_current_track = _nr_num;
1039                                         _arg3 = _arg3.substr(_arg3_ptr);
1040                                         
1041                                         memset(track_data_path[_nr_num - 1], 0x00, sizeof(_TCHAR) * _MAX_PATH);
1042                                         strncpy((char *)(track_data_path[_nr_num - 1]), image_tmp_data_path.c_str(), _MAX_PATH);
1043                                         
1044                                         _arg3_ptr_s = _arg3.find_first_of((const char *)" \t\n");
1045                                         _arg3.substr(0, _arg3_ptr_s);
1046                                         
1047                                         std::transform(_arg3.begin(), _arg3.end(), _arg3.begin(),
1048                                                                    [](unsigned char c) -> unsigned char{ return std::toupper(c); });
1049                                         
1050                                         toc_table[nr_current_track].is_audio = false;
1051                                         toc_table[nr_current_track].index0 = 0;
1052                                         toc_table[nr_current_track].index1 = 0;
1053                                         toc_table[nr_current_track].pregap = 0;
1054                                                 
1055                                         if(_arg3.compare("AUDIO") == 0) {
1056                                                 toc_table[nr_current_track].is_audio = true;
1057                                         } else if(_arg3.compare("MODE1/2352") == 0) {
1058                                                 toc_table[nr_current_track].is_audio = false;
1059                                         } else {
1060                                                 // ToDo:  another type
1061                                         }
1062                                         if(track_num < (_nr_num + 1)) track_num = _nr_num + 1;
1063                                 } else {
1064                                         // ToDo: 20181118 K.Ohta
1065                                         nr_current_track = 0;
1066                                 }
1067                                 goto _n_continue;
1068                         } else if(_arg1 == "INDEX") {
1069                                 
1070                                 if((nr_current_track > 0) && (nr_current_track < 100)) {
1071                                         _arg2_ptr_s = _arg2.find_first_of((const char *)" \t");
1072                                         if(_arg2_ptr_s == std::string::npos) goto _n_continue;
1073                                         
1074                                         _arg3 = _arg2.substr(_arg2_ptr_s);
1075                                         _arg2 = _arg2.substr(0, _arg2_ptr_s);
1076                                         _arg3_ptr = _arg3.find_first_not_of((const char *)" \t");
1077                                         if(_arg3_ptr == std::string::npos) goto _n_continue;
1078
1079                                         _arg3 = _arg3.substr(_arg3_ptr);
1080                                         _arg3_ptr_s = _arg3.find_first_of((const char *)" \t");
1081                                         _arg3.substr(0, _arg3_ptr_s);
1082                                         int index_type = atoi(_arg2.c_str());
1083
1084                                         switch(index_type) {
1085                                         case 0:
1086                                                 toc_table[nr_current_track].index0 = get_frames_from_msf(_arg3.c_str());
1087                                                 break;
1088                                         case 1:
1089                                                 toc_table[nr_current_track].index1 = get_frames_from_msf(_arg3.c_str());
1090                                                 break;
1091                                         default:
1092                                                 break;
1093                                         }
1094                                         goto _n_continue;
1095                                 } else {
1096                                         goto _n_continue;
1097                                 }
1098                         } else if(_arg1 == "PREGAP") {
1099                                 if((nr_current_track > 0) && (nr_current_track < 100)) {
1100                                         _arg2_ptr_s = _arg2.find_first_of((const char *)" \t");
1101                                         _arg2 = _arg2.substr(0, _arg2_ptr_s - 1);
1102                                         
1103                                         toc_table[nr_current_track].pregap = get_frames_from_msf(_arg2.c_str());
1104                                         goto _n_continue;
1105                                 } else {
1106                                         goto _n_continue;
1107                                 }
1108                         }
1109                 _n_continue:
1110                         if(is_eof) break;
1111                         line_buf.clear();
1112                         continue;
1113                 }
1114                 // Finish
1115                 max_logical_block = 0;
1116                 if(track_num > 0) {
1117                         toc_table[0].lba_offset = 0;
1118                         toc_table[0].lba_size = 0;
1119                         toc_table[0].index0 = toc_table[0].index1 = toc_table[0].pregap = 0;
1120                         // P1: Calc
1121                         int _n = 0;
1122                         for(int i = 1; i < track_num; i++) {
1123
1124                                 if(fio_img->IsOpened()) {
1125                                         fio_img->Fclose();
1126                                 }
1127                                 if(toc_table[i].index1 != 0) {
1128                                         toc_table[i].index0 = toc_table[i].index0 + max_logical_block;
1129                                         toc_table[i].index1 = toc_table[i].index1 + max_logical_block;
1130                                         if(toc_table[i].index0 != max_logical_block) {
1131                                                 if(toc_table[i].pregap == 0) {
1132                                                         toc_table[i].pregap = toc_table[i].index1 - toc_table[i].index0;
1133                                                 }
1134                                         }
1135                                 } else {
1136                                         toc_table[i].index1 = toc_table[i].index1 + max_logical_block;
1137                                         if(toc_table[i].index0 == 0) {
1138                                                 toc_table[i].index0 = toc_table[i].index1 - toc_table[i].pregap;
1139                                         } else {
1140                                                 toc_table[i].index0 = toc_table[i].index0 + max_logical_block;
1141                                                 if(toc_table[i].pregap == 0) {
1142                                                         toc_table[i].pregap = toc_table[i].index1 - toc_table[i].index0;
1143                                                 }
1144                                         }
1145                                 }
1146                                 // Even...
1147                                 if(toc_table[i].pregap <= 0) {
1148                                         toc_table[i].pregap = 150; // Default PREGAP must be 2Sec. From OoTake.(Only with PCE? Not with FM-Towns?)
1149                                 }
1150
1151                                 _n = 0;
1152                                 if(strlen(track_data_path[i - 1]) > 0) {
1153                                         if(fio_img->Fopen(track_data_path[i - 1], FILEIO_READ_BINARY)) {
1154                                                 if((_n = fio_img->FileLength() / 2352) > 0) {
1155                                                         max_logical_block += _n;
1156                                                 } else {
1157                                                         _n = 0;
1158                                                 }
1159                                                 fio_img->Fclose();
1160                                         }
1161                                 }
1162                                 toc_table[i].lba_size = _n;
1163                                 toc_table[i].lba_offset = max_logical_block - _n;
1164
1165                                 
1166                                 //#ifdef _CDROM_DEBUG_LOG
1167                                 this->out_debug_log(_T("TRACK#%02d TYPE=%s PREGAP=%d INDEX0=%d INDEX1=%d LBA_SIZE=%d LBA_OFFSET=%d PATH=%s\n"),
1168                                                                         i, (toc_table[i].is_audio) ? _T("AUDIO") : _T("MODE1/2352"),
1169                                                                         toc_table[i].pregap, toc_table[i].index0, toc_table[i].index1,
1170                                                                         toc_table[i].lba_size, toc_table[i].lba_offset, track_data_path[i - 1]);
1171                                 //#endif
1172                         }
1173                         toc_table[0].index0 = toc_table[0].index1 = toc_table[0].pregap = 0;
1174 //                      toc_table[track_num].index0 = toc_table[track_num].index1 = max_logical_block;
1175 //                      toc_table[track_num].lba_offset = max_logical_block;
1176 //                      toc_table[track_num].lba_size = 0;
1177                         
1178                 }
1179                 fio->Fclose();
1180         }
1181         delete fio;
1182
1183         is_cue = false;
1184         if(track_num > 0) is_cue = true;
1185         // Not Cue FILE.
1186         return is_cue;
1187 }
1188
1189 void SCSI_CDROM::open(const _TCHAR* file_path)
1190 {
1191         _TCHAR img_file_path[_MAX_PATH];
1192         
1193         close();
1194         
1195         if(check_file_extension(file_path, _T(".cue"))) {
1196 #if 1
1197                 is_cue = false;
1198                 current_track = 0;
1199                 open_cue_file(file_path);
1200 #else
1201                 // get image file name
1202                 my_stprintf_s(img_file_path, _MAX_PATH, _T("%s.img"), get_file_path_without_extensiton(file_path));
1203                 if(!FILEIO::IsFileExisting(img_file_path)) {
1204                         my_stprintf_s(img_file_path, _MAX_PATH, _T("%s.bin"), get_file_path_without_extensiton(file_path));
1205                         if(!FILEIO::IsFileExisting(img_file_path)) {
1206                                 my_stprintf_s(img_file_path, _MAX_PATH, _T("%s.gz"), get_file_path_without_extensiton(file_path));
1207                                 if(!FILEIO::IsFileExisting(img_file_path)) {
1208                                         my_stprintf_s(img_file_path, _MAX_PATH, _T("%s.img.gz"), get_file_path_without_extensiton(file_path));
1209                                         if(!FILEIO::IsFileExisting(img_file_path)) {
1210                                                 my_stprintf_s(img_file_path, _MAX_PATH, _T("%s.bin.gz"), get_file_path_without_extensiton(file_path));
1211                                         }
1212                                 }
1213                         }
1214                 }
1215                 if(fio_img->Fopen(img_file_path, FILEIO_READ_BINARY)) {
1216                         // get image file size
1217                         if((max_logical_block = fio_img->FileLength() / 2352) > 0) {
1218                                 // read cue file
1219                                 FILEIO* fio = new FILEIO();
1220                                 if(fio->Fopen(file_path, FILEIO_READ_BINARY)) {
1221                                         char line[1024], *ptr;
1222                                         int track = -1;
1223                                         while(fio->Fgets(line, 1024) != NULL) {
1224                                                 if(strstr(line, "FILE") != NULL) {
1225                                                         // do nothing
1226                                                 } else if((ptr = strstr(line, "TRACK")) != NULL) {
1227                                                         // "TRACK 01 AUDIO"
1228                                                         // "TRACK 02 MODE1/2352"
1229                                                         ptr += 6;
1230                                                         while(*ptr == ' ' || *ptr == 0x09) {
1231                                                                 ptr++;
1232                                                         }
1233                                                         if((track = atoi(ptr)) > 0) {
1234                                                                 if(track > track_num) {
1235                                                                         track_num = track;
1236                                                                 }
1237                                                                 toc_table[track - 1].is_audio = (strstr(line, "AUDIO") != NULL);
1238                                                         }
1239                                                 } else if((ptr = strstr(line, "PREGAP")) != NULL) {
1240                                                         // "PREGAP 00:02:00"
1241                                                         if(track > 0) {
1242                                                                 toc_table[track - 1].pregap = get_frames_from_msf(ptr + 7);
1243                                                         }
1244                                                 } else if((ptr = strstr(line, "INDEX")) != NULL) {
1245                                                         // "INDEX 01 00:00:00"
1246                                                         if(track > 0) {
1247                                                                 ptr += 6;
1248                                                                 while(*ptr == ' ' || *ptr == 0x09) {
1249                                                                         ptr++;
1250                                                                 }
1251                                                                 int num = atoi(ptr);
1252                                                                 while(*ptr >= '0' && *ptr <= '9') {
1253                                                                         ptr++;
1254                                                                 }
1255                                                                 if(num == 0) {
1256                                                                         toc_table[track - 1].index0 = get_frames_from_msf(ptr);
1257                                                                 } else if(num == 1) {
1258                                                                         toc_table[track - 1].index1 = get_frames_from_msf(ptr);
1259                                                                 }
1260                                                         }
1261                                                 }
1262                                         }
1263                                         if(track_num != 0) {
1264                                                 for(int i = 1; i < track_num; i++) {
1265                                                         if(toc_table[i].index0 == 0) {
1266                                                                 toc_table[i].index0 = toc_table[i].index1 - toc_table[i].pregap;
1267                                                         } else if(toc_table[i].pregap == 0) {
1268                                                                 toc_table[i].pregap = toc_table[i].index1 - toc_table[i].index0;
1269                                                         }
1270                                                 }
1271                                                 toc_table[0].index0 = toc_table[0].index1 = toc_table[0].pregap = 0;
1272                                                 toc_table[track_num].index0 = toc_table[track_num].index1 = max_logical_block;
1273                                         } else {
1274                                                 fio_img->Fclose();
1275                                         }
1276                                         fio->Fclose();
1277                                 }
1278                                 delete fio;
1279                         }
1280                 }
1281 #endif
1282         } else if(check_file_extension(file_path, _T(".ccd"))) {
1283                 // get image file name
1284                 my_stprintf_s(img_file_path, _MAX_PATH, _T("%s.img"), get_file_path_without_extensiton(file_path));
1285                 if(!FILEIO::IsFileExisting(img_file_path)) {
1286                         my_stprintf_s(img_file_path, _MAX_PATH, _T("%s.gz"), get_file_path_without_extensiton(file_path));
1287                         if(!FILEIO::IsFileExisting(img_file_path)) {
1288                                 my_stprintf_s(img_file_path, _MAX_PATH, _T("%s.img.gz"), get_file_path_without_extensiton(file_path));
1289                         }
1290                 }
1291                 if(fio_img->Fopen(img_file_path, FILEIO_READ_BINARY)) {
1292                         is_cue = false;
1293                         current_track = 0;
1294                         // get image file size
1295                         if((max_logical_block = fio_img->FileLength() / 2352) > 0) {
1296                                 // read cue file
1297                                 FILEIO* fio = new FILEIO();
1298                                 if(fio->Fopen(file_path, FILEIO_READ_BINARY)) {
1299                                         char line[1024], *ptr;
1300                                         int track = -1;
1301                                         while(fio->Fgets(line, 1024) != NULL) {
1302                                                 if(strstr(line, "[Session ") != NULL) {
1303                                                         track = -1;
1304                                                 } else if((ptr = strstr(line, "Point=0x")) != NULL) {
1305                                                         if((track = hexatoi(ptr + 8)) > 0 && track < 0xa0) {
1306                                                                 if(track > track_num) {
1307                                                                         track_num = track;
1308                                                                 }
1309                                                         }
1310                                                 } else if((ptr = strstr(line, "Control=0x")) != NULL) {
1311                                                         if(track > 0 && track < 0xa0) {
1312                                                                 toc_table[track - 1].is_audio = (hexatoi(ptr + 10) != 4);
1313                                                         }
1314                                                 } else if((ptr = strstr(line, "ALBA=-")) != NULL) {
1315                                                         if(track > 0 && track < 0xa0) {
1316                                                                 toc_table[track - 1].pregap = atoi(ptr + 6);
1317                                                         }
1318                                                 } else if((ptr = strstr(line, "PLBA=")) != NULL) {
1319                                                         if(track > 0 && track < 0xa0) {
1320                                                                 toc_table[track - 1].index1 = atoi(ptr + 5);
1321                                                         }
1322                                                 }
1323                                         }
1324                                         if(track_num != 0) {
1325                                                 toc_table[0].lba_offset = 0;
1326                                                 toc_table[0].pregap = 0;
1327                                                 for(int i = 1; i < track_num; i++) {
1328                                                         toc_table[i].index0 = toc_table[i].index1 - toc_table[i].pregap;
1329                                                         toc_table[i].lba_offset = toc_table[i].pregap;
1330                                                         toc_table[i - 1].lba_size = toc_table[i].pregap - toc_table[i - 1].pregap;
1331                                                 }
1332                                                 toc_table[0].index0 = toc_table[0].index1 = toc_table[0].pregap = 0;
1333                                                 toc_table[track_num].index0 = toc_table[track_num].index1 = max_logical_block;
1334                                                 if(track_num > 0) {
1335                                                         toc_table[track_num].lba_size = max_logical_block - toc_table[track_num - 1].lba_offset;
1336                                                 } else {
1337                                                         toc_table[track_num].lba_size = 0;
1338                                                 }
1339                                         } else {
1340                                                 fio_img->Fclose();
1341                                         }
1342                                         fio->Fclose();
1343                                 }
1344                                 delete fio;
1345                         }
1346                 }
1347         }
1348 #ifdef _SCSI_DEBUG_LOG
1349         if(mounted()) {
1350                 for(int i = 0; i < track_num + 1; i++) {
1351                         uint32_t idx0_msf = lba_to_msf(toc_table[i].index0);
1352                         uint32_t idx1_msf = lba_to_msf(toc_table[i].index1);
1353                         uint32_t pgap_msf = lba_to_msf(toc_table[i].pregap);
1354                         this->out_debug_log(_T("Track%02d: Index0=%02x:%02x:%02x Index1=%02x:%02x:%02x PreGpap=%02x:%02x:%02x\n"), i + 1,
1355                         (idx0_msf >> 16) & 0xff, (idx0_msf >> 8) & 0xff, idx0_msf & 0xff,
1356                         (idx1_msf >> 16) & 0xff, (idx1_msf >> 8) & 0xff, idx1_msf & 0xff,
1357                         (pgap_msf >> 16) & 0xff, (pgap_msf >> 8) & 0xff, pgap_msf & 0xff);
1358                 }
1359         }
1360 #endif
1361 }
1362
1363 void SCSI_CDROM::close()
1364 {
1365         if(fio_img->IsOpened()) {
1366                 fio_img->Fclose();
1367         }
1368         memset(toc_table, 0, sizeof(toc_table));
1369         track_num = 0;
1370         is_cue = false;
1371         current_track = 0;
1372         set_cdda_status(CDDA_OFF);
1373 }
1374
1375 bool SCSI_CDROM::mounted()
1376 {
1377         if(is_cue) return true;
1378         return fio_img->IsOpened();
1379 }
1380
1381 bool SCSI_CDROM::accessed()
1382 {
1383         bool value = access;
1384         access = false;
1385         return value;
1386 }
1387
1388 void SCSI_CDROM::mix(int32_t* buffer, int cnt)
1389 {
1390         if(cdda_status == CDDA_PLAYING) {
1391                 if(mix_loop_num != 0) {
1392                         int tmp_l = 0, tmp_r = 0;
1393                         for(int i = 0; i < mix_loop_num; i++) {
1394                                 event_callback(EVENT_CDDA, 0);
1395                                 tmp_l += cdda_sample_l;
1396                                 tmp_r += cdda_sample_r;
1397                         }
1398                         cdda_sample_l = tmp_l / mix_loop_num;
1399                         cdda_sample_r = tmp_r / mix_loop_num;
1400                 }
1401                 int32_t val_l = apply_volume(apply_volume(cdda_sample_l, volume_m), volume_l);
1402                 int32_t val_r = apply_volume(apply_volume(cdda_sample_r, volume_m), volume_r);
1403                 
1404                 for(int i = 0; i < cnt; i++) {
1405                         *buffer++ += val_l; // L
1406                         *buffer++ += val_r; // R
1407                 }
1408         }
1409 }
1410
1411 void SCSI_CDROM::set_volume(int ch, int decibel_l, int decibel_r)
1412 {
1413         volume_l = decibel_to_volume(decibel_l + 3.0);
1414         volume_r = decibel_to_volume(decibel_r + 3.0);
1415 }
1416
1417 void SCSI_CDROM::set_volume(int volume)
1418 {
1419         volume_m = (int)(1024.0 * (max(0, min(100, volume)) / 100.0));
1420 }
1421
1422 #define STATE_VERSION   4
1423
1424 // Q: If loading state when using another (saved) image? 20181013 K.O
1425 //    May need close() and open() (or ...?).
1426 bool SCSI_CDROM::process_state(FILEIO* state_fio, bool loading)
1427 {
1428         uint32_t offset = 0;
1429         
1430         if(!state_fio->StateCheckUint32(STATE_VERSION)) {
1431                 return false;
1432         }
1433         if(!state_fio->StateCheckInt32(this_device_id)) {
1434                 return false;
1435         }
1436         state_fio->StateValue(cdda_start_frame);
1437         state_fio->StateValue(cdda_end_frame);
1438         state_fio->StateValue(cdda_playing_frame);
1439         state_fio->StateValue(cdda_status);
1440         state_fio->StateValue(cdda_repeat);
1441         state_fio->StateValue(cdda_interrupt);
1442         state_fio->StateArray(cdda_buffer, sizeof(cdda_buffer), 1);
1443         state_fio->StateValue(cdda_buffer_ptr);
1444         state_fio->StateValue(cdda_sample_l);
1445         state_fio->StateValue(cdda_sample_r);
1446         state_fio->StateValue(event_cdda);
1447         state_fio->StateValue(event_cdda_delay_play);
1448         state_fio->StateValue(event_delay_interrupt);
1449         state_fio->StateValue(read_sectors);
1450 //      state_fio->StateValue(mix_loop_num);
1451         state_fio->StateValue(read_mode);
1452         state_fio->StateValue(volume_m);
1453         if(loading) {
1454                 offset = state_fio->FgetUint32_LE();
1455         } else {
1456                 if(fio_img->IsOpened()) {
1457                         offset = fio_img->Ftell();
1458                 }
1459                 state_fio->FputUint32_LE(offset);
1460         }
1461         
1462         state_fio->StateValue(is_cue);
1463         state_fio->StateValue(current_track);
1464         // ToDo: Re-Open Image.20181118 K.O
1465         // post process
1466         if(loading && fio_img->IsOpened()) {
1467                 fio_img->Fseek(offset, FILEIO_SEEK_SET);
1468         }
1469         return SCSI_DEV::process_state(state_fio, loading);
1470 }