@peerbots/face 0.2.0 → 0.4.0

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.
package/dist/vizij.cjs CHANGED
@@ -64,7 +64,8 @@ var defaultFaceSettings = {
64
64
  captions: {
65
65
  enabled: false,
66
66
  fontSize: 32,
67
- offset: { x: 0, y: 0 }
67
+ offset: { x: 0, y: 0 },
68
+ style: "pill"
68
69
  }
69
70
  };
70
71
  function normalizeAssetBaseUrl(assetBaseUrl = "/FaceAssets") {
@@ -459,26 +460,214 @@ function estimateVisemesFromText(text, msPerChar = 65) {
459
460
  return visemes;
460
461
  }
461
462
 
463
+ // src/services/AudioManager.ts
464
+ var SILENT_WAV_DATA_URI = "data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA";
465
+ function isIOSDevice(nav) {
466
+ const target = nav ?? (typeof navigator !== "undefined" ? navigator : void 0);
467
+ if (!target) {
468
+ return false;
469
+ }
470
+ const ua = target.userAgent ?? "";
471
+ if (/iPad|iPhone|iPod/.test(ua)) {
472
+ return true;
473
+ }
474
+ return target.platform === "MacIntel" && typeof target.maxTouchPoints === "number" && target.maxTouchPoints > 1;
475
+ }
476
+ var AudioManager = class {
477
+ audioElement = null;
478
+ registeredContexts = /* @__PURE__ */ new Set();
479
+ unlocked = false;
480
+ isUnlocked() {
481
+ return this.unlocked;
482
+ }
483
+ /**
484
+ * Registers an AudioContext so `unlock()` automatically resumes it during a
485
+ * user gesture.
486
+ */
487
+ registerAudioContext(ctx) {
488
+ this.registeredContexts.add(ctx);
489
+ }
490
+ /**
491
+ * Returns the single persistent HTMLAudioElement configured for inline
492
+ * cross-origin playback on iOS / Mobile Safari.
493
+ */
494
+ getAudioElement() {
495
+ if (this.audioElement) {
496
+ return this.audioElement;
497
+ }
498
+ if (typeof Audio === "undefined") {
499
+ return null;
500
+ }
501
+ const audio = new Audio();
502
+ audio.crossOrigin = "anonymous";
503
+ audio.preload = "auto";
504
+ audio.playsInline = true;
505
+ if (typeof audio.setAttribute === "function") {
506
+ audio.setAttribute("playsinline", "true");
507
+ }
508
+ this.audioElement = audio;
509
+ return this.audioElement;
510
+ }
511
+ /**
512
+ * Unlocks audio playback on iOS / Mobile Safari. MUST be called synchronously
513
+ * inside a user-gesture event handler (e.g. click or touchstart).
514
+ */
515
+ async unlock(options = {}) {
516
+ let anySucceeded = false;
517
+ const audio = this.getAudioElement();
518
+ let audioPlayPromise = null;
519
+ if (audio) {
520
+ try {
521
+ if (audio.paused || !audio.src) {
522
+ audio.src = SILENT_WAV_DATA_URI;
523
+ }
524
+ const playResult = audio.play();
525
+ if (playResult && typeof playResult.then === "function") {
526
+ audioPlayPromise = playResult.then(
527
+ () => {
528
+ if (audio.src === SILENT_WAV_DATA_URI) {
529
+ try {
530
+ audio.pause();
531
+ audio.currentTime = 0;
532
+ } catch (pauseErr) {
533
+ void pauseErr;
534
+ }
535
+ }
536
+ anySucceeded = true;
537
+ },
538
+ (err) => {
539
+ console.warn("AudioManager silent WAV unlock warning:", err);
540
+ }
541
+ );
542
+ } else {
543
+ if (audio.src === SILENT_WAV_DATA_URI) {
544
+ try {
545
+ audio.pause();
546
+ audio.currentTime = 0;
547
+ } catch (pauseErr) {
548
+ void pauseErr;
549
+ }
550
+ }
551
+ anySucceeded = true;
552
+ }
553
+ } catch (err) {
554
+ console.warn("AudioManager audio element unlock warning:", err);
555
+ }
556
+ }
557
+ const contextsToResume = new Set(this.registeredContexts);
558
+ if (options.audioContext) {
559
+ contextsToResume.add(options.audioContext);
560
+ }
561
+ const resumePromises = [];
562
+ for (const ctx of contextsToResume) {
563
+ if (ctx.state === "suspended" && typeof ctx.resume === "function") {
564
+ resumePromises.push(
565
+ ctx.resume().then(
566
+ () => {
567
+ anySucceeded = true;
568
+ },
569
+ (err) => {
570
+ console.warn("AudioManager AudioContext resume warning:", err);
571
+ }
572
+ )
573
+ );
574
+ }
575
+ }
576
+ if (typeof window !== "undefined" && "speechSynthesis" in window && typeof SpeechSynthesisUtterance !== "undefined") {
577
+ try {
578
+ if (window.speechSynthesis.paused) {
579
+ window.speechSynthesis.resume();
580
+ }
581
+ const utterance = new SpeechSynthesisUtterance("");
582
+ utterance.volume = 0;
583
+ window.speechSynthesis.speak(utterance);
584
+ anySucceeded = true;
585
+ } catch (err) {
586
+ console.warn("AudioManager speechSynthesis prime warning:", err);
587
+ }
588
+ }
589
+ if (audioPlayPromise) {
590
+ await audioPlayPromise;
591
+ }
592
+ if (resumePromises.length > 0) {
593
+ await Promise.all(resumePromises);
594
+ }
595
+ if (anySucceeded) {
596
+ this.unlocked = true;
597
+ }
598
+ return this.unlocked;
599
+ }
600
+ /**
601
+ * Resets internal state (primarily for unit testing).
602
+ */
603
+ reset() {
604
+ if (this.audioElement) {
605
+ try {
606
+ this.audioElement.pause();
607
+ } catch (err) {
608
+ void err;
609
+ }
610
+ }
611
+ this.audioElement = null;
612
+ this.registeredContexts.clear();
613
+ this.unlocked = false;
614
+ }
615
+ };
616
+ var audioManager = new AudioManager();
617
+
462
618
  // src/services/AudioAnalyzer.ts
463
619
  var AudioAnalyzer = class {
464
620
  ctx = null;
465
621
  analyzer = null;
466
622
  data = null;
467
623
  connectedElements = /* @__PURE__ */ new WeakSet();
468
- connect(audio) {
624
+ getContext() {
625
+ return this.ctx;
626
+ }
627
+ async resumeContext() {
628
+ if (!this.ctx) {
629
+ return false;
630
+ }
631
+ if (this.ctx.state === "suspended" && typeof this.ctx.resume === "function") {
632
+ try {
633
+ await this.ctx.resume();
634
+ } catch (error) {
635
+ console.warn("AudioAnalyzer resumeContext error:", error);
636
+ return false;
637
+ }
638
+ }
639
+ return this.ctx.state !== "suspended";
640
+ }
641
+ connect(audio, options = {}) {
469
642
  if (typeof window === "undefined") {
470
- return;
643
+ return false;
644
+ }
645
+ if (!options.force && isIOSDevice()) {
646
+ return false;
471
647
  }
472
648
  const AudioContextCtor = window.AudioContext || window.webkitAudioContext;
473
649
  if (!AudioContextCtor) {
474
- return;
650
+ return false;
475
651
  }
476
652
  try {
477
653
  if (!this.ctx) {
478
654
  this.ctx = new AudioContextCtor();
655
+ audioManager.registerAudioContext(this.ctx);
656
+ }
657
+ if (this.ctx.state === "suspended") {
658
+ if (typeof this.ctx.resume === "function") {
659
+ void this.ctx.resume().catch((err) => {
660
+ console.warn("AudioAnalyzer AudioContext resume warning:", err);
661
+ });
662
+ }
663
+ return false;
664
+ }
665
+ if (!this.analyzer) {
479
666
  this.analyzer = this.ctx.createAnalyser();
480
667
  this.analyzer.fftSize = 256;
481
- this.data = new Uint8Array(new ArrayBuffer(this.analyzer.frequencyBinCount));
668
+ this.data = new Uint8Array(
669
+ new ArrayBuffer(this.analyzer.frequencyBinCount)
670
+ );
482
671
  }
483
672
  if (!this.connectedElements.has(audio) && this.analyzer) {
484
673
  const source = this.ctx.createMediaElementSource(audio);
@@ -486,12 +675,14 @@ var AudioAnalyzer = class {
486
675
  this.analyzer.connect(this.ctx.destination);
487
676
  this.connectedElements.add(audio);
488
677
  }
678
+ return true;
489
679
  } catch (error) {
490
680
  console.warn("AudioAnalyzer connect error:", error);
681
+ return false;
491
682
  }
492
683
  }
493
684
  getAmplitude() {
494
- if (!this.analyzer || !this.data) {
685
+ if (!this.analyzer || !this.data || this.ctx?.state === "suspended") {
495
686
  return 0;
496
687
  }
497
688
  this.analyzer.getByteTimeDomainData(this.data);
@@ -736,6 +927,12 @@ var FALLBACK_DEFAULT_VOICE = {
736
927
  name: "en-US-Standard-B",
737
928
  voiceURI: "en-US-Standard-B"
738
929
  };
930
+ function isNotAllowedError(err) {
931
+ if (!err || typeof err !== "object") {
932
+ return false;
933
+ }
934
+ return err.name === "NotAllowedError";
935
+ }
739
936
  function isNativeSpeechSynthesisVoice(voice) {
740
937
  if (!voice || typeof voice !== "object") {
741
938
  return false;
@@ -766,6 +963,7 @@ function createFaceSpeechSlice(sliceOptions = {}) {
766
963
  let adapter = sliceOptions.speechAdapter ?? null;
767
964
  const cache = sliceOptions.ttsCache === false ? null : sliceOptions.ttsCache ?? defaultTtsAudioCache;
768
965
  const analyzer = sliceOptions.audioAnalyzer ?? audioAnalyzer;
966
+ const speechAudioManager = sliceOptions.audioManager ?? audioManager;
769
967
  const utteranceDeferMs = sliceOptions.utteranceDeferMs ?? 10;
770
968
  let activeAudio = null;
771
969
  let activeObjectUrl = null;
@@ -928,11 +1126,20 @@ function createFaceSpeechSlice(sliceOptions = {}) {
928
1126
  playbackUrl = synthesized.audioUrl;
929
1127
  }
930
1128
  }
931
- if (playbackUrl && typeof Audio !== "undefined") {
1129
+ const audio = playbackUrl ? speechAudioManager.getAudioElement() : null;
1130
+ if (playbackUrl && audio) {
932
1131
  get().setSpokenVisemes(visemes);
933
1132
  get().setAmplitudeData(ampData, extrema);
934
- const audio = new Audio(playbackUrl);
935
- audio.crossOrigin = "anonymous";
1133
+ audio.onplay = null;
1134
+ audio.onended = null;
1135
+ audio.onerror = null;
1136
+ try {
1137
+ audio.pause();
1138
+ audio.currentTime = 0;
1139
+ } catch (resetErr) {
1140
+ void resetErr;
1141
+ }
1142
+ audio.src = playbackUrl;
936
1143
  activeAudio = audio;
937
1144
  if (shouldRevokeUrl) {
938
1145
  activeObjectUrl = playbackUrl;
@@ -964,7 +1171,19 @@ function createFaceSpeechSlice(sliceOptions = {}) {
964
1171
  audio.onerror = () => {
965
1172
  finishGeneration(myGeneration);
966
1173
  };
967
- await audio.play();
1174
+ try {
1175
+ await audio.play();
1176
+ } catch (playError) {
1177
+ if (isNotAllowedError(playError)) {
1178
+ console.warn(
1179
+ "Audio playback blocked by browser autoplay policy (NotAllowedError); prompting user to re-enable sound."
1180
+ );
1181
+ get().setSpeechAllowed(false);
1182
+ finishGeneration(myGeneration);
1183
+ return;
1184
+ }
1185
+ throw playError;
1186
+ }
968
1187
  return;
969
1188
  }
970
1189
  } catch (adapterError) {
@@ -1070,6 +1289,16 @@ function createFaceSpeechSlice(sliceOptions = {}) {
1070
1289
  setSpeechAllowed: (allowed) => {
1071
1290
  set({ speechAllowed: allowed });
1072
1291
  },
1292
+ unlockAudio: async () => {
1293
+ const unlockPromise = speechAudioManager.unlock({
1294
+ audioContext: analyzer.getContext()
1295
+ });
1296
+ set({ speechAllowed: true });
1297
+ void get().refreshVoices();
1298
+ const unlocked = await unlockPromise;
1299
+ await analyzer.resumeContext();
1300
+ return unlocked;
1301
+ },
1073
1302
  setAvailableVoices: (voices) => {
1074
1303
  set({ availableVoices: voices });
1075
1304
  },
@@ -1356,6 +1585,9 @@ var DEFAULT_FACE_UI_LABELS = {
1356
1585
  interruptSpeech: "Interrupt current speech",
1357
1586
  queueSpeech: "Queue after current speech",
1358
1587
  captions: "Captions",
1588
+ captionStyle: "Caption Style",
1589
+ captionStylePill: "Dark Pill",
1590
+ captionStyleOutline: "Text Outline",
1359
1591
  fontSize: "Caption Font Size",
1360
1592
  verticalPosition: "Vertical Position",
1361
1593
  voiceSelectorLanguage: "Language",