-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.cpp
More file actions
2482 lines (2262 loc) · 111 KB
/
Copy pathApp.cpp
File metadata and controls
2482 lines (2262 loc) · 111 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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// App.cpp — Spatial Root ImGui + GLFW desktop GUI application implementation.
#include "App.hpp"
#include "FileDialog.hpp"
#include "imgui_stdlib.h"
#include <al/io/al_AudioIO.hpp>
#include <GLFW/glfw3.h>
#include "miniLogo_data.h"
#include "stb_image.h"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstring>
#include <fstream>
#include <cstdlib>
#include <sstream>
#include <utility>
#include <string>
#ifdef _WIN32
#include <windows.h>
#elif defined(__APPLE__)
#include <mach-o/dyld.h>
#else
#include <unistd.h>
#endif
namespace fs = std::filesystem;
namespace {
constexpr const char* kDevLayoutRoot = "source/speaker_layouts";
constexpr const char* kPackagedLayoutRoot = "speaker_layouts";
std::string toLowerCopy(std::string value) {
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return value;
}
bool pathHasExtension(const std::string& path, const char* ext) {
return toLowerCopy(fs::path(path).extension().string()) == ext;
}
bool isCultProgressLine(const std::string& line) {
return line.find("[cult-transcoder]") != std::string::npos &&
line.find('%') != std::string::npos;
}
std::string shellQuoteForDisplay(const std::string& token) {
std::string quoted = "\"";
for (char c : token) {
if (c == '"' || c == '\\') quoted.push_back('\\');
quoted.push_back(c);
}
quoted.push_back('"');
return quoted;
}
std::string joinCommandForDisplay(const std::vector<std::string>& tokens) {
std::ostringstream out;
for (size_t i = 0; i < tokens.size(); ++i) {
if (i > 0) out << ' ';
out << shellQuoteForDisplay(tokens[i]);
}
return out.str();
}
void clearLog(std::deque<LogEntry>& log, std::mutex& mutex) {
std::lock_guard<std::mutex> lock(mutex);
log.clear();
}
bool copyIfPresent(const fs::path& source, const fs::path& destination) {
std::error_code ec;
if (!fs::exists(source, ec)) return false;
fs::create_directories(destination.parent_path());
if (fs::is_directory(source, ec)) {
fs::copy(source, destination,
fs::copy_options::recursive | fs::copy_options::overwrite_existing);
return true;
}
if (fs::is_regular_file(source, ec)) {
fs::copy_file(source, destination, fs::copy_options::overwrite_existing);
return true;
}
return false;
}
bool hasDiagnosticsFiles(const std::optional<fs::path>& sessionRoot) {
if (!sessionRoot) return false;
std::error_code ec;
return fs::exists(*sessionRoot / "manifest.json", ec) ||
fs::exists(*sessionRoot / "reports", ec);
}
std::string truncateStatusText(const std::string& text, size_t maxLen) {
if (text.size() <= maxLen) return text;
if (maxLen <= 3) return text.substr(0, maxLen);
return text.substr(0, maxLen - 3) + "...";
}
std::string currentWorkingDirectoryString() {
std::error_code ec;
const fs::path cwd = fs::current_path(ec);
if (ec) return "<unavailable: " + ec.message() + ">";
return cwd.string();
}
std::vector<std::string> tailLogText(const std::deque<LogEntry>& log, size_t maxLines) {
std::vector<std::string> lines;
if (maxLines == 0 || log.empty()) return lines;
const size_t begin = log.size() > maxLines ? log.size() - maxLines : 0;
lines.reserve(log.size() - begin);
for (size_t i = begin; i < log.size(); ++i) {
lines.push_back(log[i].text);
}
return lines;
}
fs::path currentExecutablePath() {
#ifdef _WIN32
std::wstring buffer(MAX_PATH, L'\0');
for (;;) {
const DWORD len = GetModuleFileNameW(nullptr, buffer.data(),
static_cast<DWORD>(buffer.size()));
if (len == 0) return {};
if (len < buffer.size() - 1) {
buffer.resize(len);
return fs::path(buffer);
}
buffer.resize(buffer.size() * 2);
}
#elif defined(__APPLE__)
uint32_t size = 1024;
std::vector<char> buffer(size, '\0');
if (_NSGetExecutablePath(buffer.data(), &size) != 0) {
buffer.assign(size, '\0');
if (_NSGetExecutablePath(buffer.data(), &size) != 0) return {};
}
return fs::weakly_canonical(fs::path(buffer.data()));
#else
std::vector<char> buffer(1024, '\0');
for (;;) {
const ssize_t len = readlink("/proc/self/exe", buffer.data(), buffer.size() - 1);
if (len < 0) return {};
if (static_cast<size_t>(len) < buffer.size() - 1) {
buffer[static_cast<size_t>(len)] = '\0';
return fs::path(buffer.data());
}
buffer.resize(buffer.size() * 2, '\0');
}
#endif
}
fs::path executableDirectory() {
const fs::path exe = currentExecutablePath();
return exe.empty() ? fs::path{} : exe.parent_path();
}
fs::path macBundleResourcesDirectory() {
#ifdef __APPLE__
const fs::path exeDir = executableDirectory();
if (exeDir.empty()) return {};
const fs::path contentsDir = exeDir.parent_path();
if (contentsDir.filename() != "Contents") return {};
const fs::path resourcesDir = contentsDir / "Resources";
std::error_code ec;
if (fs::exists(resourcesDir, ec)) return resourcesDir;
#endif
return {};
}
fs::path installPrefixFromExecutable() {
const fs::path exeDir = executableDirectory();
if (exeDir.empty() || exeDir.filename() != "bin") return {};
return exeDir.parent_path();
}
std::string withExecutableSuffix(std::string name) {
#ifdef _WIN32
name += ".exe";
#endif
return name;
}
std::string toGenericString(const fs::path& path) {
return path.generic_string();
}
std::string layoutPackagedSubpath(const std::string& relPath) {
const std::string normalized = toGenericString(fs::path(relPath).lexically_normal());
const std::string prefix = std::string(kDevLayoutRoot) + "/";
if (normalized == kDevLayoutRoot) return {};
if (normalized.rfind(prefix, 0) == 0) return normalized.substr(prefix.size());
return normalized;
}
void appendCandidate(std::vector<fs::path>& candidates,
const fs::path& path) {
if (path.empty()) return;
if (std::find(candidates.begin(), candidates.end(), path) == candidates.end()) {
candidates.push_back(path);
}
}
std::string cultTranscoderNotFoundMessage() {
return "cult-transcoder not found in the staged package, install tree, or developer build paths. "
"Install the packaged bundle completely, set SPATIALROOT_CULT_TRANSCODER=/path/to/cult-transcoder, "
"or build the repo with ./build.sh.";
}
template <class AppendFn>
void appendArgvDiagnostics(AppendFn&& append,
const std::vector<std::string>& args,
const std::string& cwd) {
append("[GUI] Working directory: " + cwd);
append("[GUI] Executable: " + (args.empty() ? std::string("<missing>") : args.front()));
for (size_t i = 0; i < args.size(); ++i) {
append("[GUI] argv[" + std::to_string(i) + "]: " + args[i]);
}
}
template <class AppendFn>
void appendRecentOutputTail(AppendFn&& append, const std::vector<std::string>& lines) {
if (lines.empty()) {
append("[error] Recent subprocess output: <none captured>");
return;
}
append("[error] Recent subprocess output:");
for (const auto& line : lines) {
append("[error] " + line);
}
}
}
constexpr int App::kBufferSizes[];
constexpr const char* App::kBufferSizeNames[];
constexpr const char* App::kLayoutNames[];
constexpr const char* App::kLayoutPaths[];
constexpr const char* App::kElevModeNames[];
constexpr const char* App::kTcWorkflowNames[];
constexpr const char* App::kTcFormatNames[];
constexpr const char* App::kTcFormatValues[];
constexpr const char* App::kTcLfeModeNames[];
constexpr const char* App::kTcLfeModeValues[];
constexpr const char* App::kTcAdmInputModeNames[];
App::App(std::string projectRoot, bool keepTempSessions, std::string tempRootOverride)
: mProjectRoot(std::move(projectRoot))
, mKeepTempSessions(keepTempSessions)
, mTempRootOverride(std::move(tempRootOverride))
, mDefaultLayoutMgr()
, mSession(std::make_unique<EngineSession>()) {
mLayoutPath = resolveProjectPath(kLayoutPaths[0]);
appendEngineLog("[GUI] Spatial Root — ImGui + GLFW GUI started.");
appendEngineLog("[GUI] Project root: " + mProjectRoot);
if (const fs::path exePath = currentExecutablePath(); !exePath.empty()) {
appendEngineLog("[GUI] Executable path: " + exePath.string());
}
if (const char* assetRoot = std::getenv("SPATIALROOT_ASSET_ROOT"); assetRoot && *assetRoot)
appendEngineLog(std::string("[GUI] Asset root override: ") + assetRoot, {0.7f, 0.9f, 0.7f, 1.f});
appendEngineLog("[GUI] Temp session root: " + pathString(tempSessionsRoot()));
if (mKeepTempSessions) {
appendEngineLog("[GUI] Keeping temporary sessions for debugging is enabled.",
{1.f, 0.8f, 0.2f, 1.f});
}
tryLoadDefaultLayoutOnStartup();
appendEngineLog("[GUI] Select a source and layout, then click START.");
int lw = 0, lh = 0, lch = 0;
unsigned char* logoData = stbi_load_from_memory(
miniLogo_png, (int)miniLogo_png_len, &lw, &lh, &lch, 4);
if (logoData) {
glGenTextures(1, &mLogoTexId);
glBindTexture(GL_TEXTURE_2D, mLogoTexId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, lw, lh, 0, GL_RGBA, GL_UNSIGNED_BYTE, logoData);
glBindTexture(GL_TEXTURE_2D, 0);
stbi_image_free(logoData);
}
}
App::~App() {
requestShutdown();
if (mLogoTexId != 0) {
glDeleteTextures(1, &mLogoTexId);
mLogoTexId = 0;
}
}
void App::tick() {
tickEngine();
renderUI();
}
void App::tickEngine() {
if (mSession) mStatus = mSession->queryStatus();
if (mState == AppState::Running || mState == AppState::Paused) {
mSession->update();
DiagnosticEvents ev = mSession->consumeDiagnostics();
char buf[256];
if (ev.renderRelocEvent) {
snprintf(buf, sizeof(buf), "[RELOC-RENDER] t=%.1fs 0x%llx → 0x%llx",
mStatus.timeSec,
(unsigned long long)ev.renderRelocPrev,
(unsigned long long)ev.renderRelocNext);
appendEngineLog(buf, {0.7f, 0.7f, 1.f, 1.f});
}
if (ev.deviceRelocEvent) {
snprintf(buf, sizeof(buf), "[RELOC-DEVICE] t=%.1fs 0x%llx → 0x%llx",
mStatus.timeSec,
(unsigned long long)ev.deviceRelocPrev,
(unsigned long long)ev.deviceRelocNext);
appendEngineLog(buf, {0.7f, 0.7f, 1.f, 1.f});
}
if (ev.renderDomRelocEvent && mStatus.mainRms > 0.005f) {
snprintf(buf, sizeof(buf), "[DOM-RENDER] t=%.1fs 0x%llx → 0x%llx",
mStatus.timeSec,
(unsigned long long)ev.renderDomRelocPrev,
(unsigned long long)ev.renderDomRelocNext);
appendEngineLog(buf, {0.6f, 0.8f, 1.f, 1.f});
}
if (ev.renderClusterEvent && mStatus.mainRms > 0.005f) {
snprintf(buf, sizeof(buf), "[CLUSTER-RENDER] t=%.1fs 0x%llx → 0x%llx",
mStatus.timeSec,
(unsigned long long)ev.renderClusterPrev,
(unsigned long long)ev.renderClusterNext);
appendEngineLog(buf, {0.6f, 0.8f, 1.f, 1.f});
}
if (mStatus.isExitRequested) {
appendEngineLog("[Engine] Exit requested (device loss?). Shutting down.",
{1.f, 0.5f, 0.2f, 1.f});
mSession->shutdown();
mState = AppState::Idle;
}
if (mStatus.paused && mState == AppState::Running) mState = AppState::Paused;
else if (!mStatus.paused && mState == AppState::Paused) mState = AppState::Running;
}
if (mState == AppState::Transcoding && !mTranscoder.isRunning()) {
const int code = mTranscoder.exitCode();
if (code == 0) {
if (mActiveTempSessionRoot) {
updateManifest(*mActiveTempSessionRoot, mActiveTempManifest, "generated", false, false);
}
appendEngineLog("[Transcoder] Complete. Launching engine...", {0.3f, 0.9f, 0.3f, 1.f});
doLaunchEngine(mTranscodeScene, "", mTranscodeAdm);
} else {
const std::vector<std::string> recentOutput = tailLogText(mEngineLog, 5);
mLastError = "cult-transcoder exited with code " + std::to_string(code);
if (mActiveTempSessionRoot) {
updateManifest(*mActiveTempSessionRoot, mActiveTempManifest,
"failed", false, mKeepTempSessions);
}
mLastFailureHasDiagnostics = true;
appendEngineLog("[Transcoder] FAILED: " + mLastError, {1.f, 0.3f, 0.3f, 1.f});
appendEngineLog("[Transcoder] Executable: " +
(mTranscoderActiveArgs.empty() ? std::string("<unknown>")
: mTranscoderActiveArgs.front()),
{1.f, 0.5f, 0.2f, 1.f});
appendEngineLog("[Transcoder] Working directory: " + mTranscoderActiveCwd,
{1.f, 0.5f, 0.2f, 1.f});
{
std::error_code ec;
appendEngineLog("[Transcoder] Expected scene output: " + mTranscodeScene +
" (exists=" + (fs::exists(mTranscodeScene, ec) ? "yes" : "no") + ")",
{1.f, 0.5f, 0.2f, 1.f});
}
appendRecentOutputTail([this](const std::string& line) {
appendEngineLog(line, {1.f, 0.5f, 0.2f, 1.f});
}, recentOutput);
mState = AppState::Error;
}
}
const bool tcWasRunning = mTcRunning;
mTcRunning = mTcRunner.isRunning();
if (tcWasRunning && !mTcRunning) {
mTcDone = true;
const int tcExit = mTcRunner.exitCode();
mTcSuccess = false;
mTcStatusDetail.clear();
std::vector<std::string> recentTcOutput;
{
std::lock_guard<std::mutex> lock(mTcLogMutex);
recentTcOutput = tailLogText(mTcLog, 5);
}
std::vector<std::string> missingOutputs;
std::vector<std::string> warningOutputs;
if (tcExit == 0) {
std::error_code ec;
if (!mTcExpectedPrimaryOutput.empty() &&
!fs::exists(mTcExpectedPrimaryOutput, ec)) {
missingOutputs.push_back(mTcExpectedPrimaryOutput);
}
if (!mTcExpectedSecondaryOutput.empty() &&
!fs::exists(mTcExpectedSecondaryOutput, ec)) {
missingOutputs.push_back(mTcExpectedSecondaryOutput);
}
if (!mTcExpectedReportPath.empty() &&
!fs::exists(mTcExpectedReportPath, ec)) {
warningOutputs.push_back(mTcExpectedReportPath);
}
}
if (tcExit == 0 && missingOutputs.empty()) {
mTcSuccess = true;
mTcStatusDetail = "Complete";
appendTcLog("[ok] Transcode complete. Expected outputs were created.");
if (!warningOutputs.empty()) {
appendTcLog("[warn] Report file was not found at: " + warningOutputs.front());
}
} else {
if (tcExit != 0) {
mTcStatusDetail = "Failed (exit code " + std::to_string(tcExit) + ")";
appendTcLog("[error] Transcode failed. Exit code " + std::to_string(tcExit) + ".");
} else {
mTcStatusDetail = "Failed (expected output missing)";
appendTcLog("[error] Transcode finished with exit code 0, but expected output was missing.");
for (const auto& path : missingOutputs) {
appendTcLog("[error] Missing output: " + path);
}
}
appendTcLog("[error] Command path: " +
(mTcActiveArgs.empty() ? std::string("<unknown>") : mTcActiveArgs.front()));
appendTcLog("[error] Working directory: " + mTcActiveCwd);
appendTcLog("[error] Exit code: " + std::to_string(tcExit));
if (!mTcExpectedPrimaryOutput.empty()) {
std::error_code ec;
appendTcLog("[error] Expected primary output: " + mTcExpectedPrimaryOutput +
" (exists=" + (fs::exists(mTcExpectedPrimaryOutput, ec) ? "yes" : "no") + ")");
}
if (!mTcExpectedSecondaryOutput.empty()) {
std::error_code ec;
appendTcLog("[error] Expected secondary output: " + mTcExpectedSecondaryOutput +
" (exists=" + (fs::exists(mTcExpectedSecondaryOutput, ec) ? "yes" : "no") + ")");
}
if (!mTcExpectedReportPath.empty()) {
std::error_code ec;
appendTcLog("[error] Expected report path: " + mTcExpectedReportPath +
" (exists=" + (fs::exists(mTcExpectedReportPath, ec) ? "yes" : "no") + ")");
}
appendRecentOutputTail([this](const std::string& line) { appendTcLog(line); }, recentTcOutput);
}
if (mTcTempSessionRoot) {
updateManifest(*mTcTempSessionRoot, mTcTempManifest,
mTcSuccess ? "complete" : "failed",
false, mKeepTempSessions);
if (!mTcSuccess) mLastFailureHasDiagnostics = true;
}
}
const bool orWasRunning = mOrRunning;
mOrRunning = mOrRunner.isRunning();
if (orWasRunning && !mOrRunning) {
mOrDone = true;
mOrSuccess = (mOrRunner.exitCode() == 0);
if (mOrSuccess) {
appendOrLog("[GUI] Offline render complete. Exit code 0.");
} else {
appendOrLog("[GUI] Offline render FAILED. Exit code " +
std::to_string(mOrRunner.exitCode()) +
". Check log above for details.");
}
}
}
void App::requestShutdown() {
if (mShutdownRequested) return;
mShutdownRequested = true;
if (mState == AppState::Running || mState == AppState::Paused) {
appendEngineLog("[GUI] Shutting down engine...");
mSession->shutdown();
mState = AppState::Idle;
}
if (mState == AppState::Transcoding && mTranscoder.isRunning()) {
appendEngineLog("[GUI] Waiting for active transcode to finish before cleanup...",
{1.f, 0.8f, 0.2f, 1.f});
mTranscoder.wait();
}
if (mTcRunner.isRunning()) {
appendEngineLog("[GUI] Waiting for manual transcode to finish before cleanup...",
{1.f, 0.8f, 0.2f, 1.f});
mTcRunner.wait();
}
if (mOrRunner.isRunning()) {
appendEngineLog("[GUI] Waiting for offline render to finish before cleanup...",
{1.f, 0.8f, 0.2f, 1.f});
mOrRunner.wait();
}
cleanupOwnedTempSessions(true);
}
void App::renderUI() {
ImGuiIO& io = ImGui::GetIO();
ImGui::SetNextWindowPos({0.f, 0.f});
ImGui::SetNextWindowSize(io.DisplaySize);
ImGui::Begin("##root", nullptr,
ImGuiWindowFlags_NoTitleBar |
ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoBringToFrontOnFocus);
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 2.f);
const float logoH = ImGui::GetTextLineHeight();
if (mLogoTexId != 0) ImGui::Image((ImTextureID)(intptr_t)mLogoTexId, ImVec2(logoH, logoH));
else ImGui::TextColored({0.60f, 0.57f, 0.52f, 1.f}, "⊙");
ImGui::SameLine(0.f, 8.f);
ImGui::Text("Spatial Root");
ImGui::SameLine(0.f, 6.f);
ImGui::TextDisabled("Real-Time Engine");
const float leftEnd = ImGui::GetItemRectMax().x;
const char* crumb = "ADM → LUSID → Spatial Render";
const float crumbW = ImGui::CalcTextSize(crumb).x;
const float crumbX = (ImGui::GetWindowWidth() - crumbW) * 0.5f;
if (crumbX > leftEnd + 8.f) {
ImGui::SameLine(crumbX);
ImGui::TextDisabled("%s", crumb);
}
char stateBuf[64];
snprintf(stateBuf, sizeof(stateBuf), "● %s", stateName(mState));
const float stateW = ImGui::CalcTextSize(stateBuf).x + 16.f;
ImGui::SameLine(ImGui::GetWindowWidth() - stateW);
ImGui::TextColored(stateColor(mState), "%s", stateBuf);
ImGui::Separator();
if (ImGui::BeginTabBar("##tabs")) {
if (ImGui::BeginTabItem("ENGINE")) {
renderEngineTab();
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("TRANSCODE")) {
renderTranscodeTab();
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("OFFLINE RENDER")) {
renderOfflineRenderTab();
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
ImGui::End();
}
void App::renderEngineTab() {
const bool isRunning = (mState == AppState::Running || mState == AppState::Paused);
const bool isIdle = (mState == AppState::Idle || mState == AppState::Error);
const ImVec4 kGreen = {0.20f, 0.62f, 0.25f, 1.f};
const ImVec4 kAmber = {0.70f, 0.45f, 0.08f, 1.f};
const ImVec4 kRed = {0.72f, 0.18f, 0.15f, 1.f};
const bool audioReady = isRunning;
const bool audioNotReady = (mState == AppState::Error);
const ImVec4 audioStatusColor = audioReady ? kGreen : (audioNotReady ? kRed : kAmber);
const std::string backendLabel = mStatus.audioBackendLabel.empty()
? std::string("Unknown backend")
: mStatus.audioBackendLabel;
const int bufferSize = kBufferSizes[mBufferSizeIdx];
const int requiredSampleRate = 48000;
const int requestedSampleRate = mStatus.requestedSampleRate;
const int selectedOutputChannels =
(mDeviceIdx >= 0 && mDeviceIdx < static_cast<int>(mDeviceOutputChannels.size()))
? mDeviceOutputChannels[mDeviceIdx]
: 0;
const double scannedDeviceSampleRate =
(mDeviceIdx >= 0 && mDeviceIdx < static_cast<int>(mDeviceSampleRates.size()))
? mDeviceSampleRates[mDeviceIdx]
: 0.0;
// Backend-confirmed preferred/default rate when available; falls back to GUI scan metadata.
// Used for display and mismatch warnings only — never for the "Sample Rate OK" determination.
const double selectedDeviceSampleRate = mStatus.outputDevicePreferredSampleRateKnown
? mStatus.outputDevicePreferredSampleRate
: scannedDeviceSampleRate;
const bool actualStreamRateKnown = mStatus.effectiveStreamSampleRateKnown;
const int actualStreamRate = actualStreamRateKnown
? static_cast<int>(std::round(mStatus.effectiveStreamSampleRate))
: 0;
const std::string activeDeviceName = mStatus.outputDeviceName.empty()
? (mDeviceName.empty() ? "(system default)" : mDeviceName)
: mStatus.outputDeviceName;
std::string audioStatusText;
if (audioReady) {
std::ostringstream os;
os << "Ready"
<< " \xC2\xB7 " << backendLabel
<< " \xC2\xB7 ";
if (actualStreamRateKnown) {
os << (actualStreamRate / 1000) << " kHz";
} else {
os << "48 kHz not confirmed";
}
os << " \xC2\xB7 " << bufferSize;
if (selectedOutputChannels > 0) os << " \xC2\xB7 " << selectedOutputChannels << " out";
audioStatusText = os.str();
} else if (audioNotReady) {
audioStatusText = "Not Ready";
if (!mLastError.empty()) audioStatusText += " \xC2\xB7 " + truncateStatusText(mLastError, 72);
} else {
audioStatusText = "Unknown \xC2\xB7 Configure device and buffer, then start audio";
}
const char* audioToggleLabel = mShowAudioSetupPanel ? "Audio Setup \xE2\x96\xB2"
: "Audio Setup \xE2\x96\xBC";
if (audioNotReady) mShowAudioSetupPanel = true;
if (ImGui::BeginChild("##inputcard", ImVec2(0.f, 0.f),
ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeY)) {
ImGui::TextDisabled("INPUT CONFIGURATION");
ImGui::Spacing();
if (isRunning) ImGui::BeginDisabled(true);
ImGui::TextDisabled("SOURCE");
if (mSourceIsAdm) { ImGui::SameLine(); ImGui::TextColored(kGreen, "ADM"); }
else if (mSourceIsLusid) { ImGui::SameLine(); ImGui::TextColored(kGreen, "LUSID"); }
ImGui::SameLine(120.f);
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x - 78.f);
if (ImGui::InputText("##source", &mSourcePath)) detectSource();
ImGui::SameLine();
if (ImGui::Button("Browse##src")) {
const std::string p = pickFileOrDirectory("Select Audio Source");
if (!p.empty()) { mSourcePath = p; detectSource(); }
}
if (!mSourceHint.empty()) {
const bool isError = !mSourceIsAdm && !mSourceIsLusid;
ImGui::SetCursorPosX(120.f);
ImGui::TextColored(isError ? kRed : kGreen, "%s", mSourceHint.c_str());
}
ImGui::SetCursorPosX(120.f);
if (ImGui::Button("Download Atmos Examples##atmosdl")) {
#ifdef __APPLE__
system("open https://huggingface.co/datasets/lucianparisi/atmos-data/tree/main");
#elif defined(_WIN32)
system("start https://huggingface.co/datasets/lucianparisi/atmos-data/tree/main");
#else
system("xdg-open https://huggingface.co/datasets/lucianparisi/atmos-data/tree/main");
#endif
}
if (ImGui::IsItemHovered()) ImGui::SetTooltip("Download Atmos example files");
ImGui::TextDisabled("LAYOUT");
ImGui::SameLine(120.f);
ImGui::SetNextItemWidth(110.f);
if (ImGui::Combo("##layoutpreset", &mLayoutPreset, kLayoutNames, IM_ARRAYSIZE(kLayoutNames))) {
if (mLayoutPreset < IM_ARRAYSIZE(kLayoutNames) - 1) mLayoutPath = resolveProjectPath(kLayoutPaths[mLayoutPreset]);
}
ImGui::SameLine();
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x - 78.f);
ImGui::InputText("##layout", &mLayoutPath);
ImGui::SameLine();
if (ImGui::Button("Browse##layout")) {
const std::string p = pickFile("Select Speaker Layout", {"*.json"}, "JSON files");
if (!p.empty()) { mLayoutPath = p; mLayoutPreset = IM_ARRAYSIZE(kLayoutNames) - 1; }
}
renderDefaultLayoutControls();
ImGui::SetCursorPosX(120.f);
if (ImGui::Button("Layout Builder##layoutbuilder")) {
#ifdef __APPLE__
system("open https://cultdsp.com/layout-builder/");
#elif defined(_WIN32)
system("start https://cultdsp.com/layout-builder/");
#else
system("xdg-open https://cultdsp.com/layout-builder/");
#endif
}
if (ImGui::IsItemHovered()) ImGui::SetTooltip("Build or modify a custom layout here");
if (isRunning) ImGui::EndDisabled();
ImGui::TextDisabled("AUDIO");
ImGui::SameLine(120.f);
ImGui::TextColored(audioStatusColor, "%s", audioStatusText.c_str());
ImGui::SameLine();
const float toggleW = ImGui::CalcTextSize(audioToggleLabel).x + ImGui::GetStyle().FramePadding.x * 2.f;
ImGui::SetCursorPosX(std::max(ImGui::GetCursorPosX(),
ImGui::GetWindowWidth() - toggleW - ImGui::GetStyle().WindowPadding.x));
if (ImGui::Button(audioToggleLabel)) mShowAudioSetupPanel = !mShowAudioSetupPanel;
}
ImGui::EndChild();
ImGui::Spacing();
if (mShowAudioSetupPanel) {
if (ImGui::BeginChild("##audiosetupcard", ImVec2(0.f, 0.f),
ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeY)) {
ImGui::TextDisabled("AUDIO SETUP STATUS");
ImGui::Text("Realtime Audio: %s", audioReady ? "Ready" : (audioNotReady ? "Not Ready" : "Unknown"));
ImGui::Text("Backend: %s", backendLabel.c_str());
ImGui::TextWrapped("Last Error: %s", mLastError.empty() ? "none" : mLastError.c_str());
ImGui::SameLine();
ImGui::SetCursorPosX(ImGui::GetWindowWidth()
- ImGui::GetStyle().WindowPadding.x
- ImGui::CalcTextSize("Copy Diagnostics##audio").x
- ImGui::GetStyle().ItemSpacing.x);
if (ImGui::Button("Copy Diagnostics##audio")) {
std::ostringstream os;
os << "Realtime Audio: "
<< (audioReady ? "Ready" : (audioNotReady ? "Not Ready" : "Unknown")) << "\n"
<< "Backend: " << backendLabel << "\n"
<< "Device: " << activeDeviceName << "\n"
<< "Output Channels: "
<< (selectedOutputChannels > 0 ? std::to_string(selectedOutputChannels) : "unknown") << "\n"
<< "Required sample rate: " << requiredSampleRate << " Hz\n"
<< "Requested engine sample rate: " << requestedSampleRate << " Hz\n"
<< "Selected device preferred/default sample rate: "
<< (selectedDeviceSampleRate > 0.0
? std::to_string(static_cast<int>(std::round(selectedDeviceSampleRate))) + " Hz"
: "unknown") << "\n"
<< "Actual stream sample rate: "
<< (actualStreamRateKnown ? std::to_string(actualStreamRate) + " Hz" : "unknown") << "\n"
<< "Buffer: " << bufferSize << "\n"
<< "Last Error: " << (mLastError.empty() ? "none" : mLastError);
ImGui::SetClipboardText(os.str().c_str());
}
if (isRunning) ImGui::BeginDisabled(true);
ImGui::TextDisabled("DEVICE");
if (ImGui::Button("Rescan Devices##device")) scanDevices();
ImGui::SameLine();
if (mDeviceList.empty()) {
ImGui::TextDisabled("(click Rescan Devices to list output devices)");
} else {
std::vector<const char*> items;
items.reserve(mDeviceList.size());
for (const auto& d : mDeviceList) items.push_back(d.c_str());
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);
if (ImGui::Combo("##device", &mDeviceIdx, items.data(), (int)items.size())) {
mDeviceName = (mDeviceIdx == 0) ? "" : mDeviceList[mDeviceIdx];
}
}
if (selectedOutputChannels > 0) {
ImGui::Text("Output Channels: %d", selectedOutputChannels);
} else {
ImGui::TextDisabled("Output Channels: unknown");
}
ImGui::Spacing();
ImGui::TextDisabled("BUFFER SIZE");
ImGui::SetNextItemWidth(110.f);
ImGui::Combo("##bufsize", &mBufferSizeIdx, kBufferSizeNames, 5);
if (ImGui::IsItemHovered()) {
ImGui::SetTooltip(
"Buffer size affects realtime stability.\n"
"\n"
"Smaller buffers reduce latency but increase CPU load and the risk of xruns, clicks, or dropouts.\n"
"Larger buffers improve stability but increase latency.\n"
"Changing buffer size may require restarting the engine or playback session.\n"
"Safest workflow: stop playback before changing this setting."
);
}
ImGui::TextDisabled("Buffer changes apply after restarting audio.");
if (isRunning) ImGui::EndDisabled();
ImGui::Spacing();
{
const bool preferredRateKnown = selectedDeviceSampleRate > 0.0;
const int preferredRate = preferredRateKnown
? static_cast<int>(std::round(selectedDeviceSampleRate))
: 0;
const bool preferredMismatch = preferredRateKnown && preferredRate != requiredSampleRate;
const bool srOk = actualStreamRateKnown && actualStreamRate == requiredSampleRate;
const bool actualMismatch = actualStreamRateKnown && actualStreamRate != requiredSampleRate;
const ImVec4 srColor = srOk ? kGreen : ((actualMismatch || preferredMismatch) ? kRed : kAmber);
const char* srTitle = srOk ? "Sample Rate OK"
: actualMismatch ? "Sample Rate Mismatch"
: "48 kHz Not Confirmed";
std::string preferredStr = preferredRateKnown
? ("Selected device preferred/default sample rate: "
+ std::to_string(preferredRate) + " Hz")
: "Selected device preferred/default sample rate: unknown";
std::string actualStr = actualStreamRateKnown
? ("Actual stream sample rate: " + std::to_string(actualStreamRate) + " Hz")
: "Actual stream sample rate: unknown";
std::string srDesc;
if (srOk) {
srDesc = "Spatial Root confirmed a 48 kHz realtime stream.";
} else if (actualMismatch) {
srDesc = "Spatial Root requires 48000 Hz. The realtime stream is running at "
+ std::to_string(actualStreamRate)
+ " Hz, so startup must fail.";
} else if (preferredMismatch) {
srDesc = "Spatial Root requires 48000 Hz. The selected device reports a different preferred/default"
" sample rate, so confirm 48 kHz in Audio MIDI Setup, JACK/PipeWire, or system audio"
" settings before starting.";
} else {
srDesc = "Spatial Root requires 48000 Hz. The realtime stream rate is not confirmed until the"
" backend reports it.";
}
ImGui::PushStyleColor(ImGuiCol_ChildBg,
ImVec4(srColor.x * 0.10f, srColor.y * 0.10f, srColor.z * 0.10f, 1.f));
if (ImGui::BeginChild("##srbox", ImVec2(0.f, 0.f),
ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeY,
ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) {
ImGui::TextColored(srColor, "%s", srTitle);
if (srOk) {
ImGui::SameLine();
ImGui::TextColored(kGreen, "Spatial Root confirmed a 48 kHz realtime stream.");
}
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.f, 1.f, 1.f, 1.f));
ImGui::Text("Required sample rate: %d Hz -> Requested engine sample rate: %d Hz",
requiredSampleRate, requestedSampleRate);
ImGui::Text("%s -> %s", preferredStr.c_str(), actualStr.c_str());
if (!srOk) ImGui::TextWrapped("%s", srDesc.c_str());
ImGui::PopStyleColor();
}
ImGui::EndChild();
ImGui::PopStyleColor();
}
}
ImGui::EndChild();
ImGui::Spacing();
}
if (ImGui::BeginChild("##transportcard", {0.f, 90.f}, true)) {
ImGui::TextDisabled("TRANSPORT");
ImGui::Spacing();
const bool canStart = isIdle;
const bool canStop = isRunning;
const bool canPause = (mState == AppState::Running);
const bool canResume = (mState == AppState::Paused);
const bool busy = (mState == AppState::Transcoding);
if (!canStart) ImGui::BeginDisabled(true);
if (ImGui::Button("Start")) onStart();
if (!canStart) ImGui::EndDisabled();
ImGui::SameLine();
if (!canStop) ImGui::BeginDisabled(true);
if (ImGui::Button("Stop")) onStop();
if (!canStop) ImGui::EndDisabled();
ImGui::SameLine();
if (!canPause) ImGui::BeginDisabled(true);
if (ImGui::Button("Pause")) onPause();
if (!canPause) ImGui::EndDisabled();
ImGui::SameLine();
if (!canResume) ImGui::BeginDisabled(true);
if (ImGui::Button("Resume")) onResume();
if (!canResume) ImGui::EndDisabled();
ImGui::SameLine();
if (!mLastGeneratedSceneAvailable || !mActiveTempSessionRoot) ImGui::BeginDisabled(true);
if (ImGui::Button("Save Generated Scene")) {
saveGeneratedSceneCopy(*mActiveTempSessionRoot, mActiveTempManifest,
"Choose Folder for Generated Scene",
"Generated scene saved");
}
if (!mLastGeneratedSceneAvailable || !mActiveTempSessionRoot) ImGui::EndDisabled();
ImGui::SameLine();
const bool hasDiagnostics = hasDiagnosticsFiles(mActiveTempSessionRoot) ||
hasDiagnosticsFiles(mTcTempSessionRoot);
if (!hasDiagnostics) ImGui::BeginDisabled(true);
if (ImGui::Button("Save Diagnostic Files")) {
if (mActiveTempSessionRoot) {
saveDiagnosticsCopy(*mActiveTempSessionRoot, mActiveTempManifest,
"Choose Folder for Diagnostic Files",
"Diagnostic files saved");
} else if (mTcTempSessionRoot) {
saveDiagnosticsCopy(*mTcTempSessionRoot, mTcTempManifest,
"Choose Folder for Diagnostic Files",
"Diagnostic files saved");
}
}
if (!hasDiagnostics) ImGui::EndDisabled();
ImGui::SameLine();
if (ImGui::Button("Clear Temporary Files")) cleanupOwnedTempSessions(true);
if (isRunning) {
ImGui::Text("t=%.1fs", mStatus.timeSec);
ImGui::SameLine();
ImGui::Text("CPU=%.1f%%", mStatus.cpuLoad * 100.f);
ImGui::SameLine();
ImGui::Text("RMS=%.4f", mStatus.mainRms);
ImGui::SameLine();
ImGui::Text("Xrun=%zu", mStatus.xruns);
} else if (busy) {
ImGui::TextColored(kAmber, "Transcoding ADM into a temporary session...");
} else if (mState == AppState::Error && !mLastError.empty()) {
ImGui::TextColored(kRed, "Error: %s", mLastError.c_str());
}
}
ImGui::EndChild();
ImGui::Spacing();
if (ImGui::BeginChild("##ctrlcard", {0.f, 190.f}, true)) {
const bool runtimeControlsReady = audioReady;
if (runtimeControlsReady) ImGui::TextColored(kGreen, "RUNTIME CONTROLS");
else ImGui::TextDisabled("RUNTIME CONTROLS");
// Reset Parameters button — right-aligned in the header row.
// Before Run: resets staged values. After Run: resets live engine params.
{
const float btnW = 140.f;
ImGui::SameLine(ImGui::GetContentRegionAvail().x + ImGui::GetCursorPosX() - btnW);
if (ImGui::SmallButton("Reset Parameters")) {
if (isRunning) {
mSession->resetRuntimeParams();
const RuntimeParams p = mSession->getRuntimeParams();
mGainDb = p.masterGainDb;
mFocus = p.dbapFocus;
mSpkMixDb = p.speakerMixDb;
mSubMixDb = p.subMixDb;
appendEngineLog("[GUI] Runtime parameters reset to defaults.");
} else {
resetRuntimeToDefaults();
appendEngineLog("[GUI] Runtime parameters reset to defaults."
" These values will be used when playback starts.");
}
}
if (ImGui::IsItemHovered())
ImGui::SetTooltip("Restore gain, focus, and mix controls to their default values.\n"
"Elevation mode is not reset.\n"
"Does not reload the scene, layout, or transport.");
}
ImGui::Spacing();
// Controls are always enabled — editable before Run as staged values,
// and live-updated after Run. Setters are only called when running.
if (runtimeControlsReady) ImGui::TextColored(kGreen, "MASTER GAIN");
else ImGui::TextDisabled("MASTER GAIN");
ImGui::SameLine(160.f);
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x - 70.f);
if (ImGui::SliderFloat("##gain", &mGainDb, -60.f, 12.f, "%.1f dB")) {
if (isRunning) mSession->setMasterGainDb(mGainDb);
}
ImGui::SameLine();
ImGui::SetNextItemWidth(60.f);
if (ImGui::InputFloat("##gaininput", &mGainDb, 0.f, 0.f, "%.1f")) {
mGainDb = std::clamp(mGainDb, -60.f, 12.f);
if (isRunning) mSession->setMasterGainDb(mGainDb);
}
if (runtimeControlsReady) ImGui::TextColored(kGreen, "DBAP FOCUS");
else ImGui::TextDisabled("DBAP FOCUS");
ImGui::SameLine(160.f);
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x - 70.f);
if (ImGui::SliderFloat("##focus", &mFocus, 0.1f, 5.0f, "%.2f")) {
if (isRunning) mSession->setDbapFocus(mFocus);
}
ImGui::SameLine();
ImGui::SetNextItemWidth(60.f);
if (ImGui::InputFloat("##focusinput", &mFocus, 0.f, 0.f, "%.2f")) {
mFocus = std::clamp(mFocus, 0.1f, 5.0f);
if (isRunning) mSession->setDbapFocus(mFocus);
}
if (runtimeControlsReady) ImGui::TextColored(kGreen, "SPEAKER MIX (DB)");
else ImGui::TextDisabled("SPEAKER MIX (DB)");
ImGui::SameLine(160.f);
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x - 70.f);
if (ImGui::SliderFloat("##spkmix", &mSpkMixDb, -60.f, 12.f, "%.1f dB")) {
if (isRunning) mSession->setSpeakerMixDb(mSpkMixDb);
}
ImGui::SameLine();
ImGui::SetNextItemWidth(60.f);
if (ImGui::InputFloat("##spkmixinput", &mSpkMixDb, 0.f, 0.f, "%.1f")) {
mSpkMixDb = std::clamp(mSpkMixDb, -60.f, 12.f);
if (isRunning) mSession->setSpeakerMixDb(mSpkMixDb);
}
if (runtimeControlsReady) ImGui::TextColored(kGreen, "SUB MIX (DB)");
else ImGui::TextDisabled("SUB MIX (DB)");
ImGui::SameLine(160.f);
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x - 70.f);
if (ImGui::SliderFloat("##submix", &mSubMixDb, -60.f, 12.f, "%.1f dB")) {
if (isRunning) mSession->setSubMixDb(mSubMixDb);
}
ImGui::SameLine();
ImGui::SetNextItemWidth(60.f);
if (ImGui::InputFloat("##submixinput", &mSubMixDb, 0.f, 0.f, "%.1f")) {
mSubMixDb = std::clamp(mSubMixDb, -60.f, 12.f);
if (isRunning) mSession->setSubMixDb(mSubMixDb);
}
if (runtimeControlsReady) ImGui::TextColored(kGreen, "ELEVATION MODE");
else ImGui::TextDisabled("ELEVATION MODE");
ImGui::SameLine(160.f);
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x - 8.f);
if (ImGui::Combo("##elevmode", &mElevationMode, kElevModeNames, 3) && isRunning) {
mSession->setElevationMode(static_cast<ElevationMode>(mElevationMode));
}
}
ImGui::EndChild();
ImGui::Spacing();