~ppsspp/ppsspp/ppsspp_1.3.0

« back to all changes in this revision

Viewing changes to Core/HW/SasAudio.cpp

  • Committer: Sérgio Benjamim
  • Date: 2017-01-02 00:12:05 UTC
  • Revision ID: sergio_br2@yahoo.com.br-20170102001205-cxbta9za203nmjwm
1.3.0 source (from ppsspp_1.3.0-r160.p5.l1762.a165.t83~56~ubuntu16.04.1.tar.xz).

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// Copyright (c) 2012- PPSSPP Project.
 
2
 
 
3
// This program is free software: you can redistribute it and/or modify
 
4
// it under the terms of the GNU General Public License as published by
 
5
// the Free Software Foundation, version 2.0 or later versions.
 
6
 
 
7
// This program is distributed in the hope that it will be useful,
 
8
// but WITHOUT ANY WARRANTY; without even the implied warranty of
 
9
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
10
// GNU General Public License 2.0 for more details.
 
11
 
 
12
// A copy of the GPL 2.0 should have been included with the program.
 
13
// If not, see http://www.gnu.org/licenses/
 
14
 
 
15
// Official git repository and contact information can be found at
 
16
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
 
17
 
 
18
#include "base/basictypes.h"
 
19
#include "profiler/profiler.h"
 
20
 
 
21
#include "Globals.h"
 
22
#include "Core/MemMapHelpers.h"
 
23
#include "Core/HLE/sceAtrac.h"
 
24
#include "Core/Config.h"
 
25
#include "Core/Reporting.h"
 
26
#include "SasAudio.h"
 
27
 
 
28
#include <algorithm>
 
29
 
 
30
// #define AUDIO_TO_FILE
 
31
 
 
32
static const u8 f[16][2] = {
 
33
        {   0,   0 },
 
34
        {  60,   0 },
 
35
        { 115,  52 },
 
36
        {  98,  55 },
 
37
        { 122,  60 },
 
38
        // TODO: The below values could use more testing, but match initial tests.
 
39
        // Not sure if they are used by games, found by tests.
 
40
        {   0,   0 },
 
41
        {   0,   0 },
 
42
        {  52,   0 },
 
43
        {  55,   2 },
 
44
        {  60, 125 },
 
45
        {   0,   0 },
 
46
        {   0,  91 },
 
47
        {   0,   0 },
 
48
        {   2, 216 },
 
49
        { 125,   6 },
 
50
        {   0, 151 },
 
51
};
 
52
 
 
53
void VagDecoder::Start(u32 data, u32 vagSize, bool loopEnabled) {
 
54
        loopEnabled_ = loopEnabled;
 
55
        loopAtNextBlock_ = false;
 
56
        loopStartBlock_ = -1;
 
57
        numBlocks_ = vagSize / 16;
 
58
        end_ = false;
 
59
        data_ = data;
 
60
        read_ = data;
 
61
        curSample = 28;
 
62
        curBlock_ = -1;
 
63
        s_1 = 0;        // per block?
 
64
        s_2 = 0;
 
65
}
 
66
 
 
67
void VagDecoder::DecodeBlock(u8 *&read_pointer) {
 
68
        u8 *readp = read_pointer;
 
69
        int predict_nr = *readp++;
 
70
        int shift_factor = predict_nr & 0xf;
 
71
        predict_nr >>= 4;
 
72
        int flags = *readp++;
 
73
        if (flags == 7) {
 
74
                VERBOSE_LOG(SASMIX, "VAG ending block at %d", curBlock_);
 
75
                end_ = true;
 
76
                return;
 
77
        }
 
78
        else if (flags == 6) {
 
79
                loopStartBlock_ = curBlock_;
 
80
        }
 
81
        else if (flags == 3) {
 
82
                if (loopEnabled_) {
 
83
                        loopAtNextBlock_ = true;
 
84
                }
 
85
        }
 
86
 
 
87
        // Keep state in locals to avoid bouncing to memory.
 
88
        int s1 = s_1;
 
89
        int s2 = s_2;
 
90
 
 
91
        int coef1 = f[predict_nr][0];
 
92
        int coef2 = -f[predict_nr][1];
 
93
 
 
94
        // TODO: Unroll once more and interleave the unpacking with the decoding more?
 
95
        for (int i = 0; i < 28; i += 2) {
 
96
                u8 d = *readp++;
 
97
                int sample1 = (short)((d & 0xf) << 12) >> shift_factor;
 
98
                int sample2 = (short)((d & 0xf0) << 8) >> shift_factor;
 
99
                s2 = clamp_s16(sample1 + ((s1 * coef1 + s2 * coef2) >> 6));
 
100
                s1 = clamp_s16(sample2 + ((s2 * coef1 + s1 * coef2) >> 6));
 
101
                samples[i] = s2;
 
102
                samples[i + 1] = s1;
 
103
        }
 
104
 
 
105
        s_1 = s1;
 
106
        s_2 = s2;
 
107
        curSample = 0;
 
108
        curBlock_++;
 
109
        if (curBlock_ == numBlocks_) {
 
110
                end_ = true;
 
111
        }
 
112
 
 
113
        read_pointer = readp;
 
114
}
 
