-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathscratch.diff
More file actions
1600 lines (1566 loc) · 60.4 KB
/
Copy pathscratch.diff
File metadata and controls
1600 lines (1566 loc) · 60.4 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
diff --git c/ember-stereo/package.json w/ember-stereo/package.json
index 527c8ab..861f770 100644
--- c/ember-stereo/package.json
+++ w/ember-stereo/package.json
@@ -132,9 +132,11 @@
"./-private/utils/untracked-object-cache.js": "./dist/_app_/-private/utils/untracked-object-cache.js",
"./-private/utils/url-cache.js": "./dist/_app_/-private/utils/url-cache.js",
"./helpers/autoplay-allowed.js": "./dist/_app_/helpers/autoplay-allowed.js",
+ "./helpers/casting-available.js": "./dist/_app_/helpers/casting-available.js",
"./helpers/current-sound.js": "./dist/_app_/helpers/current-sound.js",
"./helpers/fastforward-sound.js": "./dist/_app_/helpers/fastforward-sound.js",
"./helpers/find-sound.js": "./dist/_app_/helpers/find-sound.js",
+ "./helpers/is-casting.js": "./dist/_app_/helpers/is-casting.js",
"./helpers/json-stringify.js": "./dist/_app_/helpers/json-stringify.js",
"./helpers/load-sound.js": "./dist/_app_/helpers/load-sound.js",
"./helpers/numeric-duration.js": "./dist/_app_/helpers/numeric-duration.js",
@@ -162,6 +164,7 @@
"./helpers/stop-sound.js": "./dist/_app_/helpers/stop-sound.js",
"./helpers/toggle-play-sound.js": "./dist/_app_/helpers/toggle-play-sound.js",
"./helpers/toggle-stereo-mute.js": "./dist/_app_/helpers/toggle-stereo-mute.js",
+ "./modifiers/cast-button.js": "./dist/_app_/modifiers/cast-button.js",
"./modifiers/sound-position-progress.js": "./dist/_app_/modifiers/sound-position-progress.js",
"./modifiers/sound-position-slider.js": "./dist/_app_/modifiers/sound-position-slider.js",
"./modifiers/stereo-volume.js": "./dist/_app_/modifiers/stereo-volume.js",
@@ -169,6 +172,7 @@
"./stereo-connections/base.js": "./dist/_app_/stereo-connections/base.js",
"./stereo-connections/hls.js": "./dist/_app_/stereo-connections/hls.js",
"./stereo-connections/howler.js": "./dist/_app_/stereo-connections/howler.js",
+ "./stereo-connections/native-audio-casting.js": "./dist/_app_/stereo-connections/native-audio-casting.js",
"./stereo-connections/native-audio.js": "./dist/_app_/stereo-connections/native-audio.js"
}
},
diff --git c/ember-stereo/src/-private/utils/sound.js w/ember-stereo/src/-private/utils/sound.js
index d705d6d..60c2bfa 100644
--- c/ember-stereo/src/-private/utils/sound.js
+++ w/ember-stereo/src/-private/utils/sound.js
@@ -23,8 +23,17 @@ export default class Sound extends Evented {
@tracked failures = [];
@tracked _value = null;
@tracked _volume;
+ @tracked _castUrl = null;
@tracked _debug = {};
+ // The *intended* play state, owned by the identity-stable Sound so it survives
+ // a backend swap. Updated by explicit play/pause/togglePause and by a real
+ // audio-played — but NOT by a backend's involuntary pause (e.g. an AirPlay
+ // route drop pausing the outlet element). The swap restores this, so play
+ // state is preserved across engage/disengage instead of following whichever
+ // connection happened to be paused at handoff time.
+ _playIntent = false;
+
// Bound event-relay handlers, keyed by event name, so the exact same
// function reference can be passed to both `on` and `off`. Re-binding on
// unregister (the previous bug) meant relays were never actually removed.
@@ -55,6 +64,18 @@ export default class Sound extends Evented {
return this.value?.url ?? this.identifier;
}
+ // The device-fetchable URL to hand an AirPlay/cast outlet, which differs from
+ // the playback url: an HLS/MSE stream can't be cast, so casting plays a public
+ // (live) or token-signed (archive) variant natively on the device. Supplied by
+ // the app (it knows the variant); defaults to the playback url for plain files.
+ get castUrl() {
+ return this._castUrl ?? this.url;
+ }
+
+ set castUrl(value) {
+ this._castUrl = value;
+ }
+
get value() {
return this._value;
}
@@ -116,13 +137,27 @@ export default class Sound extends Evented {
get metadata() {
// Once resolved, defer to the connection so the Sound and its backend agree
- // (the connection keys metadata by its resolved url).
+ // (the connection keys metadata by its resolved url). But a cast connection
+ // is keyed by the cast url, which has no metadata of its own — fall back to
+ // the identifier (the playback url the app keyed metadata under). Never
+ // null/undefined — consumers destructure it (e.g. now-playing).
if (this.value) {
- return this.value.metadata;
+ let connectionMetadata = this.value.metadata;
+ if (connectionMetadata && Object.keys(connectionMetadata).length > 0) {
+ return connectionMetadata;
+ }
}
return this.stereo?.metadataCache?.find(this.identifier) ?? {};
}
+ // The backing media element, when the connection exposes one (NativeAudio, the
+ // AirPlay outlet). Delegated so consumers that reach for it off a relayed event
+ // — e.g. the visualizer's `sound.audioElement` — get the connection's element
+ // rather than `undefined` on the proxy.
+ get audioElement() {
+ return this.value?.audioElement;
+ }
+
set metadata(value) {
if (this.value) {
this.value.metadata = value;
@@ -137,27 +172,64 @@ export default class Sound extends Evented {
return this.loadTask.perform(loadOptions);
}
- loadTask = task({ restartable: true }, async (loadOptions = {}) => {
- // Already resolved and healthy — behave like a cache hit.
- if (this.isResolved && !this.value.isErrored) {
- return this.value;
- }
+ // Does the resolved backend match the current cast state (cast while casting,
+ // local while not)?
+ _castStateMatches() {
+ let valueIsCast = this.stereo._isCastConnection(this.value);
+ return this.stereo.isCasting === valueIsCast;
+ }
+ loadTask = task({ restartable: true }, async (loadOptions = {}) => {
let options = this.stereo.prepareLoadOptions({
...this.options,
...loadOptions,
});
+
+ // The app may hand us a device-fetchable cast URL alongside the playback
+ // urls (it knows the live/archive variant). Keep it, and make it available
+ // to the strategy builder even when it was set earlier (e.g. by prewarm)
+ // rather than passed in these options.
+ if (options.castUrl != null) {
+ this._castUrl = options.castUrl;
+ } else if (this._castUrl != null) {
+ options.castUrl = this._castUrl;
+ }
+
+ // Already resolved and healthy AND on the right backend for the cast state —
+ // behave like a cache hit. If it's on the WRONG side (local while casting, or
+ // cast while not), swap to the correct backend rather than returning a stale
+ // connection (which would play locally under a cast, or vice-versa).
+ if (this.isResolved && !this.value.isErrored) {
+ if (this._castStateMatches()) {
+ return this.value;
+ }
+ let target = this.stereo.isCasting
+ ? options.castUrl
+ ? this.stereo._buildCastConnection(options.castUrl, this.metadata)
+ : null
+ : this.stereo._buildLocalConnection(this);
+ if (target) {
+ return await this.swap(target);
+ }
+ return this.value;
+ }
+
let urls = await this.stereo.urlCache.resolve(this.identifier);
// Adopt a connection already loaded for these urls (shared sound cache)
- // rather than building a duplicate one.
- let cachedConnection = this.stereo.findLoadedSound(urls);
- if (cachedConnection) {
- this.value = cachedConnection;
- return cachedConnection;
+ // rather than building a duplicate — but NOT while casting, where we must
+ // resolve through the cast strategy rather than a stale local connection.
+ if (!this.stereo.isCasting) {
+ let cachedConnection = this.stereo.findLoadedSound(urls);
+ if (cachedConnection) {
+ this.value = cachedConnection;
+ return cachedConnection;
+ }
}
- if (!this.strategies) {
+ // Rebuild while casting so the cast strategy is (re)injected at the top;
+ // otherwise reuse the cached list.
+ if (!this.strategies || this.stereo.isCasting) {
this.strategies = this.stereo._buildStrategies(urls, options);
this._debug = this.strategies;
}
@@ -247,7 +319,28 @@ export default class Sound extends Evented {
// Source-identity arbitration: drop the outgoing connection's relays before
// detaching it, so its teardown pause/ended events never reach the Sound.
this.value = null;
- outgoing?.detach();
+ // Stop the outgoing's audible playback before releasing it, or it keeps
+ // playing alongside the new backend (a local stream bleeding under a cast).
+ // detach()/teardown() alone don't pause the element, and pause() can fail to
+ // stop a shared element — so also pause the element directly. Each step is
+ // independently guarded: a throw in one must not skip the others (and must
+ // not abort the swap).
+ let outgoingElement = outgoing?.audioElement;
+ try {
+ outgoing?.pause?.();
+ } catch (e) {
+ debug('ember-stereo:sound')(`outgoing pause errored: ${e?.message}`);
+ }
+ try {
+ outgoingElement?.pause?.();
+ } catch (e) {
+ debug('ember-stereo:sound')(`outgoing element pause errored: ${e?.message}`);
+ }
+ try {
+ outgoing?.detach?.();
+ } catch (e) {
+ debug('ember-stereo:sound')(`outgoing detach errored: ${e?.message}`);
+ }
let incoming = targetConnection;
let engaged = false;
@@ -263,13 +356,28 @@ export default class Sound extends Evented {
return null;
}
- if (handoff.position != null && incoming.isSeekable) {
- incoming.position = handoff.position;
+ if (handoff.position != null) {
+ if (incoming.isSeekable) {
+ incoming.position = handoff.position;
+ } else if (typeof incoming.seedPosition === 'function') {
+ // Not seekable (a live stream): can't seek to a past point, but seed
+ // the connection's clock so elapsed continues across the swap instead
+ // of restarting at zero.
+ incoming.seedPosition(handoff.position);
+ }
}
this.value = incoming;
engaged = true;
+ // Keep the service caches consistent with the new backend: register the
+ // incoming connection so oneAtATime arbitrates it and the sound cache can
+ // find it. (The outgoing was already detached above.) A cast connection
+ // that loses control falls back to its internal clone, so oneAtATime
+ // pausing a stale one can't pause the live route.
+ this.stereo?.soundCache?.cache(incoming);
+ this.stereo?.oneAtATime?.register(incoming);
+
if (handoff.isPlaying) {
await incoming.play();
}
@@ -281,7 +389,11 @@ export default class Sound extends Evented {
// its element/HLS instance doesn't leak. (The handoff is intentionally
// left intact for a superseding swap to reuse.)
if (!engaged && incoming && !incoming.isDestroyed) {
- incoming.detach();
+ try {
+ incoming.detach();
+ } catch (e) {
+ debug('ember-stereo:sound')(`incoming detach errored: ${e?.message}`);
+ }
}
}
});
@@ -290,7 +402,10 @@ export default class Sound extends Evented {
let connection = this.value;
return {
position: connection?.position,
- isPlaying: connection?.isPlaying ?? false,
+ // Use the Sound's intent, not the connection's live isPlaying: a route drop
+ // pauses the outgoing connection before we get here, but the user still
+ // intends playback, so the swapped-in backend should resume.
+ isPlaying: this._playIntent,
};
}
@@ -309,6 +424,12 @@ export default class Sound extends Evented {
}
_relayEvent(eventName, info = {}) {
+ // A real play (e.g. the initial load plays the connection directly, not via
+ // the entity) reflects intent to play. Involuntary pauses are deliberately
+ // NOT mirrored here — only explicit pause/stop/togglePause clear intent.
+ if (eventName === 'audio-played') {
+ this._playIntent = true;
+ }
this.trigger(eventName, { ...info, sound: this });
}
@@ -333,18 +454,24 @@ export default class Sound extends Evented {
// --- Proxied playback methods/state (delegated to the connection) ---
play(...args) {
+ this._playIntent = true;
return this.value?.play(...args);
}
pause(...args) {
+ this._playIntent = false;
return this.value?.pause(...args);
}
stop(...args) {
+ this._playIntent = false;
return this.value?.stop(...args);
}
togglePause(...args) {
+ // Capture intent from the state we're toggling away from (before the
+ // connection flips it).
+ this._playIntent = !this.isPlaying;
return this.value?.togglePause(...args);
}
diff --git c/ember-stereo/src/helpers/casting-available.js w/ember-stereo/src/helpers/casting-available.js
new file mode 100644
index 0000000..b56bf1c
--- /dev/null
+++ w/ember-stereo/src/helpers/casting-available.js
@@ -0,0 +1,15 @@
+import { service } from '@ember/service';
+import Helper from '@ember/component/helper';
+
+/**
+ * `{{casting-available}}` — true when a cast target (AirPlay/Cast) is reachable.
+ *
+ * @class CastingAvailableHelper
+ */
+export default class CastingAvailable extends Helper {
+ @service stereo;
+
+ compute() {
+ return this.stereo.isCastingAvailable;
+ }
+}
diff --git c/ember-stereo/src/helpers/is-casting.js w/ember-stereo/src/helpers/is-casting.js
new file mode 100644
index 0000000..7db13a8
--- /dev/null
+++ w/ember-stereo/src/helpers/is-casting.js
@@ -0,0 +1,15 @@
+import { service } from '@ember/service';
+import Helper from '@ember/component/helper';
+
+/**
+ * `{{is-casting}}` — true while audio is routed to a remote device (AirPlay/Cast).
+ *
+ * @class IsCastingHelper
+ */
+export default class IsCasting extends Helper {
+ @service stereo;
+
+ compute() {
+ return this.stereo.isCasting;
+ }
+}
diff --git c/ember-stereo/src/modifiers/cast-button.js w/ember-stereo/src/modifiers/cast-button.js
new file mode 100644
index 0000000..f49a80d
--- /dev/null
+++ w/ember-stereo/src/modifiers/cast-button.js
@@ -0,0 +1,70 @@
+import { service } from '@ember/service';
+import Modifier from 'ember-modifier';
+import { registerDestructor } from '@ember/destroyable';
+
+// Service events that should refresh the button's enabled/casting state.
+const CAST_EVENTS = [
+ 'audio-cast-availability-changed',
+ 'audio-cast-connected',
+ 'audio-cast-disconnected',
+];
+
+/**
+ * `{{cast-button identifier}}` — turns an element into a cast control. Clicking
+ * opens the device picker for the given sound (or the current sound); the
+ * element is disabled while no cast target is available and gets a `casting`
+ * class while a route is engaged.
+ *
+ * @class CastButtonModifier
+ * @extends Modifier
+ */
+export default class CastButtonModifier extends Modifier {
+ @service stereo;
+
+ element = null;
+ identifier = null;
+
+ constructor(owner, args) {
+ super(owner, args);
+ this._onClick = this._handleClick.bind(this);
+ this._updateState = this._updateButtonState.bind(this);
+ registerDestructor(this, () => this._cleanup());
+ }
+
+ modify(element, positional) {
+ this.element = element;
+ this.identifier = positional[0];
+
+ if (!this._wired) {
+ element.addEventListener('click', this._onClick);
+ CAST_EVENTS.forEach((event) => this.stereo.on(event, this._updateState));
+ this._wired = true;
+ }
+
+ this._updateButtonState();
+ }
+
+ _handleClick(event) {
+ event.preventDefault();
+ if (this.stereo.isCastingAvailable) {
+ this.stereo.showCastMenu(this.identifier);
+ }
+ }
+
+ _updateButtonState() {
+ let element = this.element;
+ if (!element) {
+ return;
+ }
+
+ element.disabled = !this.stereo.isCastingAvailable;
+ element.classList.toggle('casting', this.stereo.isCasting);
+ }
+
+ _cleanup() {
+ if (this.element) {
+ this.element.removeEventListener('click', this._onClick);
+ }
+ CAST_EVENTS.forEach((event) => this.stereo.off(event, this._updateState));
+ }
+}
diff --git c/ember-stereo/src/services/stereo.js w/ember-stereo/src/services/stereo.js
index 0dd3fdb..c719c26 100644
--- c/ember-stereo/src/services/stereo.js
+++ w/ember-stereo/src/services/stereo.js
@@ -6,6 +6,8 @@ import { assert } from '@ember/debug';
import {
race,
task,
+ timeout,
+ forever,
waitForProperty,
waitForEvent,
didCancel,
@@ -15,6 +17,7 @@ import { isTesting, macroCondition } from '@embroider/macros';
import canAutoplay from 'can-autoplay';
import debug from 'debug';
import config from 'ember-get-config';
+import { TrackedSet } from 'tracked-built-ins';
import EmberEvented from '@ember/object/evented';
import ErrorCache from '../-private/utils/error-cache';
@@ -25,10 +28,13 @@ import SharedAudioAccess from '../-private/utils/shared-audio-access';
import SoundCache from '../-private/utils/sound-cache';
import UntrackedObjectCache from '../-private/utils/untracked-object-cache';
import Strategizer from '../-private/utils/strategizer';
+import Strategy from '../-private/utils/strategy';
import StereoUrl from '../-private/utils/stereo-url';
import Sound from '../-private/utils/sound';
import ConnectionLoader from '../-private/utils/connection-loader';
import BaseSound from '../stereo-connections/base';
+import NativeAudioCasting from '../stereo-connections/native-audio-casting';
+import hasEqualUrls from '../-private/utils/has-equal-urls';
import { EVENT_MAP, SERVICE_EVENT_MAP } from '../-private/utils/event-map';
export { EVENT_MAP, SERVICE_EVENT_MAP };
@@ -88,7 +94,9 @@ export default class Stereo extends Service.extend(EmberEvented) {
// no checks for autoplay as it messes with the fake media element
} else {
this._determineAutoplayPermissions();
+ this._detectCastingAvailabilityTask.perform();
}
+
this.isReady = true;
}
@@ -154,7 +162,13 @@ export default class Stereo extends Service.extend(EmberEvented) {
* @public
*/
get currentMetadata() {
- return this.metadataCache.find(this.currentSound?.url);
+ // While casting, the backend's url is the cast URL, which has no metadata of
+ // its own — fall back to the Sound's identifier (the playback url the app
+ // keyed now-playing metadata under).
+ return (
+ this.metadataCache.find(this.currentSound?.url) ||
+ this.metadataCache.find(this.currentSound?.identifier)
+ );
}
/**
@@ -295,6 +309,25 @@ export default class Stereo extends Service.extend(EmberEvented) {
@tracked isMobileDevice = 'ontouchstart' in window;
+ /**
+ * Is audio currently routed to a remote device (AirPlay/Cast)?
+ * @property isCasting
+ * @type {Boolean}
+ * @readOnly
+ * @public
+ */
+ @tracked isCasting = false;
+
+ /**
+ * Name of the current cast device, when the platform exposes it (WebKit
+ * AirPlay does not, so this is usually null while AirPlaying).
+ * @property castDeviceName
+ * @type {String}
+ * @readOnly
+ * @public
+ */
+ @tracked castDeviceName = null;
+
/**
* get if hifi should use a shared audio element
*
@@ -653,6 +686,414 @@ export default class Stereo extends Service.extend(EmberEvented) {
return await this.urlCache.resolve(identifier);
});
+ /* ----------------------------- CASTING ------------------------------------ */
+ /* -------------------------------------------------------------------------- */
+ /*
+ * Casting routes audio to a remote device (AirPlay today). It is just another
+ * connection: `NativeAudioCasting` (a `NativeAudio` that drives the single,
+ * route-holding `<audio x-webkit-airplay>` outlet element via the standard
+ * `SharedAudioAccess` ownership handshake). The route lives on that element and
+ * outlives every airing.
+ *
+ * - availability detection + the picker drive the cast control,
+ * - when a route engages we swap the current sound's backend for a
+ * `NativeAudioCasting` (`currentSound.swap(cast)`); the identity-stable Sound
+ * stays put, so the app's transport follows the remote clock with no fork,
+ * - while casting, `_buildStrategies` force-injects the cast connection at the
+ * top of the waterfall, so any *new* sound (a feed switch) resolves straight
+ * to the device automatically — and the SharedAudioAccess handshake stops the
+ * previously-cast sound when the new one takes the element,
+ * - on disengage we rebuild a local connection and swap back.
+ *
+ * The one thing the addon can't know is the device-fetchable URL (a public/
+ * signed variant of the stream); the app supplies it as `sound.castUrl`.
+ */
+
+ // The set of available cast transports ('general' = Remote Playback API,
+ // 'airplay' = WebKit). Non-empty ⇒ casting is offerable.
+ castingTypes = new TrackedSet();
+
+ /**
+ * Is casting available in this browser/network right now?
+ * @property isCastingAvailable
+ * @type {Boolean}
+ * @readOnly
+ * @public
+ */
+ get isCastingAvailable() {
+ return this.castingTypes.size > 0;
+ }
+
+ // The persistent route element. Created lazily, hosted offscreen, and never
+ // torn down across airings — the AirPlay route lives on it.
+ get castOutletElement() {
+ if (!this._castOutletElement) {
+ let element = document.createElement('audio');
+ element.setAttribute('x-webkit-airplay', 'allow');
+ element.setAttribute('crossorigin', 'anonymous');
+ element.setAttribute('preload', 'metadata');
+ if ('disableRemotePlayback' in element) {
+ element.disableRemotePlayback = false;
+ }
+
+ element.addEventListener(
+ 'webkitcurrentplaybacktargetiswirelesschanged',
+ () => this._onCastTargetChange(!!element.webkitCurrentPlaybackTargetIsWireless)
+ );
+ if (element.remote) {
+ element.remote.onconnect = () => this._onCastTargetChange(true);
+ element.remote.ondisconnect = () => this._onCastTargetChange(false);
+ }
+
+ // A real DOM node gets hosted offscreen so the route is genuine; the test
+ // fake isn't a Node, so skip hosting there.
+ if (element instanceof Node) {
+ this._castOutletHost().appendChild(element);
+ }
+
+ this._castOutletElement = element;
+ }
+ return this._castOutletElement;
+ }
+
+ _castOutletHost() {
+ let id = 'ember-stereo-cast-outlet';
+ let host = document.getElementById(id);
+ if (!host) {
+ host = document.createElement('div');
+ host.setAttribute('id', id);
+ host.setAttribute('aria-hidden', 'true');
+ host.style.position = 'absolute';
+ host.style.width = '1px';
+ host.style.height = '1px';
+ host.style.overflow = 'hidden';
+ host.style.clip = 'rect(0 0 0 0)';
+ host.style.pointerEvents = 'none';
+ document.body.appendChild(host);
+ }
+ return host;
+ }
+
+ _detectCastingAvailabilityTask = task({ maxConcurrency: 1 }, async () => {
+ let element = this.castOutletElement;
+ try {
+ if (element.remote && typeof element.remote.watchAvailability === 'function') {
+ element.remote.watchAvailability((available) => {
+ if (available) {
+ this.castingTypes.add('general');
+ } else {
+ this.castingTypes.delete('general');
+ }
+ this._triggerCastAvailabilityChanged();
+ });
+ }
+
+ if ('webkitShowPlaybackTargetPicker' in element) {
+ element.addEventListener(
+ 'webkitplaybacktargetavailabilitychanged',
+ (event) => {
+ if (event.availability === 'available') {
+ this.castingTypes.add('airplay');
+ } else {
+ this.castingTypes.delete('airplay');
+ }
+ this._triggerCastAvailabilityChanged();
+ }
+ );
+ }
+
+ // In case a route already exists on load (a reattached session), sync
+ // once now; the settle task keeps it reconciled thereafter.
+ this._reconcileCastState();
+
+ await forever;
+ } finally {
+ element.remote?.cancelWatchAvailability?.();
+ }
+ });
+
+ _triggerCastAvailabilityChanged() {
+ debug('ember-stereo:service')(
+ `cast availability: ${[...this.castingTypes]}`
+ );
+ this.trigger('audio-cast-availability-changed', {
+ available: this.isCastingAvailable,
+ });
+ }
+
+ /**
+ * Load a sound's cast URL onto the outlet ahead of the picker click, so Safari
+ * (which won't open a picker for an element with no parsed source) has media
+ * to offer. The app calls this when the cast control mounts; for an archive it
+ * resolves the signed URL and sets `sound.castUrl` first.
+ *
+ * @method prewarmCast
+ * @param {Array|String|Sound} identifier the sound to prepare (defaults to current)
+ * @public
+ */
+ prewarmCast(identifier) {
+ this._loadOutlet(identifier);
+ }
+
+ /**
+ * Open the device picker for a sound. Must run inside the click gesture —
+ * Safari blocks the picker otherwise — so it loads the outlet and opens the
+ * picker synchronously.
+ *
+ * @method showCastMenu
+ * @param {Array|String|Sound} identifier the sound to cast (defaults to current)
+ * @public
+ */
+ showCastMenu(identifier) {
+ if (!this.isCastingAvailable) {
+ return;
+ }
+ this._loadOutlet(identifier);
+
+ let element = this.castOutletElement;
+ if (element.remote && typeof element.remote.prompt === 'function') {
+ element.remote.prompt().catch((error) => {
+ debug('ember-stereo:service')(`cast prompt error: ${error}`);
+ });
+ } else if (typeof element.webkitShowPlaybackTargetPicker === 'function') {
+ element.webkitShowPlaybackTargetPicker();
+ }
+ }
+
+ /**
+ * Hand playback back to the local device. WebKit has no programmatic
+ * disconnect, so it re-opens the picker (where the user disconnects); the
+ * Remote Playback API can disconnect directly. Either way the cast-target-change
+ * event drives the swap back to local.
+ *
+ * @method stopCasting
+ * @public
+ */
+ stopCasting() {
+ let element = this.castOutletElement;
+ if (element.remote && typeof element.remote.disconnect === 'function') {
+ element.remote.disconnect();
+ } else if (typeof element.webkitShowPlaybackTargetPicker === 'function') {
+ element.webkitShowPlaybackTargetPicker();
+ }
+ }
+
+ // Point the outlet at the sound's cast URL if it isn't already there.
+ _loadOutlet(identifier) {
+ let sound = identifier ? this.findSound(identifier) : this.currentSound;
+ let castUrl = sound?.castUrl;
+ if (!castUrl) {
+ return;
+ }
+ let element = this.castOutletElement;
+ // hasEqualUrls/StereoUrl throws on an empty input, so don't compare against
+ // an unset src — just set it (first cast, before any prewarm landed).
+ let currentSrc = element.getAttribute('src');
+ if (!currentSrc || !hasEqualUrls(currentSrc, castUrl)) {
+ element.setAttribute('src', castUrl);
+ element.load();
+ }
+ }
+
+ _onCastTargetChange(isWireless) {
+ // Changing the outlet element's `src` (a feed switch, or first engage on a
+ // non-prewarmed url) makes Safari drop then re-establish the AirPlay route,
+ // firing this with wireless=false then true. That flap is OUR doing, not a
+ // genuine user disconnect — ignore it while a programmatic outlet change is
+ // in flight, so it can't trigger a disengage→local→re-engage cascade that
+ // fights the re-cast.
+ if (this._suppressCastTargetChange) {
+ debug('ember-stereo:service')(
+ `cast-target change ignored (programmatic outlet change): wireless=${isWireless}`
+ );
+ return;
+ }
+ debug('ember-stereo:service')(
+ `cast-target change: wireless=${isWireless} -> ${isWireless ? 'engage' : 'disengage'}`
+ );
+ if (isWireless) {
+ this.engageCastTask.perform().catch((e) => {
+ if (!didCancel(e)) throw e;
+ });
+ } else {
+ this.disengageCastTask.perform().catch((e) => {
+ if (!didCancel(e)) throw e;
+ });
+ }
+ }
+
+ // Suppress cast-target-change handling across a programmatic outlet src change
+ // (and a short settle window after, while Safari re-establishes the route on
+ // the new src). Nestable so the initial engage and a feed-switch re-cast don't
+ // clobber each other.
+ _beginOutletChange() {
+ this._outletChangeDepth = (this._outletChangeDepth || 0) + 1;
+ this._suppressCastTargetChange = true;
+ this._castTargetSettleTask.cancelAll();
+ }
+
+ _endOutletChange() {
+ this._outletChangeDepth = Math.max(0, (this._outletChangeDepth || 1) - 1);
+ if (this._outletChangeDepth === 0) {
+ this._castTargetSettleTask.perform().catch((e) => {
+ if (!didCancel(e)) throw e;
+ });
+ }
+ }
+
+ // Hold the suppression open for a beat after the last outlet change settles, so
+ // Safari's trailing route flap on the new src can't engage/disengage.
+ // restartable: a new outlet change extends the window.
+ _castTargetSettleTask = task({ restartable: true }, async () => {
+ await timeout(1500);
+ this._suppressCastTargetChange = false;
+ // A real connect/disconnect may have landed while we were suppressing the
+ // flap; reconcile isCasting to the element's actual route state so the
+ // control can't get stuck lit (or stuck off).
+ this._reconcileCastState();
+ });
+
+ // Sync isCasting to the outlet element's ground-truth route state. The tracked
+ // bool is maintained by hand off flap-prone events that can be missed (e.g.
+ // during suppression); this is the self-heal.
+ _reconcileCastState() {
+ let element = this._castOutletElement;
+ if (!element || this._suppressCastTargetChange) {
+ return;
+ }
+ let actuallyCasting =
+ !!element.webkitCurrentPlaybackTargetIsWireless ||
+ element.remote?.state === 'connected';
+
+ debug('ember-stereo:service')(
+ `reconcile cast state: actuallyCasting=${actuallyCasting} isCasting=${this.isCasting}`
+ );
+
+ if (actuallyCasting && !this.isCasting) {
+ this.engageCastTask.perform().catch((e) => {
+ if (!didCancel(e)) throw e;
+ });
+ } else if (!actuallyCasting && this.isCasting) {
+ this.disengageCastTask.perform().catch((e) => {
+ if (!didCancel(e)) throw e;
+ });
+ }
+ }
+
+ // Engage: a device target became active. Route the current sound to it by
+ // swapping its backing connection for a NativeAudioCasting on the route
+ // element. (Subsequent feed switches resolve to the device on their own via
+ // the cast strategy in _buildStrategies.) restartable so a flapping target
+ // event supersedes cleanly.
+ engageCastTask = task({ restartable: true }, async () => {
+ this.isCasting = true;
+ // The platform doesn't expose the AirPlay target's real name (WebKit and the
+ // Remote Playback API both withhold it). This is an AirPlay integration
+ // (Chromecast would be a separate Cast SDK), so default to "AirPlay".
+ // Cleared on disengage.
+ this.castDeviceName = 'AirPlay';
+ let sound = this.currentSound;
+ debug('ember-stereo:service')(
+ `engaging cast -> ${sound?.castUrl ?? '(no current sound; route held, awaiting one)'}`
+ );
+ this.trigger('audio-cast-connecting', { sound });
+ if (sound?.castUrl) {
+ let cast = this._buildCastConnection(sound.castUrl, sound.metadata);
+ if (cast) {
+ await sound.swap(cast);
+ }
+ }
+ this.trigger('audio-cast-connected', { sound });
+ });
+
+ // Disengage: swap the device-routed sound back to a fresh local connection.
+ disengageCastTask = task({ restartable: true }, async () => {
+ if (!this.isCasting) {
+ return;
+ }
+ let sound = this.currentSound;
+ debug('ember-stereo:service')(
+ `disengaging cast -> keep blessed outlet, resume local (playIntent=${sound?._playIntent})`
+ );
+ this.isCasting = false;
+ this.castDeviceName = null;
+
+ // Do NOT swap to a fresh local connection: a brand-new <audio> element has
+ // no user activation, so Safari blocks its autoplay and the audio pauses.
+ // The outlet element is already "blessed" (it played under the cast), and
+ // when the route drops it outputs locally — so keep the NativeAudioCasting
+ // and just resume it if we were playing. The route drop often pauses the
+ // element involuntarily (which doesn't change _playIntent), so re-issue play
+ // on the blessed element. A later feed switch rebuilds a normal local
+ // connection via _castStateMatches.
+ if (sound && this._isCastConnection(sound.value)) {
+ if (sound._playIntent && !sound.isPlaying) {
+ sound.play();
+ }
+ }
+
+ this.trigger('audio-cast-disconnected', { sound });
+ });
+
+ // The service-owned SharedAudioAccess wrapping the route-holding outlet
+ // element, so every NativeAudioCasting drives THAT element and coordinates
+ // single-ownership through the standard handshake — the same machinery
+ // NativeAudio uses to share one element across connections.
+ get castSharedAudioAccess() {
+ if (!this._castSharedAudioAccess) {
+ let access = new SharedAudioAccess();
+ access.audioElement = this.castOutletElement;
+ this._castSharedAudioAccess = access;
+ }
+ return this._castSharedAudioAccess;
+ }
+
+ // One definition of "the cast connection": a strategy that builds a
+ // NativeAudioCasting on the route element for `castUrl`. Shared by the engage
+ // swap and the force-injected cast strategy in _buildStrategies.
+ _castStrategy(castUrl, metadata) {
+ let service = this;
+ let strategy = new Strategy(NativeAudioCasting, new StereoUrl(castUrl), {
+ metadata,
+ sharedAudioAccess: this.castSharedAudioAccess,
+ // Changing the routed element's src flaps the AirPlay route; let the cast
+ // connection suppress the resulting cast-target events during the change.
+ options: {
+ beginOutletChange: () => service._beginOutletChange(),
+ endOutletChange: () => service._endOutletChange(),
+ },
+ });
+ setOwner(strategy, getOwner(this));
+ return strategy;
+ }
+
+ _buildCastConnection(castUrl, metadata) {
+ return this._castStrategy(castUrl, metadata).createSound();
+ }
+
+ _isCastConnection(connection) {
+ return connection?.connectionKey === NativeAudioCasting.key;
+ }
+
+ // Build a fresh local connection for a sound from its (non-cast) strategies.
+ // A sound that adopted a cached connection on load never built strategies, so
+ // rebuild them from its identifier rather than leaving disengage with nothing
+ // to swap back to (which would strand the Sound silent).
+ _buildLocalConnection(sound) {
+ let strategies = sound.strategies;
+ if (!strategies?.length) {
+ strategies = this._buildStrategies(
+ makeArray(sound.identifier),
+ this.prepareLoadOptions(sound.options)
+ );
+ }
+ let strategy = (strategies || []).find(
+ (candidate) =>
+ candidate.canPlay && candidate.connectionKey !== NativeAudioCasting.key
+ );
+ return strategy?.createSound();
+ }
+
/* ------------------------ PRIVATE(ISH) STUFF ------------------------------ */
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
@@ -664,7 +1105,20 @@ export default class Stereo extends Service.extend(EmberEvented) {
_buildStrategies(urlsToTry, options) {
let strategizer = new Strategizer(urlsToTry, options);
setOwner(strategizer, getOwner(this));
- return strategizer.strategies;
+ let strategies = [...strategizer.strategies];
+
+ // While casting, force the cast connection to the top so any sound that
+ // loads (a feed switch) resolves straight to the device. The app supplies
+ // the device-fetchable URL via options.castUrl; without it we can't cast, so
+ // that sound just plays locally.
+ if (this.isCasting && options.castUrl) {
+ debug('ember-stereo:service')(
+ `casting active: injecting cast strategy at top for ${options.castUrl}`
+ );
+ strategies.unshift(this._castStrategy(options.castUrl, options.metadata));
+ }
+
+ return strategies;
}
_handlePlaybackError({ sound, options }) {
@@ -1029,7 +1483,7 @@ export default class Stereo extends Service.extend(EmberEvented) {
navigator.mediaSession.playbackState = 'paused';
}
- let { title, artist, album, artwork } = sound.metadata;
+ let { title, artist, album, artwork } = sound.metadata ?? {};
let mediaAttributes = {
title,
@@ -1147,5 +1601,9 @@ export default class Stereo extends Service.extend(EmberEvented) {
willDestroy() {
this.loadTask.cancelAll();
this.playTask.cancelAll();
+ this.engageCastTask.cancelAll();
+ this.disengageCastTask.cancelAll();
+ this._castTargetSettleTask.cancelAll();
+ this._detectCastingAvailabilityTask.cancelAll();
}
}
diff --git c/ember-stereo/src/stereo-connections/base.js w/ember-stereo/src/stereo-connections/base.js
index 9879f09..849e702 100644
--- c/ember-stereo/src/stereo-connections/base.js
+++ w/ember-stereo/src/stereo-connections/base.js
@@ -624,9 +624,9 @@ export default class Sound extends Evented {
/**
* Release this connection during a Sound swap. For local connections this is
* a full teardown (free the backend: HLS `hls.destroy()`, Howler `unload()`,
- * NativeAudio releases shared-element control). The AirPlay connection
- * (added later) overrides this to keep its service-owned route element while
- * detaching its state — the element *is* the route.
+ * NativeAudio releases shared-element control). NativeAudioCasting's teardown
+ * keeps the service-owned route element (the element *is* the route) and only
+ * unregisters its listeners.
*
* @method detach
* @public
diff --git c/ember-stereo/src/stereo-connections/native-audio-casting.js w/ember-stereo/src/stereo-connections/native-audio-casting.js
new file mode 100644
index 0000000..87bc11a
--- /dev/null
+++ w/ember-stereo/src/stereo-connections/native-audio-casting.js
@@ -0,0 +1,300 @@
+import { isTesting, macroCondition } from '@embroider/macros';
+import NativeAudio from './native-audio';
+
+// After a seek, the device's clock keeps reporting the pre-seek position for a
+// beat. Ignore its reported position until it lands within this tolerance of the
+// seek target (or the window lapses), so the poll can't snap the playhead back.
+const SEEK_SETTLE_TOLERANCE_MS = 1500;
+const SEEK_SETTLE_WINDOW_MS = 4000;
+
+// Safari fires a spurious 'ended' after a fresh-src seek while AirPlaying; only
+// honor an 'ended' once the clock has actually reached the media's end, so a
+// bogus one can't strand play-state (and freeze the clock).
+const END_TOLERANCE_MS = 1500;
+