-
Notifications
You must be signed in to change notification settings - Fork 597
/
cdrom.cpp
2919 lines (2508 loc) · 92.9 KB
/
cdrom.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "cdrom.h"
#include "common/align.h"
#include "common/cd_image.h"
#include "common/log.h"
#include "common/platform.h"
#include "common/state_wrapper.h"
#include "dma.h"
#include "imgui.h"
#include "interrupt_controller.h"
#include "settings.h"
#include "spu.h"
#include "system.h"
#include <cmath>
Log_SetChannel(CDROM);
#if defined(CPU_X64)
#include <emmintrin.h>
#endif
static constexpr std::array<const char*, 15> s_drive_state_names = {
{"Idle", "Opening Shell", "Resetting", "Seeking (Physical)", "Seeking (Logical)", "Reading ID", "Reading TOC",
"Reading", "Playing", "Pausing", "Stopping", "Changing Session", "Spinning Up", "Seeking (Implicit)",
"Changing Speed/Implicit TOC Read"}};
struct CommandInfo
{
const char* name;
u8 expected_parameters;
};
static std::array<CommandInfo, 255> s_command_info = {{
{"Sync", 0}, {"Getstat", 0}, {"Setloc", 3}, {"Play", 0}, {"Forward", 0}, {"Backward", 0},
{"ReadN", 0}, {"MotorOn", 0}, {"Stop", 0}, {"Pause", 0}, {"Reset", 0}, {"Mute", 0},
{"Demute", 0}, {"Setfilter", 2}, {"Setmode", 1}, {"Getparam", 0}, {"GetlocL", 0}, {"GetlocP", 0},
{"SetSession", 1}, {"GetTN", 0}, {"GetTD", 1}, {"SeekL", 0}, {"SeekP", 0}, {"SetClock", 0},
{"GetClock", 0}, {"Test", 1}, {"GetID", 0}, {"ReadS", 0}, {"Init", 0}, {"GetQ", 2},
{"ReadTOC", 0}, {"VideoCD", 6}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0}, {"Unknown", 0},
{"Unknown", 0}, {"Unknown", 0}, {nullptr, 0} // Unknown
}};
CDROM g_cdrom;
CDROM::CDROM() = default;
CDROM::~CDROM() = default;
void CDROM::Initialize()
{
m_command_event = TimingEvents::CreateTimingEvent(
"CDROM Command Event", 1, 1,
[](void* param, TickCount ticks, TickCount ticks_late) { static_cast<CDROM*>(param)->ExecuteCommand(ticks_late); },
this, false);
m_command_second_response_event = TimingEvents::CreateTimingEvent(
"CDROM Command Second Response Event", 1, 1,
[](void* param, TickCount ticks, TickCount ticks_late) {
static_cast<CDROM*>(param)->ExecuteCommandSecondResponse(ticks_late);
},
this, false);
m_drive_event = TimingEvents::CreateTimingEvent(
"CDROM Drive Event", 1, 1,
[](void* param, TickCount ticks, TickCount ticks_late) { static_cast<CDROM*>(param)->ExecuteDrive(ticks_late); },
this, false);
if (g_settings.cdrom_readahead_sectors > 0)
m_reader.StartThread(g_settings.cdrom_readahead_sectors);
Reset();
}
void CDROM::Shutdown()
{
m_command_event.reset();
m_command_second_response_event.reset();
m_drive_event.reset();
m_reader.StopThread();
m_reader.RemoveMedia();
}
void CDROM::Reset()
{
m_command = Command::None;
m_command_event->Deactivate();
ClearCommandSecondResponse();
ClearDriveState();
m_status.bits = 0;
m_secondary_status.bits = 0;
m_secondary_status.motor_on = CanReadMedia();
m_secondary_status.shell_open = !CanReadMedia();
m_mode.bits = 0;
m_mode.read_raw_sector = true;
m_interrupt_enable_register = INTERRUPT_REGISTER_MASK;
m_interrupt_flag_register = 0;
m_pending_async_interrupt = 0;
m_setloc_position = {};
m_seek_start_lba = 0;
m_seek_end_lba = 0;
m_setloc_pending = false;
m_read_after_seek = false;
m_play_after_seek = false;
m_muted = false;
m_adpcm_muted = false;
m_xa_filter_file_number = 0;
m_xa_filter_channel_number = 0;
m_xa_current_file_number = 0;
m_xa_current_channel_number = 0;
m_xa_current_set = false;
std::memset(&m_last_sector_header, 0, sizeof(m_last_sector_header));
std::memset(&m_last_sector_subheader, 0, sizeof(m_last_sector_subheader));
m_last_sector_header_valid = false;
std::memset(&m_last_subq, 0, sizeof(m_last_subq));
m_last_cdda_report_frame_nibble = 0xFF;
m_next_cd_audio_volume_matrix[0][0] = 0x80;
m_next_cd_audio_volume_matrix[0][1] = 0x00;
m_next_cd_audio_volume_matrix[1][0] = 0x00;
m_next_cd_audio_volume_matrix[1][1] = 0x80;
m_cd_audio_volume_matrix = m_next_cd_audio_volume_matrix;
ResetAudioDecoder();
m_param_fifo.Clear();
m_response_fifo.Clear();
m_async_response_fifo.Clear();
m_data_fifo.Clear();
m_current_read_sector_buffer = 0;
m_current_write_sector_buffer = 0;
for (u32 i = 0; i < NUM_SECTOR_BUFFERS; i++)
{
m_sector_buffers[i].data.fill(0);
m_sector_buffers[i].size = 0;
}
UpdateStatusRegister();
SetHoldPosition(0, true);
}
void CDROM::SoftReset(TickCount ticks_late)
{
const bool was_double_speed = m_mode.double_speed;
ClearCommandSecondResponse();
ClearDriveState();
m_secondary_status.bits = 0;
m_secondary_status.motor_on = CanReadMedia();
m_secondary_status.shell_open = !CanReadMedia();
m_mode.bits = 0;
m_mode.read_raw_sector = true;
m_pending_async_interrupt = 0;
m_setloc_position = {};
m_setloc_pending = false;
m_read_after_seek = false;
m_play_after_seek = false;
m_muted = false;
m_adpcm_muted = false;
m_last_sector_header_valid = false;
m_last_cdda_report_frame_nibble = 0xFF;
ResetAudioDecoder();
m_param_fifo.Clear();
m_async_response_fifo.Clear();
m_data_fifo.Clear();
m_current_read_sector_buffer = 0;
m_current_write_sector_buffer = 0;
for (u32 i = 0; i < NUM_SECTOR_BUFFERS; i++)
{
m_sector_buffers[i].data.fill(0);
m_sector_buffers[i].size = 0;
}
UpdateStatusRegister();
if (HasMedia())
{
const TickCount toc_read_ticks = GetTicksForTOCRead();
const TickCount speed_change_ticks = was_double_speed ? GetTicksForSpeedChange() : 0;
const TickCount seek_ticks = (m_current_lba != 0) ? GetTicksForSeek(0) : 0;
const TickCount total_ticks = toc_read_ticks + speed_change_ticks + seek_ticks - ticks_late;
if (was_double_speed)
{
Log_DevPrintf("CDROM was double speed on reset, switching to single speed in %d ticks, reading TOC in %d ticks, "
"seeking in %d ticks",
speed_change_ticks, toc_read_ticks, seek_ticks);
}
else
{
Log_DevPrintf("CDROM reading TOC on reset in %d ticks and seeking in %d ticks", toc_read_ticks, seek_ticks);
}
if (m_current_lba != 0)
{
m_drive_state = DriveState::SeekingImplicit;
m_drive_event->SetIntervalAndSchedule(total_ticks);
m_requested_lba = 0;
m_reader.QueueReadSector(m_requested_lba);
m_seek_start_lba = m_current_lba;
m_seek_end_lba = 0;
}
else
{
m_drive_state = DriveState::ChangingSpeedOrTOCRead;
m_drive_event->Schedule(total_ticks);
}
}
}
bool CDROM::DoState(StateWrapper& sw)
{
sw.Do(&m_command);
sw.DoEx(&m_command_second_response, 53, Command::None);
sw.Do(&m_drive_state);
sw.Do(&m_status.bits);
sw.Do(&m_secondary_status.bits);
sw.Do(&m_mode.bits);
bool current_double_speed = m_mode.double_speed;
sw.Do(¤t_double_speed);
sw.Do(&m_interrupt_enable_register);
sw.Do(&m_interrupt_flag_register);
sw.Do(&m_pending_async_interrupt);
sw.DoPOD(&m_setloc_position);
sw.Do(&m_current_lba);
sw.Do(&m_seek_start_lba);
sw.Do(&m_seek_end_lba);
sw.DoEx(&m_physical_lba, 49, m_current_lba);
sw.DoEx(&m_physical_lba_update_tick, 49, static_cast<u32>(0));
sw.DoEx(&m_physical_lba_update_carry, 54, static_cast<u32>(0));
sw.Do(&m_setloc_pending);
sw.Do(&m_read_after_seek);
sw.Do(&m_play_after_seek);
sw.Do(&m_muted);
sw.Do(&m_adpcm_muted);
sw.Do(&m_xa_filter_file_number);
sw.Do(&m_xa_filter_channel_number);
sw.Do(&m_xa_current_file_number);
sw.Do(&m_xa_current_channel_number);
sw.Do(&m_xa_current_set);
sw.DoBytes(&m_last_sector_header, sizeof(m_last_sector_header));
sw.DoBytes(&m_last_sector_subheader, sizeof(m_last_sector_subheader));
sw.Do(&m_last_sector_header_valid);
sw.DoBytes(&m_last_subq, sizeof(m_last_subq));
sw.Do(&m_last_cdda_report_frame_nibble);
sw.Do(&m_play_track_number_bcd);
sw.Do(&m_async_command_parameter);
sw.DoEx(&m_fast_forward_rate, 49, static_cast<s8>(0));
sw.Do(&m_cd_audio_volume_matrix);
sw.Do(&m_next_cd_audio_volume_matrix);
sw.Do(&m_xa_last_samples);
sw.Do(&m_xa_resample_ring_buffer);
sw.Do(&m_xa_resample_p);
sw.Do(&m_xa_resample_sixstep);
sw.Do(&m_param_fifo);
sw.Do(&m_response_fifo);
sw.Do(&m_async_response_fifo);
sw.Do(&m_data_fifo);
sw.Do(&m_current_read_sector_buffer);
sw.Do(&m_current_write_sector_buffer);
for (u32 i = 0; i < NUM_SECTOR_BUFFERS; i++)
{
sw.Do(&m_sector_buffers[i].data);
sw.Do(&m_sector_buffers[i].size);
}
sw.Do(&m_audio_fifo);
sw.Do(&m_requested_lba);
if (sw.IsReading())
{
if (m_reader.HasMedia())
m_reader.QueueReadSector(m_requested_lba);
UpdateCommandEvent();
m_drive_event->SetState(!IsDriveIdle());
// Time will get fixed up later.
m_command_second_response_event->SetState(m_command_second_response != Command::None);
}
return !sw.HasError();
}
bool CDROM::IsMediaPS1Disc() const
{
if (!m_reader.HasMedia())
return false;
// Check for a data track as the first track.
if (m_reader.GetMedia()->GetTrackMode(1) == CDImage::TrackMode::Audio)
return false;
return true;
}
bool CDROM::DoesMediaRegionMatchConsole() const
{
if (!g_settings.cdrom_region_check)
return true;
return System::GetRegion() == System::GetConsoleRegionForDiscRegion(m_disc_region);
}
void CDROM::InsertMedia(std::unique_ptr<CDImage> media)
{
if (CanReadMedia())
RemoveMedia();
// set the region from the system area of the disc
m_disc_region = System::GetRegionForImage(media.get());
Log_InfoPrintf("Inserting new media, disc region: %s, console region: %s", Settings::GetDiscRegionName(m_disc_region),
Settings::GetConsoleRegionName(System::GetRegion()));
// motor automatically spins up
if (m_drive_state != DriveState::ShellOpening)
StartMotor();
m_reader.SetMedia(std::move(media));
SetHoldPosition(0, true);
}
std::unique_ptr<CDImage> CDROM::RemoveMedia(bool force /* = false */)
{
if (!HasMedia() && !force)
return nullptr;
const TickCount stop_ticks = GetTicksForStop(true);
Log_InfoPrintf("Removing CD...");
std::unique_ptr<CDImage> image = m_reader.RemoveMedia();
m_last_sector_header_valid = false;
m_secondary_status.motor_on = false;
m_secondary_status.shell_open = true;
m_secondary_status.ClearActiveBits();
m_disc_region = DiscRegion::Other;
// If the drive was doing anything, we need to abort the command.
ClearDriveState();
ClearCommandSecondResponse();
m_command = Command::None;
m_command_event->Deactivate();
// The console sends an interrupt when the shell is opened regardless of whether a command was executing.
if (HasPendingAsyncInterrupt())
ClearAsyncInterrupt();
SendAsyncErrorResponse(STAT_ERROR, 0x08);
// Begin spin-down timer, we can't swap the new disc in immediately for some games (e.g. Metal Gear Solid).
if (!force)
{
m_drive_state = DriveState::ShellOpening;
m_drive_event->SetIntervalAndSchedule(stop_ticks);
}
return image;
}
void CDROM::SetReadaheadSectors(u32 readahead_sectors)
{
const bool want_thread = (readahead_sectors > 0);
if (want_thread == m_reader.IsUsingThread() && m_reader.GetReadaheadCount() == readahead_sectors)
return;
if (want_thread)
m_reader.StartThread(readahead_sectors);
else
m_reader.StopThread();
m_reader.QueueReadSector(m_requested_lba);
}
void CDROM::CPUClockChanged()
{
// reschedule the disc read event
if (IsReadingOrPlaying())
m_drive_event->SetInterval(GetTicksForRead());
}
u8 CDROM::ReadRegister(u32 offset)
{
switch (offset)
{
case 0: // status register
Log_TracePrintf("CDROM read status register -> 0x%08X", m_status.bits);
return m_status.bits;
case 1: // always response FIFO
{
if (m_response_fifo.IsEmpty())
{
Log_DevPrint("Response FIFO empty on read");
return 0x00;
}
const u8 value = m_response_fifo.Pop();
UpdateStatusRegister();
Log_DebugPrintf("CDROM read response FIFO -> 0x%08X", ZeroExtend32(value));
return value;
}
case 2: // always data FIFO
{
const u8 value = m_data_fifo.Pop();
UpdateStatusRegister();
Log_DebugPrintf("CDROM read data FIFO -> 0x%08X", ZeroExtend32(value));
return value;
}
case 3:
{
if (m_status.index & 1)
{
const u8 value = m_interrupt_flag_register | ~INTERRUPT_REGISTER_MASK;
Log_DebugPrintf("CDROM read interrupt flag register -> 0x%02X", ZeroExtend32(value));
return value;
}
else
{
const u8 value = m_interrupt_enable_register | ~INTERRUPT_REGISTER_MASK;
Log_DebugPrintf("CDROM read interrupt enable register -> 0x%02X", ZeroExtend32(value));
return value;
}
}
break;
}
Log_ErrorPrintf("Unknown CDROM register read: offset=0x%02X, index=%d", offset,
ZeroExtend32(m_status.index.GetValue()));
Panic("Unknown CDROM register");
return 0;
}
void CDROM::WriteRegister(u32 offset, u8 value)
{
if (offset == 0)
{
Log_TracePrintf("CDROM status register <- 0x%02X", value);
m_status.bits = (m_status.bits & static_cast<u8>(~3)) | (value & u8(3));
return;
}
const u32 reg = (m_status.index * 3u) + (offset - 1);
switch (reg)
{
case 0:
{
Log_DebugPrintf("CDROM command register <- 0x%02X (%s)", value, s_command_info[value].name);
BeginCommand(static_cast<Command>(value));
return;
}
case 1:
{
if (m_param_fifo.IsFull())
{
Log_WarningPrintf("Parameter FIFO overflow");
m_param_fifo.RemoveOne();
}
m_param_fifo.Push(value);
UpdateStatusRegister();
return;
}
case 2:
{
Log_DebugPrintf("Request register <- 0x%02X", value);
const RequestRegister rr{value};
// Sound map is not currently implemented, haven't found anything which uses it.
if (rr.SMEN)
Log_ErrorPrintf("Sound map enable set");
if (rr.BFWR)
Log_ErrorPrintf("Buffer write enable set");
if (rr.BFRD)
{
LoadDataFIFO();
}
else
{
Log_DebugPrintf("Clearing data FIFO");
m_data_fifo.Clear();
}
UpdateStatusRegister();
return;
}
case 3:
{
Log_ErrorPrintf("Sound map data out <- 0x%02X", value);
return;
}
case 4:
{
Log_DebugPrintf("Interrupt enable register <- 0x%02X", value);
m_interrupt_enable_register = value & INTERRUPT_REGISTER_MASK;
UpdateInterruptRequest();
return;
}
case 5:
{
Log_DebugPrintf("Interrupt flag register <- 0x%02X", value);
m_interrupt_flag_register &= ~(value & INTERRUPT_REGISTER_MASK);
if (m_interrupt_flag_register == 0)
{
if (HasPendingAsyncInterrupt())
DeliverAsyncInterrupt();
else
UpdateCommandEvent();
}
// Bit 6 clears the parameter FIFO.
if (value & 0x40)
{
m_param_fifo.Clear();
UpdateStatusRegister();
}
return;
}
case 6:
{
Log_ErrorPrintf("Sound map coding info <- 0x%02X", value);
return;
}
case 7:
{
Log_DebugPrintf("Audio volume for left-to-left output <- 0x%02X", value);
m_next_cd_audio_volume_matrix[0][0] = value;
return;
}
case 8:
{
Log_DebugPrintf("Audio volume for left-to-right output <- 0x%02X", value);
m_next_cd_audio_volume_matrix[0][1] = value;
return;
}
case 9:
{
Log_DebugPrintf("Audio volume for right-to-right output <- 0x%02X", value);
m_next_cd_audio_volume_matrix[1][1] = value;
return;
}
case 10:
{
Log_DebugPrintf("Audio volume for right-to-left output <- 0x%02X", value);
m_next_cd_audio_volume_matrix[1][0] = value;
return;
}
case 11:
{
Log_DebugPrintf("Audio volume apply changes <- 0x%02X", value);
const bool adpcm_muted = ConvertToBoolUnchecked(value & u8(0x01));
if (adpcm_muted != m_adpcm_muted ||
(value & 0x20 && std::memcmp(m_cd_audio_volume_matrix.data(), m_next_cd_audio_volume_matrix.data(),
sizeof(m_cd_audio_volume_matrix)) != 0))
{
if (HasPendingDiscEvent())
m_drive_event->InvokeEarly();
g_spu.GeneratePendingSamples();
}
m_adpcm_muted = adpcm_muted;
if (value & 0x20)
m_cd_audio_volume_matrix = m_next_cd_audio_volume_matrix;
return;
}
default:
{
Log_ErrorPrintf("Unknown CDROM register write: offset=0x%02X, index=%d, reg=%u, value=0x%02X", offset,
m_status.index.GetValue(), reg, value);
return;
}
}
}
void CDROM::DMARead(u32* words, u32 word_count)
{
const u32 words_in_fifo = m_data_fifo.GetSize() / 4;
if (words_in_fifo < word_count)
{
Log_ErrorPrintf("DMA read on empty/near-empty data FIFO");
std::memset(words + words_in_fifo, 0, sizeof(u32) * (word_count - words_in_fifo));
}
const u32 bytes_to_read = std::min<u32>(word_count * sizeof(u32), m_data_fifo.GetSize());
m_data_fifo.PopRange(reinterpret_cast<u8*>(words), bytes_to_read);
}
void CDROM::SetInterrupt(Interrupt interrupt)
{
m_interrupt_flag_register = static_cast<u8>(interrupt);
UpdateInterruptRequest();
}
void CDROM::SetAsyncInterrupt(Interrupt interrupt)
{
if (m_interrupt_flag_register == static_cast<u8>(interrupt))
{
Log_DevPrintf("Not setting async interrupt %u because there is already one unacknowledged",
static_cast<u8>(interrupt));
m_async_response_fifo.Clear();
return;
}
Assert(m_pending_async_interrupt == 0);
m_pending_async_interrupt = static_cast<u8>(interrupt);
if (!HasPendingInterrupt())
DeliverAsyncInterrupt();
}
void CDROM::ClearAsyncInterrupt()
{
m_pending_async_interrupt = 0;
m_async_response_fifo.Clear();
}
void CDROM::DeliverAsyncInterrupt()
{
Assert(m_pending_async_interrupt != 0 && !HasPendingInterrupt());
Log_DebugPrintf("Delivering async interrupt %u", m_pending_async_interrupt);
if (m_pending_async_interrupt == static_cast<u8>(Interrupt::DataReady))
m_current_read_sector_buffer = m_current_write_sector_buffer;
m_response_fifo.Clear();
m_response_fifo.PushFromQueue(&m_async_response_fifo);
m_interrupt_flag_register = m_pending_async_interrupt;
m_pending_async_interrupt = 0;
UpdateInterruptRequest();
UpdateStatusRegister();
UpdateCommandEvent();
}
void CDROM::SendACKAndStat()
{
m_response_fifo.Push(m_secondary_status.bits);
SetInterrupt(Interrupt::ACK);
}
void CDROM::SendErrorResponse(u8 stat_bits /* = STAT_ERROR */, u8 reason /* = 0x80 */)
{
m_response_fifo.Push(m_secondary_status.bits | stat_bits);
m_response_fifo.Push(reason);
SetInterrupt(Interrupt::Error);
}
void CDROM::SendAsyncErrorResponse(u8 stat_bits /* = STAT_ERROR */, u8 reason /* = 0x80 */)
{
m_async_response_fifo.Push(m_secondary_status.bits | stat_bits);
m_async_response_fifo.Push(reason);
SetAsyncInterrupt(Interrupt::Error);
}
void CDROM::UpdateStatusRegister()
{
m_status.ADPBUSY = false;
m_status.PRMEMPTY = m_param_fifo.IsEmpty();
m_status.PRMWRDY = !m_param_fifo.IsFull();
m_status.RSLRRDY = !m_response_fifo.IsEmpty();
m_status.DRQSTS = !m_data_fifo.IsEmpty();
m_status.BUSYSTS = HasPendingCommand();
g_dma.SetRequest(DMA::Channel::CDROM, m_status.DRQSTS);
}
void CDROM::UpdateInterruptRequest()
{
if ((m_interrupt_flag_register & m_interrupt_enable_register) == 0)
return;
g_interrupt_controller.InterruptRequest(InterruptController::IRQ::CDROM);
}
bool CDROM::HasPendingDiscEvent() const
{
return (m_drive_event->IsActive() && m_drive_event->GetTicksUntilNextExecution() <= 0);
}
TickCount CDROM::GetAckDelayForCommand(Command command)
{
if (command == Command::Init)
{
// Init takes longer.
return 120000;
}
// Tests show that the average time to acknowledge a command is significantly higher when a disc is in the drive,
// presumably because the controller is busy doing discy-things.
constexpr u32 default_ack_delay_no_disc = 15000;
constexpr u32 default_ack_delay_with_disc = 25000;
return CanReadMedia() ? default_ack_delay_with_disc : default_ack_delay_no_disc;
}
TickCount CDROM::GetTicksForSpinUp()
{
// 1 second
return System::GetTicksPerSecond();
}
TickCount CDROM::GetTicksForIDRead()
{
TickCount ticks = ID_READ_TICKS;
if (m_drive_state == DriveState::SpinningUp)
ticks += m_drive_event->GetTicksUntilNextExecution();
return ticks;
}
TickCount CDROM::GetTicksForRead()
{
const TickCount tps = System::GetTicksPerSecond();
if (g_settings.cdrom_read_speedup > 1 && !m_mode.cdda && !m_mode.xa_enable && m_mode.double_speed)
return tps / (150 * g_settings.cdrom_read_speedup);
return m_mode.double_speed ? (tps / 150) : (tps / 75);
}
TickCount CDROM::GetTicksForSeek(CDImage::LBA new_lba, bool ignore_speed_change)
{
static constexpr TickCount MIN_TICKS = 20000;
if (g_settings.cdrom_seek_speedup == 0)
return MIN_TICKS;
u32 ticks = static_cast<u32>(MIN_TICKS);
if (IsSeeking())
ticks += m_drive_event->GetTicksUntilNextExecution();
else
UpdatePhysicalPosition(false);
const u32 ticks_per_sector =
m_mode.double_speed ? static_cast<u32>(System::MASTER_CLOCK / 150) : static_cast<u32>(System::MASTER_CLOCK / 75);
const u32 ticks_per_second = static_cast<u32>(System::MASTER_CLOCK);
const CDImage::LBA current_lba = m_secondary_status.motor_on ? (IsSeeking() ? m_seek_end_lba : m_physical_lba) : 0;
const u32 lba_diff = static_cast<u32>((new_lba > current_lba) ? (new_lba - current_lba) : (current_lba - new_lba));
// Motor spin-up time.
if (!m_secondary_status.motor_on)
{
ticks +=
(m_drive_state == DriveState::SpinningUp) ? m_drive_event->GetTicksUntilNextExecution() : GetTicksForSpinUp();
if (m_drive_state == DriveState::ShellOpening || m_drive_state == DriveState::SpinningUp)
ClearDriveState();
}
if (lba_diff < 32)
{
ticks += ticks_per_sector * std::min<u32>(5u, lba_diff);
}
else
{
// This is a still not a very accurate model, but it's roughly in line with the behavior of hardware tests.
const float disc_distance = 0.2323384936f * std::log(static_cast<float>((new_lba / 4500) + 1u));
float seconds;
if (lba_diff <= CDImage::FRAMES_PER_SECOND)
{
// 30ms + (diff * 30ms) + (disc distance * 30ms)
seconds = 0.03f + ((static_cast<float>(lba_diff) / static_cast<float>(CDImage::FRAMES_PER_SECOND)) * 0.03f) +
(disc_distance * 0.03f);
}
else if (lba_diff <= CDImage::FRAMES_PER_MINUTE)
{
// 150ms + (diff * 30ms) + (disc distance * 50ms)
seconds = 0.15f + ((static_cast<float>(lba_diff) / static_cast<float>(CDImage::FRAMES_PER_MINUTE)) * 0.03f) +
(disc_distance * 0.05f);
}
else
{
// 200ms + (diff * 500ms)
seconds = 0.2f + ((static_cast<float>(lba_diff) / static_cast<float>(72 * CDImage::FRAMES_PER_MINUTE)) * 0.4f);
}
ticks += static_cast<u32>(seconds * static_cast<float>(ticks_per_second));
}
if (m_drive_state == DriveState::ChangingSpeedOrTOCRead && !ignore_speed_change)
{
// we're still reading the TOC, so add that time in
const TickCount remaining_change_ticks = m_drive_event->GetTicksUntilNextExecution();
ticks += remaining_change_ticks;
Log_DevPrintf("Seek time for %u LBAs: %d (%.3f ms) (%d for speed change/implicit TOC read)", lba_diff, ticks,
(static_cast<float>(ticks) / static_cast<float>(ticks_per_second)) * 1000.0f, remaining_change_ticks);
}
else
{
Log_DevPrintf("Seek time for %u LBAs: %d (%.3f ms)", lba_diff, ticks,
(static_cast<float>(ticks) / static_cast<float>(ticks_per_second)) * 1000.0f);
}
if (g_settings.cdrom_seek_speedup > 1)
ticks = std::min<u32>(ticks / g_settings.cdrom_seek_speedup, MIN_TICKS);
return System::ScaleTicksToOverclock(static_cast<TickCount>(ticks));
}
TickCount CDROM::GetTicksForStop(bool motor_was_on)
{
return System::ScaleTicksToOverclock(motor_was_on ? (m_mode.double_speed ? 25000000 : 13000000) : 7000);
}
TickCount CDROM::GetTicksForSpeedChange()
{
static constexpr u32 ticks_single_to_double = static_cast<u32>(0.8 * static_cast<double>(System::MASTER_CLOCK));
static constexpr u32 ticks_double_to_single = static_cast<u32>(1.0 * static_cast<double>(System::MASTER_CLOCK));
return System::ScaleTicksToOverclock(m_mode.double_speed ? ticks_single_to_double : ticks_double_to_single);
}
TickCount CDROM::GetTicksForTOCRead()
{
if (!HasMedia())
return 0;
return System::GetTicksPerSecond() / 2u;
}
CDImage::LBA CDROM::GetNextSectorToBeRead()
{
if (!IsReadingOrPlaying())
return m_current_lba;
m_reader.WaitForReadToComplete();
return m_reader.GetLastReadSector();
}
void CDROM::BeginCommand(Command command)
{
TickCount ack_delay = GetAckDelayForCommand(command);
if (HasPendingCommand())
{
// The behavior here is kinda.. interesting. Some commands seem to take precedence over others, for example
// sending a Nop command followed by a GetlocP will return the GetlocP response, and the same for the inverse.
// However, other combinations result in strange behavior, for example sending a Setloc followed by a ReadN will
// fail with ERROR_REASON_INCORRECT_NUMBER_OF_PARAMETERS. This particular example happens in Voice Idol
// Collection - Pool Bar Story, and the loading time is lengthened as well as audio slowing down if this
// behavior is not correct. So, let's use a heuristic; if the number of parameters of the "old" command is
// greater than the "new" command, empty the FIFO, which will return the error when the command executes.
// Otherwise, override the command with the new one.
if (s_command_info[static_cast<u8>(m_command)].expected_parameters >
s_command_info[static_cast<u8>(command)].expected_parameters)
{
Log_WarningPrintf("Ignoring command 0x%02X (%s) and emptying FIFO as 0x%02x (%s) is still pending",
static_cast<u8>(command), s_command_info[static_cast<u8>(command)].name,
static_cast<u8>(m_command), s_command_info[static_cast<u8>(m_command)].name);
m_param_fifo.Clear();
return;
}
Log_WarningPrintf("Cancelling pending command 0x%02X (%s) for new command 0x%02X (%s)", static_cast<u8>(m_command),
s_command_info[static_cast<u8>(m_command)].name, static_cast<u8>(command),
s_command_info[static_cast<u8>(command)].name);
// subtract the currently-elapsed ack ticks from the new command
if (m_command_event->IsActive())
{
const TickCount elapsed_ticks = m_command_event->GetInterval() - m_command_event->GetTicksUntilNextExecution();
ack_delay = std::max(ack_delay - elapsed_ticks, 1);
m_command_event->Deactivate();
}
}
if (m_command_second_response != Command::None)
{
Log_WarningPrintf("Cancelling pending command 0x%02X (%s) second response",
static_cast<u16>(m_command_second_response),
s_command_info[static_cast<u16>(m_command_second_response)].name);
ClearCommandSecondResponse();
}
m_command = command;
m_command_event->SetIntervalAndSchedule(ack_delay);
UpdateCommandEvent();
UpdateStatusRegister();
}
void CDROM::EndCommand()
{
m_param_fifo.Clear();
m_command = Command::None;
m_command_event->Deactivate();
UpdateStatusRegister();
}
void CDROM::AbortCommand()
{
m_command = Command::None;
m_command_event->Deactivate();
UpdateStatusRegister();
}
void CDROM::ExecuteCommand(TickCount ticks_late)
{
const CommandInfo& ci = s_command_info[static_cast<u8>(m_command)];
Log_DevPrintf("CDROM executing command 0x%02X (%s), stat = 0x%02X", static_cast<u8>(m_command), ci.name,
m_secondary_status.bits);
if (m_param_fifo.GetSize() < ci.expected_parameters)
{
Log_WarningPrintf("Too few parameters for command 0x%02X (%s), expecting %u got %u", static_cast<u8>(m_command),
ci.name, ci.expected_parameters, m_param_fifo.GetSize());
SendErrorResponse(STAT_ERROR, ERROR_REASON_INCORRECT_NUMBER_OF_PARAMETERS);
EndCommand();
return;
}
if (!m_response_fifo.IsEmpty())
{
Log_DebugPrintf("Response FIFO not empty on command begin");
m_response_fifo.Clear();
}
switch (m_command)
{
case Command::Getstat:
{
Log_DebugPrintf("CDROM Getstat command");
// if bit 0 or 2 is set, send an additional byte
SendACKAndStat();
// shell open bit is cleared after sending the status
if (CanReadMedia())
m_secondary_status.shell_open = false;
EndCommand();
return;
}
case Command::Test:
{
const u8 subcommand = m_param_fifo.Pop();
ExecuteTestCommand(subcommand);
return;
}
case Command::GetID:
{
Log_DebugPrintf("CDROM GetID command");
if (!CanReadMedia())
{