@tobyt/react-native-audio-browser 1.1.0 → 1.1.1

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.
Files changed (52) hide show
  1. package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +3 -2
  2. package/android/src/main/java/com/audiobrowser/ChosenChannelMode.kt +4 -1
  3. package/android/src/main/java/com/audiobrowser/LoopRangeCommand.kt +13 -0
  4. package/android/src/main/java/com/audiobrowser/player/Player.kt +100 -14
  5. package/android/src/main/java/com/audiobrowser/player/PlayerListener.kt +11 -6
  6. package/android/src/test/java/com/audiobrowser/ChosenChannelModeTest.kt +22 -0
  7. package/android/src/test/java/com/audiobrowser/LoopRangeCommandTest.kt +22 -0
  8. package/android/src/test/java/com/audiobrowser/player/LoopRangeCaseTest.kt +6 -0
  9. package/android/src/test/java/com/audiobrowser/player/LoopRangeEngineLifecycleTest.kt +170 -0
  10. package/android/src/test/java/com/audiobrowser/player/LoopRangePinSeekTest.kt +158 -0
  11. package/android/src/test/java/com/audiobrowser/player/PlayerTrackChangeTest.kt +20 -0
  12. package/ios/AVPlayerEngine.swift +2 -2
  13. package/ios/Player/PlaybackBoundaryTime.swift +11 -0
  14. package/ios/Player/Player.swift +3 -3
  15. package/ios/Tests/ChannelModeTapAudioMixTests.swift +144 -0
  16. package/ios/Tests/LoopRangeCaseTests.swift +14 -3
  17. package/ios/Tests/PlaybackBoundaryTimeTests.swift +20 -0
  18. package/ios/Tests/PlayerChannelModeTests.swift +18 -0
  19. package/ios/Tests/SupersedingTaskTests.swift +4 -1
  20. package/lib/commonjs/test-utils/fakeAudioContext.js +221 -0
  21. package/lib/commonjs/test-utils/fakeAudioContext.js.map +1 -0
  22. package/lib/commonjs/web/NativeAudioBrowser.js +14 -10
  23. package/lib/commonjs/web/NativeAudioBrowser.js.map +1 -1
  24. package/lib/commonjs/web/TrackPlayer/ChannelRouter.js +34 -11
  25. package/lib/commonjs/web/TrackPlayer/ChannelRouter.js.map +1 -1
  26. package/lib/commonjs/web/TrackPlayer/Player.js +6 -0
  27. package/lib/commonjs/web/TrackPlayer/Player.js.map +1 -1
  28. package/lib/commonjs/web/TrackPlayer/QueuePlayer.js +6 -2
  29. package/lib/commonjs/web/TrackPlayer/QueuePlayer.js.map +1 -1
  30. package/lib/module/test-utils/fakeAudioContext.js +212 -0
  31. package/lib/module/test-utils/fakeAudioContext.js.map +1 -0
  32. package/lib/module/web/NativeAudioBrowser.js +14 -10
  33. package/lib/module/web/NativeAudioBrowser.js.map +1 -1
  34. package/lib/module/web/TrackPlayer/ChannelRouter.js +34 -11
  35. package/lib/module/web/TrackPlayer/ChannelRouter.js.map +1 -1
  36. package/lib/module/web/TrackPlayer/Player.js +6 -0
  37. package/lib/module/web/TrackPlayer/Player.js.map +1 -1
  38. package/lib/module/web/TrackPlayer/QueuePlayer.js +6 -2
  39. package/lib/module/web/TrackPlayer/QueuePlayer.js.map +1 -1
  40. package/lib/typescript/src/test-utils/fakeAudioContext.d.ts +86 -0
  41. package/lib/typescript/src/test-utils/fakeAudioContext.d.ts.map +1 -0
  42. package/package.json +1 -1
  43. package/src/test-utils/fakeAudioContext.ts +229 -0
  44. package/src/web/NativeAudioBrowser.audioProcessing.test.ts +7 -234
  45. package/src/web/NativeAudioBrowser.ts +19 -10
  46. package/src/web/TrackPlayer/ChannelRouter.ts +36 -12
  47. package/src/web/TrackPlayer/Player.channelMode.test.ts +159 -0
  48. package/src/web/TrackPlayer/Player.loopRange.test.ts +17 -4
  49. package/src/web/TrackPlayer/Player.ts +11 -0
  50. package/src/web/TrackPlayer/QueuePlayer.ts +4 -2
  51. package/src/web/__tests__/lifecycle.test.ts +53 -0
  52. package/src/web/__tests__/lifecycleHarness.ts +4 -2
