summaryrefslogtreecommitdiff
path: root/src/test_demo.cc
blob: 4ec8d70152c644d711aa28aca928f0a67e9a00a6 (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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
// Minimal audio/visual synchronization test tool
// Plays simple drum beat with synchronized screen flashes

#include "audio/audio.h"
#include "audio/audio_engine.h"
#include "audio/synth.h"
#include "generated/assets.h" // Note: uses main demo asset bundle
#include "gpu/demo_effects.h"
#include "gpu/gpu.h"
#include "platform/platform.h"
#include "util/check_return.h"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>

// External declarations from generated files
extern float GetDemoDuration();
extern void LoadTimeline(MainSequence& main_seq, const GpuContext& ctx);

// Inline peak meter effect for debugging audio-visual sync
#include "gpu/effects/post_process_helper.h"
class PeakMeterEffect : public PostProcessEffect {
 public:
  PeakMeterEffect(const GpuContext& ctx) : PostProcessEffect(ctx) {
    // Use standard post-process binding macros
    const char* shader_code = R"(
      struct VertexOutput {
        @builtin(position) position: vec4<f32>,
        @location(0) uv: vec2<f32>,
      };

      struct Uniforms {
        peak_value: f32,
        _pad0: f32,
        _pad1: f32,
        _pad2: f32,
      };

      @group(0) @binding(0) var inputSampler: sampler;
      @group(0) @binding(1) var inputTexture: texture_2d<f32>;
      @group(0) @binding(2) var<uniform> uniforms: Uniforms;

      @vertex
      fn vs_main(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {
        var output: VertexOutput;
        // Full-screen triangle (required for post-process pass-through)
        var pos = array<vec2<f32>, 3>(
          vec2<f32>(-1.0, -1.0),
          vec2<f32>(3.0, -1.0),
          vec2<f32>(-1.0, 3.0)
        );
        output.position = vec4<f32>(pos[vertexIndex], 0.0, 1.0);
        output.uv = pos[vertexIndex] * 0.5 + 0.5;
        return output;
      }

      @fragment
      fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
        // Bar dimensions
        let bar_y_min = 0.005;
        let bar_y_max = 0.015;
        let bar_x_min = 0.015;
        let bar_x_max = 0.250;
        let in_bar_y = input.uv.y >= bar_y_min && input.uv.y <= bar_y_max;
        let in_bar_x = input.uv.x >= bar_x_min && input.uv.x <= bar_x_max;

        // Optimization: Return bar color early (avoids texture sampling for ~5% of pixels)
        if (in_bar_y && in_bar_x) {
          let uv_x = (input.uv.x - bar_x_min) / (bar_x_max - bar_x_min);
          let factor = step(uv_x, uniforms.peak_value);
          return mix(vec4<f32>(0.0, 0.0, 0.0, 1.0), vec4<f32>(1.0, 0.0, 0.0,1.0), factor);
        }

        // Pass through input texture for rest of screen
        return textureSample(inputTexture, inputSampler, input.uv);
      }
    )";

    pipeline_ =
        create_post_process_pipeline(ctx_.device, ctx_.format, shader_code);
    uniforms_ = gpu_create_buffer(
        ctx_.device, 16, WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst);
  }

  void update_bind_group(WGPUTextureView input_view) {
    pp_update_bind_group(ctx_.device, pipeline_, &bind_group_, input_view,
                         uniforms_);
  }

  void render(WGPURenderPassEncoder pass, float time, float beat,
              float peak_value, float aspect_ratio) {
    (void)time;
    (void)beat;
    (void)aspect_ratio;

    float uniforms[4] = {peak_value, 0.0f, 0.0f, 0.0f};
    wgpuQueueWriteBuffer(ctx_.queue, uniforms_.buffer, 0, uniforms,
                         sizeof(uniforms));

    wgpuRenderPassEncoderSetPipeline(pass, pipeline_);
    wgpuRenderPassEncoderSetBindGroup(pass, 0, bind_group_, 0, nullptr);
    wgpuRenderPassEncoderDraw(pass, 3, 1, 0, 0); // Full-screen triangle
  }
};

#if !defined(STRIP_ALL)
static void print_usage(const char* prog_name) {
  printf("Usage: %s [OPTIONS]\n", prog_name);
  printf("\nMinimal audio/visual synchronization test tool.\n");
  printf("Plays a simple drum beat with synchronized screen flashes.\n");
  printf("\nOptions:\n");
  printf("  --help              Show this help message and exit\n");
  printf("  --fullscreen        Run in fullscreen mode\n");
  printf("  --resolution WxH    Set window resolution (e.g., 1024x768)\n");
  printf("  --tempo             Enable tempo variation test mode\n");
  printf(
      "                      (alternates between acceleration and "
      "deceleration)\n");
  printf(
      "  --log-peaks FILE    Log audio peaks at each beat (32 samples for "
      "16s)\n");
  printf(
      "  --log-peaks-fine    Log at each frame for fine analysis (~960 "
      "samples)\n");
  printf(
      "                      (use with --log-peaks for millisecond "
      "resolution)\n");
  printf("\nExamples:\n");
  printf("  %s --fullscreen\n", prog_name);
  printf("  %s --resolution 1024x768 --tempo\n", prog_name);
  printf("  %s --log-peaks peaks.txt\n", prog_name);
  printf("  %s --log-peaks peaks.txt --log-peaks-fine\n", prog_name);
  printf("\nControls:\n");
  printf("  ESC                 Exit the demo\n");
  printf("  F                   Toggle fullscreen\n");
}
#endif