115
 
 
116
void VagDecoder::GetSamples(s16 *outSamples, int numSamples) {
 
117
        if (end_) {
 
118
                memset(outSamples, 0, numSamples * sizeof(s16));
 
119
                return;
 
120
        }
 
121
        if (!Memory::IsValidAddress(read_)) {
 
122
                WARN_LOG(SASMIX, "Bad VAG samples address?");
 
123
                return;
 
124
        }
 
125
        u8 *readp = Memory::GetPointerUnchecked(read_);
 
126
        u8 *origp = readp;
 
127
 
 
128
        for (int i = 0; i < numSamples; i++) {
 
129
                if (curSample == 28) {
 
130
                        if (loopAtNextBlock_) {
 
131
                                VERBOSE_LOG(SASMIX, "Looping VAG from block %d/%d to %d", curBlock_, numBlocks_, loopStartBlock_);
 
132
                                // data_ starts at curBlock = -1.
 
133
                                read_ = data_ + 16 * loopStartBlock_ + 16;
 
134
                                readp = Memory::GetPointerUnchecked(read_);
 
135
                                origp = readp;
 
136
                                curBlock_ = loopStartBlock_;
 
137
                                loopAtNextBlock_ = false;
 
138
                        }
 
139
                        DecodeBlock(readp);
 
140
                        if (end_) {
 
141
                                // Clear the rest of the buffer and return.
 
142
                                memset(&outSamples[i], 0, (numSamples - i) * sizeof(s16));
 
143
                                return;
 
144
                        }
 
145
                }
 
146
                outSamples[i] = samples[curSample++];
 
147
        }
 
148
 
 
149
        if (readp > origp) {
 
150
                read_ += readp - origp;
 
151
        }
 
152
}
 
153
 
 
154
void VagDecoder::DoState(PointerWrap &p) {
 
155
        auto s = p.Section("VagDecoder", 1, 2);
 
156
        if (!s)
 
157
                return;
 
158
 
 
159
        if (s >= 2) {
 
160
                p.DoArray(samples, ARRAY_SIZE(samples));
 
161
        } else {
 
162
                int samplesOld[ARRAY_SIZE(samples)];
 
163
                p.DoArray(samplesOld, ARRAY_SIZE(samples));
 
164
                for (size_t i = 0; i < ARRAY_SIZE(samples); ++i) {
 
165
                        samples[i] = samplesOld[i];
 
166
                }
 
167
        }
 
168
        p.Do(curSample);
 
169
 
 
170
        p.Do(data_);
 
171
        p.Do(read_);
 
172
        p.Do(curBlock_);
 
173
        p.Do(loopStartBlock_);
 
174
        p.Do(numBlocks_);
 
175
 
 
176
        p.Do(s_1);
 
177
        p.Do(s_2);
 
178
 
 
179
        p.Do(loopEnabled_);
 
180
        p.Do(loopAtNextBlock_);
 
181
        p.Do(end_);
 
182
}
 
183
 
 
184
int SasAtrac3::setContext(u32 context) {
 
185
        contextAddr_ = context;
 
186
        atracID_ = _AtracGetIDByContext(context);
 
187
        if (!sampleQueue_)
 
188
                sampleQueue_ = new BufferQueue();
 
189
        sampleQueue_->clear();
 
190
        end_ = false;
 
191
        return 0;
 
192
}
 
193
 
 
194
void SasAtrac3::getNextSamples(s16 *outbuf, int wantedSamples) {
 
195
        if (atracID_ < 0) {
 
196
                end_ = true;
 
197
                return;
 
198
        }
 
199
        u32 finish = 0;
 
200
        int wantedbytes = wantedSamples * sizeof(s16);
 
201
        while (!finish && sampleQueue_->getQueueSize() < wantedbytes) {
 
202
                u32 numSamples = 0;
 
203
                int remains = 0;
 
204
                static s16 buf[0x800];
 
205
                _AtracDecodeData(atracID_, (u8*)buf, 0, &numSamples, &finish, &remains);
 
206
                if (numSamples > 0)
 
207
                        sampleQueue_->push((u8*)buf, numSamples * sizeof(s16));
 
208
                else
 
209
                        finish = 1;
 
210
        }
 
211
        sampleQueue_->pop_front((u8*)outbuf, wantedbytes);
 
212
        end_ = finish == 1;
 
213
}
 
214
 
 
215
int SasAtrac3::addStreamData(u32 bufPtr, u32 addbytes) {
 
216
        if (atracID_ > 0) {
 
217
                _AtracAddStreamData(atracID_, bufPtr, addbytes);
 
218
        }
 
219
        return 0;
 
220
}
 
221
 
 
222
void SasAtrac3::DoState(PointerWrap &p) {
 
223
        auto s = p.Section("SasAtrac3", 1, 2);
 
224
        if (!s)
 
225
                return;
 
226
 
 
227
        p.Do(contextAddr_);
 
228
        p.Do(atracID_);
 
229
        if (p.mode == p.MODE_READ && atracID_ >= 0 && !sampleQueue_) {
 
230
                sampleQueue_ = new BufferQueue();
 
231
        }
 
232
        if (s >= 2) {
 
233
                p.Do(end_);
 
234
        }
 
235
}
 
236
 
 
237
// http://code.google.com/p/jpcsp/source/browse/trunk/src/jpcsp/HLE/modules150/sceSasCore.java
 
238
 
 
239
static int simpleRate(int n) {
 
240
        n &= 0x7F;
 
241
        if (n == 0x7F) {
 
242
                return 0;
 
243
        }
 
244
        int rate = ((7 - (n & 0x3)) << 26) >> (n >> 2);
 
245
        if (rate == 0) {
 
246
                return 1;
 
247
        }
 
248
        return rate;
 
249
}
 
250
 
 
251
static int exponentRate(int n) {
 
252
        n &= 0x7F;
 
253
        if (n == 0x7F) {
 
254
                return 0;
 
255
        }
 
256
        int rate = ((7 - (n & 0x3)) << 24) >> (n >> 2);
 
257
        if (rate == 0) {
 
258
                return 1;
 
259
        }
 
260
        return rate;
 
261
}
 
262
 
 
263
static int getAttackRate(int bitfield1) {
 
264
        return simpleRate(bitfield1 >> 8);
 
265
}
 
