@geastack/apple 0.2.33 → 0.2.34

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,6 +1,7 @@
1
1
  // The window settings the macOS main reads from Resources/window.json: an app's
2
2
  // macos.json, overlaid with `gea.targets.macos.window` from its package.json
3
- // (size, title bar, appearance, `vsync`, `fullscreen`). Returns the JSON text,
3
+ // (size, title bar, appearance, `vsync`, `fullscreen`), plus the app's
4
+ // `cssDevicePixelRatio` for the macOS target. Returns the JSON text,
4
5
  // or '' when the app configures nothing.
5
6
  //
6
7
  // Run directly, it writes that file: node window-config.mjs <appDir> <out>
@@ -19,12 +20,16 @@ function readJson(file) {
19
20
  export function windowConfigText(appDir) {
20
21
  if (!appDir) return ''
21
22
  const file = readJson(path.join(appDir, 'macos.json'))
22
- const fromPackage = readJson(path.join(appDir, 'package.json'))?.gea?.targets?.macos?.window
23
- if (!file && !fromPackage) return ''
23
+ const gea = readJson(path.join(appDir, 'package.json'))?.gea
24
+ const fromPackage = gea?.targets?.macos?.window
25
+ // The app's CSS device pixel ratio for this target: points per CSS px.
26
+ const ratio = Number(gea?.targets?.macos?.cssDevicePixelRatio ?? gea?.cssDevicePixelRatio)
27
+ const cssDevicePixelRatio = ratio > 0 ? { cssDevicePixelRatio: ratio } : {}
28
+ if (!file && !fromPackage && !cssDevicePixelRatio.cssDevicePixelRatio) return ''
24
29
  const base = file && typeof file === 'object' ? file : {}
25
30
  // The main reads `window` when present, else the whole file (flat macos.json).
26
31
  const window = { ...(base.window ?? base), ...(fromPackage && typeof fromPackage === 'object' ? fromPackage : {}) }
27
- return `${JSON.stringify({ ...base, window }, null, 2)}\n`
32
+ return `${JSON.stringify({ ...base, ...cssDevicePixelRatio, window }, null, 2)}\n`
28
33
  }
29
34
 
30
35
  if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
@@ -265,6 +265,11 @@ public:
265
265
  double currentTime()
266
266
  {
267
267
  ensureSetup();
268
+ return engineClock();
269
+ }
270
+
271
+ double engineClock() const
272
+ {
268
273
  if (!running_.load(std::memory_order_relaxed)) return steadySeconds();
269
274
  const double rate = sampleRate_.load(std::memory_order_relaxed);
270
275
  const std::int64_t frames =
@@ -434,7 +439,12 @@ public:
434
439
  }
435
440
 
436
441
  // ---- sample playback ----------------------------------------------------
437
- bool playFile(const std::string &path)
442
+ // One file at a time on filePlayer_. A play or seek schedules the segment
443
+ // [start, length) and bumps fileGeneration_ first, so the completion
444
+ // handler of the segment it stops (AVAudioPlayerNode fires it on stop as
445
+ // well as at the end) sees a stale generation and is ignored. The handler
446
+ // runs on an AVFoundation thread and touches only atomics.
447
+ bool playFileFrom(const std::string &path, double seconds)
438
448
  {
439
449
  ensureSetup();
440
450
  if (path.empty()) return false;
@@ -447,10 +457,41 @@ public:
447
457
  NSError *error = nil;
448
458
  AVAudioFile *file = [[AVAudioFile alloc] initForReading:url error:&error];
449
459
  if (file == nil) return false;
460
+ const double rate = file.processingFormat.sampleRate;
461
+ const std::int64_t frames = static_cast<std::int64_t>(file.length);
462
+ if (!(rate > 0.0)) return false;
463
+ const std::uint64_t generation = fileGeneration_.fetch_add(1, std::memory_order_acq_rel) + 1;
464
+ fileFinished_.store(false, std::memory_order_release);
450
465
  if (filePlayer_ != nil) [filePlayer_ stop];
466
+ filePlaying_ = false;
451
467
  if (!ensurePlayerLocked(filePlayer_, filePlayerFormat_, file.processingFormat)) return false;
452
- [filePlayer_ scheduleFile:file atTime:nil completionHandler:nil];
468
+ std::int64_t start = std::isfinite(seconds) && seconds > 0.0
469
+ ? static_cast<std::int64_t>(std::llround(seconds * rate))
470
+ : 0;
471
+ start = std::min(start, frames);
472
+ file_ = file;
473
+ fileRate_ = rate;
474
+ fileFrames_ = frames;
475
+ fileStartFrame_ = start;
476
+ fileHeld_ = static_cast<double>(start) / rate;
477
+ if (start >= frames) {
478
+ fileHeld_ = static_cast<double>(frames) / rate;
479
+ fileFinished_.store(true, std::memory_order_release);
480
+ return true;
481
+ }
482
+ Engine *self = this;
483
+ [filePlayer_ scheduleSegment:file
484
+ startingFrame:static_cast<AVAudioFramePosition>(start)
485
+ frameCount:static_cast<AVAudioFrameCount>(frames - start)
486
+ atTime:nil
487
+ completionCallbackType:AVAudioPlayerNodeCompletionDataPlayedBack
488
+ completionHandler:^(AVAudioPlayerNodeCompletionCallbackType) {
489
+ if (self->fileGeneration_.load(std::memory_order_acquire) == generation)
490
+ self->fileFinished_.store(true, std::memory_order_release);
491
+ }];
492
+ fileClockStart_ = engineClock();
453
493
  [filePlayer_ play];
494
+ filePlaying_ = true;
454
495
  return true;
455
496
  } @catch (NSException *exception) {
456
497
  (void)exception;
@@ -458,6 +499,47 @@ public:
458
499
  }
459
500
  }