int main(int argc, char** argv) {
  // Parse command-line
  PlatformState platform_state;
  bool fullscreen_enabled = false;
  bool tempo_test_enabled = false;
  int width = 1280;
  int height = 720;
  const char* log_peaks_file = nullptr;
  bool log_peaks_fine = false;
  // Seek time needs to be declared here to be accessible globally for the loop.
  float seek_time = 0.0f;

#if !defined(STRIP_ALL)
  // Early exit for invalid options
  for (int i = 1; i < argc; ++i) {
    if (strcmp(argv[i], "--help") == 0) {
      print_usage(argv[0]);
      return 0;
    } else if (strcmp(argv[i], "--fullscreen") == 0) {
      fullscreen_enabled = true;
    } else if (strcmp(argv[i], "--tempo") == 0) {
      tempo_test_enabled = true;
    } else if (strcmp(argv[i], "--resolution") == 0) {
      if (i + 1 < argc) {
        const char* res_str = argv[++i];
        int w, h;
        if (sscanf(res_str, "%dx%d", &w, &h) == 2) {
          width = w;
          height = h;
        } else {
          fprintf(stderr,
                  "Error: Invalid resolution format '%s' (expected WxH, e.g., "
                  "1024x768)\n\n",
                  res_str);
          print_usage(argv[0]);
          return 1;
        }
      } else {
        fprintf(
            stderr,
            "Error: --resolution requires an argument (e.g., 1024x768)\n\n");
        print_usage(argv[0]);
        return 1;
      }
    } else if (strcmp(argv[i], "--log-peaks") == 0) {
      CHECK_RETURN_BEGIN(i + 1 >= argc, 1)
      print_usage(argv[0]);
      ERROR_MSG("--log-peaks requires a filename argument\n");
      return 1;
      CHECK_RETURN_END
      log_peaks_file = argv[++i];
    } else if (strcmp(argv[i], "--log-peaks-fine") == 0) {
      log_peaks_fine = true;
    } else {
      CHECK_RETURN_BEGIN(true, 1)
      print_usage(argv[0]);
      ERROR_MSG("Unknown option '%s'\n", argv[i]);
      return 1;
      CHECK_RETURN_END
    }
  }
#else
  (void)argc;
  (void)argv;
  fullscreen_enabled = true;
#endif

  // Initialize platform, GPU, audio
  platform_state = platform_init(fullscreen_enabled, width, height);
  gpu_init(&platform_state);

  // Add peak meter visualization effect (renders as final post-process)
#if !defined(STRIP_ALL)
  const GpuContext* gpu_ctx = gpu_get_context();
  auto* peak_meter = new PeakMeterEffect(*gpu_ctx);
  gpu_add_custom_effect(peak_meter, 0.0f, 99999.0f,
                        999); // High priority = renders last
#endif

  audio_init();

  static AudioEngine g_audio_engine;
  g_audio_engine.init();

  // Music time tracking with optional tempo variation
  static float g_music_time = 0.0f;
  static float g_last_audio_time = 0.0f;
  static float g_tempo_scale = 1.0f;

  auto fill_audio_buffer = [&](float audio_dt, double physical_time) {
    // Calculate tempo scale if --tempo flag enabled
    if (tempo_test_enabled) {
      const float t = (float)physical_time;
      if (t >= 2.0f && t < 4.0f) {
        // [2s->4s]: Accelerate from 1.0x to 1.5x
        const float progress = (t - 2.0f) / 2.0f;
        g_tempo_scale = 1.0f + (0.5f * progress);
      } else if (t >= 6.0f && t < 8.0f) {
        // [6s->8s]: Decelerate from 1.0x to 0.66x
        const float progress = (t - 6.0f) / 2.0f;
        g_tempo_scale = 1.0f - (0.34f * progress);
      } else {
        // All other times: Normal tempo
        g_tempo_scale = 1.0f;
      }
    } else {
      g_tempo_scale = 1.0f; // No tempo variation
    }

    g_music_time += audio_dt * g_tempo_scale;

    g_audio_engine.update(g_music_time, audio_dt * g_tempo_scale);
    audio_render_ahead(g_music_time, audio_dt * g_tempo_scale);
  };

  // Pre-fill audio buffer
  g_audio_engine.update(g_music_time, 1.0f / 60.0f);
  audio_render_ahead(g_music_time, 1.0f / 60.0f);
  audio_start();
  g_last_audio_time = audio_get_playback_time();

  int last_width = platform_state.width;
  int last_height = platform_state.height;
  const float demo_duration = GetDemoDuration();

#if !defined(STRIP_ALL)
  // Open peak log file if requested
  FILE* peak_log = nullptr;
  if (log_peaks_file) {
    peak_log = fopen(log_peaks_file, "w");
    if (peak_log) {
      fprintf(peak_log, "// Audio peak log from test_demo\n");
      fprintf(peak_log, "// Mode: %s\n",
              log_peaks_fine ? "fine (per-frame)" : "beat-aligned");
      fprintf(peak_log, "// To plot with gnuplot:\n");
      fprintf(peak_log,
              "//   gnuplot -p -e \"set xlabel 'Time (s)'; set ylabel 'Peak'; "
              "plot '%s' using 2:3 with lines title 'Raw Peak'\"\n",
              log_peaks_file);
      if (log_peaks_fine) {
        fprintf(peak_log,
                "// Columns: frame_number clock_time raw_peak beat_number\n");
      } else {
        fprintf(peak_log, "// Columns: beat_number clock_time raw_peak\n");
      }
      fprintf(peak_log, "//\n");
    } else {
      fprintf(stderr, "Warning: Could not open log file '%s'\n",
              log_peaks_file);
    }
  }
  int last_beat_logged = -1;
  int frame_number = 0;
#endif

  // Main loop
  while (!platform_should_close(&platform_state)) {
    platform_poll(&platform_state);

    // Handle resize
    if (platform_state.width != last_width ||
        platform_state.height != last_height) {
      last_width = platform_state.width;
      last_height = platform_state.height;
      gpu_resize(last_width, last_height);
    }

    // Graphics frame time - derived from platform's clock
    const double current_physical_time = platform_state.time + seek_time;
    // Audio playback time - master clock for audio events
    const float current_audio_time = audio_get_playback_time();
    // Delta time for audio processing, based on audio clock
    const float audio_dt = current_audio_time - g_last_audio_time;
    g_last_audio_time = current_audio_time;

    // Auto-exit at end (based on physical time for graphics loop consistency)
    if (demo_duration > 0.0f && current_physical_time >= demo_duration) {
#if !defined(STRIP_ALL)
      printf("test_demo finished at %.2f seconds. Exiting...\n",
             current_physical_time);
#endif
      break;
    }

    // This fill_audio_buffer call is crucial for audio system to process
    // events based on the *current audio time* and *graphics physical time*
    // context
    fill_audio_buffer(audio_dt, current_physical_time);

    // --- Graphics Update ---
    const float aspect_ratio = platform_state.aspect_ratio;

    // Peak value derived from audio, but used for visual effect intensity
    const float raw_peak = audio_get_realtime_peak();
    const float visual_peak = fminf(raw_peak * 8.0f, 1.0f);

    // Beat calculation should use audio time to align with audio events.
    // The graphics loop time (current_physical_time) is used for frame rate.
    const float beat_time = current_audio_time * 120.0f / 60.0f;
    const int beat_number = (int)beat_time;
    const float beat = fmodf(beat_time, 1.0f); // Fractional part (0.0 to 1.0)

#if !defined(STRIP_ALL)
    // Log peak (either per-frame or per-beat)
    if (peak_log) {
      if (log_peaks_fine) {
        // Log every frame for fine-grained analysis
        // Use platform_get_time() for high-resolution timestamps (not
        // audio_time which advances in chunks)
        const double frame_time = platform_get_time();
        fprintf(peak_log, "%d %.6f %.6f %d\n", frame_number, frame_time,
                raw_peak, beat_number);
      } else if (beat_number != last_beat_logged) {
        // Log only at beat boundaries
        fprintf(peak_log, "%d %.6f %.6f\n", beat_number, current_audio_time,
                raw_peak);
        last_beat_logged = beat_number;
      }
    }
    frame_number++;

    // Debug output every 0.5 seconds (based on graphics time for consistency)
    static float last_graphics_print_time = -1.0f;
    if (current_physical_time - last_graphics_print_time >= 0.5f) {
      if (tempo_test_enabled) {
        printf(
            "[GraphicsT=%.2f, AudioT=%.2f, MusicT=%.2f, Beat=%d, Frac=%.2f, "
            "Peak=%.2f, Tempo=%.2fx]\n",
            current_physical_time, current_audio_time, g_music_time,
            beat_number, beat, visual_peak, g_tempo_scale);
      } else {
        printf("[GraphicsT=%.2f, AudioT=%.2f, Beat=%d, Frac=%.2f, Peak=%.2f]\n",
               current_physical_time, current_audio_time, beat_number, beat,
               visual_peak);
      }
      last_graphics_print_time = current_physical_time;
    }
#endif

    // Draw graphics using the graphics frame time and synchronized audio events
    const float graphics_frame_time = (float)current_physical_time;
    gpu_draw(visual_peak, aspect_ratio, graphics_frame_time, beat);

    // Update audio systems (tracker, synth, etc.) based on audio time
    // progression
    audio_update();
  }

  // Shutdown
#if !defined(STRIP_ALL)
  if (peak_log) {
    fclose(peak_log);
    printf("Peak log written to '%s'\n", log_peaks_file);
  }
#endif
  audio_shutdown();
  gpu_shutdown();
  platform_shutdown(&platform_state);
  return 0;
}