forked from phoboslab/jsmpeg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsmpg.js
executable file
·2665 lines (2314 loc) · 96.3 KB
/
jsmpg.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
(function (window) {
'use strict';
// jsmpeg by Dominic Szablewski - phoboslab.org, github.com/phoboslab
//
// Consider this to be under MIT license. It's largely based an an Open Source
// Decoder for Java under GPL, while I looked at another Decoder from Nokia
// (under no particular license?) for certain aspects.
// I'm not sure if this work is "derivative" enough to have a different license
// but then again, who still cares about MPEG1?
//
// Based on "Java MPEG-1 Video Decoder and Player" by Korandi Zoltan:
// http://sourceforge.net/projects/javampeg1video/
//
// Inspired by "MPEG Decoder in Java ME" by Nokia:
// http://www.developer.nokia.com/Community/Wiki/MPEG_decoder_in_Java_ME+
// Modified to support socket.io-based streaming.
var requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var jsmpeg = window.jsmpeg = function (url, opts) {
opts = opts || {};
this.progressive = (opts.progressive !== false);
this.benchmark = !!opts.benchmark;
this.canvas = opts.canvas || document.createElement('canvas');
this.autoplay = !!opts.autoplay;
this.wantsToPlay = this.autoplay;
this.loop = !!opts.loop;
this.seekable = !!opts.seekable;
this.externalLoadCallback = opts.onload || null;
this.externalDecodeCallback = opts.ondecodeframe || null;
this.externalFinishedCallback = opts.onfinished || null;
this.customIntraQuantMatrix = new Uint8Array(64);
this.customNonIntraQuantMatrix = new Uint8Array(64);
this.blockData = new Int32Array(64);
this.zeroBlockData = new Int32Array(64);
this.fillArray(this.zeroBlockData, 0);
// Custom additions for socket io and stats support.
this.useSocketIO = opts.useSocketIO || false;
this.framesRendered = 0;
// use WebGL for YCbCrToRGBA conversion if possible (much faster)
if (!opts.forceCanvas2D && this.initWebGL()) {
this.renderFrame = this.renderFrameGL;
} else {
this.canvasContext = this.canvas.getContext('2d');
this.renderFrame = this.renderFrame2D;
}
if (url instanceof WebSocket) {
this.client = url;
this.client.onopen = this.initSocketClient.bind(this);
}
else if (url instanceof io.Socket) {
this.client = url;
this.client.on('connect', this.initSocketClient.bind(this));
}
else {
this.load(url);
}
};
// ----------------------------------------------------------------------------
// Streaming over WebSockets or SocketIO
jsmpeg.prototype.waitForIntraFrame = true;
jsmpeg.prototype.socketBufferSize = 512 * 1024; // 512kb each
jsmpeg.prototype.initSocketClient = function (ev) {
this.buffer = new BitReader(new ArrayBuffer(this.socketBufferSize));
this.nextPictureBuffer = new BitReader(new ArrayBuffer(this.socketBufferSize));
this.nextPictureBuffer.writePos = 0;
this.nextPictureBuffer.chunkBegin = 0;
this.nextPictureBuffer.lastWriteBeforeWrap = 0;
if (!this.useSocketIO) {
this.client.binaryType = 'arraybuffer';
this.client.onmessage = this.receiveSocketMessage.bind(this);
} else {
this.client.on('stream', function (bytes) {
this.receiveSocketMessage(bytes);
}.bind(this));
}
};
jsmpeg.prototype.decodeSocketHeader = function (data) {
// Custom header sent to all newly connected clients when streaming
// over websockets:
// struct { char magic[4] = 'jsmp'; unsigned short width, height; };
if (
data[0] === SOCKET_MAGIC_BYTES.charCodeAt(0) &&
data[1] === SOCKET_MAGIC_BYTES.charCodeAt(1) &&
data[2] === SOCKET_MAGIC_BYTES.charCodeAt(2) &&
data[3] === SOCKET_MAGIC_BYTES.charCodeAt(3)
) {
this.width = (data[4] * 256 + data[5]);
this.height = (data[6] * 256 + data[7]);
this.initBuffers();
}
};
jsmpeg.prototype.receiveSocketMessage = function (event) {
if (this.useSocketIO) {
var messageData = new Uint8Array(event);
} else {
var messageData = new Uint8Array(event.data);
}
if (!this.sequenceStarted) {
this.decodeSocketHeader(messageData);
}
var current = this.buffer;
var next = this.nextPictureBuffer;
if (next.writePos + messageData.length > next.length) {
next.lastWriteBeforeWrap = next.writePos;
next.writePos = 0;
next.index = 0;
}
next.bytes.set(messageData, next.writePos);
next.writePos += messageData.length;
var startCode = 0;
while (true) {
startCode = next.findNextMPEGStartCode();
if (
startCode === BitReader.NOT_FOUND ||
((next.index >> 3) > next.writePos)
) {
// We reached the end with no picture found yet; move back a few bytes
// in case we are at the beginning of a start code and exit.
next.index = Math.max((next.writePos - 3), 0) << 3;
return;
}
else if (startCode === START_PICTURE) {
break;
}
}
// If we are still here, we found the next picture start code!
// Skip picture decoding until we find the first intra frame?
if (this.waitForIntraFrame) {
next.advance(10); // skip temporalReference
if (next.getBits(3) === PICTURE_TYPE_I) {
this.waitForIntraFrame = false;
next.chunkBegin = (next.index - 13) >> 3;
}
return;
}
// Last picture hasn't been decoded yet? Decode now but skip output
// before scheduling the next one
if (!this.currentPictureDecoded) {
this.decodePicture(DECODE_SKIP_OUTPUT);
}
// Copy the picture chunk over to 'this.buffer' and schedule decoding.
var chunkEnd = ((next.index) >> 3);
if (chunkEnd > next.chunkBegin) {
// Just copy the current picture chunk
current.bytes.set(next.bytes.subarray(next.chunkBegin, chunkEnd));
current.writePos = chunkEnd - next.chunkBegin;
}
else {
// We wrapped the nextPictureBuffer around, so we have to copy the last part
// till the end, as well as from 0 to the current writePos
current.bytes.set(next.bytes.subarray(next.chunkBegin, next.lastWriteBeforeWrap));
var written = next.lastWriteBeforeWrap - next.chunkBegin;
current.bytes.set(next.bytes.subarray(0, chunkEnd), written);
current.writePos = chunkEnd + written;
}
current.index = 0;
next.chunkBegin = chunkEnd;
// Decode!
this.currentPictureDecoded = false;
requestAnimFrame(this.scheduleDecoding.bind(this), this.canvas);
};
jsmpeg.prototype.scheduleDecoding = function () {
this.decodePicture();
this.currentPictureDecoded = true;
};
// ----------------------------------------------------------------------------
// Recording from WebSockets
jsmpeg.prototype.isRecording = false;
jsmpeg.prototype.recorderWaitForIntraFrame = false;
jsmpeg.prototype.recordedFrames = 0;
jsmpeg.prototype.recordedSize = 0;
jsmpeg.prototype.didStartRecordingCallback = null;
jsmpeg.prototype.recordBuffers = [];
jsmpeg.prototype.canRecord = function () {
return (this.client && this.client.readyState === this.client.OPEN);
};
jsmpeg.prototype.startRecording = function (callback) {
if (!this.canRecord()) {
return;
}
// Discard old buffers and set for recording
this.discardRecordBuffers();
this.isRecording = true;
this.recorderWaitForIntraFrame = true;
this.didStartRecordingCallback = callback || null;
this.recordedFrames = 0;
this.recordedSize = 0;
// Fudge a simple Sequence Header for the MPEG file
// 3 bytes width & height, 12 bits each
var wh1 = (this.width >> 4),
wh2 = ((this.width & 0xf) << 4) | (this.height >> 8),
wh3 = (this.height & 0xff);
this.recordBuffers.push(new Uint8Array([
0x00, 0x00, 0x01, 0xb3, // Sequence Start Code
wh1, wh2, wh3, // Width & height
0x13, // aspect ratio & framerate
0xff, 0xff, 0xe1, 0x58, // Meh. Bitrate and other boring stuff
0x00, 0x00, 0x01, 0xb8, 0x00, 0x08, 0x00, // GOP
0x00, 0x00, 0x00, 0x01, 0x00 // First Picture Start Code
]));
};
jsmpeg.prototype.recordFrameFromCurrentBuffer = function () {
if (!this.isRecording) {
return;
}
if (this.recorderWaitForIntraFrame) {
// Not an intra frame? Exit.
if (this.pictureCodingType !== PICTURE_TYPE_I) {
return;
}
// Start recording!
this.recorderWaitForIntraFrame = false;
if (this.didStartRecordingCallback) {
this.didStartRecordingCallback(this);
}
}
this.recordedFrames++;
this.recordedSize += this.buffer.writePos;
// Copy the actual subrange for the current picture into a new Buffer
this.recordBuffers.push(new Uint8Array(this.buffer.bytes.subarray(0, this.buffer.writePos)));
};
jsmpeg.prototype.discardRecordBuffers = function () {
this.recordBuffers = [];
this.recordedFrames = 0;
};
jsmpeg.prototype.stopRecording = function () {
var blob = new Blob(this.recordBuffers, {type: 'video/mpeg'});
this.discardRecordBuffers();
this.isRecording = false;
return blob;
};
// ----------------------------------------------------------------------------
// Loading via Ajax
jsmpeg.prototype.intraFrames = [];
jsmpeg.prototype.currentFrame = -1;
jsmpeg.prototype.currentTime = 0;
jsmpeg.prototype.frameCount = 0;
jsmpeg.prototype.duration = 0;
jsmpeg.prototype.progressiveMinSize = 128 * 1024;
jsmpeg.prototype.fetchReaderPump = function (reader) {
var that = this;
reader.read().then(function (result) {
that.fetchReaderReceive(reader, result);
});
};
jsmpeg.prototype.fetchReaderReceive = function (reader, result) {
if (result.done) {
if (this.seekable) {
var currentBufferPos = this.buffer.index;
this.collectIntraFrames();
this.buffer.index = currentBufferPos;
}
this.duration = this.frameCount / this.pictureRate;
this.lastFrameIndex = this.buffer.writePos << 3;
return;
}
this.buffer.bytes.set(result.value, this.buffer.writePos);
this.buffer.writePos += result.value.byteLength;
// Find the last picture start code - we have to be careful not trying
// to decode any frames that aren't fully loaded yet.
this.lastFrameIndex = this.findLastPictureStartCode();
// Initialize the sequence headers and start playback if we have enough data
// (at least 128kb)
if (!this.sequenceStarted && this.buffer.writePos >= this.progressiveMinSize) {
this.findStartCode(START_SEQUENCE);
this.firstSequenceHeader = this.buffer.index;
this.decodeSequenceHeader();
// Load the first frame
this.nextFrame();
if (this.autoplay) {
this.play();
}
if (this.externalLoadCallback) {
this.externalLoadCallback(this);
}
}
// If the player starved previously, restart playback now
else if (this.sequenceStarted && this.wantsToPlay && !this.playing) {
this.play();
}
// Not enough data to start playback yet - show loading progress
else if (!this.sequenceStarted) {
var status = {loaded: this.buffer.writePos, total: this.progressiveMinSize};
if (this.gl) {
this.updateLoaderGL(status);
}
else {
this.updateLoader2D(status);
}
}
this.fetchReaderPump(reader);
};
jsmpeg.prototype.findLastPictureStartCode = function () {
var bufferBytes = this.buffer.bytes;
for (var i = this.buffer.writePos; i > 3; i--) {
if (
bufferBytes[i] == START_PICTURE &&
bufferBytes[i - 1] == 0x01 &&
bufferBytes[i - 2] == 0x00 &&
bufferBytes[i - 3] == 0x00
) {
return (i - 3) << 3;
}
}
return 0;
};
jsmpeg.prototype.load = function (url) {
this.url = url;
var that = this;
if (
this.progressive &&
window.fetch &&
window.ReadableByteStream
) {
var reqHeaders = new Headers();
reqHeaders.append('Content-Type', 'video/mpeg');
fetch(url, {headers: reqHeaders}).then(function (res) {
var contentLength = res.headers.get('Content-Length');
var reader = res.body.getReader();
that.buffer = new BitReader(new ArrayBuffer(contentLength));
that.buffer.writePos = 0;
that.fetchReaderPump(reader);
});
}
else {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === request.DONE && request.status === 200) {
that.loadCallback(request.response);
}
};
request.onprogress = this.gl
? this.updateLoaderGL.bind(this)
: this.updateLoader2D.bind(this);
request.open('GET', url);
request.responseType = 'arraybuffer';
request.send();
}
};
jsmpeg.prototype.updateLoader2D = function (ev) {
var
p = ev.loaded / ev.total,
w = this.canvas.width,
h = this.canvas.height,
ctx = this.canvasContext;
ctx.fillStyle = '#222';
ctx.fillRect(0, 0, w, h);
ctx.fillStyle = '#fff';
ctx.fillRect(0, h - h * p, w, h * p);
};
jsmpeg.prototype.updateLoaderGL = function (ev) {
var gl = this.gl;
gl.uniform1f(gl.getUniformLocation(this.loadingProgram, 'loaded'), (ev.loaded / ev.total));
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
};
jsmpeg.prototype.loadCallback = function (file) {
this.buffer = new BitReader(file);
if (this.seekable) {
this.collectIntraFrames();
this.buffer.index = 0;
}
this.findStartCode(START_SEQUENCE);
this.firstSequenceHeader = this.buffer.index;
this.decodeSequenceHeader();
// Calculate the duration. This only works if the video is seekable and we have a frame count
this.duration = this.frameCount / this.pictureRate;
// Load the first frame
this.nextFrame();
if (this.autoplay) {
this.play();
}
if (this.externalLoadCallback) {
this.externalLoadCallback(this);
}
};
jsmpeg.prototype.collectIntraFrames = function () {
// Loop through the whole buffer and collect all intraFrames to build our seek index.
// We also keep track of total frame count here
var frame;
for (frame = 0; this.findStartCode(START_PICTURE) !== BitReader.NOT_FOUND; frame++) {
// Check if the found picture is an intra frame and remember the position
this.buffer.advance(10); // skip temporalReference
if (this.buffer.getBits(3) === PICTURE_TYPE_I) {
// Remember index 13 bits back, before temporalReference and picture type
this.intraFrames.push({frame: frame, index: this.buffer.index - 13});
}
}
this.frameCount = frame;
};
jsmpeg.prototype.seekToFrame = function (seekFrame, seekExact) {
if (seekFrame < 0 || seekFrame >= this.frameCount || !this.intraFrames.length) {
return false;
}
// Find the last intra frame before or equal to seek frame
var target = null;
for (var i = 0; i < this.intraFrames.length && this.intraFrames[i].frame <= seekFrame; i++) {
target = this.intraFrames[i];
}
this.buffer.index = target.index;
this.currentFrame = target.frame - 1;
// If we're seeking to the exact frame, we may have to decode some more frames before
// the one we want
if (seekExact) {
for (var frame = target.frame; frame < seekFrame; frame++) {
this.decodePicture(DECODE_SKIP_OUTPUT);
this.findStartCode(START_PICTURE);
}
this.currentFrame = seekFrame - 1;
}
// Decode and display the picture we have seeked to
this.decodePicture();
return true;
};
jsmpeg.prototype.seekToTime = function (time, seekExact) {
this.seekToFrame((time * this.pictureRate) | 0, seekExact);
};
jsmpeg.prototype.play = function () {
if (this.playing) {
return;
}
this.targetTime = this.now();
this.playing = true;
this.wantsToPlay = true;
this.scheduleNextFrame();
};
jsmpeg.prototype.pause = function () {
this.playing = false;
this.wantsToPlay = false;
};
jsmpeg.prototype.stop = function () {
this.currentFrame = -1;
if (this.buffer) {
this.buffer.index = this.firstSequenceHeader;
}
this.playing = false;
if (this.client) {
this.client.close();
this.client = null;
}
this.wantsToPlay = false;
};
// ----------------------------------------------------------------------------
// Utilities
jsmpeg.prototype.readCode = function (codeTable) {
var state = 0;
do {
state = codeTable[state + this.buffer.getBits(1)];
} while (state >= 0 && codeTable[state] !== 0);
return codeTable[state + 2];
};
jsmpeg.prototype.findStartCode = function (code) {
var current = 0;
while (true) {
current = this.buffer.findNextMPEGStartCode();
if (current === code || current === BitReader.NOT_FOUND) {
return current;
}
}
return BitReader.NOT_FOUND;
};
jsmpeg.prototype.fillArray = function (a, value) {
for (var i = 0, length = a.length; i < length; i++) {
a[i] = value;
}
};
// ----------------------------------------------------------------------------
// Sequence Layer
jsmpeg.prototype.pictureRate = 30;
jsmpeg.prototype.lateTime = 0;
jsmpeg.prototype.firstSequenceHeader = 0;
jsmpeg.prototype.targetTime = 0;
jsmpeg.prototype.benchmark = false;
jsmpeg.prototype.benchFrame = 0;
jsmpeg.prototype.benchDecodeTimes = 0;
jsmpeg.prototype.benchAvgFrameTime = 0;
jsmpeg.prototype.now = function () {
return window.performance
? window.performance.now()
: Date.now();
};
jsmpeg.prototype.nextFrame = function () {
if (!this.buffer) {
return;
}
var frameStart = this.now();
while (true) {
var code = this.buffer.findNextMPEGStartCode();
if (code === START_SEQUENCE) {
this.decodeSequenceHeader();
}
else if (code === START_PICTURE) {
if (this.progressive && this.buffer.index >= this.lastFrameIndex) {
// Starved
this.playing = false;
return;
}
if (this.playing) {
this.scheduleNextFrame();
}
this.decodePicture();
this.benchDecodeTimes += this.now() - frameStart;
return this.canvas;
}
else if (code === BitReader.NOT_FOUND) {
this.stop(); // Jump back to the beginning
if (this.externalFinishedCallback) {
this.externalFinishedCallback(this);
}
// Only loop if we found a sequence header
if (this.loop && this.sequenceStarted) {
this.play();
}
return null;
}
else {
// ignore (GROUP, USER_DATA, EXTENSION, SLICES...)
}
}
};
jsmpeg.prototype.scheduleNextFrame = function () {
this.lateTime = this.now() - this.targetTime;
var wait = Math.max(0, (1000 / this.pictureRate) - this.lateTime);
this.targetTime = this.now() + wait;
if (this.benchmark) {
this.benchFrame++;
if (this.benchFrame >= 120) {
this.benchAvgFrameTime = this.benchDecodeTimes / this.benchFrame;
this.benchFrame = 0;
this.benchDecodeTimes = 0;
if (window.console) {
console.log('Average time per frame:', this.benchAvgFrameTime, 'ms');
}
}
setTimeout(this.nextFrame.bind(this), 0);
}
else if (wait < 18) {
this.scheduleAnimation();
}
else {
setTimeout(this.scheduleAnimation.bind(this), wait);
}
};
jsmpeg.prototype.scheduleAnimation = function () {
requestAnimFrame(this.nextFrame.bind(this), this.canvas);
};
jsmpeg.prototype.decodeSequenceHeader = function () {
this.width = this.buffer.getBits(12);
this.height = this.buffer.getBits(12);
this.buffer.advance(4); // skip pixel aspect ratio
this.pictureRate = PICTURE_RATE[this.buffer.getBits(4)];
this.buffer.advance(18 + 1 + 10 + 1); // skip bitRate, marker, bufferSize and constrained bit
this.initBuffers();
var i;
if (this.buffer.getBits(1)) { // load custom intra quant matrix?
for (i = 0; i < 64; i++) {
this.customIntraQuantMatrix[ZIG_ZAG[i]] = this.buffer.getBits(8);
}
this.intraQuantMatrix = this.customIntraQuantMatrix;
}
if (this.buffer.getBits(1)) { // load custom non intra quant matrix?
for (i = 0; i < 64; i++) {
this.customNonIntraQuantMatrix[ZIG_ZAG[i]] = this.buffer.getBits(8);
}
this.nonIntraQuantMatrix = this.customNonIntraQuantMatrix;
}
};
jsmpeg.prototype.initBuffers = function () {
this.intraQuantMatrix = DEFAULT_INTRA_QUANT_MATRIX;
this.nonIntraQuantMatrix = DEFAULT_NON_INTRA_QUANT_MATRIX;
this.mbWidth = (this.width + 15) >> 4;
this.mbHeight = (this.height + 15) >> 4;
this.mbSize = this.mbWidth * this.mbHeight;
this.codedWidth = this.mbWidth << 4;
this.codedHeight = this.mbHeight << 4;
this.codedSize = this.codedWidth * this.codedHeight;
this.halfWidth = this.mbWidth << 3;
this.halfHeight = this.mbHeight << 3;
this.quarterSize = this.codedSize >> 2;
// Sequence already started? Don't allocate buffers again
if (this.sequenceStarted) {
return;
}
this.sequenceStarted = true;
// Manually clamp values when writing macroblocks for shitty browsers
// that don't support Uint8ClampedArray
var MaybeClampedUint8Array = window.Uint8ClampedArray || window.Uint8Array;
if (!window.Uint8ClampedArray) {
this.copyBlockToDestination = this.copyBlockToDestinationClamp;
this.addBlockToDestination = this.addBlockToDestinationClamp;
}
// Allocated buffers and resize the canvas
this.currentY = new MaybeClampedUint8Array(this.codedSize);
this.currentY32 = new Uint32Array(this.currentY.buffer);
this.currentCr = new MaybeClampedUint8Array(this.codedSize >> 2);
this.currentCr32 = new Uint32Array(this.currentCr.buffer);
this.currentCb = new MaybeClampedUint8Array(this.codedSize >> 2);
this.currentCb32 = new Uint32Array(this.currentCb.buffer);
this.forwardY = new MaybeClampedUint8Array(this.codedSize);
this.forwardY32 = new Uint32Array(this.forwardY.buffer);
this.forwardCr = new MaybeClampedUint8Array(this.codedSize >> 2);
this.forwardCr32 = new Uint32Array(this.forwardCr.buffer);
this.forwardCb = new MaybeClampedUint8Array(this.codedSize >> 2);
this.forwardCb32 = new Uint32Array(this.forwardCb.buffer);
this.canvas.width = this.width;
this.canvas.height = this.height;
if (this.gl) {
this.gl.useProgram(this.program);
this.gl.viewport(0, 0, this.width, this.height);
}
else {
this.currentRGBA = this.canvasContext.getImageData(0, 0, this.width, this.height);
this.fillArray(this.currentRGBA.data, 255);
}
};
// ----------------------------------------------------------------------------
// Picture Layer
jsmpeg.prototype.currentY = null;
jsmpeg.prototype.currentCr = null;
jsmpeg.prototype.currentCb = null;
jsmpeg.prototype.currentRGBA = null;
jsmpeg.prototype.pictureCodingType = 0;
// Buffers for motion compensation
jsmpeg.prototype.forwardY = null;
jsmpeg.prototype.forwardCr = null;
jsmpeg.prototype.forwardCb = null;
jsmpeg.prototype.fullPelForward = false;
jsmpeg.prototype.forwardFCode = 0;
jsmpeg.prototype.forwardRSize = 0;
jsmpeg.prototype.forwardF = 0;
jsmpeg.prototype.decodePicture = function (skipOutput) {
this.currentFrame++;
this.currentTime = this.currentFrame / this.pictureRate;
this.buffer.advance(10); // skip temporalReference
this.pictureCodingType = this.buffer.getBits(3);
this.buffer.advance(16); // skip vbv_delay
// Skip B and D frames or unknown coding type
if (this.pictureCodingType <= 0 || this.pictureCodingType >= PICTURE_TYPE_B) {
return;
}
// full_pel_forward, forward_f_code
if (this.pictureCodingType === PICTURE_TYPE_P) {
this.fullPelForward = this.buffer.getBits(1);
this.forwardFCode = this.buffer.getBits(3);
if (this.forwardFCode === 0) {
// Ignore picture with zero forward_f_code
return;
}
this.forwardRSize = this.forwardFCode - 1;
this.forwardF = 1 << this.forwardRSize;
}
var code = 0;
do {
code = this.buffer.findNextMPEGStartCode();
} while (code === START_EXTENSION || code === START_USER_DATA);
while (code >= START_SLICE_FIRST && code <= START_SLICE_LAST) {
this.decodeSlice((code & 0x000000FF));
code = this.buffer.findNextMPEGStartCode();
}
// We found the next start code; rewind 32bits and let the main loop handle it.
this.buffer.rewind(32);
// Record this frame, if the recorder wants it
this.recordFrameFromCurrentBuffer();
if (skipOutput !== DECODE_SKIP_OUTPUT) {
this.renderFrame();
if (this.externalDecodeCallback) {
this.externalDecodeCallback(this, this.canvas);
}
}
// If this is a reference picutre then rotate the prediction pointers
if (this.pictureCodingType === PICTURE_TYPE_I || this.pictureCodingType === PICTURE_TYPE_P) {
var
tmpY = this.forwardY,
tmpY32 = this.forwardY32,
tmpCr = this.forwardCr,
tmpCr32 = this.forwardCr32,
tmpCb = this.forwardCb,
tmpCb32 = this.forwardCb32;
this.forwardY = this.currentY;
this.forwardY32 = this.currentY32;
this.forwardCr = this.currentCr;
this.forwardCr32 = this.currentCr32;
this.forwardCb = this.currentCb;
this.forwardCb32 = this.currentCb32;
this.currentY = tmpY;
this.currentY32 = tmpY32;
this.currentCr = tmpCr;
this.currentCr32 = tmpCr32;
this.currentCb = tmpCb;
this.currentCb32 = tmpCb32;
}
};
jsmpeg.prototype.YCbCrToRGBA = function () {
var pY = this.currentY;
var pCb = this.currentCb;
var pCr = this.currentCr;
var pRGBA = this.currentRGBA.data;
// Chroma values are the same for each block of 4 pixels, so we proccess
// 2 lines at a time, 2 neighboring pixels each.
// I wish we could use 32bit writes to the RGBA buffer instead of writing
// each byte separately, but we need the automatic clamping of the RGBA
// buffer.
var yIndex1 = 0;
var yIndex2 = this.codedWidth;
var yNext2Lines = this.codedWidth + (this.codedWidth - this.width);
var cIndex = 0;
var cNextLine = this.halfWidth - (this.width >> 1);
var rgbaIndex1 = 0;
var rgbaIndex2 = this.width * 4;
var rgbaNext2Lines = this.width * 4;
var cols = this.width >> 1;
var rows = this.height >> 1;
var cb, cr, r, g, b;
for (var row = 0; row < rows; row++) {
for (var col = 0; col < cols; col++) {
cb = pCb[cIndex];
cr = pCr[cIndex];
cIndex++;
r = (cr + ((cr * 103) >> 8)) - 179;
g = ((cb * 88) >> 8) - 44 + ((cr * 183) >> 8) - 91;
b = (cb + ((cb * 198) >> 8)) - 227;
// Line 1
var y1 = pY[yIndex1++];
var y2 = pY[yIndex1++];
pRGBA[rgbaIndex1] = y1 + r;
pRGBA[rgbaIndex1 + 1] = y1 - g;
pRGBA[rgbaIndex1 + 2] = y1 + b;
pRGBA[rgbaIndex1 + 4] = y2 + r;
pRGBA[rgbaIndex1 + 5] = y2 - g;
pRGBA[rgbaIndex1 + 6] = y2 + b;
rgbaIndex1 += 8;
// Line 2
var y3 = pY[yIndex2++];
var y4 = pY[yIndex2++];
pRGBA[rgbaIndex2] = y3 + r;
pRGBA[rgbaIndex2 + 1] = y3 - g;
pRGBA[rgbaIndex2 + 2] = y3 + b;
pRGBA[rgbaIndex2 + 4] = y4 + r;
pRGBA[rgbaIndex2 + 5] = y4 - g;
pRGBA[rgbaIndex2 + 6] = y4 + b;
rgbaIndex2 += 8;
}
yIndex1 += yNext2Lines;
yIndex2 += yNext2Lines;
rgbaIndex1 += rgbaNext2Lines;
rgbaIndex2 += rgbaNext2Lines;
cIndex += cNextLine;
}
};
jsmpeg.prototype.renderFrame2D = function () {
this.YCbCrToRGBA();
this.canvasContext.putImageData(this.currentRGBA, 0, 0);
this.framesRendered += 1;
};
// ----------------------------------------------------------------------------
// Accelerated WebGL YCbCrToRGBA conversion
jsmpeg.prototype.gl = null;
jsmpeg.prototype.program = null;
jsmpeg.prototype.YTexture = null;
jsmpeg.prototype.CBTexture = null;
jsmpeg.prototype.CRTexture = null;
jsmpeg.prototype.createTexture = function (index, name) {
var gl = this.gl;
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.uniform1i(gl.getUniformLocation(this.program, name), index);
return texture;
};
jsmpeg.prototype.compileShader = function (type, source) {
var gl = this.gl;
var shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
throw new Error(gl.getShaderInfoLog(shader));
}
return shader;
};
jsmpeg.prototype.initWebGL = function () {
var gl;
// attempt to get a webgl context
try {
gl = this.gl = this.canvas.getContext('webgl') || this.canvas.getContext('experimental-webgl');
} catch (e) {
return false;
}
if (!gl) {
return false;
}
// init buffers
this.buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]), gl.STATIC_DRAW);
// The main YCbCrToRGBA Shader
this.program = gl.createProgram();
gl.attachShader(this.program, this.compileShader(gl.VERTEX_SHADER, SHADER_VERTEX_IDENTITY));
gl.attachShader(this.program, this.compileShader(gl.FRAGMENT_SHADER, SHADER_FRAGMENT_YCBCRTORGBA));
gl.linkProgram(this.program);
if (!gl.getProgramParameter(this.program, gl.LINK_STATUS)) {
throw new Error(gl.getProgramInfoLog(this.program));
}
gl.useProgram(this.program);