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
|
#include "tracker.h"
#include "audio.h"
#include "audio/spectrogram_resource_manager.h"
#include "audio/synth.h"
#include "ring_buffer.h"
#include "util/asset_manager.h"
#include "util/debug.h"
#include "util/fatal_error.h"
#include <cstring>
#include <random>
static uint32_t g_last_trigger_idx = 0;
// Active pattern instance tracking
struct ActivePattern {
uint16_t pattern_id;
double start_music_time; // When this pattern was triggered (music time)
uint32_t next_event_idx; // Next event to trigger within this pattern
bool active;
};
static ActivePattern g_active_patterns[MAX_SPECTROGRAMS];
// CACHE: Pre-registered synth_ids for all samples (indexed by sample_id)
static int g_sample_synth_cache[MAX_SPECTROGRAM_RESOURCES];
static int get_free_pattern_slot() {
for (int i = 0; i < MAX_SPECTROGRAMS; ++i) {
if (!g_active_patterns[i].active)
return i;
}
return -1; // No free slots
}
void tracker_init(SpectrogramResourceManager* resource_mgr) {
g_last_trigger_idx = 0;
for (int i = 0; i < MAX_SPECTROGRAMS; ++i) {
g_active_patterns[i].active = false;
}
for (int i = 0; i < MAX_SPECTROGRAM_RESOURCES; ++i) {
g_sample_synth_cache[i] = -1;
}
// Pre-register all unique samples (assets + generated notes)
for (uint32_t sid = 0; sid < g_tracker_samples_count; ++sid) {
AssetId aid = g_tracker_sample_assets[sid];
if (resource_mgr) {
// Unified path: register metadata, load eagerly, register with synth
if (aid != AssetId::ASSET_LAST_ID) {
resource_mgr->register_asset(sid, aid);
} else {
resource_mgr->register_procedural(sid, g_tracker_samples[sid]);
}
const Spectrogram* spec = resource_mgr->get_or_load(sid);
if (spec) {
g_sample_synth_cache[sid] = synth_register_spectrogram(spec);
}
} else {
// Legacy path (no resource manager — standalone tests)
if (aid != AssetId::ASSET_LAST_ID) {
size_t size;
const uint8_t* data = GetAsset(aid, &size);
#if !defined(STRIP_ALL)
if (data && size > 0 && GetAssetType(aid) == AssetType::MP3) {
continue; // MP3 requires resource manager
}
#else
if (data != nullptr && GetAssetType(aid) == AssetType::MP3) {
continue;
}
#endif
if (data && size >= sizeof(SpecHeader)) {
const SpecHeader* header = (const SpecHeader*)data;
Spectrogram spec;
spec.spectral_data_a = (const float*)(data + sizeof(SpecHeader));
spec.spectral_data_b = spec.spectral_data_a;
spec.num_frames = header->num_frames;
spec.version = header->version;
g_sample_synth_cache[sid] = synth_register_spectrogram(&spec);
}
}
// Note: procedural notes without resource_mgr are not supported
// (requires std::vector allocation — use resource_mgr path)
}
}
#if defined(DEBUG_LOG_TRACKER)
DEBUG_TRACKER("[TRACKER INIT] Cached %d unique samples\n",
g_tracker_samples_count);
#endif
// Validate that all pattern events are sorted by unit_time
// (required for early-exit optimization in tracker_update)
FATAL_CODE_BEGIN
for (uint32_t pid = 0; pid < g_tracker_patterns_count; ++pid) {
const TrackerPattern& pattern = g_tracker_patterns[pid];
for (uint32_t i = 1; i < pattern.num_events; ++i) {
FATAL_CHECK(pattern.events[i].unit_time >=
pattern.events[i - 1].unit_time,
"Pattern %d has unsorted events: event[%d].time=%.3f < "
"event[%d].time=%.3f\n",
pid, i, pattern.events[i].unit_time, i - 1,
pattern.events[i - 1].unit_time);
}
}
FATAL_CODE_END
}
void tracker_reset() {
g_last_trigger_idx = 0;
for (int i = 0; i < MAX_SPECTROGRAMS; ++i) {
g_active_patterns[i].active = false;
}
}
// Helper to trigger a single note event (OPTIMIZED with caching)
// start_offset_samples: How many samples into the future to trigger (for
// sample-accurate timing)
// volume_mult: Additional volume multiplier (for humanization)
static void trigger_note_event(const TrackerEvent& event,
int start_offset_samples,
float volume_mult = 1.0f) {
#if defined(DEBUG_LOG_TRACKER)
// VALIDATION: Check sample_id bounds
if (event.sample_id >= g_tracker_samples_count) {
DEBUG_TRACKER("[TRACKER ERROR] Invalid sample_id=%d (max=%d)\n",
event.sample_id, g_tracker_samples_count - 1);
return;
}
// VALIDATION: Check volume and pan ranges
if (event.volume < 0.0f || event.volume > 2.0f) {
DEBUG_TRACKER("[TRACKER WARNING] Unusual volume=%.2f for sample_id=%d\n",
event.volume, event.sample_id);
}
if (event.pan < -1.0f || event.pan > 1.0f) {
DEBUG_TRACKER("[TRACKER WARNING] Invalid pan=%.2f for sample_id=%d\n",
event.pan, event.sample_id);
}
#endif /* defined(DEBUG_LOG_TRACKER) */
// OPTIMIZED: Use cached synth_id instead of regenerating spectrogram
const int cached_synth_id = g_sample_synth_cache[event.sample_id];
#if defined(DEBUG_LOG_TRACKER)
if (cached_synth_id == -1) {
DEBUG_TRACKER(
"[TRACKER ERROR] No cached synth_id for sample_id=%d (init failed?)\n",
event.sample_id);
return;
}
#endif /* defined(DEBUG_LOG_TRACKER) */
if (cached_synth_id == -1) {
return;
}
// Trigger voice with sample-accurate offset
synth_trigger_voice(cached_synth_id, event.volume * volume_mult, event.pan,
start_offset_samples);
}
void tracker_update(double music_time_sec, double dt_music_sec) {
// Unit-less timing: 1 unit = 4 beats (by convention)
const double BEATS_PER_UNIT = 4.0;
const double unit_duration_sec =
(BEATS_PER_UNIT / (double)g_tracker_score.bpm) * 60.0;
const double end_music_time = music_time_sec + dt_music_sec;
const double tempo_scale = (double)synth_get_tempo_scale();
// Step 1: Process new pattern triggers
while (g_last_trigger_idx < g_tracker_score.num_triggers) {
const TrackerPatternTrigger& trigger =
g_tracker_score.triggers[g_last_trigger_idx];
const double trigger_time_sec = (double)trigger.unit_time * unit_duration_sec;
if (trigger_time_sec > end_music_time)
break;
// Add this pattern to active patterns list
const int slot = get_free_pattern_slot();
if (slot != -1) {
g_active_patterns[slot].pattern_id = trigger.pattern_id;
g_active_patterns[slot].start_music_time = trigger_time_sec;
g_active_patterns[slot].next_event_idx = 0;
g_active_patterns[slot].active = true;
}
g_last_trigger_idx++;
}
// Step 2: Update all active patterns and trigger individual events
// Sample-accurate timing: Calculate offset relative to music_time_sec
for (int i = 0; i < MAX_SPECTROGRAMS; ++i) {
if (!g_active_patterns[i].active)
continue;
ActivePattern& active = g_active_patterns[i];
const TrackerPattern& pattern = g_tracker_patterns[active.pattern_id];
// Trigger all events that have passed their unit time
while (active.next_event_idx < pattern.num_events) {
const TrackerEvent& event = pattern.events[active.next_event_idx];
const double event_music_time =
active.start_music_time + (double)event.unit_time * unit_duration_sec;
if (event_music_time > end_music_time)
break; // This event hasn't reached its time yet
// Sample-accurate timing:
// Offset = (music_time_delta / tempo_scale) * sample_rate
int sample_offset = 0;
if (event_music_time > music_time_sec) {
sample_offset = (int)((event_music_time - music_time_sec) / tempo_scale *
(double)RING_BUFFER_SAMPLE_RATE);
}
// Apply humanization if enabled
float volume_mult = 1.0f;
if (g_tracker_score.humanize_seed != 0) {
// Deterministic per-event RNG: hash seed with pattern/event indices
uint32_t event_hash = g_tracker_score.humanize_seed ^
(active.pattern_id << 16) ^ active.next_event_idx;
std::minstd_rand rng(event_hash);
std::uniform_real_distribution<double> dist(-1.0, 1.0);
// Timing variation: jitter by % of beat duration
if (g_tracker_score.timing_variation_pct > 0.0f) {
double beat_sec = 60.0 / (double)g_tracker_score.bpm;
double jitter = dist(rng) *
(double)(g_tracker_score.timing_variation_pct / 100.0f) *
beat_sec;
sample_offset +=
(int)(jitter / tempo_scale * (double)RING_BUFFER_SAMPLE_RATE);
}
// Volume variation: vary by %
if (g_tracker_score.volume_variation_pct > 0.0f) {
volume_mult +=
(float)(dist(rng) * (double)(g_tracker_score.volume_variation_pct / 100.0f));
}
}
trigger_note_event(event, sample_offset, volume_mult);
active.next_event_idx++;
}
// Pattern remains active until full duration elapses
const double pattern_end_time =
active.start_music_time + (double)pattern.unit_length * unit_duration_sec;
if (pattern_end_time <= end_music_time) {
active.active = false;
}
}
}
|