summaryrefslogtreecommitdiff
path: root/src/audio/spectrogram_resource_manager.h
blob: 97196d1753052d309ef614bc6cbcd43b833098d3 (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
// This file is part of the 64k demo project.
// SpectrogramResourceManager: Centralized resource loading and ownership.
// Handles both asset spectrograms and procedurally generated notes.

#pragma once

#include "audio/gen.h"
#include "audio/synth.h"
#include "generated/assets.h"
#include "util/asset_manager.h"
#include <cstdint>

// Maximum number of unique spectrogram resources
constexpr int MAX_SPECTROGRAM_RESOURCES = 256;

class SpectrogramResourceManager {
 public:
  // Lifecycle
  void init();
  void shutdown();  // Frees all owned memory
  void reset();     // Clear state but keep registrations

  // Metadata registration (no loading yet, just bookkeeping)
  void register_asset(int sample_id, AssetId asset_id);
  void register_procedural(int sample_id, const NoteParams& params);

  // Lazy loading API (loads on first access if not cached)
  const Spectrogram* get_or_load(int sample_id);

  // Explicit pre-warming (for timeline seeking)
  void preload(int sample_id);
  void preload_range(int start_id, int end_id);

  // Query API
  const Spectrogram* get_spectrogram(int sample_id) const;
  bool is_loaded(int sample_id) const;
  int get_loaded_count() const;

#if defined(DEMO_ENABLE_CACHE_EVICTION)
  // Cache management (optional, compile-time flag)
  void release(int sample_id);
  void release_all();
  void try_evict_lru(float current_time);
#endif /* defined(DEMO_ENABLE_CACHE_EVICTION) */

 private:
  enum ResourceState {
    UNREGISTERED = 0,  // No metadata registered
    REGISTERED,        // Metadata registered, not loaded yet
    LOADED,            // Fully loaded and ready
#if defined(DEMO_ENABLE_CACHE_EVICTION)
    EVICTED            // Was loaded, now evicted
#endif
  };

  struct Resource {
    Spectrogram spec;
    float* owned_data;     // nullptr if asset (not owned), allocated if procedural
    AssetId asset_id;      // ASSET_LAST_ID if procedural
    NoteParams proc_params;
    ResourceState state;

#if defined(DEMO_ENABLE_CACHE_EVICTION)
    float last_access_time;
#endif
  };

  // Load implementation
  void load_asset(Resource* resource);
  void load_procedural(Resource* resource);

  Resource resources_[MAX_SPECTROGRAM_RESOURCES];
  int loaded_count_ = 0;
};