forked from ExoticMatter/ImoSPC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimospc.js
2187 lines (1906 loc) · 67.6 KB
/
imospc.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
/******************************************************************************
* Copyright (C) 2017 ExoticMatter
*
* This file is part of ImoSPC.
*
* ImoSPC is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* ImoSPC is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* ImoSPC. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
;;(function(global, document){
"use strict";
/** @const */ var IMO_VERSION_MAJOR = 1;
/** @const */ var IMO_VERSION_MINOR = 10;
/** @const */ var IMO_VERSION_BUILD = 1;
var undefined_;
var null_ = null;
/** @const */ var DEBUG = false;
/** @const */ var IMO_UNZIP_WORKER = 'bin/imo-w-unzip.js';
/** @const */ var IMO_SPC_WORKER = 'bin/imo-w-spc.js';
/** @const */ var IMO_FLASH_SWF = 'bin/imo-fl.swf';
// Allow some constructors to be inherently uncallable.
function defineUnconstructable(proto) {
function ctor() { throw new TypeError('Illegal constructor'); }
if (proto) {
defineReadonlyProperty(ctor, 'prototype', proto);
}
return ctor;
}
var _IllegalConstructor = defineUnconstructable();
// Makes it so you cannot call the constructor of an object using
// <obj>.prototype.constructor.
function assignIllegalConstructorAndFreeze() {
for (var i = -1, ii = arguments.length; ++i < ii;) {
var proto = arguments[i].prototype;
//proto['constructor'] = _IllegalConstructor;
defineReadonlyProperty(proto, 'constructor', _IllegalConstructor);
//tryFreeze(proto);
defineReadonlyProperty(arguments[i], 'prototype', proto);
}
}
//<editor-fold defaultstate="collapsed" desc="Event handlers">
var eventTable = {
'init': [],
'initerror': [],
'load': [],
'loaderror': [],
'playstatechange': []
};
var defaultEventInvokers = {};
// Allow event handlers to be required.
// For example, the events init and initerror need to be specified, or else
// the caller cannot know when ImoSPC has been initialized.
function hasEventHandler(eventName) {
var h = ImoSPC['on' + eventName];
if (h !== defaultEventInvokers[eventName] && isFunction(h))
return 1;
else {
var handlers = eventTable[eventName],
handlersLength = handlers.length;
var badHandlers = 0;
if (Array.isArray(handlers) && handlersLength) {
for (var i = -1, ii = handlers.length; ++i < ii;) {
var handler = handlers[i];
if (!isFunction(handler) && (!isNotNull(handler) || !isFunction(handler['handleEvent'])))
badHandlers++;
}
return badHandlers < handlersLength;
}
}
}
function requireEvent(eventName) {
if (!hasEventHandler(eventName))
throw new TypeError(eventName + " event must be handled.");
}
function imoAddEventHandler(eventName, callback) {
if (!isFunction(callback) && (!isNotNull(callback) || !isFunction(callback['handleEvent'])))
throw new TypeError('callback must be a function or event handler.');
var handlers = eventTable[eventName];
if (Array.isArray(handlers))
handlers.push(callback);
}
function imoDeleteEventHandler(eventName, callback) {
if (!isFunction(callback) && (!isNotNull(callback) || !isFunction(callback['handleEvent'])))
throw new TypeError('callback must be a function or event handler.');
var handlers = eventTable[eventName];
if (Array.isArray(handlers)) {
var index = handlers.lastIndexOf(callback);
if (index >= 0) handlers.splice(index, 1);
}
}
function imoDefaultInvokeEvent(eventName, target, oEvt) {
var handlers = eventTable[eventName];
if (Array.isArray(handlers)) {
for (var i = -1, ii = handlers.length; ++i < ii;) {
var handler = handlers[i];
if (isFunction(handler))
//try { handler.call(target, oEvt); } catch (e) {}
handler.call(target, oEvt);
else if (isNotNull(handler) && isFunction(handler['handleEvent']))
//try { handler['handleEvent'](oEvt); } catch (e) {}
handler['handleEvent'](oEvt);
}
}
}
function imoInvokeEvent(eventName, target, oEvt) {
var fn = ImoSPC['on' + eventName];
target = target || ImoSPC;
if (fn !== defaultEventInvokers[eventName] && isFunction(fn))
try { fn.call(target, oEvt); } catch (e) {}
else
imoDefaultInvokeEvent(eventName, target, oEvt);
}
function imoInvokeInit (oEvt) { imoInvokeEvent('init', 0, oEvt); }
function imoInvokeInitError (oEvt) { imoInvokeEvent('initerror', 0, oEvt); }
function imoInvokeLoad (oEvt) { imoInvokeEvent('load', 0, oEvt); }
function imoInvokeLoadError (oEvt) { imoInvokeEvent('loaderror', 0, oEvt); }
function imoInvokePlayStateChange (oEvt) { imoInvokeEvent('playstatechange', 0, oEvt); }
// Create default event handlers (ImoSPC.on<event>) and add them to the list
// of default event invokers, that way, isHandlerEmpty can determine if
(function(){
function createDefaultEventHandler(event) {
return function(oEvt) {
imoDefaultInvokeEvent(event, this, oEvt);
};
}
for (var evt in eventTable) if (eventTable.hasOwnProperty(evt)) {
defaultEventInvokers[evt] = createDefaultEventHandler(evt);
}
}());
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Shims, polyfills, etc.">
// Need to detect MSIE 8 or older
var msie = (function() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0) {
return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}
}());
if (!Array['isArray'] || msie && msie < 9) {
Array['isArray'] = function(o) {
return Object.prototype.toString.call(o) === '[object Array]';
};
}
var ArrayBuffer = global.ArrayBuffer;
var AudioContext = global.AudioContext || global.webkitAudioContext;
var Worker = global.Worker;
var XMLHttpRequest = global.XMLHttpRequest;
var tryFreeze = Object.freeze || function(o) { return o; };
function quickShim(cls, name, shim) {
if (!cls.prototype[name])
cls.prototype[name] = shim;
}
function quickShimRename(cls, standardName, oddName) {
quickShim(cls, standardName, cls.prototype[oddName]);
}
quickShim(Array, 'forEach', function(callback, thisArg) {
if (!thisArg) thisArg = null;
var length = this.length >>> 0;
for (var i = -1; ++i < length;) {
if (i in this)
callback.call(thisArg, this[i], i, this);
}
});
quickShim(Array, 'indexOf', function(x, i) {
var length = this.length >>> 0;
i |= 0;
if (i < 0) {
i += length;
if (i < 0) i = 0;
}
for (; i < length; i++) {
if (this[i] === x) return i;
}
return -1;
});
var defineReadonlyProperty, defineReadonlyProperties;
if (Object.defineProperty && (!msie || msie > 8)) {
defineReadonlyProperty = function (cls, propertyName, value, invisible) {
Object.defineProperty(cls, propertyName, {
'configurable': false,
'writable': false,
'enumerable': !invisible && propertyName !== 'prototype',
'value': value
});
};
defineReadonlyProperties = function(cls, properties, invisible) {
for (var key in properties)
properties[key] = {
'configurable': false,
'writable': false,
'enumerable': !invisible,
'value': properties[key]
};
Object.defineProperties(cls, properties);
};
} else {
defineReadonlyProperty = function (cls, propertyName, value) {
cls[propertyName] = value;
};
defineReadonlyProperties = function (cls, properties) {
for (var key in properties)
if (properties.hasOwnProperty(key))
cls[key] = properties[key];
};
}
function isDefined(obj) {
return obj !== undefined_;
}
function isNotNull(obj) {
// TODO: Replace with "return obj != null_" when minifying.
// Try to find a way to do so automatically.
return obj !== undefined_ && obj !== null_;
}
function isFunction(obj) {
return typeof obj === 'function';
}
function doNothing() {}
function hashOf(str) {
if (!isNaN(str)) return str;
str = String(str);
var hash = 0;
for (var i = -1, ii = str.length; ++i < ii;) {
hash = hash * 31 + str.charCodeAt(i);
}
return hash;
}
function clearArray(a) {
a['length'] = 0;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="URL functions">
// The following function is under public domain.
// See https://gist.github.com/Yaffle/1088850 for the original version.
var absolutizeURI = (function(){
function parseURI(url) {
var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
// authority = '//' + user + ':' + pass '@' + hostname + ':' port
return (m ? {
href : m[0] || '',
protocol : m[1] || '',
authority: m[2] || '',
host : m[3] || '',
hostname : m[4] || '',
port : m[5] || '',
pathname : m[6] || '',
search : m[7] || '',
hash : m[8] || ''
} : null);
}
function removeDotSegments(input) {
var output = [];
input.replace(/^(\.\.?(\/|$))+/, '')
.replace(/\/(\.(\/|$))+/g, '/')
.replace(/\/\.\.$/, '/../')
.replace(/\/?[^\/]*/g, function (p) {
if (p === '/..') {
output.pop();
} else {
output.push(p);
}
});
return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : '');
}
return function(base, href) {// RFC 3986
href = parseURI(href || '');
base = parseURI(base || '');
return !href || !base ? null : (href.protocol || base.protocol) +
(href.protocol || href.authority ? href.authority : base.authority) +
removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +
(href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
href.hash;
};
}());
function relativeToPage(url) {
return absolutizeURI(location.href, url);
}
// Get the location of the current script, so that the workers can be found.
var imoLocation = (function() {
var scripts = document.getElementsByTagName('script');
return relativeToPage(scripts[scripts.length - 1].src);
}());
function relativeToScript(url) {
return absolutizeURI(imoLocation, url);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="ImoSPC.Error, ImoSPC.Runtime, and ImoSPC.PlaybackState">
/** @const */ var E_SUCCESS = undefined_;
/** @const */ var E_UNKNOWN = 'unknown error';
/** @const */ var E_INVALID_SPC = 'invalid spc';
/** @const */ var E_INVALID_ZIP = 'invalid zip';
/** @const */ var E_EMPTY_ARCHIVE = 'empty archive';
/** @const */ var E_UNKNOWN_FILE_TYPE = 'unknown file type';
/** @const */ var E_BAD_URL = 'invalid url';
/** @const */ var E_DOWNLOAD_ERROR = 'download error';
// Can't distinguish between CORS errors and other errors with XHR, so don't
// do it with Flash, either. Use E_DOWNLOAD_ERROR instead.
///** @const */ var E_SECURITY_ERROR = 'crossdomain';
/** @const */ var E_DOWNLOAD_ABORTED = 'download aborted';
/** @const */ var E_IO = 'io error';
/** @const */ var E_PATH_NOT_FOUND = 'path not found in archive';
/** @const */ var E_BROWSER_NOT_SUPPORTED = 'browser not supported';
/** @const */ var E_TIMEOUT = 'swf load timeout';
/** @const */ var E_FLASHBLOCK = 'swf blocked';
var ImoError = tryFreeze({
'SUCCESS': E_SUCCESS,
'UNKNOWN': E_UNKNOWN,
'INVALID_SPC': E_INVALID_SPC,
'INVALID_ZIP': E_INVALID_ZIP,
'EMPTY_ARCHIVE': E_EMPTY_ARCHIVE,
'UNKNOWN_FILE_TYPE': E_UNKNOWN_FILE_TYPE,
'BAD_URL': E_BAD_URL,
'DOWNLOAD_ERROR': E_DOWNLOAD_ERROR,
//'SECURITY_ERROR': E_SECURITY_ERROR,
'DOWNLOAD_ABORTED': E_DOWNLOAD_ABORTED,
'IO_ERROR': E_IO,
'PATH_NOT_FOUND': E_PATH_NOT_FOUND,
'BROWSER_NOT_SUPPORTED': E_BROWSER_NOT_SUPPORTED,
'TIMEOUT': E_TIMEOUT,
'FLASHBLOCK': E_FLASHBLOCK
});
/** @const */ var R_NONE = null_;
/** @const */ var R_HTML5 = 'html5';
/** @const */ var R_FLASH = 'flash';
var ImoRuntime = tryFreeze({
'NONE': R_NONE,
'HTML5': R_HTML5,
'FLASH': R_FLASH
});
/** @const */ var P_STOPPED = 'stopped';
/** @const */ var P_LOADING = 'loading';
/** @const */ var P_BUFFERING = 'buffering';
/** @const */ var P_PLAYING = 'playing';
/** @const */ var P_PAUSED = 'paused';
var ImoPlaybackState = tryFreeze({
'STOPPED': P_STOPPED,
'PLAYING': P_PLAYING,
'PAUSED': P_PAUSED,
'BUFFERING': P_BUFFERING,
'LOADING': P_LOADING
});
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Comparison helpers">
// Coerces a and b to signed ints, and then compares them.
function intcmp(a, b) {
return (a | 0) - (b | 0);
}
// Replaces null or undefined with an empty string, and then
// compares the strings.
function strcmp(a, b) {
return (a || '').localeCompare(b || '');
}
function UrlTrackSort(trackA, trackB) {
return strcmp(trackA.url, trackB.url) ||
strcmp(trackA.title, trackB.title);
}
function TitleTrackSort(trackA, trackB) {
return strcmp(trackA.title, trackB.title) ||
strcmp(trackA.url, trackB.url);
}
function GameTrackSort(trackA, trackB) {
return strcmp(trackA.game, trackB.game) ||
TitleTrackSort(trackA, trackB);
}
function FilenameTrackSort(trackA, trackB) {
return strcmp(trackA.filename, trackB.filename) ||
UrlTrackSort(trackA, trackB);
}
function ChronologicalTrackSort(trackA, trackB) {
return strcmp(trackA.osttitle, trackB.osttitle) ||
intcmp(trackA.ostdisc, trackB.ostdisc) ||
intcmp(trackA.osttracknum, trackB.osttracknum) ||
strcmp(trackA.osttrackchar, trackB.osttrackchar) ||
TitleTrackSort(trackA, trackB);
}
var ImoTrackSort = tryFreeze({
'Title': TitleTrackSort,
'Game': GameTrackSort,
'URL': UrlTrackSort,
'Filename': FilenameTrackSort,
'Chronological': ChronologicalTrackSort
});
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="ImoVersion object">
function createVersionString(a, b, c) {
return a + '.' + b + '.' + c;
}
// Version info
function ImoVersion(runtime) {
// [ImoSPC vX.Y.Z, HTML5]
// [ImoSPC vX.Y.Z, uninitialized]
var prettyString = '[ImoSPC v' + createVersionString(IMO_VERSION_MAJOR, IMO_VERSION_MINOR, IMO_VERSION_BUILD) + ', ' + (runtime === R_HTML5 ? 'HTML5]' : 'unitialized]');
defineReadonlyProperties(this, {
'runtime': runtime,
'major': IMO_VERSION_MAJOR,
'minor': IMO_VERSION_MINOR,
'build': IMO_VERSION_BUILD,
'toString': function() { return prettyString; }
});
}
assignIllegalConstructorAndFreeze(ImoVersion);
var V_R_NONE = new ImoVersion(R_NONE);
var V_R_HTML5 = new ImoVersion(R_HTML5);
var V_R_FLASH = new ImoVersion(R_FLASH);
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Event descriptors">
function ImoInitEvent(v, error) {
defineReadonlyProperties(this, {
'version': v || V_R_NONE,
'error': error || E_SUCCESS
});
}
function ImoLoadEvent(url, userdata, track, playlist, corruptFiles, error, httpStatus) {
defineReadonlyProperties(this, {
'url': url,
'userdata': userdata,
'track': track,
'playlist': error ? null_ : playlist,
'corruptFiles': corruptFiles,
'error': error,
'httpStatus': error === E_DOWNLOAD_ERROR ? httpStatus : undefined_
});
}
function ImoStateEvent(state, track, playlist, trackIndex, previousTrack, previousTrackIndex) {
defineReadonlyProperties(this, {
'state': state,
'track': track,
'playlist': playlist,
'index': trackIndex,
'previousTrack': previousTrack,
'previousIndex': previousTrackIndex
});
}
assignIllegalConstructorAndFreeze(ImoInitEvent, ImoLoadEvent, ImoStateEvent/*, ImoPlayStateEvent*/);
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Support detector">
var isHtml5Supported, supportQueryArray;
/** @const */ var FLASH_MIME_TYPE = 'application/x-shockwave-flash';
/** @const */ var SHOCKWAVE_FLASH = 'Shockwave Flash';
/** @const */ var SHOCKWAVE_FLASH_AX = 'ShockwaveFlash.ShockwaveFlash';
// Flash ImoSPC requires Adobe Flash Player 11.5 or greater.
var isFlashSupported = (function(){
var major, minor, plugins = navigator.plugins, mimeTypes = navigator.mimeTypes;
if (!msie && plugins) {
if (plugins[SHOCKWAVE_FLASH]) {
var desc = plugins[SHOCKWAVE_FLASH].description;
if (desc && !(mimeTypes && mimeTypes[FLASH_MIME_TYPE] && !mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) {
var version = desc.match(/(\d+)/g);
major = version[0];
minor = version[1];
} else return;
} else return;
} else if (typeof ActiveXObject === 'function') {
try {
var version = new ActiveXObject(SHOCKWAVE_FLASH_AX).GetVariable('$version');
version = version.split(' ')[1].split(',');
major = version[0];
minor = version[1];
} catch (e) { return; }
} else return; // Can't detect Flash
major = parseInt(major, 10);
minor = parseInt(minor, 10);
return major > 11 || (major === 11 && minor >= 5);
}());
function testHTML5Support(callback) {
if (isDefined(isHtml5Supported)) {
callback(isHtml5Supported);
} else {
var _URL = global.webkitURL || global.URL;
if (!ArrayBuffer || !Worker || !AudioContext || !XMLHttpRequest ||
!global.Blob || !isFunction(_URL.createObjectURL)) {
supportQueryArray = tryFreeze(isFlashSupported ? [R_FLASH] : []);
callback(isHtml5Supported = false);
return;
}
try {
var tstBlob = new Blob(['postMessage(self.FileReaderSync?"a":"")'], { 'type': 'text/javascript' });
var u = _URL.createObjectURL(tstBlob);
var testWorker = new Worker(u);
testWorker['onmessage'] = function(s) {
_URL.revokeObjectURL(u);
testWorker.terminate();
supportQueryArray = s ? [R_HTML5] : [];
if (isFlashSupported) supportQueryArray.unshift(R_FLASH);
tryFreeze(supportQueryArray);
callback(isHtml5Supported = !!s);
};
} catch (e) {
supportQueryArray = tryFreeze(isFlashSupported ? [R_FLASH] : []);
callback(isHtml5Supported = false);
}
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Single Instance Helper">
var takeControl;
if (global['Storage'] !== 'undefined') {
/** @const */ var IMO_CTL = '_ImoCurrentInstanceController';
takeControl = function() {
try { if (!ImoSPC['allowMultipleInstances'])
localStorage.setItem(IMO_CTL, localStorage.getItem(IMO_CTL)^1);
} catch (e) {}
};
var loseControl = function(e) {
//if (_stop && (e || global['event'])['key'] === IMO_CTL) _stop();
if (_pause && (e || global['event'])['key'] === IMO_CTL) _pause();
};
if (isFunction(global.addEventListener)) {
global.addEventListener('storage', loseControl, false);
} else if (isFunction(global.attatchEvent)) {
global.attatchEvent('onstorage', loseControl);
} else takeControl = doNothing;
} else takeControl = doNothing;
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Percent decoder">
function safePctDecFn(match) {
var s = '';
match = match.split('%');
for (var i = 1, ii = match.length; i < ii;) {
var c = parseInt(match[i++], 16);
if (c > 0x7F) {
var extra, min;
/**/ if ((c & 0xE0)===0xC0) extra = 1, c &= 0x1F, min = 0x00080;
else if ((c & 0xF0)===0xE0) extra = 2, c &= 0x0F, min = 0x00800;
else if ((c & 0xF8)===0xF0) extra = 3, c &= 0x07, min = 0x10000;
else {
/**/ if ((c & 0xFC) === 0xF8) extra = 4;
else if ((c & 0xFE) === 0xFC) extra = 5;
else extra = 0;
while (--extra >= 0) {
var x = parseInt(match[i], 16);
if ((x & 0xC0) !== 0x80)
break;
i++;
}
c = 0xFFFD;
}
while (--extra >= 0) {
var x = parseInt(match[i], 16);
if ((x & 0xC0) !== 0x80) {
c = 0xFFFD;
break;
}
i++;
c = (c << 6) | (x & 0x3F);
}
if (c < min || c > 0x10FFFF ||
c === 0xFFFE || c === 0xFFFF) c = 0xFFFD;
}
if (c > 0xFFFF) {
c -= 0x10000;
var lead = 0xD800 + (c >> 10),
trail = 0xDC00 + (c & 0x3FF);
s += String.fromCharCode(lead, trail);
} else {
s += String.fromCharCode(c);
}
}
return s;
}
function safePercentDecode(str) {
return String(str).replace(/((?:%[a-f\d]{2})+)/ig, safePctDecFn);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Hashtable">
function Hashtable() {
var hashes = [],
keys = [],
values = [];
this.remove = function(key) {
var hash = hashOf(key);
for (var i = -1, ii = hashes.length; ++i < ii;) {
if (hashes[i] === hash) {
if (keys[i] === key) {
var value = values[i];
hashes.splice(i, 1);
keys.splice(i, 1);
values.splice(i, 1);
return value;
}
}
}
};
this.add = function(key, value) {
hashes.push(hashOf(key));
keys.push(key);
values.push(value);
};
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="BaseImo">
// _play: function(seekTo, track, playlist)
var volume = 1;
var _open, _play, _pause, _unpause, _stop, _getTime, _setVolume, _setLoop;
var _curPlaylist, _curTrack, _curTrackIndex;
// Keep these separate from the currently playing stuff
// The URL is kept here as well, since objects can't be sent to workers.
var pendingPlayUrl, pendingPlayTrack, pendingPlayPlaylist, pendingPlayTrackIndex;
var _isPaused;
var setIsFunctional, setVersion;
//<editor-fold defaultstate="collapsed" desc="Track">
var Track_prototype_play;
var Track_fields = [
'url', '_ofs', 'title', 'game', 'artist', 'publisher', 'copyright',
'osttitle', 'ostdisc', 'osttrack', 'osttracknum', 'osttrackchar',
'_fSt', '_fLn' //'length'
];
function Track(metadata) {
var that = this; // Cannot access this in closure
Track_fields.forEach(function(field, i) {
defineReadonlyProperty(that, field, metadata[i]);
});
var url = metadata[0];
if (url) {
var filename;
url = String(url);
var hashPos = url.indexOf('#');
if (hashPos >= 0) {
var archive = url.substring(0, hashPos);
var path = safePercentDecode(url.substring(hashPos + 1));
defineReadonlyProperties(this, {
'archive': archive,
'path': path
});
filename = path.substring(path.lastIndexOf('/') + 1);
} else {
if (!url.lastIndexOf('data:', 0)) {
filename = '[data]';
} else if (!url.lastIndexOf('blob:', 0)) {
filename = '[blob]';
} else {
filename = url.substring(url.search(/[^\/\\]*$/));
}
}
defineReadonlyProperty(that, 'filename', filename);
}
defineReadonlyProperty(that, 'length', +metadata[12] + +metadata[13]);
}
function trackfn(x) { if (!(x instanceof Track)) throw new TypeError('Track functions can only be called on Track objects.'); }
defineReadonlyProperties(Track.prototype, {
'play': Track_prototype_play = function(seekTo) {
trackfn(this);
_play(+seekTo || 0, this);
},
//'pause': function() { trackfn(this); return areTracksEqual(_curTrack, this) ? _pause() : false; },
//'unpause': function() { trackfn(this); return areTracksEqual(_curTrack, this) ? _unpause() : false; },
//'stop': function() { trackfn(this); return areTracksEqual(_curTrack, this) ? _stop() : false; },
'pause': function() { trackfn(this); return isCurrentTrack(this) ? _pause() : false; },
'unpause': function() { trackfn(this); return isCurrentTrack(this) ? _unpause() : false; },
'stop': function() { trackfn(this); return isCurrentTrack(this) ? _stop() : false; },
'time': function() { trackfn(this); return areTracksEqual(_curTrack, this) ? _getTime() : -1; },
'seek': function(to, relative) {
trackfn(this);
if (isNaN(to)) throw new TypeError('to must be a number.');
if (areTracksEqual(_curTrack, this) && (to || !relative)) {
var time = _getTime();
if (time >= 0) {
if (relative) to += time;
_play(to, _curPlaylist ? _curTrackIndex : _curTrack, _curPlaylist);
return true;
}
}
return false;
},
'toString': function(that) {
that = this;
return '[ImoSPC.Track, ' + (that['title'] || that['filename'] || that['url']) + ']';
}
});
// Track's prototype doesn't need to be sealed, because end users cannot
// access this Track function.
//defineReadonlyProperty(Track, 'prototype', Track.prototype);
// It is theoretically possible for two different track objects for the same
// URL, so compare tracks using their URLs, not the objects.
function areTracksEqual(a, b) {
if (!a || !b) return a === b;
return a['url'] === b['url'];
}
function isCurrentTrack(t) {
return areTracksEqual(pendingPlayTrack || _curTrack, t);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Playlist">
var Playlist_prototype_play;
function Playlist(tracks) {
defineReadonlyProperty(this, 'tracks', tryFreeze(tracks));
defineReadonlyProperties(this, {
'tracks': tryFreeze(tracks),
'length': tracks.length
});
}
// The user version of Playlist; verifies its arguments, and clones tracks.
function _Playlist(tracks) {
if (!Array.isArray(tracks))
throw new TypeError('tracks is not an array.');
if (!tracks.length)
throw new TypeError('tracks is empty.');
tracks.forEach(function(t) {
if (!(t instanceof Track))
throw new TypeError('tracks contains an invalid track.');
});
Playlist.call(this, tracks.slice());
}
function playlistfn(x) { if (!(x instanceof Playlist)) throw new TypeError('Playlist functions can only be called on Playlist objects.'); }
defineReadonlyProperties(Playlist.prototype, {
'constructor': _Playlist,
'play': Playlist_prototype_play = function(track, startAt) {
playlistfn(this);
var tracks = this['tracks'];
if (isNotNull(track) && isNaN(track)) {
if (track instanceof Track) {
track = tracks.indexOf(track);
} else {
throw new TypeError('track must be a Track object or the index of a track.');
}
} else track = +track;
if (isNotNull(startAt) && isNaN(startAt))
throw new TypeError('startAt must be a number.');
if (track < 0 || track > tracks.length ||
!(tracks[track >>>= 0] instanceof Track))
throw new RangeError('track is not in the playlist.');
_play(+startAt || 0, track, this);
},
'pause': function() { playlistfn(this); return isActivePlaylist(this) ? _pause() : false; },
'unpause': function() { playlistfn(this); return isActivePlaylist(this) ? _unpause() : false; },
'stop': function() { playlistfn(this); return isActivePlaylist(this) ? _stop() : false; },
'first': function() { playlistfn(this); return this['tracks'][0]; },
'previous': function() { playlistfn(this); return isActivePlaylist(this) ? this['tracks'][getCurrentTrack() - 1] : undefined_; },
'current': function() { playlistfn(this); return isActivePlaylist(this) ? pendingPlayTrack || _curTrack : undefined_; },
'next': function() { playlistfn(this); return isActivePlaylist(this) ? this['tracks'][getCurrentTrack() + 1] : undefined_; },
'last': function() { playlistfn(this); var tracks = this['tracks']; return tracks[tracks.length - 1]; },
'indexOfFirst': function() { playlistfn(this); return 0; },
'indexOfPrevious': function() { playlistfn(this); return isActivePlaylist(this) ? _curTrackIndex - 1 : -1; },
'indexOfCurrent': function() { playlistfn(this); return isActivePlaylist(this) ? _curTrack : -1; },
'indexOfNext': function() { playlistfn(this); var trkL = this['tracks'].length, trkI = getCurrentTrack() + 1; return (isActivePlaylist(this) && trkI < trkL) ? trkI : -1; },
'indexOfLast': function() { playlistfn(this); return this['tracks'].length - 1; },
'sort': function(compareFunction) {
playlistfn(this);
// Do not change to !==; treat undefined and null equally
if (isNotNull(compareFunction)) {
if (!isFunction(compareFunction))
throw new TypeError('compareFunction is not a function.');
} else compareFunction = ChronologicalTrackSort;
return new Playlist(this.tracks.slice().sort(compareFunction));
},
'sortReverse': function(compareFunction) {
playlistfn(this);
// Do not change to !==; treat undefined and null equally
if (isNotNull(compareFunction)) {
if (!isFunction(compareFunction))
throw new TypeError('compareFunction is not a function.');
} else compareFunction = ChronologicalTrackSort;
return new Playlist(this.tracks.slice().sort(compareFunction).reverse());
},
'toString': function() {
return '[ImoSPC.Playlist, ' + this['length'] + ' track(s)]';
}
});
// Seal the prototype of _Playlist so that external callers can't fuck it up
defineReadonlyProperty(_Playlist, 'prototype', Playlist.prototype);
function isActivePlaylist(p) {
return (pendingPlayPlaylist || _curPlaylist) === p;
}
function getCurrentTrack() {
return isNotNull(pendingPlayTrackIndex) ? pendingPlayTrackIndex : _curTrackIndex;
}
//</editor-fold>
var isInitializationInProgress;
var ImoSPC = {};
defineReadonlyProperties(ImoSPC, {
'Error': ImoError,
'Runtime': ImoRuntime,
'PlaybackState': ImoPlaybackState,
'TrackSort': ImoTrackSort,
'Playlist': _Playlist,
'Track': defineUnconstructable(Track['prototype']),
'InitEvent': ImoInitEvent,
'LoadEvent': ImoLoadEvent,
'PlayStateEvent': ImoStateEvent,
'currentTrack': function() {
return pendingPlayTrack || _curTrack;
},
'currentPlaylist': function() {
return pendingPlayPlaylist || _curPlaylist;
},
'querySupportedRuntimes': function(callback) {
if (isDefined(isHtml5Supported)) {
callback(supportQueryArray);
} else {
testHTML5Support(function() {
callback(supportQueryArray);
});
}
},
'open': function(url, options) { _open(url, options); },
'play': function(arg1, arg2, arg3) {
if (!arguments.length) throw new TypeError('ImoSPC.play() cannot be called without arguments.');
if (arg1 instanceof Playlist) {
Playlist_prototype_play.call(arg1, arg2, arg3);
} else if (arg1 instanceof Track) {
Track_prototype_play.call(arg1, arg2);
} else throw new TypeError('The first argument of ImoSPC.play() must be a track or playlist.');
},
'pause': function() { return _pause(); },
'unpause': function() { return _unpause(); },
'stop': function() { return _stop(); },
'time': function() { return _getTime ? _getTime() : -1; },
'getVolume': function() { return volume; },
'setVolume': function(v) {
if (isNaN(v = +v)) throw new TypeError('volume must be a number.');
if (v < 0 || v > 1) throw new RangeError('volume must be between 0 and 1.');
volume = v;
if (_setVolume) _setVolume(v);
return volume;
},
'setRepeat': function(l) { _setLoop(!!l); },
'canSeek': true,
'canSetVolume': true,
'addEventListener': imoAddEventHandler,
'removeEventListener': imoDeleteEventHandler,
'toString': function() {
return String(this['version']);
}
});
(function() {
if (Object.defineProperties && (!msie || msie > 8)) {
var version = V_R_NONE;
var autostart = false,
autoplay = true,
allowMultipleInstances = false;
Object.defineProperties(ImoSPC, {
'isFunctional': {
'enumerable': true,
'configurable': false,
'get': function() {
return !!(_open && _play && _pause && _unpause && _stop && _getTime && _setVolume);
}
},
'version': {
'enumerable': true,
'configurable': false,
'get': function() {
return version;
}
},
'autostart': {
'enumerable': true,
'configurable': false,
'get': function() { return autostart; },
'set': function(v) { autostart = !!v; }
},
'autoplay': {