@@ -243,9 +243,9 @@ final class AVPlayerEngine: PlayerEngine {
243
243
  self.playbackBoundaryObserver = nil
244
244
  }
245
245
  playbackBoundaryIdentifier = identifier
246
- guard let seconds else { return }
246
+ guard let seconds, let time = playbackBoundaryTime(seconds: seconds) else { return }
247
247
  playbackBoundaryObserver = avPlayer.addBoundaryTimeObserver(
248
- forTimes: [NSValue(time: CMTime(seconds: seconds, preferredTimescale: 1000))], queue: .main,
248
+ forTimes: [NSValue(time: time)], queue: .main,
249
249
  ) { [weak self] in
250
250
  Task { @MainActor in
251
251
  guard let self, self.playbackBoundaryIdentifier == identifier else { return }
@@ -0,0 +1,11 @@
1
+ import CoreMedia
2
+
3
+ /// The time to register a playback boundary observer at, or nil when no
4
+ /// numeric `CMTime` can hold `seconds`. `AVPlayer.addBoundaryTimeObserver`
5
+ /// raises an uncatchable `NSInvalidArgumentException` for a time that is not
6
+ /// numeric, so a nil result must register no observer.
7
+ func playbackBoundaryTime(seconds: Double) -> CMTime? {
8
+ guard seconds.isFinite else { return nil }
9
+ let time = CMTime(seconds: seconds, preferredTimescale: 1000)
10
+ return time.isNumeric ? time : nil
11
+ }
@@ -193,9 +193,9 @@ final class Player {
193
193
  func setPlayWhenReady(_ newValue: Bool) {
194
194
  let changed = newValue != playWhenReady
195
195
  playWhenReady = newValue
196
- if newValue, loopRangePausedAtEnd {
197
- loopRangePausedAtEnd = false
198
- armLoopBoundary()
196
+ // Paused at the loop end, nothing is left to play before it: resume from the loop start.
197
+ if newValue, loopRangePausedAtEnd, let range = loopRange {
198
+ restartLoopRange(at: range.start)
199
199
  }
200
200
  retry.playIntentChanged(newValue)
201
201
  // A play during an interruption owns the intent: a later pause must not be auto-resumed.
@@ -0,0 +1,144 @@
1
+ @testable import AudioBrowserTestable
2
+ import AVFoundation
3
+ import Testing
4
+
5
+ /// What a listener hears through the audio mix an item gets: a real multichannel file rendered by
6
+ /// AVFoundation through the Channel Mode tap.
7
+ @Suite("ChannelModeTap - audio mix", .timeLimit(.minutes(1)))
8
+ struct ChannelModeTapAudioMixTests {
9
+ /// Each channel of the quad source holds its own constant level.
10
+ private let levels: [Float] = [0.1, 0.2, 0.3, 0.4]
11
+
12
+ @Test
13
+ func stereoPassesEveryChannelOfAMultichannelSource() async throws {
14
+ #expect(try await render(.stereo) == levels)
15
+ }
16
+
17
+ @Test
18
+ func leftPlaysTheSourcesRealFirstChannel() async throws {
19
+ #expect(try await render(.left) == [0.1, 0.1, 0, 0])
20
+ }
21
+
22
+ @Test
23
+ func rightPlaysTheSourcesRealSecondChannel() async throws {
24
+ #expect(try await render(.right) == [0.2, 0.2, 0, 0])
25
+ }
26
+
27
+ @Test
28
+ func eachMixGetsAFreshTap() async throws {
29
+ let (_, track) = try await quadTrack()
30
+ let modeSwitch = ChannelModeSwitch()
31
+
32
+ let first = try #require(ChannelModeTap.audioMix(for: track, modeSwitch: modeSwitch))
33
+ let second = try #require(ChannelModeTap.audioMix(for: track, modeSwitch: modeSwitch))
34
+
35
+ let firstTap = try #require(first.inputParameters.first?.audioTapProcessor)
36
+ let secondTap = try #require(second.inputParameters.first?.audioTapProcessor)
37
+ #expect(firstTap !== secondTap)
38
+ }
39
+
40
+ // MARK: - Support
41
+
42
+ /// Renders the quad source through a mix playing `mode`, returning each output channel's level
43
+ /// at the first frame.
44
+ private func render(_ mode: ChannelMode) async throws -> [Float] {
45
+ let (asset, loadedTrack) = try await quadTrack()
46
+ // Only the reader's queue touches the track from here on.
47
+ nonisolated(unsafe) let track = loadedTrack
48
+ return try await Self.offThePool { try Self.firstFrameLevels(asset: asset, track: track, mode: mode) }
49
+ }
50
+
51
+ /// `copyNextSampleBuffer()` blocks until AVFoundation renders the frame. Run on a task, it holds
52
+ /// one of the cooperative pool's threads, of which a CI runner has as few as it has cores, so it
53
+ /// runs on its own queue instead.
54
+ private static func offThePool<T: Sendable>(_ work: @escaping @Sendable () throws -> T) async throws -> T {
55
+ try await withCheckedThrowingContinuation { continuation in
56
+ DispatchQueue(label: "ChannelModeTapAudioMixTests.reader").async {
57
+ continuation.resume(with: Result { try work() })
58
+ }
59
+ }
60
+ }
61
+
62
+ private struct RenderFailed: Error, CustomStringConvertible {
63
+ let description: String
64
+ }
65
+
66
+ private static func firstFrameLevels(asset: AVURLAsset, track: AVAssetTrack, mode: ChannelMode) throws -> [Float] {
67
+ let modeSwitch = ChannelModeSwitch()
68
+ modeSwitch.mode = mode
69
+ guard let mix = ChannelModeTap.audioMix(for: track, modeSwitch: modeSwitch) else {
70
+ throw RenderFailed(description: "no audio mix for the quad track")
71
+ }
72
+
73
+ let reader = try AVAssetReader(asset: asset)
74
+ let output = AVAssetReaderAudioMixOutput(audioTracks: [track], audioSettings: readerSettings)
75
+ output.audioMix = mix
76
+ reader.add(output)
77
+ defer { reader.cancelReading() }
78
+ guard reader.startReading() else {
79
+ throw RenderFailed(description: "the reader did not start: \(String(describing: reader.error))")
80
+ }
81
+ guard let sample = output.copyNextSampleBuffer() else {
82
+ throw RenderFailed(description: "no sample rendered: \(String(describing: reader.error))")
83
+ }
84
+
85
+ var blockBuffer: CMBlockBuffer?
86
+ var sizeNeeded = 0
87
+ CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
88
+ sample, bufferListSizeNeededOut: &sizeNeeded, bufferListOut: nil, bufferListSize: 0,
89
+ blockBufferAllocator: nil, blockBufferMemoryAllocator: nil, flags: 0, blockBufferOut: nil,
90
+ )
91
+ let list = UnsafeMutableRawPointer.allocate(byteCount: sizeNeeded, alignment: 16)
92
+ .assumingMemoryBound(to: AudioBufferList.self)
93
+ defer { list.deallocate() }
94
+ let status = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
95
+ sample, bufferListSizeNeededOut: nil, bufferListOut: list, bufferListSize: sizeNeeded,
96
+ blockBufferAllocator: nil, blockBufferMemoryAllocator: nil,
97
+ flags: kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment, blockBufferOut: &blockBuffer,
98
+ )
99
+ guard status == noErr else { throw RenderFailed(description: "no audio buffer list: \(status)") }
100
+ return UnsafeMutableAudioBufferListPointer(list).map { buffer in
101
+ buffer.mData!.assumingMemoryBound(to: Float.self)[0]
102
+ }
103
+ }
104
+
105
+ private static let quadLayout = AVAudioChannelLayout(layoutTag: kAudioChannelLayoutTag_Quadraphonic)!
106
+
107
+ private static var readerSettings: [String: Any] {
108
+ [
109
+ AVFormatIDKey: kAudioFormatLinearPCM,
110
+ AVSampleRateKey: 44100,
111
+ AVNumberOfChannelsKey: 4,
112
+ AVLinearPCMBitDepthKey: 32,
113
+ AVLinearPCMIsFloatKey: true,
114
+ AVLinearPCMIsNonInterleaved: true,
115
+ AVLinearPCMIsBigEndianKey: false,
116
+ AVChannelLayoutKey: Data(
117
+ bytes: quadLayout.layout, count: MemoryLayout<AudioChannelLayout>.size,
118
+ ),
119
+ ]
120
+ }
121
+
122
+ /// A one-second quad CAF file whose channels hold `levels`, and its audio track. The asset is
123
+ /// returned too: a track holds its asset weakly.
124
+ private func quadTrack() async throws -> (AVURLAsset, AVAssetTrack) {
125
+ let format = AVAudioFormat(standardFormatWithSampleRate: 44100, channelLayout: Self.quadLayout)
126
+ let url = FileManager.default.temporaryDirectory
127
+ .appendingPathComponent("channel-mode-quad-\(UUID().uuidString).caf")
128
+ let frames: AVAudioFrameCount = 44100
129
+ let buffer = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frames))
130
+ buffer.frameLength = frames
131
+ let channels = try #require(buffer.floatChannelData)
132
+ for (channel, level) in levels.enumerated() {
133
+ channels[channel].update(repeating: level, count: Int(frames))
134
+ }
135
+ do {
136
+ let file = try AVAudioFile(
137
+ forWriting: url, settings: format.settings, commonFormat: .pcmFormatFloat32, interleaved: false,
138
+ )
139
+ try file.write(from: buffer)
140
+ }
141
+ let asset = AVURLAsset(url: url)
142
+ return try (asset, #require(try await asset.loadTracks(withMediaType: .audio).first))
143
+ }
144
+ }
@@ -48,13 +48,15 @@ private struct LoopRangeStep: Decodable {
48
48
  let checksSleepTimer: Bool
49
49
  let sleepChanges: Int?
50
50
  let repeatMode: String?
51
+ let state: String?
51
52
 
52
- enum CodingKeys: String, CodingKey { case range, position, positionAtLeast, positionAtMost, changes, cleared, error, activeTrack, playWhenReady, sleepTimer, sleepChanges, repeatMode }
53
+ enum CodingKeys: String, CodingKey { case range, position, positionAtLeast, positionAtMost, changes, cleared, error, activeTrack, playWhenReady, sleepTimer, sleepChanges, repeatMode, state }
53
54
 
54
55
  init(from decoder: Decoder) throws {
55
- try rejectUnknownKeys(decoder, allowed: ["range", "position", "positionAtLeast", "positionAtMost", "changes", "cleared", "error", "activeTrack", "playWhenReady", "sleepTimer", "sleepChanges", "repeatMode"])
56
+ try rejectUnknownKeys(decoder, allowed: ["range", "position", "positionAtLeast", "positionAtMost", "changes", "cleared", "error", "activeTrack", "playWhenReady", "sleepTimer", "sleepChanges", "repeatMode", "state"])
56
57
  let c = try decoder.container(keyedBy: CodingKeys.self)
57
58
  repeatMode = try c.decodeIfPresent(String.self, forKey: .repeatMode)
59
+ state = try c.decodeIfPresent(String.self, forKey: .state)
58
60
  playWhenReady = try c.decodeIfPresent(Bool.self, forKey: .playWhenReady)
59
61
  checksSleepTimer = c.contains(.sleepTimer)
60
62
  sleepTimer = try c.decodeIfPresent(String.self, forKey: .sleepTimer)
@@ -120,7 +122,11 @@ private func loopRangeCases() throws -> [LoopRangeCase] {
120
122
  let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
121
123
  .deletingLastPathComponent()
122
124
  let data = try Data(contentsOf: root.appendingPathComponent("spec/loop-range-cases.json"))
123
- return try JSONDecoder().decode(File.self, from: data).cases.filter {
125
+ let decoder = JSONDecoder()
126
+ decoder.nonConformingFloatDecodingStrategy = .convertFromString(
127
+ positiveInfinity: "Infinity", negativeInfinity: "-Infinity", nan: "NaN",
128
+ )
129
+ return try decoder.decode(File.self, from: data).cases.filter {
124
130
  $0.platforms == nil || $0.platforms!.contains("ios")
125
131
  }
126
132
  }
@@ -212,6 +218,10 @@ struct LoopRangeCaseTests {
212
218
  remaining = 0
213
219
  }
214
220
  }
221
+ // AVPlayer reports the pause a dropped intent caused, as play reports .avPlayerPlaying.
222
+ if !player.playWhenReady, !engine.isPlaying {
223
+ engine.emit(.timeControlStatus(.paused, waitingForNoItem: false))
224
+ }
215
225
  if step.action == .advanceToLoop { #expect(looped) }
216
226
  if step.action == .advanceToPause { #expect(!player.playWhenReady) }
217
227
  }
@@ -229,6 +239,7 @@ struct LoopRangeCaseTests {
229
239
  let context = Comment(rawValue: testCase.name)
230
240
  if let mode = expected.repeatMode { #expect(player.repeatMode == RepeatMode(fromString: mode), context) }
231
241
  if let intent = expected.playWhenReady { #expect(player.playWhenReady == intent, context) }
242
+ if let state = expected.state { #expect(state == "\(player.state)", context) }
232
243
  if let count = expected.sleepChanges { #expect(callbacks.sleepTimerChanges.count == count, context) }
233
244
  if expected.checksSleepTimer {
234
245
  if expected.sleepTimer == "end" { #expect(player.sleepTimerManager.willSleepWhenCurrentItemReachesEnd, context) }
@@ -0,0 +1,20 @@
1
+ @testable import AudioBrowserTestable
2
+ import CoreMedia
3
+ import Testing
4
+
5
+ @Suite("playbackBoundaryTime(seconds:)")
6
+ struct PlaybackBoundaryTimeTests {
7
+ @Test func aTrackPositionBecomesANumericTime() throws {
8
+ let time = try #require(playbackBoundaryTime(seconds: 30))
9
+ #expect(time.isNumeric)
10
+ #expect(time.seconds == 30)
11
+ }
12
+
13
+ // AVPlayer.addBoundaryTimeObserver raises an uncatchable
14
+ // NSInvalidArgumentException for a time that is not numeric, so the engine
15
+ // must register no observer for these.
16
+ @Test(arguments: [1e300, Double.greatestFiniteMagnitude, Double.nan, Double.infinity, -Double.infinity])
17
+ func aPositionNoNumericTimeCanHoldHasNoBoundary(seconds: Double) {
18
+ #expect(playbackBoundaryTime(seconds: seconds) == nil)
19
+ }
20
+ }
@@ -118,4 +118,22 @@ struct PlayerChannelModeTests {
118
118
  #expect(engine.resolveAndLoadCalls == [a.src, b.src, b.src])
119
119
  #expect(engine.loadChannelModes == [.left, .left, .right])
120
120
  }
121
+
122
+ /// The bridge's destroy clears the Player before it releases the engine. The tap rides the item,
123
+ /// so dropping the item leaves no tap attached; the next load builds a fresh one.
124
+ @Test @MainActor
125
+ func clearingAsDestroyDoesLeavesNoItemAndSoNoTap() throws {
126
+ let engine = MockPlayerEngine()
127
+ let (player, _) = makeSubject(engine: engine)
128
+ player.channelMode = .left
129
+ try player.setQueue([a])
130
+ engine.hasItem = true
131
+
132
+ player.clear()
133
+
134
+ #expect(!engine.hasItem)
135
+ try player.setQueue([b])
136
+ #expect(engine.resolveAndLoadCalls == [a.src, b.src])
137
+ #expect(engine.loadChannelModes == [.left, .left])
138
+ }
121
139
  }
@@ -84,8 +84,11 @@ struct SupersedingTaskTests {
84
84
  await yieldUntil { work.started == 1 }
85
85
  task.run(key: "b") { try await work.run() } deliver: { _ in }
86
86
  await yieldUntil { work.started == 2 }
87
- #expect(work.cancelled == 1)
87
+ // Starting the replacement does not mean the previous task has finished
88
+ // handling cancellation; the executor may resume them in either order.
89
+ await yieldUntil { work.cancelled == 1 }
88
90
  task.cancel()
91
+ await yieldUntil { work.cancelled == 2 }
89
92
  }
90
93
 
91
94
  @Test func aDeliveredKeyIsSkippedUntilCancel() async {
@@ -0,0 +1,221 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.FakeAudioNode = exports.FakeAudioContext = void 0;
7
+ exports.ears = ears;
8
+ exports.installFakeAudioContext = installFakeAudioContext;
9
+ exports.onlyAudioContext = onlyAudioContext;
10
+ exports.reachingDestination = reachingDestination;
11
+ var _vitest = require("vitest");
12
+ /**
13
+ * A fake Web Audio `AudioContext` for web Player tests. happy-dom has no Web
14
+ * Audio, so this records the audio graph the Player builds and works out its
15
+ * channel mixing as the Web Audio spec defines it. Tests then read which
16
+ * source channels reach the destination, and how the context was driven
17
+ * (`state`, `resumes`).
18
+ *
19
+ * Install it with `installFakeAudioContext()` in `beforeEach`, and undo it
20
+ * with `vi.unstubAllGlobals()` in `afterEach`.
21
+ *
22
+ * @internal — never imported by production code, only by tests.
23
+ */
24
+
25
+ /**
26
+ * One channel of a signal: the source channels summed into it. Gains are
27
+ * left out; only which source channel reaches which ear matters here.
28
+ */
29
+
30
+ /** A signal: its channels, in order. */
31
+
32
+ /** The source channel names for each source width a test can use. */
33
+ const sourceChannelNames = {
34
+ 1: ['M'],
35
+ 2: ['L', 'R'],
36
+ 4: ['L', 'R', 'SL', 'SR'],
37
+ 6: ['L', 'R', 'C', 'LFE', 'SL', 'SR']
38
+ };
39
+ const sum = (...channels) => [...new Set(channels.flat())].sort();
40
+
41
+ /**
42
+ * The Web Audio spec's channel up-mixing and down-mixing of `input` to
43
+ * `count` channels. Only the speaker layouts a Player graph can meet are
44
+ * modelled; any other throws, so an unexpected mix fails the test.
45
+ */
46
+ function mix(input, count, interpretation) {
47
+ if (input.length === count) return input;
48
+ if (interpretation === 'discrete') {
49
+ return Array.from({
50
+ length: count
51
+ }, (_, i) => input[i] ?? []);
52
+ }
53
+ const [l, r, c,, sl, sr] = input;
54
+ if (count === 2 && input.length === 1) return [input[0], input[0]];
55
+ if (count === 1 && input.length === 2) return [sum(l, r)];
56
+ if (count === 2 && input.length === 4) {
57
+ return [sum(l, input[2]), sum(r, input[3])];
58
+ }
59
+ if (count === 2 && input.length === 6) {
60
+ return [sum(l, c, sl), sum(r, c, sr)];
61
+ }
62
+ throw new Error(`no speaker mix from ${input.length} to ${count}`);
63
+ }
64
+ class FakeAudioNode {
65
+ edges = [];
66
+ channelCount = 2;
67
+ channelCountMode = 'max';
68
+ channelInterpretation = 'speakers';
69
+ constructor(kind, context, ports = 1) {
70
+ this.kind = kind;
71
+ this.context = context;
72
+ this.ports = ports;
73
+ context.nodes.push(this);
74
+ if (kind === 'splitter') {
75
+ this.channelCount = ports;
76
+ this.channelCountMode = 'explicit';
77
+ this.channelInterpretation = 'discrete';
78
+ } else if (kind === 'merger') {
79
+ this.channelCount = 1;
80
+ this.channelCountMode = 'explicit';
81
+ } else if (kind === 'destination') {
82
+ this.channelCountMode = 'explicit';
83
+ }
84
+ }
85
+ connect(to, output = 0, input = 0) {
86
+ this.edges.push({
87
+ to,
88
+ output,
89
+ input
90
+ });
91
+ return to;
92
+ }
93
+ /** Like the real `disconnect()` with no arguments: every outgoing edge. */
94
+ disconnect() {
95
+ this.edges = [];
96
+ }
97
+
98
+ /** Each signal connected to input `input`, before this node mixes them. */
99
+ arriving(input = 0) {
100
+ return this.context.nodes.flatMap(node => node.edges.filter(e => e.to === this && e.input === input).map(e => node.output(e.output)));
101
+ }
102
+
103
+ /** The node's input `input`, mixed as its channel properties say. */
104
+ input(input) {
105
+ const sources = this.arriving(input);
106
+ if (sources.length === 0) return [];
107
+ const widest = Math.max(...sources.map(s => s.length));
108
+ const count = this.channelCountMode === 'explicit' ? this.channelCount : this.channelCountMode === 'clamped-max' ? Math.min(widest, this.channelCount) : widest;
109
+ const mixed = sources.map(s => mix(s, count, this.channelInterpretation));
110
+ return Array.from({
111
+ length: count
112
+ }, (_, i) => sum(...mixed.map(s => s[i])));
113
+ }
114
+
115
+ /** What leaves output `output`. */
116
+ output(output) {
117
+ switch (this.kind) {
118
+ case 'source':
119
+ return sourceChannelNames[this.context.sourceChannels].map(n => [n]);
120
+ case 'splitter':
121
+ return [this.input(0)[output]];
122
+ case 'merger':
123
+ return Array.from({
124
+ length: this.ports
125
+ }, (_, i) => this.input(i)[0] ?? []);
126
+ default:
127
+ return this.input(0);
128
+ }
129
+ }
130
+
131
+ /** What the node plays, for the destination: its mixed input. */
132
+ heard() {
133
+ return this.input(0);
134
+ }
135
+ }
136
+ exports.FakeAudioNode = FakeAudioNode;
137
+ class FakeAudioContext {
138
+ /** Every context made since the last `installFakeAudioContext()`. */
139
+ static instances = [];
140
+ state = 'suspended';
141
+ nodes = [];
142
+ destination = new FakeAudioNode('destination', this);
143
+ /** How many channels the element's current source has. */
144
+ sourceChannels = 2;
145
+ /** How many times `resume()` was called. */
146
+ resumes = 0;
147
+ constructor() {
148
+ FakeAudioContext.instances.push(this);
149
+ }
150
+ createMediaElementSource(element) {
151
+ if (this.source) throw new Error('InvalidStateError');
152
+ this.sourceElement = element;
153
+ this.source = new FakeAudioNode('source', this);
154
+ return this.source;
155
+ }
156
+ createGain() {
157
+ return new FakeAudioNode('gain', this);
158
+ }
159
+ createChannelSplitter(outputs) {
160
+ return new FakeAudioNode('splitter', this, outputs);
161
+ }
162
+ createChannelMerger(inputs) {
163
+ return new FakeAudioNode('merger', this, inputs);
164
+ }
165
+ resume() {
166
+ if (this.state === 'closed') {
167
+ return Promise.reject(new Error('InvalidStateError'));
168
+ }
169
+ this.resumes++;
170
+ this.state = 'running';
171
+ return Promise.resolve();
172
+ }
173
+ /** Like the real `close()`: final, and a closed context cannot resume. */
174
+ close() {
175
+ this.state = 'closed';
176
+ return Promise.resolve();
177
+ }
178
+ }
179
+
180
+ /** Stubs the global `AudioContext` with the fake and forgets old contexts. */
181
+ exports.FakeAudioContext = FakeAudioContext;
182
+ function installFakeAudioContext() {
183
+ FakeAudioContext.instances = [];
184
+ _vitest.vi.stubGlobal('AudioContext', FakeAudioContext);
185
+ }
186
+
187
+ /** The one context the Player made; fails if it made none or several. */
188
+ function onlyAudioContext() {
189
+ const {
190
+ instances
191
+ } = FakeAudioContext;
192
+ if (instances.length !== 1) {
193
+ throw new Error(`expected one AudioContext, found ${instances.length}`);
194
+ }
195
+ return instances[0];
196
+ }
197
+
198
+ /**
199
+ * Each signal connected to the destination, for a source of `channels`
200
+ * channels, before the destination mixes them. One entry per connected
201
+ * stage, so a stale stage shows up as an extra entry.
202
+ */
203
+ function reachingDestination(ctx, channels = 2) {
204
+ ctx.sourceChannels = channels;
205
+ return ctx.destination.arriving();
206
+ }
207
+
208
+ /**
209
+ * Which source channels each ear hears, for a source of `channels` channels,
210
+ * through a stereo destination.
211
+ */
212
+ function ears(ctx, channels = 2) {
213
+ ctx.sourceChannels = channels;
214
+ const [left, right, ...rest] = ctx.destination.heard();
215
+ if (rest.length > 0) throw new Error('the destination is not stereo');
216
+ return {
217
+ left: left ?? [],
218
+ right: right ?? []
219
+ };
220
+ }
221
+ //# sourceMappingURL=fakeAudioContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["_vitest","require","sourceChannelNames","sum","channels","Set","flat","sort","mix","input","count","interpretation","length","Array","from","_","i","l","r","c","sl","sr","Error","FakeAudioNode","edges","channelCount","channelCountMode","channelInterpretation","constructor","kind","context","ports","nodes","push","connect","to","output","disconnect","arriving","flatMap","node","filter","e","map","sources","widest","Math","max","s","min","mixed","sourceChannels","n","heard","exports","FakeAudioContext","instances","state","destination","resumes","createMediaElementSource","element","source","sourceElement","createGain","createChannelSplitter","outputs","createChannelMerger","inputs","resume","Promise","reject","resolve","close","installFakeAudioContext","vi","stubGlobal","onlyAudioContext","reachingDestination","ctx","ears","left","right","rest"],"sourceRoot":"../../../src","sources":["test-utils/fakeAudioContext.ts"],"mappings":";;;;;;;;;;AAaA,IAAAA,OAAA,GAAAC,OAAA;AAbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAUA;AACA;AACA;AACA;;AAGA;;AAGA;AACA,MAAMC,kBAA4C,GAAG;EACnD,CAAC,EAAE,CAAC,GAAG,CAAC;EACR,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,CAAC;EACb,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC;EACzB,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI;AACtC,CAAC;AAED,MAAMC,GAAG,GAAGA,CAAC,GAAGC,QAAmB,KACjC,CAAC,GAAG,IAAIC,GAAG,CAACD,QAAQ,CAACE,IAAI,CAAC,CAAC,CAAC,CAAC,CAACC,IAAI,CAAC,CAAC;;AAEtC;AACA;AACA;AACA;AACA;AACA,SAASC,GAAGA,CAACC,KAAa,EAAEC,KAAa,EAAEC,cAAsB,EAAU;EACzE,IAAIF,KAAK,CAACG,MAAM,KAAKF,KAAK,EAAE,OAAOD,KAAK;EACxC,IAAIE,cAAc,KAAK,UAAU,EAAE;IACjC,OAAOE,KAAK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K,EAAE,GAAGC,IAAI,CAAC,GAAGJ,GAAG,CAACrB,WAAW,CAACL,KAAK,CAAC,CAAC;EACtD,IAAI8B,IAAI,CAACvE,MAAM,GAAG,CAAC,EAAE,MAAM,IAAIU,KAAK,CAAC,+BAA+B,CAAC;EACrE,OAAO;IAAE2D,IAAI,EAAEA,IAAI,IAAI,EAAE;IAAEC,KAAK,EAAEA,KAAK,IAAI;EAAG,CAAC;AACjD","ignoreList":[]}
@@ -33,6 +33,7 @@ class NativeAudioBrowser extends _TrackPlayer.QueuePlayer {
33
33
  this.clearUpdateEventInterval();
34
34
  this.setPlaybackIntervalEnabled(false);
35
35
  this.remoteCommands.dispose();
36
+ this.closeChannelRouter();
36
37
  // Remove window event listeners to prevent memory leaks
37
38
  if (typeof window !== 'undefined' && this.onlineHandler) {
38
39
  window.removeEventListener('online', this.onlineHandler);
@@ -529,20 +530,23 @@ class NativeAudioBrowser extends _TrackPlayer.QueuePlayer {
529
530
  * keeps `activeTrack` ahead of `loading` — the order a consumer that reads
530
531
  * `getActiveTrack()` on the loading edge depends on.
531
532
  */
532
- transitionTo(track) {
533
+ transitionTo(track, reloadsActiveTrack) {
533
534
  const element = this.requireElement();
534
535
  const lastTrack = this.current;
535
536
  const lastPosition = element.currentTime;
536
537
  const lastIndex = this.queue.lastIndex;
537
538
  const currentIndex = this.queue.currentIndex;
538
539
 
539
- // A re-prepare of the item already current is not a transition, and must
540
- // not be announced as one: ExoPlayer's `prepare()` does not re-fire
540
+ // One rule: every load but a reload of the current queue entry is a new
541
+ // Active Track. That clears the Loop Range, which belongs to the Active
542
+ // Track, and is announced. The same `Track` at another queue entry, or a
543
+ // `load()` of the Active Track itself, is a new Active Track, as on iOS;
544
+ // comparing `Track` objects would miss both. A reload (a retry, a play
545
+ // after a stop) is not announced: ExoPlayer's `prepare()` does not re-fire
541
546
  // `onMediaItemTransition` for an unchanged media item, so a consumer that
542
- // resets on a track change would have its UI wiped by every retry. The
543
- // `lastTrack === track` payload was the tell.
544
- const isTransition = this.current !== track;
545
- if (isTransition) this.clearLoopRange();
547
+ // resets on a track change would have its UI wiped by every retry.
548
+ const isNewActiveTrack = !reloadsActiveTrack;
549
+ if (isNewActiveTrack) this.clearLoopRange();
546
550
 
547
551
  // `current` first, so `getActiveTrack()` already reads the new track inside
548
552
  // a handler and so `getNowPlaying()` publishes the new track's metadata. It
@@ -553,7 +557,7 @@ class NativeAudioBrowser extends _TrackPlayer.QueuePlayer {
553
557
 
554
558
  // Separately guarded: a throwing consumer handler must not skip the
555
559
  // publish, and neither may fail the load.
556
- if (isTransition) {
560
+ if (isNewActiveTrack) {
557
561
  // As Android's onMediaItemTransition does: a new item is a clean slate,
558
562
  // a retry of the same one keeps what the consumer set.
559
563
  this.nowPlayingManager.clearNowPlayingOverride();
@@ -596,7 +600,7 @@ class NativeAudioBrowser extends _TrackPlayer.QueuePlayer {
596
600
  type: 'trackLoading'
597
601
  });
598
602
  }
599
- load(track, callback) {
603
+ load(track, callback, options) {
600
604
  // Before the queue is touched, so a load before `setupPlayer()` throws
601
605
  // rather than half-applying.
602
606
  this.requireElement();
@@ -621,7 +625,7 @@ class NativeAudioBrowser extends _TrackPlayer.QueuePlayer {
621
625
  // are captured as pending seeks rather than silently dropped
622
626
  this._loadInProgress = true;
623
627
  this._pendingSeek = undefined;
624
- this.transitionTo(track);
628
+ this.transitionTo(track, reprepare || options?.reloadsActiveTrack === true);
625
629
 
626
630
  // Resolve the media URL before loading (async but we don't await)
627
631
  const doLoad = async () => {