Deluge Firmware 1.3.0
Build date: 2026.11.28
Loading...
Searching...
No Matches
audio_file_manager.h
1/*
2 * Copyright © 2017-2023 Synthstrom Audible Limited
3 *
4 * This file is part of The Synthstrom Audible Deluge Firmware.
5 *
6 * The Synthstrom Audible Deluge Firmware is free software: you can redistribute it and/or modify it under the
7 * terms of the GNU General Public License as published by the Free Software Foundation,
8 * either version 3 of the License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
11 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12 * See the GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License along with this program.
15 * If not, see <https://www.gnu.org/licenses/>.
16 */
17
18#pragma once
19#include "definitions_cxx.hpp"
20#include "storage/audio/audio_file_vector.h"
21#include "storage/cluster/cluster.h"
22#include "storage/cluster/cluster_priority_queue.h"
23#include <array>
24#include <cstdint>
25
26extern "C" {
27#include "RZA1/sdhi/inc/sd_async.h"
28#include "fatfs/ff.h"
29}
30
31class Sample;
32class SampleCache;
33class String;
34class SampleRecorder;
35class Output;
36
37enum class AlternateLoadDirStatus {
38 NONE_SET,
39 NOT_FOUND,
40 MIGHT_EXIST,
41 DOES_EXIST,
42};
43
44char const* const audioRecordingFolderNames[] = {
45 "SAMPLES/CLIPS",
46 "SAMPLES/RECORD",
47 "SAMPLES/RESAMPLE",
48 "SAMPLES/EXPORTS",
49};
50
51/*
52 * ===================== SD card audio streaming ==================
53 *
54 * Audio streaming (for Samples and AudioClips) from the SD card functions by loading
55 * and caching Clusters of audio data from the SD card. A formatted card will have a
56 * cluster size for the filesystem - often 32kB, but it could be as small as 4kB, or even smaller maybe?
57 * The Deluge deals in these Clusters, whatever size they may be for the card, which makes
58 * sense because one Cluster always exists in one physical place on the SD card (or any disk),
59 * so may be easily loaded in one operation by DMA. Whereas consecutive clusters making up an
60 * (audio) file are often placed in completely different physical locations.
61 *
62 * For a Sample associated with a Sound or AudioClip, the Deluge keeps the first two Clusters of that file
63 * (from its set start-point and subject to reversing) permanently loaded in RAM, so playback of the
64 * Sample may begin instantly when the Sound or AudioClip is played. And if the Sample has a loop-start point,
65 * it keeps the first two Clusters from that point permanently loaded too.
66 *
67 * Then as the Sample plays, the currently-playing Cluster and the next one are kept loaded in RAM.
68 * Or rather, as soon as the “play-head” enters a new Cluster, the Deluge immediately enqueues
69 * the following Cluster to be loaded from the card ASAP.
70 *
71 * Enqueued Clusters are read by the SD card interrupt (see sd_async.h): it takes the most urgent one off
72 * loadingQueue, has DMA read it, and goes straight on to the next, without the main thread waiting on the
73 * card. The main thread then finishes each one off in loadAnyEnqueuedClusters() - converting its data and
74 * marking it loaded.
75 *
76 * And then also, loaded Clusters remain loaded/cached in RAM for as long as possible while that RAM
77 * isn’t needed for something more important, so they may be played again without having to reload
78 * them from the card. Details on that process below.
79 *
80 * Quick note - Cluster objects are also used (in RAM) to store SampleCache data (which caches
81 * Sample data post-repitching or post-pitch-shifting), and “percussive” audio data (“perc” for short)
82 * which is condensed data for use by the time-stretching algorithm. The reason for these types
83 * of data being housed in Cluster objects is largely legacy, but it also is handy because all
84 * Cluster objects are made to be the same size in RAM, so “stealing” one will always make the
85 * right amount of space for another (see below to see what “stealing” means).
86 */
87
88class AudioFileManager {
89public:
90 AudioFileManager();
91
92 AudioFileVector audioFiles;
93
94 void init();
95 AudioFile* getAudioFileFromFilename(String& fileName, bool mayReadCard, Error* error, FilePointer* filePointer,
96 AudioFileType type, bool makeWaveTableWorkAtAllCosts = false);
97 bool loadCluster(Cluster& cluster, int32_t minNumReasonsAfter = 0);
98
100 void loadAnyEnqueuedClusters(bool mayProcessUserActionsBetween = false);
101
107 bool loadEnqueuedClusterNow(Cluster& cluster);
108 void removeReasonFromCluster(Cluster& cluster, char const* errorCode, bool deletingSong = false);
109
121 bool prefetchCluster(Sample* sample, int32_t clusterIndex);
122
125 [[nodiscard]] uint32_t getPrefetchGeneration() const { return prefetchGeneration_; }
126
130 void claimPrefetch(Cluster const* cluster);
131
133 void releasePrefetchesForSample(Sample const* sample);
134
137
140
141 bool ensureEnoughMemoryForOneMoreAudioFile();
142
143 void slowRoutine();
144
145 Error setupAlternateAudioFilePath(String& newPath, int32_t dirPathLength, String& oldPath);
146 Error setupAlternateAudioFileDir(String& newPath, char const* rootDir, const char* songFilenameWithoutExtension);
151
154 void forgetClusterRead(Cluster const* cluster);
157 Error getUnusedAudioRecordingFilePath(String& filePath, String* tempFilePathForRecording,
158 AudioRecordingFolder folder, uint32_t* getNumber, const char* channelName,
159 String* songName);
160 void deleteAnyTempRecordedSamplesFromMemory();
161 void deleteUnusedAudioFileFromMemory(AudioFile& audioFile, int32_t i);
162 void deleteUnusedAudioFileFromMemoryIndexUnknown(AudioFile& audioFile);
163 bool tryToDeleteAudioFileFromMemoryIfItExists(char const* filePath);
164
165 void thingBeginningLoading(ThingType newThingType);
166 void thingFinishedLoading();
167
168 void setCardRead() { cardReadOnce = true; }
169 void setCardEjected() { cardEjected = true; }
170 // Whether loadAnyEnqueuedClusters() is able to read the card at all
171 bool canLoadClusters() const { return !cardEjected && !cardDisabled; }
172
173 ClusterPriorityQueue loadingQueue;
174
175 Cluster* clusterBeingLoaded;
176 int32_t minNumReasonsForClusterBeingLoaded; // Only valid when clusterBeingLoaded is set. And this exists for bug
177 // hunting only.
178
179 String alternateAudioFileLoadPath;
180 AlternateLoadDirStatus alternateLoadDirStatus = AlternateLoadDirStatus::NONE_SET;
181 ThingType thingTypeBeingLoaded = ThingType::NONE;
182 DIR alternateLoadDir;
183
184 std::array<int32_t, kNumAudioRecordingFolders> highestUsedAudioRecordingNumber;
185 std::bitset<kNumAudioRecordingFolders> highestUsedAudioRecordingNumberNeedsReChecking;
186 void firstCardRead();
187
188private:
190 struct ClusterRead {
192 Priority priority;
193 int32_t error;
194 };
195
197 static constexpr size_t kMaxClusterReads = 32;
198
199 // The SD interrupt only ever writes clusterBeingRead_ and adds to clusterReads_. The main thread only ever takes
200 // from clusterReads_, or forgets one in it, with interrupts disabled.
201 Cluster* volatile clusterBeingRead_ = nullptr;
202 Priority priorityBeingRead_ = 0;
203 std::array<ClusterRead, kMaxClusterReads> clusterReads_;
204 volatile size_t clusterReadsStart_ = 0;
205 volatile size_t clusterReadsEnd_ = 0;
206
207 [[nodiscard]] size_t numClusterReads() const { return clusterReadsEnd_ - clusterReadsStart_; }
208 [[nodiscard]] bool isClusterBeingRead(Cluster const* cluster, const InterruptsDisabled&) const;
209
210 // The callbacks given to sd_async, which call the two below
211 friend bool sdAsyncNextRead(SdAsyncRead* read);
212 friend void sdAsyncReadDone(void* user, int error);
213
215 bool nextClusterRead(SdAsyncRead& read, const InterruptsDisabled&);
217 void clusterReadDone(int error, const InterruptsDisabled&);
218
220 void finishClusterReads();
221 void finishClusterRead(Cluster& cluster, int32_t error);
223 void finishLoadingCluster(Cluster& cluster);
225 void recycleUnwantedCluster(Cluster& cluster);
226
229 struct Prefetch {
230 Cluster* cluster;
231 Sample* sample;
232 };
233
236 static constexpr size_t kMaxPrefetches = 32;
238 std::array<Prefetch, kMaxPrefetches> prefetches_;
239 size_t numPrefetches_ = 0;
240 uint32_t prefetchGeneration_ = 0;
241
243 void releasePrefetch(size_t i);
245 void releasePrefetchesIf(auto shouldRelease);
246
247 bool cardReadOnce{false};
248 bool cardEjected;
249 bool cardDisabled = false;
250
251 uint32_t clusterSizeAtBoot{0};
252
253 void cardReinserted();
254 int32_t readBytes(char* buffer, int32_t num, int32_t* byteIndexWithinCluster, Cluster** currentCluster,
255 uint32_t* currentClusterIndex, uint32_t fileSize, Sample* sample);
256 int32_t loadAiff(Sample* newSample, uint32_t fileSize, Cluster** currentCluster, uint32_t* currentClusterIndex);
257 int32_t loadWav(Sample* newSample, uint32_t fileSize, Cluster** currentCluster, uint32_t* currentClusterIndex);
258};
259
260extern AudioFileManager audioFileManager;
Definition audio_file_manager.h:88
std::array< Prefetch, kMaxPrefetches > prefetches_
Oldest first.
Definition audio_file_manager.h:238
void releasePrefetch(size_t i)
Removes the reasons prefetches_[i] holds, and removes it from prefetches_, keeping the order.
Definition audio_file_manager.cpp:1631
volatile size_t clusterReadsEnd_
One past the newest. Only written by the SD interrupt.
Definition audio_file_manager.h:205
void releaseUnloadablePrefetches()
Lets go of prefetched Clusters that will never load because they're unloadable.
Definition audio_file_manager.cpp:1660
volatile size_t clusterReadsStart_
Oldest. Only written by the main thread.
Definition audio_file_manager.h:204
bool nextClusterRead(SdAsyncRead &read, const InterruptsDisabled &)
For the SD interrupt (see sd_async.h) - takes the next Cluster off the loading queue,...
Definition audio_file_manager.cpp:1357
void forgetClusterRead(Cluster const *cluster)
Makes sure the SD interrupt is done with cluster, and won't hand it back to finish loading,...
Definition audio_file_manager.cpp:1407
void releasePrefetchesForSample(Sample const *sample)
Lets go of every prefetched Cluster of sample, e.g. because what was going to play it has stopped.
Definition audio_file_manager.cpp:1656
void releasePrefetchesIf(auto shouldRelease)
Releases every prefetch shouldRelease returns true for.
Definition audio_file_manager.cpp:1641
void recycleUnwantedCluster(Cluster &cluster)
Recycles a Cluster whose last reason was removed while the SD interrupt was reading it.
Definition audio_file_manager.cpp:1474
uint32_t getPrefetchGeneration() const
Changes whenever a Cluster is added to or released from the prefetch list. While it and what a caller...
Definition audio_file_manager.h:125
void finishClusterReads()
Finishes off Clusters the SD interrupt has read.
Definition audio_file_manager.cpp:1426
void claimPrefetch(Cluster const *cluster)
Lets go of a prefetched Cluster, now that something that's going to play it holds its own reason on i...
Definition audio_file_manager.cpp:1652
static constexpr size_t kMaxPrefetches
Most Clusters held at once. Bounds the RAM they can pin, and keeps them from crowding out Clusters so...
Definition audio_file_manager.h:236
bool prefetchCluster(Sample *sample, int32_t clusterIndex)
Holds a Cluster that's likely to be requested soon, loading it first if need be.
Definition audio_file_manager.cpp:1588
void loadAnyEnqueuedClusters(bool mayProcessUserActionsBetween=false)
Finishes off Clusters the SD interrupt has read, and gets it reading any that are enqueued.
Definition audio_file_manager.cpp:1325
void clusterReadDone(int error, const InterruptsDisabled &)
For the SD interrupt - it's finished reading clusterBeingRead_.
Definition audio_file_manager.cpp:1385
static constexpr size_t kMaxClusterReads
Most reads finishClusterReads() can fall behind by. The SD interrupt stops reading once there are thi...
Definition audio_file_manager.h:197
void finishLoadingCluster(Cluster &cluster)
Converts cluster's data and swaps the bytes that overhang its neighbours, now that it's been read.
Definition audio_file_manager.cpp:1111
bool hasClusterLoadsPending()
Whether any Clusters are still waiting to load, or being loaded.
Definition audio_file_manager.cpp:1687
bool loadEnqueuedClusterNow(Cluster &cluster)
Loads cluster right now if it's in the loading queue, without loading what's ahead of it....
Definition audio_file_manager.cpp:1486
Error getUnusedAudioRecordingFilePath(String &filePath, String *tempFilePathForRecording, AudioRecordingFolder folder, uint32_t *getNumber, const char *channelName, String *songName)
Definition audio_file_manager.cpp:270
bool loadingQueueHasAnySampleStarts()
Whether any Samples' first Clusters, which let them start instantly, are still waiting to load.
Definition audio_file_manager.cpp:1673
void releaseAllPrefetches()
Lets go of every prefetched Cluster and its Sample, loaded or not.
Definition audio_file_manager.cpp:1667
Definition audio_file_vector.h:24
Definition audio_file.h:26
Definition cluster.h:34
Definition output.h:81
Definition sample_cache.h:25
Definition sample_recorder.h:53
Definition sample.h:50
Definition d_string.h:41
A Cluster the SD interrupt has finished reading, waiting for finishClusterReads().
Definition audio_file_manager.h:190
Cluster * cluster
nullptr if forgetClusterRead() was called for it
Definition audio_file_manager.h:191
int32_t error
SD_OK, or an SD_ERR_* code.
Definition audio_file_manager.h:193
A Cluster that prefetchCluster() is holding. We hold one reason on it and one on its Sample,...
Definition audio_file_manager.h:229