-
-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathInput.js
1163 lines (1052 loc) · 41.4 KB
/
Input.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {Enumerations} from "./Enumerations.js";
import {EventEmitter} from "../node_modules/djipevents/src/djipevents.js";
import {Forwarder} from "./Forwarder.js";
import {InputChannel} from "./InputChannel.js";
import {Message} from "./Message.js";
import {Utilities} from "./Utilities.js";
import {WebMidi} from "./WebMidi.js";
/**
* The `Input` class represents a single MIDI input port. This object is automatically instantiated
* by the library according to the host's MIDI subsystem and does not need to be directly
* instantiated. Instead, you can access all `Input` objects by referring to the
* [`WebMidi.inputs`](WebMidi#inputs) array. You can also retrieve inputs by using methods such as
* [`WebMidi.getInputByName()`](WebMidi#getInputByName) and
* [`WebMidi.getInputById()`](WebMidi#getInputById).
*
* Note that a single MIDI device may expose several inputs and/or outputs.
*
* **Important**: the `Input` class does not directly fire channel-specific MIDI messages
* (such as [`noteon`](InputChannel#event:noteon) or
* [`controlchange`](InputChannel#event:controlchange), etc.). The [`InputChannel`](InputChannel)
* object does that. However, you can still use the
* [`Input.addListener()`](#addListener) method to listen to channel-specific events on multiple
* [`InputChannel`](InputChannel) objects at once.
*
* @fires Input#opened
* @fires Input#disconnected
* @fires Input#closed
* @fires Input#midimessage
*
* @fires Input#sysex
* @fires Input#timecode
* @fires Input#songposition
* @fires Input#songselect
* @fires Input#tunerequest
* @fires Input#clock
* @fires Input#start
* @fires Input#continue
* @fires Input#stop
* @fires Input#activesensing
* @fires Input#reset
*
* @fires Input#unknownmidimessage
*
* @extends EventEmitter
* @license Apache-2.0
*/
export class Input extends EventEmitter {
/**
* Creates an `Input` object.
*
* @param {MIDIInput} midiInput [`MIDIInput`](https://developer.mozilla.org/en-US/docs/Web/API/MIDIInput)
* object as provided by the MIDI subsystem (Web MIDI API).
*/
constructor(midiInput) {
super();
/**
* Reference to the actual MIDIInput object
* @private
*/
this._midiInput = midiInput;
/**
* @type {number}
* @private
*/
this._octaveOffset = 0;
/**
* Array containing the 16 [`InputChannel`](InputChannel) objects available for this `Input`. The
* channels are numbered 1 through 16.
*
* @type {InputChannel[]}
*/
this.channels = [];
for (let i = 1; i <= 16; i++) this.channels[i] = new InputChannel(this, i);
/**
* @type {Forwarder[]}
* @private
*/
this._forwarders = [];
// Setup listeners
this._midiInput.onstatechange = this._onStateChange.bind(this);
this._midiInput.onmidimessage = this._onMidiMessage.bind(this);
}
/**
* Destroys the `Input` by removing all listeners, emptying the [`channels`](#channels) array and
* unlinking the MIDI subsystem. This is mostly for internal use.
*
* @returns {Promise<void>}
*/
async destroy() {
this.removeListener();
this.channels.forEach(ch => ch.destroy());
this.channels = [];
this._forwarders = [];
if (this._midiInput) {
this._midiInput.onstatechange = null;
this._midiInput.onmidimessage = null;
}
await this.close();
this._midiInput = null;
}
/**
* Executed when a `"statechange"` event occurs.
*
* @param e
* @private
*/
_onStateChange(e) {
let event = {
timestamp: WebMidi.time,
target: this,
port: this // for consistency
};
if (e.port.connection === "open") {
/**
* Event emitted when the `Input` has been opened by calling the [`open()`]{@link #open}
* method.
*
* @event Input#opened
* @type {object}
* @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in
* milliseconds since the navigation start of the document).
* @property {string} type `opened`
* @property {Input} target The object that dispatched the event.
* @property {Input} port The `Input` that triggered the event.
*/
event.type = "opened";
this.emit("opened", event);
} else if (e.port.connection === "closed" && e.port.state === "connected") {
/**
* Event emitted when the `Input` has been closed by calling the
* [`close()`]{@link #close} method.
*
* @event Input#closed
* @type {object}
* @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in
* milliseconds since the navigation start of the document).
* @property {string} type `closed`
* @property {Input} target The object that dispatched the event.
* @property {Input} port The `Input` that triggered the event.
*/
event.type = "closed";
this.emit("closed", event);
} else if (e.port.connection === "closed" && e.port.state === "disconnected") {
/**
* Event emitted when the `Input` becomes unavailable. This event is typically fired
* when the MIDI device is unplugged.
*
* @event Input#disconnected
* @type {object}
* @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in
* milliseconds since the navigation start of the document).
* @property {string} type `disconnected`
* @property {Input} port Object with properties describing the {@link Input} that was
* disconnected. This is not the actual `Input` as it is no longer available.
* @property {Input} target The object that dispatched the event.
*/
event.type = "disconnected";
event.port = {
connection: e.port.connection,
id: e.port.id,
manufacturer: e.port.manufacturer,
name: e.port.name,
state: e.port.state,
type: e.port.type
};
this.emit("disconnected", event);
} else if (e.port.connection === "pending" && e.port.state === "disconnected") {
// I don't see the need to forward that...
} else {
console.warn("This statechange event was not caught: ", e.port.connection, e.port.state);
}
}
/**
* Executed when a `"midimessage"` event is received
* @param e
* @private
*/
_onMidiMessage(e) {
// Create Message object from MIDI data
const message = new Message(e.data);
/**
* Event emitted when any MIDI message is received on an `Input`.
*
* @event Input#midimessage
*
* @type {object}
*
* @property {Input} port The `Input` that triggered the event.
* @property {Input} target The object that dispatched the event.
* @property {Message} message A [`Message`](Message) object containing information about the
* incoming MIDI message.
* @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in
* milliseconds since the navigation start of the document).
* @property {string} type `midimessage`
*
* @since 2.1
*/
const event = {
port: this,
target: this,
message: message,
timestamp: e.timeStamp,
type: "midimessage",
data: message.data, // @deprecated (will be removed in v4)
rawData: message.data, // @deprecated (will be removed in v4)
statusByte: message.data[0], // @deprecated (will be removed in v4)
dataBytes: message.dataBytes // @deprecated (will be removed in v4)
};
this.emit("midimessage", event);
// Messages are forwarded to InputChannel if they are channel messages or parsed locally for
// system messages.
if (message.isSystemMessage) { // system messages
this._parseEvent(event);
} else if (message.isChannelMessage) { // channel messages
this.channels[message.channel]._processMidiMessageEvent(event);
}
// Forward message if forwarders have been defined
this._forwarders.forEach(forwarder => forwarder.forward(message));
}
/**
* @private
*/
_parseEvent(e) {
// Make a shallow copy of the incoming event so we can use it as the new event.
const event = Object.assign({}, e);
event.type = event.message.type || "unknownmidimessage";
// Add custom property for 'songselect'
if (event.type === "songselect") {
event.song = e.data[1] + 1; // deprecated
event.value = e.data[1];
event.rawValue = event.value;
}
// Emit event
this.emit(event.type, event);
}
/**
* Opens the input for usage. This is usually unnecessary as the port is opened automatically when
* WebMidi is enabled.
*
* @returns {Promise<Input>} The promise is fulfilled with the `Input` object.
*/
async open() {
// Explicitly opens the port for usage. This is not mandatory. When the port is not explicitly
// opened, it is implicitly opened (asynchronously) when assigning a listener to the
// `onmidimessage` property of the `MIDIInput`. We do it explicitly so that 'connected' events
// are dispatched immediately and that we are ready to listen.
try {
await this._midiInput.open();
} catch (err) {
return Promise.reject(err);
}
return Promise.resolve(this);
}
/**
* Closes the input. When an input is closed, it cannot be used to listen to MIDI messages until
* the input is opened again by calling [`Input.open()`](Input#open).
*
* **Note**: if what you want to do is stop events from being dispatched, you should use
* [`eventsSuspended`](#eventsSuspended) instead.
*
* @returns {Promise<Input>} The promise is fulfilled with the `Input` object
*/
async close() {
// We close the port. This triggers a statechange event which, in turn, will emit the 'closed'
// event.
if (!this._midiInput) return Promise.resolve(this);
try {
await this._midiInput.close();
} catch (err) {
return Promise.reject(err);
}
return Promise.resolve(this);
}
/**
* @private
* @deprecated since v3.0.0 (moved to 'Utilities' class)
*/
getChannelModeByNumber() {
if (WebMidi.validation) {
console.warn(
"The 'getChannelModeByNumber()' method has been moved to the 'Utilities' class."
);
}
}
/**
* Adds an event listener that will trigger a function callback when the specified event is
* dispatched. The event usually is **input-wide** but can also be **channel-specific**.
*
* Input-wide events do not target a specific MIDI channel so it makes sense to listen for them
* at the `Input` level and not at the [`InputChannel`](InputChannel) level. Channel-specific
* events target a specific channel. Usually, in this case, you would add the listener to the
* [`InputChannel`](InputChannel) object. However, as a convenience, you can also listen to
* channel-specific events directly on an `Input`. This allows you to react to a channel-specific
* event no matter which channel it actually came through.
*
* When listening for an event, you simply need to specify the event name and the function to
* execute:
*
* ```javascript
* const listener = WebMidi.inputs[0].addListener("midimessage", e => {
* console.log(e);
* });
* ```
*
* Calling the function with an input-wide event (such as
* [`"midimessage"`]{@link #event:midimessage}), will return the [`Listener`](Listener) object
* that was created.
*
* If you call the function with a channel-specific event (such as
* [`"noteon"`]{@link InputChannel#event:noteon}), it will return an array of all
* [`Listener`](Listener) objects that were created (one for each channel):
*
* ```javascript
* const listeners = WebMidi.inputs[0].addListener("noteon", someFunction);
* ```
*
* You can also specify which channels you want to add the listener to:
*
* ```javascript
* const listeners = WebMidi.inputs[0].addListener("noteon", someFunction, {channels: [1, 2, 3]});
* ```
*
* In this case, `listeners` is an array containing 3 [`Listener`](Listener) objects. The order of
* the listeners in the array follows the order the channels were specified in.
*
* Note that, when adding channel-specific listeners, it is the [`InputChannel`](InputChannel)
* instance that actually gets a listener added and not the `Input` instance. You can check that
* by calling [`InputChannel.hasListener()`](InputChannel#hasListener()).
*
* There are 8 families of events you can listen to:
*
* 1. **MIDI System Common** Events (input-wide)
*
* * [`songposition`]{@link Input#event:songposition}
* * [`songselect`]{@link Input#event:songselect}
* * [`sysex`]{@link Input#event:sysex}
* * [`timecode`]{@link Input#event:timecode}
* * [`tunerequest`]{@link Input#event:tunerequest}
*
* 2. **MIDI System Real-Time** Events (input-wide)
*
* * [`clock`]{@link Input#event:clock}
* * [`start`]{@link Input#event:start}
* * [`continue`]{@link Input#event:continue}
* * [`stop`]{@link Input#event:stop}
* * [`activesensing`]{@link Input#event:activesensing}
* * [`reset`]{@link Input#event:reset}
*
* 3. **State Change** Events (input-wide)
*
* * [`opened`]{@link Input#event:opened}
* * [`closed`]{@link Input#event:closed}
* * [`disconnected`]{@link Input#event:disconnected}
*
* 4. **Catch-All** Events (input-wide)
*
* * [`midimessage`]{@link Input#event:midimessage}
* * [`unknownmidimessage`]{@link Input#event:unknownmidimessage}
*
* 5. **Channel Voice** Events (channel-specific)
*
* * [`channelaftertouch`]{@link InputChannel#event:channelaftertouch}
* * [`controlchange`]{@link InputChannel#event:controlchange}
* * [`controlchange-controller0`]{@link InputChannel#event:controlchange-controller0}
* * [`controlchange-controller1`]{@link InputChannel#event:controlchange-controller1}
* * [`controlchange-controller2`]{@link InputChannel#event:controlchange-controller2}
* * (...)
* * [`controlchange-controller127`]{@link InputChannel#event:controlchange-controller127}
* * [`keyaftertouch`]{@link InputChannel#event:keyaftertouch}
* * [`noteoff`]{@link InputChannel#event:noteoff}
* * [`noteon`]{@link InputChannel#event:noteon}
* * [`pitchbend`]{@link InputChannel#event:pitchbend}
* * [`programchange`]{@link InputChannel#event:programchange}
*
* Note: you can listen for a specific control change message by using an event name like this:
* `controlchange-controller23`, `controlchange-controller99`, `controlchange-controller122`,
* etc.
*
* 6. **Channel Mode** Events (channel-specific)
*
* * [`allnotesoff`]{@link InputChannel#event:allnotesoff}
* * [`allsoundoff`]{@link InputChannel#event:allsoundoff}
* * [`localcontrol`]{@link InputChannel#event:localcontrol}
* * [`monomode`]{@link InputChannel#event:monomode}
* * [`omnimode`]{@link InputChannel#event:omnimode}
* * [`resetallcontrollers`]{@link InputChannel#event:resetallcontrollers}
*
* 7. **NRPN** Events (channel-specific)
*
* * [`nrpn`]{@link InputChannel#event:nrpn}
* * [`nrpn-dataentrycoarse`]{@link InputChannel#event:nrpn-dataentrycoarse}
* * [`nrpn-dataentryfine`]{@link InputChannel#event:nrpn-dataentryfine}
* * [`nrpn-dataincrement`]{@link InputChannel#event:nrpn-dataincrement}
* * [`nrpn-datadecrement`]{@link InputChannel#event:nrpn-datadecrement}
*
* 8. **RPN** Events (channel-specific)
*
* * [`rpn`]{@link InputChannel#event:rpn}
* * [`rpn-dataentrycoarse`]{@link InputChannel#event:rpn-dataentrycoarse}
* * [`rpn-dataentryfine`]{@link InputChannel#event:rpn-dataentryfine}
* * [`rpn-dataincrement`]{@link InputChannel#event:rpn-dataincrement}
* * [`rpn-datadecrement`]{@link InputChannel#event:rpn-datadecrement}
*
* @param event {string | EventEmitter.ANY_EVENT} The type of the event.
*
* @param listener {function} A callback function to execute when the specified event is detected.
* This function will receive an event parameter object. For details on this object's properties,
* check out the documentation for the various events (links above).
*
* @param {object} [options={}]
*
* @param {array} [options.arguments] An array of arguments which will be passed separately to the
* callback function. This array is stored in the [`arguments`](Listener#arguments) property of
* the [`Listener`](Listener) object and can be retrieved or modified as desired.
*
* @param {number|number[]} [options.channels=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]]
* An integer between 1 and 16 or an array of such integers representing the MIDI channel(s) to
* listen on. If no channel is specified, all channels will be used. This parameter is ignored for
* input-wide events.
*
* @param {object} [options.context=this] The value of `this` in the callback function.
*
* @param {number} [options.duration=Infinity] The number of milliseconds before the listener
* automatically expires.
*
* @param {boolean} [options.prepend=false] Whether the listener should be added at the beginning
* of the listeners array and thus be triggered before others.
*
* @param {number} [options.remaining=Infinity] The number of times after which the callback
* should automatically be removed.
*
* @returns {Listener|Listener[]} If the event is input-wide, a single [`Listener`](Listener)
* object is returned. If the event is channel-specific, an array of all the
* [`Listener`](Listener) objects is returned (one for each channel).
*/
addListener(event, listener, options = {}) {
if (WebMidi.validation) {
// Legacy compatibility
if (typeof options === "function") {
let channels = (listener != undefined) ? [].concat(listener) : undefined; // clone
listener = options;
options = {channels: channels};
}
}
// Check if the event is channel-specific or input-wide
if (Enumerations.CHANNEL_EVENTS.includes(event)) {
// If no channel defined, use all.
if (options.channels === undefined) options.channels = Enumerations.MIDI_CHANNEL_NUMBERS;
let listeners = [];
Utilities.sanitizeChannels(options.channels).forEach(ch => {
listeners.push(this.channels[ch].addListener(event, listener, options));
});
return listeners;
} else {
return super.addListener(event, listener, options);
}
}
/**
* Adds a one-time event listener that will trigger a function callback when the specified event
* happens. The event can be **channel-bound** or **input-wide**. Channel-bound events are
* dispatched by [`InputChannel`]{@link InputChannel} objects and are tied to a specific MIDI
* channel while input-wide events are dispatched by the `Input` object itself and are not tied
* to a specific channel.
*
* Calling the function with an input-wide event (such as
* [`"midimessage"`]{@link #event:midimessage}), will return the [`Listener`](Listener) object
* that was created.
*
* If you call the function with a channel-specific event (such as
* [`"noteon"`]{@link InputChannel#event:noteon}), it will return an array of all
* [`Listener`](Listener) objects that were created (one for each channel):
*
* ```javascript
* const listeners = WebMidi.inputs[0].addOneTimeListener("noteon", someFunction);
* ```
*
* You can also specify which channels you want to add the listener to:
*
* ```javascript
* const listeners = WebMidi.inputs[0].addOneTimeListener("noteon", someFunction, {channels: [1, 2, 3]});
* ```
*
* In this case, the `listeners` variable contains an array of 3 [`Listener`](Listener) objects.
*
* The code above will add a listener for the `"noteon"` event and call `someFunction` when the
* event is triggered on MIDI channels `1`, `2` or `3`.
*
* Note that, when adding events to channels, it is the [`InputChannel`](InputChannel) instance
* that actually gets a listener added and not the `Input` instance.
*
* Note: if you want to add a listener to a single MIDI channel you should probably do so directly
* on the [`InputChannel`](InputChannel) object itself.
*
* There are 8 families of events you can listen to:
*
* 1. **MIDI System Common** Events (input-wide)
*
* * [`songposition`]{@link Input#event:songposition}
* * [`songselect`]{@link Input#event:songselect}
* * [`sysex`]{@link Input#event:sysex}
* * [`timecode`]{@link Input#event:timecode}
* * [`tunerequest`]{@link Input#event:tunerequest}
*
* 2. **MIDI System Real-Time** Events (input-wide)
*
* * [`clock`]{@link Input#event:clock}
* * [`start`]{@link Input#event:start}
* * [`continue`]{@link Input#event:continue}
* * [`stop`]{@link Input#event:stop}
* * [`activesensing`]{@link Input#event:activesensing}
* * [`reset`]{@link Input#event:reset}
*
* 3. **State Change** Events (input-wide)
*
* * [`opened`]{@link Input#event:opened}
* * [`closed`]{@link Input#event:closed}
* * [`disconnected`]{@link Input#event:disconnected}
*
* 4. **Catch-All** Events (input-wide)
*
* * [`midimessage`]{@link Input#event:midimessage}
* * [`unknownmidimessage`]{@link Input#event:unknownmidimessage}
*
* 5. **Channel Voice** Events (channel-specific)
*
* * [`channelaftertouch`]{@link InputChannel#event:channelaftertouch}
* * [`controlchange`]{@link InputChannel#event:controlchange}
* * [`controlchange-controller0`]{@link InputChannel#event:controlchange-controller0}
* * [`controlchange-controller1`]{@link InputChannel#event:controlchange-controller1}
* * [`controlchange-controller2`]{@link InputChannel#event:controlchange-controller2}
* * (...)
* * [`controlchange-controller127`]{@link InputChannel#event:controlchange-controller127}
* * [`keyaftertouch`]{@link InputChannel#event:keyaftertouch}
* * [`noteoff`]{@link InputChannel#event:noteoff}
* * [`noteon`]{@link InputChannel#event:noteon}
* * [`pitchbend`]{@link InputChannel#event:pitchbend}
* * [`programchange`]{@link InputChannel#event:programchange}
*
* Note: you can listen for a specific control change message by using an event name like this:
* `controlchange-controller23`, `controlchange-controller99`, `controlchange-controller122`,
* etc.
*
* 6. **Channel Mode** Events (channel-specific)
*
* * [`allnotesoff`]{@link InputChannel#event:allnotesoff}
* * [`allsoundoff`]{@link InputChannel#event:allsoundoff}
* * [`localcontrol`]{@link InputChannel#event:localcontrol}
* * [`monomode`]{@link InputChannel#event:monomode}
* * [`omnimode`]{@link InputChannel#event:omnimode}
* * [`resetallcontrollers`]{@link InputChannel#event:resetallcontrollers}
*
* 7. **NRPN** Events (channel-specific)
*
* * [`nrpn`]{@link InputChannel#event:nrpn}
* * [`nrpn-dataentrycoarse`]{@link InputChannel#event:nrpn-dataentrycoarse}
* * [`nrpn-dataentryfine`]{@link InputChannel#event:nrpn-dataentryfine}
* * [`nrpn-dataincrement`]{@link InputChannel#event:nrpn-dataincrement}
* * [`nrpn-datadecrement`]{@link InputChannel#event:nrpn-datadecrement}
*
* 8. **RPN** Events (channel-specific)
*
* * [`rpn`]{@link InputChannel#event:rpn}
* * [`rpn-dataentrycoarse`]{@link InputChannel#event:rpn-dataentrycoarse}
* * [`rpn-dataentryfine`]{@link InputChannel#event:rpn-dataentryfine}
* * [`rpn-dataincrement`]{@link InputChannel#event:rpn-dataincrement}
* * [`rpn-datadecrement`]{@link InputChannel#event:rpn-datadecrement}
*
* @param event {string} The type of the event.
*
* @param listener {function} A callback function to execute when the specified event is detected.
* This function will receive an event parameter object. For details on this object's properties,
* check out the documentation for the various events (links above).
*
* @param {object} [options={}]
*
* @param {array} [options.arguments] An array of arguments which will be passed separately to the
* callback function. This array is stored in the [`arguments`](Listener#arguments) property of
* the [`Listener`](Listener) object and can be retrieved or modified as desired.
*
* @param {number|number[]} [options.channels] An integer between 1 and 16 or an array of
* such integers representing the MIDI channel(s) to listen on. This parameter is ignored for
* input-wide events.
*
* @param {object} [options.context=this] The value of `this` in the callback function.
*
* @param {number} [options.duration=Infinity] The number of milliseconds before the listener
* automatically expires.
*
* @param {boolean} [options.prepend=false] Whether the listener should be added at the beginning
* of the listeners array and thus be triggered before others.
*
* @returns {Listener[]} An array of all [`Listener`](Listener) objects that were created.
*/
addOneTimeListener(event, listener, options = {}) {
options.remaining = 1;
return this.addListener(event, listener, options);
}
/**
* This is an alias to the [Input.addListener()]{@link Input#addListener} method.
* @since 2.0.0
* @deprecated since v3.0
* @private
*/
on(event, channel, listener, options) {
return this.addListener(event, channel, listener, options);
}
/**
* Checks if the specified event type is already defined to trigger the specified callback
* function. For channel-specific events, the function will return `true` only if all channels
* have the listener defined.
*
* @param event {string|Symbol} The type of the event.
*
* @param listener {function} The callback function to check for.
*
* @param {object} [options={}]
*
* @param {number|number[]} [options.channels] An integer between 1 and 16 or an array of such
* integers representing the MIDI channel(s) to check. This parameter is ignored for input-wide
* events.
*
* @returns {boolean} Boolean value indicating whether or not the `Input` or
* [`InputChannel`](InputChannel) already has this listener defined.
*/
hasListener(event, listener, options = {}) {
if (WebMidi.validation) {
// Legacy compatibility
if (typeof options === "function") {
let channels = [].concat(listener); // clone
listener = options;
options = {channels: channels};
}
}
if (Enumerations.CHANNEL_EVENTS.includes(event)) {
// If no channel defined, use all.
if (options.channels === undefined) options.channels = Enumerations.MIDI_CHANNEL_NUMBERS;
return Utilities.sanitizeChannels(options.channels).every(ch => {
return this.channels[ch].hasListener(event, listener);
});
} else {
return super.hasListener(event, listener);
}
}
/**
* Removes the specified event listener. If no listener is specified, all listeners matching the
* specified event will be removed. If the event is channel-specific, the listener will be removed
* from all [`InputChannel`]{@link InputChannel} objects belonging to that channel. If no event is
* specified, all listeners for the `Input` as well as all listeners for all
* [`InputChannel`]{@link InputChannel} objects belonging to the `Input` will be removed.
*
* By default, channel-specific listeners will be removed from all
* [`InputChannel`]{@link InputChannel} objects unless the `options.channel` narrows it down.
*
* @param [type] {string} The type of the event.
*
* @param [listener] {function} The callback function to check for.
*
* @param {object} [options={}]
*
* @param {number|number[]} [options.channels] An integer between 1 and 16 or an array of
* such integers representing the MIDI channel(s) to match. This parameter is ignored for
* input-wide events.
*
* @param {*} [options.context] Only remove the listeners that have this exact context.
*
* @param {number} [options.remaining] Only remove the listener if it has exactly that many
* remaining times to be executed.
*/
removeListener(event, listener, options = {}) {
if (WebMidi.validation) {
// Legacy compatibility
if (typeof options === "function") {
let channels = [].concat(listener); // clone
listener = options;
options = {channels: channels};
}
}
if (options.channels === undefined) options.channels = Enumerations.MIDI_CHANNEL_NUMBERS;
// If the event is not specified, remove everything (channel-specific and input-wide)!
if (event == undefined) {
Utilities.sanitizeChannels(options.channels).forEach(ch => {
if (this.channels[ch]) this.channels[ch].removeListener();
});
return super.removeListener();
}
// If the event is specified, check if it's channel-specific or input-wide.
if (Enumerations.CHANNEL_EVENTS.includes(event)) {
Utilities.sanitizeChannels(options.channels).forEach(ch => {
this.channels[ch].removeListener(event, listener, options);
});
} else {
super.removeListener(event, listener, options);
}
}
/**
* Adds a forwarder that will forward all incoming MIDI messages matching the criteria to the
* specified [`Output`](Output) destination(s). This is akin to the hardware MIDI THRU port, with
* the added benefit of being able to filter which data is forwarded.
*
* @param {Output|Output[]} output An [`Output`](Output) object, or an array of such
* objects, to forward messages to.
* @param {object} [options={}]
* @param {string|string[]} [options.types=(all messages)] A message type, or an array of such
* types (`noteon`, `controlchange`, etc.), that the message type must match in order to be
* forwarded. If this option is not specified, all types of messages will be forwarded. Valid
* messages are the ones found in either
* [`SYSTEM_MESSAGES`](Enumerations#SYSTEM_MESSAGES) or
* [`CHANNEL_MESSAGES`](Enumerations#CHANNEL_MESSAGES).
* @param {number|number[]} [options.channels=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]]
* A MIDI channel number or an array of channel numbers that the message must match in order to be
* forwarded. By default all MIDI channels are included (`1` to `16`).
*
* @returns {Forwarder} The [`Forwarder`](Forwarder) object created to handle the forwarding. This
* is useful if you wish to manipulate or remove the [`Forwarder`](Forwarder) later on.
*/
addForwarder(output, options = {}) {
let forwarder;
// Unless 'output' is a forwarder, create a new forwarder
if (output instanceof Forwarder) {
forwarder = output;
} else {
forwarder = new Forwarder(output, options);
}
this._forwarders.push(forwarder);
return forwarder;
}
/**
* Removes the specified [`Forwarder`](Forwarder) object from the input.
*
* @param {Forwarder} forwarder The [`Forwarder`](Forwarder) to remove (the
* [`Forwarder`](Forwarder) object is returned when calling `addForwarder()`.
*/
removeForwarder(forwarder) {
this._forwarders = this._forwarders.filter(item => item !== forwarder);
}
/**
* Checks whether the specified [`Forwarder`](Forwarder) object has already been attached to this
* input.
*
* @param {Forwarder} forwarder The [`Forwarder`](Forwarder) to check for (the
* [`Forwarder`](Forwarder) object is returned when calling [`addForwarder()`](#addForwarder).
* @returns {boolean}
*/
hasForwarder(forwarder) {
return this._forwarders.includes(forwarder);
}
/**
* Name of the MIDI input.
*
* @type {string}
* @readonly
*/
get name() {
return this._midiInput.name;
}
/**
* ID string of the MIDI port. The ID is host-specific. Do not expect the same ID on different
* platforms. For example, Google Chrome and the Jazz-Plugin report completely different IDs for
* the same port.
*
* @type {string}
* @readonly
*/
get id() {
return this._midiInput.id;
}
/**
* Input port's connection state: `pending`, `open` or `closed`.
*
* @type {string}
* @readonly
*/
get connection() {
return this._midiInput.connection;
}
/**
* Name of the manufacturer of the device that makes this input port available.
*
* @type {string}
* @readonly
*/
get manufacturer() {
return this._midiInput.manufacturer;
}
/**
* An integer to offset the reported octave of incoming notes. By default, middle C (MIDI note
* number 60) is placed on the 4th octave (C4).
*
* If, for example, `octaveOffset` is set to 2, MIDI note number 60 will be reported as C6. If
* `octaveOffset` is set to -1, MIDI note number 60 will be reported as C3.
*
* Note that this value is combined with the global offset value defined in the
* [`WebMidi.octaveOffset`](WebMidi#octaveOffset) property (if any).
*
* @type {number}
*
* @since 3.0
*/
get octaveOffset() {
return this._octaveOffset;
}
set octaveOffset(value) {
if (this.validation) {
value = parseInt(value);
if (isNaN(value)) throw new TypeError("The 'octaveOffset' property must be an integer.");
}
this._octaveOffset = value;
}
/**
* State of the input port: `connected` or `disconnected`.
*
* @type {string}
* @readonly
*/
get state() {
return this._midiInput.state;
}
/**
* The port type. In the case of the `Input` object, this is always: `input`.
*
* @type {string}
* @readonly
*/
get type() {
return this._midiInput.type;
}
/**
* @type {boolean}
* @private
* @deprecated since v3.0.0 (moved to 'InputChannel' class)
*/
get nrpnEventsEnabled() {
if (WebMidi.validation) {
console.warn("The 'nrpnEventsEnabled' property has been moved to the 'InputChannel' class.");
}
return false;
}
}
// Events that do not have code below them must be placed outside the class definition (?!)
/**
* Input-wide (system) event emitted when a **system exclusive** message has been received.
* You should note that, to receive `sysex` events, you must call the
* [`WebMidi.enable()`](WebMidi#enable()) method with the `sysex` option set to `true`:
*
* ```js
* WebMidi.enable({sysex: true})
* .then(() => console.log("WebMidi has been enabled with sysex support."))
* ```
*
* @event Input#sysex
*
* @type {object}
*
* @property {Input} port The `Input` that triggered the event.
* @property {Input} target The object that dispatched the event.
* @property {Message} message A [`Message`](Message) object containing information about the
* incoming MIDI message.
* @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in
* milliseconds since the navigation start of the document).
* @property {string} type `sysex`
*
*/
/**
* Input-wide (system) event emitted when a **time code quarter frame** message has been
* received.
*
* @event Input#timecode
*
* @type {object}
*
* @property {Input} port The `Input` that triggered the event.
* @property {Input} target The object that dispatched the event.
* @property {Message} message A [`Message`](Message) object containing information about the
* incoming MIDI message.
* @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in
* milliseconds since the navigation start of the document).
* @property {string} type `timecode`
*
* @since 2.1
*/
/**
* Input-wide (system) event emitted when a **song position** message has been received.
*
* @event Input#songposition
*
* @type {object}
*
* @property {Input} port The `Input` that triggered the event.
* @property {Input} target The object that dispatched the event.
* @property {Message} message A [`Message`](Message) object containing information about the
* incoming MIDI message.
* @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in
* milliseconds since the navigation start of the document).
* @property {string} type `songposition`
*
* @since 2.1
*/