460
501
 
502
+ bool playFile(const std::string &path) { return playFileFrom(path, 0.0); }
503
+
504
+ double playbackPosition()
505
+ {
506
+ std::lock_guard<std::mutex> guard(graphMutex_);
507
+ return filePositionLocked();
508
+ }
509
+
510
+ bool playbackFinished()
511
+ {
512
+ std::lock_guard<std::mutex> guard(graphMutex_);
513
+ if (fileFinished_.load(std::memory_order_acquire)) return true;
514
+ // The render clock reaching the end counts too: it does not depend on
515
+ // the played-back callback, which manual rendering may never deliver.
516
+ if (filePlaying_ && fileRate_ > 0.0 &&
517
+ filePositionLocked() >= static_cast<double>(fileFrames_) / fileRate_) {
518
+ fileFinished_.store(true, std::memory_order_release);
519
+ return true;
520
+ }
521
+ return false;
522
+ }
523
+
524
+ double playbackDuration(const std::string &path) const
525
+ {
526
+ const double unknown = std::numeric_limits<double>::quiet_NaN();
527
+ if (path.empty()) return unknown;
528
+ NSURL *url = resolveURL(path);
529
+ if (url == nil) return unknown;
530
+ @try {
531
+ NSError *error = nil;
532
+ AVAudioFile *file = [[AVAudioFile alloc] initForReading:url error:&error];
533
+ if (file == nil) return unknown;
534
+ const double rate = file.processingFormat.sampleRate;
535
+ if (!(rate > 0.0)) return unknown;
536
+ return static_cast<double>(file.length) / rate;
537
+ } @catch (NSException *exception) {
538
+ (void)exception;
539
+ return unknown;
540
+ }
541
+ }
542
+
461
543
  bool playPcm(const std::int16_t *samples, std::size_t sampleCount, int sampleRate, int channels)
462
544
  {
463
545
  ensureSetup();
@@ -545,6 +627,10 @@ public:
545
627
  streams_.clear();
546
628
  std::lock_guard<std::mutex> guard(graphMutex_);
547
629
  flushStreamBuffersLocked();
630
+ if (filePlaying_) fileHeld_ = filePositionLocked();
631
+ filePlaying_ = false;
632
+ fileGeneration_.fetch_add(1, std::memory_order_acq_rel);
633
+ fileFinished_.store(false, std::memory_order_release);
548
634
  @try {
549
635
  if (filePlayer_ != nil) [filePlayer_ stop];
550
636
  if (pcmPlayer_ != nil) [pcmPlayer_ stop];
@@ -1061,6 +1147,23 @@ private:
1061
1147
  }
1062
1148
  }
1063
1149
 
1150
+ // Seconds into the current file: the segment's start plus the engine
1151
+ // render clock (AudioContext.currentTime's timebase: frames the graph has
1152
+ // rendered, a steady clock while it is not running) since play. The player
1153
+ // node's own lastRenderTime/playerTimeForNodeTime is not used: a player
1154
+ // restarted after stop() anchors its player time to the stale render time
1155
+ // of its last pull, which read hundreds of ms ahead in the offline tests.
1156
+ // Clamped to the file.
1157
+ double filePositionLocked() const
1158
+ {
1159
+ if (file_ == nil || !(fileRate_ > 0.0)) return 0.0;
1160
+ const double length = static_cast<double>(fileFrames_) / fileRate_;
1161
+ if (fileFinished_.load(std::memory_order_acquire)) return length;
1162
+ if (!filePlaying_) return fileHeld_;
1163
+ const double played = std::max(0.0, engineClock() - fileClockStart_);
1164
+ return std::min(length, static_cast<double>(fileStartFrame_) / fileRate_ + played);
1165
+ }
1166
+
1064
1167
  bool ensurePlayerLocked(AVAudioPlayerNode *__strong &player, AVAudioFormat *__strong &current,
1065
1168
  AVAudioFormat *wanted)
