/
DVDInterface.cpp
1671 lines (1441 loc) · 57.7 KB
/
DVDInterface.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
// Copyright 2008 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "Core/HW/DVD/DVDInterface.h"
#include <algorithm>
#include <memory>
#include <optional>
#include <string>
#include <vector>
#include "AudioCommon/AudioCommon.h"
#include "Common/Align.h"
#include "Common/BitField.h"
#include "Common/ChunkFile.h"
#include "Common/CommonTypes.h"
#include "Common/Config/Config.h"
#include "Common/Logging/Log.h"
#include "Core/Config/MainSettings.h"
#include "Core/Config/SessionSettings.h"
#include "Core/CoreTiming.h"
#include "Core/DolphinAnalytics.h"
#include "Core/HW/AudioInterface.h"
#include "Core/HW/DVD/DVDMath.h"
#include "Core/HW/DVD/DVDThread.h"
#include "Core/HW/EXI/EXI_DeviceIPL.h"
#include "Core/HW/MMIO.h"
#include "Core/HW/Memmap.h"
#include "Core/HW/ProcessorInterface.h"
#include "Core/HW/StreamADPCM.h"
#include "Core/HW/SystemTimers.h"
#include "Core/IOS/DI/DI.h"
#include "Core/IOS/IOS.h"
#include "Core/Movie.h"
#include "Core/System.h"
#include "DiscIO/Blob.h"
#include "DiscIO/DiscUtils.h"
#include "DiscIO/Enums.h"
#include "DiscIO/VolumeDisc.h"
#include "DiscIO/VolumeWii.h"
#include "VideoCommon/OnScreenDisplay.h"
// The minimum time it takes for the DVD drive to process a command (in microseconds)
constexpr u64 MINIMUM_COMMAND_LATENCY_US = 300;
// The time it takes for a read command to start (in microseconds)
constexpr u64 READ_COMMAND_LATENCY_US = 600;
// The size of the streaming buffer.
constexpr u64 STREAMING_BUFFER_SIZE = 1024 * 1024;
// A single DVD disc sector
constexpr u64 DVD_SECTOR_SIZE = 0x800;
// The minimum amount that a drive will read
constexpr u64 DVD_ECC_BLOCK_SIZE = 16 * DVD_SECTOR_SIZE;
// Rate the drive can transfer data to main memory, given the data
// is already buffered. Measured in bytes per second.
constexpr u64 BUFFER_TRANSFER_RATE = 32 * 1024 * 1024;
namespace DVDInterface
{
// internal hardware addresses
constexpr u32 DI_STATUS_REGISTER = 0x00;
constexpr u32 DI_COVER_REGISTER = 0x04;
constexpr u32 DI_COMMAND_0 = 0x08;
constexpr u32 DI_COMMAND_1 = 0x0C;
constexpr u32 DI_COMMAND_2 = 0x10;
constexpr u32 DI_DMA_ADDRESS_REGISTER = 0x14;
constexpr u32 DI_DMA_LENGTH_REGISTER = 0x18;
constexpr u32 DI_DMA_CONTROL_REGISTER = 0x1C;
constexpr u32 DI_IMMEDIATE_DATA_BUFFER = 0x20;
constexpr u32 DI_CONFIG_REGISTER = 0x24;
// DI Status Register
union UDISR
{
u32 Hex = 0;
BitField<0, 1, u32> BREAK; // Stop the Device + Interrupt
BitField<1, 1, u32> DEINTMASK; // Access Device Error Int Mask
BitField<2, 1, u32> DEINT; // Access Device Error Int
BitField<3, 1, u32> TCINTMASK; // Transfer Complete Int Mask
BitField<4, 1, u32> TCINT; // Transfer Complete Int
BitField<5, 1, u32> BRKINTMASK;
BitField<6, 1, u32> BRKINT; // w 1: clear brkint
BitField<7, 25, u32> reserved;
UDISR() = default;
explicit UDISR(u32 hex) : Hex{hex} {}
};
// DI Cover Register
union UDICVR
{
u32 Hex = 0;
BitField<0, 1, u32> CVR; // 0: Cover closed 1: Cover open
BitField<1, 1, u32> CVRINTMASK; // 1: Interrupt enabled
BitField<2, 1, u32> CVRINT; // r 1: Interrupt requested w 1: Interrupt clear
BitField<3, 29, u32> reserved;
UDICVR() = default;
explicit UDICVR(u32 hex) : Hex{hex} {}
};
// DI DMA Control Register
union UDICR
{
u32 Hex = 0;
BitField<0, 1, u32> TSTART; // w:1 start r:0 ready
BitField<1, 1, u32> DMA; // 1: DMA Mode
// 0: Immediate Mode (can only do Access Register Command)
BitField<2, 1, u32> RW; // 0: Read Command (DVD to Memory) 1: Write Command (Memory to DVD)
BitField<3, 29, u32> reserved;
};
// DI Config Register
union UDICFG
{
u32 Hex = 0;
BitField<0, 8, u32> CONFIG;
BitField<8, 24, u32> reserved;
UDICFG() = default;
explicit UDICFG(u32 hex) : Hex{hex} {}
};
struct DVDInterfaceState::Data
{
// Hardware registers
UDISR DISR;
UDICVR DICVR;
u32 DICMDBUF[3];
u32 DIMAR;
u32 DILENGTH;
UDICR DICR;
u32 DIIMMBUF;
UDICFG DICFG;
StreamADPCM::ADPCMDecoder adpcm_decoder;
// DTK
bool stream = false;
bool stop_at_track_end = false;
u64 audio_position;
u64 current_start;
u32 current_length;
u64 next_start;
u32 next_length;
u32 pending_samples;
bool enable_dtk = false;
u8 dtk_buffer_length = 0; // TODO: figure out how this affects the regular buffer
// Disc drive state
DriveState drive_state;
DriveError error_code;
u64 disc_end_offset;
// Disc drive timing
u64 read_buffer_start_time;
u64 read_buffer_end_time;
u64 read_buffer_start_offset;
u64 read_buffer_end_offset;
// Disc changing
std::string disc_path_to_insert;
std::vector<std::string> auto_disc_change_paths;
size_t auto_disc_change_index;
// Events
CoreTiming::EventType* finish_executing_command;
CoreTiming::EventType* auto_change_disc;
CoreTiming::EventType* eject_disc;
CoreTiming::EventType* insert_disc;
};
DVDInterfaceState::DVDInterfaceState() : m_data(std::make_unique<Data>())
{
}
DVDInterfaceState::~DVDInterfaceState() = default;
static void AutoChangeDiscCallback(Core::System& system, u64 userdata, s64 cyclesLate);
static void EjectDiscCallback(Core::System& system, u64 userdata, s64 cyclesLate);
static void InsertDiscCallback(Core::System& system, u64 userdata, s64 cyclesLate);
static void FinishExecutingCommandCallback(Core::System& system, u64 userdata, s64 cycles_late);
static void SetLidOpen();
static void UpdateInterrupts();
static void GenerateDIInterrupt(DIInterruptType dvd_interrupt);
static bool ExecuteReadCommand(u64 dvd_offset, u32 output_address, u32 dvd_length,
u32 output_length, const DiscIO::Partition& partition,
ReplyType reply_type, DIInterruptType* interrupt_type);
static u64 PackFinishExecutingCommandUserdata(ReplyType reply_type, DIInterruptType interrupt_type);
static void ScheduleReads(u64 offset, u32 length, const DiscIO::Partition& partition,
u32 output_address, ReplyType reply_type);
void DoState(PointerWrap& p)
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
p.Do(state.DISR);
p.Do(state.DICVR);
p.DoArray(state.DICMDBUF);
p.Do(state.DIMAR);
p.Do(state.DILENGTH);
p.Do(state.DICR);
p.Do(state.DIIMMBUF);
p.Do(state.DICFG);
p.Do(state.stream);
p.Do(state.stop_at_track_end);
p.Do(state.audio_position);
p.Do(state.current_start);
p.Do(state.current_length);
p.Do(state.next_start);
p.Do(state.next_length);
p.Do(state.pending_samples);
p.Do(state.enable_dtk);
p.Do(state.dtk_buffer_length);
p.Do(state.drive_state);
p.Do(state.error_code);
p.Do(state.read_buffer_start_time);
p.Do(state.read_buffer_end_time);
p.Do(state.read_buffer_start_offset);
p.Do(state.read_buffer_end_offset);
p.Do(state.disc_path_to_insert);
DVDThread::DoState(p);
state.adpcm_decoder.DoState(p);
}
static size_t ProcessDTKSamples(std::vector<s16>* temp_pcm, const std::vector<u8>& audio_data)
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
size_t samples_processed = 0;
size_t bytes_processed = 0;
while (samples_processed < temp_pcm->size() / 2 && bytes_processed < audio_data.size())
{
state.adpcm_decoder.DecodeBlock(&(*temp_pcm)[samples_processed * 2],
&audio_data[bytes_processed]);
for (size_t i = 0; i < StreamADPCM::SAMPLES_PER_BLOCK * 2; ++i)
{
// TODO: Fix the mixer so it can accept non-byte-swapped samples.
s16* sample = &(*temp_pcm)[samples_processed * 2 + i];
*sample = Common::swap16(*sample);
}
samples_processed += StreamADPCM::SAMPLES_PER_BLOCK;
bytes_processed += StreamADPCM::ONE_BLOCK_SIZE;
}
return samples_processed;
}
static u32 AdvanceDTK(u32 maximum_samples, u32* samples_to_process)
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
u32 bytes_to_process = 0;
*samples_to_process = 0;
while (*samples_to_process < maximum_samples)
{
if (state.audio_position >= state.current_start + state.current_length)
{
DEBUG_LOG_FMT(DVDINTERFACE,
"AdvanceDTK: NextStart={:08x}, NextLength={:08x}, "
"CurrentStart={:08x}, CurrentLength={:08x}, AudioPos={:08x}",
state.next_start, state.next_length, state.current_start, state.current_length,
state.audio_position);
state.audio_position = state.next_start;
state.current_start = state.next_start;
state.current_length = state.next_length;
if (state.stop_at_track_end)
{
state.stop_at_track_end = false;
state.stream = false;
break;
}
state.adpcm_decoder.ResetFilter();
}
state.audio_position += StreamADPCM::ONE_BLOCK_SIZE;
bytes_to_process += StreamADPCM::ONE_BLOCK_SIZE;
*samples_to_process += StreamADPCM::SAMPLES_PER_BLOCK;
}
return bytes_to_process;
}
static void DTKStreamingCallback(DIInterruptType interrupt_type, const std::vector<u8>& audio_data,
s64 cycles_late)
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
// Actual games always set this to 48 KHz
// but let's make sure to use GetAISSampleRateDivisor()
// just in case it changes to 32 KHz
const u32 sample_rate_divisor = AudioInterface::GetAISSampleRateDivisor();
// Determine which audio data to read next.
// 3.5 ms of samples
const u32 maximum_samples =
((Mixer::FIXED_SAMPLE_RATE_DIVIDEND / 2000) * 7) / sample_rate_divisor;
u64 read_offset = 0;
u32 read_length = 0;
if (interrupt_type == DIInterruptType::TCINT)
{
// Send audio to the mixer.
std::vector<s16> temp_pcm(state.pending_samples * 2, 0);
ProcessDTKSamples(&temp_pcm, audio_data);
auto& system = Core::System::GetInstance();
SoundStream* sound_stream = system.GetSoundStream();
sound_stream->GetMixer()->PushStreamingSamples(temp_pcm.data(), state.pending_samples);
if (state.stream && AudioInterface::IsPlaying())
{
read_offset = state.audio_position;
read_length = AdvanceDTK(maximum_samples, &state.pending_samples);
}
else
{
read_length = 0;
state.pending_samples = maximum_samples;
}
}
else
{
read_length = 0;
state.pending_samples = maximum_samples;
}
// Read the next chunk of audio data asynchronously.
s64 ticks_to_dtk = SystemTimers::GetTicksPerSecond() * s64(state.pending_samples) *
sample_rate_divisor / Mixer::FIXED_SAMPLE_RATE_DIVIDEND;
ticks_to_dtk -= cycles_late;
if (read_length > 0)
{
DVDThread::StartRead(read_offset, read_length, DiscIO::PARTITION_NONE, ReplyType::DTK,
ticks_to_dtk);
}
else
{
// There's nothing to read, so using DVDThread is unnecessary.
u64 userdata = PackFinishExecutingCommandUserdata(ReplyType::DTK, DIInterruptType::TCINT);
CoreTiming::ScheduleEvent(ticks_to_dtk, state.finish_executing_command, userdata);
}
}
void Init()
{
ASSERT(!IsDiscInside());
DVDThread::Start();
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
state.DISR.Hex = 0;
state.DICVR.Hex = 1; // Disc Channel relies on cover being open when no disc is inserted
state.DICMDBUF[0] = 0;
state.DICMDBUF[1] = 0;
state.DICMDBUF[2] = 0;
state.DIMAR = 0;
state.DILENGTH = 0;
state.DICR.Hex = 0;
state.DIIMMBUF = 0;
state.DICFG.Hex = 0;
state.DICFG.CONFIG = 1; // Disable bootrom descrambler
ResetDrive(false);
state.auto_change_disc = CoreTiming::RegisterEvent("AutoChangeDisc", AutoChangeDiscCallback);
state.eject_disc = CoreTiming::RegisterEvent("EjectDisc", EjectDiscCallback);
state.insert_disc = CoreTiming::RegisterEvent("InsertDisc", InsertDiscCallback);
state.finish_executing_command =
CoreTiming::RegisterEvent("FinishExecutingCommand", FinishExecutingCommandCallback);
u64 userdata = PackFinishExecutingCommandUserdata(ReplyType::DTK, DIInterruptType::TCINT);
CoreTiming::ScheduleEvent(0, state.finish_executing_command, userdata);
}
// Resets state on the MN102 chip in the drive itself, but not the DI registers exposed on the
// emulated device, or any inserted disc.
void ResetDrive(bool spinup)
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
state.stream = false;
state.stop_at_track_end = false;
state.audio_position = 0;
state.next_start = 0;
state.next_length = 0;
state.current_start = 0;
state.current_length = 0;
state.pending_samples = 0;
state.enable_dtk = false;
state.dtk_buffer_length = 0;
if (!IsDiscInside())
{
// CoverOpened is used when the cover is open;
// NoMediumPresent is used when the cover is closed but there is no disc.
// On the Wii, this can only happen if something other than a DVD is inserted into the disc
// drive (for instance, an audio CD) and only after it attempts to read it. Otherwise, it will
// report the cover as opened.
SetDriveState(DriveState::CoverOpened);
}
else if (!spinup)
{
// Wii hardware tests indicate that this is used when ejecting and inserting a new disc, or
// performing a reset without spinup.
SetDriveState(DriveState::DiscChangeDetected);
}
else
{
SetDriveState(DriveState::DiscIdNotRead);
}
SetDriveError(DriveError::None);
// The buffer is empty at start
state.read_buffer_start_offset = 0;
state.read_buffer_end_offset = 0;
state.read_buffer_start_time = 0;
state.read_buffer_end_time = 0;
}
void Shutdown()
{
DVDThread::Stop();
}
static u64 GetDiscEndOffset(const DiscIO::VolumeDisc& disc)
{
u64 size = disc.GetDataSize();
if (disc.GetDataSizeType() == DiscIO::DataSizeType::Accurate)
{
if (size == DiscIO::MINI_DVD_SIZE)
return DiscIO::MINI_DVD_SIZE;
}
else
{
size = DiscIO::GetBiggestReferencedOffset(disc);
}
const bool should_be_mini_dvd =
disc.GetVolumeType() == DiscIO::Platform::GameCubeDisc || disc.IsDatelDisc();
// We always return standard DVD sizes here, not DVD-R sizes.
// RVT-R (devkit) consoles can't read the extra megabytes there are on RVT-R (DVD-R) discs.
if (should_be_mini_dvd && size <= DiscIO::MINI_DVD_SIZE)
return DiscIO::MINI_DVD_SIZE;
else if (size <= DiscIO::SL_DVD_R_SIZE)
return DiscIO::SL_DVD_SIZE;
else
return DiscIO::DL_DVD_SIZE;
}
void SetDisc(std::unique_ptr<DiscIO::VolumeDisc> disc,
std::optional<std::vector<std::string>> auto_disc_change_paths = {})
{
bool had_disc = IsDiscInside();
bool has_disc = static_cast<bool>(disc);
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
if (has_disc)
{
state.disc_end_offset = GetDiscEndOffset(*disc);
if (disc->GetDataSizeType() != DiscIO::DataSizeType::Accurate)
WARN_LOG_FMT(DVDINTERFACE, "Unknown disc size, guessing {0} bytes", state.disc_end_offset);
const DiscIO::BlobReader& blob = disc->GetBlobReader();
// DirectoryBlobs (including Riivolution-patched discs) may end up larger than a real physical
// Wii disc, which triggers Error #001. In those cases we manually make the check succeed to
// avoid problems.
const bool should_fake_error_001 =
SConfig::GetInstance().bWii && blob.GetBlobType() == DiscIO::BlobType::DIRECTORY;
Config::SetCurrent(Config::SESSION_SHOULD_FAKE_ERROR_001, should_fake_error_001);
if (!blob.HasFastRandomAccessInBlock() && blob.GetBlockSize() > 0x200000)
{
OSD::AddMessage("You are running a disc image with a very large block size.", 60000);
OSD::AddMessage("This will likely lead to performance problems.", 60000);
OSD::AddMessage("You can use Dolphin's convert feature to reduce the block size.", 60000);
}
}
if (auto_disc_change_paths)
{
ASSERT_MSG(DISCIO, (*auto_disc_change_paths).size() != 1,
"Cannot automatically change between one disc");
state.auto_disc_change_paths = *auto_disc_change_paths;
state.auto_disc_change_index = 0;
}
// Assume that inserting a disc requires having an empty disc before
if (had_disc != has_disc)
ExpansionInterface::g_rtc_flags[ExpansionInterface::RTCFlag::DiscChanged] = true;
DVDThread::SetDisc(std::move(disc));
SetLidOpen();
ResetDrive(false);
}
bool IsDiscInside()
{
return DVDThread::HasDisc();
}
static void AutoChangeDiscCallback(Core::System& system, u64 userdata, s64 cyclesLate)
{
AutoChangeDisc();
}
static void EjectDiscCallback(Core::System& system, u64 userdata, s64 cyclesLate)
{
SetDisc(nullptr, {});
}
static void InsertDiscCallback(Core::System& system, u64 userdata, s64 cyclesLate)
{
auto& state = system.GetDVDInterfaceState().GetData();
std::unique_ptr<DiscIO::VolumeDisc> new_disc = DiscIO::CreateDisc(state.disc_path_to_insert);
if (new_disc)
SetDisc(std::move(new_disc), {});
else
PanicAlertFmtT("The disc that was about to be inserted couldn't be found.");
state.disc_path_to_insert.clear();
}
// Must only be called on the CPU thread
void EjectDisc(EjectCause cause)
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
CoreTiming::ScheduleEvent(0, state.eject_disc);
if (cause == EjectCause::User)
ExpansionInterface::g_rtc_flags[ExpansionInterface::RTCFlag::EjectButton] = true;
}
// Must only be called on the CPU thread
void ChangeDisc(const std::vector<std::string>& paths)
{
ASSERT_MSG(DISCIO, !paths.empty(), "Trying to insert an empty list of discs");
if (paths.size() > 1)
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
state.auto_disc_change_paths = paths;
state.auto_disc_change_index = 0;
}
ChangeDisc(paths[0]);
}
// Must only be called on the CPU thread
void ChangeDisc(const std::string& new_path)
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
if (!state.disc_path_to_insert.empty())
{
PanicAlertFmtT("A disc is already about to be inserted.");
return;
}
EjectDisc(EjectCause::User);
state.disc_path_to_insert = new_path;
CoreTiming::ScheduleEvent(SystemTimers::GetTicksPerSecond(), state.insert_disc);
Movie::SignalDiscChange(new_path);
for (size_t i = 0; i < state.auto_disc_change_paths.size(); ++i)
{
if (state.auto_disc_change_paths[i] == new_path)
{
state.auto_disc_change_index = i;
return;
}
}
state.auto_disc_change_paths.clear();
}
// Must only be called on the CPU thread
bool AutoChangeDisc()
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
if (state.auto_disc_change_paths.empty())
return false;
state.auto_disc_change_index =
(state.auto_disc_change_index + 1) % state.auto_disc_change_paths.size();
ChangeDisc(state.auto_disc_change_paths[state.auto_disc_change_index]);
return true;
}
static void SetLidOpen()
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
const u32 old_value = state.DICVR.CVR;
state.DICVR.CVR = IsDiscInside() ? 0 : 1;
if (state.DICVR.CVR != old_value)
GenerateDIInterrupt(DIInterruptType::CVRINT);
}
bool UpdateRunningGameMetadata(std::optional<u64> title_id)
{
if (!DVDThread::HasDisc())
return false;
return DVDThread::UpdateRunningGameMetadata(IOS::HLE::DIDevice::GetCurrentPartition(), title_id);
}
void RegisterMMIO(MMIO::Mapping* mmio, u32 base, bool is_wii)
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
mmio->Register(base | DI_STATUS_REGISTER, MMIO::DirectRead<u32>(&state.DISR.Hex),
MMIO::ComplexWrite<u32>([](Core::System& system, u32, u32 val) {
auto& state = system.GetDVDInterfaceState().GetData();
const UDISR tmp_status_reg(val);
state.DISR.DEINTMASK = tmp_status_reg.DEINTMASK.Value();
state.DISR.TCINTMASK = tmp_status_reg.TCINTMASK.Value();
state.DISR.BRKINTMASK = tmp_status_reg.BRKINTMASK.Value();
state.DISR.BREAK = tmp_status_reg.BREAK.Value();
if (tmp_status_reg.DEINT)
state.DISR.DEINT = 0;
if (tmp_status_reg.TCINT)
state.DISR.TCINT = 0;
if (tmp_status_reg.BRKINT)
state.DISR.BRKINT = 0;
if (state.DISR.BREAK)
{
DEBUG_ASSERT(0);
}
UpdateInterrupts();
}));
mmio->Register(base | DI_COVER_REGISTER, MMIO::DirectRead<u32>(&state.DICVR.Hex),
MMIO::ComplexWrite<u32>([](Core::System& system, u32, u32 val) {
auto& state = system.GetDVDInterfaceState().GetData();
const UDICVR tmp_cover_reg(val);
state.DICVR.CVRINTMASK = tmp_cover_reg.CVRINTMASK.Value();
if (tmp_cover_reg.CVRINT)
state.DICVR.CVRINT = 0;
UpdateInterrupts();
}));
// Command registers, which have no special logic
mmio->Register(base | DI_COMMAND_0, MMIO::DirectRead<u32>(&state.DICMDBUF[0]),
MMIO::DirectWrite<u32>(&state.DICMDBUF[0]));
mmio->Register(base | DI_COMMAND_1, MMIO::DirectRead<u32>(&state.DICMDBUF[1]),
MMIO::DirectWrite<u32>(&state.DICMDBUF[1]));
mmio->Register(base | DI_COMMAND_2, MMIO::DirectRead<u32>(&state.DICMDBUF[2]),
MMIO::DirectWrite<u32>(&state.DICMDBUF[2]));
// DMA related registers. Mostly direct accesses (+ masking for writes to
// handle things like address alignment) and complex write on the DMA
// control register that will trigger the DMA.
// The DMA address register masks away the top and bottom bits on GameCube, but only the top bits
// on Wii (which can be observed by reading back the register; this difference probably exists due
// to the existence of MEM2). The behavior of GameCube mode on a Wii (via MIOS/booting form the
// system menu) has not been tested yet. Note that RegisterMMIO does not get re-called when
// switching to GameCube mode; we handle this difference by applying the masking when using the
// GameCube's DI MMIO address (0x0C006000) but not applying it when using the Wii's DI MMIO
// address (0x0D006000), although we allow writes to both of these addresses if Dolphin was
// started in Wii mode. (Also, normally in Wii mode the DI MMIOs are only written by the
// IOS /dev/di module, but we *do* emulate /dev/di writing the DI MMIOs.)
mmio->Register(base | DI_DMA_ADDRESS_REGISTER, MMIO::DirectRead<u32>(&state.DIMAR),
MMIO::DirectWrite<u32>(&state.DIMAR, is_wii ? ~0x1F : ~0xFC00001F));
mmio->Register(base | DI_DMA_LENGTH_REGISTER, MMIO::DirectRead<u32>(&state.DILENGTH),
MMIO::DirectWrite<u32>(&state.DILENGTH, ~0x1F));
mmio->Register(base | DI_DMA_CONTROL_REGISTER, MMIO::DirectRead<u32>(&state.DICR.Hex),
MMIO::ComplexWrite<u32>([](Core::System& system, u32, u32 val) {
auto& state = system.GetDVDInterfaceState().GetData();
state.DICR.Hex = val & 7;
if (state.DICR.TSTART)
{
ExecuteCommand(ReplyType::Interrupt);
}
}));
mmio->Register(base | DI_IMMEDIATE_DATA_BUFFER, MMIO::DirectRead<u32>(&state.DIIMMBUF),
MMIO::DirectWrite<u32>(&state.DIIMMBUF));
// DI config register is read only.
mmio->Register(base | DI_CONFIG_REGISTER, MMIO::DirectRead<u32>(&state.DICFG.Hex),
MMIO::InvalidWrite<u32>());
}
static void UpdateInterrupts()
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
const bool set_mask = (state.DISR.DEINT & state.DISR.DEINTMASK) != 0 ||
(state.DISR.TCINT & state.DISR.TCINTMASK) != 0 ||
(state.DISR.BRKINT & state.DISR.BRKINTMASK) != 0 ||
(state.DICVR.CVRINT & state.DICVR.CVRINTMASK) != 0;
ProcessorInterface::SetInterrupt(ProcessorInterface::INT_CAUSE_DI, set_mask);
// Required for Summoner: A Goddess Reborn
CoreTiming::ForceExceptionCheck(50);
}
static void GenerateDIInterrupt(DIInterruptType dvd_interrupt)
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
switch (dvd_interrupt)
{
case DIInterruptType::DEINT:
state.DISR.DEINT = true;
break;
case DIInterruptType::TCINT:
state.DISR.TCINT = true;
break;
case DIInterruptType::BRKINT:
state.DISR.BRKINT = true;
break;
case DIInterruptType::CVRINT:
state.DICVR.CVRINT = true;
break;
}
UpdateInterrupts();
}
void SetInterruptEnabled(DIInterruptType interrupt, bool enabled)
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
switch (interrupt)
{
case DIInterruptType::DEINT:
state.DISR.DEINTMASK = enabled;
break;
case DIInterruptType::TCINT:
state.DISR.TCINTMASK = enabled;
break;
case DIInterruptType::BRKINT:
state.DISR.BRKINTMASK = enabled;
break;
case DIInterruptType::CVRINT:
state.DICVR.CVRINTMASK = enabled;
break;
}
}
void ClearInterrupt(DIInterruptType interrupt)
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
switch (interrupt)
{
case DIInterruptType::DEINT:
state.DISR.DEINT = false;
break;
case DIInterruptType::TCINT:
state.DISR.TCINT = false;
break;
case DIInterruptType::BRKINT:
state.DISR.BRKINT = false;
break;
case DIInterruptType::CVRINT:
state.DICVR.CVRINT = false;
break;
}
}
// Checks the drive state to make sure a read-like command can be performed.
// If false is returned, SetDriveError will have been called, and the caller
// should issue a DEINT interrupt.
static bool CheckReadPreconditions()
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
if (!IsDiscInside()) // Implies CoverOpened or NoMediumPresent
{
ERROR_LOG_FMT(DVDINTERFACE, "No disc inside.");
SetDriveError(DriveError::MediumNotPresent);
return false;
}
if (state.drive_state == DriveState::DiscChangeDetected)
{
ERROR_LOG_FMT(DVDINTERFACE, "Disc changed (motor stopped).");
SetDriveError(DriveError::MediumChanged);
return false;
}
if (state.drive_state == DriveState::MotorStopped)
{
ERROR_LOG_FMT(DVDINTERFACE, "Motor stopped.");
SetDriveError(DriveError::MotorStopped);
return false;
}
if (state.drive_state == DriveState::DiscIdNotRead)
{
ERROR_LOG_FMT(DVDINTERFACE, "Disc id not read.");
SetDriveError(DriveError::NoDiscID);
return false;
}
return true;
}
// Iff false is returned, ScheduleEvent must be used to finish executing the command
static bool ExecuteReadCommand(u64 dvd_offset, u32 output_address, u32 dvd_length,
u32 output_length, const DiscIO::Partition& partition,
ReplyType reply_type, DIInterruptType* interrupt_type)
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
if (!CheckReadPreconditions())
{
// Disc read fails
*interrupt_type = DIInterruptType::DEINT;
return false;
}
else
{
// Disc read succeeds
*interrupt_type = DIInterruptType::TCINT;
}
if (dvd_length > output_length)
{
WARN_LOG_FMT(DVDINTERFACE, "Detected an attempt to read more data from the DVD "
"than what fits inside the out buffer. Clamping.");
dvd_length = output_length;
}
// Many Wii games intentionally try to read from an offset which is just past the end of a
// regular DVD but just before the end of a DVD-R, displaying "Error #001" and failing to boot
// if the read succeeds, so it's critical that we set the correct error code for such reads.
// See https://wiibrew.org/wiki//dev/di#0x8D_DVDLowUnencryptedRead for details on Error #001.
if (dvd_offset + dvd_length > state.disc_end_offset)
{
SetDriveError(DriveError::BlockOOB);
*interrupt_type = DIInterruptType::DEINT;
return false;
}
ScheduleReads(dvd_offset, dvd_length, partition, output_address, reply_type);
return true;
}
// When the command has finished executing, callback_event_type
// will be called using CoreTiming::ScheduleEvent,
// with the userdata set to the interrupt type.
void ExecuteCommand(ReplyType reply_type)
{
auto& state = Core::System::GetInstance().GetDVDInterfaceState().GetData();
DIInterruptType interrupt_type = DIInterruptType::TCINT;
bool command_handled_by_thread = false;
// DVDLowRequestError needs access to the error code set by the previous command
if (static_cast<DICommand>(state.DICMDBUF[0] >> 24) != DICommand::RequestError)
SetDriveError(DriveError::None);
switch (static_cast<DICommand>(state.DICMDBUF[0] >> 24))
{
// Used by both GC and Wii
case DICommand::Inquiry:
// (shuffle2) Taken from my Wii
Memory::Write_U32(0x00000002, state.DIMAR); // Revision level, device code
Memory::Write_U32(0x20060526, state.DIMAR + 4); // Release date
Memory::Write_U32(0x41000000, state.DIMAR + 8); // Version
INFO_LOG_FMT(DVDINTERFACE, "DVDLowInquiry (Buffer {:#010x}, {:#x})", state.DIMAR,
state.DILENGTH);
break;
// GC-only patched drive firmware command, used by libogc
case DICommand::Unknown55:
INFO_LOG_FMT(DVDINTERFACE, "SetExtension");
SetDriveError(DriveError::InvalidCommand);
interrupt_type = DIInterruptType::DEINT;
break;
// Wii-exclusive
case DICommand::ReportKey:
INFO_LOG_FMT(DVDINTERFACE, "DVDLowReportKey");
// Does not work on retail discs/drives
// Retail games send this command to see if they are running on real retail hw
SetDriveError(DriveError::InvalidCommand);
interrupt_type = DIInterruptType::DEINT;
break;
// DMA Read from Disc. Only used through direct access on GC; direct use is prohibited by
// IOS (which uses it internally)
case DICommand::Read:
switch (state.DICMDBUF[0] & 0xFF)
{
case 0x00: // Read Sector
{
const u64 dvd_offset = static_cast<u64>(state.DICMDBUF[1]) << 2;
INFO_LOG_FMT(
DVDINTERFACE,
"Read: DVDOffset={:08x}, DMABuffer = {:08x}, SrcLength = {:08x}, DMALength = {:08x}",
dvd_offset, state.DIMAR, state.DICMDBUF[2], state.DILENGTH);
if (state.drive_state == DriveState::ReadyNoReadsMade)
SetDriveState(DriveState::Ready);
command_handled_by_thread =
ExecuteReadCommand(dvd_offset, state.DIMAR, state.DICMDBUF[2], state.DILENGTH,
DiscIO::PARTITION_NONE, reply_type, &interrupt_type);
}
break;
case 0x40: // Read DiscID
INFO_LOG_FMT(DVDINTERFACE, "Read DiscID: buffer {:08x}", state.DIMAR);
if (state.drive_state == DriveState::DiscIdNotRead)
{
SetDriveState(DriveState::ReadyNoReadsMade);
}
else if (state.drive_state == DriveState::ReadyNoReadsMade)
{
// The first disc ID reading is required before DTK can be configured.
// If the disc ID is read again (or any other read occurs), it no longer can
// be configured.
SetDriveState(DriveState::Ready);
}
command_handled_by_thread =
ExecuteReadCommand(0, state.DIMAR, 0x20, state.DILENGTH, DiscIO::PARTITION_NONE,
reply_type, &interrupt_type);
break;
default:
ERROR_LOG_FMT(DVDINTERFACE, "Unknown read subcommand: {:08x}", state.DICMDBUF[0]);
break;
}
break;
// Used by both GC and Wii
case DICommand::Seek:
// Currently unimplemented
INFO_LOG_FMT(DVDINTERFACE, "Seek: offset={:09x} (ignoring)",
static_cast<u64>(state.DICMDBUF[1]) << 2);
break;
// Wii-exclusive
case DICommand::ReadDVDMetadata:
switch ((state.DICMDBUF[0] >> 16) & 0xFF)
{
case 0:
ERROR_LOG_FMT(DVDINTERFACE, "DVDLowReadDvdPhysical");
break;
case 1:
ERROR_LOG_FMT(DVDINTERFACE, "DVDLowReadDvdCopyright");
break;
case 2:
ERROR_LOG_FMT(DVDINTERFACE, "DVDLowReadDvdDiscKey");
break;
default:
ERROR_LOG_FMT(DVDINTERFACE, "Unknown 0xAD subcommand in {:08x}", state.DICMDBUF[0]);
break;
}
SetDriveError(DriveError::InvalidCommand);
interrupt_type = DIInterruptType::DEINT;
break;
// Wii-exclusive
case DICommand::ReadDVD:
ERROR_LOG_FMT(DVDINTERFACE, "DVDLowReadDvd");
SetDriveError(DriveError::InvalidCommand);
interrupt_type = DIInterruptType::DEINT;
break;
// Wii-exclusive
case DICommand::ReadDVDConfig:
ERROR_LOG_FMT(DVDINTERFACE, "DVDLowReadDvdConfig");
SetDriveError(DriveError::InvalidCommand);