-
Notifications
You must be signed in to change notification settings - Fork 0
/
player.js
670 lines (600 loc) · 15.3 KB
/
player.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
/**
* Constructor for an analogue of the TimeRanges class
* returned by various HTMLMediaElement properties
*
* Pass an array of two-element arrays, each containing a start and end time.
*/
function OgvJsTimeRanges(ranges) {
Object.defineProperty(this, 'length', {
get: function getLength() {
return ranges.length;
}
});
this.start = function(i) {
return ranges[i][0];
};
this.end = function(i) {
return ranges[i][1];
}
return this;
}
function OgvJsPlayer(canvas) {
var ctx = canvas.getContext('2d');
var ended = false;
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame;
if (!requestAnimationFrame) {
throw new Error("No requestAnimationFrame available!");
}
var getTimestamp;
if (window.performance === undefined) {
getTimestamp = function() {
return Date.now();
}
} else {
getTimestamp = function() {
return window.performance.now();
}
}
var self = this;
var codec, audioFeeder;
var stream, nextProcessingTimer, paused = true;
var muted = false;
var framesPlayed = 0;
// Benchmark data, exposed via getPlaybackStats()
var framesProcessed = 0, // frames
demuxingTime = 0, // seconds
videoDecodingTime = 0, // ms
audioDecodingTime = 0, // ms
bufferTime = 0, // ms
colorTime = 0, // ms
drawingTime = 0; // ms
function stopVideo() {
// kill the previous video if any
paused = true; // ?
ended = true;
continueVideo = null;
if (stream) {
stream.abort();
stream = null;
}
if (codec) {
codec.destroy();
codec = null;
}
if (audioFeeder) {
audioFeeder.close();
audioFeeder = null;
}
if (nextProcessingTimer) {
cancelAnimationFrame(nextProcessingTimer);
nextProcessingTimer = null;
}
}
function togglePauseVideo() {
if (self.paused) {
self.play();
} else {
self.pause();
}
}
var continueVideo = null;
var lastFrameTime = getTimestamp(),
frameEndTimestamp = 0.0,
frameScheduled = false,
imageData = null,
yCbCrBuffer = null;
function prepareFrame() {
yCbCrBuffer = codec.dequeueFrame();
frameEndTimestamp = yCbCrBuffer.timestamp;
}
function drawFrame() {
var start, delta;
start = getTimestamp();
convertYCbCr(yCbCrBuffer, imageData.data);
delta = getTimestamp() - start;
colorTime += delta;
lastFrameDecodeTime += delta;
start = getTimestamp();
ctx.putImageData(imageData,
0, 0,
videoInfo.picX, videoInfo.picY,
videoInfo.picWidth, videoInfo.picHeight);
delta = getTimestamp() - start;
lastFrameDecodeTime += delta;
drawingTime += delta;
framesProcessed++;
framesPlayed++;
}
var lastFrameDecodeTime = 0.0;
var targetFrameTime;
function doDrawFrame() {
prepareFrame();
drawFrame();
if (self.onframecallback) {
self.onframecallback(lastFrameDecodeTime);
lastFrameDecodeTime = 0;
}
}
/**
* In IE, pushing data to the Flash shim is expensive.
* Combine multiple small Vorbis packet outputs into
* larger buffers so we don't have to make as many calls.
*/
function joinAudioBuffers(buffers) {
if (buffers.length == 1) {
return buffers[0];
}
var sampleCount = 0,
channelCount = buffers[0].length,
i,
c,
out = [];
for (i = 0; i < buffers.length; i++) {
sampleCount += buffers[i][0].length;
}
for (c = 0; c < channelCount; c++) {
var channelOut = new Float32Array(sampleCount);
var position = 0;
for (i = 0; i < buffers.length; i++) {
var channelIn = buffers[i][c];
channelOut.set(channelIn, position);
position += channelIn.length;
}
out.push(channelOut);
}
return out;
}
function doProcessing() {
nextProcessingTimer = null;
var audioBuffers = [];
function queueAudio() {
if (audioBuffers.length > 0) {
var start = getTimestamp();
audioFeeder.bufferData(joinAudioBuffers(audioBuffers));
var delta = (getTimestamp() - start);
lastFrameDecodeTime += delta;
bufferTime += delta;
if (!codec.hasVideo) {
framesProcessed++; // pretend!
if (self.onframecallback) {
self.onframecallback(lastFrameDecodeTime);
lastFrameDecodeTime = 0;
}
}
}
}
var audioBufferedDuration = 0,
decodedSamples = 0;
if (codec.hasAudio) {
var audioState = audioFeeder.getPlaybackState();
audioBufferedDuration = (audioState.samplesQueued / audioFeeder.targetRate) * 1000;
}
var n = 0;
while (true) {
n++;
if (n > 100) {
throw new Error("Got stuck in the loop!");
}
// Process until we run out of data or
// completely decode a video frame...
var currentTime = getTimestamp();
var start = getTimestamp();
var hasAudio = codec.hasAudio,
hasVideo = codec.hasVideo;
more = codec.process();
if (hasAudio != codec.hasAudio || hasVideo != codec.hasVideo) {
// we just fell over from headers into content; reinit
pingProcessing();
targetFrameTime = getTimestamp() + 1000.0 / fps
return;
}
var delta = (getTimestamp() - start);
lastFrameDecodeTime += delta;
demuxingTime += delta;
if (!more) {
queueAudio();
if (stream) {
// Ran out of buffered input
stream.readBytes();
} else {
// Ran out of stream!
var finalDelay = 0;
if (hasAudio) {
if (self.durationHint) {
finalDelay = self.durationHint * 1000 - audioState.playbackPosition;
} else {
// This doesn't seem to be enough with Flash audio shim.
// Not quite sure why.
finalDelay = audioBufferedDuration;
}
}
console.log('End of stream reached in ' + finalDelay + ' ms.');
setTimeout(function() {
stopVideo();
}, finalDelay);
}
return;
}
if ((hasAudio || hasVideo) && !(codec.audioReady || codec.frameReady)) {
// Have to process some more pages to find data. Continue the loop.
continue;
}
// THIS IS THE HACK TO MAKE IT AUTOPLAY!!!!
hasAudio = false;
if (hasAudio) {
// Drive on the audio clock!
var fudgeDelta = 0.1,
//readyForAudio = audioState.samplesQueued <= (audioFeeder.bufferSize * 2),
//readyForFrame = (audioState.playbackPosition >= frameEndTimestamp);
readyForAudio = audioState.samplesQueued <= (audioFeeder.bufferSize * 2),
frameDelay = (frameEndTimestamp - audioState.playbackPosition) * 1000,
readyForFrame = (frameDelay <= fudgeDelta);
// THIS IS THE HACK TO MAKE IT AUTOPLAY!!!!
// readyForFrame = true;
// console.log(readyForAudio);
if (codec.audioReady && readyForAudio) {
var start = getTimestamp();
var ok = codec.decodeAudio();
var delta = (getTimestamp() - start);
lastFrameDecodeTime += delta;
audioDecodingTime += delta;
var start = getTimestamp();
if (ok) {
var buffer = codec.dequeueAudio();
//audioFeeder.bufferData(buffer);
audioBuffers.push(buffer);
audioBufferedDuration += (buffer[0].length / audioInfo.rate) * 1000;
decodedSamples += buffer[0].length;
}
}
if (codec.frameReady && readyForFrame) {
var start = getTimestamp();
var ok = codec.decodeFrame();
var delta = (getTimestamp() - start);
lastFrameDecodeTime += delta;
videoDecodingTime += delta;
if (ok) {
doDrawFrame();
} else {
// Bad packet or something.
// console.log('Bad video packet or something');
}
targetFrameTime = currentTime + 1000.0 / fps;
}
// Check in when all audio runs out
var bufferDuration = (audioFeeder.bufferSize / audioFeeder.targetRate) * 1000;
var nextDelays = [];
if (audioBufferedDuration <= bufferDuration * 2) {
// NEED MOAR BUFFERS
} else {
// Check in when the audio buffer runs low again...
nextDelays.push(bufferDuration);
if (hasVideo) {
// Check in when the next frame is due
nextDelays.push(frameDelay);
}
}
//console.log(n, audioState.playbackPosition, frameEndTimestamp, audioBufferedDuration, bufferDuration, frameDelay, '[' + nextDelays.join("/") + ']');
var nextDelay = Math.min.apply(Math, nextDelays);
if (nextDelays.length > 0) {
queueAudio();
pingProcessing(nextDelay);
return;
}
} else if (hasVideo) {
// Video-only: drive on the video clock
if (codec.frameReady && getTimestamp() >= targetFrameTime) {
// it's time to draw
var start = getTimestamp();
var ok = codec.decodeFrame();
var delta = (getTimestamp() - start);
lastFrameDecodeTime += delta;
videoDecodingTime += delta;
if (ok) {
doDrawFrame();
targetFrameTime += 1000.0 / fps;
pingProcessing();
} else {
// console.log('Bad video packet or something');
pingProcessing(targetFrameTime - getTimestamp());
}
} else {
// check in again soon!
pingProcessing(targetFrameTime - getTimestamp());
}
return;
} else {
// Ok we're just waiting for more input.
// console.log('Still waiting for headers...');
}
}
}
function pingProcessing(delay) {
if (delay === undefined) {
delay = 0;
}
if (nextProcessingTimer) {
// already scheduled
return;
}
// console.log('delaying for ' + delay);
//nextProcessingTimer = setTimeout(doProcessing, delay);
nextProcessingTimer = requestAnimationFrame(doProcessing);
}
var fps = 60;
var videoInfo,
audioInfo,
imageData;
function playVideo() {
paused = false;
var options = {};
// Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/536.30.1 (KHTML, like Gecko) Version/6.0.5 Safari/536.30.1
if (navigator.userAgent.match(/Version\/6\.0\.[0-9a-z.]+ Safari/)) {
// Something may be wrong with the JIT compiler in Safari 6.0;
// when we decode Vorbis with the debug console closed it falls
// into 100% CPU loop and never exits.
//
// Blacklist audio decoding for this browser.
//
// Known working in Safari 6.1 and 7.
options.audio = false;
console.log('Audio disabled due to bug on Safari 6.0');
}
framesProcessed = 0;
demuxingTime = 0;
videoDecodingTime = 0;
audioDecodingTime = 0;
bufferTime = 0;
drawingTime = 0;
codec = new OgvJs(options);
codec.oninitvideo = function(info) {
videoInfo = info;
fps = info.fps;
canvas.width = info.picWidth;
canvas.height = info.picHeight;
imageData = ctx.createImageData(info.frameWidth, info.frameHeight);
if (self.oninitvideo) {
self.oninitvideo(info);
}
}
codec.oninitaudio = function(info) {
audioInfo = info;
if (self.oninitaudio) {
self.oninitaudio(info);
}
audioFeeder.init(info.channels, info.rate);
}
continueVideo = pingProcessing;
audioFeeder = new AudioFeeder(2, 44100);
if (muted) {
audioFeeder.mute();
}
audioFeeder.waitUntilReady(function(feeder) {
// Start reading!
if (started) {
stream.readBytes();
} else {
onstart = function() {
stream.readBytes();
};
}
});
}
var started = false;
var onstart;
/**
* HTMLMediaElement load method
*/
this.load = function() {
// console.log('1');
if (stream) {
// already loaded.
return;
}
var that = this;
started = false;
var options = {
url: this.src,
bufferSize: 65536,
onstart: function() {
// Fire off the read/decode/draw loop...
started = true;
if (onstart) {
onstart();
}
},
onread: function(data) {
// Pass chunk into the codec's buffer
codec.receiveInput(data);
// Continue the read/decode/draw loop...
pingProcessing();
},
ondone: function() {
console.log("reading done.");
stream = undefined;
that.load();
// Let the read/decode/draw loop know we're out!
pingProcessing();
},
onerror: function(err) {
console.log("reading error: " + err);
}
}
stream = new StreamFile(options);
paused = true;
};
/**
* HTMLMediaElement canPlayType method
*/
this.canPlayType = function(type) {
// @todo: implement better parsing
if (type === 'audio/ogg; codecs="vorbis"') {
return 'probably';
} else if (type.match(/^audio\/ogg\b/)) {
return 'maybe';
} else if (type === 'video/ogg; codecs="theora"') {
return 'probably';
} else if (type === 'video/ogg; codecs="theora,vorbis"') {
return 'probably';
} else if (type.match(/^video\/ogg\b/)) {
return 'maybe';
} else {
return '';
}
};
/**
* HTMLMediaElement play method
*/
this.play = function() {
if (!stream) {
this.load();
}
if (paused) {
paused = false;
if (continueVideo) {
continueVideo();
} else {
playVideo();
}
}
};
/**
* custom onframecallback, takes frame decode time in ms
*/
this.onframecallback = null;
/**
* custom getPlaybackStats method
*/
this.getPlaybackStats = function() {
return {
framesProcessed: framesProcessed,
demuxingTime: demuxingTime,
videoDecodingTime: videoDecodingTime,
audioDecodingTime: audioDecodingTime,
bufferTime: bufferTime,
colorTime: colorTime,
drawingTime: drawingTime
};
};
this.resetPlaybackStats = function() {
framesProcessed = 0;
demuxingTime = 0;
videoDecodingTime = 0;
audioDecodingTime = 0;
bufferTime = 0;
colorTime = 0;
drawingTime = 0;
};
/**
* HTMLMediaElement pause method
*/
this.pause = function() {
if (!stream) {
console.log('initializing stream');
paused = true;
this.load();
} else if (!paused) {
console.log('pausing');
cancelAnimationFrame(nextProcessingTimer);
nextProcessingTimer = null;
paused = true;
}
};
/**
* custom 'stop' method
*/
this.stop = function() {
stopVideo();
};
/**
* HTMLMediaElement src property
*/
this.src = "";
/**
*/
Object.defineProperty(this, "buffered", {
get: function getBuffered() {
var estimatedBufferTime;
if (stream && this.byteLengthHint && this.durationHint) {
estimatedBufferTime = (stream.bytesBuffered / this.byteLengthHint) * this.durationHint;
} else {
estimatedBufferTime = 0;
}
return new OgvJsTimeRanges([[0, estimatedBufferTime]]);
}
});
/**
* HTMLMediaElement currentTime property
*/
Object.defineProperty(this, "currentTime", {
get: function getCurrentTime() {
if (codec && codec.hasAudio) {
return audioFeeder.getPlaybackState().playbackPosition;
} else if (codec && codec.hasVideo) {
return framesPlayed * videoInfo.fps;
} else {
return 0;
}
}
});
/**
* custom durationHint property
*/
this.durationHint = null;
/**
* custom byteLengthHint property
*/
this.byteLengthHint = null;
/**
* HTMLMediaElement duration property
*/
Object.defineProperty(this, "duration", {
get: function getDuration() {
if (codec && (codec.hasAudio || codec.hasVideo)) {
if (this.durationHint) {
return this.durationHint;
} else {
// @todo figure out how to estimate it
return Infinity;
}
} else {
return NaN;
}
}
});
/**
* HTMLMediaElement paused property
*/
Object.defineProperty(this, "paused", {
get: function getPaused() {
return paused;
}
});
/**
* HTMLMediaElement ended property
*/
Object.defineProperty(this, "ended", {
get: function getEnded() {
return ended;
}
});
/**
* HTMLMediaElement muted property
*/
Object.defineProperty(this, "muted", {
get: function getMuted() {
return muted;
},
set: function setMuted(val) {
muted = val;
if (audioFeeder) {
if (muted) {
audioFeeder.mute();
} else {
audioFeeder.unmute();
}
}
}
});
return this;
}