summaryrefslogtreecommitdiff
path: root/src/audio/spectrogram_resource_manager.cc
blob: f1828694382e06e3f3e8ab3502eb5edbfaca37fe (plain)
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
// This file is part of the 64k demo project.
// SpectrogramResourceManager implementation.

#include "spectrogram_resource_manager.h"
#include "audio/audio.h"
#include "audio/dct.h"
#include "procedural/generator.h"
#include "util/debug.h"
#include <cstring>
#include <vector>

#if !defined(STRIP_ALL)
#include "audio/mp3_sample.h"
#include "audio/window.h"
#endif

void SpectrogramResourceManager::init() {
  for (int i = 0; i < MAX_SPECTROGRAM_RESOURCES; ++i) {
    resources_[i].owned_data = nullptr;
    resources_[i].asset_id = AssetId::ASSET_LAST_ID;
    resources_[i].state = UNREGISTERED;
#if defined(DEMO_ENABLE_CACHE_EVICTION)
    resources_[i].last_access_time = 0.0f;
#endif
  }
  loaded_count_ = 0;
}

void SpectrogramResourceManager::shutdown() {
  // Free all owned memory (procedural spectrograms)
  for (int i = 0; i < MAX_SPECTROGRAM_RESOURCES; ++i) {
    if (resources_[i].owned_data != nullptr) {
      delete[] resources_[i].owned_data;
      resources_[i].owned_data = nullptr;
    }
  }
  loaded_count_ = 0;
}

void SpectrogramResourceManager::reset() {
  // Clear state and free owned memory, keep registrations
  for (int i = 0; i < MAX_SPECTROGRAM_RESOURCES; ++i) {
    if (resources_[i].state == LOADED) {
      if (resources_[i].owned_data) {
        delete[] resources_[i].owned_data;
        resources_[i].owned_data = nullptr;
      }
      resources_[i].state = REGISTERED;
    }
  }
  loaded_count_ = 0;
}

void SpectrogramResourceManager::register_asset(int sample_id,
                                                AssetId asset_id) {
  if (sample_id < 0 || sample_id >= MAX_SPECTROGRAM_RESOURCES) {
    return;
  }

  Resource& resource = resources_[sample_id];
  resource.asset_id = asset_id;
  if (resource.state == UNREGISTERED) {
    resource.state = REGISTERED;
  }

#if defined(DEBUG_LOG_ASSETS)
  DEBUG_ASSETS("[ResourceMgr] Registered asset sample_id=%d, asset_id=%d\n",
               sample_id, (int)asset_id);
#endif
}

void SpectrogramResourceManager::register_procedural(int sample_id,
                                                     const NoteParams& params) {
  if (sample_id < 0 || sample_id >= MAX_SPECTROGRAM_RESOURCES) {
    return;
  }

  Resource& resource = resources_[sample_id];
  resource.asset_id = AssetId::ASSET_LAST_ID; // Mark as procedural
  resource.proc_params = params;
  if (resource.state == UNREGISTERED) {
    resource.state = REGISTERED;
  }

#if defined(DEBUG_LOG_ASSETS)
  DEBUG_ASSETS("[ResourceMgr] Registered procedural sample_id=%d, freq=%.2f\n",
               sample_id, params.base_freq);
#endif
}

const Spectrogram* SpectrogramResourceManager::get_or_load(int sample_id) {
  if (sample_id < 0 || sample_id >= MAX_SPECTROGRAM_RESOURCES) {
    return nullptr;
  }

  Resource& resource = resources_[sample_id];

  // Already loaded?
  if (resource.state == LOADED) {
#if defined(DEMO_ENABLE_CACHE_EVICTION)
    resource.last_access_time = 0.0f; // TODO: Get actual time
#endif
    return &resource.spec;
  }

  // Need to load
  if (resource.state == REGISTERED) {
    if (resource.asset_id != AssetId::ASSET_LAST_ID) {
      load_asset(&resource);
    } else {
      load_procedural(&resource);
    }
    resource.state = LOADED;
    loaded_count_++;
  }

  return (resource.state == LOADED) ? &resource.spec : nullptr;
}

void SpectrogramResourceManager::preload(int sample_id) {
  // Just call get_or_load to trigger loading
  get_or_load(sample_id);
}

void SpectrogramResourceManager::preload_range(int start_id, int end_id) {
  for (int i = start_id; i <= end_id && i < MAX_SPECTROGRAM_RESOURCES; ++i) {
    preload(i);
  }
}

const Spectrogram*
SpectrogramResourceManager::get_spectrogram(int sample_id) const {
  if (sample_id < 0 || sample_id >= MAX_SPECTROGRAM_RESOURCES) {
    return nullptr;
  }

  const Resource& resource = resources_[sample_id];
  return (resource.state == LOADED) ? &resource.spec : nullptr;
}

bool SpectrogramResourceManager::is_loaded(int sample_id) const {
  if (sample_id < 0 || sample_id >= MAX_SPECTROGRAM_RESOURCES) {
    return false;
  }
  return resources_[sample_id].state == LOADED;
}

int SpectrogramResourceManager::get_loaded_count() const {
  return loaded_count_;
}

