@geastack/apple 0.2.30 → 0.2.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,43 +1,79 @@
1
1
  #import <AppKit/AppKit.h>
2
2
 
3
- #include "apps.h"
3
+ #include "geaos.h"
4
4
 
5
5
  #include <string>
6
+ #include <vector>
6
7
 
7
- // macOS app-launcher platform. When the JSX-level `Apps.launch('foo')` runs,
8
- // AppManager::launch routes through this platform. We don't have in-process
9
- // app swapping yet (that'd need every app's __gea_top_level bundled into one
10
- // binary with a registry — like ESP32's resident-app system), so we cheat:
11
- // find dist/<id>/*.app next to the currently running bundle, open it with
12
- // NSWorkspace, and terminate self. Result is "click a tile → next app's
13
- // window appears, launcher window goes away" — same UX as the watch, just
14
- // realized via separate Mac processes.
8
+ // The macOS GeaOS host. Apps on macOS are bundled with the shell: the ones
9
+ // built next to this one (dist/<id>/<Name>.app) are its bundledApps(), and
10
+ // launching one opens that bundle and quits this process -- "click a tile,
11
+ // the app's window appears, Home's goes away", like the watch, realized as
12
+ // separate Mac processes. Apps are never downloaded and loaded at run time
13
+ // on Apple targets.
15
14
  //
16
- // If the target .app hasn't been built yet, we log a message and stay in
17
- // the launcher. The user runs `targets/macos/build-macos.sh <id>` first.
15
+ // An app that has not been built yet is not listed; build it with
16
+ // `gea build --target macos <id>`.
18
17
 