266
 
 
267
static int getAttackType(int bitfield1) {
 
268
        return (bitfield1 & 0x8000) == 0 ? PSP_SAS_ADSR_CURVE_MODE_LINEAR_INCREASE : PSP_SAS_ADSR_CURVE_MODE_LINEAR_BENT;
 
269
}
 
270
 
 
271
static int getDecayRate(int bitfield1) {
 
272
        int n = (bitfield1 >> 4) & 0x000F;
 
273
        if (n == 0)
 
274
                return 0x7FFFFFFF;
 
275
        return 0x80000000 >> n;
 
276
}
 
277
 
 
278
static int getSustainType(int bitfield2) {
 
279
        return (bitfield2 >> 14) & 3;
 
280
}
 
281
 
 
282
static int getSustainRate(int bitfield2) {
 
283
        if (getSustainType(bitfield2) == PSP_SAS_ADSR_CURVE_MODE_EXPONENT_DECREASE) {
 
284
                return exponentRate(bitfield2 >> 6);
 
285
        } else {
 
286
                return simpleRate(bitfield2 >> 6);
 
287
        }
 
288
}
 
289
 
 
290
static int getReleaseType(int bitfield2) {
 
291
        return (bitfield2 & 0x0020) == 0 ? PSP_SAS_ADSR_CURVE_MODE_LINEAR_DECREASE : PSP_SAS_ADSR_CURVE_MODE_EXPONENT_DECREASE;
 
292
}
 
293
 
 
294
static int getReleaseRate(int bitfield2) {
 
295
        int n = bitfield2 & 0x001F;
 
296
        if (n == 31) {
 
297
                return 0;
 
298
        }
 
299
        if (getReleaseType(bitfield2) == PSP_SAS_ADSR_CURVE_MODE_LINEAR_DECREASE) {
 
300
                if (n == 30) {
 
301
                        return 0x40000000;
 
302
                } else if (n == 29) {
 
303
                        return 1;
 
304
                }
 
305
                return 0x10000000 >> n;
 
306
        }
 
307
        if (n == 0)
 
308
                return 0x7FFFFFFF;
 
309
        return 0x80000000 >> n;
 
310
}
 
311
 
 
312
static int getSustainLevel(int bitfield1) {
 
313
        return ((bitfield1 & 0x000F) + 1) << 26;
 
314
}
 
315
 
 
316
void ADSREnvelope::SetSimpleEnvelope(u32 ADSREnv1, u32 ADSREnv2) {
 
317
        attackRate              = getAttackRate(ADSREnv1);
 
318
        attackType              = getAttackType(ADSREnv1);
 
319
        decayRate               = getDecayRate(ADSREnv1);
 
320
        decayType               = PSP_SAS_ADSR_CURVE_MODE_EXPONENT_DECREASE;
 
321
        sustainRate     = getSustainRate(ADSREnv2);
 
322
        sustainType     = getSustainType(ADSREnv2);
 
323
        releaseRate     = getReleaseRate(ADSREnv2);
 
324
        releaseType     = getReleaseType(ADSREnv2);
 
325
        sustainLevel    = getSustainLevel(ADSREnv1);
 
326
 
 
327
        if (attackRate < 0 || decayRate < 0 || sustainRate < 0 || releaseRate < 0) {
 
328
                ERROR_LOG_REPORT(SCESAS, "Simple ADSR resulted in invalid rates: %04x, %04x", ADSREnv1, ADSREnv2);
 
329
        }
 
330
}
 
331
 
 
332
SasInstance::SasInstance()
 
333
        : maxVoices(PSP_SAS_VOICES_MAX),
 
334
                sampleRate(44100),
 
335
                outputMode(PSP_SAS_OUTPUTMODE_MIXED),
 
336
                mixBuffer(0),
 
337
                sendBuffer(0),
 
338
                sendBufferDownsampled(0),
 
339
                sendBufferProcessed(0),
 
340
                resampleBuffer(0),
 
341
                grainSize(0) {
 
342
#ifdef AUDIO_TO_FILE
 
343
        audioDump = fopen("D:\\audio.raw", "wb");
 
344
#endif
 
345
        memset(&waveformEffect, 0, sizeof(waveformEffect));
 
346
        waveformEffect.type = PSP_SAS_EFFECT_TYPE_OFF;
 
347
        waveformEffect.isDryOn = 1;
 
348
}
 
349
 
 
350
SasInstance::~SasInstance() {
 
351
        ClearGrainSize();
 
352
}
 
353
 
 
354
void SasInstance::GetDebugText(char *text, size_t bufsize) {
 
355
        char voiceBuf[4096];
 
356
        voiceBuf[0] = '\0';
 
357
        char *p = voiceBuf;
 
358
        for (int i = 0; i < maxVoices; i++) {
 
359
                if (voices[i].playing) {
 
360
                        p += snprintf(p, sizeof(voiceBuf) - (p - voiceBuf), " %d: Pitch %d L/R,FX: %d,%d|%d,%d VAG: %08x:%d:%08x Height:%d%%\n", i, voices[i].pitch, voices[i].volumeLeft, voices[i].volumeRight, voices[i].effectLeft, voices[i].effectRight, voices[i].vagAddr, voices[i].vagSize, voices[i].vag.GetReadPtr(), (int)((int64_t)voices[i].envelope.GetHeight() * 100 / PSP_SAS_ENVELOPE_HEIGHT_MAX));
 
361
                }
 
362
        }
 
363
 
 
364
        snprintf(text, bufsize,
 
365
                "SR: %d Mode: %s Grain: %d\n"
 
366
                "Effect: Type: %d Dry: %d Wet: %d L: %d R: %d Delay: %d Feedback: %d\n"
 
367
                "\n%s\n",
 
368
                sampleRate, outputMode == PSP_SAS_OUTPUTMODE_RAW ? "Raw" : "Mixed", grainSize,
 
369
                waveformEffect.type, waveformEffect.isDryOn, waveformEffect.isWetOn, waveformEffect.leftVol, waveformEffect.rightVol, waveformEffect.delay, waveformEffect.feedback,
 
370
                voiceBuf);
 
371
 
 
372
}
 
