forked from mgile/Cast-Player-Sample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
player.js
executable file
·2107 lines (1882 loc) · 60.5 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
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.
*/
/**
* @fileoverview Receiver / Player sample
* <p>
* This sample demonstrates how to build your own Receiver for use with Google
* Cast. One of the goals of this sample is to be fully UX compliant.
* </p>
* <p>
* A receiver is typically an HTML5 application with a html, css, and JavaScript
* components. It demonstrates the following Cast Receiver API's:
* </p>
* <ul>
* <li>CastReceiverManager</li>
* <li>MediaManager</li>
* <li>Media Player Library</li>
* </ul>
* <p>
* It also demonstrates the following player functions:
* </p>
* <ul>
* <li>Branding Screen</li>
* <li>Playback Complete image</li>
* <li>Limited Animation</li>
* <li>Buffering Indicator</li>
* <li>Seeking</li>
* <li>Pause indicator</li>
* <li>Loading Indicator</li>
* </ul>
*
*/
'use strict';
/**
* Creates the namespace
*/
var sampleplayer = sampleplayer || {};
/**
* <p>
* Cast player constructor - This does the following:
* </p>
* <ol>
* <li>Bind a listener to visibilitychange</li>
* <li>Set the default state</li>
* <li>Bind event listeners for img & video tags<br />
* error, stalled, waiting, playing, pause, ended, timeupdate, seeking, &
* seeked</li>
* <li>Find and remember the various elements</li>
* <li>Create the MediaManager and bind to onLoad & onStop</li>
* </ol>
*
* @param {!Element} element the element to attach the player
* @struct
* @constructor
* @export
*/
sampleplayer.CastPlayer = function(element) {
/**
* The debug setting to control receiver, MPL and player logging.
* @private {boolean}
*/
this.debug_ = sampleplayer.DISABLE_DEBUG_;
if (this.debug_) {
cast.player.api.setLoggerLevel(cast.player.api.LoggerLevel.DEBUG);
cast.receiver.logger.setLevelValue(cast.receiver.LoggerLevel.DEBUG);
}
/**
* The DOM element the player is attached.
* @private {!Element}
*/
this.element_ = element;
/**
* The current type of the player.
* @private {sampleplayer.Type}
*/
this.type_;
this.setType_(sampleplayer.Type.UNKNOWN, false);
/**
* The current state of the player.
* @private {sampleplayer.State}
*/
this.state_;
/**
* Timestamp when state transition happened last time.
* @private {number}
*/
this.lastStateTransitionTime_ = 0;
this.setState_(sampleplayer.State.LAUNCHING, false);
/**
* The id returned by setInterval for the screen burn timer
* @private {number|undefined}
*/
this.burnInPreventionIntervalId_;
/**
* The id returned by setTimeout for the idle timer
* @private {number|undefined}
*/
this.idleTimerId_;
/**
* The id of timer to handle seeking UI.
* @private {number|undefined}
*/
this.seekingTimerId_;
/**
* The id of timer to defer setting state.
* @private {number|undefined}
*/
this.setStateDelayTimerId_;
/**
* Current application state.
* @private {string|undefined}
*/
this.currentApplicationState_;
/**
* The DOM element for the inner portion of the progress bar.
* @private {!Element}
*/
this.progressBarInnerElement_ = this.getElementByClass_(
'.controls-progress-inner');
/**
* The DOM element for the thumb portion of the progress bar.
* @private {!Element}
*/
this.progressBarThumbElement_ = this.getElementByClass_(
'.controls-progress-thumb');
/**
* The DOM element for the current time label.
* @private {!Element}
*/
this.curTimeElement_ = this.getElementByClass_('.controls-cur-time');
/**
* The DOM element for the total time label.
* @private {!Element}
*/
this.totalTimeElement_ = this.getElementByClass_('.controls-total-time');
/**
* The DOM element for the preview time label.
* @private {!Element}
*/
this.previewModeTimerElement_ = this.getElementByClass_('.preview-mode-timer-countdown');
/**
* Handler for buffering-related events for MediaElement.
* @private {function()}
*/
this.bufferingHandler_ = this.onBuffering_.bind(this);
/**
* Media player to play given manifest.
* @private {cast.player.api.Player}
*/
this.player_ = null;
/**
* Media player used to preload content.
* @private {cast.player.api.Player}
*/
this.preloadPlayer_ = null;
/**
* Text Tracks currently supported.
* @private {?sampleplayer.TextTrackType}
*/
this.textTrackType_ = null;
/**
* Whether player app should handle autoplay behavior.
* @private {boolean}
*/
this.playerAutoPlay_ = false;
/**
* Whether player app should display the preview mode UI.
* @private {boolean}
*/
this.displayPreviewMode_ = false;
/**
* Id of deferred play callback
* @private {?number}
*/
this.deferredPlayCallbackId_ = null;
/**
* Whether the player is ready to receive messages after a LOAD request.
* @private {boolean}
*/
this.playerReady_ = false;
/**
* Whether the player has received the metadata loaded event after a LOAD
* request.
* @private {boolean}
*/
this.metadataLoaded_ = false;
/**
* The media element.
* @private {HTMLMediaElement}
*/
this.mediaElement_ = /** @type {HTMLMediaElement} */
(this.element_.querySelector('video'));
this.mediaElement_.addEventListener('error', this.onError_.bind(this), false);
this.mediaElement_.addEventListener('playing', this.onPlaying_.bind(this),
false);
this.mediaElement_.addEventListener('pause', this.onPause_.bind(this), false);
this.mediaElement_.addEventListener('ended', this.onEnded_.bind(this), false);
this.mediaElement_.addEventListener('abort', this.onAbort_.bind(this), false);
this.mediaElement_.addEventListener('timeupdate', this.onProgress_.bind(this),
false);
this.mediaElement_.addEventListener('seeking', this.onSeekStart_.bind(this),
false);
this.mediaElement_.addEventListener('seeked', this.onSeekEnd_.bind(this),
false);
/**
* The cast receiver manager.
* @private {!cast.receiver.CastReceiverManager}
*/
this.receiverManager_ = cast.receiver.CastReceiverManager.getInstance();
this.receiverManager_.onReady = this.onReady_.bind(this);
this.receiverManager_.onSenderDisconnected =
this.onSenderDisconnected_.bind(this);
this.receiverManager_.onVisibilityChanged =
this.onVisibilityChanged_.bind(this);
this.receiverManager_.setApplicationState(
sampleplayer.getApplicationState_());
/**
* The remote media object.
* @private {cast.receiver.MediaManager}
*/
this.mediaManager_ = new cast.receiver.MediaManager(this.mediaElement_);
/**
* The original load callback.
* @private {?function(cast.receiver.MediaManager.Event)}
*/
this.onLoadOrig_ =
this.mediaManager_.onLoad.bind(this.mediaManager_);
this.mediaManager_.onLoad = this.onLoad_.bind(this);
/**
* The original editTracksInfo callback
* @private {?function(!cast.receiver.MediaManager.Event)}
*/
this.onEditTracksInfoOrig_ =
this.mediaManager_.onEditTracksInfo.bind(this.mediaManager_);
this.mediaManager_.onEditTracksInfo = this.onEditTracksInfo_.bind(this);
/**
* The original metadataLoaded callback
* @private {?function(!cast.receiver.MediaManager.LoadInfo)}
*/
this.onMetadataLoadedOrig_ =
this.mediaManager_.onMetadataLoaded.bind(this.mediaManager_);
this.mediaManager_.onMetadataLoaded = this.onMetadataLoaded_.bind(this);
/**
* The original stop callback.
* @private {?function(cast.receiver.MediaManager.Event)}
*/
this.onStopOrig_ =
this.mediaManager_.onStop.bind(this.mediaManager_);
this.mediaManager_.onStop = this.onStop_.bind(this);
/**
* The original metadata error callback.
* @private {?function(!cast.receiver.MediaManager.LoadInfo)}
*/
this.onLoadMetadataErrorOrig_ =
this.mediaManager_.onLoadMetadataError.bind(this.mediaManager_);
this.mediaManager_.onLoadMetadataError = this.onLoadMetadataError_.bind(this);
/**
* The original error callback
* @private {?function(!Object)}
*/
this.onErrorOrig_ =
this.mediaManager_.onError.bind(this.mediaManager_);
this.mediaManager_.onError = this.onError_.bind(this);
this.mediaManager_.customizedStatusCallback =
this.customizedStatusCallback_.bind(this);
this.mediaManager_.onPreload = this.onPreload_.bind(this);
this.mediaManager_.onCancelPreload = this.onCancelPreload_.bind(this);
};
/**
* The amount of time in a given state before the player goes idle.
*/
sampleplayer.IDLE_TIMEOUT = {
LAUNCHING: 1000 * 60 * 5, // 5 minutes
LOADING: 1000 * 60 * 5, // 5 minutes
PAUSED: 1000 * 60 * 20, // 20 minutes
DONE: 1000 * 60 * 5, // 5 minutes
IDLE: 1000 * 60 * 5 // 5 minutes
};
/**
* Describes the type of media being played.
*
* @enum {string}
*/
sampleplayer.Type = {
AUDIO: 'audio',
VIDEO: 'video',
UNKNOWN: 'unknown'
};
/**
* Describes the type of captions being used.
*
* @enum {string}
*/
sampleplayer.TextTrackType = {
SIDE_LOADED_TTML: 'ttml',
SIDE_LOADED_VTT: 'vtt',
SIDE_LOADED_UNSUPPORTED: 'unsupported',
EMBEDDED: 'embedded'
};
/**
* Describes the type of captions being used.
*
* @enum {string}
*/
sampleplayer.CaptionsMimeType = {
TTML: 'application/ttml+xml',
VTT: 'text/vtt'
};
/**
* Describes the type of track.
*
* @enum {string}
*/
sampleplayer.TrackType = {
AUDIO: 'audio',
VIDEO: 'video',
TEXT: 'text'
};
/**
* Describes the state of the player.
*
* @enum {string}
*/
sampleplayer.State = {
LAUNCHING: 'launching',
LOADING: 'loading',
BUFFERING: 'buffering',
PLAYING: 'playing',
PAUSED: 'paused',
DONE: 'done',
IDLE: 'idle'
};
/**
* The amount of time (in ms) a screen should stay idle before burn in
* prevention kicks in
*
* @type {number}
*/
sampleplayer.BURN_IN_TIMEOUT = 30 * 1000;
/**
* The minimum duration (in ms) that media info is displayed.
*
* @const @private {number}
*/
sampleplayer.MEDIA_INFO_DURATION_ = 3 * 1000;
/**
* Transition animation duration (in sec).
*
* @const @private {number}
*/
sampleplayer.TRANSITION_DURATION_ = 1.5;
/**
* Const to enable debugging.
*
* @const @private {boolean}
*/
sampleplayer.ENABLE_DEBUG_ = true;
/**
* Const to disable debugging.
*
* #@const @private {boolean}
*/
sampleplayer.DISABLE_DEBUG_ = false;
/**
* Returns the element with the given class name
*
* @param {string} className The class name of the element to return.
* @return {!Element}
* @throws {Error} If given class cannot be found.
* @private
*/
sampleplayer.CastPlayer.prototype.getElementByClass_ = function(className) {
var element = this.element_.querySelector(className);
if (element) {
return element;
} else {
throw Error('Cannot find element with class: ' + className);
}
};
/**
* Returns this player's media element.
*
* @return {HTMLMediaElement} The media element.
* @export
*/
sampleplayer.CastPlayer.prototype.getMediaElement = function() {
return this.mediaElement_;
};
/**
* Returns this player's media manager.
*
* @return {cast.receiver.MediaManager} The media manager.
* @export
*/
sampleplayer.CastPlayer.prototype.getMediaManager = function() {
return this.mediaManager_;
};
/**
* Returns this player's MPL player.
*
* @return {cast.player.api.Player} The current MPL player.
* @export
*/
sampleplayer.CastPlayer.prototype.getPlayer = function() {
return this.player_;
};
/**
* Starts the player.
*
* @export
*/
sampleplayer.CastPlayer.prototype.start = function() {
this.receiverManager_.start();
};
/**
* Preloads the given data.
*
* @param {!cast.receiver.media.MediaInformation} mediaInformation The
* asset media information.
* @return {boolean} Whether the media can be preloaded.
* @export
*/
sampleplayer.CastPlayer.prototype.preload = function(mediaInformation) {
this.log_('preload');
// For video formats that cannot be preloaded (mp4...), display preview UI.
if (sampleplayer.canDisplayPreview_(mediaInformation || {})) {
this.showPreviewMode_(mediaInformation);
return true;
}
if (!sampleplayer.supportsPreload_(mediaInformation || {})) {
this.log_('preload: no supportsPreload_');
return false;
}
if (this.preloadPlayer_) {
this.preloadPlayer_.unload();
this.preloadPlayer_ = null;
}
// Only videos are supported for now
var couldPreload = this.preloadVideo_(mediaInformation);
if (couldPreload) {
this.showPreviewMode_(mediaInformation);
}
this.log_('preload: couldPreload=' + couldPreload);
return couldPreload;
};
/**
* Display preview mode metadata.
*
* @param {boolean} show whether player is showing preview mode metadata
* @export
*/
sampleplayer.CastPlayer.prototype.showPreviewModeMetadata = function(show) {
this.element_.setAttribute('preview-mode', show.toString());
};
/**
* Show the preview mode UI.
*
* @param {!cast.receiver.media.MediaInformation} mediaInformation The
* asset media information.
* @private
*/
sampleplayer.CastPlayer.prototype.showPreviewMode_ = function(mediaInformation) {
this.displayPreviewMode_ = true;
this.loadPreviewModeMetadata_(mediaInformation);
this.showPreviewModeMetadata(true);
};
/**
* Hide the preview mode UI.
*
* @private
*/
sampleplayer.CastPlayer.prototype.hidePreviewMode_ = function() {
this.showPreviewModeMetadata(false);
this.displayPreviewMode_ = false;
};
/**
* Preloads some video content.
*
* @param {!cast.receiver.media.MediaInformation} mediaInformation The
* asset media information.
* @return {boolean} Whether the video can be preloaded.
* @private
*/
sampleplayer.CastPlayer.prototype.preloadVideo_ = function(mediaInformation) {
this.log_('preloadVideo_');
var self = this;
var url = mediaInformation.contentId;
var protocolFunc = sampleplayer.getProtocolFunction_(mediaInformation);
if (!protocolFunc) {
this.log_('No protocol found for preload');
return false;
}
var host = new cast.player.api.Host({
'url': url,
'mediaElement': self.mediaElement_
});
host.onError = function() {
self.preloadPlayer_.unload();
self.preloadPlayer_ = null;
self.showPreviewModeMetadata(false);
self.displayPreviewMode_ = false;
self.log_('Error during preload');
};
self.preloadPlayer_ = new cast.player.api.Player(host);
self.preloadPlayer_.preload(protocolFunc(host));
return true;
};
/**
* Loads the given data.
*
* @param {!cast.receiver.MediaManager.LoadInfo} info The load request info.
* @export
*/
sampleplayer.CastPlayer.prototype.load = function(info) {
this.log_('onLoad_');
clearTimeout(this.idleTimerId_);
var self = this;
var media = info.message.media || {};
var contentType = media.contentType;
var playerType = sampleplayer.getType_(media);
var isLiveStream = media.streamType === cast.receiver.media.StreamType.LIVE;
if (!media.contentId) {
this.log_('Load failed: no content');
self.onLoadMetadataError_(info);
} else if (playerType === sampleplayer.Type.UNKNOWN) {
this.log_('Load failed: unknown content type: ' + contentType);
self.onLoadMetadataError_(info);
} else {
this.log_('Loading: ' + playerType);
self.resetMediaElement_();
self.setType_(playerType, isLiveStream);
var preloaded = false;
switch (playerType) {
case sampleplayer.Type.AUDIO:
self.loadAudio_(info);
break;
case sampleplayer.Type.VIDEO:
preloaded = self.loadVideo_(info);
break;
}
self.playerReady_ = false;
self.metadataLoaded_ = false;
self.loadMetadata_(media);
self.showPreviewModeMetadata(false);
self.displayPreviewMode_ = false;
sampleplayer.preload_(media, function() {
self.log_('preloaded=' + preloaded);
if (preloaded) {
// Data is ready to play so transiton directly to playing.
self.setState_(sampleplayer.State.PLAYING, false);
self.playerReady_ = true;
self.maybeSendLoadCompleted_(info);
// Don't display metadata again, since autoplay already did that.
self.deferPlay_(0);
self.playerAutoPlay_ = false;
} else {
sampleplayer.transition_(self.element_, sampleplayer.TRANSITION_DURATION_, function() {
self.setState_(sampleplayer.State.LOADING, false);
// Only send load completed after we reach this point so the media
// manager state is still loading and the sender can't send any PLAY
// messages
self.playerReady_ = true;
self.maybeSendLoadCompleted_(info);
if (self.playerAutoPlay_) {
// Make sure media info is displayed long enough before playback
// starts.
self.deferPlay_(sampleplayer.MEDIA_INFO_DURATION_);
self.playerAutoPlay_ = false;
}
});
}
});
}
};
/**
* Sends the load complete message to the sender if the two necessary conditions
* are met, the player is ready for messages and the loaded metadata event has
* been received.
* @param {!cast.receiver.MediaManager.LoadInfo} info The load request info.
* @private
*/
sampleplayer.CastPlayer.prototype.maybeSendLoadCompleted_ = function(info) {
if (!this.playerReady_) {
this.log_('Deferring load response, player not ready');
} else if (!this.metadataLoaded_) {
this.log_('Deferring load response, loadedmetadata event not received');
} else {
this.onMetadataLoadedOrig_(info);
this.log_('Sent load response, player is ready and metadata loaded');
}
};
/**
* Resets the media element.
*
* @private
*/
sampleplayer.CastPlayer.prototype.resetMediaElement_ = function() {
this.log_('resetMediaElement_');
if (this.player_) {
this.player_.unload();
this.player_ = null;
}
this.textTrackType_ = null;
};
/**
* Loads the metadata for the given media.
*
* @param {!cast.receiver.media.MediaInformation} media The media.
* @private
*/
sampleplayer.CastPlayer.prototype.loadMetadata_ = function(media) {
this.log_('loadMetadata_');
if (!sampleplayer.isCastForAudioDevice_()) {
var metadata = media.metadata || {};
var titleElement = this.element_.querySelector('.media-title');
sampleplayer.setInnerText_(titleElement, metadata.title);
var subtitleElement = this.element_.querySelector('.media-subtitle');
sampleplayer.setInnerText_(subtitleElement, metadata.subtitle);
var artwork = sampleplayer.getMediaImageUrl_(media);
if (artwork) {
var artworkElement = this.element_.querySelector('.media-artwork');
sampleplayer.setBackgroundImage_(artworkElement, artwork);
}
}
};
/**
* Loads the metadata for the given preview mode media.
*
* @param {!cast.receiver.media.MediaInformation} media The media.
* @private
*/
sampleplayer.CastPlayer.prototype.loadPreviewModeMetadata_ = function(media) {
this.log_('loadPreviewModeMetadata_');
if (!sampleplayer.isCastForAudioDevice_()) {
var metadata = media.metadata || {};
var titleElement = this.element_.querySelector('.preview-mode-title');
sampleplayer.setInnerText_(titleElement, metadata.title);
var subtitleElement = this.element_.querySelector('.preview-mode-subtitle');
sampleplayer.setInnerText_(subtitleElement, metadata.subtitle);
var artwork = sampleplayer.getMediaImageUrl_(media);
if (artwork) {
var artworkElement = this.element_.querySelector('.preview-mode-artwork');
sampleplayer.setBackgroundImage_(artworkElement, artwork);
}
}
};
/**
* Lets player handle autoplay, instead of depending on underlying
* MediaElement to handle it. By this way, we can make sure that media playback
* starts after loading screen is displayed.
*
* @param {!cast.receiver.MediaManager.LoadInfo} info The load request info.
* @private
*/
sampleplayer.CastPlayer.prototype.letPlayerHandleAutoPlay_ = function(info) {
this.log_('letPlayerHandleAutoPlay_: ' + info.message.autoplay);
var autoplay = info.message.autoplay;
info.message.autoplay = false;
this.mediaElement_.autoplay = false;
this.playerAutoPlay_ = autoplay == undefined ? true : autoplay;
};
/**
* Loads some audio content.
*
* @param {!cast.receiver.MediaManager.LoadInfo} info The load request info.
* @private
*/
sampleplayer.CastPlayer.prototype.loadAudio_ = function(info) {
this.log_('loadAudio_');
this.letPlayerHandleAutoPlay_(info);
this.loadDefault_(info);
};
/**
* Loads some video content.
*
* @param {!cast.receiver.MediaManager.LoadInfo} info The load request info.
* @return {boolean} Whether the media was preloaded
* @private
*/
sampleplayer.CastPlayer.prototype.loadVideo_ = function(info) {
this.log_('loadVideo_');
var self = this;
var protocolFunc = null;
var url = info.message.media.contentId;
var protocolFunc = sampleplayer.getProtocolFunction_(info.message.media);
var wasPreloaded = false;
this.letPlayerHandleAutoPlay_(info);
if (!protocolFunc) {
this.log_('loadVideo_: using MediaElement');
this.mediaElement_.addEventListener('stalled', this.bufferingHandler_,
false);
this.mediaElement_.addEventListener('waiting', this.bufferingHandler_,
false);
} else {
this.log_('loadVideo_: using Media Player Library');
// When MPL is used, buffering status should be detected by
// getState()['underflow]'
this.mediaElement_.removeEventListener('stalled', this.bufferingHandler_);
this.mediaElement_.removeEventListener('waiting', this.bufferingHandler_);
// If we have not preloaded or the content preloaded does not match the
// content that needs to be loaded, perform a full load
var loadErrorCallback = function() {
// unload player and trigger error event on media element
if (self.player_) {
self.resetMediaElement_();
self.mediaElement_.dispatchEvent(new Event('error'));
}
};
if (!this.preloadPlayer_ || (this.preloadPlayer_.getHost &&
this.preloadPlayer_.getHost().url != url)) {
if (this.preloadPlayer_) {
this.preloadPlayer_.unload();
this.preloadPlayer_ = null;
}
this.log_('Regular video load');
var host = new cast.player.api.Host({
'url': url,
'mediaElement': this.mediaElement_
});
host.onError = loadErrorCallback;
this.player_ = new cast.player.api.Player(host);
this.player_.load(protocolFunc(host));
} else {
this.log_('Preloaded video load');
this.player_ = this.preloadPlayer_;
this.preloadPlayer_ = null;
// Replace the "preload" error callback with the "load" error callback
this.player_.getHost().onError = loadErrorCallback;
this.player_.load();
wasPreloaded = true;
}
}
this.loadMediaManagerInfo_(info, !!protocolFunc);
return wasPreloaded;
};
/**
* Loads media and tracks info into media manager.
*
* @param {!cast.receiver.MediaManager.LoadInfo} info The load request info.
* @param {boolean} loadOnlyTracksMetadata Only load the tracks metadata (if
* it is in the info provided).
* @private
*/
sampleplayer.CastPlayer.prototype.loadMediaManagerInfo_ =
function(info, loadOnlyTracksMetadata) {
if (loadOnlyTracksMetadata) {
// In the case of media that uses MPL we do not
// use the media manager default onLoad API but we still need to load
// the tracks metadata information into media manager (so tracks can be
// managed and properly reported in the status messages) if they are
// provided in the info object (side loaded).
this.maybeLoadSideLoadedTracksMetadata_(info);
} else {
// Media supported by mediamanager, use the media manager default onLoad API
// to load the media, tracks metadata and, if the tracks are vtt the media
// manager will process the cues too.
this.loadDefault_(info);
}
};
/**
* Sets the captions type based on the text tracks.
*
* @param {!cast.receiver.MediaManager.LoadInfo} info The load request info.
* @private
*/
sampleplayer.CastPlayer.prototype.readSideLoadedTextTrackType_ =
function(info) {
if (!info.message || !info.message.media || !info.message.media.tracks) {
return;
}
for (var i = 0; i < info.message.media.tracks.length; i++) {
var oldTextTrackType = this.textTrackType_;
if (info.message.media.tracks[i].type !=
cast.receiver.media.TrackType.TEXT) {
continue;
}
if (this.isTtmlTrack_(info.message.media.tracks[i])) {
this.textTrackType_ =
sampleplayer.TextTrackType.SIDE_LOADED_TTML;
} else if (this.isVttTrack_(info.message.media.tracks[i])) {
this.textTrackType_ =
sampleplayer.TextTrackType.SIDE_LOADED_VTT;
} else {
this.log_('Unsupported side loaded text track types');
this.textTrackType_ =
sampleplayer.TextTrackType.SIDE_LOADED_UNSUPPORTED;
break;
}
// We do not support text tracks with different caption types for a single
// piece of content
if (oldTextTrackType && oldTextTrackType != this.textTrackType_) {
this.log_('Load has inconsistent text track types');
this.textTrackType_ =
sampleplayer.TextTrackType.SIDE_LOADED_UNSUPPORTED;
break;
}
}
};
/**
* If there is tracks information in the LoadInfo, it loads the side loaded
* tracks information in the media manager without loading media.
*
* @param {!cast.receiver.MediaManager.LoadInfo} info The load request info.
* @private
*/
sampleplayer.CastPlayer.prototype.maybeLoadSideLoadedTracksMetadata_ =
function(info) {
// If there are no tracks we will not load the tracks information here as
// we are likely in a embedded captions scenario and the information will
// be loaded in the onMetadataLoaded_ callback
if (!info.message || !info.message.media || !info.message.media.tracks ||
info.message.media.tracks.length == 0) {
return;
}
var tracksInfo = /** @type {cast.receiver.media.TracksInfo} **/ ({
tracks: info.message.media.tracks,
activeTrackIds: info.message.activeTrackIds,
textTrackStyle: info.message.media.textTrackStyle
});
this.mediaManager_.loadTracksInfo(tracksInfo);
};
/**
* Loads embedded tracks information without loading media.
* If there is embedded tracks information, it loads the tracks information
* in the media manager without loading media.
*
* @param {!cast.receiver.MediaManager.LoadInfo} info The load request info.
* @private
*/
sampleplayer.CastPlayer.prototype.maybeLoadEmbeddedTracksMetadata_ =
function(info) {
if (!info.message || !info.message.media) {
return;
}
var tracksInfo = this.readInBandTracksInfo_();
if (tracksInfo) {
this.textTrackType_ = sampleplayer.TextTrackType.EMBEDDED;
tracksInfo.textTrackStyle = info.message.media.textTrackStyle;
this.mediaManager_.loadTracksInfo(tracksInfo);
}
};
/**
* Processes ttml tracks and enables the active ones.
*
* @param {!Array.<number>} activeTrackIds The active tracks.
* @param {!Array.<cast.receiver.media.Track>} tracks The track definitions.
* @private
*/
sampleplayer.CastPlayer.prototype.processTtmlCues_ =
function(activeTrackIds, tracks) {
if (activeTrackIds.length == 0) {
return;
}
// If there is an active text track, that is using ttml, apply it
for (var i = 0; i < tracks.length; i++) {
var contains = false;
for (var j = 0; j < activeTrackIds.length; j++) {
if (activeTrackIds[j] == tracks[i].trackId) {
contains = true;
break;
}
}
if (!contains ||
!this.isTtmlTrack_(tracks[i])) {
continue;
}
if (!this.player_) {
// We do not have a player, it means we need to create it to support
// loading ttml captions
var host = new cast.player.api.Host({
'url': '',
'mediaElement': this.mediaElement_
});