forked from mgile/Cast-Player-Sample
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1213 lines (1091 loc) · 44.4 KB
/
app.js
File metadata and controls
1213 lines (1091 loc) · 44.4 KB
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
// constants
var OOYALA_PLAYER_URL = "//player.ooyala.com/core/e48c9b51282d406f957c666149763424?plugins=bm";
var SPLASH_SCREEN_SRC = "./images/ooyala-logo.png";
var LOGO_IMAGE_SRC = "./images/ooyala-logo.png";
var PAUSE_ICON_SRC = " ./images/pause.svg";
var PLAY_ICON_SRC = " ./images/play.svg";
var WATERMARK_ICON_SRC = "./images/ooyala-logo-watermark.png";
var CHROMECAST_DEBUG_TAG = "Chromecast-debug";
var PLAYER_DEBUG_TAG = "Player-debug";
// set the timeouts to be 5 minutes
var SPLASH_SCREEN_TIMEOUT_MILLIS = 5 * 60 * 1000;
var LOADING_SCREEN_TIMEOUT_MILLIS = 5 * 60 * 1000;
var PAUSE_STATE_TIMEOUT_MILLIS = 5 * 60 * 1000;
window.castReceiverManager = null;
window.castMB = null;
window.mediaManager = null;
window.mediaElement = null;
window.namespace = "urn:x-cast:ooyala";
var debug = true;
var initialTimeout = null;
var player = null;
var playerId = null;
var senders = [];
var currentEmbedCode = null;
var currentPlayheadTimeInfo = {};
var duration = 0;
var hasBeenInitialized = false;
// Closed Captioning resources
var ccResourceMap = {}; // Resource map of closed captions, it has format: "language" => URL
var ccLanguage = 'en'; // currently used closed captions language, empty if none
var isLiveStream = false; // used for closed captions on live assets
// loading screen elements
var promoImageElement = null;
var titleElement = null;
var descriptionElement = null;
var autoPlay = false;
var controls = null;
var rootElement = null;
var stopped = false;
var ended = false;
var stopEvent = null;
var adsPlayed = false;
var hasAds = false;
// Screen related variables
var screenController = null;
var screens = null;
var splashScreen = null;
var loadingScreen = null;
var playerScreen = null;
var errorScreen = null;
/*************************************************************************/
// CHROMECAST SETUP
/*************************************************************************/
// Initialize Chromecast receiver application
window.onload = function() {
//cast.receiver.logger.setLevelValue(cast.receiver.LoggerLevel.DEBUG);
setupMediaManager();
setupCastReceiver();
setupMessageBus();
window.castReceiverManager.start();
initUIElements();
// Start the initial timeout set to timeout on the splash screen
initialTimeout = setTimeout(function() {
window.castReceiverManager.stop();
}, SPLASH_SCREEN_TIMEOUT_MILLIS);
}
/**
Required initialization of cast.receiver.MediaManager
https://developers.google.com/cast/docs/reference/receiver/cast.receiver.MediaManager
**/
function setupMediaManager() {
window.mediaElement = document.getElementById('tmp_video');
window.mediaManager = new cast.receiver.MediaManager(window.mediaElement);
window.mediaManager.onGetStatus = onGetStatus.bind(this);
window.mediaManager.onLoad = onLoad.bind(this);
window.mediaManager.onPauseOrig = window.mediaManager.onPause;
window.mediaManager.onPause = onPause.bind(this);
window.mediaManager.onPlayOrig = window.mediaManager.onPlay;
window.mediaManager.onPlay = onPlay.bind(this);
window.mediaManager.onSeekOrig = window.mediaManager.onSeek;
window.mediaManager.onSeek = onSeek.bind(this);
window.mediaManager.onSetVolumeOrig = window.mediaManager.onSetVolume;
window.mediaManager.onSetVolume = onSetVolume.bind(this);
window.mediaManager.onEndedOrig = window.mediaManager.onEnded;
window.mediaManager.onEnded = onEnded.bind(this);
window.mediaManager.onStopOrig = window.mediaManager.onStop;
window.mediaManager.onStop = onStop.bind(this);
window.mediaManager.onErrorOrig = window.mediaManager.onError;
window.mediaManager.onError = onError.bind(this);
window.mediaManager.customizedStatusCallback = customizedStatusCallback.bind(this);
window.mediaManager.onPlayAgainOrig = window.mediaManager.onPlayAgain;
window.mediaManager.onPlayAgain = function(e){
console.log("Play again event: ", e);
player.mb.publish(OO.EVENTS.REPLAY);
window.mediaManager.onPlayAgainOrig(
new cast.receiver.MediaManager.Event(cast.receiver.MediaManager.EventType.PLAY_AGAIN, "on play again event", e.senderId));
}
}
/**
For debugging purposes only, debug output of current cast.receiver.media.MediaStatus object
**/
function customizedStatusCallback(ms) {
ms.data = { customData: { debug: debug } } // to make sure it will be printed with Chromecast-debug tag
printDebugMessage("customizedStatusCallback", ms);
return ms;
}
/**
Response to getStatus request of sender'media object
**/
function onGetStatus(event) {
event.data = { customData: { debug: debug } } // to make sure it will be printed with Chromecast-debug tag
printDebugMessage("onGetStatus", event);
window.mediaManager.sendStatus(event.senderId, event.data.requestId, true);
}
/**
Response to pause request of sender'media object
**/
function onPause(event) {
printDebugMessage("onPause", event);
window.mediaManager.onPauseOrig(event);
//player.mb.publish(OO.EVENTS.PAUSE);
player.pause();
window.mediaManager.sendStatus(event.senderId, event.data.requestId, true);
}
/**
Response to play request of sender'media object
**/
function onPlay(event) {
printDebugMessage("onPlay", event);
window.mediaManager.onPlayOrig(event);
//player.mb.publish(OO.EVENTS.INITIAL_PLAY);
player.play();
window.mediaManager.sendStatus(event.senderId, event.data.requestId, true);
}
/**
Response to seek request of sender'media object
**/
function onSeek(event) {
var seekTime = parseInt(event.data.currentTime);
if (seekTime >= duration - 1) {
seekTime = (duration > 1) ? duration - 1 : 0;
}
event.data.currentTime = seekTime;
printDebugMessage("onSeek", event);
player.mb.publish(OO.EVENTS.SEEK, seekTime);
window.mediaManager.onSeekOrig(event);
window.mediaManager.sendStatus(event.senderId, event.data.requestId, true);
}
/**
Response to setVolume request of sender'media object
**/
function onSetVolume(event) {
printDebugMessage("onSetVolume", event);
window.mediaManager.onSetVolumeOrig(event);
var volume = event.data.volume.level;
player.mb.publish(OO.EVENTS.CHANGE_VOLUME, volume);
window.mediaManager.sendStatus(event.senderId, event.data.requestId, true);
}
/**
Session will be stopped, show splash screen
**/
function onStop(event) {
stopped = true;
stopEvent = event;
player.mb.publish(OO.EVENTS.PLAYED);
printDebugMessage("onStop", event);
}
/**
Playback has finished, sender will be notified
**/
function onEnded() {
console.log("Entre al end del video")
if (ended) {
return;
}
ended = true;
printDebugMessage("onEnded", null);
window.mediaManager.onEndedOrig(event);
}
/**
Error notification callback
**/
function onError(errorObj) {
printDebugMessage("onError", errorObj);
window.mediaManager.onErrorOrig(errorObj);
// Display on Chromecast screen this errorObj.
// If this object is chrome.cast.Error, then it will
// show error code and description, otherwise it wil
// print string representation of this object
displayCastMediaError(errorObj);
}
/**
Response to loadMedia request from sender's cast session
**/
function onLoad(event) {
printDebugMessage("onLoad", event);
stopped = false;
stopEvent = null;
var playerData = event.data.media.customData;
handleLoadingScreenInfo(playerData);
// For first time setup, load the Ooyala player
// Otherwise, simply set the embed code
if (!hasBeenInitialized) {
screenController.showScreen(splashScreen);
initPlayer(playerData);
$("#tmp_video").remove();
} else {
reinitPlayer(playerData, event);
}
window.mediaManager.sendStatus(event.senderId, event.data.requestId, true);
}
function onLoadEXP(e){
printDebugMessage("MediaManager:onLoad", e);
var params = event.data.media.customData;
handleLoadingScreenInfo(params);
initPlayer();
}
/**
Allows to control dynamically debug console output about sender commands and ooyala player events
**/
function printDebugMessage(command, event, ignorePattern) {
if (event) {
if (event.data && event.data.customData) {
if (typeof event.data.customData.debug === "boolean") {
var newDebug = event.data.customData.debug;
if (debug !== newDebug) {
if (debug) {
console.log(CHROMECAST_DEBUG_TAG, "disabling debug");
} else {
console.log(CHROMECAST_DEBUG_TAG, command, JSON.stringify(event, null, '\t'));
}
debug = newDebug;
} else if (debug) {
console.log(CHROMECAST_DEBUG_TAG, command, JSON.stringify(event, null, '\t'));
}
}
} else if (debug && (!ignorePattern || command.indexOf(ignorePattern) < 0)) {
console.log(PLAYER_DEBUG_TAG, command, JSON.stringify(event, null, '\t'));
}
} else if (debug) {
console.log(CHROMECAST_DEBUG_TAG, command);
}
}
/**
Get the instance of the cast receiver
if one needs to debug CastReceiverManager, one can override methods
(onReady, onSenderConnected, etc.) here.
For more info on castReceiverManager,
visit: https://developers.google.com/cast/docs/reference/receiver/cast.receiver.CastReceiverManager
**/
function setupCastReceiver() {
window.castReceiverManager = cast.receiver.CastReceiverManager.getInstance();
window.castReceiverManager.onSenderConnected = function(event) {
senders = window.castReceiverManager.getSenders();
printDebugMessage("connected senders", senders);
}
window.castReceiverManager.onSenderDisconnected = function(event) {
senders = window.castReceiverManager.getSenders();
// if the last sender disconnects, then stop the cast session entirely if it
// was an explicit disconnection
if ((senders.length === 0) && (event.reason == cast.receiver.system.DisconnectReason.REQUESTED_BY_SENDER)) {
if (player !== null){
player.destroy(function(){
window.castReceiverManager.stop();
});
} else {
window.castReceiverManager.stop();
}
}
}
window.castReceiverManager.onShutdown = function(event) {
senders = window.castReceiverManager.getSenders();
}
}
/**
This method opens a namespace channel for a message bus
It then receives messages through onMessage and gets filtered into our
communication protocol cases.
For more info on castMessageBus,
visit: https://developers.google.com/cast/docs/reference/receiver/cast.receiver.CastMessageBus
**/
function setupMessageBus() {
// create message bus for communications between receiver and sender
window.castMB = castReceiverManager.getCastMessageBus(window.namespace)
// onMessage gets called every time the sender sends a message
// It receives messages through ooyala's message bus
window.castMB.onMessage = function(evt) {
// Adds error handling to the received messages
var message = null;
var ERROR_MESSAGE = "Exception in message format";
// verify message
var message = null;
if (evt && evt.data) {
message = JSON.parse(evt.data);
if (!message || !message.action) {
console.error(ERROR_MESSAGE);
return;
}
}
switch (message.action) {
case "setCCLanguage":
setClosedCaptionsLanguage(message.data);
break;
case "getstatus":
// if status is requested, return the state, playhead, and embedcode
var status = {
state: player.getState(),
playhead: currentPlayheadTimeInfo,
embed: currentEmbedCode
}
// only send the status back to the sender that requested it
window.castMB.send(evt.senderId, JSON.stringify(status));
break;
case "error":
// This message came from sender through ooyala namespace, its purpose is to render on
// Chromecast display errors that may come from sender side. This message has structure:
// { action: 'error', message: chrome.cast.Error }
// Both chrome.cast.Error's code and description will be printed on the screen
displayCastMediaError(message.message);
break;
}
}
}
function initPlayerExp(params){
console.log("InitPlayer: ",params);
}
/**
This initPlayer will be called when the sender sends the init call
It will load Ooyala player and subscribe to all events that the player publishes
**/
function initPlayer(data) {
ended = false;
// Clear the initial timeout set to timeout on the splash screen
if (data && data.ec) {
clearTimeout(initialTimeout);
}
// mark as initialized
hasBeenInitialized = true;
currentEmbedCode = data.ec;
// Change the V3 version here
var v3Version;
if (data && data.version) {
v3Version = "version=" + data.version;
}
if (data && typeof data.debug === "boolean") {
debug = data.debug;
} else {
debug = false;
}
// prepare the player load script
var playerJs = document.createElement("script");
playerJs.type = "text/javascript";
playerJs.src = OOYALA_PLAYER_URL;
var playerParams = {};
if (data.params) {
if (typeof data.params === "string") {
playerParams = eval("(" + data.params + ")");
} else if (typeof data.params === "object") {
playerParams = data.params;
}
}
if (typeof playerParams['autoplay'] !== "boolean") {
playerParams['autoplay'] = true;
}
autoPlay = playerParams['autoplay'];
ccLanguage = '';
if (!!playerParams['ccLanguage']) {
// player paramteres may contain ccLanguage: "en" (or other language), in which case
// we should set up ccLanguage variable so that playback starts with closed captioning
ccLanguage = playerParams['ccLanguage'];
}
//data.ec = "o2YWQ4YzE6ono3qI5c3fN-R3Jhi1yPXn";
//data.ec = "hsdHIyYzE668escyHgrFiednk4831Un3"
//playerParams.embedToken = "//player.ooyala.com/sas/embed_token/lhNmYyOuUnCvRiHi5NbFBBLOG4xm/o2YWQ4YzE6ono3qI5c3fN-R3Jhi1yPXn?api_key=lhNmYyOuUnCvRiHi5NbFBBLOG4xm.S9VRE&expires=1507108002&signature=U3zyP8bgBQwOZrofz8J+76rNtAVe4EkW5OMszkPTd1c&override_syndication_group=override_synd_groups_in_backlot";
//var extra = {"api_ssl_server":"https://player-staging.ooyala.com","api_server":"http://player-staging.ooyala.com","auth_ssl_server":"https://player-staging.ooyala.com/sas","auth_server":"http://player-staging.ooyala.com/sas"};
//Object.assign(playerParams, extra);
if (!playerParams.onCreate) {
playerParams.onCreate = function(player) {
player.mb.subscribe("*", "chromecast", function(evt) {
switch (evt) {
case OO.EVENTS.PLAYHEAD_TIME_CHANGED:
currentPlayheadTimeInfo = arguments;
duration = arguments[2];
// As the playhead moves, update the progress bar, playhead, and duration
controls.setValuePlayhead(currentPlayheadTimeInfo);
sendToAllSenders(JSON.stringify(arguments));
break;
case OO.EVENTS.PLAYED:
// If finished playing, display the splash screen
screenController.showScreen(splashScreen);
window.mediaManager.onEnded();
sendToAllSenders(JSON.stringify(arguments));
break;
case OO.EVENTS.SET_EMBED_CODE:
if ($("#cc_track")) {
// remove track element for closed captions, if any - a new one will be created
// if needed
$("#cc_track").remove();
}
screenController.showScreen(loadingScreen);
break;
case OO.EVENTS.STREAM_PLAYING:
// Show the player screen
screenController.showScreen(playerScreen, "setClosedCaptionsLanguage(ccLanguage)");
// Fade out the title, labels, and the scrubber after a specified delay
controls.fadeOutControls(controls.getDelayInMillis());
// Replace pause icon by play icon and fade it out after a specified delay
controls.fadeOutPausePlay(controls.getDelayInMillis());
controls.setDisplaySpinner("none");
break;
case OO.EVENTS.PAUSED:
// Finish fading of of play button if this is the case
finishFadeEffect(controls.playIcon);
// Show all the controls and make sure playhead has been updated
controls.showControls();
// Fade out the title, labels, and the scrubber after a specified delay
controls.fadeOutControls(controls.getDelayInMillis());
controls.setValuePlayhead(currentPlayheadTimeInfo);
sendToAllSenders(JSON.stringify(arguments));
break;
case OO.EVENTS.PLAYBACK_READY:
// Assign the root element and controls when player is created
rootElement = document.querySelector(".innerWrapper");
window.mediaElement = document.querySelectorAll(`#${playerId}`)[0];
printDebugMessage("new mediaElement", window.mediaElement);
if (window.mediaElement) {
window.mediaManager.setMediaElement(window.mediaElement);
}
if (controls === null) {
controls = new _Controls(rootElement);
}
controls.showControls();
// Handling timeouts
handleReceiverTimeouts(player);
break;
case OO.EVENTS.SEEKED:
controls.setValuePlayhead(currentPlayheadTimeInfo);
controls.fadeOutScrubber();
sendToAllSenders(JSON.stringify(arguments));
break;
case OO.EVENTS.BUFFERING:
// Show spinner
controls.setDisplaySpinner("block");
break;
case OO.EVENTS.BUFFERED:
// Show the player screen
screenController.showScreen(playerScreen, "setClosedCaptionsLanguage(ccLanguage)");
// Fade out the title, labels, and the scrubber after a specified delay
controls.fadeOutControls(controls.getDelayInMillis());
// Replace pause icon by play icon and fade it out after a specified delay
controls.fadeOutPausePlay(controls.getDelayInMillis());
// Hide spinner
controls.setDisplaySpinner("none");
break;
case OO.EVENTS.AUTHORIZATION_FETCHED:
var stream = arguments[1].streams[0];
if (stream) {
if (stream.is_live_stream) {
printDebugMessage("Live stream:", arguments[1].streams[0].delivery_type);
isLiveStream = true;
} else {
printDebugMessage("Stream type:", arguments[1].streams[0].delivery_type);
}
} else {
printDebugMessage("No stream info", null);
}
break;
case OO.EVENTS.CONTENT_TREE_FETCHED:
// We should clear closed captions resource map as it may be populated from from
// playback of previous title
if (!$.isEmptyObject(ccResourceMap)) {
ccResourceMap = {}
}
// Closed captions availability for this asset is known when content tree is
// fetched. Content tree data is available in arguments[1], closed captions
// information is stored in closed_captions_vtt object of content tree
if (arguments[1].closed_captions_vtt) {
var ccData = arguments[1].closed_captions_vtt;
var languages = ccData.languages;
for (var i in languages) {
// Populate resource map of closed captions, it has format: "language" => URL
printDebugMessage("CC:", languages[i] + " " + ccData.captions[languages[i]].url);
ccResourceMap[languages[i]] = ccData.captions[languages[i]].url;
}
}
break;
case OO.EVENTS.SEEK:
// Just show seek bar, duration and played labels
controls.showScrubber();
sendToAllSenders(JSON.stringify(arguments));
break;
case OO.EVENTS.CLOSED_CAPTIONS_INFO_AVAILABLE:
case OO.EVENTS.PLAYING:
window.mediaElement = document.querySelectorAll(`#${playerId}`)[0];
if (window.mediaElement) {
window.mediaManager.setMediaElement(window.mediaElement);
}
sendToAllSenders(JSON.stringify(arguments));
break;
case OO.EVENTS.ERROR:
// Display the error screen with the proper errors
screenController.showScreen(errorScreen);
// Display the title and description errors the index 1 of the arguments array
// is an object containing the OO.ERROR code
var error = "";
if (arguments[1] && arguments[1].code) {
error = arguments[1].code;
}
displayErrorTitleDescription(error);
sendToAllSenders(JSON.stringify(arguments));
break;
case OO.EVENTS.ADS_PLAYED:
console.log("Ya se terminaron los ADSSSS ", arguments);
adsPlayed = true;
break;
case OO.EVENTS.WILL_PLAY_ADS:
console.log("Voy a tocar los Adddddss papuuuuu!!!!", arguments);
hasAds = true;
break;
case OO.EVENTS.EMBED_CODE_CHANGED:
console.log("EMBED_CODE_CHANGED, ", arguments);
break;
case OO.EVENTS.VC_VIDEO_ELEMENT_CREATED:
playerId = "bitmovinplayer-video-" + arguments[1].domId;
break;
}
printDebugMessage("receiver.html " + evt, arguments, "playheadTimeChanged");
});
}
}
// when the script has loaded, create the player
playerJs.onload = (function(data) {
playerParams.debug = true;
player = OO.Player.create('player', data.ec, playerParams);
}).bind(this, data);
document.head.appendChild(playerJs);
}
/**
Sets the embed code of the player with the parameters
**/
function reinitPlayer(data, event) {
if (data && data.ec) {
debug = data.debug;
currentEmbedCode = data.ec;
//if the embed code it is the same, just trigger the replay event
if (player && player.getEmbedCode() === currentEmbedCode){
//window.mediaManager.onPlayAgain(event);
player.mb.publish(OO.EVENTS.REPLAY);
return;
}
ended = false;
isLiveStream = false;
duration = 0;
var playerParams = {};
if (data.params) {
if (typeof data.params === "string") {
playerParams = eval("(" + data.params + ")");
} else if (typeof data.params === "object") {
playerParams = data.params;
}
}
if (typeof playerParams['autoplay'] !== 'boolean') {
playerParams['autoplay'] = true;
}
autoPlay = playerParams['autoplay'];
ccLanguage = '';
if (!!playerParams['ccLanguage']) {
// We should also check for closed captions-related player parameter on playback of next asset,
// and set ccLanguage variable so that playback starts with closed captioning
ccLanguage = playerParams['ccLanguage'];
}
player.setEmbedCode(data.ec, playerParams);
if (controls) {
var title = (!data.title) ? "" : data.title;
var promo_url = (!data.promo_url) ? "" : data.promo_url;
promoImageElement.src = promo_url + "?t=" + new Date().getTime();
controls.reset(title, promo_url);
controls.showControls();
}
}
}
/**
This sends a message to all senders that are connected to this receiver
**/
function sendToAllSenders(message) {
if (window.castMB && senders.length > 0) {
window.castMB.broadcast(message);
}
}
/**
Closed captions - enable if language argument is not empty / disable if language argument is empty
**/
function setClosedCaptionsLanguage(language) {
if (!language && !ccLanguage) {
return;
}
if (isLiveStream) {
// Setting CC is required right away, language selection was passed in player params
player.mb.publish(OO.EVENTS.SET_CLOSED_CAPTIONS_LANGUAGE, '', { type: cast.player.api.CaptionsType.CEA608, data: language });
if (!!language) {
// sender will enable CC button on this event, otherwise it will be disabled
player.mb.publish(OO.EVENTS.CLOSED_CAPTIONS_INFO_AVAILABLE, { lang : 'live', value : 'Live Closed Captions' });
}
} else {
player.mb.publish(OO.EVENTS.SET_CLOSED_CAPTIONS_LANGUAGE, language);
}
ccLanguage = language;
}
/*************************************************************************/
// SCREEN TRANSITION CONTROLLER
/*************************************************************************/
/**
This controls which screen should be shown by hiding the others
**/
function _ScreenController(elements) {
this.screens = elements;
}
/**
This function will make sure to only display the screen that is passed
as the parameter while hiding the others
**/
_ScreenController.prototype.showScreen = function(screenToShow, callback) {
if (this.currentScreen === screenToShow) {
// some events come up more than once, so we should ignore repeated requests
// as it may cause problems if to-be-performed actions are defined
return;
}
for (var index in this.screens) {
if (this.screens[index] !== screenToShow) {
this.screens[index].style.display = "none";
}
}
if (!!callback && typeof callback === 'string') {
eval(callback);
}
screenToShow.style.display = "block";
this.currentScreen = screenToShow;
}
/**
Set the necessary UI elements for ease of use
Also, initialize the screen controller to handle the transitioning of screens
You are welcomed to modify the necessary screens and how they interact based on your use case.
These screens DOM are instantiated at the beginning of this HTML page.
**/
function initUIElements() {
document.getElementById('splash_image').src = SPLASH_SCREEN_SRC;
document.getElementById('logo_image').src = LOGO_IMAGE_SRC;
promoImageElement = document.getElementById('promo_image');
titleElement = document.getElementById('loading_title');
descriptionElement = document.getElementById('loading_description');
splashScreen = document.querySelector("#splash_screen");
loadingScreen = document.querySelector("#loading_screen");
playerScreen = document.querySelector("#player");
errorScreen = document.querySelector("#error_screen");
screens = [ splashScreen, loadingScreen, playerScreen, errorScreen ];
screenController = new _ScreenController(screens);
}
/**
Check to make sure all 3 parts- promo, title, and description were sent
then change the variables
**/
function handleLoadingScreenInfo(data) {
titleElement.innerHTML = (!data.title) ? "" : data.title;
descriptionElement.innerHTML = (!data.description) ? "" : data.description;
promoImageElement.src = (!data.promo_url) ? "" : data.promo_url;
}
/*************************************************************************/
// CONTROL BAR UI
/*************************************************************************/
/**
Function to use a fade effect using webkit transitions
**/
function fadeEffect(element, opacity, time) {
var listener = function() {
element.style.webkitTransition = '';
element.removeEventListener('webkitTransitionEnd', listener, false);
};
element.addEventListener('webkitTransitionEnd', listener, false);
element.style.webkitTransition = 'opacity ' + time + 's linear';
element.style.opacity = opacity;
}
/**
Function to finish fade effect of an element
**/
function finishFadeEffect(element) {
var listener = function() {
element.style.webkitTransition = '';
element.removeEventListener('webkitTransitionEnd', listener, false);
};
element.removeEventListener('webkitTransitionEnd', listener, false);
element.style.webkitTransition = '';
element.style.opacity = 0;
}
/**
This operates all of the video controls that are put on top of the video
It works as an overlay with a higher z-index than the video
**/
function _Controls(rootElement) {
this.rootElement = rootElement;
this.currentScreen = null;
/** CONSTANTS FOR TRANSITION EFFECTS **/
// Adjusts the size of the spinner
this.spinnerScale = 0.10;
// Start the opacity at 0 (invisible) and make it transition to 1 (visible)
this.desiredOpacity = 0;
this.originalOpacity = 1;
// The duration and times for other transitions
this.secondsToTransition = 1;
this.secondsToScrubberTransition = 5;
this.millisToFade = 2000;
/** END CONSTANTS FOR TRANSITIONS**/
// Initialize the controls
this.init();
}
/*
_Controls specifies how control Bar is going to appear on Receiver.
You are welcomed to modify, add and remove:
- Logo: watermark image and TV rating
- Video Metadata: promo image, Title
- Play / Pause button
- Scrubber bar
- Time and Duration
- Spinner icon
*/
_Controls.prototype.init = function() {
this.controls_wrap = document.createElement('div');
this.controls_wrap.className = "oo_controls";
this.rootElement.appendChild(this.controls_wrap);
// Append the initial html to the control wrapper
document.querySelector(".oo_controls").innerHTML +=
'<div id="spinner_wrapper">\
<div id="spinner_icon" class="absolute_center spinner"></div>\
</div>\
<div id="promo_title_container">\
<img id ="promo_icon" />\
<div id="title_wrapper">\
<h1 id="title_header" class="cast_text"></h1>\
</div>\
</div>\
<div id="watermark_wrapper">\
<img id ="watermark_icon" />\
</div>\
<div id="scrubber_wrapper">\
<div id ="play_pause_wrapper">\
<img id="pause_icon" />\
<img id="play_icon" />\
</div>\
<div id ="playhead_container">\
<h5 id="playhead">00:00</h5>\
</div>\
<div id ="seek_bar">\
<div id="progress"></div>\
<div id="buffered_progress"></div>\
</div>\
<div id = "duration_wrapper">\
<h5 id = "duration">00:00</h5>\
</div>\
</div>';
// Initialize variables to their associated DOM elements
this.seekContainer = document.querySelector('#seek_bar');
this.progressBar = document.querySelector('#progress');
this.bufferedBar = document.querySelector('#buffered_progress');
this.durationLabel = document.querySelector('#duration');
this.playheadLabel = document.querySelector('#playhead');
this.videoTitle = document.querySelector('#title_header');
this.pauseIcon = document.querySelector('#pause_icon');
this.playIcon = document.querySelector('#play_icon');
this.spinnerIcon = document.querySelector("#spinner_icon");
this.promoIcon = document.querySelector("#promo_icon");
this.watermark = document.querySelector("#watermark_icon");
// Set the image sources and text to their proper values
this.videoTitle.innerHTML = titleElement.innerHTML;
this.pauseIcon.src = PAUSE_ICON_SRC;
this.playIcon.src = PLAY_ICON_SRC;
this.playIcon.style.opacity = 0;
this.promoIcon.src = promoImageElement.src;
promoImageElement.src += "?t=" + new Date().getTime();
this.watermark.src = WATERMARK_ICON_SRC;
// Setting up spinner icon
var spinnerWidthAndHeight = $("#loading_screen").height() * this.spinnerScale;
this.spinnerIcon.style.width = spinnerWidthAndHeight;
this.spinnerIcon.style.height= spinnerWidthAndHeight;
// The first array of elements relate solely to the scrubber itself
// The second array contains all of the controls that needed to be faded out
this.scrubberFadeElements = [ this.playheadLabel, this.durationLabel, this.seekContainer ];
this.controlsFadeElements = [ this.playheadLabel, this.durationLabel, this.seekContainer,
this.videoTitle, this.promoIcon ];
}
/**
Setter method for updating control bar UI element of Title and promo image
**/
_Controls.prototype.reset = function(title, promo_url) {
this.videoTitle.innerHTML = title;
this.promoIcon.src = promo_url;
this.setValue(0, 0, 0, 0);
}
/**
Getter method for the milliseconds to fade
**/
_Controls.prototype.getDelayInMillis = function() {
return this.millisToFade;
}
/**
Setter method for setting the display property of the spinner
**/
_Controls.prototype.setDisplaySpinner= function(display) {
if (this.spinnerIcon) {
this.spinnerIcon.style.display = display;
}
}
/**
Fade out all scrubber-related elements
**/
_Controls.prototype.fadeOutScrubber = function() {
for (var element in this.scrubberFadeElements) {
fadeEffect(this.scrubberFadeElements[element], this.desiredOpacity, this.secondsToScrubberTransition);
}
}
/**
Replace pause icon by play icon and within a specified delay, fade out play icon
**/
_Controls.prototype.fadeOutPausePlay = function(delay) {
finishFadeEffect(this.pauseIcon);
this.playIcon.style.webkitTransition = '';
this.playIcon.style.opacity = this.originalOpacity;
var self = this;
setTimeout(function() {
fadeEffect(self.playIcon, self.desiredOpacity, self.secondsToTransition);
}, delay);
}
/**
Within a specified delay, fade out all the control-related elements
**/
_Controls.prototype.fadeOutControls = function(delay) {
var self = this;
setTimeout(function() {
for (var element in self.controlsFadeElements) {
fadeEffect(self.controlsFadeElements[element], self.desiredOpacity, self.secondsToTransition);
}
}, delay);
}
/**
Shows only scrubber related elements by setting elements to be visible at
opacity 1
**/
_Controls.prototype.showScrubber = function() {
for (var element in this.scrubberFadeElements) {
this.scrubberFadeElements[element].style.webkitTransition = '';
this.scrubberFadeElements[element].style.opacity = this.originalOpacity;
}
}
/**
Shows all control related elements by setting elements to be visible at opacity 1
**/
_Controls.prototype.showControls = function() {
for (var element in this.controlsFadeElements) {
this.controlsFadeElements[element].style.webkitTransition = '';
this.controlsFadeElements[element].style.opacity = this.originalOpacity;
}
this.pauseIcon.style.webkitTransition = '';
this.pauseIcon.style.opacity = this.originalOpacity;
}
/**
Call the setValue to update the playhead information
**/
_Controls.prototype.setValuePlayhead = function(playhead) {
// Explanation of the playhead parameter array:
// 1 is time played, 2 is duration, 3 is buffered
// 4 (start, end) is (mintime and maxtime)
this.setValue(playhead[1], playhead[3], playhead[4].start, playhead[4].end);
}
/**
This sets the buffered and playhead related controls' positions
**/
_Controls.prototype.setValue = function(played, buffered, minTime, maxTime) {
// Calculate played percentage
var playedPercent = (played - minTime) / (maxTime - minTime);
playedPercent = Math.min(Math.max(0, playedPercent), 1);
this.progressBar.style.width = (playedPercent * 100) + "%";
// calculate buffer percentage
var bufferedPercent = (buffered - minTime) / (maxTime - minTime);
bufferedPercent = Math.min(Math.max(0, bufferedPercent), 1);
this.bufferedBar.style.width = (bufferedPercent * this.seekContainer.clientWidth ) + 'px';
//labels using the equivalent of OO.formatSeconds
this.playheadLabel.innerHTML = timeFormat(played || 0);
this.durationLabel.innerHTML = isLiveStream ? "Live" : timeFormat(maxTime || 0);
}
/**
Get a formatted time derived from the time in seconds
**/
function timeFormat(timeInSeconds) {
if (timeInSeconds === Number.POSITIVE_INFINITY) {
return '';
}
var seconds = parseInt(timeInSeconds,10) % 60;
var hours = parseInt(timeInSeconds / 3600, 10);
var minutes = parseInt((timeInSeconds - hours * 3600) / 60, 10);
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;