Remove unused cache.
[pwl6.git] / src / yuu / audio.js
1 /* Copyright 2014 Yukkuri Games
2 Licensed under the terms of the GNU GPL v2 or later
3 @license https://www.gnu.org/licenses/gpl-2.0.html
4 @source: https://yukkurigames.com/yuu/
5 */
6
7 (function (yuu) {
8 "use strict";
9
10 var yT = this.yT || require("./yT");
11 var yf = this.yf || require("./yf");
12
13 yuu.Audio = yT({
14 /** Audio context/source/buffer accessor
15
16 You probably don't need to make this yourself; one is made
17 named yuu.audio during initialization.
18
19 You can set the master volume with yuu.audio.masterVolume.
20 */
21 constructor: function () {
22 this._ctx = new window.AudioContext();
23 this._compressor = this._ctx.createDynamicsCompressor();
24 this._masterVolume = this._ctx.createGain();
25 this._masterVolume.connect(this._compressor);
26 this._compressor.connect(this._ctx.destination);
27 this._musicVolume = this._ctx.createGain();
28 this._musicVolume.connect(this._masterVolume);
29 this._masterVolume.gain.value = 0.5;
30 this._musicVolume.gain.value = 0.5;
31
32 this._mute = false;
33 this._storage = null;
34 this._volume = this._masterVolume.gain.value;
35 },
36
37 destination: { alias: "_masterVolume", readonly: true },
38 music: { alias: "_musicVolume", readonly: true },
39
40 _readStorage: function () {
41 if (!this._storage)
42 return;
43 yf.each.call(this, function (prop) {
44 this[prop] = this._storage.getObject(prop, this[prop]);
45 }, ["volume", "musicVolume", "mute"]);
46 },
47
48 _writeStorage: yf.debounce(function () {
49 if (!this._storage)
50 return;
51 yf.each.call(this, function (prop) {
52 this._storage.setObject(prop, this[prop]);
53 }, ["volume", "musicVolume", "mute"]);
54 }),
55
56 storage: {
57 get: function () { return this._storage; },
58 set: function (v) {
59 this._storage = v;
60 this._readStorage();
61 }
62 },
63
64 mute: {
65 get: function () { return this._mute; },
66 set: function (v) {
67 this._mute = !!v;
68 this.volume = this.volume;
69 }
70 },
71
72 volume: {
73 get: function () { return this._volume; },
74 set: function (v) {
75 this._volume = v;
76 v = this._mute ? 0 : v;
77 this._masterVolume.gain.value = v;
78 this._writeStorage();
79 }
80 },
81
82 musicVolume: {
83 get: function () { return this._musicVolume.gain.value; },
84 set: function (v) {
85 this._musicVolume.gain.value = v;
86 this._writeStorage();
87 }
88 },
89
90 currentTime: { alias: "_ctx.currentTime" },
91
92 decodeAudioData: function (data) {
93 var ctx = this._ctx;
94 try {
95 return ctx.decodeAudioData(data);
96 } catch (exc) {
97 return new Promise(function (resolve, reject) {
98 ctx.decodeAudioData(data, function (buffer) {
99 resolve(buffer);
100 }, function () {
101 reject(new Error("Error decoding audio buffer"));
102 });
103 });
104 }
105 },
106
107 createBufferSource: function (path) {
108 var source = this._ctx.createBufferSource();
109 var sample = yf.isString(path)
110 ? new yuu.AudioSample(path, this)
111 : path;
112 if ((source.buffer = sample.buffer) === null) {
113 sample.ready.then(function () {
114 source.buffer = sample.buffer;
115 });
116 }
117 return source;
118 },
119
120 sampleRate: { alias: "_ctx.sampleRate" },
121 createGain: { proxy: "_ctx.createGain" },
122 createOscillator: { proxy: "_ctx.createOscillator" },
123 });
124
125 // FIXME: This parsing is garbagey, would be better to parse when
126 // first handed a dfn and turn everything into a function.
127 function applyMod (s, v) {
128 if (yf.isFunction(s))
129 return s(v);
130 else if (s === +s)
131 return s;
132 else if (s[0] === "-" || s[0] === "+")
133 return v + (+s);
134 else if (s[0] === "x" || s[0] === "*")
135 return v * +s.substring(1);
136 else if (s[s.length - 1] === "%")
137 return v * (parseFloat(s) / 100);
138 else
139 return +s;
140 }
141
142 var Envelope = yuu.Envelope = yT({
143 constructor: function (timeline) {
144 timeline = timeline || { 0: 1 };
145 this.ts = Object.keys(timeline);
146 this.vs = yf.map.call(timeline, yf.getter, this.ts);
147 var ts = this.ts.filter(isFinite);
148 this.duration = (Math.max.apply(Math, ts)
149 - Math.min.apply(Math, ts));
150 this.unlimited = !this.duration || ts.length !== this.ts.length;
151 },
152
153 clampDuration: function (duration) {
154 return this.unlimited
155 ? Math.max(duration, this.duration)
156 : this.duration;
157 },
158
159 schedule: function (param, t0, scale, duration) {
160 yf.each(function (s, v) {
161 v = v * scale;
162 var t = t0 + applyMod(s, duration);
163 if (t === t0)
164 param.setValueAtTime(v, t);
165 else
166 param.linearRampToValueAtTime(v, t);
167 }, this.ts, this.vs);
168 }
169 });
170
171 yuu.AudioSample = yuu.Caching(yT({
172 constructor: function (path, ctx) {
173 ctx = ctx || yuu.audio;
174 var url = yuu.resourcePath(path, "sound", "wav");
175 this.data = null;
176 this.ready = yuu.GET(url, { responseType: "arraybuffer" })
177 .then(ctx.decodeAudioData.bind(ctx))
178 .then(yf.setter.bind(this, "buffer"))
179 .then(yf.K(this));
180 }
181 }), function (args) { return args.length <= 2 ? args[0] : null; });
182
183 yuu.Modulator = yT({
184 constructor: function (dfn) {
185 this.envelope = new Envelope(dfn.envelope);
186 this.frequency = dfn.frequency;
187 this.index = dfn.index || 1.0;
188 },
189
190 createModulator: function (ctx, t0, fundamental, duration) {
191 var modulator = ctx.createOscillator();
192 modulator.frequency.value = applyMod(
193 this.frequency, fundamental);
194 modulator.start(t0);
195 modulator.stop(t0 + duration);
196 var modulatorG = ctx.createGain();
197 modulator.connect(modulatorG);
198 this.envelope.schedule(
199 modulatorG.gain, t0, this.index * fundamental, duration);
200 return modulatorG;
201 }
202 });
203
204 var BaseInstrument = yT({
205 play: yf.argcd(
206 function () {
207 return this.play(null, 0, 0, 1, 1);
208 },
209 function (ctx, t, freq, amp, duration) {
210 ctx = ctx || yuu.audio;
211 t = t || ctx.currentTime;
212 var g = this.createSound(ctx, t, freq, amp, duration);
213 g.connect(ctx.destination);
214 return g;
215 }
216 )
217 });
218
219 var FastInstrument = yT(BaseInstrument, {
220 constructor: function (dfn) {
221 this.sample = new yuu.AudioSample(dfn);
222 this.ready = this.sample.ready.then(yf.K(this));
223 },
224
225 createSound: function (ctx, t0, fundamental, amplitude, duration) {
226 var src = ctx.createBufferSource(this.sample);
227 var ret = src;
228 src.start(t0, 0);
229 src.stop(t0 + duration);
230 if (amplitude !== 1.0) {
231 ret = ctx.createGain();
232 src.connect(ret);
233 ret.gain.value = amplitude;
234 }
235 return ret;
236 }
237 });
238
239 var Instrument = yT(BaseInstrument, {
240 constructor: function (dfn) {
241 this.envelope = new yuu.Envelope(dfn.envelope);
242 this.frequency = dfn.frequency || (dfn.sample ? {} : { "x1": 1.0 });
243 this.modulator = yf.map(
244 yf.new_(yuu.Modulator), yf.arrayify(dfn.modulator || []));
245 this.sample = dfn.sample || {};
246 this.ready = yuu.ready(
247 yf.map(yf.new_(yuu.AudioSample), Object.keys(this.sample)),
248 this);
249 },
250
251 createSound: function (ctx, t0, fundamental, amplitude, duration) {
252 duration = this.envelope.clampDuration(duration || 0);
253 var ret = ctx.createGain();
254 var dst = ret;
255
256 yf.ipairs(function (name, params) {
257 var buffer = new yuu.AudioSample(name).buffer;
258 if (buffer && !params.loop)
259 duration = Math.max(buffer.duration, duration);
260 }, this.sample);
261
262 var modulators = yf.map(function (modulator) {
263 return modulator.createModulator(
264 ctx, t0, fundamental, duration);
265 }, this.modulator);
266
267 yf.ipairs(function (name, params) {
268 var src = ctx.createBufferSource(name);
269 src.loop = params.loop || false;
270 src.playbackRate.value = applyMod(
271 params.playbackRate || 1, fundamental || ctx.sampleRate);
272 yf.each(function (mod) { mod.connect(src.playbackRate); },
273 modulators);
274 if (params.duration)
275 src.start(t0, params.offset || 0, params.duration);
276 else
277 src.start(t0, params.offset || 0);
278 src.stop(t0 + duration);
279 src.connect(dst);
280 }, this.sample);
281
282 yf.ipairs(function (mfreq, mamp) {
283 var osc = ctx.createOscillator();
284 osc.frequency.value = applyMod(mfreq, fundamental);
285 osc.start(t0);
286 osc.stop(t0 + duration);
287 yf.each(function (mod) { mod.connect(osc.frequency); },
288 modulators);
289 if (mamp !== 1) {
290 var gain = ctx.createGain();
291 gain.gain.value = mamp;
292 osc.connect(gain);
293 gain.connect(dst);
294 } else {
295 osc.connect(dst);
296 }
297 }, this.frequency);
298
299 ret.gain.value = 0;
300 this.envelope.schedule(ret.gain, t0, amplitude, duration);
301 return ret;
302 }
303 });
304
305 yuu.Instrument = function (dfn) {
306 return yf.isString(dfn)
307 ? new FastInstrument(dfn)
308 : new Instrument(dfn);
309 };
310
311 yuu.Instruments = yf.mapValues(yf.new_(yuu.Instrument), {
312 SINE: {
313 envelope: { "0": 0, "0.016": 1, "-0.016": 1, "100%": 0 },
314 },
315
316 ORGAN: {
317 envelope: { "0": 0, "0.016": 1, "-0.016": 1, "100%": 0 },
318 frequency: { "x1": 0.83, "x1.5": 0.17 }
319 },
320
321 SIREN: {
322 envelope: { "0": 1 },
323 modulator: {
324 envelope: { "0": 1 },
325 frequency: "1",
326 index: 0.2
327 }
328 },
329
330 BELL: {
331 envelope: { "0": 1, "2.5": 0.2, "5": 0 },
332 modulator: {
333 envelope: { "0": 1, "2.5": 0.2, "5": 0 },
334 frequency: "x1.5",
335 }
336 },
337
338 BRASS: {
339 envelope: { "0": 0, "0.2": 1, "0.4": 0.6, "-0.1": 0.5, "100%": 0 },
340 modulator: {
341 envelope: { "0": 0, "0.2": 1, "0.4": 0.6,
342 "-0.1": 0.5, "100%": 0 },
343 frequency: "x1",
344 index: 5.0
345 }
346 },
347 });
348
349 // Tune to A440 by default, although every interface should provide
350 // some ways to work around this. This gives C4 = ~261.63 Hz.
351 // https://en.wikipedia.org/wiki/Scientific_pitch_notation
352 yuu.C4_HZ = 440 * Math.pow(2, -9/12);
353
354 yuu.Scale = yT({
355 constructor: function (intervals) {
356 this.intervals = intervals;
357 this.length = this.intervals.length;
358 this.span = yf.foldl(function (a, b) { return a + b; }, intervals);
359 },
360
361 hz: function (tonic, degree, accidental) {
362 accidental = accidental || 0;
363 var s = this.span * ((degree / this.intervals.length) | 0)
364 + accidental;
365 degree %= this.intervals.length;
366 if (degree < 0) {
367 degree += this.intervals.length;
368 s -= this.span;
369 }
370 var i = 0;
371 while (degree >= 1) {
372 degree -= 1;
373 s += this.intervals[i];
374 i++;
375 }
376 if (degree > 0)
377 s += this.intervals[i] * degree;
378 return tonic * Math.pow(2, s / 1200.0);
379 }
380 });
381
382 yuu.Scales = yf.mapValues(yf.new_(yuu.Scale), {
383 CHROMATIC: yf.repeat(100, 12),
384 MINOR: [200, 100, 200, 200, 100, 200, 200],
385 MAJOR: [200, 200, 100, 200, 200, 200, 100],
386 WHOLE_TONE: [200, 200, 200, 200, 200, 200],
387 AUGMENTED: [300, 100, 300, 100, 300, 100],
388 _17ET: yf.repeat(1200 / 17, 17),
389 DOUBLE_HARMONIC: [100, 300, 100, 200, 100, 300, 100],
390 });
391
392 var DURATION = { T: 1/8, S: 1/4, I: 1/2, Q: 1, H: 2, W: 4,
393 ".": 1.5, "/": 1/3, "<": -1 };
394 var ACCIDENTAL = { b: -1, "#": 1, t: 0.5, d: -0.5 };
395
396 var NOTE = /([TSIQHW][<.\/]*)?(?:([XZ]|(?:[A-G][b#dt]*[0-9]+))|([+-]?[0-9.]+)([b#dt]*))|([-+<>{]|(?:[TSIQHW][.\/]?))/g;
397
398 var LETTERS = { Z: null, X: null };
399
400 yuu.parseNote = function (note, scale, C4) {
401 return (C4 || yuu.C4_HZ) * Math.pow(2, LETTERS[note] / 12);
402 };
403
404 yuu.parseScore = function (score, scale, tonic, C4) {
405 // Note language:
406 //
407 // To play a scientific pitch note and advance the time, just
408 // use its name: G4, Cb2, A#0
409 //
410 // To adjust the length of the note, use T, S, I, Q (default),
411 // H, W for 32nd through whole. Append . to do
412 // time-and-a-half. Append / to cut into a third. Append < to
413 // go back in time.
414 //
415 // To play a note on the provided scale, use a 0-based number
416 // (which can be negative). To move the current scale up or
417 // down, use + or -. For example, in C major, 0 and C4 produce
418 // the same note; after a -, 0 and C3 produce the same note.
419 //
420 // To rest, use Z or X.
421 //
422 // To play multiple notes at the same time, enclose them all with
423 // < ... >. The time will advance in accordance with the shortest
424 // one.
425 //
426 // To reset the time, scale offset, and duration, use a {.
427 // This can be more convenient when writing pieces with
428 // multiple parts than grouping, e.g.
429 // H < 1 8 > < 2 7 > < 3 6 > < 4 5 >
430 // is easier to understand when split into multiple lines:
431 // H 1 2 3 4
432 // { H 8 7 6 5
433
434 scale = scale || yuu.Scales.MAJOR;
435 C4 = C4 || yuu.C4_HZ;
436 tonic = tonic || scale.tonic || C4;
437 if (yf.isString(tonic))
438 tonic = yuu.parseNote(tonic, C4);
439
440 var t = 0;
441 var notes = [];
442 var degree = 0;
443 var groupLength = 0;
444 var defaultDuration = "Q";
445 var match;
446
447 function calcDuration (d, m) { return d * DURATION[m]; }
448 function calcAccidental (d, m) { return d * ACCIDENTAL[m]; }
449
450 while ((match = NOTE.exec(score))) {
451 switch (match[5]) {
452 case "<":
453 groupLength = Infinity;
454 break;
455 case ">":
456 t += groupLength === Infinity ? 0 : groupLength;
457 groupLength = 0;
458 break;
459 case "+":
460 degree += scale.length;
461 break;
462 case "-":
463 degree -= scale.length;
464 break;
465 case "{":
466 t = 0;
467 degree = 0;
468 groupLength = 0;
469 defaultDuration = "Q";
470 break;
471 default:
472 if (match[5]) {
473 defaultDuration = match[5];
474 continue;
475 }
476 var letter = match[2];
477 var duration = yf.foldl(
478 calcDuration, match[1] || defaultDuration, 1);
479 if (LETTERS[letter] !== null) {
480 var offset = match[3];
481 var accidental = yf.foldl(
482 calcAccidental, match[4] || "", 0) * 100;
483 notes.push({
484 time: t,
485 duration: duration,
486 hz: letter
487 ? C4 * Math.pow(2, LETTERS[letter]/12.0)
488 : scale.hz(tonic, degree + (+offset || 0), accidental)
489 });
490 }
491 if (groupLength && duration > 0)
492 groupLength = Math.min(groupLength, duration);
493 else
494 t += duration;
495 }
496 }
497
498 notes.sort(function (a, b) { return a.time - b.time; });
499 return notes;
500 };
501
502 yf.irange.call(LETTERS, function (i) {
503 yf.ipairs.call(this, function (l, o) {
504 var b = o + 12 * (i - 4);
505 this[l + i] = b;
506 yf.ipairs.call(this, function (s, m) {
507 this[l + s + i] = b + m;
508 }, ACCIDENTAL);
509 }, { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 });
510 }, 11);
511
512 yuu.registerInitHook(function () {
513 if (!window.AudioContext)
514 throw new Error("Web Audio isn't supported.");
515 yuu.audio = new yuu.Audio();
516 yuu.defaultCommands.volume = yuu.propcmd(
517 yuu.audio, "volume",
518 "get/set the current master audio volume", "0...1");
519 yuu.defaultCommands.musicVolume = yuu.propcmd(
520 yuu.audio, "musicVolume",
521 "get/set the current music volume", "0...1");
522 yuu.defaultCommands.mute = yuu.propcmd(
523 yuu.audio, "mute", "mute or unmute audio");
524 });
525
526 }).call(typeof exports === "undefined" ? this : exports,
527 typeof exports === "undefined"
528 ? this.yuu : (module.exports = require('./core')));