forked from projectM-visualizer/projectm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprojectM_emscripten.cpp
More file actions
637 lines (575 loc) · 19.6 KB
/
Copy pathprojectM_emscripten.cpp
File metadata and controls
637 lines (575 loc) · 19.6 KB
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
// projectM_emscripten.cpp (ProjectMWasmMain)
//
// Init orchestration and AppData ownership for the projectM Emscripten/WASM
// host. Owns the process-global engine state, the transpiled-GLSL shader cache
// hooks, the render loop, and the engine-lifecycle / render C exports.
//
// The rest of the host glue lives in the focused WASM TUs:
// WasmWebGLContext.cpp WebGL context create/destroy + extensions + canvas selectors
// WasmGraphics.hpp dual-FBO classes + compositing shader
// WasmDualFbo.cpp dual_fbo_* / transition_* exports
// WasmAudioBridge.cpp audio worklet + stream analyser + PCM feed
// WasmPerfGovernor.cpp perf HUD + adaptive quality governor + OpenMP info
// WasmPlaylistBridge.cpp preset callbacks + playlist path helpers
// WasmJsBindings.cpp EM_JS DOM/VFS bootstrap + host-page notifications
//
// See docs/EMSCRIPTEN.md ("Where to add a WASM export").
#include "ProjectMWasmInternal.hpp"
#include "WasmGraphics.hpp"
#include "WasmWebGLContext.hpp"
#include <cstdlib>
using namespace emscripten;
// ---- Core engine state (declared extern in ProjectMWasmInternal.hpp) -------
projectm_handle pm;
AppData app_data;
projectm_playlist_handle playlist = {};
// ---- Async preset loading / transition gating (declared extern in header) --
bool g_presetBReady = false;
uint32_t g_renderedFrameCount = 0;
uint32_t g_presetReadyFrame = 0;
bool g_presetSwitchFailed = false;
// kWasmPthreadPoolSize comes from cmake/generated/ProjectMWasmBuildConfig.hpp
// (generated from PROJECTM_WASM_PTHREAD_POOL_SIZE in EmscriptenWasmFlags.cmake).
static void ConfigureWasmOpenMPThreadCount()
{
#ifdef _OPENMP
omp_set_dynamic(0);
omp_set_num_threads(kWasmPthreadPoolSize);
#endif
}
static void TearDownEngineForRebind()
{
// Cancel the Emscripten main loop if one is running so rebind can restart it
// via start_render() after a fresh init().
emscripten_cancel_main_loop();
if (playlist)
{
projectm_playlist_destroy(playlist);
playlist = nullptr;
}
if (pm)
{
projectm_destroy(pm);
pm = nullptr;
}
app_data.projectm_engine = nullptr;
app_data.playlist = nullptr;
app_data.loading = EM_FALSE;
g_dualFbo.ReleaseAll();
WasmWebGLDestroyContext();
}
// =============================================================================
// Transpiled GLSL cache (browser IndexedDB via JS hooks)
// =============================================================================
static std::string g_shaderCacheKey;
static std::optional<std::string> g_importedWarpGlsl;
static std::optional<std::string> g_importedCompGlsl;
EM_JS(void, js_on_transpiled_shader_stored, (const char* key, int kind, const char* glsl), {
if (typeof window.pmOnTranspiledShaderStored === 'function')
{
window.pmOnTranspiledShaderStored(UTF8ToString(key), kind, UTF8ToString(glsl));
}
});
EM_JS(int, js_dual_fbo_prefer_high_precision, (), {
if (typeof window === 'undefined' || !window.location || !window.location.search)
{
return 0;
}
try
{
const value = new URLSearchParams(window.location.search).get('fboPrecision');
return (value && value.toLowerCase() === 'high') ? 1 : 0;
}
catch (e)
{
return 0;
}
});
EM_JS(int, js_blur_force_copy_path, (), {
if (typeof window === 'undefined' || !window.location || !window.location.search)
{
return 0;
}
try
{
const value = new URLSearchParams(window.location.search).get('blurPath');
return (value && value.toLowerCase() === 'copy') ? 1 : 0;
}
catch (e)
{
return 0;
}
});
// Ablation switch for benchmarking the blur chain: ?blurPath=copy restores the legacy
// render-to-scratch + glCopyTexSubImage2D behaviour so it can be A/B'd against the
// default render-to-texture path on one build. See docs/GRAPHICS_PERF_RECOVERY_PLAN.md.
static void ApplyBlurPathOverride()
{
if (js_blur_force_copy_path() != 0)
{
setenv("PROJECTM_BLUR_COPY_PATH", "1", 1);
}
}
static void InstallShaderTranspileCacheHooks()
{
libprojectM::Renderer::SetTranspiledGlslCacheCallbacks(
[](const std::string& key, int shaderType) -> std::optional<std::string> {
if (key != g_shaderCacheKey)
{
return std::nullopt;
}
if (shaderType == 0 && g_importedWarpGlsl)
{
return g_importedWarpGlsl;
}
if (shaderType == 1 && g_importedCompGlsl)
{
return g_importedCompGlsl;
}
return std::nullopt;
},
[](const std::string& key, int shaderType, const std::string& glsl) {
js_on_transpiled_shader_stored(key.c_str(), shaderType, glsl.c_str());
});
}
extern "C" {
EMSCRIPTEN_KEEPALIVE
void shader_cache_begin_load(const char* key)
{
g_shaderCacheKey = key ? key : "";
g_importedWarpGlsl.reset();
g_importedCompGlsl.reset();
libprojectM::Renderer::SetTranspiledGlslCacheKey(g_shaderCacheKey);
}
EMSCRIPTEN_KEEPALIVE
void shader_cache_import_glsl(int shaderType, const char* glsl)
{
if (!glsl)
{
return;
}
if (shaderType == 0)
{
g_importedWarpGlsl = glsl;
}
else if (shaderType == 1)
{
g_importedCompGlsl = glsl;
}
}
EMSCRIPTEN_KEEPALIVE
void shader_cache_end_load()
{
libprojectM::Renderer::ClearTranspiledGlslCacheKey();
g_shaderCacheKey.clear();
g_importedWarpGlsl.reset();
g_importedCompGlsl.reset();
}
EMSCRIPTEN_KEEPALIVE
int get_glsl_generator_version()
{
return static_cast<int>(
libprojectM::MilkdropPreset::MilkdropStaticShaders::Get()->GetGlslGeneratorVersion());
}
} // extern "C"
extern "C" {
EMSCRIPTEN_KEEPALIVE
void create_sprite()
{
const char* new_sprite_code =
"[preset01]"
"img='textures/rv_IP_20250421_060250.png';"
"per_frame_1=blendmode=1;"
"per_frame_2=x = 0.5;" // Center X
"per_frame_3=y = 0.5;" // Center Y
"per_frame_4=z = 0.0;" // Center Y
"per_frame_5=scaling = 1.0;" // Make it huge (twice the screen height)
"per_pixel_2=a = 1;" // Fully opaque
"per_pixel_3=r = 1.0;" // Bright Red
"per_pixel_4=g = 0.0;"
"per_pixel_5=b = 1.0;";
projectm_sprite_create(app_data.projectm_engine, "milkdrop", new_sprite_code);
return;
}
EMSCRIPTEN_KEEPALIVE
uintptr_t get_projectm_handle()
{
return reinterpret_cast<uintptr_t>(app_data.projectm_engine);
}
} // extern "C"
// Forward declaration: render_frame() is defined later in this file (Phase 5
// dual-FBO compositor pipeline), but renderLoop() — registered as the
// Emscripten main loop by start_render() — must call it every frame.
extern "C" void render_frame();
void renderLoop()
{
if (app_data.loading == EM_TRUE)
{
g_wasLoading = true;
return;
}
if (g_wasLoading)
{
g_wasLoading = false;
g_postLoadGraceFrames = kPostLoadGraceFrames;
ResetGovernorCounters();
}
const double frameStartMs = emscripten_get_now();
if (g_is_streaming_audio)
{
js_feed_stream_data_to_projectm(
reinterpret_cast<uintptr_t>(app_data.projectm_engine),
2048 // This MUST match the analyser.fftSize
);
}
// Phase 5: Route through render_frame(). Steady-state frames render directly
// to the canvas; the dual-FBO compositor runs only during preset crossfades.
if (g_perfHudEnabled)
{
js_perf_gpu_begin_frame();
}
render_frame();
if (g_perfHudEnabled)
{
js_perf_gpu_end_frame();
}
// The compositor (and the legacy fallback) both leave the composited frame
// in the default framebuffer (FBO 0). The browser presents the canvas directly;
// no eglSwapBuffers() is required on wasm.
if (g_perfHudEnabled)
{
projectm_perf_frame_timings timings;
projectm_perf_get_frame_timings(&timings);
js_perf_report_frame(
timings.total_ms, timings.audio_analysis_ms, timings.per_frame_eval_ms,
timings.per_pixel_eval_ms, timings.blur_ms, timings.waveforms_shapes_ms,
timings.composite_ms, js_perf_gpu_get_last_ms(), timings.fps);
}
UpdateQualityGovernor(emscripten_get_now() - frameStartMs);
return;
}
extern "C" {
EMSCRIPTEN_KEEPALIVE
void start_render(int width, int height)
{
// glClearColor( 1.0, 1.0, 1.0, 0.0 );
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
printf("Setting window size: %i x %i\n", width, height);
glViewport(0, 0, 8192, 8192); // viewport/scissor after UsePrg runs at full resolution
glViewport(0, 0, width, height); // viewport/scissor after UsePrg runs at full resolution
glEnable(GL_SCISSOR_TEST);
glScissor(0, 0, width, height);
glHint(GL_FRAGMENT_SHADER_DERIVATIVE_HINT, GL_NICEST);
glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
// GL_DITHER only affects fixed-function/blit paths on most GLES drivers and
// is a no-op for the shader-based render passes used here, but in the
// degraded RGBA8 dual-FBO fallback (DetectFormat() already ran in init())
// every bit of extra entropy on the final blit helps hide 8-bit banding, so
// leave it enabled in that case instead of unconditionally disabling it.
if (g_dualFbo.GetFormat() == FboFloatFormat::RGBA8)
{
glEnable(GL_DITHER);
}
else
{
glDisable(GL_DITHER);
}
glFrontFace(GL_CW);
glCullFace(GL_BACK);
app_data.loading = EM_FALSE;
projectm_set_window_size(pm, width, height);
// Phase 2: Persist dual-FBO dimensions now that the viewport is known.
// Preset A/B textures are lazily allocated on first transition request.
g_dualFbo.Resize(width, height);
// Phase 5: Compile and link the compositing blend shader now that the GL
// context is current.
if (!g_compositorShader.Init())
{
fprintf(stderr, "start_render: CompositingBlendShader failed to initialise – transitions will be unavailable.\n");
}
emscripten_set_main_loop((void (*)()) renderLoop, 0, 0);
emscripten_set_main_loop_timing(2, 1);
return;
}
} // extern "C"
extern "C" {
EMSCRIPTEN_KEEPALIVE int init();
EMSCRIPTEN_KEEPALIVE
void set_canvas_selectors(const char* primary, const char* secondary)
{
WasmWebGLSetCanvasSelectors(primary, secondary);
}
EMSCRIPTEN_KEEPALIVE
int init_with_canvases(const char* primary, const char* secondary)
{
set_canvas_selectors(primary, secondary);
return init();
}
EMSCRIPTEN_KEEPALIVE
int rebind_canvases(const char* primary, const char* secondary)
{
// Single-instance rebind: tear down the active engine/GL context and re-init
// against new canvas selectors. Does not support two simultaneous engines in
// one Module (INITIAL_MEMORY ≈ 1 GiB per Module instance).
set_canvas_selectors(primary, secondary);
if (pm || WasmWebGLGetContext())
{
TearDownEngineForRebind();
}
return init();
}
EMSCRIPTEN_KEEPALIVE
int init()
{
if (pm)
{
js_report_init_success();
return 0;
}
ConfigureWasmOpenMPThreadCount();
WasmWebGLApplyModuleCanvasSelectorsIfPresent();
js_init_projectm_dom();
if (!WasmWebGLCreateAndActivateContext())
{
return 2;
}
// Phase 2: Detect the best available floating-point texture format for the
// dual ping-pong FBO system. Default is RGBA16F -> RGBA32F -> RGBA8.
// Hosts can opt into RGBA32F-first probing with ?fboPrecision=high.
// This must be called after the WebGL context is made current so that
// extension availability can be probed reliably.
g_dualFbo.DetectFormat(WasmWebGLGetContext(), js_dual_fbo_prefer_high_precision() != 0);
// Must happen before the first preset renders, since the blur path is decided once.
ApplyBlurPathOverride();
pm = projectm_create();
if (!pm)
{
fprintf(stderr, "Failed to create projectM handle\n");
js_report_init_error(3, "projectm_create() returned null");
return 3;
}
app_data.projectm_engine = pm;
playlist = projectm_playlist_create(pm);
app_data.playlist = playlist;
const char* loc = "/presets/";
projectm_playlist_add_path(playlist, loc, true, true);
projectm_playlist_set_preset_switched_event_callback(playlist, &load_preset_callback_done, &app_data);
const char* texture_search_paths[] = {"textures"};
projectm_set_texture_search_paths(pm, texture_search_paths, 1);
projectm_set_fps(pm, 60);
projectm_set_preset_duration(pm, 30.0);
projectm_set_soft_cut_duration(pm, 17.0);
// projectm_set_hard_cut_duration(pm, 48.0);
// projectm_set_hard_cut_enabled(pm, true);
projectm_set_beat_sensitivity(pm, 1.50);
projectm_playlist_set_shuffle(playlist, true);
projectm_set_preset_switch_failed_event_callback(pm, &_on_preset_switch_failed, nullptr);
projectm_set_preset_switch_requested_event_callback(pm, &on_preset_switch_requested, &app_data);
InstallShaderTranspileCacheHooks();
// projectm_playlist_connect(app_data.playlist,app_data.projectm_engine);
printf(" --== projectM initialized! ==--\n");
js_initialize_worklet_system_once(reinterpret_cast<uintptr_t>(app_data.projectm_engine));
js_initialize_stream_analyser();
js_report_init_success();
return 0;
}
} // extern "C"
extern "C" {
EMSCRIPTEN_KEEPALIVE
void set_mesh(int w, int h)
{
projectm_set_mesh_size(pm, w, h);
return;
}
EMSCRIPTEN_KEEPALIVE
void destruct()
{
if (pm)
{
projectm_destroy(pm);
}
pm = NULL;
// Phase 2: Release dual FBO resources before destroying the WebGL context
// to avoid calling OpenGL functions with an invalid context.
g_dualFbo.ReleaseAll();
WasmWebGLDestroyContext();
return;
}
// Called from the host page's "webglcontextlost" handler (see
// html/projectm-context-loss.js), before the browser's "webglcontextrestored"
// event fires. At this point the WebGL context is already gone, so every GL
// call below (inside projectm_destroy() and g_dualFbo.ReleaseAll()) is a
// no-op per the WebGL spec; they only exist to reset projectM's bookkeeping
// (pm, playlist, gl_ctx, dual-FBO allocation flags) so that a subsequent
// init() call takes the full re-initialization path instead of the
// "already initialized" early return.
EMSCRIPTEN_KEEPALIVE
void pm_handle_context_loss()
{
if (pm)
{
projectm_destroy(pm);
}
pm = NULL;
app_data.projectm_engine = NULL;
playlist = NULL;
app_data.playlist = NULL;
g_dualFbo.ReleaseAll();
WasmWebGLDestroyContext();
return;
}
EMSCRIPTEN_KEEPALIVE
void set_aspect_correction(bool enabled)
{
if (!pm)
return;
projectm_set_aspect_correction(pm, enabled);
return;
}
EMSCRIPTEN_KEEPALIVE
void set_preset_locked(bool locked)
{
if (!pm)
return;
projectm_set_preset_locked(pm, locked);
printf("Preset lock set to: %s\n", locked ? "true" : "false");
return;
}
EMSCRIPTEN_KEEPALIVE
void set_transparency_mode(bool enabled)
{
if (!pm)
return;
projectm_set_transparency_mode(pm, enabled);
return;
}
EMSCRIPTEN_KEEPALIVE
bool get_transparency_mode()
{
if (!pm)
return false;
return projectm_get_transparency_mode(pm);
}
EMSCRIPTEN_KEEPALIVE
void set_transparency_threshold(float threshold)
{
if (!pm)
return;
projectm_set_transparency_threshold(pm, threshold);
return;
}
EMSCRIPTEN_KEEPALIVE
float get_transparency_threshold()
{
if (!pm)
return 0.01f;
return projectm_get_transparency_threshold(pm);
}
// Returns true when the dual-FBO compositor path is required this frame.
// Steady-state playback renders directly to the canvas (one pass); the
// offscreen ping-pong FBO + fullscreen compositor blit is only used while a
// preset crossfade is active.
static bool ShouldUseDualFboCompositor()
{
return g_transitionActive &&
g_dualFbo.IsPresetAAllocated() &&
g_dualFbo.IsPresetBAllocated() &&
g_compositorShader.IsInitialized();
}
EMSCRIPTEN_KEEPALIVE
void render_frame()
{
if (!pm)
return;
// Phase 5: Integrated dual-FBO render pipeline (transitions only).
//
// When a crossfade is active, the render loop orchestrates:
//
// 1. Render Preset A → FBO_A_Write, ping-pong to FBO_A_Read.
// 2. Render Preset B → FBO_B_Write, ping-pong to FBO_B_Read.
// 3. Composite to screen: blend FBO_A_Read + FBO_B_Read using uBlend.
// 4. Advance blend timer; auto-complete when uBlend >= 1.0.
//
// Between transitions (the common case), render straight to the default
// framebuffer via projectm_opengl_render_frame() — the same path used before
// the dual-FBO work landed — avoiding an extra FBO resolve + fullscreen blit
// every frame.
if (!ShouldUseDualFboCompositor())
{
// Direct-to-canvas path (steady state, startup, or compositor unavailable).
GLStateGuard guard;
projectm_opengl_render_frame(pm);
g_renderedFrameCount++;
return;
}
const int w = g_dualFbo.Width();
const int h = g_dualFbo.Height();
const bool ditherOutput = (g_dualFbo.GetFormat() == FboFloatFormat::RGBA8);
const bool transparencyMode = projectm_get_transparency_mode(pm);
const float transparencyThreshold = projectm_get_transparency_threshold(pm);
// --- Step 1: Render Preset A into its Write FBO ---
// Note: projectm_opengl_render_frame() hardcodes its final composite blit to
// FBO 0 (the default framebuffer / canvas) regardless of which FBO is bound
// when called. Use projectm_opengl_render_frame_fbo() so the final composite
// lands in our Write FBO instead of clobbering the canvas directly.
{
GLStateGuard guard;
projectm_opengl_render_frame_fbo(pm, g_dualFbo.GetAWriteFBO());
}
g_dualFbo.SwapPresetA();
// --- Step 2: Render Preset B into its Write FBO ---
gl_reset_state_between_pipelines();
{
GLStateGuard guard;
projectm_opengl_render_frame_fbo(pm, g_dualFbo.GetBWriteFBO());
}
g_dualFbo.SwapPresetB();
// --- Step 3: Composite to the default framebuffer (browser canvas) ---
g_compositorShader.Draw(g_dualFbo.GetAReadTex(), g_dualFbo.GetBReadTex(),
g_transitionBlend, w, h, ditherOutput,
transparencyMode, transparencyThreshold);
// --- Step 4: Advance blend timer ---
float newBlend;
if (g_transitionDuration <= 0.0f)
{
// Hard cut: jump immediately to full B.
newBlend = 1.0f;
}
else
{
// Time-based blend (emscripten_get_now() returns milliseconds).
const double now = emscripten_get_now();
newBlend = static_cast<float>((now - g_transitionStartTime) / (static_cast<double>(g_transitionDuration) * 1000.0));
}
g_transitionBlend = newBlend < 1.0f ? newBlend : 1.0f;
if (g_transitionBlend >= 1.0f)
{
// Transition complete: promote B → A, release B's FBOs, reset state.
g_dualFbo.PromoteBtoA();
g_transitionBlend = 0.0f;
g_transitionActive = false;
g_presetBReady = false;
fprintf(stderr, "Phase5: Transition complete – Preset B promoted to A.\n");
}
g_renderedFrameCount++;
return;
}
EMSCRIPTEN_KEEPALIVE
void set_window_size(int width, int height)
{
if (!pm)
return;
WasmWebGLResizeCanvases(width, height);
glViewport(0, 0, width, height);
glScissor(0, 0, width, height);
projectm_set_window_size(pm, width, height);
// Phase 2: Resize all allocated dual ping-pong FBOs to match the new viewport.
g_dualFbo.Resize(width, height);
return;
}
} // extern "C"
int main()
{
init();
return 0;
}