19
18
  namespace {
20
19
 
21
- class MacosAppLauncherPlatform final : public gea::framework::apps::AppLauncherPlatform {
20
+ // The bundle that plays Home.
21
+ constexpr const char *kHomeAppId = "app-launcher";
22
+
23
+ class MacosAppHost final : public gea::geaos::AppHost {
22
24
  public:
23
- explicit MacosAppLauncherPlatform(std::string currentId) : currentId_(std::move(currentId)) {}
25
+ explicit MacosAppHost(std::string currentId) : currentId_(std::move(currentId)) {}
26
+
27
+ const char *targetKey() const override { return "macos"; }
28
+ // Bundled apps are built with this shell; there is nothing to mismatch.
29
+ const char *abi() const override { return "macos-bundled"; }
30
+ const char *firmwareId() const override { return currentId_.c_str(); }
31
+ const char *runningAppId() const override { return currentId_ == kHomeAppId ? "" : currentId_.c_str(); }
24
32
 
25
- const char *currentInstalledAppId() override { return currentId_.c_str(); }
26
- bool runningAppIsLauncher(const char *launcherAppId) override
33
+ std::vector<gea::geaos::InstalledApp> bundledApps() const override
27
34
  {
28
- if (!launcherAppId) return false;
29
- return currentId_ == launcherAppId;
35
+ std::vector<gea::geaos::InstalledApp> apps;
36
+ NSString *dist = distDirectory();
37
+ NSArray<NSString *> *ids = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dist error:nil];
38
+ for (NSString *candidate in ids) {
39
+ const char *id = candidate.UTF8String;
40
+ if (!gea::geaos::isValidAppId(id) || std::string(id) == kHomeAppId) continue;
41
+ NSString *bundle = findBundleForAppId(candidate);
42
+ if (!bundle) continue;
43
+ gea::geaos::InstalledApp app;
44
+ app.manifest.id = id;
45
+ NSString *name = [[bundle lastPathComponent] stringByDeletingPathExtension];
46
+ app.manifest.name = name.length ? name.UTF8String : id;
47
+ app.manifest.abi = abi();
48
+ app.volumeId = "bundle";
49
+ app.location = bundle.UTF8String;
50
+ apps.push_back(std::move(app));
51
+ }
52
+ return apps;
30
53
  }
31
54
 
32
- bool launchInstalledApp(const char *appId) override
55
+ bool launch(const gea::geaos::InstalledApp &app, std::string &error) override
56
+ {
57
+ return open(app.manifest.id.c_str(), error);
58
+ }
59
+
60
+ bool home(std::string &error) override
61
+ {
62
+ if (currentId_ == kHomeAppId) {
63
+ error = "Home is already running";
64
+ return false;
65
+ }
66
+ return open(kHomeAppId, error);
67
+ }
68
+
69
+ private:
70
+ bool open(const char *appId, std::string &error)
33
71
  {
34
- if (!appId || !appId[0]) return false;
35
72
  NSString *target = [NSString stringWithUTF8String:appId];
36
73
  NSString *bundle = findBundleForAppId(target);
37
74
  if (!bundle) {
38
- NSLog(@"[gea-launch] no built .app for '%@' under dist/. Run "
39
- @"targets/macos/build-macos.sh %@ first.",
40
- target, target);
75
+ NSLog(@"[gea-launch] no built .app for '%@' under dist/. Run gea build --target macos %@ first.", target, target);
76
+ error = std::string("no built app for ") + appId;
41
77
  return false;
42
78
  }
43
79
  NSURL *url = [NSURL fileURLWithPath:bundle];
@@ -48,7 +84,11 @@ public:
48
84
  configuration:cfg
49
85
  completionHandler:^(NSRunningApplication *app, NSError *err) {
50
86
  (void)app;
51
- if (err) NSLog(@"[gea-launch] open failed: %@", err);
87
+ if (err) {
88
+ NSLog(@"[gea-launch] open failed: %@", err);
89
+ gea::geaos::Launcher::setLastError(err.localizedDescription.UTF8String);
90
+ return;
91
+ }
52
92
  dispatch_async(dispatch_get_main_queue(), ^{
53
93
  [NSApp terminate:nil];
54
94
  });
@@ -56,19 +96,22 @@ public:
56
96
  return true;
57
97
  }
58
98
 
99
+ // Default bundle: .../dist/<currentId>/<Name>.app. Tagged builds use
100
+ // .../dist/.namespaces/<tag>/<currentId>/<Name>.app. In both layouts two
101
+ // parent traversals land on the folder whose children are app ids, so a
102
+ // tagged Home opens apps built in the same output namespace.
103
+ static NSString *distDirectory()
104
+ {
105
+ NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
106
+ return [[bundlePath stringByDeletingLastPathComponent] stringByDeletingLastPathComponent];
107
+ }
108
+
59
109
  private:
60
110
  std::string currentId_;
61
111
 
62
112
  static NSString *findBundleForAppId(NSString *appId)
63
113
  {
64
- // Default bundle: .../dist/<currentId>/<Name>.app. Tagged builds use
65
- // .../dist/.namespaces/<tag>/<currentId>/<Name>.app. In both layouts,
66
- // two parent traversals land on the root whose children are app ids, so a
67
- // tagged launcher opens apps built in the same output namespace.
68
- NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
69
- NSString *distDir = [[bundlePath stringByDeletingLastPathComponent]
70
- stringByDeletingLastPathComponent];
71
- NSString *appDir = [distDir stringByAppendingPathComponent:appId];
114
+ NSString *appDir = [distDirectory() stringByAppendingPathComponent:appId];
72
115
  NSError *err = nil;
73
116
  NSArray<NSString *> *entries =
74
117
  [[NSFileManager defaultManager] contentsOfDirectoryAtPath:appDir error:&err];
@@ -86,10 +129,10 @@ namespace gea::macos {
86
129
 
87
130
  void installAppLauncherPlatform(const char *currentAppId)
88
131
  {
89
- static MacosAppLauncherPlatform *instance = nullptr;
132
+ static MacosAppHost *instance = nullptr;
90
133
  if (instance) return;
91
- instance = new MacosAppLauncherPlatform(currentAppId ? currentAppId : "");
92
- gea::framework::apps::AppManager::setPlatform(instance);
134
+ instance = new MacosAppHost(currentAppId ? currentAppId : "");
135
+ gea::geaos::Launcher::setHost(instance);
93
136
  }
94
137
 
95
138
  } // namespace gea::macos
@@ -5,6 +5,7 @@
5
5
  #include "canvas.h"
6
6
  #include "host/display_orientation.h"
7
7
  #include "pixel.h"
8
+ #include "platform/prerender_capture.h"
8
9
  #include "thermalright_hid_display.h"
9
10
 
10
11
  #include <algorithm>
@@ -91,22 +92,27 @@ bool gea_macos_prepare_prerender(int width, int height)
91
92
  return true;
92
93
  }
93
94
 
94
- bool gea_macos_write_prerender_png(NSString *path)
95
+ bool gea_macos_write_prerender_png(NSString *path, const std::string &selector, bool transparent)
95
96
  {
97
+ const auto region = gea::platform::prerender::prepareCaptureRegion(
98
+ g_canvas_w, g_canvas_h, selector, transparent);
99
+ const int channels = transparent ? 4 : 3;
96
100
  NSBitmapImageRep *image = [[NSBitmapImageRep alloc]
97
- initWithBitmapDataPlanes:nullptr pixelsWide:g_canvas_w pixelsHigh:g_canvas_h
98
- bitsPerSample:8 samplesPerPixel:3 hasAlpha:NO isPlanar:NO
99
- colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
101
+ initWithBitmapDataPlanes:nullptr pixelsWide:region.width pixelsHigh:region.height
102
+ bitsPerSample:8 samplesPerPixel:channels hasAlpha:transparent isPlanar:NO
103
+ colorSpaceName:NSDeviceRGBColorSpace bitmapFormat:transparent ? NSBitmapFormatAlphaNonpremultiplied : 0
104
+ bytesPerRow:0 bitsPerPixel:0];
100
105
  if (!image) return false;
101
- for (int y = 0; y < g_canvas_h; ++y) {
106
+ for (int y = 0; y < region.height; ++y) {
102
107
  auto *row = image.bitmapData + y * image.bytesPerRow;
103
- for (int x = 0; x < g_canvas_w; ++x) {
108
+ for (int x = 0; x < region.width; ++x) {
104
109
  int r, g, b, a;
105
110
  gea::framework::graphics::pixel::unpackNative8(
106
- g_framebuffer[static_cast<size_t>(y) * g_canvas_w + x], &r, &g, &b, &a);
107
- row[x * 3] = r;
108
- row[x * 3 + 1] = g;
109
- row[x * 3 + 2] = b;
111
+ g_framebuffer[static_cast<size_t>(y + region.y) * g_canvas_w + x + region.x], &r, &g, &b, &a);
112
+ row[x * channels] = r;
113
+ row[x * channels + 1] = g;
114
+ row[x * channels + 2] = b;
115
+ if (transparent) row[x * channels + 3] = a;
110
116
  }
111
117
  }
112
118
  NSData *png = [image representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
@@ -19,7 +19,7 @@ extern void gea_macos_debugger_start();
19
19
  #include "thermalright_hid_display.h"
20
20
 
21
21
  // Optional app-owned process cleanup, before the native runtime/static teardown.
22
- // No callback on a skin/resident-app replacement; this is actual process exit.
22
+ // No callback on a skin replacement; this is actual process exit.
23
23
  extern "C" __attribute__((weak)) void gea_native_application_terminate() {}
24
24
  namespace {
25
25
  void geaRetireNativeProcess() noexcept {
@@ -39,7 +39,10 @@ struct GeaNativeTerminationGuard {
39
39
  };
40
40
  }
41
41
 
42
+ #if GEA_GEAOS
43
+ // GeaOS builds only (build-macos.sh with GEA_GEAOS=1): macos_app_platform.mm.
42
44
  namespace gea::macos { void installAppLauncherPlatform(const char *currentAppId); }
45
+ #endif
43
46
  namespace gea::macos { void installWifiDriver(); int nodeIdForView(NSView *view); }
44
47
 
45
48
  #include "app.h"
@@ -51,12 +54,6 @@ namespace gea::macos { void installWifiDriver(); int nodeIdForView(NSView *view)
51
54
  #define GEA_MACOS_PRERENDER_VIDEO 1
52
55
  #endif
53
56
  #include "platform/file_cache.h"
54
- #if __has_include("resident_apps.h")
55
- #include "resident_apps.h"
56
- #define GEA_MACOS_HAS_RESIDENT_APPS 1
57
- #else
58
- #define GEA_MACOS_HAS_RESIDENT_APPS 0
59
- #endif
60
57
  #include "ui/document.h"
61
58
  #include "ui/node.h"
62
59
  #include "ui/node_model.h"
@@ -355,6 +352,20 @@ static bool geaOwnsContourPress(int x, int y) {
355
352
  }
356
353
  @end
357
354
 
355
+ static void installStorageProviders()
356
+ {
357
+ gea::platform::storage::setMountProvider(+[]() { return true; });
358
+ gea::platform::storage::setReadPathProvider(+[](const std::string &path) -> std::string {
359
+ if (!path.starts_with("/sdcard/")) return path;
360
+ NSString *relative = [NSString stringWithUTF8String:path.c_str() + 1];
361
+ if (relative == nil || [relative.pathComponents containsObject:@".."]) return path;
362
+ NSString *resource = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:relative];
363
+ if (resource != nil && [NSFileManager.defaultManager isReadableFileAtPath:resource])
364
+ return resource.fileSystemRepresentation;
365
+ return path;
366
+ });
367
+ }
368
+
358
369
  @interface AppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate>
359
370
  @property(nonatomic, strong) NSWindow *window;
360
371
  @property(nonatomic, strong) GeaContentView *rootView;
@@ -446,7 +457,7 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
446
457
  // macOS has an available host filesystem before app initialization.
447
458
  // ImageService gates external reads on this provider just as device targets
448
459
  // gate theirs on mounted storage.
449
- gea::platform::storage::setMountProvider(+[]() { return true; });
460
+ installStorageProviders();
450
461
  const bool thermalrightTarget = gea::macos::thermalright::enabled();
451
462
  if (!thermalrightTarget) [self installMainMenu];
452
463
 
@@ -456,17 +467,26 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
456
467
  NSString *fontsDir = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Fonts"];
457
468
  gea::macos::registerCustomTtfDirectory(fontsDir);
458
469
 
459
- // Wire the AppManager platform so JSX-level Apps.launch('foo') opens
470
+ #if GEA_GEAOS
471
+ // GeaOS build: register the GeaOS host so JSX-level Apps.launch('foo') opens
460
472
  // dist/foo/Foo.app and terminates this process. Derive the current app
461
473
  // id from CFBundleIdentifier (set by Info.plist.in to com.gea.<id>).
462
- NSString *bundleId = [[NSBundle mainBundle] bundleIdentifier] ?: @"";
463
- NSString *currentId = [bundleId hasPrefix:@"com.gea."] ? [bundleId substringFromIndex:8] : @"";
464
- gea::macos::installAppLauncherPlatform(currentId.UTF8String);
474
+ {
475
+ NSString *bundleId = [[NSBundle mainBundle] bundleIdentifier] ?: @"";
476
+ NSString *currentId = [bundleId hasPrefix:@"com.gea."] ? [bundleId substringFromIndex:8] : @"";
477
+ gea::macos::installAppLauncherPlatform(currentId.UTF8String);
478
+ }
479
+ #endif
465
480
 
466
481
  if (thermalrightTarget) {
467
482
  NSLog(@"[gea-thermalright] headless display target %dx%d",
468
483
  gea::platform::display::kWidth,
469
484
  gea::platform::display::kHeight);
485
+ // Seed the timer clock with the frame clock before the program's top level
486
+ // runs: a setTimeout scheduled during init otherwise reads the host's
487
+ // steady clock (time since boot) while frames pass time since launch,
488
+ // and its deadline never arrives.
489
+ gea::host::runAnimationFrameCallbacks(gea_embedded_now_ms());
470
490
  gea::framework::app::Application::init(gea::platform::display::kWidth,
471
491
  gea::platform::display::kHeight);
472
492
  [self tick];
@@ -550,6 +570,11 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
550
570
  gea_appkit_host_attach((__bridge void *)self.rootView, size.width, size.height,
551
571
  self.window.backingScaleFactor > 0 ? self.window.backingScaleFactor : 1.0);
552
572
  gea_macos_smoke_log("[gea-macos] before Application::init");
573
+ // Seed the timer clock with the frame clock before the program's top level
574
+ // runs: a setTimeout scheduled during init otherwise reads the host's
575
+ // steady clock (time since boot) while frames pass time since launch,
576
+ // and its deadline never arrives.
577
+ gea::host::runAnimationFrameCallbacks(gea_embedded_now_ms());
553
578
  gea::framework::app::Application::init(static_cast<int>(size.width), static_cast<int>(size.height));
554
579
  gea_macos_smoke_log("[gea-macos] after Application::init");
555
580
 
@@ -703,32 +728,6 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
703
728
  std::fprintf(stderr, "[gea-macos] tick %d now=%d\n", tickCount, gea_embedded_now_ms());
704
729
  }
705
730
  }
706
- // Drain any pending resident-app launch from the previous frame BEFORE
707
- // running app::frame for this tick. When the launcher's onPress called
708
- // Apps.launch('foo'), the registry pushed 'foo' onto its pending queue;
709
- // here we pop it, select it as the new active resident, and re-run
710
- // Application::init so its __gea_top_level mounts the new UI. After this
711
- // switch, Application::frame below targets the new resident.
712
- #if GEA_MACOS_HAS_RESIDENT_APPS
713
- {
714
- char pendingId[64] = "";
715
- if (gea::framework::apps::ResidentApps::consumeLaunch(pendingId, sizeof(pendingId))) {
716
- if (gea::framework::apps::ResidentApps::select(pendingId)) {
717
- NSSize sz = gea::macos::thermalright::enabled()
718
- ? NSMakeSize(gea::platform::display::kWidth, gea::platform::display::kHeight)
719
- : self.rootView.bounds.size;
720
- gea::macos::MacosRenderer::instance().teardown();
721
- // Node ids are recycled by the next mount, so animations still
722
- // running against the outgoing app's nodes must be dropped
723
- // before it is torn down (runtime.cpp does this via
724
- // LaunchSurface). The scan below restarts them for the new app.
725
- gea::css::AnimationEngine::instance().clear();
726
- gea::framework::app::Application::init(static_cast<int>(sz.width),
727
- static_cast<int>(sz.height));
728
- }
729
- }
730
- }
731
- #endif
732
731
  static const bool profile = std::getenv("GEA_NATIVE_FRAME_PROFILE") != nullptr;
733
732
  using Clock = std::chrono::steady_clock;
734
733
  const auto applicationBegin = profile ? Clock::now() : Clock::time_point{};
@@ -744,21 +743,11 @@ static __weak AppDelegate *gGeaAppDelegate = nil;
744
743
  // loop and never compiled that file, so `data-anim` declarative animations
745
744
  // and @keyframes rules were registered and then never started or advanced —
746
745
  // every animated app rendered its first frame and froze. Mirrors
747
- // runtime.cpp: scan once per mounted app (activeId change, or exactly once
748
- // in a single-app build where activeId() is always null), then tick.
746
+ // runtime.cpp: scan once for the mounted app, then tick.
749
747
  {
750
- const char *active = nullptr;
751
- #if GEA_MACOS_HAS_RESIDENT_APPS
752
- active = gea::framework::apps::ResidentApps::activeId();
753
- #endif
754
- static char lastScannedAnim[64] = {0};
755
- static bool singleAppAnimScanned = false;
756
- const bool shouldScan = active ? std::strcmp(active, lastScannedAnim) != 0 : !singleAppAnimScanned;
757
- if (shouldScan) {
758
- if (active)
759
- std::strncpy(lastScannedAnim, active, sizeof(lastScannedAnim) - 1);
760
- else
761
- singleAppAnimScanned = true;
748
+ static bool animScanned = false;
749
+ if (!animScanned) {
750
+ animScanned = true;
762
751
  gea::css::DeclarativeAnimations::scanAndStart(gea_embedded_now_ms());
763
752
  }
764
753
  }
@@ -1257,7 +1246,7 @@ static void preparePrerenderHost()
1257
1246
  NSString *fontsDir = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"Fonts"];
1258
1247
  gea::macos::registerCustomTtfDirectory(fontsDir);
1259
1248
  gea::macos::useSoftwareTextMeasurement();
1260
- gea::platform::storage::setMountProvider(+[]() { return true; });
1249
+ installStorageProviders();
1261
1250
  }
1262
1251
 
1263
1252
  static bool loadPrerenderPage(int width, int height, double dpr)
@@ -1375,12 +1364,16 @@ static int prerenderWorker()
1375
1364
  NSNumber *heightNumber = request[@"height"] ?: @220;
1376
1365
  NSNumber *dprNumber = request[@"dpr"] ?: @1;
1377
1366
  NSNumber *reuse = request[@"reusePage"] ?: @NO;
1367
+ NSString *selector = request[@"selector"] ?: @"";
1368
+ NSNumber *transparent = request[@"transparent"] ?: @NO;
1378
1369
  if (![input isKindOfClass:NSString.class] || input.length == 0 ||
1379
1370
  ![output isKindOfClass:NSString.class] || output.length == 0 ||
1380
1371
  ![widthNumber isKindOfClass:NSNumber.class] ||
1381
1372
  ![heightNumber isKindOfClass:NSNumber.class] ||
1382
1373
  ![dprNumber isKindOfClass:NSNumber.class] ||
1383
1374
  ![reuse isKindOfClass:NSNumber.class] ||
1375
+ ![selector isKindOfClass:NSString.class] ||
1376
+ ![transparent isKindOfClass:NSNumber.class] ||
1384
1377
  widthNumber.doubleValue != widthNumber.intValue ||
1385
1378
  heightNumber.doubleValue != heightNumber.intValue ||
1386
1379
  !validPrerenderViewport(widthNumber.intValue, heightNumber.intValue, dprNumber.doubleValue)) {
@@ -1390,7 +1383,8 @@ static int prerenderWorker()
1390
1383
 
1391
1384
  const int width = widthNumber.intValue, height = heightNumber.intValue;
1392
1385
  const double dpr = dprNumber.doubleValue;
1393
- const bool reusePage = reuse.boolValue && mountedInput == input.UTF8String &&
1386
+ const bool isolated = selector.length != 0 || transparent.boolValue;
1387
+ const bool reusePage = reuse.boolValue && !isolated && mountedInput == input.UTF8String &&
1394
1388
  mountedWidth == width && mountedHeight == height && mountedDpr == dpr;
1395
1389
  const auto started = std::chrono::steady_clock::now();
1396
1390
  try {
@@ -1407,10 +1401,12 @@ static int prerenderWorker()
1407
1401
  mountedHeight = height;
1408
1402
  mountedDpr = dpr;
1409
1403
  }
1410
- if (!gea_macos_write_prerender_png(output)) {
1404
+ if (!gea_macos_write_prerender_png(output, selector.UTF8String, transparent.boolValue)) {
1405
+ mountedInput.clear();
1411
1406
  connected = writePrerenderReply(protocol, @{@"ok": @NO, @"error": @"Could not write the PNG"});
1412
1407
  continue;
1413
1408
  }
1409
+ if (isolated) mountedInput.clear();
1414
1410
  const double ms = std::chrono::duration<double, std::milli>(
1415
1411
  std::chrono::steady_clock::now() - started).count();
1416
1412
  connected = writePrerenderReply(protocol, @{@"ok": @YES, @"ms": @(ms), @"reusedPage": @(reusePage)});
@@ -1,8 +1,10 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  #pragma once
3
3
 
4
+ #include <string>
5
+
4
6
  @class NSString;
5
7
 
6
8
  bool gea_macos_prepare_prerender(int width, int height);
7
- bool gea_macos_write_prerender_png(NSString *path);
9
+ bool gea_macos_write_prerender_png(NSString *path, const std::string &selector = {}, bool transparent = false);
8
10
  void gea_macos_set_prerender_time(int timestampMs);
@@ -5,7 +5,7 @@
5
5
  // The font generator puts that set -- its raster baseline plus every
6
6
  // `--gea-font-charset` the app's CSS names -- into gea_embedded_font_generated.cpp,
7
7
  // but a windowed macOS build does not link that TU (it carries baked atlases the
8
- // window never uses), and resident builds prefix its symbols. Without this file
8
+ // window never uses). Without this file
9
9
  // the engine's weak default applies and `·`, `€`, `–` render as `?`.
10
10
  //
11
11
  // usage: runtime-glyphs.mjs --out <file.cpp> <gea_embedded_font_generated.cpp>...
@@ -11,7 +11,8 @@
11
11
  // │ is rendered here, sample-accurately scheduled and
12
12
  // │ mixed against every other live note.
13
13
  // ├─ AVAudioPlayerNode ── AudioSystem::playFile
14
- // └─ AVAudioPlayerNode ── AudioSystem::playPcm
14
+ // ├─ AVAudioPlayerNode ── AudioSystem::playPcm
15
+ // └─ AVAudioPlayerNode ── continuous PCM streams (including AudioWorklets)
15
16
  // └─ mainMixerNode ─ outputNode
16
17
  //
17
18
  // Timebase
@@ -63,18 +64,22 @@
63
64
  #include <TargetConditionals.h>
64
65
 
65
66
  #include "audio.h"
67
+ #include "audio_stream.h"
66
68
 
67
69
  #include "apple_audio_testing.h"
68
70
 
69
71
  #include <algorithm>
72
+ #include <array>
70
73
  #include <atomic>
71
74
  #include <chrono>
72
75
  #include <cmath>
76
+ #include <condition_variable>
73
77
  #include <cstdint>
74
78
  #include <cstdio>
75
79
  #include <cstdlib>
76
80
  #include <cstring>
77
81
  #include <limits>
82
+ #include <memory>
78
83
  #include <mutex>
79
84
  #include <string>
80
85
  #include <thread>
@@ -422,6 +427,7 @@ public:
422
427
  @try {
423
428
  if (filePlayer_ != nil) filePlayer_.volume = linear;
424
429
  if (pcmPlayer_ != nil) pcmPlayer_.volume = linear;
430
+ if (streamPlayer_ != nil) streamPlayer_.volume = linear;
425
431
  } @catch (NSException *exception) {
426
432
  (void)exception;
427
433
  }
@@ -494,9 +500,51 @@ public:
494
500
  }
495
501
  }
496
502
 
503
+ std::uint64_t playPcmStream(PcmStreamMixer::Pull pull)
504
+ {
505
+ if (!pull) return 0;
506
+ ensureSetup();
507
+ {
508
+ std::lock_guard<std::mutex> guard(graphMutex_);
509
+ @try {
510
+ if (streamFormat_ == nil) {
511
+ streamFormat_ = [[AVAudioFormat alloc] initWithCommonFormat:AVAudioPCMFormatFloat32
512
+ sampleRate:deviceSampleRate
513
+ channels:2
514
+ interleaved:NO];
515
+ }
516
+ if (!ensurePlayerLocked(streamPlayer_, streamPlayerFormat_, streamFormat_)) return 0;
517
+ } @catch (NSException *exception) {
518
+ (void)exception;
519
+ return 0;
520
+ }
521
+ }
522
+ const auto stream = [&] {
523
+ std::lock_guard<std::mutex> guard(streamWakeMutex_);
524
+ return streams_.add(std::move(pull));
525
+ }();
526
+ streamWake_.notify_one();
527
+ std::call_once(streamWorker_, [this] {
528
+ std::thread([this] { feedPcmStreams(); }).detach();
529
+ });
530
+ return stream;
531
+ }
532
+
533
+ void stopPcmStream(std::uint64_t stream) { streams_.remove(stream); }
534
+ bool pcmStreamSettled(std::uint64_t stream) const { return streams_.settled(stream); }
535
+
536
+ void flushPlayback()
537
+ {
538
+ std::lock_guard<std::mutex> guard(graphMutex_);
539
+ flushStreamBuffersLocked();
540
+ }
541
+
497
542
  void stopPlayback()
498
543
  {
544
+ std::lock_guard<std::mutex> streamsGuard(streamWakeMutex_);
545
+ streams_.clear();
499
546
  std::lock_guard<std::mutex> guard(graphMutex_);
547
+ flushStreamBuffersLocked();
500
548
  @try {
501
549
  if (filePlayer_ != nil) [filePlayer_ stop];
502
550
  if (pcmPlayer_ != nil) [pcmPlayer_ stop];
@@ -609,6 +657,83 @@ public:
609
657
  private:
610
658
  Engine() = default;
611
659
 
660
+ // Pull callbacks may take locks. Feed the player on a worker and leave
661
+ // the CoreAudio render callback free of application code.
662
+ void feedPcmStreams()
663
+ {
664
+ while (true) {
665
+ {
666
+ std::unique_lock<std::mutex> lock(streamWakeMutex_);
667
+ streamWake_.wait(lock, [this] { return streams_.active(); });
668
+ }
669
+ @autoreleasepool {
670
+ queuePcmStreamBuffer();
671
+ }
672
+ std::this_thread::sleep_for(std::chrono::milliseconds(4));
673
+ }
674
+ }
675
+
676
+ void flushStreamBuffersLocked()
677
+ {
678
+ // Completion callbacks can arrive after stop. Retire their counter
679
+ // along with the queued buffers so it cannot affect the next queue.
680
+ queuedStreamBuffers_ = std::make_shared<std::atomic<int>>(0);
681
+ @try {
682
+ if (streamPlayer_ != nil) [streamPlayer_ stop];
683
+ } @catch (NSException *exception) {
684
+ (void)exception;
685
+ }
686
+ }
687
+
688
+ void queuePcmStreamBuffer()
689
+ {
690
+ std::shared_ptr<std::atomic<int>> queued;
691
+ {
692
+ std::lock_guard<std::mutex> guard(graphMutex_);
693
+ queued = queuedStreamBuffers_;
694
+ if (queued->load(std::memory_order_relaxed) >= 2) return;
695
+ }
696
+ std::array<std::int16_t, PcmStreamMixer::chunkFrames * 2> samples{};
697
+ const auto frames = streams_.mix(samples.data(), PcmStreamMixer::chunkFrames);
698
+ if (frames == 0) return;
699
+
700
+ std::lock_guard<std::mutex> guard(graphMutex_);
701
+ if (queued != queuedStreamBuffers_) {
702
+ streams_.didWrite(true);
703
+ return;
704
+ }
705
+ bool submitted = false;
706
+ @try {
707
+ if (ensurePlayerLocked(streamPlayer_, streamPlayerFormat_, streamFormat_)) {
708
+ const auto count = static_cast<AVAudioFrameCount>(frames);
709
+ AVAudioPCMBuffer *buffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:streamFormat_
710
+ frameCapacity:count];
711
+ if (buffer != nil) {
712
+ buffer.frameLength = count;
713
+ float *const *channels = buffer.floatChannelData;
714
+ for (std::size_t frame = 0; frame < frames; ++frame) {
715
+ channels[0][frame] = static_cast<float>(samples[2 * frame]) / 32768.0f;
716
+ channels[1][frame] = static_cast<float>(samples[2 * frame + 1]) / 32768.0f;
717
+ }
718
+ queued->fetch_add(1, std::memory_order_relaxed);
719
+ @try {
720
+ [streamPlayer_ scheduleBuffer:buffer completionCallbackType:AVAudioPlayerNodeCompletionDataRendered
721
+ completionHandler:^(AVAudioPlayerNodeCompletionCallbackType) {
722
+ queued->fetch_sub(1, std::memory_order_relaxed);
723
+ }];
724
+ submitted = true;
725
+ } @finally {
726
+ if (!submitted) queued->fetch_sub(1, std::memory_order_relaxed);
727
+ }
728
+ if (!streamPlayer_.isPlaying) [streamPlayer_ play];
729
+ }
730
+ }
731
+ } @catch (NSException *exception) {
732
+ (void)exception;
733
+ }
734
+ streams_.didWrite(submitted);
735
+ }
736
+
612
737
  // ---- records ------------------------------------------------------------
613
738
  OscillatorRecord *find(std::uint64_t handle)
614
739
  {
@@ -1084,6 +1209,14 @@ private:
1084
1209
  AVAudioFormat *filePlayerFormat_ = nil;
1085
1210
  AVAudioPlayerNode *pcmPlayer_ = nil;
1086
1211
  AVAudioFormat *pcmPlayerFormat_ = nil;
1212
+ PcmStreamMixer streams_;
1213
+ std::mutex streamWakeMutex_;
1214
+ std::condition_variable streamWake_;
1215
+ std::once_flag streamWorker_;
1216
+ std::shared_ptr<std::atomic<int>> queuedStreamBuffers_ = std::make_shared<std::atomic<int>>(0);
1217
+ AVAudioPlayerNode *streamPlayer_ = nil;
1218
+ AVAudioFormat *streamPlayerFormat_ = nil;
1219
+ AVAudioFormat *streamFormat_ = nil;
1087
1220
  id configurationObserver_ = nil;
1088
1221
  id interruptionObserver_ = nil;
1089
1222
  };
@@ -1175,9 +1308,15 @@ bool AudioSystem::playPcm(const std::int16_t *samples, std::size_t sample_count,
1175
1308
  }
1176
1309
 
1177
1310
  void AudioSystem::stopPlayback() { Engine::instance().stopPlayback(); }
1178
- // No PCM stream output is queued by this backend (only the ESP32 runtime
1179
- // streams PCM), so a flush has nothing to discard.
1180
- void AudioSystem::flushPlayback() {}
1311
+ void AudioSystem::flushPlayback() { Engine::instance().flushPlayback(); }
1312
+
1313
+ std::uint64_t AudioSystem::playPcmStream(PcmStreamMixer::Pull pull)
1314
+ {
1315
+ return Engine::instance().playPcmStream(std::move(pull));
1316
+ }
1317
+
1318
+ void AudioSystem::stopPcmStream(std::uint64_t stream) { Engine::instance().stopPcmStream(stream); }
1319
+ bool AudioSystem::pcmStreamSettled(std::uint64_t stream) { return Engine::instance().pcmStreamSettled(stream); }
1181
1320
 
1182
1321
  namespace testing {
1183
1322