forked from googleads/videojs-ima
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvideojs.ima.js
1452 lines (1300 loc) · 46.8 KB
/
videojs.ima.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.
*
* 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.
*
* IMA SDK integration plugin for Video.js. For more information see
* https://www.github.com/googleads/videojs-ima
*/
(function(factory) {
if (typeof define === 'function' && define['amd']) {
define(['video.js', 'videojs-contrib-ads'], function(videojs){ factory(window, document, videojs) });
} else if (typeof exports === 'object' && typeof module === 'object') {
var vjs = require('video.js');
require('videojs-contrib-ads');
factory(window, document, vjs);
} else {
factory(window, document, videojs);
}
})(function(window, document, videojs) {
"use strict";
var extend = function(obj) {
var arg;
var index;
var key;
for (index = 1; index < arguments.length; index++) {
arg = arguments[index];
for (key in arg) {
if (arg.hasOwnProperty(key)) {
obj[key] = arg[key];
}
}
}
return obj;
};
var ima_defaults = {
debug: false,
timeout: 5000,
prerollTimeout: 100,
adLabel: 'Advertisement',
showControlsForJSAds: true
};
var init = function(options, readyCallback) {
this.ima = new ImaPlugin(this, options, readyCallback);
};
var ImaPlugin = function(player, options, readyCallback) {
this.player = player;
/**
* Assigns the unique id and class names to the given element as well as the style class
* @param element
* @param controlName
* @private
*/
var assignControlAttributes_ = function(element, controlName) {
element.id = this.controlPrefix + controlName;
element.className = this.controlPrefix + controlName + ' ' + controlName;
}.bind(this);
/**
* Returns a regular expression to test a string for the given className
* @param className
* @returns {RegExp}
* @private
*/
var getClassRegexp_ = function(className){
// Matches on
// (beginning of string OR NOT word char)
// classname
// (negative lookahead word char OR end of string)
return new RegExp('(^|[^A-Za-z-])' + className + '((?![A-Za-z-])|$)', 'gi');
};
/**
* Adds a class to the given element if it doesn't already have the class
* @param element
* @param classToAdd
* @private
*/
var addClass_ = function(element, classToAdd){
if(getClassRegexp_(classToAdd).test(element.className)){
return element;
}
return element.className = element.className.trim() + ' ' + classToAdd;
};
/**
* Removes a class from the given element if it has the given class
* @param element
* @param classToRemove
* @private
*/
var removeClass_ = function(element, classToRemove){
var classRegexp = getClassRegexp_(classToRemove);
if(!classRegexp.test(element.className)){
return element;
}
return element.className = element.className.trim().replace(classRegexp, '');
};
/**
* Creates the ad container passed to the IMA SDK.
* @private
*/
var createAdContainer_ = function() {
// The adContainerDiv is the DOM of the element that will house
// the ads and ad controls.
this.vjsControls = this.player.getChild('controlBar');
this.adContainerDiv =
this.vjsControls.el().parentNode.appendChild(
document.createElement('div'));
assignControlAttributes_(this.adContainerDiv, 'ima-ad-container');
this.adContainerDiv.style.position = "absolute";
this.adContainerDiv.style.zIndex = 1111;
this.adContainerDiv.addEventListener(
'mouseenter',
showAdControls_,
false);
this.adContainerDiv.addEventListener(
'mouseleave',
hideAdControls_,
false);
createControls_();
this.adDisplayContainer =
new google.ima.AdDisplayContainer(this.adContainerDiv, this.contentPlayer);
}.bind(this);
/**
* Creates the controls for the ad.
* @private
*/
var createControls_ = function() {
this.controlsDiv = document.createElement('div');
assignControlAttributes_(this.controlsDiv, 'ima-controls-div');
this.controlsDiv.style.width = '100%';
this.countdownDiv = document.createElement('div');
assignControlAttributes_(this.countdownDiv, 'ima-countdown-div');
this.countdownDiv.innerHTML = this.settings.adLabel;
this.countdownDiv.style.display = this.showCountdown ? 'block' : 'none';
this.seekBarDiv = document.createElement('div');
assignControlAttributes_(this.seekBarDiv, 'ima-seek-bar-div');
this.seekBarDiv.style.width = '100%';
this.progressDiv = document.createElement('div');
assignControlAttributes_(this.progressDiv, 'ima-progress-div');
this.playPauseDiv = document.createElement('div');
assignControlAttributes_(this.playPauseDiv, 'ima-play-pause-div');
addClass_(this.playPauseDiv, 'ima-playing');
this.playPauseDiv.addEventListener(
'click',
onAdPlayPauseClick_,
false);
this.muteDiv = document.createElement('div');
assignControlAttributes_(this.muteDiv, 'ima-mute-div');
addClass_(this.muteDiv, 'ima-non-muted');
this.muteDiv.addEventListener(
'click',
onAdMuteClick_,
false);
this.sliderDiv = document.createElement('div');
assignControlAttributes_(this.sliderDiv, 'ima-slider-div');
this.sliderDiv.addEventListener(
'mousedown',
onAdVolumeSliderMouseDown_,
false);
this.sliderLevelDiv = document.createElement('div');
assignControlAttributes_(this.sliderLevelDiv, 'ima-slider-level-div');
this.fullscreenDiv = document.createElement('div');
assignControlAttributes_(this.fullscreenDiv, 'ima-fullscreen-div');
addClass_(this.fullscreenDiv, 'ima-non-fullscreen');
this.fullscreenDiv.addEventListener(
'click',
onAdFullscreenClick_,
false);
this.adContainerDiv.appendChild(this.controlsDiv);
this.controlsDiv.appendChild(this.countdownDiv);
this.controlsDiv.appendChild(this.seekBarDiv);
this.controlsDiv.appendChild(this.playPauseDiv);
this.controlsDiv.appendChild(this.muteDiv);
this.controlsDiv.appendChild(this.sliderDiv);
this.controlsDiv.appendChild(this.fullscreenDiv);
this.seekBarDiv.appendChild(this.progressDiv);
this.sliderDiv.appendChild(this.sliderLevelDiv);
}.bind(this);
/**
* Initializes the AdDisplayContainer. On mobile, this must be done as a
* result of user action.
*/
this.initializeAdDisplayContainer = function() {
this.adDisplayContainerInitialized = true;
this.adDisplayContainer.initialize();
}.bind(this);
/**
* Creates the AdsRequest and request ads through the AdsLoader.
*/
this.requestAds = function() {
if (!this.adDisplayContainerInitialized) {
this.adDisplayContainer.initialize();
}
var adsRequest = new google.ima.AdsRequest();
if (this.settings.adTagUrl) {
adsRequest.adTagUrl = this.settings.adTagUrl;
} else {
adsRequest.adsResponse = this.settings.adsResponse;
}
if (this.settings.forceNonLinearFullSlot) {
adsRequest.forceNonLinearFullSlot = true;
}
adsRequest.linearAdSlotWidth = this.getPlayerWidth();
adsRequest.linearAdSlotHeight = this.getPlayerHeight();
adsRequest.nonLinearAdSlotWidth =
this.settings.nonLinearWidth || this.getPlayerWidth();
adsRequest.nonLinearAdSlotHeight =
this.settings.nonLinearHeight || (this.getPlayerHeight() / 3);
adsRequest.setAdWillAutoPlay(this.settings.adWillAutoPlay);
this.adsLoader.requestAds(adsRequest);
}.bind(this);
/**
* Listener for the ADS_MANAGER_LOADED event. Creates the AdsManager,
* sets up event listeners, and triggers the 'adsready' event for
* videojs-ads-contrib.
* @private
*/
var onAdsManagerLoaded_ = function(adsManagerLoadedEvent) {
this.adsManager = adsManagerLoadedEvent.getAdsManager(
this.contentPlayheadTracker, this.adsRenderingSettings);
this.adsManager.addEventListener(
google.ima.AdErrorEvent.Type.AD_ERROR,
onAdError_);
this.adsManager.addEventListener(
google.ima.AdEvent.Type.AD_BREAK_READY,
onAdBreakReady_);
this.adsManager.addEventListener(
google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,
this.onContentPauseRequested_);
this.adsManager.addEventListener(
google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
this.onContentResumeRequested_);
this.adsManager.addEventListener(
google.ima.AdEvent.Type.ALL_ADS_COMPLETED,
onAllAdsCompleted_);
this.adsManager.addEventListener(
google.ima.AdEvent.Type.LOADED,
onAdLoaded_);
this.adsManager.addEventListener(
google.ima.AdEvent.Type.STARTED,
onAdStarted_);
this.adsManager.addEventListener(
google.ima.AdEvent.Type.CLICK,
onAdPlayPauseClick_);
this.adsManager.addEventListener(
google.ima.AdEvent.Type.COMPLETE,
this.onAdComplete_);
this.adsManager.addEventListener(
google.ima.AdEvent.Type.SKIPPED,
this.onAdComplete_);
if (!this.autoPlayAdBreaks) {
try {
var initWidth = this.getPlayerWidth();
var initHeight = this.getPlayerHeight();
this.adsManagerDimensions.width = initWidth;
this.adsManagerDimensions.height = initHeight;
this.adsManager.init(
initWidth,
initHeight,
google.ima.ViewMode.NORMAL);
this.adsManager.setVolume(this.player.muted() ? 0 : this.player.volume());
} catch (adError) {
onAdError_(adError);
}
}
this.player.trigger('adsready');
}.bind(this);
/**
* DEPRECATED: Use startFromReadyCallback
* Start ad playback, or content video playback in the absence of a
* pre-roll.
*/
this.start = function() {
window.console.log(
'WARNING: player.ima.start is deprecated. Use ' +
'player.ima.startFromReadyCallback instead.');
};
/**
* Start ad playback, or content video playback in the absence of a
* pre-roll. **NOTE**: This method only needs to be called if you provide
* your own readyCallback as the second parameter to player.ima(). If you
* only provide options and do not provide your own readyCallback,
* **DO NOT** call this method. If you do provide your own readyCallback,
* you should call this method in the last line of that callback. For more
* info, see this method's usage in our advanced and playlist examples.
*/
this.startFromReadyCallback = function() {
if (this.autoPlayAdBreaks) {
try {
this.adsManager.init(
this.getPlayerWidth(),
this.getPlayerHeight(),
google.ima.ViewMode.NORMAL);
this.adsManager.setVolume(this.player.muted() ? 0 : this.player.volume());
this.adsManager.start();
} catch (adError) {
onAdError_(adError);
}
}
}.bind(this);
/**
* Listener for errors fired by the AdsLoader.
* @param {google.ima.AdErrorEvent} event The error event thrown by the
* AdsLoader. See
* https://developers.google.com/interactive-media-ads/docs/sdks/html5/v3/apis#ima.AdError.Type
* @private
*/
var onAdsLoaderError_ = function(event) {
window.console.log('AdsLoader error: ' + event.getError());
this.adContainerDiv.style.display = 'none';
if (this.adsManager) {
this.adsManager.destroy();
}
this.player.trigger({type: 'adserror', data: { AdError: event.getError(), AdErrorEvent: event }});
}.bind(this);
/**
* Listener for errors thrown by the AdsManager.
* @param {google.ima.AdErrorEvent} adErrorEvent The error event thrown by
* the AdsManager.
* @private
*/
var onAdError_ = function(adErrorEvent) {
var errorMessage = adErrorEvent.getError !== undefined ? adErrorEvent.getError() : adErrorEvent.stack;
window.console.log('Ad error: ' + errorMessage);
this.vjsControls.show();
this.adsManager.destroy();
this.adContainerDiv.style.display = 'none';
this.player.trigger({ type: 'adserror', data: { AdError: errorMessage, AdErrorEvent: adErrorEvent }});
}.bind(this);
/**
* Listener for AD_BREAK_READY. Passes event on to publisher's listener.
* @param {google.ima.AdEvent} adEvent AdEvent thrown by the AdsManager.
* @private
*/
var onAdBreakReady_ = function(adEvent) {
this.adBreakReadyListener(adEvent);
}.bind(this);
/**
* Called by publishers in manual ad break playback mode to start an ad
* break.
*/
this.playAdBreak = function() {
if (!this.autoPlayAdBreaks) {
this.adsManager.start();
}
}.bind(this);
/**
* Pauses the content video and displays the ad container so ads can play.
* @param {google.ima.AdEvent} adEvent The AdEvent thrown by the AdsManager.
* @private
*/
this.onContentPauseRequested_ = function(adEvent) {
this.adsActive = true;
this.adPlaying = true;
this.contentSource = this.player.currentSrc();
this.player.off('ended', this.localContentEndedListener);
if (adEvent.getAd().getAdPodInfo().getPodIndex() != -1) {
// Skip this call for post-roll ads
this.player.ads.startLinearAdMode();
}
this.adContainerDiv.style.display = 'block';
var contentType = adEvent.getAd().getContentType();
if ((contentType === 'application/javascript') && !this.settings.showControlsForJSAds) {
this.controlsDiv.style.display = 'none';
} else {
this.controlsDiv.style.display = 'block';
}
this.vjsControls.hide();
showPlayButton();
this.player.pause();
}.bind(this);
/**
* Resumes content video and hides the ad container.
* @param {google.ima.AdEvent} adEvent The AdEvent thrown by the AdsManager.
* @private
*/
this.onContentResumeRequested_ = function(adEvent) {
this.adsActive = false;
this.adPlaying = false;
this.player.on('ended', this.localContentEndedListener);
if (this.currentAd == null || // hide for post-roll only playlist
this.currentAd.isLinear()) { // don't hide for non-linear ads
this.adContainerDiv.style.display = 'none';
}
this.vjsControls.show();
if (!this.currentAd) {
// Something went wrong playing the ad
this.player.ads.endLinearAdMode();
} else if (!this.contentComplete &&
// Don't exit linear mode after post-roll or content will auto-replay
this.currentAd.getAdPodInfo().getPodIndex() != -1 ) {
this.player.ads.endLinearAdMode();
}
// Hide controls in case of future non-linear ads. They'll be unhidden in
// content_pause_requested.
this.controlsDiv.style.display = 'none';
this.countdownDiv.innerHTML = '';
}.bind(this);
/**
* Records that ads have completed and calls contentAndAdsEndedListeners
* if content is also complete.
* @param {google.ima.AdEvent} adEvent The AdEvent thrown by the AdsManager.
* @private
*/
var onAllAdsCompleted_ = function(adEvent) {
this.allAdsCompleted = true;
this.adContainerDiv.style.display = 'none';
if (this.contentComplete == true) {
if (this.contentPlayer.src != this.contentSource) {
this.player.src(this.contentSource);
}
for (var index in this.contentAndAdsEndedListeners) {
this.contentAndAdsEndedListeners[index]();
}
}
}.bind(this);
/**
* Starts the content video when a non-linear ad is loaded.
* @param {google.ima.AdEvent} adEvent The AdEvent thrown by the AdsManager.
* @private
*/
var onAdLoaded_ = function(adEvent) {
if (!adEvent.getAd().isLinear()) {
this.player.play();
}
}.bind(this);
/**
* Starts the interval timer to check the current ad time when an ad starts
* playing.
* @param {google.ima.AdEvent} adEvent The AdEvent thrown by the AdsManager.
* @private
*/
var onAdStarted_ = function(adEvent) {
this.currentAd = adEvent.getAd();
if (this.currentAd.isLinear()) {
this.adTrackingTimer = setInterval(
onAdPlayheadTrackerInterval_, 250);
// Don't bump container when controls are shown
removeClass_(this.adContainerDiv, 'bumpable-ima-ad-container');
} else {
// Bump container when controls are shown
addClass_(this.adContainerDiv, 'bumpable-ima-ad-container');
}
// For non-linear ads that show after a linear ad.
this.adContainerDiv.style.display = 'block';
}.bind(this);
/**
* Clears the interval timer for current ad time when an ad completes.
* @param {google.ima.AdEvent} adEvent The AdEvent thrown by the AdsManager.
* @private
*/
this.onAdComplete_ = function(adEvent) {
if (this.currentAd.isLinear()) {
clearInterval(this.adTrackingTimer);
}
}.bind(this);
/**
* Gets the current time and duration of the ad and calls the method to
* update the ad UI.
* @private
*/
var onAdPlayheadTrackerInterval_ = function() {
var remainingTime = this.adsManager.getRemainingTime();
var duration = this.currentAd.getDuration();
var currentTime = duration - remainingTime;
currentTime = currentTime > 0 ? currentTime : 0;
var isPod = false;
var totalAds = 0;
var adPosition;
if (this.currentAd.getAdPodInfo()) {
isPod = true;
adPosition = this.currentAd.getAdPodInfo().getAdPosition();
totalAds = this.currentAd.getAdPodInfo().getTotalAds();
}
// Update countdown timer data
var remainingMinutes = Math.floor(remainingTime / 60);
var remainingSeconds = Math.floor(remainingTime % 60);
if (remainingSeconds.toString().length < 2) {
remainingSeconds = '0' + remainingSeconds;
}
var podCount = ': ';
if (isPod && (totalAds > 1)) {
podCount = ' (' + adPosition + ' of ' + totalAds + '): ';
}
this.countdownDiv.innerHTML =
this.settings.adLabel + podCount +
remainingMinutes + ':' + remainingSeconds;
// Update UI
var playProgressRatio = currentTime / duration;
var playProgressPercent = playProgressRatio * 100;
this.progressDiv.style.width = playProgressPercent + '%';
}.bind(this);
this.getPlayerWidth = function() {
var computedStyle = getComputedStyle(this.player.el()) || {};
return parseInt(computedStyle.width, 10) || this.player.width();
}.bind(this);
this.getPlayerHeight = function() {
var computedStyle = getComputedStyle(this.player.el()) || {};
return parseInt(computedStyle.height, 10) || this.player.height();
}.bind(this);
/**
* Hides the ad controls on mouseout.
* @private
*/
var hideAdControls_ = function() {
this.controlsDiv.style.height = '14px';
this.playPauseDiv.style.display = 'none';
this.muteDiv.style.display = 'none';
this.sliderDiv.style.display = 'none';
this.fullscreenDiv.style.display = 'none';
}.bind(this);
/**
* Shows ad controls on mouseover.
* @private
*/
var showAdControls_ = function() {
this.controlsDiv.style.height = '37px';
this.playPauseDiv.style.display = 'block';
this.muteDiv.style.display = 'block';
this.sliderDiv.style.display = 'block';
this.fullscreenDiv.style.display = 'block';
}.bind(this);
/**
* Show pause and hide play button
*/
var showPauseButton = function() {
addClass_(this.playPauseDiv, 'ima-paused');
removeClass_(this.playPauseDiv, 'ima-playing');
}.bind(this);
/**
* Show play and hide pause button
*/
var showPlayButton = function() {
addClass_(this.playPauseDiv, 'ima-playing');
removeClass_(this.playPauseDiv, 'ima-paused');
}.bind(this);
/**
* Listener for clicks on the play/pause button during ad playback.
* @private
*/
var onAdPlayPauseClick_ = function() {
if (this.adPlaying) {
showPauseButton();
this.adsManager.pause();
this.adPlaying = false;
} else {
showPlayButton();
this.adsManager.resume();
this.adPlaying = true;
}
}.bind(this);
/**
* Listener for clicks on the mute button during ad playback.
* @private
*/
var onAdMuteClick_ = function() {
if (this.adMuted) {
addClass_(this.muteDiv, 'ima-non-muted');
removeClass_(this.muteDiv, 'ima-muted');
this.adsManager.setVolume(1);
// Bubble down to content player
this.player.muted(false);
this.adMuted = false;
this.sliderLevelDiv.style.width = this.player.volume() * 100 + "%";
} else {
addClass_(this.muteDiv, 'ima-muted');
removeClass_(this.muteDiv, 'ima-non-muted');
this.adsManager.setVolume(0);
// Bubble down to content player
this.player.muted(true);
this.adMuted = true;
this.sliderLevelDiv.style.width = "0%";
}
}.bind(this);
/* Listener for mouse down events during ad playback. Used for volume.
* @private
*/
var onAdVolumeSliderMouseDown_ = function() {
document.addEventListener('mouseup', onMouseUp_, false);
document.addEventListener('mousemove', onMouseMove_, false);
};
/* Mouse movement listener used for volume slider.
* @private
*/
var onMouseMove_ = function(event) {
setVolumeSlider_(event);
};
/* Mouse release listener used for volume slider.
* @private
*/
var onMouseUp_ = function(event) {
setVolumeSlider_(event);
document.removeEventListener('mousemove', onMouseMove_);
document.removeEventListener('mouseup', onMouseUp_);
};
/* Utility function to set volume and associated UI
* @private
*/
var setVolumeSlider_ = function(event) {
var percent =
(event.clientX - this.sliderDiv.getBoundingClientRect().left) /
this.sliderDiv.offsetWidth;
percent *= 100;
//Bounds value 0-100 if mouse is outside slider region.
percent = Math.min(Math.max(percent, 0), 100);
this.sliderLevelDiv.style.width = percent + "%";
this.player.volume(percent / 100); //0-1
this.adsManager.setVolume(percent / 100);
if (this.player.volume() == 0) {
addClass_(this.muteDiv, 'ima-muted');
removeClass_(this.muteDiv, 'ima-non-muted');
this.player.muted(true);
this.adMuted = true;
}
else
{
addClass_(this.muteDiv, 'ima-non-muted');
removeClass_(this.muteDiv, 'ima-muted');
this.player.muted(false);
this.adMuted = false;
}
}.bind(this);
/**
* Listener for clicks on the fullscreen button during ad playback.
* @private
*/
var onAdFullscreenClick_ = function() {
if (this.player.isFullscreen()) {
this.player.exitFullscreen();
} else {
this.player.requestFullscreen();
}
}.bind(this);
/**
* Listens for the video.js player to change its fullscreen status. This
* keeps the fullscreen-ness of the AdContainer in sync with the player.
* @private
*/
var onFullscreenChange_ = function() {
if (this.player.isFullscreen()) {
addClass_(this.fullscreenDiv, 'ima-fullscreen');
removeClass_(this.fullscreenDiv, 'ima-non-fullscreen');
if (this.adsManager) {
this.adsManager.resize(
window.screen.width,
window.screen.height,
google.ima.ViewMode.FULLSCREEN);
}
} else {
addClass_(this.fullscreenDiv, 'ima-non-fullscreen');
removeClass_(this.fullscreenDiv, 'ima-fullscreen');
if (this.adsManager) {
this.adsManager.resize(
this.getPlayerWidth(),
this.getPlayerHeight(),
google.ima.ViewMode.NORMAL);
}
}
}.bind(this);
/**
* Listens for the video.js player to change its volume. This keeps the ad
* volume in sync with the content volume if the volume of the player is
* changed while content is playing
* @private
*/
var onVolumeChange_ = function() {
var newVolume = this.player.muted() ? 0 : this.player.volume();
if (this.adsManager) {
this.adsManager.setVolume(newVolume);
}
// Update UI
if (newVolume == 0) {
this.adMuted = true;
addClass_(this.muteDiv, 'ima-muted');
removeClass_(this.muteDiv, 'ima-non-muted');
this.sliderLevelDiv.style.width = '0%';
} else {
this.adMuted = false;
addClass_(this.muteDiv, 'ima-non-muted');
removeClass_(this.muteDiv, 'ima-muted');
this.sliderLevelDiv.style.width = newVolume * 100 + '%';
}
}.bind(this);
/**
* Seeks content to 00:00:00. This is used as an event handler for the
* loadedmetadata event, since seeking is not possible until that event has
* fired.
* @private
*/
var seekContentToZero_ = function() {
this.player.off('loadedmetadata', seekContentToZero_);
this.player.currentTime(0);
}.bind(this);
/**
* Seeks content to 00:00:00 and starts playback. This is used as an event
* handler for the loadedmetadata event, since seeking is not possible until
* that event has fired.
* @private
*/
var playContentFromZero_ = function() {
this.player.off('loadedmetadata', playContentFromZero_);
this.player.currentTime(0);
this.player.play();
}.bind(this);
/**
* Destroys the AdsManager, sets it to null, and calls contentComplete to
* reset correlators. Once this is done it requests ads again to keep the
* inventory available.
* @private
*/
var resetIMA_ = function() {
this.adsActive = false;
this.adPlaying = false;
this.player.on('ended', this.localContentEndedListener);
this.vjsControls.show();
this.player.ads.endLinearAdMode();
if (this.adTrackingTimer) {
// If this is called while an ad is playing, stop trying to get that
// ad's current time.
clearInterval(this.adTrackingTimer);
}
// Reset the content time we give the SDK. Fixes an issue where requesting
// VMAP followed by VMAP would play the second mid-rolls as pre-rolls if
// the first playthrough of the video passed the second response's
// mid-roll time.
this.contentPlayheadTracker.currentTime = 0;
if (this.adsManager) {
this.adsManager.destroy();
this.adsManager = null;
}
if (this.adsLoader && !this.contentComplete) {
this.adsLoader.contentComplete();
}
this.contentComplete = false;
this.allAdsCompleted = false;
}.bind(this);
/**
* Ads an EventListener to the AdsManager. For a list of available events,
* see
* https://developers.google.com/interactive-media-ads/docs/sdks/html5/v3/apis#ima.AdEvent.Type
* @param {google.ima.AdEvent.Type} event The AdEvent.Type for which to listen.
* @param {function} callback The method to call when the event is fired.
*/
this.addEventListener = function(event, callback) {
if (this.adsManager) {
this.adsManager.addEventListener(event, callback);
}
}.bind(this);
/**
* Returns the instance of the AdsManager.
* @return {google.ima.AdsManager} The AdsManager being used by the plugin.
*/
this.getAdsManager = function() {
return this.adsManager;
}.bind(this);
/**
* DEPRECATED: Use setContentWithAdTag.
* Sets the content of the video player. You should use this method instead
* of setting the content src directly to ensure the proper ad tag is
* requested when the video content is loaded.
* @param {?string} contentSrc The URI for the content to be played. Leave
* blank to use the existing content.
* @param {?string} adTag The ad tag to be requested when the content loads.
* Leave blank to use the existing ad tag.
* @param {?boolean} playOnLoad True to play the content once it has loaded,
* false to only load the content but not start playback.
*/
this.setContent = function(contentSrc, adTag, playOnLoad) {
window.console.log(
'WARNING: player.ima.setContent is deprecated. Use ' +
'player.ima.setContentWithAdTag instead.');
this.setContentWithAdTag(contentSrc, adTag, playOnLoad);
}.bind(this);
/**
* Sets the content of the video player. You should use this method instead
* of setting the content src directly to ensure the proper ad tag is
* requested when the video content is loaded.
* @param {?string} contentSrc The URI for the content to be played. Leave
* blank to use the existing content.
* @param {?string} adTag The ad tag to be requested when the content loads.
* Leave blank to use the existing ad tag.
* @param {?boolean} playOnLoad True to play the content once it has loaded,
* false to only load the content but not start playback.
*/
this.setContentWithAdTag = function(contentSrc, adTag, playOnLoad) {
resetIMA_();
this.settings.adTagUrl = adTag ? adTag : this.settings.adTagUrl;
changeSource_(contentSrc, playOnLoad);
}.bind(this);
/**
* Sets the content of the video player. You should use this method instead
* of setting the content src directly to ensure the proper ads response is
* used when the video content is loaded.
* @param {?string} contentSrc The URI for the content to be played. Leave
* blank to use the existing content.
* @param {?string} adsResponse The ads response to be requested when the
* content loads. Leave blank to use the existing ads response.
* @param {?boolean} playOnLoad True to play the content once it has loaded,
* false to only load the content but not start playback.
*/
this.setContentWithAdsResponse = function(contentSrc, adsResponse, playOnLoad) {
resetIMA_();
this.settings.adsResponse = adsResponse ? adsResponse : this.settings.adsResponse;
changeSource_(contentSrc, playOnLoad);
}.bind(this);
/**
* Changes the ad tag. You will need to call requestAds after this method
* for the new ads to be requested.
* @param {?string} adTag The ad tag to be requested the next time requestAds
* is called.
*/
this.changeAdTag = function(adTag) {
resetIMA_();
this.settings.adTagUrl = adTag;
}.bind(this);
/**
* Changes the player source.
* @param {?string} contentSrc The URI for the content to be played. Leave
* blank to use the existing content.
* @param {?boolean} playOnLoad True to play the content once it has loaded,
* false to only load the content but not start playback.
* @private
*/
var changeSource_ = function(contentSrc, playOnLoad) {
// Only try to pause the player when initialised with a source already
if (!!this.player.currentSrc()) {
this.player.currentTime(0);
this.player.pause();
}
if (contentSrc) {
this.player.src(contentSrc);
}
if (playOnLoad) {
this.player.on('loadedmetadata', playContentFromZero_);
} else {
this.player.on('loadedmetadata', seekContentToZero_);
}
}.bind(this);
/**
* Adds a listener for the 'ended' event of the video player. This should be
* used instead of setting an 'ended' listener directly to ensure that the
* ima can do proper cleanup of the SDK before other event listeners
* are called.
* @param {function} listener The listener to be called when content completes.
*/
this.addContentEndedListener = function(listener) {
this.contentEndedListeners.push(listener);
}.bind(this);
/**
* Adds a listener that will be called when content and all ads have
* finished playing.
* @param {function} listener The listener to be called when content and ads complete.
*/
this.addContentAndAdsEndedListener = function(listener) {
this.contentAndAdsEndedListeners.push(listener);
}.bind(this);
/**
* Sets the listener to be called to trigger manual ad break playback.
* @param {function} listener The listener to be called to trigger manual ad break playback.
*/
this.setAdBreakReadyListener = function(listener) {
this.adBreakReadyListener = listener;
}.bind(this);
/**
* Pauses the ad.
*/
this.pauseAd = function() {
if (this.adsActive && this.adPlaying) {
showPauseButton();
this.adsManager.pause();
this.adPlaying = false;
}
}.bind(this);
/**
* Resumes the ad.
*/
this.resumeAd = function() {
if (this.adsActive && !this.adPlaying) {
showPlayButton();
this.adsManager.resume();
this.adPlaying = true;
}
}.bind(this);
/**
* Set up intervals to check for seeking and update current video time.
* @private
*/
var setUpPlayerIntervals_ = function() {
this.updateTimeIntervalHandle =
setInterval(updateCurrentTime_, this.seekCheckInterval);
this.seekCheckIntervalHandle =
setInterval(checkForSeeking_, this.seekCheckInterval);
this.resizeCheckIntervalHandle =
setInterval(checkForResize_, this.resizeCheckInterval);
}.bind(this);
/**
* Updates the current time of the video
* @private
*/
var updateCurrentTime_ = function() {
if (!this.contentPlayheadTracker.seeking) {
this.contentPlayheadTracker.currentTime = this.player.currentTime();
}
}.bind(this);
/**
* Detects when the user is seeking through a video.
* This is used to prevent mid-rolls from playing while a user is seeking.
*
* There *is* a seeking property of the HTML5 video element, but it's not
* properly implemented on all platforms (e.g. mobile safari), so we have to
* check ourselves to be sure.
*
* @private
*/
var checkForSeeking_ = function() {
var tempCurrentTime = this.player.currentTime();