swf2js 0.1.1 → 0.1.2
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/README.md +9 -9
- package/package.json +2 -1
- package/src/cli.js +15 -6
- package/src/emitter/bundle-emitter.js +56 -16
- package/src/runtime/avm1-runtime.js +329 -84
- package/src/runtime/avm2-runtime.js +56 -6
- package/src/runtime/embedded-movie-runtime.js +6 -1
- package/src/runtime/index.js +2 -6
- package/src/runtime/movie-runtime.js +2 -1
- package/src/runtime/swflib/assemble.js +34 -0
- package/src/runtime/swflib/bitmap-image.js +4 -0
- package/src/runtime/swflib/bitmap.js +1004 -0
- package/src/runtime/swflib/builtins.js +156 -0
- package/src/runtime/swflib/bytearray.js +949 -0
- package/src/runtime/swflib/compiled-swf.js +3 -0
- package/src/runtime/swflib/context-menu.js +245 -0
- package/src/runtime/swflib/cursor-flag.js +12 -0
- package/src/runtime/swflib/dictionary.js +121 -0
- package/src/runtime/swflib/display.js +823 -0
- package/src/runtime/swflib/events.js +754 -0
- package/src/runtime/swflib/filters.js +298 -0
- package/src/runtime/swflib/flash.js +130 -0
- package/src/runtime/swflib/geom.js +759 -0
- package/src/runtime/swflib/glyph-metrics.js +14 -0
- package/src/runtime/swflib/graphics.js +735 -0
- package/src/runtime/swflib/host.js +2 -0
- package/src/runtime/swflib/inherit.js +22 -0
- package/src/runtime/swflib/input.js +1085 -0
- package/src/runtime/swflib/loader.js +687 -0
- package/src/runtime/swflib/marks.js +16 -0
- package/src/runtime/swflib/matrix3d.js +144 -0
- package/src/runtime/swflib/pointer-bridge.js +8 -0
- package/src/runtime/swflib/projection.js +158 -0
- package/src/runtime/swflib/render.js +1240 -0
- package/src/runtime/swflib/sound.js +1166 -0
- package/src/runtime/swflib/sprite-drag.js +116 -0
- package/src/runtime/swflib/stage-ref.js +9 -0
- package/src/runtime/swflib/stage.js +484 -0
- package/src/runtime/swflib/system.js +987 -0
- package/src/runtime/swflib/text-field.js +519 -0
- package/src/runtime/swflib/text-paint.js +797 -0
- package/src/runtime/swflib/text.js +1387 -0
- package/src/runtime/swflib/transform.js +133 -0
- package/src/runtime/swflib/xml.js +268 -0
- package/src/transpiler/avm1/avm1-ir.js +2 -1
- package/src/transpiler/avm1/avm1-rewrite.js +23 -2
- package/src/transpiler/avm1/avm1-transpiler.js +4 -1
- package/src/transpiler/avm2/avm2-transpiler.js +38 -7
- package/src/transpiler/timeline/timeline-codegen.js +366 -123
- package/src/runtime/swflib.js +0 -14050
|
@@ -0,0 +1,1166 @@
|
|
|
1
|
+
import { ByteArray } from './bytearray.js';
|
|
2
|
+
import { Event, EventDispatcher, IOErrorEvent, ProgressEvent } from './events.js';
|
|
3
|
+
import { global } from './host.js';
|
|
4
|
+
import { Security } from './system.js';
|
|
5
|
+
|
|
6
|
+
// ---- media / filters / ui / system ----
|
|
7
|
+
export class SoundTransform {
|
|
8
|
+
constructor(vol, pan) {
|
|
9
|
+
this._volume = vol == null ? 1 : +vol;
|
|
10
|
+
this._pan = pan == null ? 0 : +pan;
|
|
11
|
+
this._leftToLeft = 1;
|
|
12
|
+
this._leftToRight = 0;
|
|
13
|
+
this._rightToLeft = 0;
|
|
14
|
+
this._rightToRight = 1;
|
|
15
|
+
this._channels = [];
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function soundTransformProperty(name) {
|
|
19
|
+
return {
|
|
20
|
+
enumerable: true, configurable: true,
|
|
21
|
+
get: function () { return this['_' + name]; },
|
|
22
|
+
set: function (value) {
|
|
23
|
+
this['_' + name] = +value || 0;
|
|
24
|
+
var channels = this._channels || [];
|
|
25
|
+
for (var i = 0; i < channels.length; i++) channels[i]._applyTransform();
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
Object.defineProperties(SoundTransform.prototype, {
|
|
30
|
+
volume: soundTransformProperty('volume'), pan: soundTransformProperty('pan'),
|
|
31
|
+
leftToLeft: soundTransformProperty('leftToLeft'), leftToRight: soundTransformProperty('leftToRight'),
|
|
32
|
+
rightToLeft: soundTransformProperty('rightToLeft'), rightToRight: soundTransformProperty('rightToRight'),
|
|
33
|
+
});
|
|
34
|
+
export var activeMixerSounds = new Map();
|
|
35
|
+
export var mixerTransform = new SoundTransform();
|
|
36
|
+
export function applyMixerVolume(audio, volume) {
|
|
37
|
+
if (!audio) return;
|
|
38
|
+
try { audio.volume = Math.max(0, Math.min(1, (+volume || 0) * mixerTransform.volume)); } catch (_) {}
|
|
39
|
+
}
|
|
40
|
+
export function registerMixerSound(stop, media, updateVolume) {
|
|
41
|
+
updateVolume = updateVolume || function () { applyMixerVolume(media(), 1); };
|
|
42
|
+
activeMixerSounds.set(stop, { media: media, updateVolume: updateVolume });
|
|
43
|
+
updateVolume();
|
|
44
|
+
return function () { activeMixerSounds.delete(stop); };
|
|
45
|
+
}
|
|
46
|
+
export function SoundMixer() {}
|
|
47
|
+
export function copyMixerTransform(source) {
|
|
48
|
+
var copy = new SoundTransform(source.volume, source.pan);
|
|
49
|
+
copy.leftToLeft = source.leftToLeft;
|
|
50
|
+
copy.leftToRight = source.leftToRight;
|
|
51
|
+
copy.rightToLeft = source.rightToLeft;
|
|
52
|
+
copy.rightToRight = source.rightToRight;
|
|
53
|
+
return copy;
|
|
54
|
+
}
|
|
55
|
+
Object.defineProperty(SoundMixer, 'soundTransform', {
|
|
56
|
+
get: function () { return copyMixerTransform(mixerTransform); },
|
|
57
|
+
set: function (value) {
|
|
58
|
+
if (value == null) throw new TypeError('Parameter sndTransform must be non-null.');
|
|
59
|
+
mixerTransform = copyMixerTransform(value);
|
|
60
|
+
if (mixerGraph) applyMixerStereo(mixerGraph);
|
|
61
|
+
for (var sound of activeMixerSounds.values()) sound.updateVolume();
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
SoundMixer.stopAll = function () {
|
|
65
|
+
for (var stop of Array.from(activeMixerSounds.keys())) stop();
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
export var mixerGraph = null;
|
|
69
|
+
export var mixerInputCount = 0;
|
|
70
|
+
export var mixerMediaNodes = new WeakMap();
|
|
71
|
+
export var mixerMediaCorsModes = new WeakMap();
|
|
72
|
+
export function rememberMixerMedia(audio) {
|
|
73
|
+
// Changing the attribute later does not establish access to the current response.
|
|
74
|
+
if (!mixerMediaCorsModes.has(audio)) mixerMediaCorsModes.set(audio, audio.crossOrigin != null);
|
|
75
|
+
}
|
|
76
|
+
export function soundAudioContext() {
|
|
77
|
+
var AudioContextClass = typeof AudioContext !== 'undefined' ? AudioContext
|
|
78
|
+
: typeof webkitAudioContext !== 'undefined' ? webkitAudioContext : null;
|
|
79
|
+
if (!AudioContextClass) return null;
|
|
80
|
+
return SoundChannel._audioContext || (SoundChannel._audioContext = new AudioContextClass());
|
|
81
|
+
}
|
|
82
|
+
export function soundMixerGraph(context) {
|
|
83
|
+
if (mixerGraph && mixerGraph.context === context) return mixerGraph;
|
|
84
|
+
if (!context.createGain || !context.createChannelSplitter || !context.createAnalyser) return null;
|
|
85
|
+
var input = context.createGain(), split = context.createChannelSplitter(2);
|
|
86
|
+
var left = context.createAnalyser(), right = context.createAnalyser();
|
|
87
|
+
if (!left.getFloatTimeDomainData || !right.getFloatTimeDomainData) return null;
|
|
88
|
+
input.channelCount = 2;
|
|
89
|
+
input.channelCountMode = 'explicit';
|
|
90
|
+
var output = input, matrix = null;
|
|
91
|
+
if (context.createChannelMerger) {
|
|
92
|
+
var stereo = context.createChannelSplitter(2);
|
|
93
|
+
output = context.createChannelMerger(2);
|
|
94
|
+
input.connect(stereo);
|
|
95
|
+
matrix = [];
|
|
96
|
+
for (var route = 0; route < 4; route++) {
|
|
97
|
+
var gain = context.createGain();
|
|
98
|
+
stereo.connect(gain, route >> 1);
|
|
99
|
+
gain.connect(output, 0, route & 1);
|
|
100
|
+
matrix.push(gain);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
output.connect(context.destination);
|
|
104
|
+
output.connect(split);
|
|
105
|
+
split.connect(left, 0);
|
|
106
|
+
split.connect(right, 1);
|
|
107
|
+
mixerGraph = { context: context, input: input, left: left, right: right, matrix: matrix };
|
|
108
|
+
applyMixerStereo(mixerGraph);
|
|
109
|
+
return mixerGraph;
|
|
110
|
+
}
|
|
111
|
+
export function applyMixerStereo(graph) {
|
|
112
|
+
if (!graph.matrix) return;
|
|
113
|
+
var pan = Math.max(-1, Math.min(1, mixerTransform.pan || 0));
|
|
114
|
+
var left = Math.sqrt(1 - pan), right = Math.sqrt(1 + pan);
|
|
115
|
+
var routes = [mixerTransform.leftToLeft, mixerTransform.leftToRight,
|
|
116
|
+
mixerTransform.rightToLeft, mixerTransform.rightToRight];
|
|
117
|
+
for (var route = 0; route < routes.length; route++) {
|
|
118
|
+
graph.matrix[route].gain.value = Number.isFinite(routes[route]) ? routes[route] * (route & 1 ? right : left) : 0;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
export function mediaOrigin(audio) {
|
|
122
|
+
var src = audio.currentSrc || audio.src, page = global.location?.href;
|
|
123
|
+
if (!src || !page) return null;
|
|
124
|
+
try {
|
|
125
|
+
var base = new URL(page), url = new URL(src, global.document?.baseURI || base);
|
|
126
|
+
return { sameOrigin: url.origin === base.origin, protocol: url.protocol };
|
|
127
|
+
} catch (_) { return false; }
|
|
128
|
+
}
|
|
129
|
+
export function analyzableMedia(audio) {
|
|
130
|
+
var origin = mediaOrigin(audio);
|
|
131
|
+
return origin === null || !!(origin && (origin.protocol === 'data:' ||
|
|
132
|
+
(origin.sameOrigin && origin.protocol !== 'file:') || mixerMediaCorsModes.get(audio)));
|
|
133
|
+
}
|
|
134
|
+
SoundMixer.areSoundsInaccessible = function () {
|
|
135
|
+
for (var sound of activeMixerSounds.values()) {
|
|
136
|
+
var audio = sound.media();
|
|
137
|
+
if (!audio || audio.paused !== false || audio.ended || audio.error || mixerMediaCorsModes.get(audio) !== false ||
|
|
138
|
+
!(audio.readyState >= 2)) continue;
|
|
139
|
+
var origin = mediaOrigin(audio);
|
|
140
|
+
if (origin && !origin.sameOrigin && (origin.protocol === 'https:' || origin.protocol === 'http:')) return true;
|
|
141
|
+
}
|
|
142
|
+
return false;
|
|
143
|
+
};
|
|
144
|
+
export function resumeSoundContext(context) {
|
|
145
|
+
if (context.state === 'suspended' && context.resume) {
|
|
146
|
+
var resume = context.resume();
|
|
147
|
+
if (resume && resume.catch) resume.catch(function () {});
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
export function routeMixerMedia(audio) {
|
|
151
|
+
try {
|
|
152
|
+
rememberMixerMedia(audio);
|
|
153
|
+
if (!analyzableMedia(audio)) return null;
|
|
154
|
+
var context = soundAudioContext();
|
|
155
|
+
// Do not divert already permitted HTML playback into a locked graph.
|
|
156
|
+
if (context && context.state === 'suspended' && !global.navigator?.userActivation?.isActive) return null;
|
|
157
|
+
var graph = context && soundMixerGraph(context);
|
|
158
|
+
if (!graph) return null;
|
|
159
|
+
var source = mixerMediaNodes.get(audio);
|
|
160
|
+
if (!source) {
|
|
161
|
+
source = context.createMediaElementSource(audio);
|
|
162
|
+
mixerMediaNodes.set(audio, source);
|
|
163
|
+
}
|
|
164
|
+
resumeSoundContext(context);
|
|
165
|
+
source.connect(graph.input);
|
|
166
|
+
mixerInputCount++;
|
|
167
|
+
return function () {
|
|
168
|
+
mixerInputCount--;
|
|
169
|
+
try { source.disconnect(graph.input); } catch (_) {}
|
|
170
|
+
};
|
|
171
|
+
} catch (_) { return null; }
|
|
172
|
+
}
|
|
173
|
+
export function mixerWaveform(analyser, rate) {
|
|
174
|
+
var ratio = rate / 44100;
|
|
175
|
+
var available = Math.ceil(511 * ratio) + 1;
|
|
176
|
+
analyser.fftSize = Math.max(32, Math.pow(2, Math.ceil(Math.log2(available))));
|
|
177
|
+
var buffer = new Float32Array(analyser.fftSize);
|
|
178
|
+
analyser.getFloatTimeDomainData(buffer);
|
|
179
|
+
var wave = new Float32Array(512), first = buffer.length - available;
|
|
180
|
+
for (var i = 0; i < wave.length; i++) {
|
|
181
|
+
var offset = first + i * ratio, before = Math.floor(offset);
|
|
182
|
+
wave[i] = buffer[before] + (buffer[Math.min(before + 1, buffer.length - 1)] - buffer[before]) * (offset - before);
|
|
183
|
+
}
|
|
184
|
+
return wave;
|
|
185
|
+
}
|
|
186
|
+
export function mixerFFT(wave) {
|
|
187
|
+
// Flash-compatible spectrum spacing uses 512 captured samples padded to 2048.
|
|
188
|
+
var size = 2048, real = new Float64Array(size), imaginary = new Float64Array(size);
|
|
189
|
+
real.set(wave);
|
|
190
|
+
for (var i = 1, reversed = 0; i < size; i++) {
|
|
191
|
+
var bit = size >> 1;
|
|
192
|
+
while (reversed & bit) { reversed ^= bit; bit >>= 1; }
|
|
193
|
+
reversed ^= bit;
|
|
194
|
+
if (i < reversed) { var swap = real[i]; real[i] = real[reversed]; real[reversed] = swap; }
|
|
195
|
+
}
|
|
196
|
+
for (var span = 2; span <= size; span <<= 1) {
|
|
197
|
+
var half = span >> 1;
|
|
198
|
+
for (var j = 0; j < half; j++) {
|
|
199
|
+
var angle = -2 * Math.PI * j / span, cos = Math.cos(angle), sin = Math.sin(angle);
|
|
200
|
+
for (var i = j; i < size; i += span) {
|
|
201
|
+
var paired = i + half;
|
|
202
|
+
var r = cos * real[paired] - sin * imaginary[paired];
|
|
203
|
+
var m = sin * real[paired] + cos * imaginary[paired];
|
|
204
|
+
real[paired] = real[i] - r; imaginary[paired] = imaginary[i] - m;
|
|
205
|
+
real[i] += r; imaginary[i] += m;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return real.subarray(0, 512).map(function (value, k) {
|
|
210
|
+
// Flash's spectrum uses the log of the raw FFT magnitude and floors quiet bins.
|
|
211
|
+
return Math.log(Math.max(1, Math.hypot(value, imaginary[k]))) / 4;
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
SoundMixer.computeSpectrum = function (output, fft, stretchFactor) {
|
|
215
|
+
if (!(output instanceof ByteArray)) throw new TypeError('computeSpectrum requires a ByteArray');
|
|
216
|
+
if (SoundMixer.areSoundsInaccessible()) return;
|
|
217
|
+
var rate = mixerGraph && mixerGraph.context.sampleRate || 44100;
|
|
218
|
+
var stretch = Math.max(0, stretchFactor | 0);
|
|
219
|
+
output.length = 2048;
|
|
220
|
+
output.position = 0;
|
|
221
|
+
for (var side of ['left', 'right']) {
|
|
222
|
+
var samples = null;
|
|
223
|
+
if (mixerInputCount && mixerGraph && mixerGraph.context.state !== 'suspended') {
|
|
224
|
+
try { samples = mixerWaveform(mixerGraph[side], rate); } catch (_) {}
|
|
225
|
+
}
|
|
226
|
+
if (fft && samples) samples = mixerFFT(samples);
|
|
227
|
+
for (var i = 0; i < 256; i++) {
|
|
228
|
+
var index = stretch ? Math.floor(i / Math.max(1, stretch - 1)) : i * 2;
|
|
229
|
+
var value = samples ? samples[index] : 0;
|
|
230
|
+
output.writeFloat(Math.min(1, Math.max(-1, value || 0)));
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
output.position = 0;
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
export class SoundChannel extends EventDispatcher {
|
|
237
|
+
constructor() {
|
|
238
|
+
super();
|
|
239
|
+
this._position = 0;
|
|
240
|
+
this._soundTransform = null;
|
|
241
|
+
this._audio = null;
|
|
242
|
+
this._audioContext = null;
|
|
243
|
+
this._panner = null;
|
|
244
|
+
this._sourceNode = null;
|
|
245
|
+
this._splitter = null;
|
|
246
|
+
this._merger = null;
|
|
247
|
+
this._routeGains = null;
|
|
248
|
+
this._leftAnalyser = null;
|
|
249
|
+
this._rightAnalyser = null;
|
|
250
|
+
this.soundTransform = new SoundTransform();
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
stop() {
|
|
254
|
+
this._stopped = true;
|
|
255
|
+
if (this._releaseStreamEvents) this._releaseStreamEvents();
|
|
256
|
+
if (this._mixerRouted) { mixerInputCount--; this._mixerRouted = false; }
|
|
257
|
+
if (this._releaseMixerSound) { this._releaseMixerSound(); this._releaseMixerSound = null; }
|
|
258
|
+
if (this._swoofSoundScope) {
|
|
259
|
+
this._swoofSoundScope.channels.delete(this);
|
|
260
|
+
this._swoofSoundScope = null;
|
|
261
|
+
}
|
|
262
|
+
if (this._audio) {
|
|
263
|
+
if (this._mediaError) {
|
|
264
|
+
try { this._audio.removeEventListener('error', this._mediaError); } catch (_) {}
|
|
265
|
+
this._mediaError = null;
|
|
266
|
+
}
|
|
267
|
+
if (this._ended) {
|
|
268
|
+
try { this._audio.removeEventListener('ended', this._ended); } catch (_) {}
|
|
269
|
+
this._ended = null;
|
|
270
|
+
}
|
|
271
|
+
try { if (this._sourceNode) this._sourceNode.disconnect(); } catch (_) {}
|
|
272
|
+
try { if (this._panner) this._panner.disconnect(); } catch (_) {}
|
|
273
|
+
try { if (this._splitter) this._splitter.disconnect(); } catch (_) {}
|
|
274
|
+
try { if (this._merger) this._merger.disconnect(); } catch (_) {}
|
|
275
|
+
if (this._routeGains) for (var i = 0; i < this._routeGains.length; i++) {
|
|
276
|
+
try { this._routeGains[i].disconnect(); } catch (_) {}
|
|
277
|
+
}
|
|
278
|
+
this._position = (this._audio.currentTime || 0) * 1000;
|
|
279
|
+
try { this._audio.pause(); this._audio.currentTime = 0; } catch (_) {}
|
|
280
|
+
this._audio = null;
|
|
281
|
+
this._audioContext = null;
|
|
282
|
+
this._sourceNode = this._panner = this._splitter = this._merger = this._routeGains = null;
|
|
283
|
+
this._leftAnalyser = this._rightAnalyser = null;
|
|
284
|
+
}
|
|
285
|
+
var transform = this._soundTransform;
|
|
286
|
+
if (transform && transform._channels) {
|
|
287
|
+
var index = transform._channels.indexOf(this);
|
|
288
|
+
if (index >= 0) transform._channels.splice(index, 1);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
_applyTransform() {
|
|
292
|
+
var audio = this._audio, transform = this.soundTransform;
|
|
293
|
+
if (!audio || !transform) return;
|
|
294
|
+
applyMixerVolume(audio, transform.volume);
|
|
295
|
+
try {
|
|
296
|
+
if (!this._sourceNode && analyzableMedia(audio)) {
|
|
297
|
+
var context = soundAudioContext();
|
|
298
|
+
if (!context) return;
|
|
299
|
+
var graph = soundMixerGraph(context);
|
|
300
|
+
var destination = graph ? graph.input : context.destination;
|
|
301
|
+
resumeSoundContext(context);
|
|
302
|
+
this._audioContext = context;
|
|
303
|
+
this._sourceNode = context.createMediaElementSource(audio);
|
|
304
|
+
this._panner = context.createStereoPanner ? context.createStereoPanner() : null;
|
|
305
|
+
if (context.createChannelSplitter && context.createAnalyser) {
|
|
306
|
+
this._splitter = context.createChannelSplitter(2);
|
|
307
|
+
this._leftAnalyser = context.createAnalyser();
|
|
308
|
+
this._rightAnalyser = context.createAnalyser();
|
|
309
|
+
this._leftAnalyser.fftSize = this._rightAnalyser.fftSize = 256;
|
|
310
|
+
this._sourceNode.connect(this._splitter);
|
|
311
|
+
this._splitter.connect(this._leftAnalyser, 0);
|
|
312
|
+
this._splitter.connect(this._rightAnalyser, 1);
|
|
313
|
+
}
|
|
314
|
+
if (this._splitter && context.createChannelMerger && context.createGain) {
|
|
315
|
+
this._merger = context.createChannelMerger(2);
|
|
316
|
+
this._routeGains = [context.createGain(), context.createGain(), context.createGain(), context.createGain()];
|
|
317
|
+
this._splitter.connect(this._routeGains[0], 0); this._routeGains[0].connect(this._merger, 0, 0);
|
|
318
|
+
this._splitter.connect(this._routeGains[1], 0); this._routeGains[1].connect(this._merger, 0, 1);
|
|
319
|
+
this._splitter.connect(this._routeGains[2], 1); this._routeGains[2].connect(this._merger, 0, 0);
|
|
320
|
+
this._splitter.connect(this._routeGains[3], 1); this._routeGains[3].connect(this._merger, 0, 1);
|
|
321
|
+
if (this._panner) { this._merger.connect(this._panner); this._panner.connect(destination); }
|
|
322
|
+
else this._merger.connect(destination);
|
|
323
|
+
} else if (this._panner) {
|
|
324
|
+
this._sourceNode.connect(this._panner);
|
|
325
|
+
this._panner.connect(destination);
|
|
326
|
+
} else this._sourceNode.connect(destination);
|
|
327
|
+
if (graph) { this._mixerRouted = true; mixerInputCount++; }
|
|
328
|
+
}
|
|
329
|
+
if (this._routeGains) {
|
|
330
|
+
var coeffs = [transform.leftToLeft, transform.leftToRight, transform.rightToLeft, transform.rightToRight];
|
|
331
|
+
for (var gi = 0; gi < this._routeGains.length; gi++) this._routeGains[gi].gain.value = isFinite(+coeffs[gi]) ? +coeffs[gi] : 0;
|
|
332
|
+
}
|
|
333
|
+
if (this._panner) this._panner.pan.value = Math.max(-1, Math.min(1, +transform.pan || 0));
|
|
334
|
+
} catch (_) {}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
Object.defineProperty(SoundChannel.prototype, 'soundTransform', {
|
|
339
|
+
get: function () { return this._soundTransform || (this._soundTransform = new SoundTransform()); },
|
|
340
|
+
set: function (value) {
|
|
341
|
+
var old = this._soundTransform;
|
|
342
|
+
if (old && old._channels) {
|
|
343
|
+
var oldIndex = old._channels.indexOf(this);
|
|
344
|
+
if (oldIndex >= 0) old._channels.splice(oldIndex, 1);
|
|
345
|
+
}
|
|
346
|
+
this._soundTransform = value || new SoundTransform();
|
|
347
|
+
if (this._soundTransform._channels && this._soundTransform._channels.indexOf(this) < 0) this._soundTransform._channels.push(this);
|
|
348
|
+
this._applyTransform();
|
|
349
|
+
},
|
|
350
|
+
configurable: true,
|
|
351
|
+
});
|
|
352
|
+
Object.defineProperty(SoundChannel.prototype, 'position', {
|
|
353
|
+
get: function () { return this._audio ? (this._audio.currentTime || 0) * 1000 : this._position; },
|
|
354
|
+
configurable: true,
|
|
355
|
+
});
|
|
356
|
+
export function channelPeak(analyser) {
|
|
357
|
+
if (!analyser || !analyser.getFloatTimeDomainData) return 0;
|
|
358
|
+
var samples = new Float32Array(analyser.fftSize || 256);
|
|
359
|
+
try { analyser.getFloatTimeDomainData(samples); } catch (_) { return 0; }
|
|
360
|
+
var peak = 0;
|
|
361
|
+
for (var i = 0; i < samples.length; i++) peak = Math.max(peak, Math.abs(samples[i]));
|
|
362
|
+
return peak;
|
|
363
|
+
}
|
|
364
|
+
Object.defineProperty(SoundChannel.prototype, 'leftPeak', { get: function () { return channelPeak(this._leftAnalyser); } });
|
|
365
|
+
Object.defineProperty(SoundChannel.prototype, 'rightPeak', { get: function () { return channelPeak(this._rightAnalyser); } });
|
|
366
|
+
|
|
367
|
+
export function createMovieSoundScope(getHost) {
|
|
368
|
+
var scope = { channels: new Set(), loads: new Set(), stopped: false };
|
|
369
|
+
class MovieSound extends Sound {
|
|
370
|
+
constructor(request, context) {
|
|
371
|
+
// Defer load until scope/host are set (Sound.constructor loads when request != null).
|
|
372
|
+
super(undefined, undefined);
|
|
373
|
+
this._swoofSoundScope = scope;
|
|
374
|
+
this._swoofSoundHost = getHost;
|
|
375
|
+
if (request != null) this.load(request, context);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
Object.defineProperty(MovieSound, Symbol.hasInstance, { value: function (value) {
|
|
379
|
+
return Function.prototype[Symbol.hasInstance].call(this === MovieSound ? Sound : this, value);
|
|
380
|
+
} });
|
|
381
|
+
MovieSound.__swoofQualifiedName = 'flash.media.Sound';
|
|
382
|
+
return { Sound: MovieSound, stopAll: function () {
|
|
383
|
+
scope.stopped = true;
|
|
384
|
+
for (var channel of scope.channels) channel.stop();
|
|
385
|
+
for (var sound of scope.loads) sound._cancelSoundLoad();
|
|
386
|
+
} };
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
export function soundHost(sound) {
|
|
390
|
+
var host = sound._swoofSoundHost;
|
|
391
|
+
return typeof host === 'function' ? host() : host || global.__swoof;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
export class ID3Info {
|
|
395
|
+
constructor() {
|
|
396
|
+
this.album = this.artist = this.comment = this.genre =
|
|
397
|
+
this.songName = this.track = this.year = null;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
export function id3Latin1(bytes) {
|
|
402
|
+
var chunks = [];
|
|
403
|
+
for (var i = 0; i < bytes.length; i += 8192) {
|
|
404
|
+
chunks.push(String.fromCharCode.apply(null, bytes.subarray(i, i + 8192)));
|
|
405
|
+
}
|
|
406
|
+
return chunks.join('');
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
export function id3Size(bytes, start, shift, width) {
|
|
410
|
+
var size = 0;
|
|
411
|
+
for (var i = start; i < start + (width || 4); i++) {
|
|
412
|
+
if (shift === 7 && bytes[i] >= 128) return -1;
|
|
413
|
+
size = size * (1 << shift) + bytes[i];
|
|
414
|
+
}
|
|
415
|
+
return size;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
export function id3Unsync(bytes) {
|
|
419
|
+
var result = new Uint8Array(bytes.length);
|
|
420
|
+
var end = 0;
|
|
421
|
+
for (var i = 0; i < bytes.length; i++) {
|
|
422
|
+
result[end++] = bytes[i];
|
|
423
|
+
if (bytes[i] === 255 && bytes[i + 1] === 0) i++;
|
|
424
|
+
}
|
|
425
|
+
return result.subarray(0, end);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
export function id3Text(bytes, encoding) {
|
|
429
|
+
if (encoding === 0) return id3Latin1(bytes).split(String.fromCharCode(0))[0];
|
|
430
|
+
var label = encoding === 3 ? 'utf-8' : encoding === 2 || bytes[0] === 254 ? 'utf-16be' : 'utf-16le';
|
|
431
|
+
return new TextDecoder(label).decode(bytes).split(String.fromCharCode(0))[0];
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
export var id3Fields = {
|
|
435
|
+
TALB: 'album', TPE1: 'artist', COMM: 'comment', TCON: 'genre',
|
|
436
|
+
TIT2: 'songName', TRCK: 'track', TYER: 'year', TDRC: 'year',
|
|
437
|
+
TAL: 'album', TP1: 'artist', COM: 'comment', TCO: 'genre',
|
|
438
|
+
TT2: 'songName', TRK: 'track', TYE: 'year',
|
|
439
|
+
};
|
|
440
|
+
// ID3v2.3 Appendix A lists the original ID3v1 genres and Winamp extensions.
|
|
441
|
+
export var id3Genres = ('Blues|Classic Rock|Country|Dance|Disco|Funk|Grunge|Hip-Hop|Jazz|Metal|' +
|
|
442
|
+
'New Age|Oldies|Other|Pop|R&B|Rap|Reggae|Rock|Techno|Industrial|' +
|
|
443
|
+
'Alternative|Ska|Death Metal|Pranks|Soundtrack|Euro-Techno|Ambient|Trip-Hop|Vocal|Jazz+Funk|' +
|
|
444
|
+
'Fusion|Trance|Classical|Instrumental|Acid|House|Game|Sound Clip|Gospel|Noise|' +
|
|
445
|
+
'AlternRock|Bass|Soul|Punk|Space|Meditative|Instrumental Pop|Instrumental Rock|Ethnic|Gothic|' +
|
|
446
|
+
'Darkwave|Techno-Industrial|Electronic|Pop-Folk|Eurodance|Dream|Southern Rock|Comedy|Cult|Gangsta|' +
|
|
447
|
+
'Top 40|Christian Rap|Pop/Funk|Jungle|Native American|Cabaret|New Wave|Psychadelic|Rave|Showtunes|' +
|
|
448
|
+
'Trailer|Lo-Fi|Tribal|Acid Punk|Acid Jazz|Polka|Retro|Musical|Rock & Roll|Hard Rock|' +
|
|
449
|
+
'Folk|Folk-Rock|National Folk|Swing|Fast Fusion|Bebob|Latin|Revival|Celtic|Bluegrass|' +
|
|
450
|
+
'Avantgarde|Gothic Rock|Progressive Rock|Psychedelic Rock|Symphonic Rock|Slow Rock|Big Band|Chorus|Easy Listening|Acoustic|' +
|
|
451
|
+
'Humour|Speech|Chanson|Opera|Chamber Music|Sonata|Symphony|Booty Bass|Primus|Porn Groove|' +
|
|
452
|
+
'Satire|Slow Jam|Club|Tango|Samba|Folklore|Ballad|Power Ballad|Rhythmic Soul|Freestyle|' +
|
|
453
|
+
'Duet|Punk Rock|Drum Solo|A cappella|Euro-House|Dance Hall').split('|');
|
|
454
|
+
|
|
455
|
+
export function readSoundId3v2(bytes) {
|
|
456
|
+
if (bytes.length < 10 || bytes[0] !== 73 || bytes[1] !== 68 || bytes[2] !== 51) return null;
|
|
457
|
+
var version = bytes[3];
|
|
458
|
+
if (version < 2 || version > 4) return null;
|
|
459
|
+
var flags = bytes[5], size = id3Size(bytes, 6, 7);
|
|
460
|
+
if (size <= 0 || size > bytes.length - 10) return null;
|
|
461
|
+
var shortFrames = version === 2;
|
|
462
|
+
if (shortFrames && (flags & 64)) return null; // ID3v2.2 tag compression was never specified.
|
|
463
|
+
var tag = bytes.subarray(10, 10 + size);
|
|
464
|
+
if (version < 4 && (flags & 128)) tag = id3Unsync(tag);
|
|
465
|
+
var start = 0;
|
|
466
|
+
if (flags & 64) {
|
|
467
|
+
if (tag.length < 4) return null;
|
|
468
|
+
var extendedSize = id3Size(tag, 0, version === 4 ? 7 : 8);
|
|
469
|
+
if (extendedSize < 6) return null;
|
|
470
|
+
start = extendedSize + (version === 3 ? 4 : 0);
|
|
471
|
+
}
|
|
472
|
+
var info = null;
|
|
473
|
+
var idWidth = shortFrames ? 3 : 4;
|
|
474
|
+
var headerWidth = shortFrames ? 6 : 10;
|
|
475
|
+
while (start + headerWidth <= tag.length) {
|
|
476
|
+
var id = id3Latin1(tag.subarray(start, start + idWidth));
|
|
477
|
+
if (!/^[A-Z0-9]+$/.test(id)) break;
|
|
478
|
+
var length = id3Size(tag, start + idWidth, version === 4 ? 7 : 8, idWidth);
|
|
479
|
+
var format = shortFrames ? 0 : tag[start + 9];
|
|
480
|
+
start += headerWidth;
|
|
481
|
+
if (length < 0 || start + length > tag.length) break;
|
|
482
|
+
var data = tag.subarray(start, start + length);
|
|
483
|
+
start += length;
|
|
484
|
+
if ((version === 3 && (format & 0xe0)) || (version === 4 && (format & 0x4c))) continue;
|
|
485
|
+
if (version === 4 && ((flags & 128) || (format & 2))) data = id3Unsync(data);
|
|
486
|
+
if (version === 4 && (format & 1)) data = data.subarray(4);
|
|
487
|
+
var comment = id === 'COM' || id === 'COMM';
|
|
488
|
+
if (!data.length || data[0] > (shortFrames ? 1 : 3) ||
|
|
489
|
+
(!comment && (id[0] !== 'T' || id === 'TXX' || id === 'TXXX'))) continue;
|
|
490
|
+
var encoding = data[0], textStart = 1;
|
|
491
|
+
if (comment) {
|
|
492
|
+
var stride = encoding === 1 || encoding === 2 ? 2 : 1;
|
|
493
|
+
textStart = 4;
|
|
494
|
+
while (textStart + stride <= data.length) {
|
|
495
|
+
var terminator = data[textStart] === 0 && (stride === 1 || data[textStart + 1] === 0);
|
|
496
|
+
textStart += stride;
|
|
497
|
+
if (terminator) break;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
if (textStart >= data.length) continue;
|
|
501
|
+
var value = id3Text(data.subarray(textStart), encoding);
|
|
502
|
+
if (!value) continue;
|
|
503
|
+
if (!info) info = new ID3Info();
|
|
504
|
+
if (info[id] == null) info[id] = value;
|
|
505
|
+
var property = id3Fields[id];
|
|
506
|
+
if (property && info[property] == null) info[property] = value;
|
|
507
|
+
}
|
|
508
|
+
return info;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
export function readSoundId3(bytes) {
|
|
512
|
+
var info = readSoundId3v2(bytes);
|
|
513
|
+
if (bytes.length < 128) return info;
|
|
514
|
+
var tail = bytes.subarray(bytes.length - 128);
|
|
515
|
+
if (tail[0] !== 84 || tail[1] !== 65 || tail[2] !== 71) return info;
|
|
516
|
+
var hasTrack = tail[125] === 0 && tail[126] !== 0;
|
|
517
|
+
var fields = [
|
|
518
|
+
['songName', 3, 33], ['artist', 33, 63], ['album', 63, 93],
|
|
519
|
+
['year', 93, 97], ['comment', 97, hasTrack ? 125 : 127],
|
|
520
|
+
];
|
|
521
|
+
for (var [name, start, end] of fields) {
|
|
522
|
+
var value = id3Text(tail.subarray(start, end), 0).trimEnd();
|
|
523
|
+
if (!value) continue;
|
|
524
|
+
if (!info) info = new ID3Info();
|
|
525
|
+
if (info[name] == null) info[name] = value;
|
|
526
|
+
}
|
|
527
|
+
var genre = id3Genres[tail[127]];
|
|
528
|
+
if (hasTrack || genre) {
|
|
529
|
+
if (!info) info = new ID3Info();
|
|
530
|
+
if (hasTrack && info.track == null) info.track = String(tail[126]);
|
|
531
|
+
if (genre && info.genre == null) info.genre = genre;
|
|
532
|
+
}
|
|
533
|
+
return info;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
export var soundUrlPrefixLimit = 65536;
|
|
537
|
+
export async function readUrlSoundPrefix(url, signal) {
|
|
538
|
+
var response = await global.fetch(url, {
|
|
539
|
+
headers: { Range: 'bytes=0-' + (soundUrlPrefixLimit - 1) },
|
|
540
|
+
signal: signal,
|
|
541
|
+
});
|
|
542
|
+
if (!response.body) return null;
|
|
543
|
+
var reader = response.body.getReader();
|
|
544
|
+
var length = 0, ended = false;
|
|
545
|
+
try {
|
|
546
|
+
if (signal.aborted || (response.status !== 200 && response.status !== 206)) return null;
|
|
547
|
+
var range = /^bytes 0-(\d+)\/(\d+|\*)$/.exec(response.headers.get('Content-Range') || '');
|
|
548
|
+
// A CORS response may hide Content-Range. The request starts at zero,
|
|
549
|
+
// but without its total we cannot treat a partial response as the file.
|
|
550
|
+
if (response.status === 206 && response.headers.has('Content-Range') && !range) return null;
|
|
551
|
+
var buffer = new Uint8Array(soundUrlPrefixLimit);
|
|
552
|
+
while (length < buffer.length) {
|
|
553
|
+
var chunk = await reader.read();
|
|
554
|
+
if (chunk.done) { ended = true; break; }
|
|
555
|
+
var bytes = chunk.value.subarray(0, buffer.length - length);
|
|
556
|
+
buffer.set(bytes, length);
|
|
557
|
+
length += bytes.length;
|
|
558
|
+
}
|
|
559
|
+
var prefix = buffer.subarray(0, length);
|
|
560
|
+
var whole = response.status === 200 ? ended : range && Number(range[1]) + 1 === length && Number(range[2]) === length;
|
|
561
|
+
return { bytes: prefix, whole: Boolean(whole) };
|
|
562
|
+
} finally {
|
|
563
|
+
if (!ended) reader.cancel().catch(function () {});
|
|
564
|
+
reader.releaseLock();
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
export async function readUrlSoundId3Footer(url, signal) {
|
|
569
|
+
var response = await global.fetch(url, { headers: { Range: 'bytes=-128' }, signal: signal });
|
|
570
|
+
if (!response.body) return null;
|
|
571
|
+
var reader = response.body.getReader();
|
|
572
|
+
var ended = false;
|
|
573
|
+
try {
|
|
574
|
+
// A 200 response means the server ignored the range. Cancel before reading.
|
|
575
|
+
var range = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(response.headers.get('Content-Range') || '');
|
|
576
|
+
if (signal.aborted || response.status !== 206 || !range) return null;
|
|
577
|
+
var start = Number(range[1]), end = Number(range[2]), total = Number(range[3]);
|
|
578
|
+
if (!Number.isSafeInteger(total) || total < 128 || start !== total - 128 || end !== total - 1) return null;
|
|
579
|
+
var footer = new Uint8Array(128), length = 0;
|
|
580
|
+
while (true) {
|
|
581
|
+
var chunk = await reader.read();
|
|
582
|
+
if (chunk.done) { ended = true; break; }
|
|
583
|
+
if (chunk.value.length > footer.length - length) return null;
|
|
584
|
+
footer.set(chunk.value, length);
|
|
585
|
+
length += chunk.value.length;
|
|
586
|
+
}
|
|
587
|
+
return length === footer.length ? readSoundId3(footer) : null;
|
|
588
|
+
} finally {
|
|
589
|
+
if (!ended) reader.cancel().catch(function () {});
|
|
590
|
+
reader.releaseLock();
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
export var extractionAudioContext;
|
|
595
|
+
export function decodeSoundForExtraction(bytes) {
|
|
596
|
+
var Context = global.OfflineAudioContext || global.webkitOfflineAudioContext;
|
|
597
|
+
if (!Context || !bytes.length) return null;
|
|
598
|
+
try {
|
|
599
|
+
if (!extractionAudioContext) extractionAudioContext = new Context(2, 1, 44100);
|
|
600
|
+
// Web Audio takes ownership of this ArrayBuffer.
|
|
601
|
+
return Promise.resolve(extractionAudioContext.decodeAudioData(new Uint8Array(bytes).buffer))
|
|
602
|
+
.catch(function () { return null; });
|
|
603
|
+
} catch (_) {
|
|
604
|
+
return null;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
export class SoundLoaderContext {
|
|
609
|
+
constructor(bufferTime, checkPolicyFile) {
|
|
610
|
+
this.bufferTime = bufferTime === undefined ? 1000 : Number(bufferTime);
|
|
611
|
+
this.checkPolicyFile = !!checkPolicyFile;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/** Seed Sound fields onto an existing object (AS2 subclass super() cannot call ES class ctors). */
|
|
616
|
+
export function installSoundInstance(sound) {
|
|
617
|
+
if (!sound || typeof sound !== 'object') return sound;
|
|
618
|
+
if (!sound._listeners) sound._listeners = Object.create(null);
|
|
619
|
+
sound.length = sound.length || 0;
|
|
620
|
+
if (sound.url === undefined) sound.url = null;
|
|
621
|
+
sound.bytesLoaded = sound.bytesLoaded || 0;
|
|
622
|
+
sound.bytesTotal = sound.bytesTotal || 0;
|
|
623
|
+
if (sound.isStreaming == null) sound.isStreaming = false;
|
|
624
|
+
if (sound._id === undefined) sound._id = null;
|
|
625
|
+
if (sound._channel === undefined) sound._channel = null;
|
|
626
|
+
if (!(sound._channels instanceof Set)) sound._channels = new Set();
|
|
627
|
+
if (sound._audio === undefined) sound._audio = null;
|
|
628
|
+
if (sound._id3 === undefined) sound._id3 = null;
|
|
629
|
+
if (sound._extractionPcm === undefined) sound._extractionPcm = null;
|
|
630
|
+
sound._extractionPosition = sound._extractionPosition || 0;
|
|
631
|
+
return sound;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
export class Sound extends EventDispatcher {
|
|
635
|
+
constructor(request, context) {
|
|
636
|
+
super();
|
|
637
|
+
installSoundInstance(this);
|
|
638
|
+
if (request != null) this.load(request, context);
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
setVolume(value) {
|
|
642
|
+
this._volume = Math.max(0, Math.min(100, +value || 0));
|
|
643
|
+
if (this._channel) this._channel.soundTransform.volume = this._volume / 100;
|
|
644
|
+
}
|
|
645
|
+
getVolume() { return this._volume == null ? 100 : this._volume; }
|
|
646
|
+
load(req, context) {
|
|
647
|
+
var self = this;
|
|
648
|
+
var scope = this._swoofSoundScope;
|
|
649
|
+
if (scope && scope.stopped) return;
|
|
650
|
+
this._cancelSoundLoad();
|
|
651
|
+
var generation = this._loadGeneration;
|
|
652
|
+
this._closedSound = false;
|
|
653
|
+
this._loadingSound = true;
|
|
654
|
+
this._streamBufferTime = Math.max(0, Number(context?.bufferTime ?? 1000) || 0) / 1000;
|
|
655
|
+
this.length = this.bytesLoaded = this.bytesTotal = 0;
|
|
656
|
+
this._id3 = null;
|
|
657
|
+
if (scope) scope.loads.add(this);
|
|
658
|
+
var url = req && (req.url || req) || this.url;
|
|
659
|
+
if (!url || typeof Audio === 'undefined') {
|
|
660
|
+
setTimeout(function () {
|
|
661
|
+
if (!self._finishSoundLoad(generation)) return;
|
|
662
|
+
try { self.dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR, false, false, 'No audio source available')); } catch (_) {}
|
|
663
|
+
}, 0);
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
this.url = url;
|
|
667
|
+
var policy = context && context.checkPolicyFile && Security._checkPolicyFiles(url);
|
|
668
|
+
if (policy) {
|
|
669
|
+
this._loadPolicy = policy.then(function () {
|
|
670
|
+
if (self._loadGeneration !== generation) return;
|
|
671
|
+
self._loadPolicy = null;
|
|
672
|
+
self._loadAudio(url, generation);
|
|
673
|
+
});
|
|
674
|
+
} else this._loadAudio(url, generation);
|
|
675
|
+
}
|
|
676
|
+
loadCompressedDataFromByteArray(bytes, bytesLength) {
|
|
677
|
+
var scope = this._swoofSoundScope;
|
|
678
|
+
if (scope && scope.stopped) return;
|
|
679
|
+
if (!(bytes instanceof ByteArray)) throw new TypeError('Expected a ByteArray');
|
|
680
|
+
var length = bytesLength >>> 0;
|
|
681
|
+
if (length > bytes.bytesAvailable) throw new RangeError('Not enough bytes to read the MP3 data');
|
|
682
|
+
var begin = bytes.position;
|
|
683
|
+
var raw = bytes._getU8().subarray(begin, begin + length);
|
|
684
|
+
var url = 'data:audio/mpeg;base64,' + btoa(id3Latin1(raw));
|
|
685
|
+
var info = readSoundId3(raw);
|
|
686
|
+
bytes.position = begin + length;
|
|
687
|
+
this._cancelSoundLoad();
|
|
688
|
+
var generation = this._loadGeneration;
|
|
689
|
+
this._closedSound = false;
|
|
690
|
+
this._loadingSound = true;
|
|
691
|
+
if (scope) scope.loads.add(this);
|
|
692
|
+
this.url = null;
|
|
693
|
+
this.length = 0;
|
|
694
|
+
this.bytesLoaded = this.bytesTotal = length;
|
|
695
|
+
this._id3 = info;
|
|
696
|
+
this._loadAudio(url, generation, decodeSoundForExtraction(raw));
|
|
697
|
+
if (info && this._loadGeneration === generation) {
|
|
698
|
+
this.dispatchEvent(new Event(Event.ID3));
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
extract(target, length, startPosition) {
|
|
702
|
+
if (!(target instanceof ByteArray)) throw new TypeError('Expected a ByteArray target');
|
|
703
|
+
var pcm = this._extractionPcm;
|
|
704
|
+
if (!pcm || !Number.isFinite(+length) || length <= 0) return 0;
|
|
705
|
+
var position = startPosition === undefined || +startPosition === -1
|
|
706
|
+
? this._extractionPosition : Math.trunc(+startPosition);
|
|
707
|
+
if (!Number.isFinite(position) || position < 0) return 0;
|
|
708
|
+
position = Math.min(position, pcm.length);
|
|
709
|
+
var count = Math.min(Math.floor(+length), pcm.length - position);
|
|
710
|
+
if (!count) return 0;
|
|
711
|
+
var left = pcm.getChannelData(0);
|
|
712
|
+
var right = pcm.numberOfChannels === 1 ? left : pcm.getChannelData(1);
|
|
713
|
+
var end = position + count;
|
|
714
|
+
for (var i = position; i < end; i++) {
|
|
715
|
+
target.writeFloat(left[i]);
|
|
716
|
+
target.writeFloat(right[i]);
|
|
717
|
+
}
|
|
718
|
+
this._extractionPosition = end;
|
|
719
|
+
return count;
|
|
720
|
+
}
|
|
721
|
+
_probeSoundBytes(url, generation) {
|
|
722
|
+
if (typeof global.fetch !== 'function' || typeof global.AbortController !== 'function') return;
|
|
723
|
+
try {
|
|
724
|
+
var resolved = new URL(url, global.location?.href);
|
|
725
|
+
if (!/^https?:$/.test(resolved.protocol) || !/\.mp3$/i.test(resolved.pathname)) return;
|
|
726
|
+
} catch (_) { return; }
|
|
727
|
+
var controller = new global.AbortController();
|
|
728
|
+
var self = this;
|
|
729
|
+
this._soundByteProbe = controller;
|
|
730
|
+
function active() {
|
|
731
|
+
return !controller.signal.aborted && self._loadGeneration === generation;
|
|
732
|
+
}
|
|
733
|
+
readUrlSoundPrefix(resolved.href, controller.signal).then(async function (result) {
|
|
734
|
+
if (!result || !active()) return;
|
|
735
|
+
var info = result.whole ? readSoundId3(result.bytes) : readSoundId3v2(result.bytes);
|
|
736
|
+
var bytes = result.bytes;
|
|
737
|
+
var hasV2Header = bytes[0] === 73 && bytes[1] === 68 && bytes[2] === 51;
|
|
738
|
+
if (!result.whole && bytes.length >= 3 && !hasV2Header) {
|
|
739
|
+
info = await readUrlSoundId3Footer(resolved.href, controller.signal);
|
|
740
|
+
if (!active()) return;
|
|
741
|
+
}
|
|
742
|
+
if (info) {
|
|
743
|
+
self._id3 = info;
|
|
744
|
+
self.dispatchEvent(new Event(Event.ID3));
|
|
745
|
+
}
|
|
746
|
+
if (!result.whole || !active()) return;
|
|
747
|
+
var pcm = await decodeSoundForExtraction(result.bytes);
|
|
748
|
+
if (active() && pcm?.numberOfChannels > 0 && pcm.sampleRate === 44100) self._extractionPcm = pcm;
|
|
749
|
+
}).catch(function () {}).finally(function () {
|
|
750
|
+
if (self._soundByteProbe !== controller) return;
|
|
751
|
+
self._soundByteProbe = null;
|
|
752
|
+
if (!self._loadingSound) self._swoofSoundScope?.loads.delete(self);
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
_finishSoundLoad(generation) {
|
|
756
|
+
if (this._loadGeneration !== generation || !this._loadingSound) return false;
|
|
757
|
+
this._loadingSound = false;
|
|
758
|
+
if (!this._soundByteProbe) this._swoofSoundScope?.loads.delete(this);
|
|
759
|
+
if (this._audio) {
|
|
760
|
+
this._audio.oncanplaythrough = this._audio.onerror = this._audio.onloadstart =
|
|
761
|
+
this._audio.onloadedmetadata = this._audio.onprogress = this._audio.onsuspend = null;
|
|
762
|
+
}
|
|
763
|
+
return true;
|
|
764
|
+
}
|
|
765
|
+
_cancelSoundLoad() {
|
|
766
|
+
this._loadGeneration = (this._loadGeneration || 0) + 1;
|
|
767
|
+
this._loadPolicy = null;
|
|
768
|
+
this._soundByteProbe?.abort();
|
|
769
|
+
this._soundByteProbe = null;
|
|
770
|
+
this._swoofSoundScope?.loads.delete(this);
|
|
771
|
+
this._streamBufferTime = null;
|
|
772
|
+
this._extractionPcm = null;
|
|
773
|
+
this._extractionPosition = 0;
|
|
774
|
+
this._finishSoundLoad(this._loadGeneration);
|
|
775
|
+
if (!this._audio) return;
|
|
776
|
+
try {
|
|
777
|
+
this._audio.pause();
|
|
778
|
+
this._audio.removeAttribute?.('src');
|
|
779
|
+
this._audio.load?.();
|
|
780
|
+
} catch (_) {}
|
|
781
|
+
this._audio = null;
|
|
782
|
+
}
|
|
783
|
+
_loadAudio(url, generation, extractionDecode) {
|
|
784
|
+
var self = this;
|
|
785
|
+
try {
|
|
786
|
+
var audio = new Audio();
|
|
787
|
+
audio.preload = 'auto';
|
|
788
|
+
this._audio = audio;
|
|
789
|
+
var started = global.performance?.now?.();
|
|
790
|
+
var opened = false, playable = false, hasNativeTotal = this.bytesTotal > 0;
|
|
791
|
+
var extractionPending = !!extractionDecode;
|
|
792
|
+
function active() { return self._loadingSound && self._loadGeneration === generation; }
|
|
793
|
+
function open() {
|
|
794
|
+
if (!active() || opened) return;
|
|
795
|
+
opened = true;
|
|
796
|
+
try { self.dispatchEvent(new Event(Event.OPEN)); } catch (_) {}
|
|
797
|
+
if (active() && self.url) self._probeSoundBytes(url, generation);
|
|
798
|
+
}
|
|
799
|
+
function update(event) {
|
|
800
|
+
if (!active()) return;
|
|
801
|
+
open();
|
|
802
|
+
if (!active()) return;
|
|
803
|
+
var duration = audio.duration;
|
|
804
|
+
if (Number.isFinite(duration)) self.length = duration * 1000;
|
|
805
|
+
var loaded = self.bytesLoaded, total = self.bytesTotal;
|
|
806
|
+
if (Number.isSafeInteger(event?.loaded) && event.loaded > loaded) loaded = event.loaded;
|
|
807
|
+
if (event?.lengthComputable && Number.isSafeInteger(event.total) && event.total > 0) {
|
|
808
|
+
hasNativeTotal = true;
|
|
809
|
+
total = Math.max(total, event.total);
|
|
810
|
+
}
|
|
811
|
+
if (started != null) {
|
|
812
|
+
var entries = global.performance.getEntriesByName?.(audio.currentSrc || audio.src, 'resource') || [];
|
|
813
|
+
for (var entry of entries) {
|
|
814
|
+
if (entry.initiatorType === 'audio' && entry.startTime >= started &&
|
|
815
|
+
entry.responseStatus === 200 && entry.decodedBodySize > 0) {
|
|
816
|
+
loaded = Math.max(loaded, entry.decodedBodySize);
|
|
817
|
+
total = Math.max(total, entry.decodedBodySize);
|
|
818
|
+
hasNativeTotal = true;
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
if (total) total = Math.max(loaded, total);
|
|
823
|
+
if (loaded !== self.bytesLoaded || total !== self.bytesTotal) {
|
|
824
|
+
self.bytesLoaded = loaded;
|
|
825
|
+
self.bytesTotal = total;
|
|
826
|
+
try { self.dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, loaded, total)); } catch (_) {}
|
|
827
|
+
}
|
|
828
|
+
if (!active() || !playable || extractionPending) return;
|
|
829
|
+
// Media readiness alone does not establish that download is complete.
|
|
830
|
+
if (!(hasNativeTotal && loaded >= total) && !soundMediaFullyBuffered(audio)) return;
|
|
831
|
+
if (self._finishSoundLoad(generation)) {
|
|
832
|
+
try { self.dispatchEvent(new Event(Event.COMPLETE)); } catch (_) {}
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
audio.onloadstart = open;
|
|
836
|
+
audio.onprogress = audio.onsuspend = audio.onloadedmetadata = update;
|
|
837
|
+
audio.oncanplaythrough = function () { playable = true; update(); };
|
|
838
|
+
audio.onerror = function () {
|
|
839
|
+
if (!self._finishSoundLoad(generation)) return;
|
|
840
|
+
self._soundByteProbe?.abort();
|
|
841
|
+
var message = audio.error?.message || 'Could not load audio: ' + url;
|
|
842
|
+
try { self.dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR, false, false, message)); } catch (_) {}
|
|
843
|
+
}
|
|
844
|
+
if (extractionDecode) {
|
|
845
|
+
function settleExtraction(pcm) {
|
|
846
|
+
if (!active()) return;
|
|
847
|
+
extractionPending = false;
|
|
848
|
+
if (pcm?.numberOfChannels > 0 && pcm.sampleRate === 44100) self._extractionPcm = pcm;
|
|
849
|
+
// Native media remains authoritative for whether playback is ready.
|
|
850
|
+
if (playable) update();
|
|
851
|
+
}
|
|
852
|
+
extractionDecode.then(settleExtraction);
|
|
853
|
+
}
|
|
854
|
+
audio.src = url;
|
|
855
|
+
} catch (error) {
|
|
856
|
+
setTimeout(function () {
|
|
857
|
+
if (!self._finishSoundLoad(generation)) return;
|
|
858
|
+
try { self.dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR, false, false, error.message)); } catch (_) {}
|
|
859
|
+
}, 0);
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
/** AS2: attachSound(id) then start(). id is library linkage / character id. */
|
|
863
|
+
attachSound(id) {
|
|
864
|
+
var host = soundHost(this);
|
|
865
|
+
var symbol = host?.exportAssets?.find(function (symbol) { return symbol.name === id; });
|
|
866
|
+
this._id = symbol ? symbol.id : id;
|
|
867
|
+
var asset = host?.assets?.find(function (asset) { return asset.id === this._id; }, this);
|
|
868
|
+
if (asset?.sampleRate) this.length = asset.sampleCount / asset.sampleRate * 1000;
|
|
869
|
+
else this.length = 0;
|
|
870
|
+
}
|
|
871
|
+
start(secondsOffset, loops) {
|
|
872
|
+
return this.play((Number(secondsOffset) || 0) * 1000, loops);
|
|
873
|
+
}
|
|
874
|
+
play(startTime, loops, sndTransform) {
|
|
875
|
+
var self = this, ch = new SoundChannel();
|
|
876
|
+
installSoundInstance(this);
|
|
877
|
+
var scope = this._swoofSoundScope;
|
|
878
|
+
if (scope && scope.stopped) { ch.stop(); return ch; }
|
|
879
|
+
if (scope) { scope.channels.add(ch); ch._swoofSoundScope = scope; }
|
|
880
|
+
this._channels.add(ch);
|
|
881
|
+
var release = registerMixerSound(function () { ch.stop(); }, function () { return ch._audio; },
|
|
882
|
+
function () { applyMixerVolume(ch._audio, ch.soundTransform.volume); });
|
|
883
|
+
ch._releaseMixerSound = function () { self._channels.delete(ch); release(); };
|
|
884
|
+
ch.soundTransform = sndTransform || new SoundTransform(this.getVolume() / 100, 0);
|
|
885
|
+
this._channel = ch;
|
|
886
|
+
var policy = this._loadPolicy;
|
|
887
|
+
if (policy) {
|
|
888
|
+
var generation = this._loadGeneration;
|
|
889
|
+
policy.then(function () {
|
|
890
|
+
if (ch._stopped) return;
|
|
891
|
+
if (self._loadGeneration === generation) self._playAudio(ch, startTime, loops);
|
|
892
|
+
else ch.stop();
|
|
893
|
+
});
|
|
894
|
+
} else this._playAudio(ch, startTime, loops);
|
|
895
|
+
return ch;
|
|
896
|
+
}
|
|
897
|
+
_playAudio(ch, startTime, loops) {
|
|
898
|
+
var id = this._id;
|
|
899
|
+
var loaded = soundHost(this)?.loaded;
|
|
900
|
+
var src = this._audio;
|
|
901
|
+
var urlPlayback = !!src && this._streamBufferTime != null;
|
|
902
|
+
if (!src && loaded && id != null && loaded[id]) src = loaded[id];
|
|
903
|
+
if (!src && this.url && !this._closedSound && typeof Audio !== 'undefined') {
|
|
904
|
+
try { src = new Audio(this.url); urlPlayback = true; } catch (_) { src = null; }
|
|
905
|
+
}
|
|
906
|
+
if (!src || typeof Audio === 'undefined') { ch.stop(); return; }
|
|
907
|
+
try {
|
|
908
|
+
var a = src.cloneNode ? src.cloneNode(true) : new Audio(src.src || src);
|
|
909
|
+
var repeatCount = Math.max(0, loops | 0);
|
|
910
|
+
var repeatsLeft = repeatCount;
|
|
911
|
+
var startSeconds = (+startTime || 0) / 1000;
|
|
912
|
+
a.loop = false;
|
|
913
|
+
if (startSeconds) a.currentTime = startSeconds;
|
|
914
|
+
ch._audio = a;
|
|
915
|
+
ch._urlSoundPlayback = urlPlayback;
|
|
916
|
+
rememberMixerMedia(a);
|
|
917
|
+
ch._applyTransform();
|
|
918
|
+
var self = this;
|
|
919
|
+
function startPlayback() {
|
|
920
|
+
var play = a.play();
|
|
921
|
+
if (play && play.catch) play.catch(function () { if (ch._audio === a) ch.stop(); });
|
|
922
|
+
}
|
|
923
|
+
ch._ended = function () {
|
|
924
|
+
if (ch._stopped || ch._audio !== a) return;
|
|
925
|
+
if (repeatsLeft > 1) {
|
|
926
|
+
repeatsLeft--;
|
|
927
|
+
try { a.currentTime = startSeconds; startPlayback(); } catch (_) { ch.stop(); }
|
|
928
|
+
return;
|
|
929
|
+
}
|
|
930
|
+
ch.stop();
|
|
931
|
+
try { ch.dispatchEvent(new Event(Event.SOUND_COMPLETE)); } catch (_) {}
|
|
932
|
+
if (self._channel === ch && typeof self.onSoundComplete === 'function') self.onSoundComplete();
|
|
933
|
+
}
|
|
934
|
+
a.addEventListener('ended', ch._ended);
|
|
935
|
+
ch._mediaError = function () { if (ch._audio === a) ch.stop(); };
|
|
936
|
+
a.addEventListener('error', ch._mediaError);
|
|
937
|
+
if (this._streamBufferTime == null || typeof a.readyState !== 'number') startPlayback();
|
|
938
|
+
else startBufferedSound(ch, a, this._streamBufferTime, startPlayback);
|
|
939
|
+
} catch (_) { ch.stop(); }
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
stop() {
|
|
943
|
+
if (this._channel) this._channel.stop();
|
|
944
|
+
this._channel = null;
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
close() {
|
|
948
|
+
this._closedSound = true;
|
|
949
|
+
this._cancelSoundLoad();
|
|
950
|
+
for (var channel of this._channels) {
|
|
951
|
+
var audio = channel._audio;
|
|
952
|
+
if (channel._urlSoundPlayback && audio && !audio.paused && !audio.seeking &&
|
|
953
|
+
!channel._streamBuffering && soundMediaFullyBuffered(audio)) continue;
|
|
954
|
+
channel.stop();
|
|
955
|
+
try { audio?.removeAttribute?.('src'); audio?.load?.(); } catch (_) {}
|
|
956
|
+
}
|
|
957
|
+
if (this._channel?._stopped) this._channel = null;
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
Object.defineProperties(Sound.prototype, {
|
|
962
|
+
duration: { get: function () { return this.length; } },
|
|
963
|
+
position: { get: function () { return this._channel ? this._channel.position : 0; } },
|
|
964
|
+
id3: { get: function () { return this._id3; } },
|
|
965
|
+
isBuffering: { get: function () {
|
|
966
|
+
for (var channel of this._channels) {
|
|
967
|
+
if (channel._streamBuffering) return true;
|
|
968
|
+
}
|
|
969
|
+
return false;
|
|
970
|
+
} },
|
|
971
|
+
});
|
|
972
|
+
|
|
973
|
+
export function soundMediaFullyBuffered(audio) {
|
|
974
|
+
var duration = audio?.duration, buffered = audio?.buffered;
|
|
975
|
+
return Number.isFinite(duration) && duration > 0 && buffered?.length === 1 &&
|
|
976
|
+
buffered.start(0) <= 0.001 && buffered.end(0) >= duration - 0.001;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
export function startBufferedSound(channel, audio, seconds, play) {
|
|
980
|
+
var readinessEvents = ['loadeddata', 'canplay', 'canplaythrough', 'progress', 'seeked'];
|
|
981
|
+
function clearReadiness() {
|
|
982
|
+
for (var type of readinessEvents) audio.removeEventListener(type, check);
|
|
983
|
+
}
|
|
984
|
+
function waiting() { channel._streamBuffering = true; }
|
|
985
|
+
function playing() { channel._streamBuffering = false; }
|
|
986
|
+
function check() {
|
|
987
|
+
if (channel._stopped || audio.seeking || audio.readyState < 2) return;
|
|
988
|
+
var position = audio.currentTime || 0;
|
|
989
|
+
var requiredEnd = Math.min(Number.isFinite(audio.duration) ? audio.duration : Infinity, position + seconds);
|
|
990
|
+
var buffered = audio.buffered;
|
|
991
|
+
var ready = seconds === 0 || requiredEnd <= position;
|
|
992
|
+
for (var i = 0; !ready && i < buffered?.length; i++) {
|
|
993
|
+
ready = buffered.start(i) <= position + 0.001 && buffered.end(i) >= requiredEnd - 0.001;
|
|
994
|
+
}
|
|
995
|
+
if (!ready) return;
|
|
996
|
+
clearReadiness();
|
|
997
|
+
try { play(); } catch (_) { channel.stop(); }
|
|
998
|
+
}
|
|
999
|
+
channel._releaseStreamEvents = function () {
|
|
1000
|
+
clearReadiness();
|
|
1001
|
+
audio.removeEventListener('waiting', waiting);
|
|
1002
|
+
audio.removeEventListener('playing', playing);
|
|
1003
|
+
channel._streamBuffering = false;
|
|
1004
|
+
channel._releaseStreamEvents = null;
|
|
1005
|
+
};
|
|
1006
|
+
for (var type of readinessEvents) audio.addEventListener(type, check);
|
|
1007
|
+
audio.addEventListener('waiting', waiting);
|
|
1008
|
+
audio.addEventListener('playing', playing);
|
|
1009
|
+
waiting();
|
|
1010
|
+
check();
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
export function createTimelineAudio(getMovie) {
|
|
1014
|
+
var activeTimelineSounds = Object.create(null);
|
|
1015
|
+
function pauseSound(audio) {
|
|
1016
|
+
try {
|
|
1017
|
+
if (audio.__swoofSoundChannel) audio.__swoofSoundChannel.stop();
|
|
1018
|
+
else { audio.pause(); audio.currentTime = 0; }
|
|
1019
|
+
} catch (_) {}
|
|
1020
|
+
}
|
|
1021
|
+
function stopTimelineSound(id) {
|
|
1022
|
+
var list = activeTimelineSounds[id] || [];
|
|
1023
|
+
delete activeTimelineSounds[id];
|
|
1024
|
+
for (var audio of list.slice()) audio.__swoofStopTimelineSound();
|
|
1025
|
+
}
|
|
1026
|
+
function stopAllTimelineSounds() {
|
|
1027
|
+
var ids = Object.keys(activeTimelineSounds);
|
|
1028
|
+
for (var i = 0; i < ids.length; i++) stopTimelineSound(ids[i]);
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
/** Play a loaded audio asset by character id (timeline StartSound / AS2). */
|
|
1032
|
+
function playTimelineSound(id, loops, soundInfo) {
|
|
1033
|
+
soundInfo = soundInfo || {};
|
|
1034
|
+
if (soundInfo.syncStop) { stopTimelineSound(id); return null; }
|
|
1035
|
+
var movie = getMovie();
|
|
1036
|
+
var loaded = movie && movie.loaded;
|
|
1037
|
+
if (!loaded || loaded[id] == null) return null;
|
|
1038
|
+
var active = activeTimelineSounds[id] || (activeTimelineSounds[id] = []);
|
|
1039
|
+
if (soundInfo.syncNoMultiple && active.length) return active[0];
|
|
1040
|
+
var src = loaded[id];
|
|
1041
|
+
try {
|
|
1042
|
+
var a = src.cloneNode ? src.cloneNode(true) : new Audio(src.src);
|
|
1043
|
+
rememberMixerMedia(a);
|
|
1044
|
+
var assets = movie.assets || [];
|
|
1045
|
+
var sampleRate = 44100;
|
|
1046
|
+
for (var mi = 0; mi < assets.length; mi++) if (assets[mi].id === (id | 0)) { sampleRate = assets[mi].sampleRate || sampleRate; break; }
|
|
1047
|
+
var startTime = soundInfo.inPoint == null ? 0 : soundInfo.inPoint / sampleRate;
|
|
1048
|
+
var endTime = soundInfo.outPoint == null ? (a.duration || Infinity) : soundInfo.outPoint / sampleRate;
|
|
1049
|
+
var repeats = Math.max(0, soundInfo.loopCount == null ? (loops | 0) - 1 : soundInfo.loopCount | 0);
|
|
1050
|
+
var envelope = Array.isArray(soundInfo.envelope) ? soundInfo.envelope.slice().sort(function (x, y) { return x.position - y.position; }) : [];
|
|
1051
|
+
a.loop = false;
|
|
1052
|
+
if (startTime) a.currentTime = startTime;
|
|
1053
|
+
var envelopeChannel = null, envelopeScheduled = false;
|
|
1054
|
+
if (envelope.length) {
|
|
1055
|
+
envelopeChannel = new SoundChannel();
|
|
1056
|
+
envelopeChannel._audio = a;
|
|
1057
|
+
envelopeChannel._applyTransform();
|
|
1058
|
+
a.__swoofSoundChannel = envelopeChannel;
|
|
1059
|
+
}
|
|
1060
|
+
function envelopeLevelsAt(position) {
|
|
1061
|
+
if (!envelope.length) return [32768, 32768];
|
|
1062
|
+
var next = 0;
|
|
1063
|
+
while (next < envelope.length && envelope[next].position < position) next++;
|
|
1064
|
+
var before = envelope[Math.max(0, next - 1)] || envelope[0];
|
|
1065
|
+
var after = envelope[Math.min(envelope.length - 1, next)] || before;
|
|
1066
|
+
if (position <= envelope[0].position) return [envelope[0].leftLevel, envelope[0].rightLevel];
|
|
1067
|
+
var span = after.position - before.position;
|
|
1068
|
+
var t = span > 0 ? Math.max(0, Math.min(1, (position - before.position) / span)) : 1;
|
|
1069
|
+
return [
|
|
1070
|
+
before.leftLevel + (after.leftLevel - before.leftLevel) * t,
|
|
1071
|
+
before.rightLevel + (after.rightLevel - before.rightLevel) * t,
|
|
1072
|
+
];
|
|
1073
|
+
}
|
|
1074
|
+
function normalizedLevel(value) { return Math.max(0, Math.min(1, (+value || 0) / 32768)); }
|
|
1075
|
+
function applyEnvelope() {
|
|
1076
|
+
if (!envelope.length) return;
|
|
1077
|
+
var position = (a.currentTime || 0) * 44100;
|
|
1078
|
+
var levels = envelopeLevelsAt(position), left = normalizedLevel(levels[0]), right = normalizedLevel(levels[1]);
|
|
1079
|
+
if (envelopeChannel && envelopeChannel._routeGains) {
|
|
1080
|
+
var values = [left, 0, 0, right];
|
|
1081
|
+
for (var gi = 0; gi < 4; gi++) envelopeChannel._routeGains[gi].gain.value = values[gi];
|
|
1082
|
+
applyMixerVolume(a, 1);
|
|
1083
|
+
} else {
|
|
1084
|
+
applyMixerVolume(a, (left + right) / 2);
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
function scheduleEnvelope() {
|
|
1088
|
+
envelopeScheduled = false;
|
|
1089
|
+
var gains = envelopeChannel && envelopeChannel._routeGains;
|
|
1090
|
+
var context = envelopeChannel && envelopeChannel._audioContext;
|
|
1091
|
+
if (!envelope.length || !gains || !context || typeof context.currentTime !== 'number' || !gains[0].gain.setValueAtTime || !gains[0].gain.linearRampToValueAtTime) {
|
|
1092
|
+
applyEnvelope();
|
|
1093
|
+
return;
|
|
1094
|
+
}
|
|
1095
|
+
var now = context.currentTime, samplePosition = (a.currentTime || 0) * 44100;
|
|
1096
|
+
var levels = envelopeLevelsAt(samplePosition);
|
|
1097
|
+
var initialValues = [normalizedLevel(levels[0]), 0, 0, normalizedLevel(levels[1])];
|
|
1098
|
+
for (var gi = 0; gi < 4; gi++) {
|
|
1099
|
+
var param = gains[gi].gain;
|
|
1100
|
+
try {
|
|
1101
|
+
param.cancelScheduledValues(now);
|
|
1102
|
+
param.setValueAtTime(initialValues[gi], now);
|
|
1103
|
+
} catch (_) { return applyEnvelope(); }
|
|
1104
|
+
}
|
|
1105
|
+
for (var ei = 0; ei < envelope.length; ei++) {
|
|
1106
|
+
var point = envelope[ei];
|
|
1107
|
+
if (point.position <= samplePosition) continue;
|
|
1108
|
+
var at = now + (point.position - samplePosition) / 44100;
|
|
1109
|
+
try {
|
|
1110
|
+
gains[0].gain.linearRampToValueAtTime(normalizedLevel(point.leftLevel), at);
|
|
1111
|
+
gains[3].gain.linearRampToValueAtTime(normalizedLevel(point.rightLevel), at);
|
|
1112
|
+
} catch (_) { return applyEnvelope(); }
|
|
1113
|
+
}
|
|
1114
|
+
envelopeScheduled = true;
|
|
1115
|
+
applyMixerVolume(a, 1);
|
|
1116
|
+
}
|
|
1117
|
+
function release() {
|
|
1118
|
+
var at = active.indexOf(a);
|
|
1119
|
+
if (at < 0) return;
|
|
1120
|
+
active.splice(at, 1);
|
|
1121
|
+
unregister();
|
|
1122
|
+
if (unroute) unroute();
|
|
1123
|
+
if (!active.length && activeTimelineSounds[id] === active) delete activeTimelineSounds[id];
|
|
1124
|
+
pauseSound(a);
|
|
1125
|
+
}
|
|
1126
|
+
function startPlayback() {
|
|
1127
|
+
try {
|
|
1128
|
+
var promise = a.play();
|
|
1129
|
+
if (promise && promise.catch) promise.catch(release);
|
|
1130
|
+
scheduleEnvelope();
|
|
1131
|
+
} catch (_) { release(); }
|
|
1132
|
+
}
|
|
1133
|
+
function finishOrRepeat() {
|
|
1134
|
+
if (activeTimelineSounds[id] !== active || active.indexOf(a) < 0) return;
|
|
1135
|
+
if (repeats > 0) {
|
|
1136
|
+
repeats--;
|
|
1137
|
+
try { a.currentTime = startTime; } catch (_) { release(); return; }
|
|
1138
|
+
startPlayback();
|
|
1139
|
+
} else release();
|
|
1140
|
+
}
|
|
1141
|
+
a.addEventListener('timeupdate', function () {
|
|
1142
|
+
if (activeTimelineSounds[id] !== active || active.indexOf(a) < 0) return;
|
|
1143
|
+
if (!envelopeScheduled) applyEnvelope();
|
|
1144
|
+
if (a.currentTime >= endTime) {
|
|
1145
|
+
try { a.pause(); } catch (_) {}
|
|
1146
|
+
finishOrRepeat();
|
|
1147
|
+
}
|
|
1148
|
+
});
|
|
1149
|
+
a.addEventListener('ended', finishOrRepeat);
|
|
1150
|
+
var unregister = registerMixerSound(release, function () { return a; }, function () {
|
|
1151
|
+
if (!envelope.length || envelopeScheduled) applyMixerVolume(a, 1);
|
|
1152
|
+
else applyEnvelope();
|
|
1153
|
+
});
|
|
1154
|
+
var unroute = envelopeChannel && envelopeChannel._sourceNode ? null : routeMixerMedia(a);
|
|
1155
|
+
a.__swoofStopTimelineSound = release;
|
|
1156
|
+
active.push(a);
|
|
1157
|
+
startPlayback();
|
|
1158
|
+
return a;
|
|
1159
|
+
} catch (_) {
|
|
1160
|
+
return null;
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
return { playSound: playTimelineSound, stopSound: stopTimelineSound, stopAll: stopAllTimelineSounds };
|
|
1165
|
+
}
|
|
1166
|
+
|