persona-3-dual
A DS demake of Persona 3
Loading...
Searching...
No Matches
VideoController.cpp
Go to the documentation of this file.
1#include "VideoController.hpp"
2#include "core/globals.hpp"
3#include "core/logger.hpp"
5#include <malloc.h>
6#include <maxmod9.h>
7#include <nds.h>
8#include <new>
9#include <p3d-qoa>
10#include <stdio.h>
11#include <stdlib.h>
12#include <string.h>
13
14constexpr uint8_t VID_AUDIO_NONE = 0;
15constexpr uint8_t VID_AUDIO_QOA = 1;
16
17namespace
18{
19constexpr uint32_t RING_SIZE = 32768; // compressed audio ring, must be a power of two
20constexpr uint32_t RING_MASK = RING_SIZE - 1;
21static_assert(AUDIO_CHUNK_MAX <= RING_SIZE, "audio ring must hold at least one audio chunk");
22} // namespace
23
24// ===========================================================================
25// Internal QOA player: compressed ring -> QOA decode -> maxmod stream
26// ===========================================================================
27static mm_word videoAudioCallback(mm_word length, mm_addr dest, mm_stream_formats);
28static VideoAudio* g_audio = nullptr;
29
31{
32 uint8_t* ring = nullptr;
33 uint32_t head = 0;
34 uint32_t count = 0;
35
36 short* pcm = nullptr; // one decoded QOA frame, interleaved
37 uint32_t pcmPos = 0;
38 uint32_t pcmLen = 0;
39
40 uint8_t* scratch = nullptr; // for frames that wrap around the ring end
41 uint32_t scratchSize = 0;
42
43 qoa_desc desc;
44 uint32_t rate = 0;
45 uint32_t channels = 0;
46 uint32_t streamSamples = 0;
47
48 uint32_t contentSamples = 0; // real audio samples handed to maxmod
49 uint32_t freeRunSamples = 0; // silence after the file ended (keeps the clock running)
50 uint32_t silentRun = 0; // consecutive fully-silent samples
51 bool fileEnded = false;
52 bool fault = false;
53 bool streamOpen = false;
54
55 bool open(uint32_t sampleRate, uint32_t numChannels)
56 {
57 rate = sampleRate;
58 channels = numChannels;
59 memset(&desc, 0, sizeof(desc));
60 desc.channels = numChannels;
61 desc.samplerate = sampleRate;
62
63 scratchSize = qoa_max_frame_size(&desc);
64 ring = (uint8_t*)malloc(RING_SIZE);
65 pcm = (short*)malloc(QOA_FRAME_LEN * numChannels * sizeof(short));
66 scratch = (uint8_t*)malloc(scratchSize);
67 if (!ring || !pcm || !scratch)
68 {
69 close();
70 return false;
71 }
72
73 uint32_t s = (rate * VIDEO_AUDIO_STREAM_MS / 1000) & ~15u;
74 streamSamples = s < 512 ? 512 : (s > 8192 ? 8192 : s);
75 return true;
76 }
77
78 bool start()
79 {
80 mm_stream stream;
81 stream.sampling_rate = rate;
82 stream.buffer_length = streamSamples;
83 stream.callback = videoAudioCallback;
84 stream.format = (channels == 1) ? MM_STREAM_16BIT_MONO : MM_STREAM_16BIT_STEREO;
85 stream.timer = MM_TIMER0;
86 stream.manual = true;
87
88 g_audio = this;
89 mmStreamOpen(&stream);
90 streamOpen = true;
91 mmStreamUpdate(); // prime the buffer
92 mmResume(); // harmless if not paused; covers a leftover mmPause()
93 return true;
94 }
95
96 void close()
97 {
98 if (streamOpen)
99 {
100 mmStreamClose();
101 streamOpen = false;
102 }
103 g_audio = nullptr;
104 free(ring);
105 free(pcm);
106 free(scratch);
107 ring = nullptr;
108 pcm = nullptr;
109 scratch = nullptr;
110 }
111
112 void pump()
113 {
114 if (streamOpen)
115 {
116 mmStreamUpdate();
117 }
118 }
119
120 uint32_t space() const
121 {
122 return RING_SIZE - count;
123 }
124
125 // Reads `size` bytes from f directly into the ring (handles wrap-around).
126 bool readFrom(FILE* f, uint32_t size)
127 {
128 uint32_t tail = (head + count) & RING_MASK;
129 uint32_t first = RING_SIZE - tail;
130 if (first > size)
131 {
132 first = size;
133 }
134 if (fread(ring + tail, 1, first, f) != first)
135 {
136 return false;
137 }
138 if (size > first && fread(ring, 1, size - first, f) != size - first)
139 {
140 return false;
141 }
142 count += size;
143 return true;
144 }
145
146 // Decodes the next whole QOA frame from the ring into pcm.
148 {
149 pcmPos = 0;
150 pcmLen = 0;
151 if (count < 8)
152 {
153 return false;
154 }
155
156 uint8_t h[8];
157 for (uint32_t i = 0; i < 8; i++)
158 {
159 h[i] = ring[(head + i) & RING_MASK];
160 }
161 uint32_t size = ((uint32_t)h[6] << 8) | h[7];
162 if (h[0] != channels || size < 8 || size > scratchSize)
163 {
164 fault = true;
165 return false;
166 }
167 if (count < size)
168 {
169 return false; // underrun
170 }
171
172 const uint8_t* src;
173 uint32_t toEnd = RING_SIZE - head;
174 if (size <= toEnd)
175 {
176 src = ring + head;
177 }
178 else
179 {
180 memcpy(scratch, ring + head, toEnd);
181 memcpy(scratch + toEnd, ring, size - toEnd);
182 src = scratch;
183 }
184
185 uint32_t len = 0;
186 qoa_decode_frame(src, size, &desc, pcm, &len);
187 head = (head + size) & RING_MASK;
188 count -= size;
189
190 if (len == 0 || len > QOA_FRAME_LEN)
191 {
192 fault = true;
193 return false;
194 }
195 pcmLen = len;
196 return true;
197 }
198
199 // Playback position in samples (what is audible, not just decoded).
200 uint32_t clock() const
201 {
202 s32 latency = (s32)streamSamples + (VIDEO_SYNC_OFFSET_MS * (s32)rate) / 1000;
203 s32 played = (s32)(contentSamples + freeRunSamples) - latency;
204 return played > 0 ? (uint32_t)played : 0;
205 }
206
207 bool failed() const
208 {
209 return fault || (!fileEnded && silentRun > rate * 2);
210 }
211};
212
213static mm_word videoAudioCallback(mm_word length, mm_addr dest, mm_stream_formats)
214{
215 VideoAudio* a = g_audio;
216 if (!a)
217 {
218 return 0;
219 }
220
221 short* out = (short*)dest;
222 const uint32_t ch = a->channels;
223 uint32_t done = 0;
224
225 while (done < length)
226 {
227 if (a->pcmPos >= a->pcmLen && !a->decodeFrame())
228 {
229 break;
230 }
231 uint32_t n = a->pcmLen - a->pcmPos;
232 if (n > length - done)
233 {
234 n = length - done;
235 }
236 const size_t copySamples = static_cast<size_t>(n) * static_cast<size_t>(ch);
237 const size_t copyBytes = copySamples * sizeof(short);
238 memcpy(out + done * ch, a->pcm + a->pcmPos * ch, copyBytes);
239 a->pcmPos += n;
240 done += n;
241 }
242
243 a->contentSamples += done;
244
245 if (done < length)
246 {
247 uint32_t pad = length - done;
248 const size_t padSamples = static_cast<size_t>(pad) * static_cast<size_t>(ch);
249 const size_t padBytes = padSamples * sizeof(short);
250 memset(out + done * ch, 0, padBytes);
251 if (a->fileEnded)
252 {
253 a->freeRunSamples += pad; // no more audio will come: let time pass
254 }
255 a->silentRun = done ? 0 : a->silentRun + pad;
256 }
257 else
258 {
259 a->silentRun = 0;
260 }
261 return length;
262}
263
264// ===========================================================================
265// VideoController
266// ===========================================================================
268
270{
271 if (instance == nullptr)
272 {
274 }
275}
276
278{
279 if (instance != nullptr)
280 {
281 delete instance;
282 }
283 instance = nullptr;
284}
285
287{
288 if (instance == nullptr)
289 {
290 create();
291 }
292 return instance;
293}
294
296{
297 if (aud)
298 {
299 aud->pump();
300 }
301}
302
304{
305 if (aud)
306 {
307 aud->close();
308 delete aud;
309 aud = nullptr;
310 }
311}
312
314{
315 fileEOF = true;
316 if (aud)
317 {
318 aud->fileEnded = true;
319 }
320}
321
323{
324 if (aud)
325 {
326 return (int)(((u64)aud->clock() * (uint32_t)fpsInt) / aud->rate);
327 }
328 return (int)(((u64)silentVblanks * (uint32_t)fpsInt) / 60);
329}
330
331void VideoController::init(std::string iFileName, ae::q20_12_t iFps, ViewState iNextState)
332{
333 // Make repeated initialization safe.
335 if (ramBuffer != nullptr)
336 {
337 free(ramBuffer);
338 ramBuffer = nullptr;
339 }
340 if (videoFile != nullptr)
341 {
342 fclose(videoFile);
343 videoFile = nullptr;
344 }
345
346 fileEOF = false;
347 framesAvailable = 0;
348 readIndex = 0;
349 writeIndex = 0;
350 currentFrame = 0;
351 silentVblanks = 0;
352 haveChunkHeader = false;
354
355 nextState = iNextState;
356 fpsInt = (int)(iFps.raw_value() >> 12); // fallback if no header exists
357
358 std::string videoPath = fatBasePath + "video/" + iFileName;
359
360 videoSetMode(MODE_5_2D | DISPLAY_BG3_ACTIVE);
361 videoSetModeSub(MODE_0_2D);
362
363 vramSetBankA(VRAM_A_MAIN_BG_0x06000000);
364 vramSetBankD(VRAM_D_MAIN_BG_0x06020000);
365 vramSetBankC(VRAM_C_SUB_BG);
366
367 // maxmod supports one stream at a time: release any music stream first.
368 AudioManager::getInstance().stopAudio();
369
370 logMessage(LogSeverity::DEBUG, "Video playback initialized: " + iFileName);
371
372 videoFile = fopen(videoPath.c_str(), "rb");
373 if (!videoFile)
374 {
375 logMessage(LogSeverity::FATAL, videoPath);
376 }
377
378 // Read the optional dynamic video header.
379 uint8_t header[16];
380 size_t hRead = fread(header, 1, 16, videoFile);
381 uint8_t audioCodec = VID_AUDIO_NONE;
382 uint32_t audioRate = 0;
383 uint32_t audioChannels = 0;
384
385 if (hRead == 16 && memcmp(header, "VID\0", 4) == 0)
386 {
387 // byte-wise reads avoid unaligned access crashes on the ARM9
388 fpsInt = header[4] | (header[5] << 8);
389 bpp = header[6];
390 audioCodec = header[7];
391 frameW = header[8] | (header[9] << 8);
392 frameH = header[10] | (header[11] << 8);
393 audioRate = header[12] | (header[13] << 8);
394 audioChannels = header[14];
395 }
396 else
397 {
398 // Support legacy raw 16-bit 256x192 video files.
399 fseek(videoFile, 0, SEEK_SET);
400 bpp = 2;
401 frameW = 256;
402 frameH = 192;
403 }
404
405 if (fpsInt <= 0)
406 {
407 fpsInt = 24;
408 }
409 if ((bpp != 1 && bpp != 2) || frameW == 0 || frameH == 0)
410 {
411 logMessage(LogSeverity::FATAL, "bad video header");
412 }
413
414 frameSize = (uint32_t)frameW * frameH * bpp;
416
417 // Select the background format from the parsed bit depth.
418 if (bpp == 1)
419 {
420 bg = bgInit(3, BgType_Bmp8, BgSize_B8_256x256, 0, 0);
421
422 uint16_t palette[256];
423 size_t palRead = fread(palette, 2, 256, videoFile);
424 if (palRead != 256)
425 {
426 logMessage(LogSeverity::FATAL, "palette read failed");
427 }
428
429 for (int i = 0; i < 256; i++)
430 {
431 BG_PALETTE[i] = palette[i];
432 }
433 }
434 else
435 {
436 bgExtPaletteEnable();
437 bg = bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0, 0);
438 }
439
440 // Clear the first frame target before playback.
441 dmaFillWords(0, bgGetGfxPtr(bg), frameSize);
442
443 ramBuffer = (uint8_t*)memalign(32, bufferSize);
444 if (!ramBuffer)
445 {
446 logMessage(LogSeverity::FATAL, "malloc failed");
447 }
448
449 // Set up the internal audio player (falls back to silent playback on failure).
450 if (audioCodec == VID_AUDIO_QOA && audioRate > 0 && (audioChannels == 1 || audioChannels == 2))
451 {
452 aud = new (std::nothrow) VideoAudio();
453 if (aud && !aud->open(audioRate, audioChannels))
454 {
455 delete aud;
456 aud = nullptr;
457 }
458 }
459
460 // Prefill video (and the first audio chunks) before the stream starts.
461 for (int i = 0; i < 3; i++)
462 {
463 if (!refillBuffer())
464 {
465 break;
466 }
467 }
468
469 if (aud)
470 {
471 aud->start();
472 }
473}
474
476{
478 {
479 return false;
480 }
481
482 // Each frame starts with a uint32_t audio size.
483 if (!haveChunkHeader)
484 {
485 uint32_t size = 0;
486 if (fread(&size, 4, 1, videoFile) != 1)
487 {
488 setEOF();
489 return false;
490 }
491 pendingAudioSize = size;
492 haveChunkHeader = true;
493 }
494
495 if (pendingAudioSize > 0)
496 {
498 {
499 if (aud->space() < pendingAudioSize)
500 {
501 return false; // backpressure: wait for the audio to drain
502 }
503 if (!aud->readFrom(videoFile, pendingAudioSize))
504 {
505 setEOF();
506 return false;
507 }
508 }
509 else if (fseek(videoFile, (long)pendingAudioSize, SEEK_CUR) != 0)
510 {
511 // silent/legacy file (or oversized chunk): skip the payload
512 setEOF();
513 return false;
514 }
516 }
517 haveChunkHeader = false;
518
519 // Read the video frame in slices, feeding the audio stream in between.
520 uint8_t* dest = &ramBuffer[writeIndex * frameSize];
521 uint32_t got = 0;
522 while (got < frameSize)
523 {
524 uint32_t n = frameSize - got;
525 if (n > VIDEO_READ_SLICE)
526 {
528 }
529 size_t r = fread(dest + got, 1, n, videoFile);
530 got += (uint32_t)r;
531 if (r != n)
532 {
533 break;
534 }
535 pumpAudio();
536 }
537
538 if (got != frameSize)
539 {
540 setEOF();
541 return false;
542 }
543
544 DC_FlushRange(dest, frameSize);
547 return true;
548}
549
551{
552 pumpAudio();
553
554 // Audio faulted or went silent before the file ended: continue on the vblank clock.
555 if (aud && aud->failed())
556 {
558 silentVblanks = (uint32_t)(((u64)currentFrame * 60) / (uint32_t)fpsInt);
559 }
560
561 if (!aud)
562 {
564 }
565
566 int expected = clockFrame();
567
568 // Drop late frames (bounded so we never stall on a long catch-up).
569 int dropBudget = 3;
570 while (currentFrame < expected - 1 && framesAvailable > 0 && dropBudget-- > 0)
571 {
574 currentFrame++;
575 }
576
577 if (fileEOF && framesAvailable == 0)
578 {
579 return nextState;
580 }
581
582 // Display first, so SD reads never delay a due frame.
583 if (framesAvailable > 0 && currentFrame <= expected)
584 {
585 pumpAudio();
586 dmaCopy(&ramBuffer[readIndex * frameSize], bgGetGfxPtr(bg), frameSize);
589 currentFrame++;
590 }
591
592 // Use the remaining time to read ahead; stop early if the next frame is already due.
593 for (int r = 0; r < READS_PER_UPDATE; r++)
594 {
595 if (r > 0 && framesAvailable > 0 && currentFrame <= clockFrame())
596 {
597 break;
598 }
599 if (!refillBuffer())
600 {
601 break;
602 }
603 pumpAudio();
604 }
605
607}
608
610{
612
613 if (ramBuffer != nullptr)
614 {
615 if (bg >= 0)
616 {
617 dmaFillWords(0, bgGetGfxPtr(bg), frameSize);
618 }
619 free(ramBuffer);
620 ramBuffer = nullptr;
621 }
622
623 bg = -1;
624
625 if (videoFile != nullptr)
626 {
627 fclose(videoFile);
628 videoFile = nullptr;
629 }
630
631 haveChunkHeader = false;
633 silentVblanks = 0;
634
635 fileEOF = false;
636 framesAvailable = 0;
637 readIndex = 0;
638 writeIndex = 0;
639 currentFrame = 0;
640}
Manager for hardware specific audio functions.
SaveHeader header
Definition SaveTypes.hpp:0
ViewState
Definition StateTypes.hpp:4
static mm_word videoAudioCallback(mm_word length, mm_addr dest, mm_stream_formats)
static VideoAudio * g_audio
constexpr uint8_t VID_AUDIO_NONE
constexpr uint8_t VID_AUDIO_QOA
constexpr uint16_t AUDIO_CHUNK_MAX
Maximum audio payload (bytes) in one per-frame chunk. Must match MAX_AUDIO_CHUNK in video2vid....
constexpr uint8_t FRAMES_TO_BUFFER
Number of decoded video frames held in the RAM ring buffer.
constexpr uint8_t VIDEO_AUDIO_STREAM_MS
Length of the maxmod audio stream buffer in ms. Larger tolerates slower SD reads.
constexpr int8_t VIDEO_SYNC_OFFSET_MS
Fine A/V sync offset in ms.
constexpr uint8_t READS_PER_UPDATE
Maximum frame reads per update(). Reads stop early if a frame is already due.
constexpr uint16_t VIDEO_READ_SLICE
Size (bytes) of each SD card read slice when loading a video frame.
Streams video frames and multiplexed QOA audio from a single .vid file.
static void create()
Creates the singleton instance if it does not exist.
void pumpAudio()
Feeds the maxmod stream; a no-op when no audio is active.
VideoAudio * aud
Internal audio player; non-null while audio is active.
uint32_t frameSize
Size of one frame in bytes.
void stopInternalAudio()
Shuts down and frees the internal audio player.
uint8_t * ramBuffer
Ring buffer holding FRAMES_TO_BUFFER decoded frames.
static VideoController * instance
Singleton instance.
void cleanup()
Stops playback and releases the file, audio stream and frame buffer.
FILE * videoFile
Open .vid file handle.
static VideoController * getInstance()
uint16_t frameW
Frame width in pixels.
int64_t currentFrame
Index of the next frame to display.
ViewState update()
Advances playback: pumps audio, displays the next due frame and reads ahead.
ViewState nextState
State returned when playback ends.
bool haveChunkHeader
True if the current chunk's audio size has been read.
uint16_t writeIndex
Ring slot the next frame is read into.
uint32_t pendingAudioSize
Audio bytes still to be read for the current chunk.
void setEOF()
Marks end of file and tells the audio player no more data will arrive.
bool refillBuffer()
Reads one audio chunk (into the audio ring) and one video frame.
static void destroy()
Destroys the singleton instance and releases all video resources.
void init(std::string iFileName, ae::q20_12_t iFps, ViewState iNextState)
Opens and prepares a video stream.
int8_t bg
Background id returned by bgInit().
uint32_t silentVblanks
Pacing clock (vblanks) used when there is no audio.
bool fileEOF
True once the file (or a read) is exhausted.
int clockFrame() const
Computes the frame that should be on screen now.
VideoController()=default
uint16_t framesAvailable
Number of frames currently buffered.
uint8_t bpp
Bytes per pixel (1 = 8-bit paletted, 2 = 16-bit).
uint16_t frameH
Frame height in pixels.
uint32_t bufferSize
Total size of the frame ring buffer in bytes.
uint8_t fpsInt
Frame rate in whole fps (from the header or fallback).
uint16_t readIndex
Ring slot of the next frame to display.
Holds global variables used game-wide.
std::string fatBasePath
Definition main.cpp:38
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.
uint8_t * scratch
uint32_t freeRunSamples
bool failed() const
uint32_t contentSamples
uint32_t streamSamples
uint32_t channels
bool open(uint32_t sampleRate, uint32_t numChannels)
uint32_t space() const
uint32_t silentRun
bool readFrom(FILE *f, uint32_t size)
uint32_t scratchSize
uint32_t clock() const