persona-3-dual
A DS demake of Persona 3
Loading...
Searching...
No Matches
AudioManager.cpp
Go to the documentation of this file.
1#define QOA_IMPLEMENTATION
2#include "AudioManager.hpp"
3#include "core/globals.hpp"
4#include "core/logger.hpp"
5
6#include <nds.h>
7#include <p3d-qoa>
8
9extern "C"
10{
11#include "soundbank.h"
12#include "soundbank_bin.h"
13}
14
16{
17 // initialize maxmod (for audio)
18 mm_ds_system sys;
19 sys.mod_count = 0;
20 sys.samp_count = 0;
21 sys.mem_bank = 0;
22 mmInit(&sys);
23 isAudioRegistered = false;
24
25 // initialize maxmod (for sfx)
26 mmInitDefaultMem((mm_addr)soundbank_bin);
27}
28
30{
32 {
33 mmStreamUpdate();
34 }
35}
36
38{
39 stopAudio();
40}
41
43{
44 if (!qp || qp->info.samplerate == 0)
45 {
46 logMessage(LogSeverity::WARNING, "Called with null or invalid audio stream");
47 return ae::q20_12_t{0};
48 }
49 return ae::q20_12_t{qp->info.samples} / ae::q20_12_t{qp->info.samplerate};
50}
51
53{
54 if (!qp || qp->info.samplerate == 0)
55 {
56 return ae::q20_12_t{0};
57 }
58 return ae::q20_12_t{qp->samplePos} / ae::q20_12_t{qp->info.samplerate};
59}
60
62{
63 if (!qp)
64 {
65 return 0;
66 }
67 return qp->samplePos / QOA_FRAME_LEN;
68}
69
71{
72 if (!qp || !qp->file)
73 {
74 logMessage(LogSeverity::WARNING, "Called on null audio player or file");
75 return;
76 }
77
78 if (frame < 0)
79 {
80 frame = 0;
81 }
82 if (frame > (int)qp->info.samples / QOA_FRAME_LEN)
83 {
84 frame = qp->info.samples / QOA_FRAME_LEN;
85 }
86
87 qp->samplePos = frame * QOA_FRAME_LEN;
88 qp->sampleDataLen = 0;
89 qp->sampleDataPos = 0;
90
91 uint32_t offset = qp->firstFramePos + frame * qoa_max_frame_size(&qp->info);
92 fseek(qp->file, offset, SEEK_SET);
93}
94
95void AudioManager::setLoop(ae::q20_12_t startTime, ae::q20_12_t endTime)
96{
97 if (!qp)
98 {
99 logMessage(LogSeverity::WARNING, "Called with null audio player");
100 return;
101 }
102
103 isLoopingEnabled = true;
104
105 // use 64-bit integers to prevent overflow
106 // .raw_value() returns the number pre-multiplied by 2^12, so we shift right by 12
107 int64_t startSample = ((int64_t)startTime.raw_value() * qp->info.samplerate) >> 12;
108 startFrame = startSample / QOA_FRAME_LEN;
109
110 if (endTime != ae::q20_12_t{-1})
111 {
112 int64_t endSample = ((int64_t)endTime.raw_value() * qp->info.samplerate) >> 12;
113 endFrame = endSample / QOA_FRAME_LEN;
114 }
115 else
116 {
117 endFrame = qp->info.samples / QOA_FRAME_LEN;
118 }
119}
120
122{
123 if (!isLoopingEnabled)
124 {
125 return;
126 }
127
128 if (getFrame() >= endFrame)
129 {
130 // rewind to start time
132 }
133}
134
136{
137 if (!qp || !qp->file)
138 {
139 return;
140 }
141
142 fseek(qp->file, qp->firstFramePos, SEEK_SET);
143 qp->samplePos = 0;
144 qp->sampleDataLen = 0;
145 qp->sampleDataPos = 0;
146}
147
149{
150 if (!qp || !qp->file || !qp->buffer || !qp->sampleData)
151 {
152 return 0;
153 }
154
155 qp->bufferLen = fread(qp->buffer, 1, qoa_max_frame_size(&qp->info), qp->file);
156
157 uint32_t frame_len;
158 qoa_decode_frame(qp->buffer, qp->bufferLen, &qp->info, qp->sampleData, &frame_len);
159 qp->sampleDataPos = 0;
160 qp->sampleDataLen = frame_len;
161 return frame_len;
162}
163
164uint32_t AudioManager::decode(short* sample_data, int num_samples)
165{
166 if (!qp || !sample_data)
167 {
168 return 0;
169 }
170
171 int src_index = qp->sampleDataPos * qp->info.channels;
172 int dst_index = 0;
173 for (int i = 0; i < num_samples; i++)
174 {
175 // do we have to decode more samples?
176 if (qp->sampleDataLen - qp->sampleDataPos == 0)
177 {
178 // loop audio section
179 loop();
180
181 // decode audio
182 if (!decodeFrame())
183 {
184 // loop to the beginning if audio is finished
185 rewind();
186 decodeFrame();
187 }
188 src_index = 0;
189 }
190
191 // write raw 16-bit PCM samples in interleaved channel order
192 for (int c = 0; c < (int)qp->info.channels; c++)
193 {
194 sample_data[dst_index++] = qp->sampleData[src_index++];
195 }
196 qp->sampleDataPos++;
197 qp->samplePos++;
198 }
199 return num_samples;
200}
201
202mm_word AudioManager::audioCallback(mm_word length, mm_addr dest, mm_stream_formats format)
203{
204 return AudioManager::getInstance().processStream(length, dest, format);
205}
206
207mm_word AudioManager::processStream(mm_word length, mm_addr dest, mm_stream_formats format)
208{
209 if (!qp)
210 {
211 return 0;
212 }
213
214 if (((qp->info.channels == 1) && (format != MM_STREAM_16BIT_MONO)) ||
215 ((qp->info.channels == 2) && (format != MM_STREAM_16BIT_STEREO)))
216 {
218 "Audio format from the current audio track does not match the original audio format");
219 }
220
221 uint32_t decoded = decode((short*)dest, length);
222 return decoded;
223}
224
225void AudioManager::registerAudio(std::string path, ae::q20_12_t loopStartTime, ae::q20_12_t loopEndTime)
226{
227 if (isAudioRegistered || qp)
228 {
229 stopAudio();
230 }
231
232 // open header
233 FILE* file = fopen(path.c_str(), "rb");
234 if (!file)
235 {
236 logMessage(LogSeverity::WARNING, "Failed to open audio file: " + path);
237 return;
238 }
239
240 // read header
241 uint8_t header[QOA_MIN_FILESIZE];
242 int read = fread(header, QOA_MIN_FILESIZE, 1, file);
243 if (!read)
244 {
245 logMessage(LogSeverity::ERROR, "Failed to read QOA header from: " + path);
246 fclose(file);
247 return;
248 }
249
250 // decode header
251 qoa_desc qoa;
252 uint32_t firstFramePos = qoa_decode_header(header, QOA_MIN_FILESIZE, &qoa);
253 if (!firstFramePos)
254 {
255 logMessage(LogSeverity::ERROR, "Failed to decode QOA header from: " + path);
256 fclose(file);
257 return;
258 }
259
260 // rewind file back to beginning of the first frame
261 fseek(file, firstFramePos, SEEK_SET);
262
263 // allocate one chunk of memory for the qoaplay_desc struct, the sample data
264 // for one frame and a buffer to hold one frame of encoded data.
265 uint32_t bufferSize = qoa_max_frame_size(&qoa);
266 uint32_t sampleDataSize = qoa.channels * QOA_FRAME_LEN * sizeof(short) * 2;
267
268 qp = (qoaplay_desc*)malloc(sizeof(qoaplay_desc) + bufferSize + sampleDataSize);
269 if (!qp)
270 {
271 logMessage(LogSeverity::ERROR, "Failed to allocate memory for QOA player: " + path);
272 fclose(file);
273 return;
274 }
275 memset(qp, 0, sizeof(qoaplay_desc));
276
277 // set qoaplay_desc values
278 qp->firstFramePos = firstFramePos;
279 qp->file = file;
280 qp->buffer = ((uint8_t*)qp) + sizeof(qoaplay_desc);
281 qp->sampleData = (short*)(((uint8_t*)qp) + sizeof(qoaplay_desc) + bufferSize);
282
283 qp->info.channels = qoa.channels;
284 qp->info.samplerate = qoa.samplerate;
285 qp->info.samples = qoa.samples;
286
287 // set loop
288 setLoop(loopStartTime, loopEndTime);
289
290 // setup maxmod audio
291 mm_stream stream;
292 stream.sampling_rate = qoa.samplerate;
293 stream.buffer_length = bufferSize;
294 stream.callback = audioCallback;
295 stream.format = (qoa.channels == 1) ? MM_STREAM_16BIT_MONO : MM_STREAM_16BIT_STEREO;
296 stream.timer = MM_TIMER0;
297 stream.manual = true;
298
299 mmStreamOpen(&stream);
300 mmPause();
301 isAudioRegistered = true;
302}
303
305{
306 mmResume();
307}
308
310{
311 mmPause();
312}
313
315{
316 if (qp)
317 {
318 if (qp->file)
319 {
320 fclose(qp->file);
321 qp->file = nullptr;
322 }
323
324 free(qp);
325 qp = nullptr;
326 }
327
328 isLoopingEnabled = false;
329 startFrame = 0;
330 endFrame = 0;
331
332 mmStreamClose();
333 isAudioRegistered = false;
334}
335
337{
338 mmLoadEffect((int)sfx);
339}
340
341void AudioManager::playSFX(SFX sfx, int volume, int panning)
342{
343 mm_sound_effect effect;
344 effect.id = (int)sfx;
345 effect.rate = (int)(1.0f * (1 << 10));
346 effect.handle = 0;
347 effect.volume = volume;
348 effect.panning = panning;
349 mmEffectEx(&effect);
350}
351
353{
354 mmEffectCancelAll();
355}
Manager for hardware specific audio functions.
SFX
SFX wrapper enums.
SaveHeader header
Definition SaveTypes.hpp:0
static mm_word audioCallback(mm_word length, mm_addr dest, mm_stream_formats format)
Callback for maxmod audio streaming, acting as a wrapper for processStream.
void stopSFX()
Stop all currently playing SFXs.
void setLoop(ae::q20_12_t startTime, ae::q20_12_t endTime)
Set the audio looping points.
void registerSFX(SFX sfx)
Register the SFX to be played.
void stopAudio()
Deregister the currently registered audio.
void pauseAudio()
Pause the currently registered audio, if playing.
ae::q20_12_t getDuration()
Get the total duration of the audio.
void process() override
mm_word processStream(mm_word length, mm_addr dest, mm_stream_formats format)
Processes the next audio data to play.
void rewind()
Move to the start of the audio track.
ae::q20_12_t getTime()
Get the current time of the audio.
void seekFrame(int frame)
Move to the specified audio frame.
void shutdown() override
void loop()
Looping logic.
void registerAudio(std::string path, ae::q20_12_t loopStartTime, ae::q20_12_t loopEndTime)
Sets up the audio track to be played.
uint32_t decodeFrame()
Decode the current audio frame.
void playSFX(SFX sfx, int volume, int panning)
Play the specified registered SFX.
void init() override
int getFrame()
Get the current audio frame.
uint32_t decode(short *sample_data, int num_samples)
Decode the given audio sample based on the current frame.
void playAudio()
Play the currently registered audio, if paused.
qoaplay_desc * qp
Holds global variables used game-wide.
volatile int32_t frame
Definition main.cpp:35
void logMessage(LogSeverity severity, std::string_view message, std::source_location location)
Logs a diagnostic message and halts only for fatal messages.
Definition logger.cpp:110
Util to handle error logging.
QOA audio stream data.