forked from jamesward/JSAMF
-
Notifications
You must be signed in to change notification settings - Fork 1
/
amf.js
executable file
·1580 lines (1385 loc) · 46.4 KB
/
amf.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
/**
* @file amf.js
* @desc An AMF library in JavaScript
* @auth James Ward, Torleif West
*
* Copyright (c) 2010
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY JAMES WARD ''AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JAMES WARD OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of James Ward.
*
*/
// fallback swf bridge for IE (js file still encodes the data)
var swfBridgeLocation = "js/bridge.swf";
//
var swfBridgeRemotingProxyList = new Array();
function decodeAMF(data)
{
var bytes = new amf.ByteArray(data, amf.Endian.BIG);
//console.log(dumpHex(bytes));
var version = bytes.readUnsignedShort();
bytes.objectEncoding = amf.ObjectEncoding.AMF0;
var response = new amf.AMFPacket();
// Headers
var headerCount = bytes.readUnsignedShort();
for (var h = 0; h < headerCount; h++)
{
var headerName = bytes.readUTF();
var mustUnderstand = bytes.readBoolean();
bytes.readInt(); // read header length
// Handle AVM+ type marker
if (version == amf.ObjectEncoding.AMF3)
{
var typeMarker = bytes.readByte();
if (typeMarker == amf.Amf0Types.kAvmPlusObjectType)
bytes.objectEncoding = amf.ObjectEncoding.AMF3;
else
bytes.pos = bytes.pos - 1;
}
var headerValue = bytes.readObject();
var header = new amf.AMFHeader(headerName, mustUnderstand, headerValue);
response.headers.push(header);
// Reset to AMF0 for next header
bytes.objectEncoding = amf.ObjectEncoding.AMF0;
}
// Message Bodies
var messageCount = bytes.readUnsignedShort();
for (var m = 0; m < messageCount; m++)
{
var targetURI = bytes.readUTF();
var responseURI = bytes.readUTF();
bytes.readInt(); // Consume message body length...
// Handle AVM+ type marker
if (version == amf.ObjectEncoding.AMF3)
{
var typeMarker = bytes.readByte();
if (typeMarker == amf.Amf0Types.kAvmPlusObjectType)
bytes.objectEncoding = amf.ObjectEncoding.AMF3;
else
bytes.pos = bytes.pos - 1;
}
var messageBody = bytes.readObject();
var message = new amf.AMFMessage(targetURI, responseURI, messageBody);
response.messages.push(message);
bytes.objectEncoding = amf.ObjectEncoding.AMF0;
}
return response;
}
function ErrorClass() {
}
// remoting proxy type
function RemotingProxy(url, service, encoding)
{
this.url = url;
this.service = service;
this.encoding = encoding;
this.handles = new Array();
this.response_number = 0;
// vars used if you're using the swf gateway
this.flashgateway;
this.flashgatewayloaded;
this.flashgatewaybuffer = new Array();
// either AMF 0 or 3.
if (encoding != amf.ObjectEncoding.AMF0 &&
encoding != amf.ObjectEncoding.AMF3) {
this.encoding = amf.ObjectEncoding.AMF0;
}
// if you're on IE, we need to add the flash file to send the binary data.
if('undefined' != typeof(window.ActiveXObject)) {
var bridge = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" \
id="ExternalFlashInterface" width="400" height="400"\
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">\
<param name="movie" value="'+swfBridgeLocation+'" />\
<param name="allowScriptAccess" value="sameDomain" />\
<embed src="'+swfBridgeLocation+'"\
width="400" height="400" name="ExternalFlashInterface" align="middle"\
play="true" loop="false" quality="high" allowScriptAccess="sameDomain"\
type="application/x-shockwave-flash"\
pluginspage="http://www.macromedia.com/go/getflashplayer">\
</embed>\
</object>';
document.body.innerHTML += bridge;
if (navigator.appName.indexOf("Microsoft") != -1) {
this.flashgateway = window["ExternalFlashInterface"];
} else {
this.flashgateway = document["ExternalFlashInterface"];
}
this.flashgatewayloaded = false;
swfBridgeRemotingProxyList.push (this);
}
registerClassAlias("flex.messaging.messages.ErrorMessage", ErrorClass);
}
// object that gets created upon a remote request
RemotingProxy.RequestHandle = function (req, resultFunction, statusFunction, n)
{
this.req = req;
this.resultFunction = resultFunction;
this.statusFunction = statusFunction;
this.response_number = n;
}
// callback after receiving data
RemotingProxy.prototype._callBackFunction = function (handle) {
if (handle.req.readyState == 4) {
if (handle.req.status == 200) {
var o = decodeAMF(handle.req.responseText);
// ErrorClass
console.log(o.messages);
handle.resultFunction(o.messages[0].body);
} else {
handle.statusFunction('ERROR: AJAX request status = ' + handle.req.status);
}
}
}
//
function FlashCallbackSuccess( str ) {
try {
var mstr = unescape(str);
var o = decodeAMF(mstr);
}
catch (e) {
txt="There was an error on this page.\n\n";
txt+="Error description: " + e.description + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
//handle.resultFunction(o.messages[0].body);;
return false;
}
// if the flash file has failed to send message, we just ignore it
function FlashCallbackFailure( str ){
alert(str);
return false;
}
// once the flash player has loaded, you can now send any buffered messages
// note this may fail under multiple RemotingProxy's
function FlashInterfaceLoaded() {
var remotingProxy = swfBridgeRemotingProxyList.pop();
remotingProxy.flashgatewayloaded = true;
for (var i = 0; i < remotingProxy.flashgatewaybuffer.length; i ++) {
var b = remotingProxy.flashgatewaybuffer[i];
remotingProxy.flashgateway.sendData(b[0], b[1]);
}
remotingProxy.flashgatewaybuffer = new Array(); //erase buffer
}
// adds a remoting function to this handler
RemotingProxy.prototype.addHandler = function(
handlestr,
resultFunction,
statusFunction)
{
// create handle function
this[handlestr] = function () {
var headers = new Array();
var handle;
// begin to write the request for data
var bytes = new amf.ByteArray('', amf.Endian.BIG);
bytes.writeInt(this.encoding, 16);// protocol version 0 or 3.
bytes.writeInt(headers.length, 16);// headers count
bytes.writeInt(arguments.length, 16);// messages count
for (var h in headers) {
// @TODO test headers
bytes.writeUTF(h.name); //header name
bytes.writeInt(0, 8);// must understand
bytes.writeInt(headers.length, 32);// write header data length
bytes.writeInt(1, 8); // type of header (????)
}
// write the body
bytes.writeUTF(this.service +'.'+ handlestr);// target
bytes.writeUTF("/"+(this.response_number++));// responce
bytes.writeInt(0x0e, 32);// byte-length of message ( -1 for unknowen)
this.handles[this.response_number] = this[handlestr];
// write body args as an array.
var args = new Array();
for( var i = 0; i < arguments.length; i++ ) args.push(arguments[i]);
bytes.writeObject(args);
// string to send
var str = bytes.data;
if (window.XMLHttpRequest && 'undefined' == typeof(window.ActiveXObject)) {
req = new XMLHttpRequest();
//XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
req.overrideMimeType('text/plain; charset=x-user-defined');
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-amf");
handle = new RemotingProxy.RequestHandle(req, resultFunction,statusFunction, this.response_number);
req.onreadystatechange = function () {
RemotingProxy.prototype._callBackFunction(handle);
};
}
// the browser must support binary Http requests
if('undefined' != typeof(req) && req.sendAsBinary) { // firefox (w3 standard)
req.sendAsBinary(str);
} else if ('undefined' != typeof(BlobBuilder)) { // chrome
//var bb = new BlobBuilder();
//bb.append(str);
req.send(bytes.blobData.getBlob());
}else if (window.ActiveXObject) { // IE
// gateway not ready, buffer the requests
if(!this.flashgatewayloaded) {
var ar = new Array(url, escape(str));
this.flashgatewaybuffer.push(ar);
return;
}
try {
this.flashgateway.sendData(url, escape(str));
} catch (e) {
// @TODO have a cry here
alert('failed to send binary data ' + e.description);
}
} else {
// Safari does not convert binary to string. Let's hope if gets here, so does your browser
req.send(str);
}
}
}
function dumpHex(bytes)
{
var s = "";
var i = 0;
var chunk = [];
while (i < bytes.length)
{
if (((i % 16) == 0) && (i != 0))
{
s += writeChunk(chunk, 16) + "\n";
chunk = [];
}
chunk.push(bytes.readByte());
i++;
}
s += writeChunk(chunk, 16);
bytes.pos = 0;
return s;
}
function writeChunk(chunk, width)
{
var s = "";
for (var i = 0; i < chunk.length; i++)
{
if (((i % 4) == 0) && (i != 0))
{
s += " ";
}
var b = chunk[i];
var ss = b.toString(16) + " ";
if (ss.length == 2)
{
ss = "0" + ss;
}
s += ss;
}
for (var i = 0; i < (width - chunk.length); i++)
{
s += " ";
}
var j = Math.floor((width - chunk.length) / 4);
for (var i = 0; i < j; i++)
{
s += " ";
}
s += " ";
for (var i = 0; i < chunk.length; i++)
{
var b = chunk[i];
if ((b <= 126) && (b > 32))
{
var ss = String.fromCharCode(b);
s += ss;
}
else
{
s += ".";
}
}
return s;
}
// 'static' data definitions
if ('undefined' == typeof(amf))
{
amf = {
registeredClasses: [],
RegisteredClass: function (name, funt) {
this.name = name;
this.initFunct = funt;
}
};
}
// dynamic objects get made here
function registerClassAlias(VOname, classVO)
{
amf.registeredClasses.push(new amf.RegisteredClass(VOname, classVO));
}
// src http://ejohn.org/blog/simple-javascript-inheritance/
(function()
{
var initializing = false;
// Base Class implementation
this.Class = function()
{
};
// Create a new Class that inherits from this class
Class.extend = function(prop)
{
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop)
{
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn)
{
return function()
{
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
function Class()
{
// All construction is actually done in the init method
if (!initializing && this.init)
this.init.apply(this, arguments);
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.constructor = Class;
// And make this class extendable
Class.extend = arguments.callee;
return Class;
};
})();
//Enum for big or little endian.
amf.Endian = {
BIG: 0,
LITTLE: 1
};
// AMF encoding type
amf.ObjectEncoding = {
AMF0: 0,
AMF3: 3
};
// AMF data types
amf.Amf0Types = {
kNumberType: 0,
kBooleanType: 1,
kStringType: 2,
kObjectType: 3,
kMovieClipType: 4,
kNullType: 5,
kUndefinedType: 6,
kReferenceType: 7,
kECMAArrayType: 8,
kObjectEndType: 9,
kStrictArrayType: 10,
kDateType: 11,
kLongStringType: 12,
kUnsupportedType: 13,
kRecordsetType: 14,
kXMLObjectType: 15,
kTypedObjectType: 16,
kAvmPlusObjectType: 17
};
// AMF3 datatypes
amf.Amf3Types = {
kUndefinedType: 0,
kNullType: 1,
kFalseType: 2,
kTrueType: 3,
kIntegerType: 4,
kDoubleType: 5,
kStringType: 6,
kXMLType: 7,
kDateType: 8,
kArrayType: 9,
kObjectType: 10,
kAvmPlusXmlType: 11,
kByteArrayType: 12
};
// each AMF message has a target
amf.AMFMessage = Class.extend({
targetURL: "",
responseURI: "",
body: {},
init: function(targetURL, responseURI, body)
{
this.targetURL = targetURL;
this.responseURI = responseURI;
this.body = body;
}
});
amf.AMFPacket = Class.extend({
version: 0,
headers: [],
messages: [],
init: function(version)
{
this.version = (version !== undefined) ? version : 0;
this.headers = new Array();
this.messages = new Array();
}
});
amf.AMFHeader = Class.extend({
name: "",
mustUnderstand: false,
data: {},
init: function(name, mustUnderstand, data)
{
this.name = name;
this.mustUnderstand = (mustUnderstand != undefined) ? mustUnderstand : false;
this.data = data;
}
});
// AMF 0 objects
function Integer()
{
this.data = 0;
}
Integer.prototype.set = function(i)
{
this.data = parseInt(i);
}
/**
* Attempt to imitate AS3's ByteArray as very high-performance javascript.
* I aliased the functions to have shorter names, like ReadUInt32 as well as ReadUnsignedInt.
* I used some code from http://fhtr.blogspot.com/2009/12/3d-models-and-parsing-binary-data-with.html
* to kick-start it, but I added optimizations and support both big and little endian.
* Note that you cannot change the endianness after construction.
* @extends Class
*/
amf.ByteArray = Class.extend({
data: '' ,
blobData: null,
length: 0 ,
pos: 0 ,
pow: Math.pow ,
endian: amf.Endian.BIG ,
TWOeN23: Math.pow(2, -23) ,
TWOeN52: Math.pow(2, -52) ,
objectEncoding: amf.ObjectEncoding.AMF0 ,
stringTable: [] ,
objectTable: [] ,
traitTable: []
/** @constructor */
,
init: function(data, endian)
{
this.data = (data !== undefined) ? data : '';
if (endian !== undefined) this.endian = endian;
this.length = data.length;
this.stringTable = new Array();
this.objectTable = new Array();
this.traitTable = new Array();
if('undefined' != typeof(BlobBuilder)) {
this.blobData = new BlobBuilder();
}
// Cache the function pointers based on endianness.
// This avoids doing an if-statement in every function call.
var funcExt = (endian == amf.Endian.BIG) ? 'BE' : 'LE';
var funcs = [ 'readInt16', 'readUInt30','readUInt32',
'readUInt16', 'readFloat32', 'readFloat64'];
for (var func in funcs)
{
this[funcs[func]] = this[funcs[func] + funcExt];
}
// Add redundant members that match actionscript for compatibility
var funcMap = {
readByte: 'readByte',
readUnsignedInt: 'readUInt32',
readFloat: 'readFloat32',
readDouble: 'readDouble',
readShort: 'readInt16',
readUnsignedShort: 'readUnsignedShort',
readBoolean: 'readBool',
readInt: 'readInt',
writeInt:'writeInt',
writeUTF:'writeUTF',
//writeAMF3Int:'writeAMF3Int',
readString: 'readString',
hexTob64: 'hexTob64',
base64ToHex: 'base64ToHex',
writeInt29:'writeInt29'
};
for (var func in funcMap)
{
this[func] = this[funcMap[func]];
}
},
writeInt29:function (i) {
i = parseInt(i);
i &= 0x1fffffff;
if(i < 0x80)
{
this.data += i;
}
else if(i < 0x4000)
{
this.data += (i >> 7 & 0x7f | 0x80) + (i & 0x7f);
}
else if(i < 0x200000)
{
this.data += (i >> 14 & 0x7f | 0x80) + (i >> 7 & 0x7f | 0x80) + (i & 0x7f);
}
else
{
this.data += (i >> 22 & 0x7f | 0x80) + (i >> 15 & 0x7f | 0x80) +
(i >> 8 & 0x7f | 0x80) + (i & 0xff);
}
},
readByte: function()
{
var cc = this.data.charCodeAt(this.pos++);
return (cc & 0xFF);
},
readByteRaw: function()
{
return this.data[this.pos++];
},
writeByte: function(byt)
{
// @TODO: make a blob builder equivalent
if('undefined' != typeof(BlobBuilder)) {
}
this.data = this.data + String.fromCharCode(byt & 0xFF);
},
readBool: function()
{
return (this.data.charCodeAt(this.pos++) & 0xFF) ? true : false;
},
readUInt30BE: function()
{
var ch1 = this.readByte();
var ch2 = this.readByte();
var ch3 = this.readByte();
var ch4 = this.readByte();
if (ch1 >= 64)
return undefined;
return ch4 | (ch3 << 8) | (ch2 << 16) | (ch1 << 24);
},
readUInt32BE: function()
{
var data = this.data, pos = (this.pos += 4) - 4;
return ((data.charCodeAt(pos) & 0xFF) << 24) |
((data.charCodeAt(++pos) & 0xFF) << 16) |
((data.charCodeAt(++pos) & 0xFF) << 8) |
(data.charCodeAt(++pos) & 0xFF);
}
,
readInt: function()
{
if(this.endian == amf.Endian.BIG) {
return this.readInt32BE();
} else {
return this.readInt32LE();
}
}
,
readInt32BE: function()
{
var data = this.data, pos = (this.pos += 4) - 4;
var x = ((data.charCodeAt(pos) & 0xFF) << 24) |
((data.charCodeAt(++pos) & 0xFF) << 16) |
((data.charCodeAt(++pos) & 0xFF) << 8) |
(data.charCodeAt(++pos) & 0xFF);
return (x >= 2147483648) ? x - 4294967296 : x;
}
,
readUInt16BE: function()
{
var data = this.data, pos = (this.pos += 2) - 2;
return ((data.charCodeAt(pos) & 0xFF) << 8) |
(data.charCodeAt(++pos) & 0xFF);
}
,
readInt16BE: function()
{
var data = this.data, pos = (this.pos += 2) - 2;
var x = ((data.charCodeAt(pos) & 0xFF) << 8) |
(data.charCodeAt(++pos) & 0xFF);
return (x >= 32768) ? x - 65536 : x;
},
readDouble: function (){
if(this.endian == amf.Endian.BIG) {
return this.readFloat64BE();
} else {
return this.readFloat64LE();
}
},
readUnsignedShort: function (){
if(this.endian == amf.Endian.BIG) {
return this.readInt16BE();
} else {
return this.readInt16LE();
}
} ,
readFloat32LE: function()
{
var b4 = this.readByte(),
b3 = this.readByte(),
b2 = this.readByte();
b1 = this.readByte();
var sign = 1 - ((b1 >> 7) << 1); // sign = bit 0
var exp = (((b1 << 1) & 0xFF) | (b2 >> 7)) - 127; // exponent = bits 1..8
var sig = ((b2 & 0x7F) << 16) | (b3 << 8) | b4; // significand = bits 9..31
if (sig == 0 && exp == -127)
return 0.0;
return sign * (1 + this.TWOeN23 * sig) * this.pow(2, exp);
} ,
readFloat32BE: function()
{
var b1 = this.readByte(),
b2 = this.readByte(),
b3 = this.readByte(),
b4 = this.readByte();
var sign = 1 - ((b1 >> 7) << 1); // sign = bit 0
var exp = (((b1 << 1) & 0xFF) | (b2 >> 7)) - 127; // exponent = bits 1..8
var sig = ((b2 & 0x7F) << 16) | (b3 << 8) | b4; // significand = bits 9..31
if (sig == 0 && exp == -127)
return 0.0;
return sign * (1 + this.TWOeN23 * sig) * this.pow(2, exp);
} ,
readFloat64BE: function()
{
var b1 = this.readByte();
var b2 = this.readByte();
var b3 = this.readByte();
var b4 = this.readByte();
var b5 = this.readByte();
var b6 = this.readByte();
var b7 = this.readByte();
var b8 = this.readByte();
var sign = 1 - ((b1 >> 7) << 1); // sign = bit 0
var exp = (((b1 << 4) & 0x7FF) | (b2 >> 4)) - 1023; // exponent = bits 1..11
// This crazy toString() stuff works around the fact that js ints are
// only 32 bits and signed, giving us 31 bits to work with
var sig = (((b2 & 0xF) << 16) | (b3 << 8) | b4).toString(2) +
((b5 >> 7) ? '1' : '0') +
(((b5 & 0x7F) << 24) | (b6 << 16) | (b7 << 8) | b8).toString(2); // significand = bits 12..63
sig = parseInt(sig, 2);
if (sig == 0 && exp == -1023)
return 0.0;
return sign*(1.0 + this.TWOeN52*sig)*this.pow(2, exp);
}
,
readUInt29: function()
{
// @TODO fix in IE. After reading a byte array, this function sometimes
// returns the wrong value
var value;
// Each byte must be treated as unsigned
var b = this.readByte();
if (b < 128)
return b;
value = (b & 0x7F) << 7;
b = this.readByte() & 0xFF;
if (b < 128)
return (value | b);
value = (value | (b & 0x7F)) << 7;
b = this.readByte() & 0xFF;
if (b < 128)
return (value | b);
value = (value | (b & 0x7F)) << 8;
b = this.readByte() & 0xFF;
return (value | b);
}
,
readUInt30LE: function()
{
var ch1 = readByte();
var ch2 = readByte();
var ch3 = readByte();
var ch4 = readByte();
if (ch4 >= 64)
return undefined;
return ch1 | (ch2 << 8) | (ch3 << 16) | (ch4 << 24);
}
,
readUInt32LE: function()
{
var data = this.data, pos = (this.pos += 4);
return ((data.charCodeAt(--pos) & 0xFF) << 24) |
((data.charCodeAt(--pos) & 0xFF) << 16) |
((data.charCodeAt(--pos) & 0xFF) << 8) |
(data.charCodeAt(--pos) & 0xFF);
}
,
readInt32LE: function()
{
var data = this.data, pos = (this.pos += 4);
var x = ((data.charCodeAt(--pos) & 0xFF) << 24) |
((data.charCodeAt(--pos) & 0xFF) << 16) |
((data.charCodeAt(--pos) & 0xFF) << 8) |
(data.charCodeAt(--pos) & 0xFF);
return (x >= 2147483648) ? x - 4294967296 : x;
}
,
readUInt16LE: function()
{
var data = this.data, pos = (this.pos += 2);
return ((data.charCodeAt(--pos) & 0xFF) << 8) |
(data.charCodeAt(--pos) & 0xFF);
}
,
readInt16LE: function()
{
var data = this.data, pos = (this.pos += 2);
var x = ((data.charCodeAt(--pos) & 0xFF) << 8) |
(data.charCodeAt(--pos) & 0xFF);
return (x >= 32768) ? x - 65536 : x;
}
,
readFloat64LE: function()
{
var b1 = this.readByte(),
b2 = this.readByte(),
b3 = this.readByte(),
b4 = this.readByte(),
b5 = this.readByte(),
b6 = this.readByte(),
b7 = this.readByte(),
b8 = this.readByte();
var sign = 1 - ((b1 >> 7) << 1); // sign = bit 0
var exp = (((b1 << 4) & 0x7FF) | (b2 >> 4)) - 1023; // exponent = bits 1..11
// This crazy toString() stuff works around the fact that js ints are
// only 32 bits and signed, giving us 31 bits to work with
var sig = (((b2 & 0xF) << 16) | (b3 << 8) | b4).toString(2) +
((b5 >> 7) ? '1' : '0') +
(((b5 & 0x7F) << 24) | (b6 << 16) | (b7 << 8) | b8).toString(2); // significand = bits 12..63
sig = parseInt(sig, 2);
if (sig == 0 && exp == -1023)
return 0.0;
return sign * (1.0 + this.TWOeN52 * sig) * this.pow(2, exp);
}
,
readDate: function()
{
var time_ms = this.readDouble();
var tz_min = this.readUInt16BE();
return new Date(time_ms + tz_min * 60 * 1000);
}
,
readString: function(len)
{
var str = "";
while (len > 0)
{
str += String.fromCharCode(this.readByte());
len--;
}
return str;
}
,
readUTF: function()
{
var s = this.readString(this.readUnsignedShort());
return s;
}
,
readLongUTF: function()
{
return this.readString(this.readUInt30());
}
,
stringToXML: function(str)
{
var xmlDoc;
if (window.DOMParser)
{
var parser = new DOMParser();
xmlDoc = parser.parseFromString(str, "text/xml");
}
else // IE
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(stc);
}
return xmlDoc;
}
,
readXML: function()
{
var xml = this.readLongUTF();
return this.stringToXML(xml);
}
,
readStringAMF3: function()
{
var ref = this.readUInt29();
if ((ref & 1) == 0) {// This is a reference
return this.stringTable[(ref >> 1)];
}
var len = (ref >> 1);
if (0 == len)
return "";
var str = this.readString(len);
this.stringTable.push(str);
return str;
}
,
readTraits: function(ref)
{
var traitInfo = new Object();
traitInfo.properties = new Array();
if ((ref & 3) == 1)
return this.traitTable[(ref >> 2)];
traitInfo.externalizable = ((ref & 4) == 4);
traitInfo.dynamic = ((ref & 8) == 8);
traitInfo.count = (ref >> 4);
traitInfo.className = this.readStringAMF3();