WebMIDIAPI.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /* Copyright 2013 Chris Wilson
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. // Initialize the MIDI library.
  13. (function (global) {
  14. 'use strict';
  15. var midiIO, _requestMIDIAccess, MIDIAccess, _onReady, MIDIPort, MIDIInput, MIDIOutput, _midiProc;
  16. function Promise() {
  17. }
  18. Promise.prototype.then = function(accept, reject) {
  19. this.accept = accept;
  20. this.reject = reject;
  21. }
  22. Promise.prototype.succeed = function(access) {
  23. if (this.accept)
  24. this.accept(access);
  25. }
  26. Promise.prototype.fail = function(error) {
  27. if (this.reject)
  28. this.reject(error);
  29. }
  30. function _JazzInstance() {
  31. this.inputInUse = false;
  32. this.outputInUse = false;
  33. // load the Jazz plugin
  34. var o1 = document.createElement("object");
  35. o1.id = "_Jazz" + Math.random() + "ie";
  36. o1.classid = "CLSID:1ACE1618-1C7D-4561-AEE1-34842AA85E90";
  37. this.activeX = o1;
  38. var o2 = document.createElement("object");
  39. o2.id = "_Jazz" + Math.random();
  40. o2.type="audio/x-jazz";
  41. o1.appendChild(o2);
  42. this.objRef = o2;
  43. var e = document.createElement("p");
  44. e.appendChild(document.createTextNode("This page requires the "));
  45. var a = document.createElement("a");
  46. a.appendChild(document.createTextNode("Jazz plugin"));
  47. a.href = "http://jazz-soft.net/";
  48. e.appendChild(a);
  49. e.appendChild(document.createTextNode("."));
  50. o2.appendChild(e);
  51. var insertionPoint = document.getElementById("MIDIPlugin");
  52. if (!insertionPoint) {
  53. // Create hidden element
  54. var insertionPoint = document.createElement("div");
  55. insertionPoint.id = "MIDIPlugin";
  56. insertionPoint.style.position = "absolute";
  57. insertionPoint.style.visibility = "hidden";
  58. insertionPoint.style.left = "-9999px";
  59. insertionPoint.style.top = "-9999px";
  60. document.body.appendChild(insertionPoint);
  61. }
  62. insertionPoint.appendChild(o1);
  63. if (this.objRef.isJazz)
  64. this._Jazz = this.objRef;
  65. else if (this.activeX.isJazz)
  66. this._Jazz = this.activeX;
  67. else
  68. this._Jazz = null;
  69. if (this._Jazz) {
  70. this._Jazz._jazzTimeZero = this._Jazz.Time();
  71. this._Jazz._perfTimeZero = window.performance.now();
  72. }
  73. }
  74. _requestMIDIAccess = function _requestMIDIAccess() {
  75. var access = new MIDIAccess();
  76. return access._promise;
  77. };
  78. // API Methods
  79. MIDIAccess = function() {
  80. this._jazzInstances = new Array();
  81. this._jazzInstances.push( new _JazzInstance() );
  82. this._promise = new Promise;
  83. if (this._jazzInstances[0]._Jazz) {
  84. this._Jazz = this._jazzInstances[0]._Jazz;
  85. window.setTimeout( _onReady.bind(this), 3 );
  86. } else {
  87. window.setTimeout( _onNotReady.bind(this), 3 );
  88. }
  89. };
  90. _onReady = function _onReady() {
  91. if (this._promise)
  92. this._promise.succeed(this);
  93. };
  94. function _onNotReady() {
  95. if (this._promise)
  96. this._promise.fail( { code: 1 } );
  97. };
  98. MIDIAccess.prototype.inputs = function( ) {
  99. if (!this._Jazz)
  100. return null;
  101. var list=this._Jazz.MidiInList();
  102. var inputs = new Array( list.length );
  103. for ( var i=0; i<list.length; i++ ) {
  104. inputs[i] = new MIDIInput( this, list[i], i );
  105. }
  106. return inputs;
  107. }
  108. MIDIAccess.prototype.outputs = function( ) {
  109. if (!this._Jazz)
  110. return null;
  111. var list=this._Jazz.MidiOutList();
  112. var outputs = new Array( list.length );
  113. for ( var i=0; i<list.length; i++ ) {
  114. outputs[i] = new MIDIOutput( this, list[i], i );
  115. }
  116. return outputs;
  117. };
  118. MIDIInput = function MIDIInput( midiAccess, name, index ) {
  119. this._listeners = [];
  120. this._midiAccess = midiAccess;
  121. this._index = index;
  122. this._inLongSysexMessage = false;
  123. this._sysexBuffer = new Uint8Array();
  124. this.id = "" + index + "." + name;
  125. this.manufacturer = "";
  126. this.name = name;
  127. this.type = "input";
  128. this.version = "";
  129. this.onmidimessage = null;
  130. var inputInstance = null;
  131. for (var i=0; (i<midiAccess._jazzInstances.length)&&(!inputInstance); i++) {
  132. if (!midiAccess._jazzInstances[i].inputInUse)
  133. inputInstance=midiAccess._jazzInstances[i];
  134. }
  135. if (!inputInstance) {
  136. inputInstance = new _JazzInstance();
  137. midiAccess._jazzInstances.push( inputInstance );
  138. }
  139. inputInstance.inputInUse = true;
  140. this._jazzInstance = inputInstance._Jazz;
  141. this._input = this._jazzInstance.MidiInOpen( this._index, _midiProc.bind(this) );
  142. };
  143. // Introduced in DOM Level 2:
  144. MIDIInput.prototype.addEventListener = function (type, listener, useCapture ) {
  145. if (type !== "midimessage")
  146. return;
  147. for (var i=0; i<this._listeners.length; i++)
  148. if (this._listeners[i] == listener)
  149. return;
  150. this._listeners.push( listener );
  151. };
  152. MIDIInput.prototype.removeEventListener = function (type, listener, useCapture ) {
  153. if (type !== "midimessage")
  154. return;
  155. for (var i=0; i<this._listeners.length; i++)
  156. if (this._listeners[i] == listener) {
  157. this._listeners.splice( i, 1 ); //remove it
  158. return;
  159. }
  160. };
  161. MIDIInput.prototype.preventDefault = function() {
  162. this._pvtDef = true;
  163. };
  164. MIDIInput.prototype.dispatchEvent = function (evt) {
  165. this._pvtDef = false;
  166. // dispatch to listeners
  167. for (var i=0; i<this._listeners.length; i++)
  168. if (this._listeners[i].handleEvent)
  169. this._listeners[i].handleEvent.bind(this)( evt );
  170. else
  171. this._listeners[i].bind(this)( evt );
  172. if (this.onmidimessage)
  173. this.onmidimessage( evt );
  174. return this._pvtDef;
  175. };
  176. MIDIInput.prototype.appendToSysexBuffer = function ( data ) {
  177. var oldLength = this._sysexBuffer.length;
  178. var tmpBuffer = new Uint8Array( oldLength + data.length );
  179. tmpBuffer.set( this._sysexBuffer );
  180. tmpBuffer.set( data, oldLength );
  181. this._sysexBuffer = tmpBuffer;
  182. };
  183. MIDIInput.prototype.bufferLongSysex = function ( data, initialOffset ) {
  184. var j = initialOffset;
  185. while (j<data.length) {
  186. if (data[j] == 0xF7) {
  187. // end of sysex!
  188. j++;
  189. this.appendToSysexBuffer( data.slice(initialOffset, j) );
  190. return j;
  191. }
  192. j++;
  193. }
  194. // didn't reach the end; just tack it on.
  195. this.appendToSysexBuffer( data.slice(initialOffset, j) );
  196. this._inLongSysexMessage = true;
  197. return j;
  198. };
  199. _midiProc = function _midiProc( timestamp, data ) {
  200. // Have to use createEvent/initEvent because IE10 fails on new CustomEvent. Thanks, IE!
  201. var length = 0;
  202. var i,j;
  203. var isSysexMessage = false;
  204. // Jazz sometimes passes us multiple messages at once, so we need to parse them out
  205. // and pass them one at a time.
  206. for (i=0; i<data.length; i+=length) {
  207. if (this._inLongSysexMessage) {
  208. i = this.bufferLongSysex(data,i);
  209. if ( data[i-1] != 0xf7 ) {
  210. // ran off the end without hitting the end of the sysex message
  211. return;
  212. }
  213. isSysexMessage = true;
  214. } else {
  215. isSysexMessage = false;
  216. switch (data[i] & 0xF0) {
  217. case 0x80: // note off
  218. case 0x90: // note on
  219. case 0xA0: // polyphonic aftertouch
  220. case 0xB0: // control change
  221. case 0xE0: // channel mode
  222. length = 3;
  223. break;
  224. case 0xC0: // program change
  225. case 0xD0: // channel aftertouch
  226. length = 2;
  227. break;
  228. case 0xF0:
  229. switch (data[i]) {
  230. case 0xf0: // variable-length sysex.
  231. i = this.bufferLongSysex(data,i);
  232. if ( data[i-1] != 0xf7 ) {
  233. // ran off the end without hitting the end of the sysex message
  234. return;
  235. }
  236. isSysexMessage = true;
  237. break;
  238. case 0xF1: // MTC quarter frame
  239. case 0xF3: // song select
  240. length = 2;
  241. break;
  242. case 0xF2: // song position pointer
  243. length = 3;
  244. break;
  245. default:
  246. length = 1;
  247. break;
  248. }
  249. break;
  250. }
  251. }
  252. var evt = document.createEvent( "Event" );
  253. evt.initEvent( "midimessage", false, false );
  254. evt.receivedTime = parseFloat( timestamp.toString()) + this._jazzInstance._perfTimeZero;
  255. if (isSysexMessage || this._inLongSysexMessage) {
  256. evt.data = new Uint8Array( this._sysexBuffer );
  257. this._sysexBuffer = new Uint8Array(0);
  258. this._inLongSysexMessage = false;
  259. } else
  260. evt.data = new Uint8Array(data.slice(i, length+i));
  261. this.dispatchEvent( evt );
  262. }
  263. };
  264. MIDIOutput = function MIDIOutput( midiAccess, name, index ) {
  265. this._listeners = [];
  266. this._midiAccess = midiAccess;
  267. this._index = index;
  268. this.id = "" + index + "." + name;
  269. this.manufacturer = "";
  270. this.name = name;
  271. this.type = "output";
  272. this.version = "";
  273. var outputInstance = null;
  274. for (var i=0; (i<midiAccess._jazzInstances.length)&&(!outputInstance); i++) {
  275. if (!midiAccess._jazzInstances[i].outputInUse)
  276. outputInstance=midiAccess._jazzInstances[i];
  277. }
  278. if (!outputInstance) {
  279. outputInstance = new _JazzInstance();
  280. midiAccess._jazzInstances.push( outputInstance );
  281. }
  282. outputInstance.outputInUse = true;
  283. this._jazzInstance = outputInstance._Jazz;
  284. this._jazzInstance.MidiOutOpen(this.name);
  285. };
  286. function _sendLater() {
  287. this.jazz.MidiOutLong( this.data ); // handle send as sysex
  288. }
  289. MIDIOutput.prototype.send = function( data, timestamp ) {
  290. var delayBeforeSend = 0;
  291. if (data.length === 0)
  292. return false;
  293. if (timestamp)
  294. delayBeforeSend = Math.floor( timestamp - window.performance.now() );
  295. if (timestamp && (delayBeforeSend>1)) {
  296. var sendObj = new Object();
  297. sendObj.jazz = this._jazzInstance;
  298. sendObj.data = data;
  299. window.setTimeout( _sendLater.bind(sendObj), delayBeforeSend );
  300. } else {
  301. this._jazzInstance.MidiOutLong( data );
  302. }
  303. return true;
  304. };
  305. //init: create plugin
  306. if (!window.navigator.requestMIDIAccess)
  307. window.navigator.requestMIDIAccess = _requestMIDIAccess;
  308. }(window));
  309. // Polyfill window.performance.now() if necessary.
  310. (function (exports) {
  311. var perf = {}, props;
  312. function findAlt() {
  313. var prefix = ['moz', 'webkit', 'o', 'ms'],
  314. i = prefix.length,
  315. //worst case, we use Date.now()
  316. props = {
  317. value: (function (start) {
  318. return function () {
  319. return Date.now() - start;
  320. };
  321. }(Date.now()))
  322. };
  323. //seach for vendor prefixed version
  324. for (; i >= 0; i--) {
  325. if ((prefix[i] + "Now") in exports.performance) {
  326. props.value = function (method) {
  327. return function () {
  328. exports.performance[method]();
  329. }
  330. }(prefix[i] + "Now");
  331. return props;
  332. }
  333. }
  334. //otherwise, try to use connectionStart
  335. if ("timing" in exports.performance && "connectStart" in exports.performance.timing) {
  336. //this pretty much approximates performance.now() to the millisecond
  337. props.value = (function (start) {
  338. return function() {
  339. Date.now() - start;
  340. };
  341. }(exports.performance.timing.connectStart));
  342. }
  343. return props;
  344. }
  345. //if already defined, bail
  346. if (("performance" in exports) && ("now" in exports.performance))
  347. return;
  348. if (!("performance" in exports))
  349. Object.defineProperty(exports, "performance", {
  350. get: function () {
  351. return perf;
  352. }});
  353. //otherwise, performance is there, but not "now()"
  354. props = findAlt();
  355. Object.defineProperty(exports.performance, "now", props);
  356. }(window));