373
 
 
374
void SasInstance::ClearGrainSize() {
 
375
        delete[] mixBuffer;
 
376
        delete[] sendBuffer;
 
377
        delete[] sendBufferDownsampled;
 
378
        delete[] sendBufferProcessed;
 
379
        delete[] resampleBuffer;
 
380
        mixBuffer = nullptr;
 
381
        sendBuffer = nullptr;
 
382
        resampleBuffer = nullptr;
 
383
        sendBufferDownsampled = nullptr;
 
384
        sendBufferProcessed = nullptr;
 
385
}
 
386
 
 
387
void SasInstance::SetGrainSize(int newGrainSize) {
 
388
        grainSize = newGrainSize;
 
389
 
 
390
        // If you change the sizes here, don't forget DoState().
 
391
        delete[] mixBuffer;
 
392
        delete[] sendBuffer;
 
393
        delete[] sendBufferDownsampled;
 
394
        delete[] sendBufferProcessed;
 
395
        delete[] resampleBuffer;
 
396
 
 
397
        mixBuffer = new s32[grainSize * 2];
 
398
        sendBuffer = new s32[grainSize * 2];
 
399
        sendBufferDownsampled = new s16[grainSize];
 
400
        sendBufferProcessed = new s16[grainSize * 2];
 
401
        memset(mixBuffer, 0, sizeof(int) * grainSize * 2);
 
402
        memset(sendBuffer, 0, sizeof(int) * grainSize * 2);
 
403
        memset(sendBufferDownsampled, 0, sizeof(s16) * grainSize);
 
404
        memset(sendBufferProcessed, 0, sizeof(s16) * grainSize * 2);
 
405
 
 
406
        // 2 samples padding at the start, that's where we copy the two last samples from the channel
 
407
        // so that we can do bicubic resampling if necessary.  Plus 1 for smoothness hackery.
 
408
        resampleBuffer = new s16[grainSize * 4 + 3];
 
409
}
 
410
 
 
411
int SasInstance::EstimateMixUs() {
 
412
        int voicesPlayingCount = 0;
 
413
 
 
414
        for (int v = 0; v < PSP_SAS_VOICES_MAX; v++) {
 
415
                SasVoice &voice = voices[v];
 
416
                if (!voice.playing || voice.paused)
 
417
                        continue;
 
418
                voicesPlayingCount++;
 
419
        }
 
420
 
 
421
        // Each voice costs extra time, and each byte of grain costs extra time.
 
422
        return 20 + voicesPlayingCount * 68 + (grainSize * 60) / 100;
 
423
}
 
424
 
 
425
void SasVoice::ReadSamples(s16 *output, int numSamples) {
 
426
        // Read N samples into the resample buffer. Could do either PCM or VAG here.
 
427
        switch (type) {
 
428
        case VOICETYPE_VAG:
 
429
                vag.GetSamples(output, numSamples);
 
430
                break;
 
431
        case VOICETYPE_PCM:
 
432
                {
 
433
                        int needed = numSamples;
 
434
                        s16 *out = output;
 
435
                        while (needed > 0) {
 
436
                                u32 size = std::min(pcmSize - pcmIndex, needed);
 
437
                                if (!on) {
 
438
                                        pcmIndex = 0;
 
439
                                        break;
 
440
                                }
 
441
                                Memory::Memcpy(out, pcmAddr + pcmIndex * sizeof(s16), size * sizeof(s16));
 
442
                                pcmIndex += size;
 
443
                                needed -= size;
 
444
                                out += size;
 
445
                                if (pcmIndex >= pcmSize) {
 
446
                                        if (!loop) {
 
447
                                                // All out, quit.  We'll end in HaveSamplesEnded().
 
448
                                                break;
 
449
                                        }
 
450
                                        pcmIndex = pcmLoopPos;
 
451
                                }
 
452
                        }
 
453
                        if (needed > 0) {
 
454
                                memset(out, 0, needed * sizeof(s16));
 
455
                        }
 
456
                }
 
457
                break;
 
458
        case VOICETYPE_ATRAC3:
 
459
                atrac3.getNextSamples(output, numSamples);
 
460
                break;
 
461
        default:
 
462
                {
 
463
                        memset(output, 0, numSamples * sizeof(s16));
 
464
                }
 
465
                break;
 
466
        }
 
467
}
 
468
 
 
469
bool SasVoice::HaveSamplesEnded() const {
 
470
        switch (type) {
 
471
        case VOICETYPE_VAG:
 
472
                return vag.End();
 
473
 
 
474
        case VOICETYPE_PCM:
 
475
                return pcmIndex >= pcmSize;
 
476
 
 
477
        case VOICETYPE_ATRAC3:
 
478
                return atrac3.End();
 
479
 
 
480
        default:
 
481
                return false;
 
482
        }
 
483
}
 