#if defined(DEMO_ENABLE_CACHE_EVICTION)
void SpectrogramResourceManager::release(int sample_id) {
  if (sample_id < 0 || sample_id >= MAX_SPECTROGRAM_RESOURCES) {
    return;
  }

  Resource& resource = resources_[sample_id];
  if (resource.state == LOADED && resource.owned_data != nullptr) {
    delete[] resource.owned_data;
    resource.owned_data = nullptr;
    resource.state = EVICTED;
    loaded_count_--;

#if defined(DEBUG_LOG_ASSETS)
    DEBUG_ASSETS("[ResourceMgr] Released sample_id=%d\n", sample_id);
#endif
  }
}

void SpectrogramResourceManager::release_all() {
  for (int i = 0; i < MAX_SPECTROGRAM_RESOURCES; ++i) {
    release(i);
  }
}

void SpectrogramResourceManager::try_evict_lru(float current_time) {
  // Find least recently used loaded resource
  int lru_id = -1;
  float oldest_time = current_time;

  for (int i = 0; i < MAX_SPECTROGRAM_RESOURCES; ++i) {
    if (resources_[i].state == LOADED &&
        resources_[i].last_access_time < oldest_time) {
      oldest_time = resources_[i].last_access_time;
      lru_id = i;
    }
  }

  // Evict if not accessed in last 10 seconds
  if (lru_id != -1 && (current_time - oldest_time) > 10.0f) {
    release(lru_id);
  }
}
#endif /* defined(DEMO_ENABLE_CACHE_EVICTION) */

void SpectrogramResourceManager::load_asset(Resource* resource) {
  size_t size;
  const uint8_t* data = GetAsset(resource->asset_id, &size);
  if (data == nullptr || size == 0) {
    return;
  }

#if !defined(STRIP_ALL)
  // MP3 assets: decode to spectrogram via OLA analysis
  if (GetAssetType(resource->asset_id) == AssetType::MP3) {
    load_mp3(resource, data, size);
    return;
  }
#endif

  if (size < sizeof(SpecHeader)) {
    return;
  }

  const SpecHeader* header = (const SpecHeader*)data;
  const float* spectral_data = (const float*)(data + sizeof(SpecHeader));

  resource->spec.spectral_data_a = spectral_data;
  resource->spec.spectral_data_b = spectral_data;
  resource->spec.num_frames = header->num_frames;
  resource->spec.version = header->version;
  resource->owned_data = nullptr; // Asset data is not owned
}

#if !defined(STRIP_ALL)
void SpectrogramResourceManager::load_mp3(Resource* resource,
                                          const uint8_t* data, size_t size) {
  Mp3Decoder* dec = mp3_open(data, size);
  if (!dec)
    return;

  float window[DCT_SIZE];
  hann_window_512(window);

  std::vector<float> spec_data;
  float pcm_buf[DCT_SIZE];
  float pcm_chunk[DCT_SIZE];
  float dct_chunk[DCT_SIZE];

  memset(pcm_buf, 0, sizeof(pcm_buf));

  for (;;) {
    memmove(pcm_buf, pcm_buf + OLA_HOP_SIZE, OLA_HOP_SIZE * sizeof(float));
    const int decoded = mp3_decode(dec, OLA_HOP_SIZE, pcm_buf + OLA_HOP_SIZE);
    if (decoded < OLA_HOP_SIZE) {
      memset(pcm_buf + OLA_HOP_SIZE + decoded, 0,
             (OLA_HOP_SIZE - decoded) * sizeof(float));
    }

    for (int i = 0; i < DCT_SIZE; ++i)
      pcm_chunk[i] = pcm_buf[i] * window[i];
    fdct_512(pcm_chunk, dct_chunk);
    spec_data.insert(spec_data.end(), dct_chunk, dct_chunk + DCT_SIZE);

    if (decoded == 0)
      break;
  }

  mp3_close(dec);
  if (spec_data.empty())
    return;

  const int num_frames = (int)(spec_data.size() / DCT_SIZE);
  resource->owned_data = new float[spec_data.size()];
  memcpy(resource->owned_data, spec_data.data(),
         spec_data.size() * sizeof(float));

  resource->spec.spectral_data_a = resource->owned_data;
  resource->spec.spectral_data_b = resource->owned_data;
  resource->spec.num_frames = num_frames;
  resource->spec.version = SPEC_VERSION_V2_OLA;
}
#endif

void SpectrogramResourceManager::load_procedural(Resource* resource) {
  int note_frames = 0;
  std::vector<float> note_data =
      generate_note_spectrogram(resource->proc_params, &note_frames);

  if (note_frames <= 0 || note_data.empty()) {
#if defined(DEBUG_LOG_ASSETS)
    DEBUG_ASSETS("[ResourceMgr ERROR] Failed to generate procedural note\n");
#endif
    return;
  }

  // Allocate persistent storage
  resource->owned_data = new float[note_data.size()];
  memcpy(resource->owned_data, note_data.data(),
         note_data.size() * sizeof(float));

  resource->spec.spectral_data_a = resource->owned_data;
  resource->spec.spectral_data_b = resource->owned_data;
  resource->spec.num_frames = note_frames;
  resource->spec.version = SPEC_VERSION_V1;

#if defined(DEBUG_LOG_ASSETS)
  DEBUG_ASSETS("[ResourceMgr] Generated procedural: %d frames, freq=%.2f\n",
               note_frames, resource->proc_params.base_freq);
#endif
}