1066
1169
  {
@@ -1207,6 +1310,15 @@ private:
1207
1310
  AVAudioPCMBuffer *manualBuffer_ = nil;
1208
1311
  AVAudioPlayerNode *filePlayer_ = nil;
1209
1312
  AVAudioFormat *filePlayerFormat_ = nil;
1313
+ AVAudioFile *file_ = nil;
1314
+ double fileRate_ = 0.0;
1315
+ std::int64_t fileFrames_ = 0;
1316
+ std::int64_t fileStartFrame_ = 0;
1317
+ double fileHeld_ = 0.0;
1318
+ double fileClockStart_ = 0.0;
1319
+ bool filePlaying_ = false;
1320
+ std::atomic<std::uint64_t> fileGeneration_{0};
1321
+ std::atomic<bool> fileFinished_{false};
1210
1322
  AVAudioPlayerNode *pcmPlayer_ = nil;
1211
1323
  AVAudioFormat *pcmPlayerFormat_ = nil;
1212
1324
  PcmStreamMixer streams_;
@@ -1301,6 +1413,13 @@ int AudioSystem::volume() { return Engine::instance().volume(); }
1301
1413
  void AudioSystem::setVolume(int volume_percent) { Engine::instance().setVolume(volume_percent); }
1302
1414
 
1303
1415
  bool AudioSystem::playFile(const std::string &path) { return Engine::instance().playFile(path); }
1416
+ bool AudioSystem::playFileFrom(const std::string &path, double seconds)
1417
+ {
1418
+ return Engine::instance().playFileFrom(path, seconds);
1419
+ }
1420
+ double AudioSystem::playbackPosition() { return Engine::instance().playbackPosition(); }
1421
+ double AudioSystem::playbackDuration(const std::string &path) { return Engine::instance().playbackDuration(path); }
1422
+ bool AudioSystem::playbackFinished() { return Engine::instance().playbackFinished(); }
1304
1423
 
1305
1424
  bool AudioSystem::playPcm(const std::int16_t *samples, std::size_t sample_count, int sample_rate, int channels)
1306
1425
  {
@@ -176,7 +176,9 @@ audio::OscillatorNode note(double frequency, audio::OscillatorType type, double
176
176
  return oscillator;
177
177
  }
178
178
 
179
- std::string writeTestWav(double frequency, double seconds, int sampleRate)
179
+ // A second frequency, when given, takes over halfway through the file, so a
180
+ // seek can be checked by pitch.
181
+ std::string writeTestWav(double frequency, double seconds, int sampleRate, double secondFrequency = 0.0)
180
182
  {
181
183
  const char *tmp = std::getenv("TMPDIR");
182
184
  std::string path = (tmp != nullptr && tmp[0] != '\0') ? tmp : "/var/tmp";
@@ -186,7 +188,8 @@ std::string writeTestWav(double frequency, double seconds, int sampleRate)
186
188
  const int frames = static_cast<int>(seconds * sampleRate);
187
189
  std::vector<std::int16_t> samples(static_cast<std::size_t>(frames));
188
190
  for (int frame = 0; frame < frames; ++frame) {
189
- const double phase = 2.0 * M_PI * frequency * static_cast<double>(frame) / sampleRate;
191
+ const double tone = secondFrequency > 0.0 && frame >= frames / 2 ? secondFrequency : frequency;
192
+ const double phase = 2.0 * M_PI * tone * static_cast<double>(frame) / sampleRate;
190
193
  samples[static_cast<std::size_t>(frame)] = static_cast<std::int16_t>(std::sin(phase) * 12000.0);
191
194
  }
192
195
 
@@ -544,6 +547,75 @@ int main(int argc, char **argv)
544
547
  }
545
548
  }
546
549
 
550
+ // -------------------------------------------------------------- test 11b
551
+ // File position, seek and end: what HTMLAudioElement.currentTime,
552
+ // .duration, .paused and .ended are built on. One second: 500 Hz for the
553
+ // first half, 900 Hz for the second.
554
+ std::printf("\n11b. playFileFrom / playbackPosition / playbackFinished\n");
555
+ {
556
+ const std::string path = writeTestWav(500.0, 1.0, 44100, 900.0);
557
+ if (path.empty()) {
558
+ check(false, "could not write the test wav", "");
559
+ } else {
560
+ const double length = audio::AudioSystem::playbackDuration(path);
561
+ check(std::fabs(length - 1.0) < 1e-6, "playbackDuration reads the file length",
562
+ format("%.6f s", length).c_str());
563
+ check(std::isnan(audio::AudioSystem::playbackDuration("/definitely/not/here.wav")),
564
+ "playbackDuration of a missing file is NaN", "");
565
+
566
+ check(audio::AudioSystem::playFile(path), "playFile reported success", "");
567
+ render(0.30);
568
+ const double early = audio::AudioSystem::playbackPosition();
569
+ check(std::fabs(early - 0.30) < 0.03, "position follows the render clock",
570
+ format("%.4f s after 0.30 s", early).c_str());
571
+ check(!audio::AudioSystem::playbackFinished(), "not finished mid-file", "");
572
+
573
+ check(audio::AudioSystem::playFileFrom(path, 0.60), "seek while playing reported success", "");
574
+ const Capture seeked = render(0.20);
575
+ std::size_t onset = 0;
576
+ while (onset < seeked.frames() && std::fabs(seeked.left(onset)) < 1e-4) ++onset;
577
+ const double afterSeek = audio::AudioSystem::playbackPosition();
578
+ const double seekedPitch = measuredFrequency(seeked, 0.02, 0.18);
579
+ check(std::fabs(afterSeek - 0.80) < 0.03, "position continues from the seek target",
580
+ format("%.4f s, want 0.80", afterSeek).c_str());
581
+ check(std::fabs(seekedPitch - 900.0) < 8.0, "audio after the seek is the second half",
582
+ format("%.2f Hz vs 900 Hz", seekedPitch).c_str());
583
+ // stop + scheduleSegment + play takes effect on the next render
584
+ // cycle, so the gap is at most one render quantum (the offline
585
+ // 4096-frame pull here, one IO buffer on a device), never longer.
586
+ check(onset <= 4096, "seek gap is at most one render quantum", format("%zu frames", onset).c_str());
587
+
588
+ audio::AudioSystem::stopPlayback();
589
+ const double held = audio::AudioSystem::playbackPosition();
590
+ render(0.10);
591
+ check(std::fabs(audio::AudioSystem::playbackPosition() - held) < 1e-9 && std::fabs(held - 0.80) < 0.03,
592
+ "stopPlayback holds the position", format("%.4f s", held).c_str());
593
+ check(!audio::AudioSystem::playbackFinished(), "a stopped file is not finished", "");
594
+
595
+ check(audio::AudioSystem::playFileFrom(path, held), "resume from the held position", "");
596
+ render(0.30);
597
+ check(audio::AudioSystem::playbackFinished(), "finished after playing to the end", "");
598
+ check(std::fabs(audio::AudioSystem::playbackPosition() - 1.0) < 1e-9, "finished position is the length",
599
+ format("%.6f s", audio::AudioSystem::playbackPosition()).c_str());
600
+ const double tail = rms(render(0.10), 0.0, 0.10);
601
+ check(tail < 1e-6, "silent after the end", format("rms %.9f", tail).c_str());
602
+
603
+ check(audio::AudioSystem::playFileFrom(path, 5.0), "seek past the end reports success", "");
604
+ check(audio::AudioSystem::playbackFinished(), "seek past the end finishes at once", "");
605
+ check(std::fabs(audio::AudioSystem::playbackPosition() - 1.0) < 1e-9, "past-the-end position clamps to the length", "");
606
+
607
+ // stop() fires the completion handler of the segment it stops: that
608
+ // must not read as the end.
609
+ check(audio::AudioSystem::playFileFrom(path, 0.0), "replay from 0", "");
610
+ render(0.05);
611
+ check(audio::AudioSystem::playFileFrom(path, 0.25), "seek again", "");
612
+ render(0.05);
613
+ check(!audio::AudioSystem::playbackFinished(), "the stopped segment's completion is ignored", "");
614
+ audio::AudioSystem::stopPlayback();
615
+ std::remove(path.c_str());
616
+ }
617
+ }
618
+
547
619
  // --------------------------------------------------------------- test 12
548
620
  // The oscillator pool recycles: an app that creates one oscillator per note
549
621
  // forever (button-tetris does) must keep sounding indefinitely.