484
 
 
485
void SasInstance::MixVoice(SasVoice &voice) {
 
486
        switch (voice.type) {
 
487
        case VOICETYPE_VAG:
 
488
                if (voice.type == VOICETYPE_VAG && !voice.vagAddr)
 
489
                        break;
 
490
                // else fallthrough! Don't change the check above.
 
491
        case VOICETYPE_PCM:
 
492
                if (voice.type == VOICETYPE_PCM && !voice.pcmAddr)
 
493
                        break;
 
494
                // else fallthrough! Don't change the check above.
 
495
        default:
 
496
                // Load resample history (so we can use a wide filter)
 
497
                resampleBuffer[0] = voice.resampleHist[0];
 
498
                resampleBuffer[1] = voice.resampleHist[1];
 
499
 
 
500
                // Figure out number of samples to read.
 
501
                // Actually this is not entirely correct - we need to get one extra sample, and store it
 
502
                // for the next time around. A little complicated...
 
503
                // But for now, see Smoothness HACKERY below :P
 
504
                u32 numSamples = ((u32)voice.sampleFrac + (u32)grainSize * (u32)voice.pitch) >> PSP_SAS_PITCH_BASE_SHIFT;
 
505
                if ((int)numSamples > grainSize * 4) {
 
506
                        ERROR_LOG(SASMIX, "numSamples too large, clamping: %i vs %i", numSamples, grainSize * 4);
 
507
                        numSamples = grainSize * 4;
 
508
                }
 
509
 
 
510
                // This feels a bit hacky.  The first 32 samples after a keyon are 0s.
 
511
                const bool ignorePitch = voice.type == VOICETYPE_PCM && voice.pitch > PSP_SAS_PITCH_BASE;
 
512
                if (voice.envelope.NeedsKeyOn()) {
 
513
                        int delay = ignorePitch ? 32 : (32 * (u32)voice.pitch) >> PSP_SAS_PITCH_BASE_SHIFT;
 
514
                        // VAG seems to have an extra sample delay (not shared by PCM.)
 
515
                        if (voice.type == VOICETYPE_VAG)
 
516
                                ++delay;
 
517
                        voice.ReadSamples(resampleBuffer + 2 + delay, numSamples - delay);
 
518
                } else {
 
519
                        voice.ReadSamples(resampleBuffer + 2, numSamples);
 
520
                }
 
521
 
 
522
                // Smoothness HACKERY
 
523
                resampleBuffer[2 + numSamples] = resampleBuffer[2 + numSamples - 1];
 
524
 
 
525
                // Save resample history
 
526
                voice.resampleHist[0] = resampleBuffer[2 + numSamples - 2];
 
527
                voice.resampleHist[1] = resampleBuffer[2 + numSamples - 1];
 
528
 
 
529
                // Resample to the correct pitch, writing exactly "grainSize" samples.
 
530
                // This is a HORRIBLE resampler by the way.
 
531
                // TODO: Special case no-resample case (and 2x and 0.5x) for speed, it's not uncommon
 
532
 
 
533
                u32 sampleFrac = voice.sampleFrac;
 
534
                for (int i = 0; i < grainSize; i++) {
 
535
                        // For now: nearest neighbour, not even using the resample history at all.
 
536
                        int sample = resampleBuffer[sampleFrac / PSP_SAS_PITCH_BASE + 2];
 
537
                        sampleFrac += voice.pitch;
 
538
 
 
539
                        // The maximum envelope height (PSP_SAS_ENVELOPE_HEIGHT_MAX) is (1 << 30) - 1.
 
540
                        // Reduce it to 14 bits, by shifting off 15.  Round up by adding (1 << 14) first.
 
541
                        int envelopeValue = voice.envelope.GetHeight();
 
542
                        voice.envelope.Step();
 
543
                        envelopeValue = (envelopeValue + (1 << 14)) >> 15;
 
544
 
 
545
                        // We just scale by the envelope before we scale by volumes.
 
546
                        // Again, we round up by adding (1 << 14) first (*after* multiplying.)
 
547
                        sample = ((sample * envelopeValue) + (1 << 14)) >> 15;
 
548
 
 
549
                        // We mix into this 32-bit temp buffer and clip in a second loop
 
550
                        // Ideally, the shift right should be there too but for now I'm concerned about
 
551
                        // not overflowing.
 
552
                        mixBuffer[i * 2] += (sample * voice.volumeLeft ) >> 12;
 
553
                        mixBuffer[i * 2 + 1] += (sample * voice.volumeRight) >> 12;
 
554
                        sendBuffer[i * 2] += sample * voice.effectLeft >> 12;
 
555
                        sendBuffer[i * 2 + 1] += sample * voice.effectRight >> 12;
 
556
                }
 
557
 
 
558
                voice.sampleFrac = sampleFrac;
 
559
                // Let's hope grainSize is a power of 2.
 
560
                //voice.sampleFrac &= grainSize * PSP_SAS_PITCH_BASE - 1;
 
561
                voice.sampleFrac -= numSamples * PSP_SAS_PITCH_BASE;
 
562
 
 
563
                if (voice.HaveSamplesEnded())
 
564
                        voice.envelope.End();
 
565
                if (voice.envelope.HasEnded())
 
566
                {
 
567
                        // NOTICE_LOG(SCESAS, "Hit end of envelope");
 
568
                        voice.playing = false;
 
569
                        voice.on = false;
 
570
                }
 
571
        }
 
572
}
 
