-
Notifications
You must be signed in to change notification settings - Fork 6
/
oggvorbis.js
3856 lines (3446 loc) · 129 KB
/
oggvorbis.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
// Ogg Vorbis I audio decoder -- version 0.99996
//
// Written in April 2007 by Sean Barrett, sponsored by RAD Game Tools. http://nothings.org/stb_vorbis/
//
// This Version is a javascript version hand ported by Dominik Homberger ([email protected])
// License: CC BY-NC-SA 4.0 https://creativecommons.org/licenses/by-nc-sa/4.0/
(function(){
var buffer_time;
var player_type_audio;
var player_type_embed;
var player_type;
// JavaScript Document
var _iobuf = function(){
this._ptr=char_;//*
this._ptr_off=0;//*
this._cnt=int_;
this._base=char_;//*
this._base_off=0;//*
this._flag=int_;
this._file=int_;
this._charbuf=int_;
this._bufsiz=int_;
this._tmpfname=char_;//*
this._tmpfname_off=0;//*
};
var FILE=_iobuf;
var EOF = (-1);
//FILE * fopen ( const char * filename, const char * mode );
function fopen ( filename, mode ) {
var f = new FILE();
f._ptr=filename;
return f;
}
//int fgetc ( FILE * stream );
function fgetc ( stream ) {
if(stream._ptr.length<=stream._ptr_off) return EOF;
return stream._ptr[stream._ptr_off++];
}
//fread
//size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
function fread ( ptr, size, count, stream ) {
//ptr.val=new Array();
//todo: size include
if(stream._ptr.length<count+stream._ptr_off) {stream._ptr_off += count; return EOF; }//0
for(var i=0;i<size*count;++i)
ptr[i]=(stream._ptr[stream._ptr_off++]);
return 1;
}
/* Seek method constants */
var SEEK_CUR = 1;
var SEEK_END = 2;
var SEEK_SET = 0;
//int fseek ( FILE * stream, long int offset, int origin );
function fseek ( stream, offset, origin ) {
switch (origin) {
case SEEK_CUR:
break;
case SEEK_END:
break;
case SEEK_SET:
stream._ptr_off = offset;
break;
default:
assert(0);
break;
}
}
//ftell
//long int ftell ( FILE * stream );
function ftell(stream) {
return stream._ptr_off;
}
//int memcmp ( const void * ptr1, const void * ptr2, size_t num );
function memcmp ( ptr1, ptr2, num ) {
var i;
for(i=0;i<num;i++)
if(ptr1[i]!=ptr2[i])
return 1;
return 0;
}
var char_=0, short_=0, int_=0, long_=0, void_=0;
var int8=char_;
var uint8=char_;
var int16=short_;
var uint16=short_;
var int32=int_;
var uint32=int_;
var uint64=long_;
var int64=long_;
var float_=0.00;
function memcpy(dst, dst_off, src, src_off, num) {
var i;
for(i=0;i<num;++i)
dst[dst_off + i] = src[src_off + i];
}
function memset(ptr, ptr_off, value, num) {
var i=0;
for(i=0; i<num; ++i)
ptr[ptr_off + i]=value;
}
function Arr(len,val) {
var i;
var result = new Array(); for (i = 0; i < len; ++i) result.push(val);
return result;
}
function Arr_new(len,val) {
var i;
var result = new Array(); for (i = 0; i < len; ++i) result.push(new val);
return result;
}
function assert(bCondition) {
if (!bCondition) {
throw new Error('assert :P');
}
}
// JavaScript Document
//readfile("");
//10
// stb_vorbis_decode_filename: decode an entire file to interleaved shorts
function test_decode_filename(g, filename)
{
var decoded=[short_];//*
var channels=[int_], len=int_;
len = stb_vorbis_decode_filename(filename, channels, decoded);
/*if (len) {//decoded[0].length=1024*1024;//alert('test');
var dataURI = "data:audio/wav;base64,"+escape(btoa(uint8ToString(decoded[0])));
var player = document.createElement("embed");
player.setAttribute("src", dataURI);
player.setAttribute("width", 400);
player.setAttribute("height", 100);
player.setAttribute("autostart", true);
document.getElementById('player-container').appendChild(player);
}*/
// if (len)
// fwrite(decoded, 2, len*channels[0], g);
// else
// stb_fatal("Couldn't open {%s}", filename);
}
function oggvorbisdata(filename) {
buffer_time = document.getElementById('buffer_time').value; //seconds
player_type_audio = document.getElementById('player_type_audio');
player_type_embed = document.getElementById('player_type_embed');
player_type = player_type_audio.checked?"audio":player_type_embed.checked?"embed":"flash";
test_decode_filename(null, filename);
}
window['oggvorbisdata'] = oggvorbisdata;
function playbackSound(dataURI) {
if (player_type=="audio" || player_type=="embed") {
var player = document.createElement(player_type);
player.setAttribute("src", dataURI);
player.setAttribute("width", 400);
player.setAttribute("height", 100);
player.setAttribute("autostart", true);
player.setAttribute("autoplay", true);
player.setAttribute("controls", true);
} else
if (player_type=="flash") {
var player = document.createElement("span");//<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="100" height="50" id="WaveBase64_Player" align="middle"> <param name="allowScriptAccess" value="sameDomain" /><param name="FlashVars" value="base64='+dataURI+'" /> <param name="allowFullScreen" value="false" /> <param name="movie" value="WaveBase64_Player.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /> </object>
player.innerHTML ='<embed src="WaveBase64_Player.swf" quality="high" bgcolor="#ffffff" width="100" height="50" name="WaveBase64_Player" FlashVars="base64='+dataURI+'" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer_de" />';
}
document.getElementById('player-container').appendChild(player);
}
function uint8ToString(buf) {
var i, length, out = '';
for (i = 0, length = buf.length; i < length; i += 1) {
out += String.fromCharCode(buf[i]);
}
return out;
}
// Base 64 encoding function, for browsers that do not support btoa()
// by Tyler Akins (http://rumkin.com), available in the public domain
function btoa2(input) {
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
do {
chr1 = input[i++];
chr2 = input[i++];
chr3 = input[i++];
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
keyStr.charAt(enc3) + keyStr.charAt(enc4);
} while (i < input.length);
return output;
}
// JavaScript Document
//312
//////// ERROR CODES
//enum STBVorbisError
//{
var
VORBIS__no_error=0,
VORBIS_need_more_data=1, // not a real error
VORBIS_invalid_api_mixing=2, // can't mix API modes
VORBIS_outofmem=3, // not enough memory
VORBIS_feature_not_supported=4, // uses floor 0
VORBIS_too_many_channels=5, // STB_VORBIS_MAX_CHANNELS is too small
VORBIS_file_open_failure=6, // fopen() failed
VORBIS_seek_without_length=7, // can't seek in unknown-length file
VORBIS_unexpected_eof=10, // file is truncated?
VORBIS_seek_invalid=11, // seek past EOF
// decoding errors (corrupt/invalid stream) -- you probably
// don't care about the exact details of these
// vorbis errors:
VORBIS_invalid_setup=20,
VORBIS_invalid_stream=21,
// ogg errors:
VORBIS_missing_capture_pattern=30,
VORBIS_invalid_stream_structure_version=31,
VORBIS_continued_packet_flag_invalid=32,
VORBIS_incorrect_stream_serial_number=33,
VORBIS_invalid_first_page=34,
VORBIS_bad_packet_type=35,
VORBIS_cant_find_last_page=36,
VORBIS_seek_failed=37
//}
;
//391
// STB_VORBIS_MAX_CHANNELS [number]
// globally define this to the maximum number of channels you need.
// The spec does not put a restriction on channels except that
// the count is stored in a byte, so 255 is the hard limit.
// Reducing this saves about 16 bytes per value, so using 16 saves
// (255-16)*16 or around 4KB. Plus anything other memory usage
// I forgot to account for. Can probably go as low as 8 (7.1 audio),
// 6 (5.1 audio), or 2 (stereo only).
//#ifndef STB_VORBIS_MAX_CHANNELS
var STB_VORBIS_MAX_CHANNELS = 16; // enough for anyone?
//#endif
//403
// STB_VORBIS_PUSHDATA_CRC_COUNT [number]
// after a flush_pushdata(), stb_vorbis begins scanning for the
// next valid page, without backtracking. when it finds something
// that looks like a page, it streams through it and verifies its
// CRC32. Should that validation fail, it keeps scanning. But it's
// possible that _while_ streaming through to check the CRC32 of
// one candidate page, it sees another candidate page. This #define
// determines how many "overlapping" candidate pages it can search
// at once. Note that "real" pages are typically ~4KB to ~8KB, whereas
// garbage pages could be as big as 64KB, but probably average ~16KB.
// So don't hose ourselves by scanning an apparent 64KB page and
// missing a ton of real ones in the interim; so minimum of 2
//#ifndef STB_VORBIS_PUSHDATA_CRC_COUNT
var STB_VORBIS_PUSHDATA_CRC_COUNT = 4;
//#endif
//419
// STB_VORBIS_FAST_HUFFMAN_LENGTH [number]
// sets the log size of the huffman-acceleration table. Maximum
// supported value is 24. with larger numbers, more decodings are O(1),
// but the table size is larger so worse cache missing, so you'll have
// to probe (and try multiple ogg vorbis files) to find the sweet spot.
//#ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH
var STB_VORBIS_FAST_HUFFMAN_LENGTH = 10;
//#endif
//571
//#ifdef STB_VORBIS_CODEBOOK_FLOATS
var codetype=float_;
//#else
//typedef uint16 codetype;
//#endif
// @NOTE
//
// Some arrays below are tagged "//varies", which means it's actually
// a variable-sized piece of data, but rather than malloc I assume it's
// small enough it's better to just allocate it all together with the
// main thing
//
// Most of the variables are specified with the smallest size I could pack
// them into. It might give better performance to make them all full-sized
// integers. It should be safe to freely rearrange the structures or change
// the sizes larger--nothing relies on silently truncating etc., nor the
// order of variables.
var FAST_HUFFMAN_TABLE_SIZE = (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH);
var FAST_HUFFMAN_TABLE_MASK = (FAST_HUFFMAN_TABLE_SIZE - 1);
//593
var Codebook = function()
{
this.dimensions=int_, this.entries=int_;
this.codeword_lengths=uint8;//*
this.minimum_value=float_;
this.delta_value=float_;
this.value_bits=uint8;
this.lookup_type=uint8;
this.sequence_p=uint8;
this.sparse=uint8;
this.lookup_values=uint32;
this.multiplicands=codetype;//*
this.codewords=uint32;//*
// #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
this.fast_huffman=new Array(FAST_HUFFMAN_TABLE_SIZE);//int16
// #else
// int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
// #endif
this.sorted_codewords=uint32;//*
this.sorted_values=int_;//*
this.sorted_values_off=0;//*
this.sorted_entries=int_;
};
//616
var Floor0 = function()
{
this.order=uint8;
this.rate=uint16;
this.bark_map_size=uint16;
this.amplitude_bits=uint8;
this.amplitude_offset=uint8;
this.number_of_books=uint8;
this.book_list=new Array(16);//uint8 // varies
};
//627
var Floor1 = function()
{
this.partitions=uint8;
this.partition_class_list=new Array(32);//uint8 // varies
this.class_dimensions=new Array(16);//uint8 // varies
this.class_subclasses=new Array(16);//uint8 // varies
this.class_masterbooks=new Array(16);//uint8 // varies
this.subclass_books=new Array(16);for(var i=0;i<16;i++)this.subclass_books[i]=new Array(8);//int16 // varies
this.Xlist=new Array(31*8+2);//uint16 // varies
this.sorted_order=new Array(31*8+2);//uint8
this.neighbors=new Array(31*8+2);for(var i=0;i<31*8+2;i++)this.neighbors[i]=new Array(2);//uint8
this.floor1_multiplier=uint8;
this.rangebits=uint8;
this.values=int_;
};
//643
var Floor = function() //union
{
this.floor0=new Floor0();
this.floor1=new Floor1();
};
//649
var Residue = function()
{
this.begin=uint32, this.end=uint32;
this.part_size=uint32;
this.classifications=uint8;
this.classbook=uint8;
this.classdata=uint8;//**
this.residue_books=new Array(8);//int16 //(*)
};
//659
var MappingChannel = function()
{
this.magnitude=uint8;
this.angle=uint8;
this.mux=uint8;
};
//666
var Mapping = function()
{
this.coupling_steps=uint16;
this.chan='MappingChannel';//*
this.submaps=uint8;
this.submap_floor=new Array(15);//uint8 // varies
this.submap_residue=new Array(15);//uint8 // varies
};
//675
var Mode = function()
{
this.blockflag=uint8;
this.mapping=uint8;
this.windowtype=uint16;
this.transformtype=uint16;
};
//692
var ProbedPage = function()
{
this.page_start, this.page_end=uint32;
this.after_previous_page_start=uint32;
this.first_decoded_sample=uint32;
this.last_decoded_sample=uint32;
};
//700
var stb_vorbis = function()
{
// user-accessible info
this.sample_rate=int_;//unsigned
this.channels=int_;
this.setup_memory_required=int_;//unsigned
this.temp_memory_required=int_;//unsigned
this.setup_temp_memory_required=int_;//unsigned
// input config
//#ifndef STB_VORBIS_NO_STDIO
this.f='FILE';//*
this.f_start=uint32;
this.close_on_free=int_;
//#endif
this.stream=uint8;//*
this.stream_off=0;//*
this.stream_start=uint8;//*
this.stream_start_off=0;//*
this.stream_end=uint8;//*
this.stream_end_off=0;//*
this.stream_len=uint32;
this.push_mode=uint8;
this.first_audio_page_offset=uint32;
this.p_first='ProbedPage', this.p_last='ProbedPage';
// memory management
this.alloc='stb_vorbis_alloc';
this.setup_offset=int_;
this.temp_offset=int_;
// run-time results
this.eof=int_;
this.error='enum STBVorbisError';
// user-useful data
// header info
this.blocksize=new Array(2);//int
this.blocksize_0=int_, this.blocksize_1=int_;
this.codebook_count=int_;
this.codebooks='Codebook';//*
this.floor_count=int_;
this.floor_types=new Array(64);//uint16 // varies
this.floor_config='Floor';//*
this.residue_count=int_;
this.residue_types=new Array(64);//uint16 // varies
this.residue_config='Residue';//*
this.mapping_count=int_;
this.mapping='Mapping';//*
this.mode_count=int_;
this.mode_config=Arr_new(64,Mode); // varies
this.total_samples=uint32;
// decode buffer
this.channel_buffers=new Array(STB_VORBIS_MAX_CHANNELS);//float *
this.outputs =new Array(STB_VORBIS_MAX_CHANNELS);//float *
this.previous_window=new Array(STB_VORBIS_MAX_CHANNELS);//float *
this.previous_length=int_;
//#ifndef STB_VORBIS_NO_DEFER_FLOOR
this.finalY=new Array(STB_VORBIS_MAX_CHANNELS);//int16 *
//#else
//float *floor_buffers[STB_VORBIS_MAX_CHANNELS];
//#endif
this.current_loc=uint32; // sample location of next frame to decode
this.current_loc_valid=int_;
// per-blocksize precomputed data
// twiddle factors
this.A=new Array(2),this.B=new Array(2),this.C=new Array(2);//float *,*,*
this.window_=new Array(2);//float *
this.bit_reverse=new Array(2);//uint16 *
// current page/packet/segment streaming info
this.serial=uint32; // stream serial number for verification
this.last_page=int_;
this.segment_count=int_;
this.segments=Arr(255,uint8);//
this.page_flag=uint8;
this.bytes_in_seg=uint8;
this.first_decode=uint8;
this.next_seg=int_;
this.last_seg=int_; // flag that we're on the last segment
this.last_seg_which=int_; // what was the segment number of the last seg?
this.acc=uint32;
this.valid_bits=int_;
this.packet_bytes=int_;
this.end_seg_with_known_loc=int_;
this.known_loc_for_packet=uint32;
this.discard_samples_deferred=int_;
this.samples_output=uint32;
// push mode scanning
this.page_crc_tests=int_; // only in push_mode: number of tests active; -1 if not searching
//#ifndef STB_VORBIS_NO_PUSHDATA_API
this.scan=new Array(STB_VORBIS_PUSHDATA_CRC_COUNT);//CRCscan
//#endif
// sample-access
this.channel_buffer_start=int_;
this.channel_buffer_end=int_;
};
//818
//extern int my_prof(int slot);
////#define stb_prof my_prof
//
//#ifndef stb_prof
function stb_prof(x) { return 0 }
//#endif
//818
//#if defined(STB_VORBIS_NO_PUSHDATA_API)
// #define IS_PUSH_MODE(f) FALSE
//#elif defined(STB_VORBIS_NO_PULLDATA_API)
// #define IS_PUSH_MODE(f) TRUE
//#else
function IS_PUSH_MODE(f) { return ((f).push_mode) }
//#endif
//851
function temp_alloc_save(f) { return ((f).temp_offset) }
function temp_alloc_restore(f,p) { return ((f).temp_offset = (p)) }
var CRC32_POLY = 0x04c11db7; // from spec
var crc_table=new Array(256);//static uint32
//911
function crc32_init()//void
{
var i=int_,j=int_;
var s=uint32;
for(i=0; i < 256; i++) {
for (s=(i<<24)>>>0, j=0; j < 8; ++j)
s = ((s << 1) ^ (s >= ((1<<31)>>>0) ? CRC32_POLY : 0))>>>0;
crc_table[i] = s;
}
}
// used in setup, and for huffman that doesn't go fast path
//929
function bit_reverse(n)
{
n = (((n & 0xAAAAAAAA) >>> 1) | ((n & 0x55555555) << 1))>>>0;
n = (((n & 0xCCCCCCCC) >>> 2) | ((n & 0x33333333) << 2))>>>0;
n = (((n & 0xF0F0F0F0) >>> 4) | ((n & 0x0F0F0F0F) << 4))>>>0;
n = (((n & 0xFF00FF00) >>> 8) | ((n & 0x00FF00FF) << 8))>>>0;
return ((n >>> 16) | (n << 16))>>>0;
}
//938
function square(x)
{
return x*x;
}
// this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3
// as required by the specification. fast(?) implementation from stb.h
// @OPTIMIZE: called multiple times per-packet with "constants"; move to setup
//946
function ilog(n)
{
var log2_4 = new Array( 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 );//static signed char_
// 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29)
if (n < (1 << 14))//U
if (n < (1 << 4)) return 0 + log2_4[n ];//U
else if (n < (1 << 9)) return 5 + log2_4[n >>> 5];//U
else return 10 + log2_4[n >>> 10];
else if (n < (1 << 24))//U
if (n < (1 << 19)) return 15 + log2_4[n >>> 15];//U
else return 20 + log2_4[n >>> 20];
else if (n < (1 << 29)) return 25 + log2_4[n >>> 25];//U
else if (n < (1 << 31)>>>0) return 30 + log2_4[n >>> 30];//U
else return 0; // signed n returns 0
}
//#ifndef M_PI
//964
var M_PI = 3.14159265358979323846264;//f // from CRC
//#endif
//967
// code length assigned to a value with no huffman encoding
var NO_CODE = 255;
/////////////////////// LEAF SETUP FUNCTIONS //////////////////////////
//
// these functions are only called at setup, and only a few times
// per file
//975
function float32_unpack(x)
{
// from the specification
var mantissa = (x & 0x1fffff)>>>0;//uint32
var sign = (x & 0x80000000)>>>0;//uint32
var exp_ = (x & 0x7fe00000) >>> 21;//uint32
var res = sign ? -mantissa : mantissa;//double (double):(double)
return res*Math.pow(2,exp_-788);//(float) ldexp((float), )
}
// zlib & jpeg huffman tables assume that the output symbols
// can either be arbitrarily arranged, or have monotonically
// increasing frequencies--they rely on the lengths being sorted;
// this makes for a very simple generation algorithm.
// vorbis allows a huffman table with non-sorted lengths. This
// requires a more sophisticated construction, since symbols in
// order do not map to huffman codes "in order".
//993
function add_entry(c, huff_code, symbol, count, len, values)
{
if (!c.sparse) {
c.codewords [symbol] = huff_code;
} else {
c.codewords [count] = huff_code;
c.codeword_lengths[count] = len;
values [count] = symbol;
}
}
//1004
function compute_codewords(c, len, n, values)
{
var i=int_,k=int_,m=0;//int_
var available=new Array(32);//uint32
memset(available, 0, 0, 32);//sizeof(available)
// find the first entry
for (k=0; k < n; ++k) if (len[k] < NO_CODE) break;
if (k == n) { assert(c.sorted_entries == 0); return true; }
// add to the list
add_entry(c, 0, k, m++, len[k], values);
// add all available leaves
for (i=1; i <= len[k]; ++i)
available[i] = (1 << (32-i))>>>0;
// note that the above code treats the first case specially,
// but it's really the same as the following code, so they
// could probably be combined (except the initial code is 0,
// and I use 0 in available[] to mean 'empty')
for (i=k+1; i < n; ++i) {
var res=uint32;
var z = len[i], y=int_;//int_
if (z == NO_CODE) continue;
// find lowest available leaf (should always be earliest,
// which is what the specification calls for)
// note that this property, and the fact we can never have
// more than one free leaf at a given level, isn't totally
// trivial to prove, but it seems true and the assert never
// fires, so!
while (z > 0 && !available[z]) --z;
if (z == 0) { assert(0); return false; }
res = available[z];
available[z] = 0;
add_entry(c, bit_reverse(res), i, m++, len[i], values);
// propogate availability up the tree
if (z != len[i]) {
for (y=len[i]; y > z; --y) {
assert(available[y] == 0);
available[y] = res + ((1 << (32-y)))>>>0;
}
}
}
return true;
}
// accelerated huffman table allows fast O(1) match of all symbols
// of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH
//1050
function compute_accelerated_huffman(c)
{
var i=int_, len=int_;
for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i)
c.fast_huffman[i] = -1;
len = c.sparse ? c.sorted_entries : c.entries;
//#ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
if (len > 32767) len = 32767; // largest possible value we can encode!
//#endif
for (i=0; i < len; ++i) {
if (c.codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {
var z = c.sparse ? bit_reverse(c.sorted_codewords[i]) : c.codewords[i];//uint32
// set table entries for all bit combinations in the higher bits
while (z < FAST_HUFFMAN_TABLE_SIZE) {
c.fast_huffman[z] = i;
z += (1 << c.codeword_lengths[i])>>>0;
}
}
}
}
//1072
function uint32_compare(p, q)
{
var x = p;//uint32 = * (uint32 *)
var y = q;//uint32 = * (uint32 *)
return x < y ? -1 : x > y;
}
//1079
function include_in_sort(c, len)
{
if (c.sparse) { assert(len != NO_CODE); return true; }
if (len == NO_CODE) return false;
if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return true;
return false;
}
// if the fast table above doesn't work, we want to binary
// search them... need to reverse the bits
//1089
function compute_sorted_huffman(c, lengths, values)
{
var i=int_, len=int_;
// build a list of all the entries
// OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN.
// this is kind of a frivolous optimization--I don't see any performance improvement,
// but it's like 4 extra lines of code, so.
if (!c.sparse) {
var k = 0;//int_
for (i=0; i < c.entries; ++i)
if (include_in_sort(c, lengths[i]))
c.sorted_codewords[k++] = bit_reverse(c.codewords[i]);
assert(k == c.sorted_entries);
} else {
for (i=0; i < c.sorted_entries; ++i)
c.sorted_codewords[i] = bit_reverse(c.codewords[i]);
}
c.sorted_codewords.sort(uint32_compare);//qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare);
c.sorted_codewords[c.sorted_entries] = 0xffffffff;
len = c.sparse ? c.sorted_entries : c.entries;
// now we need to indicate how they correspond; we could either
// #1: sort a different data structure that says who they correspond to
// #2: for each sorted entry, search the original list to find who corresponds
// #3: for each original entry, find the sorted entry
// #1 requires extra storage, #2 is slow, #3 can use binary search!
for (i=0; i < len; ++i) {
var huff_len = c.sparse ? lengths[values[i]] : lengths[i];//int_
if (include_in_sort(c,huff_len)) {
var code = bit_reverse(c.codewords[i]);//uint32
var x=0, n=c.sorted_entries;//int_
while (n > 1) {
// invariant: sc[x] <= code < sc[x+n]
var m = x + (n >>> 1);//int_
if (c.sorted_codewords[m] <= code) {
x = m;
n -= (n>>>1);
} else {
n >>>= 1;
}
}
assert(c.sorted_codewords[x] == code);
if (c.sparse) {
c.sorted_values[x] = values[i];
c.codeword_lengths[x] = huff_len;
} else {
c.sorted_values[x] = i;
}
}
}
}
//1142
// only run while parsing the header (3 times)
function vorbis_validate(data)
{
var vorbis = new Array( 118, 111, 114, 98, 105, 115 );//new Array( 'v', 'o', 'r', 'b', 'i', 's' );//static uint8
return memcmp(data, vorbis, 6) == 0;
}
// called from setup only, once per code book
// (formula implied by specification)
//1151
function lookup1_values(entries, dim)
{
var r = Math.floor(Math.exp(Math.log(entries) / dim));//int_ = (int_) (float_) (float_)
if (Math.floor(Math.pow(r+1, dim)) <= entries) //(int_) (float_) // (int) cast for MinGW warning;
++r; // floor() to avoid _ftol() when non-CRT
assert(Math.pow( r+1, dim) > entries);//(float_)
assert(Math.floor(Math.pow(r, dim)) <= entries); //(int_) (float) // (int),floor() as above
return r;
}
// called twice per file
//1162
function compute_twiddle_factors(n, A, B, C)
{
var n4 = n >>> 2, n8 = n >>> 3;//int_
var k=int_,k2=int_;
for (k=k2=0; k < n4; ++k,k2+=2) {
A[k2 ] = Math.cos(4*k*M_PI/n);//(float_)
A[k2+1] = -Math.sin(4*k*M_PI/n);//(float_)
B[k2 ] = Math.cos((k2+1)*M_PI/n/2) * 0.5;//f //(float_)
B[k2+1] = Math.sin((k2+1)*M_PI/n/2) * 0.5;//f //(float_)
}
for (k=k2=0; k < n8; ++k,k2+=2) {
C[k2 ] = Math.cos(2*(k2+1)*M_PI/n);//(float_)
C[k2+1] = -Math.sin(2*(k2+1)*M_PI/n);//(float_)
}
}
//1179
function compute_window(n, window_)
{
var n2 = n >> 1, i=int_;//int_
for (i=0; i < n2; ++i)
window_[i] = Math.sin(0.5 * M_PI * square(Math.sin((i - 0 + 0.5) / n2 * 0.5 * M_PI)));//(float) (float)
}
//1186
function compute_bitreverse(n, rev)
{
var ld = ilog(n) - 1;//int_ // ilog is off-by-one from normal definitions
var i=int_, n8 = n >>> 3;//int_
for (i=0; i < n8; ++i)
rev[i] = (bit_reverse(i) >>> (32-ld+3)) << 2;
}
//1194
function init_blocksize(f, b, n)
{
var n2 = n >>> 1, n4 = n >>> 2, n8 = n >>> 3;//int_
f.A[b] = new Array(n2);//(float *) setup_malloc(f, sizeof(float) * n2);
f.B[b] = new Array(n2);//(float *) setup_malloc(f, sizeof(float) * n2);
f.C[b] = new Array(n4);//(float *) setup_malloc(f, sizeof(float) * n4);
if (!f.A[b] || !f.B[b] || !f.C[b]) return error(f, VORBIS_outofmem);
compute_twiddle_factors(n, f.A[b], f.B[b], f.C[b]);
f.window_[b] = new Array(n2);//(float *) setup_malloc(f, sizeof(float) * n2);
if (!f.window_[b]) return error(f, VORBIS_outofmem);
compute_window(n, f.window_[b]);
f.bit_reverse[b] = new Array(n8);//(uint16 *) setup_malloc(f, sizeof(uint16) * n8);
if (!f.bit_reverse[b]) return error(f, VORBIS_outofmem);
compute_bitreverse(n, f.bit_reverse[b]);
return true;
}
//1211
function neighbors(x, n, plow, phigh)
{
var low = -1;//int_
var high = 65536;//int_
var i;//int_
for (i=0; i < n; ++i) {
if (x[i] > low && x[i] < x[n]) { plow[0] = i; low = x[i]; }
if (x[i] < high && x[i] > x[n]) { phigh[0] = i; high = x[i]; }
}
}
// this has been repurposed so y is now the original index instead of y
//1223
var Point = function()
{
this.x=52428,this.y=52428;//uint16,uint16
};
//1228
function point_compare(p, q)
{
var a = p;//Point * = (Point *)
var b = q;//Point * = (Point *)
return a.x < b.x ? -1 : a.x > b.x;
}
//
/////////////////////// END LEAF SETUP FUNCTIONS //////////////////////////
//#if defined(STB_VORBIS_NO_STDIO)
// #define USE_MEMORY(z) TRUE
//#else
function USE_MEMORY(z) { return ((z).stream) }
//#endif
//1245
function get8(z)
{
if (USE_MEMORY(z)) {
if (z.stream_off >= z.stream_end_off) { z.eof = true; return 0; }
return z.stream_off++;//*
}
//#ifndef STB_VORBIS_NO_STDIO
{
var c = fgetc(z.f);//int_
if (c == EOF) { z.eof = true; return 0; }
return c;
}
//#endif
}
//1261
function get32(f)
{
var x=uint32;
x = get8(f);
x += get8(f) << 8;
x += get8(f) << 16;
x += get8(f) << 24;
return x;
}
//1271
function getn(z, data, n)
{
if (USE_MEMORY(z)) {
if (z.stream_off+n > z.stream_end_off) { z.eof = 1; return 0; }
memcpy(data, 0, z.stream, z.stream_off, n);
z.stream_off += n;
return 1;
}
//#ifndef STB_VORBIS_NO_STDIO
if (fread(data, n, 1, z.f) == 1)
return 1;
else {
z.eof = 1;
return 0;
}
//#endif
}
//1290
function skip(z, n)
{
if (USE_MEMORY(z)) {
z.stream_off += n;
if (z.stream_off >= z.stream_end_off) z.eof = 1;
return;
}
//#ifndef STB_VORBIS_NO_STDIO
{
var x = ftell(z.f);//long
fseek(z.f, x+n, SEEK_SET);
}
//#endif
}
//1339
function capture_pattern(f)
{