/
Zelda.cpp
1281 lines (1083 loc) · 36.4 KB
/
Zelda.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 2013 Dolphin Emulator Project
// Licensed under GPLv2
// Refer to the license.txt file included.
// Games that use this UCode (exhaustive list):
// * Animal Crossing (type ????, CRC ????)
// * Donkey Kong Jungle Beat (type ????, CRC ????)
// * IPL (type ????, CRC ????)
// * Luigi's Mansion (type ????, CRC ????)
// * Mario Kart: Double Dash!! (type ????, CRC ????)
// * Pikmin (type ????, CRC ????)
// * Pikmin 2 (type ????, CRC ????)
// * Super Mario Galaxy (type ????, CRC ????)
// * Super Mario Galaxy 2 (type ????, CRC ????)
// * Super Mario Sunshine (type ????, CRC ????)
// * The Legend of Zelda: Four Swords Adventures (type ????, CRC ????)
// * The Legend of Zelda: The Wind Waker (type DAC, CRC 86840740)
// * The Legend of Zelda: Twilight Princess (type ????, CRC ????)
#include "Core/ConfigManager.h"
#include "Core/HW/DSPHLE/MailHandler.h"
#include "Core/HW/DSPHLE/UCodes/UCodes.h"
#include "Core/HW/DSPHLE/UCodes/Zelda.h"
ZeldaUCode::ZeldaUCode(DSPHLE *dsphle, u32 crc)
: UCodeInterface(dsphle, crc)
{
m_mail_handler.PushMail(DSP_INIT, true);
m_mail_handler.PushMail(0xF3551111); // handshake
}
ZeldaUCode::~ZeldaUCode()
{
m_mail_handler.Clear();
}
void ZeldaUCode::Update()
{
if (NeedsResumeMail())
{
m_mail_handler.PushMail(DSP_RESUME, true);
}
}
u32 ZeldaUCode::GetUpdateMs()
{
return SConfig::GetInstance().m_LocalCoreStartupParameter.bWii ? 3 : 5;
}
void ZeldaUCode::DoState(PointerWrap &p)
{
p.Do(m_mail_current_state);
p.Do(m_mail_expected_cmd_mails);
p.Do(m_sync_max_voice_id);
p.Do(m_sync_voice_skip_flags);
p.Do(m_cmd_buffer);
p.Do(m_read_offset);
p.Do(m_write_offset);
p.Do(m_pending_commands_count);
p.Do(m_cmd_can_execute);
p.Do(m_rendering_requested_frames);
p.Do(m_rendering_voices_per_frame);
p.Do(m_rendering_curr_frame);
p.Do(m_rendering_curr_voice);
m_renderer.DoState(p);
DoStateShared(p);
}
void ZeldaUCode::HandleMail(u32 mail)
{
if (m_upload_setup_in_progress) // evaluated first!
{
PrepareBootUCode(mail);
return;
}
switch (m_mail_current_state)
{
case MailState::WAITING:
if (mail & 0x80000000)
{
if ((mail >> 16) != 0xCDD1)
{
PanicAlert("Rendering end mail without prefix CDD1: %08x",
mail);
}
switch (mail & 0xFFFF)
{
case 1:
NOTICE_LOG(DSPHLE, "UCode being replaced.");
m_upload_setup_in_progress = true;
SetMailState(MailState::HALTED);
break;
case 2:
NOTICE_LOG(DSPHLE, "UCode being rebooted to ROM.");
SetMailState(MailState::HALTED);
m_dsphle->SetUCode(UCODE_ROM);
break;
case 3:
m_cmd_can_execute = true;
RunPendingCommands();
break;
default:
NOTICE_LOG(DSPHLE, "Unknown end rendering action. Halting.");
case 0:
NOTICE_LOG(DSPHLE, "UCode asked to halt. Stopping any processing.");
SetMailState(MailState::HALTED);
break;
}
}
else if (!(mail & 0xFFFF))
{
if (RenderingInProgress())
{
SetMailState(MailState::RENDERING);
}
else
{
NOTICE_LOG(DSPHLE, "Sync mail (%08x) received when rendering was not active. Halting.",
mail);
SetMailState(MailState::HALTED);
}
}
else
{
SetMailState(MailState::WRITING_CMD);
m_mail_expected_cmd_mails = mail & 0xFFFF;
}
break;
case MailState::RENDERING:
m_sync_max_voice_id = (((mail >> 16) & 0xF) + 1) << 4;
m_sync_voice_skip_flags[(mail >> 16) & 0xFF] = mail & 0xFFFF;
RenderAudio();
SetMailState(MailState::WAITING);
break;
case MailState::WRITING_CMD:
Write32(mail);
if (--m_mail_expected_cmd_mails == 0)
{
m_pending_commands_count += 1;
SetMailState(MailState::WAITING);
RunPendingCommands();
}
break;
case MailState::HALTED:
WARN_LOG(DSPHLE, "Received mail %08x while we're halted.", mail);
break;
}
}
void ZeldaUCode::RunPendingCommands()
{
if (RenderingInProgress() || !m_cmd_can_execute)
{
// No commands can be ran while audio rendering is in progress or
// waiting for an ACK.
return;
}
while (m_pending_commands_count)
{
m_pending_commands_count--;
u32 cmd_mail = Read32();
u32 command = (cmd_mail >> 24) & 0x7f;
u32 sync = cmd_mail >> 16;
u32 extra_data = cmd_mail & 0xFFFF;
switch (command)
{
case 0x00:
case 0x03:
case 0x0A:
case 0x0B:
case 0x0C:
case 0x0E:
case 0x0F:
// NOP commands. Log anyway in case we encounter a new version
// where these are not NOPs anymore.
NOTICE_LOG(DSPHLE, "Received a NOP command: %d", command);
SendCommandAck(CommandAck::STANDARD, sync);
break;
case 0x04:
case 0x05:
case 0x06:
case 0x07:
case 0x08:
case 0x09:
// Commands that crash the DAC UCode. Log and enter HALTED mode.
NOTICE_LOG(DSPHLE, "Received a crashy command: %d", command);
SetMailState(MailState::HALTED);
return;
// Command 01: Setup/initialization command. Provides the address to
// voice parameter blocks (VPBs) as well as some array of coefficients
// used for mixing.
case 0x01:
{
m_rendering_voices_per_frame = extra_data;
m_renderer.SetVPBBaseAddress(Read32());
u16* data_ptr = (u16*)HLEMemory_Get_Pointer(Read32());
std::array<s16, 0x100> resampling_coeffs;
for (size_t i = 0; i < 0x100; ++i)
resampling_coeffs[i] = Common::swap16(data_ptr[i]);
m_renderer.SetResamplingCoeffs(std::move(resampling_coeffs));
// TODO: 0x100 more words here to figure out.
std::array<s16, 0x80> sine_table;
for (size_t i = 0; i < 0x80; ++i)
sine_table[i] = Common::swap16(data_ptr[0x200 + i]);
m_renderer.SetSineTable(std::move(sine_table));
u16* afc_coeffs_ptr = (u16*)HLEMemory_Get_Pointer(Read32());
std::array<s16, 0x20> afc_coeffs;
for (size_t i = 0; i < 0x20; ++i)
afc_coeffs[i] = Common::swap16(afc_coeffs_ptr[i]);
m_renderer.SetAfcCoeffs(std::move(afc_coeffs));
m_renderer.SetReverbPBBaseAddress(Read32());
SendCommandAck(CommandAck::STANDARD, sync);
break;
}
// Command 02: starts audio processing. NOTE: this handler uses return,
// not break. This is because it hijacks the mail control flow and
// stops processing of further commands until audio processing is done.
case 0x02:
m_rendering_requested_frames = (cmd_mail >> 16) & 0xFF;
m_renderer.SetOutputVolume(cmd_mail & 0xFFFF);
m_renderer.SetOutputLeftBufferAddr(Read32());
m_renderer.SetOutputRightBufferAddr(Read32());
m_rendering_curr_frame = 0;
m_rendering_curr_voice = 0;
RenderAudio();
return;
// Command 0D: TODO: find a name and implement.
case 0x0D:
WARN_LOG(DSPHLE, "CMD0D: %08x", Read32());
SendCommandAck(CommandAck::STANDARD, sync);
break;
default:
NOTICE_LOG(DSPHLE, "Received a non-existing command (%d), halting.", command);
SetMailState(MailState::HALTED);
return;
}
}
}
void ZeldaUCode::SendCommandAck(CommandAck ack_type, u16 sync_value)
{
u32 ack_mail = 0;
switch (ack_type)
{
case CommandAck::STANDARD: ack_mail = DSP_SYNC; break;
case CommandAck::DONE_RENDERING: ack_mail = DSP_FRAME_END; break;
}
m_mail_handler.PushMail(ack_mail, true);
if (ack_type == CommandAck::STANDARD)
{
m_mail_handler.PushMail(0xF3550000 | sync_value);
}
}
void ZeldaUCode::RenderAudio()
{
if (!RenderingInProgress())
{
WARN_LOG(DSPHLE, "Trying to render audio while no rendering should be happening.");
return;
}
while (m_rendering_curr_frame < m_rendering_requested_frames)
{
if (m_rendering_curr_voice == 0)
m_renderer.PrepareFrame();
while (m_rendering_curr_voice < m_rendering_voices_per_frame)
{
// If we are not meant to render this voice yet, go back to message
// processing.
if (m_rendering_curr_voice >= m_sync_max_voice_id)
return;
// Test the sync flag for this voice, skip it if not set.
u16 flags = m_sync_voice_skip_flags[m_rendering_curr_voice >> 4];
u8 bit = 0xF - (m_rendering_curr_voice & 0xF);
if (flags & (1 << bit))
m_renderer.AddVoice(m_rendering_curr_voice);
m_rendering_curr_voice++;
}
SendCommandAck(CommandAck::STANDARD, 0xFF00 | m_rendering_curr_frame);
m_renderer.FinalizeFrame();
m_rendering_curr_voice = 0;
m_sync_max_voice_id = 0;
m_rendering_curr_frame++;
}
SendCommandAck(CommandAck::DONE_RENDERING, 0);
m_cmd_can_execute = false; // Block command execution until ACK is received.
}
// Utility to define 32 bit accessors/modifiers methods based on two 16 bit
// fields named _l and _h.
#define DEFINE_32BIT_ACCESSOR(field_name, name) \
u32 Get##name() const { return (field_name##_h << 16) | field_name##_l; } \
void Set##name(u32 v) \
{ \
field_name##_h = v >> 16; \
field_name##_l = v & 0xFFFF; \
}
#pragma pack(push, 1)
struct ZeldaAudioRenderer::VPB
{
static const u16 SIZE_IN_WORDS = 0xC0;
static const u16 RW_SIZE_IN_WORDS = 0x80;
// If zero, skip processing this voice.
u16 enabled;
// If non zero, skip processing this voice.
u16 done;
// In 4.12 format. 1.0 (0x1000) means 0x50 raw samples from RAM/accelerator
// will be "resampled" to 0x50 input samples. 2.0 (0x2000) means 2 raw
// samples for one input samples. 0.5 (0x800) means one raw sample for 2
// input samples.
u16 resampling_ratio;
u16 unk_03;
// If non zero, reset some value in the VPB when processing it.
u16 reset_vpb;
// If non zero, tells PCM8/PCM16 sample sources that the end of the voice
// has been reached and looping should be considered if enabled.
u16 end_reached;
// If non zero, input samples to this VPB will be the fixed value from
// VPB[33] (constant_sample_value). This is used when a voice is being
// terminated in order to force silence.
u16 use_constant_sample;
// Number of samples that should be saved in the VPB for processing during
// future frames. Should be at most TODO.
u16 samples_to_keep_count;
// Channel mixing information. Each voice can be mixed to 6 different
// channels, with separate volume information.
//
// Used only if VPB[2C] (use_dolby_volume) is not set. Otherwise, the
// values from VPB[0x20:0x2C] are used to mix to all available channels.
struct Channel
{
// Can be treated as an ID, but in the real world this is actually the
// address in DRAM of a DSP buffer. The game passes that information to
// the DSP, which means the game must know the memory layout of the DSP
// UCode... that's terrible.
u16 id;
s16 target_volume;
s16 current_volume;
u16 unk;
};
Channel channels[6];
u16 unk_20_28[0x8];
// When using Dolby voice mixing (see VPB[2C] use_dolby_volume), the X
// (left/right) and Y (front/back) coordinates of the sound. 0x00 is all
// right/back, 0x7F is all left/front. Format is 0XXXXXXX0YYYYYYY.
u16 dolby_voice_position;
u8 GetDolbyVoiceX() const { return (dolby_voice_position >> 8) & 0x7F; }
u8 GetDolbyVoiceY() const { return dolby_voice_position & 0x7F; }
// How much reverbation to apply to the Dolby mixed voice. 0 is none,
// 0x7FFF is the maximum value.
s16 dolby_reverb_factor;
// The volume for the 0x50 samples being mixed will ramp between current
// and target. After the ramping is done, the current value is updated (to
// match target, usually).
s16 dolby_volume_current;
s16 dolby_volume_target;
// If non zero, use positional audio mixing. Instead of using the channels
// information, use the 4 Dolby related VPB fields defined above.
u16 use_dolby_volume;
u16 unk_2D;
u16 unk_2E;
u16 unk_2F;
// Fractional part of the current sample position, in 0.12 format (all
// decimal part, 0x0800 = 0.5). The 4 top bits are unused.
u16 current_pos_frac;
u16 unk_31;
// Number of remaining decoded AFC samples in the VPB internal buffer (see
// VPB[0x58]) that haven't been output yet.
u16 afc_remaining_decoded_samples;
// Value used as the constant sample value if VPB[6] (use_constant_sample)
// is set. Reset to the last sample value after each round of resampling.
s16 constant_sample;
// Current position in the voice. Not needed for accelerator based voice
// types since the accelerator exposes a streaming based interface, but DMA
// based voice types (PCM16_FROM_MRAM for example) require it to know where
// to seek in the MRAM buffer.
u16 current_position_h;
u16 current_position_l;
DEFINE_32BIT_ACCESSOR(current_position, CurrentPosition)
// Number of samples that will be processed before the loop point of the
// voice is reached. Maintained by the UCode and used by the game to
// schedule some parameters updates.
u16 samples_before_loop;
u16 unk_37;
// Current address used to stream samples for the ARAM sample source types.
u16 current_aram_addr_h;
u16 current_aram_addr_l;
DEFINE_32BIT_ACCESSOR(current_aram_addr, CurrentARAMAddr)
// Remaining number of samples to load before considering the voice
// rendering complete and setting the done flag. Note that this is an
// absolute value that does not take into account loops. If a loop of 100
// samples is played 4 times, remaining_length will have decreased by 400.
u16 remaining_length_h;
u16 remaining_length_l;
DEFINE_32BIT_ACCESSOR(remaining_length, RemainingLength)
// Stores the last 4 resampled input samples after each frame, so that they
// can be used for future linear interpolation.
s16 resample_buffer[4];
// TODO: document and implement.
s16 prev_input_samples[0x18];
// Values from the last decoded AFC block. The last two values are
// especially important since AFC decoding - as a variant of ADPCM -
// requires the two latest sample values to be able to decode future
// samples.
s16 afc_remaining_samples[0x10];
s16* AFCYN2() { return &afc_remaining_samples[0xE]; }
s16* AFCYN1() { return &afc_remaining_samples[0xF]; }
u16 unk_68_80[0x80 - 0x68];
enum SamplesSourceType
{
// Simple square wave at 50% amplitude and frequency controlled via the
// resampling ratio.
SRC_SQUARE_WAVE = 0,
// Simple saw wave at 100% amplitude and frequency controlled via the
// resampling ratio.
SRC_SAW_WAVE = 1,
// Samples stored in ARAM in PCM8 format, at an arbitrary sampling rate
// (resampling is applied).
SRC_PCM8_FROM_ARAM = 8,
// Samples stored in ARAM at a rate of 16 samples/9 bytes, AFC encoded,
// at an arbitrary sample rate (resampling is applied).
SRC_AFC_HQ_FROM_ARAM = 9,
// Samples stored in MRAM at an arbitrary sample rate (resampling is
// applied, unlike PCM16_FROM_MRAM_RAW).
SRC_PCM16_FROM_MRAM = 33,
};
u16 samples_source_type;
// If non zero, indicates that the sound should loop.
u16 is_looping;
// For AFC looping voices, the values of the last 2 samples before the
// start of the loop, in order to be able to decode samples after looping.
s16 loop_yn1;
s16 loop_yn2;
u16 unk_84;
// If true, ramp down quickly to a volume of zero, and end the voice (by
// setting VPB[1] done) when it reaches zero.
u16 end_requested;
u16 unk_86;
u16 unk_87;
// Base address used to download samples data after the loop point of the
// voice has been reached.
u16 loop_address_h;
u16 loop_address_l;
DEFINE_32BIT_ACCESSOR(loop_address, LoopAddress)
// Offset (in number of raw samples) of the start of the loop area in the
// voice. Note: some sample sources only use the _h part of this.
//
// TODO: rename to length? confusion with remaining_length...
u16 loop_start_position_h;
u16 loop_start_position_l;
DEFINE_32BIT_ACCESSOR(loop_start_position, LoopStartPosition)
// Base address used to download samples data before the loop point of the
// voice has been reached.
u16 base_address_h;
u16 base_address_l;
DEFINE_32BIT_ACCESSOR(base_address, BaseAddress)
u16 padding[SIZE_IN_WORDS];
};
struct ReverbPB
{
// If zero, skip this reverb PB.
u16 enabled;
// Size of the circular buffer in MRAM, expressed in number of 0x50 samples
// blocks (0xA0 bytes).
u16 circular_buffer_size;
// Base address of the circular buffer in MRAM.
u16 circular_buffer_base_h;
u16 circular_buffer_base_l;
struct Destination
{
u16 buffer_id; // See VPB::Channel::id.
u16 volume; // 1.15 format.
};
Destination dest[2];
// Coefficients for an 8-tap filter applied to each reverb buffer before
// adding its data to the destination.
s16 filter_coefs[8];
};
#pragma pack(pop)
void ZeldaAudioRenderer::PrepareFrame()
{
if (m_prepared)
return;
m_buf_front_left.fill(0);
m_buf_front_right.fill(0);
ApplyVolumeInPlace_1_15(&m_buf_back_left, 0x6784);
ApplyVolumeInPlace_1_15(&m_buf_back_right, 0x6784);
// TODO: Back left and back right should have a filter applied to them,
// then get mixed into front left and front right. In practice, TWW never
// uses this AFAICT. PanicAlert to help me find places that use this.
if (m_buf_back_left[0] != 0 || m_buf_back_right[0] != 0)
PanicAlert("Zelda HLE using back mixing buffers");
// Add reverb data from previous frame.
ApplyReverb(false);
AddBuffersWithVolume(m_buf_front_left_reverb.data(),
m_buf_back_left_reverb.data(),
0x50, 0x7FFF);
AddBuffersWithVolume(m_buf_front_right_reverb.data(),
m_buf_back_left_reverb.data(),
0x50, 0xB820);
AddBuffersWithVolume(m_buf_front_left_reverb.data(),
m_buf_back_right_reverb.data() + 0x28,
0x28, 0xB820);
AddBuffersWithVolume(m_buf_front_right_reverb.data(),
m_buf_back_left_reverb.data() + 0x28,
0x28, 0x7FFF);
m_buf_back_left_reverb.fill(0);
m_buf_back_right_reverb.fill(0);
m_prepared = true;
}
void ZeldaAudioRenderer::ApplyReverb(bool post_rendering)
{
if (!m_reverb_pb_base_addr)
{
PanicAlert("Trying to apply reverb without available parameters.");
return;
}
// Each of the 4 RPBs maps to one of these buffers.
MixingBuffer* reverb_buffers[4] = {
&m_buf_unk0_reverb,
&m_buf_unk1_reverb,
&m_buf_front_left_reverb,
&m_buf_front_right_reverb,
};
std::array<s16, 8>* last8_samples_buffers[4] = {
&m_buf_unk0_reverb_last8,
&m_buf_unk1_reverb_last8,
&m_buf_front_left_reverb_last8,
&m_buf_front_right_reverb_last8,
};
u16* rpb_base_ptr = (u16*)HLEMemory_Get_Pointer(m_reverb_pb_base_addr);
for (u16 rpb_idx = 0; rpb_idx < 4; ++rpb_idx)
{
ReverbPB rpb;
u16* rpb_raw_ptr = reinterpret_cast<u16*>(&rpb);
for (size_t i = 0; i < sizeof (ReverbPB) / 2; ++i)
rpb_raw_ptr[i] = Common::swap16(rpb_base_ptr[rpb_idx * sizeof (ReverbPB) / 2 + i]);
if (!rpb.enabled)
continue;
u16 mram_buffer_idx = m_reverb_pb_frames_count[rpb_idx];
u32 mram_addr = ((rpb.circular_buffer_base_h << 16) |
rpb.circular_buffer_base_l) +
mram_buffer_idx * 0x50 * sizeof (s16);
s16* mram_ptr = (s16*)HLEMemory_Get_Pointer(mram_addr);
if (!post_rendering)
{
// 8 more samples because of the filter order. The first 8 samples
// are the last 8 samples of the previous frame.
std::array<s16, 0x58> buffer;
for (u16 i = 0; i < 8; ++i)
buffer[i] = (*last8_samples_buffers[rpb_idx])[i];
for (u16 i = 0; i < 0x50; ++i)
buffer[8 + i] = Common::swap16(mram_ptr[i]);
for (u16 i = 0; i < 8; ++i)
(*last8_samples_buffers[rpb_idx])[i] = buffer[0x50 + i];
// Filter the buffer using provided coefficients.
for (u16 i = 0; i < 0x50; ++i)
{
s32 sample = 0;
for (u16 j = 0; j < 8; ++j)
sample += (s32)buffer[i + j] * rpb.filter_coefs[j];
sample >>= 15;
MathUtil::Clamp(&sample, -0x8000, 0x7fff);
buffer[i] = sample;
}
for (const auto& dest : rpb.dest)
{
if (dest.buffer_id == 0)
continue;
MixingBuffer* dest_buffer = BufferForID(dest.buffer_id);
if (!dest_buffer)
{
PanicAlert("RPB mixing to an unknown buffer: %04x", dest.buffer_id);
continue;
}
AddBuffersWithVolume(dest_buffer->data(), buffer.data(),
0x50, dest.volume);
}
// TODO: If "enabled" & 2, the filtering should be done post and
// not pre mixing.
if (rpb.enabled & 2)
PanicAlert("RPB wants post filtering.");
for (u16 i = 0; i < 0x50; ++i)
(*reverb_buffers[rpb_idx])[i] = buffer[i];
}
else
{
MixingBuffer* buffer = reverb_buffers[rpb_idx];
// Upload the reverb data to RAM.
for (auto sample : *buffer)
*mram_ptr++ = Common::swap16(sample);
mram_buffer_idx = (mram_buffer_idx + 1) % rpb.circular_buffer_size;
m_reverb_pb_frames_count[rpb_idx] = mram_buffer_idx;
}
}
}
ZeldaAudioRenderer::MixingBuffer* ZeldaAudioRenderer::BufferForID(u16 buffer_id)
{
switch (buffer_id)
{
case 0x0D00: return &m_buf_front_left;
case 0x0D60: return &m_buf_front_right;
case 0x0F40: return &m_buf_back_left;
case 0x0CA0: return &m_buf_back_right;
case 0x0E80: return &m_buf_front_left_reverb;
case 0x0EE0: return &m_buf_front_right_reverb;
case 0x0C00: return &m_buf_back_left_reverb;
case 0x0C50: return &m_buf_back_right_reverb;
case 0x0DC0: return &m_buf_unk0_reverb;
case 0x0E20: return &m_buf_unk1_reverb;
default: return nullptr;
}
}
void ZeldaAudioRenderer::AddVoice(u16 voice_id)
{
VPB vpb;
FetchVPB(voice_id, &vpb);
if (!vpb.enabled || vpb.done)
return;
MixingBuffer input_samples;
LoadInputSamples(&input_samples, &vpb);
// TODO: In place effects.
// TODO: IIR filter.
if (vpb.use_dolby_volume)
{
if (vpb.end_requested)
{
vpb.dolby_volume_target = vpb.dolby_volume_current / 2;
if (vpb.dolby_volume_target == 0)
vpb.done = true;
}
// Each of these volumes is in 1.15 fixed format.
s16 right_volume = m_sine_table[vpb.GetDolbyVoiceX()];
s16 back_volume = m_sine_table[vpb.GetDolbyVoiceY()];
s16 left_volume = m_sine_table[vpb.GetDolbyVoiceX() ^ 0x7F];
s16 front_volume = m_sine_table[vpb.GetDolbyVoiceY() ^ 0x7F];
// Compute volume for each quadrant.
s16 quadrant_volumes[4] = {
(s16)((left_volume * front_volume) >> 16),
(s16)((left_volume * back_volume) >> 16),
(s16)((right_volume * front_volume) >> 16),
(s16)((right_volume * back_volume) >> 16),
};
// Compute the volume delta for each sample to match the difference
// between current and target volume.
s16 delta = vpb.dolby_volume_target - vpb.dolby_volume_current;
s16 volume_deltas[4];
for (size_t i = 0; i < 4; ++i)
volume_deltas[i] = ((u16)quadrant_volumes[i] * delta) >> 16;
// Apply master volume to each quadrant.
for (size_t i = 0; i < 4; ++i)
quadrant_volumes[i] = (quadrant_volumes[i] * vpb.dolby_volume_current) >> 16;
// Compute reverb volume and ramp deltas.
s16 reverb_volumes[4], reverb_volume_deltas[4];
s16 reverb_volume_factor = (vpb.dolby_volume_current * vpb.dolby_reverb_factor) >> 15;
for (size_t i = 0; i < 4; ++i)
{
reverb_volumes[i] = (quadrant_volumes[i] * reverb_volume_factor) >> 15;
reverb_volume_deltas[i] = (volume_deltas[i] * vpb.dolby_reverb_factor) >> 16;
}
struct {
MixingBuffer* buffer;
s16 volume;
s16 volume_delta;
} buffers[8] = {
{ &m_buf_front_left, quadrant_volumes[0], volume_deltas[0] },
{ &m_buf_back_left, quadrant_volumes[1], volume_deltas[1] },
{ &m_buf_front_right, quadrant_volumes[2], volume_deltas[2] },
{ &m_buf_back_right, quadrant_volumes[3], volume_deltas[3] },
{ &m_buf_front_left_reverb, reverb_volumes[0], reverb_volume_deltas[0] },
{ &m_buf_back_left_reverb, reverb_volumes[1], reverb_volume_deltas[1] },
{ &m_buf_front_right_reverb, reverb_volumes[2], reverb_volume_deltas[2] },
{ &m_buf_back_right_reverb, reverb_volumes[3], reverb_volume_deltas[3] },
};
for (const auto& buffer : buffers)
{
AddBuffersWithVolumeRamp(buffer.buffer, input_samples, buffer.volume << 16,
(buffer.volume_delta << 16) / (s32)buffer.buffer->size());
}
vpb.dolby_volume_current = vpb.dolby_volume_target;
}
else
{
// TODO: Store input samples if requested by the VPB.
if (vpb.end_requested)
{
bool all_mute = true;
for (auto& channel : vpb.channels)
{
channel.target_volume = channel.current_volume / 2;
all_mute &= (channel.target_volume == 0);
}
if (all_mute)
vpb.done = true;
}
for (auto& channel : vpb.channels)
{
if (!channel.id)
continue;
s16 volume_delta = channel.target_volume - channel.current_volume;
s32 volume_step = (volume_delta << 16) / (s32)input_samples.size(); // In 1.31 format.
// TODO: The last value of each channel structure is used to
// determine whether a channel should be skipped or not. Not
// implemented yet.
if (!channel.current_volume && !volume_step)
continue;
MixingBuffer* dst_buffer = BufferForID(channel.id);
if (!dst_buffer)
{
PanicAlert("Mixing to an unmapped buffer: %04x", channel.id);
continue;
}
s32 new_volume = AddBuffersWithVolumeRamp(
dst_buffer, input_samples, channel.current_volume << 16,
volume_step);
channel.current_volume = new_volume >> 16;
}
}
// By then the VPB has been reset, unless we're in the "constant sample" /
// silence mode.
if (!vpb.use_constant_sample)
vpb.reset_vpb = false;
StoreVPB(voice_id, vpb);
}
void ZeldaAudioRenderer::FinalizeFrame()
{
// TODO: Dolby mixing.
ApplyVolumeInPlace_4_12(&m_buf_front_left, m_output_volume);
ApplyVolumeInPlace_4_12(&m_buf_front_right, m_output_volume);
u16* ram_left_buffer = (u16*)HLEMemory_Get_Pointer(m_output_lbuf_addr);
u16* ram_right_buffer = (u16*)HLEMemory_Get_Pointer(m_output_rbuf_addr);
for (size_t i = 0; i < m_buf_front_left.size(); ++i)
{
ram_left_buffer[i] = Common::swap16(m_buf_front_left[i]);
ram_right_buffer[i] = Common::swap16(m_buf_front_right[i]);
}
m_output_lbuf_addr += sizeof (u16) * (u32)m_buf_front_left.size();
m_output_rbuf_addr += sizeof (u16) * (u32)m_buf_front_right.size();
// TODO: Some more Dolby mixing.
ApplyReverb(true);
m_prepared = false;
}
void ZeldaAudioRenderer::FetchVPB(u16 voice_id, VPB* vpb)
{
u16* vpb_words = (u16*)vpb;
u16* ram_vpbs = (u16*)HLEMemory_Get_Pointer(m_vpb_base_addr);
size_t base_idx = voice_id * VPB::SIZE_IN_WORDS;
for (size_t i = 0; i < VPB::SIZE_IN_WORDS; ++i)
vpb_words[i] = Common::swap16(ram_vpbs[base_idx + i]);
}
void ZeldaAudioRenderer::StoreVPB(u16 voice_id, const VPB& vpb)
{
const u16* vpb_words = (const u16*)&vpb;
u16* ram_vpbs = (u16*)HLEMemory_Get_Pointer(m_vpb_base_addr);
size_t base_idx = voice_id * VPB::SIZE_IN_WORDS;
// Only the first 0x80 words are transferred back - the rest is read-only.
for (size_t i = 0; i < VPB::RW_SIZE_IN_WORDS; ++i)
ram_vpbs[base_idx + i] = Common::swap16(vpb_words[i]);
}
void ZeldaAudioRenderer::LoadInputSamples(MixingBuffer* buffer, VPB* vpb)
{
// Input data pre-resampling. Resampled into the mixing buffer parameter at
// the end of processing, if needed.
//
// Maximum of 0x500 samples here - see NeededRawSamplesCount to understand
// this practical limit (resampling_ratio = 0xFFFF -> 0x500 samples). Add a
// margin of 4 that is needed for samples source that do resampling.
std::array<s16, 0x500 + 4> raw_input_samples;
for (size_t i = 0; i < 4; ++i)
raw_input_samples[i] = vpb->resample_buffer[i];
if (vpb->use_constant_sample)
{
buffer->fill(vpb->constant_sample);
return;
}
switch (vpb->samples_source_type)
{
case VPB::SRC_SQUARE_WAVE:
{
u32 pos = vpb->current_pos_frac << 1;
for (size_t i = 0; i < buffer->size(); ++i)
{
(*buffer)[i] = ((pos >> 16) & 1) ? 0x4000 : 0xC000;
pos += vpb->resampling_ratio;
}
vpb->current_pos_frac = (pos >> 1) & 0xFFFF;
break;
}
case VPB::SRC_SAW_WAVE:
{
u32 pos = vpb->current_pos_frac;
for (size_t i = 0; i < buffer->size(); ++i)
{
(*buffer)[i] = pos & 0xFFFF;
pos += (vpb->resampling_ratio) >> 1;
}
vpb->current_pos_frac = pos & 0xFFFF;
break;
}
case VPB::SRC_PCM8_FROM_ARAM:
DownloadPCM8SamplesFromARAM(raw_input_samples.data() + 4, vpb,
NeededRawSamplesCount(*vpb));
Resample(vpb, raw_input_samples.data(), buffer);
break;
case VPB::SRC_AFC_HQ_FROM_ARAM:
DownloadAFCSamplesFromARAM(raw_input_samples.data() + 4, vpb,
NeededRawSamplesCount(*vpb));
Resample(vpb, raw_input_samples.data(), buffer);
break;
case VPB::SRC_PCM16_FROM_MRAM:
DownloadRawSamplesFromMRAM(raw_input_samples.data() + 4, vpb,
NeededRawSamplesCount(*vpb));
Resample(vpb, raw_input_samples.data(), buffer);
break;
default:
PanicAlert("Using an unknown/unimplemented sample source: %04x", vpb->samples_source_type);
buffer->fill(0);
return;
}
}
u16 ZeldaAudioRenderer::NeededRawSamplesCount(const VPB& vpb)
{
// Both of these are 4.12 fixed point, so shift by 12 to get the int part.
return (vpb.current_pos_frac + 0x50 * vpb.resampling_ratio) >> 12;
}
void ZeldaAudioRenderer::Resample(VPB* vpb, const s16* src, MixingBuffer* dst)
{
// Both in 20.12 format.
u32 ratio = vpb->resampling_ratio;
u32 pos = vpb->current_pos_frac;
// Check if we need to do some interpolation. If the resampling ratio is
// more than 4:1, it's not worth it.
if ((ratio >> 12) >= 4)
{
for (s16& dst_sample : *dst)
{
pos += ratio;
dst_sample = src[pos >> 12];
}
}
else
{
for (auto& dst_sample : *dst)
{
// We have 0x40 * 4 coeffs that need to be selected based on the
// most significant bits of the fractional part of the position. 12
// bits >> 6 = 6 bits = 0x40. Multiply by 4 since there are 4