573
 
 
574
void SasInstance::Mix(u32 outAddr, u32 inAddr, int leftVol, int rightVol) {
 
575
        int voicesPlayingCount = 0;
 
576
 
 
577
        for (int v = 0; v < PSP_SAS_VOICES_MAX; v++) {
 
578
                SasVoice &voice = voices[v];
 
579
                if (!voice.playing || voice.paused)
 
580
                        continue;
 
581
                voicesPlayingCount++;
 
582
                MixVoice(voice);
 
583
        }
 
584
 
 
585
        // Then mix the send buffer in with the rest.
 
586
 
 
587
        // Alright, all voices mixed. Let's convert and clip, and at the same time, wipe mixBuffer for next time. Could also dither.
 
588
        s16 *outp = (s16 *)Memory::GetPointer(outAddr);
 
589
        const s16 *inp = inAddr ? (s16*)Memory::GetPointer(inAddr) : 0;
 
590
        if (outputMode == PSP_SAS_OUTPUTMODE_MIXED) {
 
591
                // Okay, apply effects processing to the Send buffer.
 
592
                WriteMixedOutput(outp, inp, leftVol, rightVol);
 
593
        } else {
 
594
                s16 *outpL = outp + grainSize * 0;
 
595
                s16 *outpR = outp + grainSize * 1;
 
596
                s16 *outpSendL = outp + grainSize * 2;
 
597
                s16 *outpSendR = outp + grainSize * 3;
 
598
                WARN_LOG_REPORT_ONCE(sasraw, SCESAS, "sceSasCore: raw outputMode");
 
599
                for (int i = 0; i < grainSize * 2; i += 2) {
 
600
                        *outpL++ = clamp_s16(mixBuffer[i + 0]);
 
601
                        *outpR++ = clamp_s16(mixBuffer[i + 1]);
 
602
                        *outpSendL++ = clamp_s16(sendBuffer[i + 0]);
 
603
                        *outpSendR++ = clamp_s16(sendBuffer[i + 1]);
 
604
                }
 
605
        }
 
606
        memset(mixBuffer, 0, grainSize * sizeof(int) * 2);
 
607
        memset(sendBuffer, 0, grainSize * sizeof(int) * 2);
 
608
 
 
609
#ifdef AUDIO_TO_FILE
 
610
        fwrite(Memory::GetPointer(outAddr), 1, grainSize * 2 * 2, audioDump);
 
611
#endif
 
612
}
 
613
 
 
614
void SasInstance::WriteMixedOutput(s16 *outp, const s16 *inp, int leftVol, int rightVol) {
 
615
        const bool dry = waveformEffect.isDryOn != 0;
 
616
        const bool wet = waveformEffect.isWetOn != 0;
 
617
        if (wet) {
 
618
                ApplyWaveformEffect();
 
619
        }
 
620
 
 
621
        if (inp) {
 
622
                for (int i = 0; i < grainSize * 2; i += 2) {
 
623
                        int sampleL = ((*inp++) * leftVol >> 12);
 
624
                        int sampleR = ((*inp++) * rightVol >> 12);
 
625
                        if (dry) {
 
626
                                sampleL += mixBuffer[i + 0];
 
627
                                sampleR += mixBuffer[i + 1];
 
628
                        }
 
629
                        if (wet) {
 
630
                                sampleL += sendBufferProcessed[i + 0];
 
631
                                sampleR += sendBufferProcessed[i + 1];
 
632
                        }
 
633
                        *outp++ = clamp_s16(sampleL);
 
634
                        *outp++ = clamp_s16(sampleR);
 
635
                }
 
636
        } else {
 
637
                // These are the optimal cases.
 
638
                if (dry && wet) {
 
639
                        for (int i = 0; i < grainSize * 2; i += 2) {
 
640
                                *outp++ = clamp_s16(mixBuffer[i + 0] + sendBufferProcessed[i + 0]);
 
641
                                *outp++ = clamp_s16(mixBuffer[i + 1] + sendBufferProcessed[i + 1]);
 
642
                        }
 
643
                } else if (dry) {
 
644
                        for (int i = 0; i < grainSize * 2; i += 2) {
 
645
                                *outp++ = clamp_s16(mixBuffer[i + 0]);
 
646
                                *outp++ = clamp_s16(mixBuffer[i + 1]);
 
647
                        }
 
648
                } else {
 
649
                        // This is another uncommon case, dry must be off but let's keep it for clarity.
 
650
                        for (int i = 0; i < grainSize * 2; i += 2) {
 
651
                                int sampleL = 0;
 
652
                                int sampleR = 0;
 
653
                                if (dry) {
 
654
                                        sampleL += mixBuffer[i + 0];
 
655
                                        sampleR += mixBuffer[i + 1];
 
656
                                }
 
657
                                if (wet) {
 
658
                                        sampleL += sendBufferProcessed[i + 0];
 
659
                                        sampleR += sendBufferProcessed[i + 1];
 
660
                                }
 
661
                                *outp++ = clamp_s16(sampleL);
 
662
                                *outp++ = clamp_s16(sampleR);
 
663
                        }
 
664
                }
 
665
        }
 
666
}
 
667
 
 
668
void SasInstance::SetWaveformEffectType(int type) {
 
669
        if (type != waveformEffect.type) {
 
670
                waveformEffect.type = type;
 
671
                reverb_.SetPreset(type);
 
672
        }
 
673
}
 
674
 
 
675
// http://psx.rules.org/spu.txt has some information about setting up the delay time by modifying the delay preset.
 
676
// See http://report.ppsspp.org/logs/kind/772 for a list of games that use different types. Maybe can help us figure out
 
677
// which is which.
 
678
void SasInstance::ApplyWaveformEffect() {
 
679
        // First, downsample the send buffer to 22khz. We do this naively for now.
 
680
        for (int i = 0; i < grainSize / 2; i++) {
 
681
                sendBufferDownsampled[i * 2] = clamp_s16(sendBuffer[i * 4]);
 
682
                sendBufferDownsampled[i * 2 + 1] = clamp_s16(sendBuffer[i * 4 + 1]);
 
683
        }
 
684
 
 
685
        // Volume max is 0x1000, while our factor is up to 0x8000. Shifting right by 3 fixes that.
 
686
        reverb_.ProcessReverb(sendBufferProcessed, sendBufferDownsampled, grainSize / 2, waveformEffect.leftVol << 3, waveformEffect.rightVol << 3);
 
687
}
 
