-
Notifications
You must be signed in to change notification settings - Fork 0
/
CastVideos.js
1129 lines (1024 loc) · 40.8 KB
/
CastVideos.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
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
(function() {
'use strict';
/**
* Media source root URL
**/
var MEDIA_SOURCE_ROOT = 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/';
/**
* Media source URL JSON
**/
var MEDIA_SOURCE_URL = 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/videos.json';
/**
* Width of progress bar in pixel
**/
var PROGRESS_BAR_WIDTH = 600;
/**
* Constatns of states for Chromecast device
**/
var DEVICE_STATE = {
'IDLE' : 0,
'ACTIVE' : 1,
'WARNING' : 2,
'ERROR' : 3,
};
/**
* Constatns of states for CastPlayer
**/
var PLAYER_STATE = {
'IDLE' : 'IDLE',
'LOADING' : 'LOADING',
'LOADED' : 'LOADED',
'PLAYING' : 'PLAYING',
'PAUSED' : 'PAUSED',
'STOPPED' : 'STOPPED',
'SEEKING' : 'SEEKING',
'ERROR' : 'ERROR'
};
/**
* Cast player object
* main variables:
* - deviceState for Cast mode:
* IDLE: Default state indicating that Cast extension is installed, but showing no current activity
* ACTIVE: Shown when Chrome has one or more local activities running on a receiver
* WARNING: Shown when the device is actively being used, but when one or more issues have occurred
* ERROR: Should not normally occur, but shown when there is a failure
* - Cast player variables for controlling Cast mode media playback
* - Local player variables for controlling local mode media playbacks
* - Current media variables for transition between Cast and local modes
*/
var CastPlayer = function() {
/* device variables */
// @type {DEVICE_STATE} A state for device
this.deviceState = DEVICE_STATE.IDLE;
/* Cast player variables */
// @type {Object} a chrome.cast.media.Media object
this.currentMediaSession = null;
// @type {Number} volume
this.currentVolume = 0.5;
// @type {Boolean} A flag for autoplay after load
this.autoplay = true;
// @type {string} a chrome.cast.Session object
this.session = null;
// @type {PLAYER_STATE} A state for Cast media player
this.castPlayerState = PLAYER_STATE.IDLE;
/* Local player variables */
// @type {PLAYER_STATE} A state for local media player
this.localPlayerState = PLAYER_STATE.IDLE;
// @type {HTMLElement} local player
this.localPlayer = null;
// @type {Boolean} Fullscreen mode on/off
this.fullscreen = false;
/* Current media variables */
// @type {Boolean} Audio on and off
this.audio = true;
// @type {Number} A number for current media index
this.currentMediaIndex = 0;
// @type {Number} A number for current media time
this.currentMediaTime = 0;
// @type {Number} A number for current media duration
this.currentMediaDuration = -1;
// @type {Timer} A timer for tracking progress of media
this.timer = null;
// @type {Boolean} A boolean to stop timer update of progress when triggered by media status event
this.progressFlag = true;
// @type {Number} A number in milliseconds for minimal progress update
this.timerStep = 1000;
/* media contents from JSON */
this.mediaContents = null;
this.initializeCastPlayer();
this.initializeLocalPlayer();
};
/**
* Initialize local media player
*/
CastPlayer.prototype.initializeLocalPlayer = function() {
this.localPlayer = document.getElementById('video_element')
};
/**
* Initialize Cast media player
* Initializes the API. Note that either successCallback and errorCallback will be
* invoked once the API has finished initialization. The sessionListener and
* receiverListener may be invoked at any time afterwards, and possibly more than once.
*/
CastPlayer.prototype.initializeCastPlayer = function() {
if (!chrome.cast || !chrome.cast.isAvailable) {
setTimeout(this.initializeCastPlayer.bind(this), 1000);
return;
}
// default set to the default media receiver app ID
// optional: you may change it to point to your own
var applicationID = chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID;
// request session
var sessionRequest = new chrome.cast.SessionRequest(applicationID);
var apiConfig = new chrome.cast.ApiConfig(sessionRequest,
this.sessionListener.bind(this),
this.receiverListener.bind(this));
chrome.cast.initialize(apiConfig, this.onInitSuccess.bind(this), this.onError.bind(this));
this.addVideoThumbs();
this.initializeUI();
};
/**
* Callback function for init success
*/
CastPlayer.prototype.onInitSuccess = function() {
console.log("init success");
this.updateMediaControlUI();
};
/**
* Generic error callback function
*/
CastPlayer.prototype.onError = function() {
console.log("error");
};
/**
* @param {!Object} e A new session
* This handles auto-join when a page is reloaded
* When active session is detected, playback will automatically
* join existing session and occur in Cast mode and media
* status gets synced up with current media of the session
*/
CastPlayer.prototype.sessionListener = function(e) {
this.session = e;
if( this.session ) {
this.deviceState = DEVICE_STATE.ACTIVE;
if( this.session.media[0] ) {
this.onMediaDiscovered('activeSession', this.session.media[0]);
}
else {
this.loadMedia(this.currentMediaIndex);
}
}
}
/**
* @param {string} e Receiver availability
* This indicates availability of receivers but
* does not provide a list of device IDs
*/
CastPlayer.prototype.receiverListener = function(e) {
if( e === 'available' ) {
console.log("receiver found");
}
else {
console.log("receiver list empty");
}
};
/**
* Select a media content
* @param {Number} mediaIndex A number for media index
*/
CastPlayer.prototype.selectMedia = function(mediaIndex) {
console.log("media selected" + mediaIndex);
this.currentMediaIndex = mediaIndex;
// reset progress bar
var pi = document.getElementById("progress_indicator");
var p = document.getElementById("progress");
// reset currentMediaTime
this.currentMediaTime = 0;
p.style.width = '0px';
pi.style.marginLeft = -21 - PROGRESS_BAR_WIDTH + 'px';
if( !this.currentMediaSession ) {
if( this.localPlayerState == PLAYER_STATE.PLAYING ) {
this.localPlayerState = PLAYER_STATE.IDLE;
this.playMediaLocally(0);
}
}
else {
this.castPlayerState = PLAYER_STATE.IDLE;
this.playMedia();
}
this.selectMediaUpdateUI(mediaIndex);
};
/**
* Requests that a receiver application session be created or joined. By default, the SessionRequest
* passed to the API at initialization time is used; this may be overridden by passing a different
* session request in opt_sessionRequest.
*/
CastPlayer.prototype.launchApp = function() {
console.log("launching app...");
chrome.cast.requestSession(this.onRequestSessionSuccess.bind(this), this.onLaunchError.bind(this));
if( this.timer ) {
clearInterval(this.timer);
}
};
/**
* Callback function for request session success
* @param {Object} e A chrome.cast.Session object
*/
CastPlayer.prototype.onRequestSessionSuccess = function(e) {
console.log("session success: " + e.sessionId);
this.session = e;
this.deviceState = DEVICE_STATE.ACTIVE;
this.updateMediaControlUI();
this.loadMedia(this.currentMediaIndex);
};
/**
* Callback function for launch error
*/
CastPlayer.prototype.onLaunchError = function() {
console.log("launch error");
this.deviceState = DEVICE_STATE.ERROR;
};
/**
* Stops the running receiver application associated with the session.
*/
CastPlayer.prototype.stopApp = function() {
this.session.stop(this.onStopAppSuccess.bind(this, 'Session stopped'),
this.onError.bind(this));
};
/**
* Callback function for stop app success
*/
CastPlayer.prototype.onStopAppSuccess = function(message) {
console.log(message);
this.deviceState = DEVICE_STATE.IDLE;
this.castPlayerState = PLAYER_STATE.IDLE;
this.currentMediaSession = null;
clearInterval(this.timer);
this.updateDisplayMessage();
// continue to play media locally
console.log("current time: " + this.currentMediaTime);
this.playMediaLocally(this.currentMediaTime);
this.updateMediaControlUI();
};
/**
* Loads media into a running receiver application
* @param {Number} mediaIndex An index number to indicate current media content
*/
CastPlayer.prototype.loadMedia = function(mediaIndex) {
if (!this.session) {
console.log("no session");
return;
}
console.log("loading..." + this.mediaContents[mediaIndex]['title']);
var mediaInfo = new chrome.cast.media.MediaInfo(this.mediaContents[mediaIndex]['sources'][0]);
mediaInfo.contentType = 'video/mp4';
var request = new chrome.cast.media.LoadRequest(mediaInfo);
request.autoplay = this.autoplay;
if( this.localPlayerState == PLAYER_STATE.PLAYING ) {
request.currentTime = this.localPlayer.currentTime;
}
else {
request.currentTime = 0;
}
var payload = {
"title:" : this.mediaContents[0]['title'],
"thumb" : this.mediaContents[0]['thumb']
};
var json = {
"payload" : payload
};
request.customData = json;
this.castPlayerState = PLAYER_STATE.LOADING;
this.session.loadMedia(request,
this.onMediaDiscovered.bind(this, 'loadMedia'),
this.onLoadMediaError.bind(this));
document.getElementById("media_title").innerHTML = this.mediaContents[this.currentMediaIndex]['title'];
document.getElementById("media_subtitle").innerHTML = this.mediaContents[this.currentMediaIndex]['subtitle'];
document.getElementById("media_desc").innerHTML = this.mediaContents[this.currentMediaIndex]['description'];
};
/**
* Callback function for loadMedia success
* @param {Object} mediaSession A new media object.
*/
CastPlayer.prototype.onMediaDiscovered = function(how, mediaSession) {
console.log("new media session ID:" + mediaSession.mediaSessionId + ' (' + how + ')');
this.currentMediaSession = mediaSession;
if( how == 'loadMedia' ) {
if( this.autoplay ) {
this.castPlayerState = PLAYER_STATE.PLAYING;
}
else {
this.castPlayerState = PLAYER_STATE.LOADED;
}
}
if( how == 'activeSession' ) {
this.castPlayerState = this.session.media[0].playerState;
this.currentMediaTime = this.session.media[0].currentTime;
}
if( this.castPlayerState == PLAYER_STATE.PLAYING ) {
// start progress timer
this.startProgressTimer(this.incrementMediaTime);
}
this.currentMediaSession.addUpdateListener(this.onMediaStatusUpdate.bind(this));
this.currentMediaDuration = this.currentMediaSession.media.duration;
var duration = this.currentMediaDuration;
var hr = parseInt(duration/3600);
duration -= hr * 3600;
var min = parseInt(duration/60);
var sec = parseInt(duration % 60);
if ( hr > 0 ) {
duration = hr + ":" + min + ":" + sec;
}
else {
if( min > 0 ) {
duration = min + ":" + sec;
}
else {
duration = sec;
}
}
document.getElementById("duration").innerHTML = duration;
if( this.localPlayerState == PLAYER_STATE.PLAYING ) {
this.localPlayerState == PLAYER_STATE.STOPPED;
var vi = document.getElementById('video_image')
vi.style.display = 'block';
this.localPlayer.style.display = 'none';
// start progress timer
this.startProgressTimer(this.incrementMediaTime);
}
// update UIs
this.updateMediaControlUI();
this.updateDisplayMessage();
};
/**
* Callback function when media load returns error
*/
CastPlayer.prototype.onLoadMediaError = function(e) {
console.log("media error");
this.castPlayerState = PLAYER_STATE.IDLE;
// update UIs
this.updateMediaControlUI();
this.updateDisplayMessage();
};
/**
* Callback function for media status update from receiver
* @param {!Boolean} e true/false
*/
CastPlayer.prototype.onMediaStatusUpdate = function(e) {
if( e == false ) {
this.currentMediaTime = 0;
this.castPlayerState = PLAYER_STATE.IDLE;
}
console.log("updating media");
this.updateProgressBar(e);
this.updateDisplayMessage();
this.updateMediaControlUI();
};
/**
* Helper function
* Increment media current position by 1 second
*/
CastPlayer.prototype.incrementMediaTime = function() {
if( this.castPlayerState == PLAYER_STATE.PLAYING || this.localPlayerState == PLAYER_STATE.PLAYING ) {
if( this.currentMediaTime < this.currentMediaDuration ) {
this.currentMediaTime += 1;
this.updateProgressBarByTimer();
}
else {
this.currentMediaTime = 0;
clearInterval(this.timer);
}
}
};
/**
* Play media in local player
* @param {Number} currentTime A number for media current position
*/
CastPlayer.prototype.playMediaLocally = function(currentTime) {
var vi = document.getElementById('video_image')
vi.style.display = 'none';
this.localPlayer.style.display = 'block';
if( this.localPlayerState != PLAYER_STATE.PLAYING && this.localPlayerState != PLAYER_STATE.PAUSED ) {
this.localPlayer.src = this.mediaContents[this.currentMediaIndex]['sources'][0];
this.localPlayer.load();
this.localPlayer.addEventListener('loadeddata', this.onMediaLoadedLocally.bind(this, currentTime));
}
else {
this.localPlayer.play();
// start progress timer
this.startProgressTimer(this.incrementMediaTime);
}
this.localPlayerState = PLAYER_STATE.PLAYING;
this.updateMediaControlUI();
};
/**
* Callback when media is loaded in local player
* @param {Number} currentTime A number for media current position
*/
CastPlayer.prototype.onMediaLoadedLocally = function(currentTime) {
this.currentMediaDuration = this.localPlayer.duration;
var duration = this.currentMediaDuration;
var hr = parseInt(duration/3600);
duration -= hr * 3600;
var min = parseInt(duration/60);
var sec = parseInt(duration % 60);
if ( hr > 0 ) {
duration = hr + ":" + min + ":" + sec;
}
else {
if( min > 0 ) {
duration = min + ":" + sec;
}
else {
duration = sec;
}
}
document.getElementById("duration").innerHTML = duration;
this.localPlayer.currentTime= currentTime;
this.localPlayer.play();
// start progress timer
this.startProgressTimer(this.incrementMediaTime);
};
/**
* Play media in Cast mode
*/
CastPlayer.prototype.playMedia = function() {
if( !this.currentMediaSession ) {
this.playMediaLocally(0);
return;
}
switch( this.castPlayerState )
{
case PLAYER_STATE.LOADED:
case PLAYER_STATE.PAUSED:
this.currentMediaSession.play(null,
this.mediaCommandSuccessCallback.bind(this,"playing started for " + this.currentMediaSession.sessionId),
this.onError.bind(this));
this.currentMediaSession.addUpdateListener(this.onMediaStatusUpdate.bind(this));
this.castPlayerState = PLAYER_STATE.PLAYING;
// start progress timer
this.startProgressTimer(this.incrementMediaTime);
break;
case PLAYER_STATE.IDLE:
case PLAYER_STATE.LOADING:
case PLAYER_STATE.STOPPED:
this.loadMedia(this.currentMediaIndex);
this.currentMediaSession.addUpdateListener(this.onMediaStatusUpdate.bind(this));
this.castPlayerState = PLAYER_STATE.PLAYING;
break;
default:
break;
}
this.updateMediaControlUI();
this.updateDisplayMessage();
};
/**
* Pause media playback in Cast mode
*/
CastPlayer.prototype.pauseMedia = function() {
if( !this.currentMediaSession ) {
this.pauseMediaLocally();
return;
}
if( this.castPlayerState == PLAYER_STATE.PLAYING ) {
this.castPlayerState = PLAYER_STATE.PAUSED;
this.currentMediaSession.pause(null,
this.mediaCommandSuccessCallback.bind(this,"paused " + this.currentMediaSession.sessionId),
this.onError.bind(this));
this.updateMediaControlUI();
this.updateDisplayMessage();
clearInterval(this.timer);
}
};
/**
* Pause media playback in local player
*/
CastPlayer.prototype.pauseMediaLocally = function() {
this.localPlayer.pause();
this.localPlayerState = PLAYER_STATE.PAUSED;
this.updateMediaControlUI();
clearInterval(this.timer);
};
/**
* Stop meia playback in either Cast or local mode
*/
CastPlayer.prototype.stopMedia = function() {
if( !this.currentMediaSession ) {
this.stopMediaLocally();
return;
}
this.currentMediaSession.stop(null,
this.mediaCommandSuccessCallback.bind(this,"stopped " + this.currentMediaSession.sessionId),
this.onError.bind(this));
this.castPlayerState = PLAYER_STATE.STOPPED;
clearInterval(this.timer);
this.updateDisplayMessage();
this.updateMediaControlUI();
};
/**
* Stop media playback in local player
*/
CastPlayer.prototype.stopMediaLocally = function() {
var vi = document.getElementById('video_image')
vi.style.display = 'block';
this.localPlayer.style.display = 'none';
this.localPlayer.stop();
this.localPlayerState = PLAYER_STATE.STOPPED;
this.updateMediaControlUI();
};
/**
* Set media volume in Cast mode
* @param {Boolean} mute A boolean
*/
CastPlayer.prototype.setMediaVolume = function(mute) {
var p = document.getElementById("audio_bg_level");
if( event.currentTarget.id == 'audio_bg_track' ) {
var pos = 100 - parseInt(event.offsetY);
}
else {
var pos = parseInt(p.clientHeight) - parseInt(event.offsetY);
}
if( !this.currentMediaSession ) {
this.localPlayer.volume = pos < 100 ? pos/100 : 1;
p.style.height = pos + 'px';
p.style.marginTop = -pos + 'px';
return;
}
if( event.currentTarget.id == 'audio_bg_track' || event.currentTarget.id == 'audio_bg_level' ) {
// add a drag to avoid loud volume
if( pos < 100 ) {
var vScale = this.currentVolume * 100;
if( pos > vScale ) {
pos = vScale + (pos - vScale)/2;
}
p.style.height = pos + 'px';
p.style.marginTop = -pos + 'px';
this.currentVolume = pos/100;
}
else {
this.currentVolume = 1;
}
}
var volume = new chrome.cast.Volume();
volume.level = this.currentVolume;
volume.muted = mute;
var request = new chrome.cast.media.VolumeRequest();
request.volume = volume;
this.currentMediaSession.setVolume(request,
this.mediaCommandSuccessCallback.bind(this),
this.onError.bind(this));
this.updateMediaControlUI();
};
/**
* Mute media function in either Cast or local mode
*/
CastPlayer.prototype.muteMedia = function() {
if( this.audio == true ) {
this.audio = false;
document.getElementById('audio_on').style.display = 'none';
document.getElementById('audio_off').style.display = 'block';
if( this.currentMediaSession ) {
this.setMediaVolume(true);
}
else {
this.localPlayer.muted = true;
}
}
else {
this.audio = true;
document.getElementById('audio_on').style.display = 'block';
document.getElementById('audio_off').style.display = 'none';
if( this.currentMediaSession ) {
this.setMediaVolume(false);
}
else {
this.localPlayer.muted = false;
}
}
this.updateMediaControlUI();
};
/**
* media seek function in either Cast or local mode
* @param {Event} e An event object from seek
*/
CastPlayer.prototype.seekMedia = function(event) {
var pos = parseInt(event.offsetX);
var pi = document.getElementById("progress_indicator");
var p = document.getElementById("progress");
if( event.currentTarget.id == 'progress_indicator' ) {
var curr = parseInt(this.currentMediaTime + this.currentMediaDuration * pos / PROGRESS_BAR_WIDTH);
var pp = parseInt(pi.style.marginLeft) + pos;
var pw = parseInt(p.style.width) + pos;
}
else {
var curr = parseInt(pos * this.currentMediaDuration / PROGRESS_BAR_WIDTH);
var pp = pos -21 - PROGRESS_BAR_WIDTH;
var pw = pos;
}
if( this.localPlayerState == PLAYER_STATE.PLAYING || this.localPlayerState == PLAYER_STATE.PAUSED ) {
this.localPlayer.currentTime= curr;
this.currentMediaTime = curr;
this.localPlayer.play();
}
if( this.localPlayerState == PLAYER_STATE.PLAYING || this.localPlayerState == PLAYER_STATE.PAUSED
|| this.castPlayerState == PLAYER_STATE.PLAYING || this.castPlayerState == PLAYER_STATE.PAUSED ) {
p.style.width = pw + 'px';
pi.style.marginLeft = pp + 'px';
}
if( this.castPlayerState != PLAYER_STATE.PLAYING && this.castPlayerState != PLAYER_STATE.PAUSED ) {
return;
}
this.currentMediaTime = curr;
console.log('Seeking ' + this.currentMediaSession.sessionId + ':' +
this.currentMediaSession.mediaSessionId + ' to ' + pos + "%");
var request = new chrome.cast.media.SeekRequest();
request.currentTime = this.currentMediaTime;
this.currentMediaSession.seek(request,
this.onSeekSuccess.bind(this, 'media seek done'),
this.onError.bind(this));
this.castPlayerState = PLAYER_STATE.SEEKING;
this.updateDisplayMessage();
this.updateMediaControlUI();
};
/**
* Callback function for seek success
* @param {String} info A string that describe seek event
*/
CastPlayer.prototype.onSeekSuccess = function(info) {
console.log(info);
this.castPlayerState = PLAYER_STATE.PLAYING;
this.updateDisplayMessage();
this.updateMediaControlUI();
};
/**
* Callback function for media command success
*/
CastPlayer.prototype.mediaCommandSuccessCallback = function(info, e) {
console.log(info);
};
/**
* Update progress bar when there is a media status update
* @param {Object} e An media status update object
*/
CastPlayer.prototype.updateProgressBar = function(e) {
var p = document.getElementById("progress");
var pi = document.getElementById("progress_indicator");
if( e.idleReason == 'FINISHED' && e.playerState == 'IDLE' ) {
p.style.width = '0px';
pi.style.marginLeft = -21 - PROGRESS_BAR_WIDTH + 'px';
clearInterval(this.timer);
this.castPlayerState = PLAYER_STATE.STOPPED;
this.updateDisplayMessage();
}
else {
p.style.width = Math.ceil(PROGRESS_BAR_WIDTH * e.currentTime / this.currentMediaSession.media.duration + 1) + 'px';
this.progressFlag = false;
setTimeout(this.setProgressFlag.bind(this),1000); // don't update progress in 1 second
var pp = Math.ceil(PROGRESS_BAR_WIDTH * e.currentTime / this.currentMediaSession.media.duration);
pi.style.marginLeft = -21 - PROGRESS_BAR_WIDTH + pp + 'px';
}
};
/**
* Set progressFlag with a timeout of 1 second to avoid UI update
* until a media status update from receiver
*/
CastPlayer.prototype.setProgressFlag = function() {
this.progressFlag = true;
};
/**
* Update progress bar based on timer
*/
CastPlayer.prototype.updateProgressBarByTimer = function() {
var p = document.getElementById("progress");
if( isNaN(parseInt(p.style.width)) ) {
p.style.width = 0;
}
if( this.currentMediaDuration > 0 ) {
var pp = Math.floor(PROGRESS_BAR_WIDTH * this.currentMediaTime/this.currentMediaDuration);
}
if( this.progressFlag ) {
// don't update progress if it's been updated on media status update event
p.style.width = pp + 'px';
var pi = document.getElementById("progress_indicator");
pi.style.marginLeft = -21 - PROGRESS_BAR_WIDTH + pp + 'px';
}
if( pp > PROGRESS_BAR_WIDTH ) {
clearInterval(this.timer);
this.deviceState = DEVICE_STATE.IDLE;
this.castPlayerState = PLAYER_STATE.IDLE;
this.updateDisplayMessage();
this.updateMediaControlUI();
}
};
/**
* Update display message depending on cast mode by deviceState
*/
CastPlayer.prototype.updateDisplayMessage = function() {
if( this.deviceState != DEVICE_STATE.ACTIVE || this.castPlayerState == PLAYER_STATE.IDLE || this.castPlayerState == PLAYER_STATE.STOPPED ) {
document.getElementById("playerstate").style.display = 'none';
document.getElementById("playerstatebg").style.display = 'none';
document.getElementById("play").style.display = 'block';
document.getElementById("video_image_overlay").style.display = 'none';
//document.getElementById("media_control").style.opacity = 0.0;
}
else {
document.getElementById("playerstate").style.display = 'block';
document.getElementById("playerstatebg").style.display = 'block';
document.getElementById("video_image_overlay").style.display = 'block';
//document.getElementById("media_control").style.opacity = 0.5;
}
document.getElementById("playerstate").innerHTML = this.castPlayerState
+ " on " + this.session.receiver.friendlyName;
}
/**
* Update media control UI components based on localPlayerState or castPlayerState
*/
CastPlayer.prototype.updateMediaControlUI = function() {
if( this.deviceState == DEVICE_STATE.ACTIVE ) {
document.getElementById("casticonactive").style.display = 'block';
document.getElementById("casticonidle").style.display = 'none';
var playerState = this.castPlayerState;
}
else {
document.getElementById("casticonidle").style.display = 'block';
document.getElementById("casticonactive").style.display = 'none';
var playerState = this.localPlayerState;
}
switch( playerState )
{
case PLAYER_STATE.LOADED:
case PLAYER_STATE.PLAYING:
document.getElementById("play").style.display = 'none';
document.getElementById("pause").style.display = 'block';
break;
case PLAYER_STATE.PAUSED:
case PLAYER_STATE.IDLE:
case PLAYER_STATE.LOADING:
case PLAYER_STATE.STOPPED:
document.getElementById("play").style.display = 'block';
document.getElementById("pause").style.display = 'none';
break;
default:
break;
}
}
/**
* Update UI components after selectMedia call
* @param {Number} mediaIndex An number
*/
CastPlayer.prototype.selectMediaUpdateUI = function(mediaIndex) {
document.getElementById('video_image').src = MEDIA_SOURCE_ROOT + this.mediaContents[mediaIndex]['thumb'];
document.getElementById("progress").style.width = '0px';
document.getElementById("media_title").innerHTML = this.mediaContents[mediaIndex]['title'];
document.getElementById("media_subtitle").innerHTML = this.mediaContents[mediaIndex]['subtitle'];
document.getElementById("media_desc").innerHTML = this.mediaContents[mediaIndex]['description'];
};
/**
* Initialize UI components and add event listeners
*/
CastPlayer.prototype.initializeUI = function() {
// set initial values for title, subtitle, and description
document.getElementById("media_title").innerHTML = this.mediaContents[0]['title'];
document.getElementById("media_subtitle").innerHTML = this.mediaContents[this.currentMediaIndex]['subtitle'];
document.getElementById("media_desc").innerHTML = this.mediaContents[this.currentMediaIndex]['description'];
// add event handlers to UI components
document.getElementById("casticonidle").addEventListener('click', this.launchApp.bind(this));
document.getElementById("casticonactive").addEventListener('click', this.stopApp.bind(this));
document.getElementById("progress_bg").addEventListener('click', this.seekMedia.bind(this));
document.getElementById("progress").addEventListener('click', this.seekMedia.bind(this));
document.getElementById("progress_indicator").addEventListener('dragend', this.seekMedia.bind(this));
document.getElementById("audio_on").addEventListener('click', this.muteMedia.bind(this));
document.getElementById("audio_off").addEventListener('click', this.muteMedia.bind(this));
document.getElementById("audio_bg").addEventListener('mouseover', this.showVolumeSlider.bind(this));
document.getElementById("audio_on").addEventListener('mouseover', this.showVolumeSlider.bind(this));
document.getElementById("audio_bg_level").addEventListener('mouseover', this.showVolumeSlider.bind(this));
document.getElementById("audio_bg_track").addEventListener('mouseover', this.showVolumeSlider.bind(this));
document.getElementById("audio_bg_level").addEventListener('click', this.setMediaVolume.bind(this, false));
document.getElementById("audio_bg_track").addEventListener('click', this.setMediaVolume.bind(this, false));
document.getElementById("audio_bg").addEventListener('mouseout', this.hideVolumeSlider.bind(this));
document.getElementById("audio_on").addEventListener('mouseout', this.hideVolumeSlider.bind(this));
document.getElementById("media_control").addEventListener('mouseover', this.showMediaControl.bind(this));
document.getElementById("media_control").addEventListener('mouseout', this.hideMediaControl.bind(this));
document.getElementById("fullscreen_expand").addEventListener('click', this.requestFullScreen.bind(this));
document.getElementById("fullscreen_collapse").addEventListener('click', this.cancelFullScreen.bind(this));
document.addEventListener("fullscreenchange", this.changeHandler.bind(this), false);
document.addEventListener("webkitfullscreenchange", this.changeHandler.bind(this), false);
// enable play/pause buttons
document.getElementById("play").addEventListener('click', this.playMedia.bind(this));
document.getElementById("pause").addEventListener('click', this.pauseMedia.bind(this));
document.getElementById("progress_indicator").draggable = true;
};
/**
* Show the media control
*/
CastPlayer.prototype.showMediaControl = function() {
document.getElementById('media_control').style.opacity = 0.7;
};
/**
* Hide the media control
*/
CastPlayer.prototype.hideMediaControl = function() {
document.getElementById('media_control').style.opacity = 0;
};
/**
* Show the volume slider
*/
CastPlayer.prototype.showVolumeSlider = function() {
document.getElementById('audio_bg').style.opacity = 1;
document.getElementById('audio_bg_track').style.opacity = 1;
document.getElementById('audio_bg_level').style.opacity = 1;
document.getElementById('audio_indicator').style.opacity = 1;
};
/**
* Hide the volume stlider
*/
CastPlayer.prototype.hideVolumeSlider = function() {
document.getElementById('audio_bg').style.opacity = 0;
document.getElementById('audio_bg_track').style.opacity = 0;
document.getElementById('audio_bg_level').style.opacity = 0;
document.getElementById('audio_indicator').style.opacity = 0;
};
/**
* Request full screen mode
*/
CastPlayer.prototype.requestFullScreen = function() {
// Supports most browsers and their versions.
var element = document.getElementById("video_element");
var requestMethod = element.requestFullScreen || element.webkitRequestFullScreen;
if (requestMethod) { // Native full screen.
requestMethod.call(element);
console.log("requested fullscreen");
}
};
/**
* Exit full screen mode
*/
CastPlayer.prototype.cancelFullScreen = function() {
// Supports most browsers and their versions.
var requestMethod = document.cancelFullScreen || document.webkitCancelFullScreen;
if (requestMethod) {
requestMethod.call(document);
}
};
/**
* Exit fullscreen mode by escape
*/
CastPlayer.prototype.changeHandler = function(){
if (this.fullscreen) {
document.getElementById('fullscreen_expand').style.display = 'block';
document.getElementById('fullscreen_collapse').style.display = 'none';
this.fullscreen = false;
}
else {
document.getElementById('fullscreen_expand').style.display = 'none';
document.getElementById('fullscreen_collapse').style.display = 'block';
this.fullscreen = true;
}
};
/**
* @param {function} A callback function for the fucntion to start timer
*/
CastPlayer.prototype.startProgressTimer = function(callback) {
if( this.timer ) {
clearInterval(this.timer);
this.timer = null;
}
// start progress timer
this.timer = setInterval(callback.bind(this), this.timerStep);
};
/**
* Do AJAX call to load media json
* @param {String} src A URL for media json.
*/
CastPlayer.prototype.retrieveMediaJSON = function(src) {
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', this.onMediaJsonLoad.bind(this));
xhr.addEventListener('error', this.onMediaJsonError.bind(this));
xhr.open('GET', src);
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.responseType = "json";
xhr.send(null);
};
/**
* Callback function for AJAX call on load success
* @param {Object} evt An object returned from Ajax call
*/
CastPlayer.prototype.onMediaJsonLoad = function(evt) {