688
 
 
689
void SasInstance::DoState(PointerWrap &p) {
 
690
        auto s = p.Section("SasInstance", 1);
 
691
        if (!s)
 
692
                return;
 
693
 
 
694
        p.Do(grainSize);
 
695
        if (p.mode == p.MODE_READ) {
 
696
                if (grainSize > 0) {
 
697
                        SetGrainSize(grainSize);
 
698
                } else {
 
699
                        ClearGrainSize();
 
700
                }
 
701
        }
 
702
 
 
703
        p.Do(maxVoices);
 
704
        p.Do(sampleRate);
 
705
        p.Do(outputMode);
 
706
 
 
707
        // SetGrainSize() / ClearGrainSize() should've made our buffers match.
 
708
        if (mixBuffer != NULL && grainSize > 0) {
 
709
                p.DoArray(mixBuffer, grainSize * 2);
 
710
        }
 
711
        if (sendBuffer != NULL && grainSize > 0) {
 
712
                p.DoArray(sendBuffer, grainSize * 2);
 
713
        }
 
714
        if (resampleBuffer != NULL && grainSize > 0) {
 
715
                p.DoArray(resampleBuffer, grainSize * 4 + 3);
 
716
        }
 
717
 
 
718
        int n = PSP_SAS_VOICES_MAX;
 
719
        p.Do(n);
 
720
        if (n != PSP_SAS_VOICES_MAX) {
 
721
                ERROR_LOG(HLE, "Savestate failure: wrong number of SAS voices");
 
722
                return;
 
723
        }
 
724
        p.DoArray(voices, ARRAY_SIZE(voices));
 
725
        p.Do(waveformEffect);
 
726
        if (p.mode == p.MODE_READ) {
 
727
                reverb_.SetPreset(waveformEffect.type);
 
728
        }
 
729
}
 
730
 
 
731
void SasVoice::Reset() {
 
732
        resampleHist[0] = 0;
 
733
        resampleHist[1] = 0;
 
734
}
 
735
 
 
736
void SasVoice::KeyOn() {
 
737
        envelope.KeyOn();
 
738
        switch (type) {
 
739
        case VOICETYPE_VAG:
 
740
                if (Memory::IsValidAddress(vagAddr)) {
 
741
                        vag.Start(vagAddr, vagSize, loop);
 
742
                } else {
 
743
                        ERROR_LOG(SASMIX, "Invalid VAG address %08x", vagAddr);
 
744
                        return;
 
745
                }
 
746
                break;
 
747
        default:
 
748
                break;
 
749
        }
 
750
        playing = true;
 
751
        on = true;
 
752
        paused = false;
 
753
        sampleFrac = 0;
 
754
}
 
755
 
 
756
void SasVoice::KeyOff() {
 
757
        on = false;
 
758
        envelope.KeyOff();
 
759
}
 
760
 
 
761
void SasVoice::ChangedParams(bool changedVag) {
 
762
        if (!playing && on) {
 
763
                playing = true;
 
764
                if (changedVag)
 
765
                        vag.Start(vagAddr, vagSize, loop);
 
766
        }
 
767
        // TODO: restart VAG somehow
 
768
}
 
769
 
 
770
void SasVoice::DoState(PointerWrap &p) {
 
771
        auto s = p.Section("SasVoice", 1, 3);
 
772
        if (!s)
 
773
                return;
 
774
 
 
775
        p.Do(playing);
 
776
        p.Do(paused);
 
777
        p.Do(on);
 
778
 
 
779
        p.Do(type);
 
780
 
 
781
        p.Do(vagAddr);
 
782
        p.Do(vagSize);
 
783
        p.Do(pcmAddr);
 
784
        p.Do(pcmSize);
 
785
        p.Do(pcmIndex);
 
786
        if (s >= 2) {
 
787
                p.Do(pcmLoopPos);
 
788
        } else {
 
789
                pcmLoopPos = 0;
 
790
        }
 
791
        p.Do(sampleRate);
 
792
 
 
793
        p.Do(sampleFrac);
 
794
        p.Do(pitch);
 
795
        p.Do(loop);
 
796
        if (s < 2 && type == VOICETYPE_PCM) {
 
797
                // We set loop incorrectly before, and always looped.
 
798
                // Let's keep always looping, since it's usually right.
 
799
                loop = true;
 
800
        }
 
801
 
 
802
        p.Do(noiseFreq);
 
803
 
 
804
        p.Do(volumeLeft);
 
805
        p.Do(volumeRight);
 
806
        if (s < 3) {
 
807
                // There were extra variables here that were for the same purpose.
 
808
                p.Do(effectLeft);
 
809
                p.Do(effectRight);
 
810
        }
 
811
        p.Do(effectLeft);
 
812
        p.Do(effectRight);
 
813
        p.DoArray(resampleHist, ARRAY_SIZE(resampleHist));
 
814
 
 
815
        envelope.DoState(p);
 
816
        vag.DoState(p);
 
817
        atrac3.DoState(p);
 
818
}
 
819
 
 
820
ADSREnvelope::ADSREnvelope()
 
821
        : attackRate(0),
 
822
                decayRate(0),
 
823
                sustainRate(0),
 
824
                releaseRate(0),
 
825
                attackType(PSP_SAS_ADSR_CURVE_MODE_LINEAR_INCREASE),
 
826
                decayType(PSP_SAS_ADSR_CURVE_MODE_LINEAR_DECREASE),
 
827
                sustainType(PSP_SAS_ADSR_CURVE_MODE_LINEAR_DECREASE),
 
828
                sustainLevel(0),
 
829
                releaseType(PSP_SAS_ADSR_CURVE_MODE_LINEAR_DECREASE),
 
830
                state_(STATE_OFF),
 
831
                height_(0) {
 
832
}
 
833
 
 
834
void ADSREnvelope::WalkCurve(int type, int rate) {
 
835
        s64 expDelta;
 
836
        switch (type) {
 
837
        case PSP_SAS_ADSR_CURVE_MODE_LINEAR_INCREASE:
 
838
                height_ += rate;
 
839
                break;
 
840
 
 
841
        case PSP_SAS_ADSR_CURVE_MODE_LINEAR_DECREASE:
 
842
                height_ -= rate;
 
843
                break;
 
844
 
 
845
        case PSP_SAS_ADSR_CURVE_MODE_LINEAR_BENT:
 
846
                if (height_ <= (s64)PSP_SAS_ENVELOPE_HEIGHT_MAX * 3 / 4) {
 
847
                        height_ += rate;
 
848
                } else {
 
849
                        height_ += rate / 4;
 
850
                }
 
851
                break;
 
852
 
 
853
        case PSP_SAS_ADSR_CURVE_MODE_EXPONENT_DECREASE:
 
854
                expDelta = height_ - PSP_SAS_ENVELOPE_HEIGHT_MAX;
 
855
                // Flipping the sign so that we can shift in the top bits.
 
856
                expDelta += (-expDelta * rate) >> 32;
 
857
                height_ = expDelta + PSP_SAS_ENVELOPE_HEIGHT_MAX - (rate + 3UL) / 4UL;
 
858
                break;
 
859
 
 
860
        case PSP_SAS_ADSR_CURVE_MODE_EXPONENT_INCREASE:
 
861
                expDelta = height_ - PSP_SAS_ENVELOPE_HEIGHT_MAX;
 
862
                // Flipping the sign so that we can shift in the top bits.
 
863
                expDelta += (-expDelta * rate) >> 32;
 
864
                height_ = expDelta + 0x4000 + PSP_SAS_ENVELOPE_HEIGHT_MAX;
 
865
                break;
 
866
 
 
867
        case PSP_SAS_ADSR_CURVE_MODE_DIRECT:
 
868
                height_ = rate;  // Simple :)
 
869
                break;
 
870
        }
 
871
}
 
872
 
 
873
void ADSREnvelope::SetState(ADSRState state) {
 
874
        if (height_ > PSP_SAS_ENVELOPE_HEIGHT_MAX) {
 
875
                height_ = PSP_SAS_ENVELOPE_HEIGHT_MAX;
 
876
        }
 
877
        // TODO: Also check for height_ < 0 and set to 0?
 
878
        state_ = state;
 
879
}
 
880
 
 
881
inline void ADSREnvelope::Step() {
 
882
        switch (state_) {
 
883
        case STATE_ATTACK:
 
884
                WalkCurve(attackType, attackRate);
 
885
                if (height_ >= PSP_SAS_ENVELOPE_HEIGHT_MAX || height_ < 0)
 
886
                        SetState(STATE_DECAY);
 
887
                break;
 
888
        case STATE_DECAY:
 
889
                WalkCurve(decayType, decayRate);
 
890
                if (height_ < sustainLevel)
 
891
                        SetState(STATE_SUSTAIN);
 
892
                break;
 
893
        case STATE_SUSTAIN:
 
894
                WalkCurve(sustainType, sustainRate);
 
895
                if (height_ <= 0) {
 
896
                        height_ = 0;
 
897
                        SetState(STATE_RELEASE);
 
898
                }
 
899
                break;
 
900
        case STATE_RELEASE:
 
901
                WalkCurve(releaseType, releaseRate);
 
902
                if (height_ <= 0) {
 
903
                        height_ = 0;
 
904
                        SetState(STATE_OFF);
 
905
                }
 
906
                break;
 
907
        case STATE_OFF:
 
908
                // Do nothing
 
909
                break;
 
910
 
 
911
        case STATE_KEYON:
 
912
                height_ = 0;
 
913
                SetState(STATE_KEYON_STEP);
 
914
                break;
 
915
        case STATE_KEYON_STEP:
 
916
                // This entire state is pretty much a hack to reproduce PSP behavior.
 
917
                // The STATE_KEYON state is a real state, but not sure how it switches.
 
918
                // It takes 32 steps at 0 for keyon to "kick in", 31 should shift to 0 anyway.
 
919
                height_++;
 
920
                if (height_ >= 31) {
 
921
                        height_ = 0;
 
922
                        SetState(STATE_ATTACK);
 
923
                }
 
924
                break;
 
925
        }
 
926
}
 
927
 
 
928
void ADSREnvelope::KeyOn() {
 
929
        SetState(STATE_KEYON);
 
930
}
 
931
 
 
932
void ADSREnvelope::KeyOff() {
 
933
        SetState(STATE_RELEASE);
 
934
}
 
935
 
 
936
void ADSREnvelope::End() {
 
937
        SetState(STATE_OFF);
 
938
        height_ = 0;
 
939
}
 
940
 
 
941
void ADSREnvelope::DoState(PointerWrap &p) {
 
942
        auto s = p.Section("ADSREnvelope", 1, 2);
 
943
        if (!s) {
 
944
                return;
 
945
        }
 
946
 
 
947
        p.Do(attackRate);
 
948
        p.Do(decayRate);
 
949
        p.Do(sustainRate);
 
950
        p.Do(releaseRate);
 
951
        p.Do(attackType);
 
952
        p.Do(decayType);
 
953
        p.Do(sustainType);
 
954
        p.Do(sustainLevel);
 
955
        p.Do(releaseType);
 
956
        if (s < 2) {
 
957
                p.Do(state_);
 
958
                if (state_ == 4) {
 
959
                        state_ = STATE_OFF;
 
960
                }
 
961
                int stepsLegacy;
 
962
                p.Do(stepsLegacy);
 
963
        } else {
 
964
                p.Do(state_);
 
965
        }
 
966
        p.Do(height_);
 
967
}