This repository has been archived by the owner on Jan 16, 2023. It is now read-only.
forked from Dash-Industry-Forum/dash.js
/
MediaPlayer.js
2296 lines (2069 loc) · 83.7 KB
/
MediaPlayer.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
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import cea608parser from '../../externals/cea608-parser';
import Constants from './constants/Constants';
import DashConstants from '../dash/constants/DashConstants';
import MetricsConstants from './constants/MetricsConstants';
import PlaybackController from './controllers/PlaybackController';
import StreamController from './controllers/StreamController';
import MediaController from './controllers/MediaController';
import BaseURLController from './controllers/BaseURLController';
import ManifestLoader from './ManifestLoader';
import ErrorHandler from './utils/ErrorHandler';
import Capabilities from './utils/Capabilities';
import TextTracks from './text/TextTracks';
import RequestModifier from './utils/RequestModifier';
import TextController from './text/TextController';
import URIFragmentModel from './models/URIFragmentModel';
import ManifestModel from './models/ManifestModel';
import MediaPlayerModel from './models/MediaPlayerModel';
import AbrController from './controllers/AbrController';
import SchemeLoaderFactory from './net/SchemeLoaderFactory';
import VideoModel from './models/VideoModel';
import CmcdModel from './models/CmcdModel';
import DOMStorage from './utils/DOMStorage';
import Debug from './../core/Debug';
import Errors from './../core/errors/Errors';
import EventBus from './../core/EventBus';
import Events from './../core/events/Events';
import MediaPlayerEvents from './MediaPlayerEvents';
import FactoryMaker from '../core/FactoryMaker';
import Settings from '../core/Settings';
import {
getVersionString
}
from './../core/Version';
//Dash
import SegmentBaseController from '../dash/controllers/SegmentBaseController';
import DashAdapter from '../dash/DashAdapter';
import DashMetrics from '../dash/DashMetrics';
import TimelineConverter from '../dash/utils/TimelineConverter';
import {
HTTPRequest
} from './vo/metrics/HTTPRequest';
import BASE64 from '../../externals/base64';
import ISOBoxer from 'codem-isoboxer';
import DashJSError from './vo/DashJSError';
import { checkParameterType } from './utils/SupervisorTools';
import ManifestUpdater from './ManifestUpdater';
import URLUtils from '../streaming/utils/URLUtils';
import BoxParser from './utils/BoxParser';
/* jscs:disable */
/**
* The media types
* @typedef {("video" | "audio" | "text" | "fragmentedText" | "embeddedText" | "image")} MediaType
*/
/* jscs:enable */
/**
* @module MediaPlayer
* @description The MediaPlayer is the primary dash.js Module and a Facade to build your player around.
* It will allow you access to all the important dash.js properties/methods via the public API and all the
* events to build a robust DASH media player.
*/
function MediaPlayer() {
/**
* @constant {string} STREAMING_NOT_INITIALIZED_ERROR error string thrown when a function is called before the dash.js has been fully initialized
* @inner
*/
const STREAMING_NOT_INITIALIZED_ERROR = 'You must first call initialize() and set a source before calling this method';
/**
* @constant {string} PLAYBACK_NOT_INITIALIZED_ERROR error string thrown when a function is called before the dash.js has been fully initialized
* @inner
*/
const PLAYBACK_NOT_INITIALIZED_ERROR = 'You must first call initialize() and set a valid source and view before calling this method';
/**
* @constant {string} ELEMENT_NOT_ATTACHED_ERROR error string thrown when a function is called before the dash.js has received a reference of an HTML5 video element
* @inner
*/
const ELEMENT_NOT_ATTACHED_ERROR = 'You must first call attachView() to set the video element before calling this method';
/**
* @constant {string} SOURCE_NOT_ATTACHED_ERROR error string thrown when a function is called before the dash.js has received a valid source stream.
* @inner
*/
const SOURCE_NOT_ATTACHED_ERROR = 'You must first call attachSource() with a valid source before calling this method';
/**
* @constant {string} MEDIA_PLAYER_NOT_INITIALIZED_ERROR error string thrown when a function is called before the dash.js has been fully initialized.
* @inner
*/
const MEDIA_PLAYER_NOT_INITIALIZED_ERROR = 'MediaPlayer not initialized!';
const context = this.context;
const eventBus = EventBus(context).getInstance();
let settings = Settings(context).getInstance();
const debug = Debug(context).getInstance({settings: settings});
let instance,
logger,
source,
protectionData,
mediaPlayerInitialized,
streamingInitialized,
playbackInitialized,
autoPlay,
abrController,
schemeLoaderFactory,
timelineConverter,
mediaController,
protectionController,
metricsReportingController,
mssHandler,
offlineController,
adapter,
mediaPlayerModel,
errHandler,
baseURLController,
capabilities,
streamController,
playbackController,
dashMetrics,
manifestModel,
cmcdModel,
videoModel,
textController,
uriFragmentModel,
domStorage,
segmentBaseController;
/*
---------------------------------------------------------------------------
INIT FUNCTIONS
---------------------------------------------------------------------------
*/
function setup() {
logger = debug.getLogger(instance);
mediaPlayerInitialized = false;
playbackInitialized = false;
streamingInitialized = false;
autoPlay = true;
protectionController = null;
offlineController = null;
protectionData = null;
adapter = null;
segmentBaseController = null;
Events.extend(MediaPlayerEvents);
mediaPlayerModel = MediaPlayerModel(context).getInstance();
videoModel = VideoModel(context).getInstance();
uriFragmentModel = URIFragmentModel(context).getInstance();
}
/**
* Configure media player with customs controllers. Helpful for tests
*
* @param {object=} config controllers configuration
* @memberof module:MediaPlayer
* @instance
*/
function setConfig(config) {
if (!config) {
return;
}
if (config.capabilities) {
capabilities = config.capabilities;
}
if (config.streamController) {
streamController = config.streamController;
}
if (config.playbackController) {
playbackController = config.playbackController;
}
if (config.mediaPlayerModel) {
mediaPlayerModel = config.mediaPlayerModel;
}
if (config.abrController) {
abrController = config.abrController;
}
if (config.schemeLoaderFactory) {
schemeLoaderFactory = config.schemeLoaderFactory;
}
if (config.mediaController) {
mediaController = config.mediaController;
}
if (config.settings) {
settings = config.settings;
}
}
/**
* Upon creating the MediaPlayer you must call initialize before you call anything else.
* There is one exception to this rule. It is crucial to call {@link module:MediaPlayer#extend extend()}
* with all your extensions prior to calling initialize.
*
* ALL arguments are optional and there are individual methods to set each argument later on.
* The args in this method are just for convenience and should only be used for a simple player setup.
*
* @param {HTML5MediaElement=} view - Optional arg to set the video element. {@link module:MediaPlayer#attachView attachView()}
* @param {string=} source - Optional arg to set the media source. {@link module:MediaPlayer#attachSource attachSource()}
* @param {boolean=} AutoPlay - Optional arg to set auto play. {@link module:MediaPlayer#setAutoPlay setAutoPlay()}
* @see {@link module:MediaPlayer#attachView attachView()}
* @see {@link module:MediaPlayer#attachSource attachSource()}
* @see {@link module:MediaPlayer#setAutoPlay setAutoPlay()}
* @memberof module:MediaPlayer
* @instance
*/
function initialize(view, source, AutoPlay) {
if (!capabilities) {
capabilities = Capabilities(context).getInstance();
}
errHandler = ErrorHandler(context).getInstance();
if (!capabilities.supportsMediaSource()) {
errHandler.error(new DashJSError(Errors.CAPABILITY_MEDIASOURCE_ERROR_CODE, Errors.CAPABILITY_MEDIASOURCE_ERROR_MESSAGE));
return;
}
if (mediaPlayerInitialized) return;
mediaPlayerInitialized = true;
// init some controllers and models
timelineConverter = TimelineConverter(context).getInstance();
if (!abrController) {
abrController = AbrController(context).getInstance();
abrController.setConfig({
settings: settings
});
}
if (!schemeLoaderFactory) {
schemeLoaderFactory = SchemeLoaderFactory(context).getInstance();
}
if (!playbackController) {
playbackController = PlaybackController(context).getInstance();
}
if (!mediaController) {
mediaController = MediaController(context).getInstance();
}
if (!streamController) {
streamController = StreamController(context).getInstance();
}
adapter = DashAdapter(context).getInstance();
manifestModel = ManifestModel(context).getInstance();
cmcdModel = CmcdModel(context).getInstance();
dashMetrics = DashMetrics(context).getInstance({
settings: settings
});
textController = TextController(context).getInstance();
domStorage = DOMStorage(context).getInstance({
settings: settings
});
adapter.setConfig({
constants: Constants,
cea608parser: cea608parser,
errHandler: errHandler,
BASE64: BASE64
});
if (!baseURLController) {
baseURLController = BaseURLController(context).create();
}
baseURLController.setConfig({
adapter: adapter
});
segmentBaseController = SegmentBaseController(context).getInstance({
dashMetrics: dashMetrics,
mediaPlayerModel: mediaPlayerModel,
errHandler: errHandler,
baseURLController: baseURLController,
events: Events,
eventBus: eventBus,
debug: debug,
boxParser: BoxParser(context).getInstance(),
requestModifier: RequestModifier(context).getInstance(),
errors: Errors
});
segmentBaseController.initialize();
restoreDefaultUTCTimingSources();
setAutoPlay(AutoPlay !== undefined ? AutoPlay : true);
// Detect and initialize offline module to support offline contents playback
detectOffline();
if (view) {
attachView(view);
}
if (source) {
attachSource(source);
}
logger.info('[dash.js ' + getVersion() + '] ' + 'MediaPlayer has been initialized');
}
/**
* Sets the MPD source and the video element to null. You can also reset the MediaPlayer by
* calling attachSource with a new source file.
*
* Calling this method is all that is necessary to destroy a MediaPlayer instance.
*
* @memberof module:MediaPlayer
* @instance
*/
function reset() {
attachSource(null);
attachView(null);
protectionData = null;
if (protectionController) {
protectionController.reset();
protectionController = null;
}
if (metricsReportingController) {
metricsReportingController.reset();
metricsReportingController = null;
}
segmentBaseController.reset();
settings.reset();
if (offlineController) {
offlineController.reset();
offlineController = null;
}
}
/**
* The ready state of the MediaPlayer based on both the video element and MPD source being defined.
*
* @returns {boolean} The current ready state of the MediaPlayer
* @see {@link module:MediaPlayer#attachView attachView()}
* @see {@link module:MediaPlayer#attachSource attachSource()}
* @memberof module:MediaPlayer
* @instance
*/
function isReady() {
return (!!source && !!videoModel.getElement());
}
/**
* Use the on method to listen for public events found in MediaPlayer.events. {@link MediaPlayerEvents}
*
* @param {string} type - {@link MediaPlayerEvents}
* @param {Function} listener - callback method when the event fires.
* @param {Object} scope - context of the listener so it can be removed properly.
* @memberof module:MediaPlayer
* @instance
*/
function on(type, listener, scope) {
eventBus.on(type, listener, scope);
}
/**
* Use the off method to remove listeners for public events found in MediaPlayer.events. {@link MediaPlayerEvents}
*
* @param {string} type - {@link MediaPlayerEvents}
* @param {Function} listener - callback method when the event fires.
* @param {Object} scope - context of the listener so it can be removed properly.
* @memberof module:MediaPlayer
* @instance
*/
function off(type, listener, scope) {
eventBus.off(type, listener, scope);
}
/**
* Current version of Dash.js
* @returns {string} the current dash.js version string.
* @memberof module:MediaPlayer
* @instance
*/
function getVersion() {
return getVersionString();
}
/**
* Use this method to access the dash.js logging class.
*
* @returns {Debug}
* @memberof module:MediaPlayer
* @instance
*/
function getDebug() {
return debug;
}
/*
---------------------------------------------------------------------------
PLAYBACK FUNCTIONS
---------------------------------------------------------------------------
*/
/**
* Causes the player to begin streaming the media as set by the {@link module:MediaPlayer#attachSource attachSource()}
* method in preparation for playing. It specifically does not require a view to be attached with {@link module:MediaPlayer#attachSource attachView()} to begin preloading.
* When a view is attached after preloading, the buffered data is transferred to the attached mediaSource buffers.
*
* @see {@link module:MediaPlayer#attachSource attachSource()}
* @see {@link module:MediaPlayer#attachView attachView()}
* @memberof module:MediaPlayer
* @throws {@link module:MediaPlayer~SOURCE_NOT_ATTACHED_ERROR SOURCE_NOT_ATTACHED_ERROR} if called before attachSource function
* @instance
*/
function preload() {
if (videoModel.getElement() || streamingInitialized) {
return false;
}
if (source) {
initializePlayback();
} else {
throw SOURCE_NOT_ATTACHED_ERROR;
}
}
/**
* The play method initiates playback of the media defined by the {@link module:MediaPlayer#attachSource attachSource()} method.
* This method will call play on the native Video Element.
*
* @see {@link module:MediaPlayer#attachSource attachSource()}
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @memberof module:MediaPlayer
* @instance
*/
function play() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
if (!autoPlay || (isPaused() && playbackInitialized)) {
playbackController.play();
}
}
/**
* This method will call pause on the native Video Element.
*
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @memberof module:MediaPlayer
* @instance
*/
function pause() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
playbackController.pause();
}
/**
* Returns a Boolean that indicates whether the Video Element is paused.
* @return {boolean}
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @memberof module:MediaPlayer
* @instance
*/
function isPaused() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
return playbackController.isPaused();
}
/**
* Sets the currentTime property of the attached video element. If it is a live stream with a
* timeShiftBufferLength, then the DVR window offset will be automatically calculated.
*
* @param {number} value - A relative time, in seconds, based on the return value of the {@link module:MediaPlayer#duration duration()} method is expected
* @see {@link module:MediaPlayer#getDVRSeekOffset getDVRSeekOffset()}
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @throws {@link Constants#BAD_ARGUMENT_ERROR BAD_ARGUMENT_ERROR} if called with an invalid argument, not number type or is NaN.
* @memberof module:MediaPlayer
* @instance
*/
function seek(value) {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
checkParameterType(value, 'number');
if (isNaN(value)) {
throw Constants.BAD_ARGUMENT_ERROR;
}
let s = playbackController.getIsDynamic() ? getDVRSeekOffset(value) : value;
playbackController.seek(s);
}
/**
* Returns a Boolean that indicates whether the media is in the process of seeking to a new position.
* @return {boolean}
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @memberof module:MediaPlayer
* @instance
*/
function isSeeking() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
return playbackController.isSeeking();
}
/**
* Returns a Boolean that indicates whether the media is in the process of dynamic.
* @return {boolean}
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @memberof module:MediaPlayer
* @instance
*/
function isDynamic() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
return playbackController.getIsDynamic();
}
/**
* Use this method to set the native Video Element's playback rate.
* @param {number} value
* @memberof module:MediaPlayer
* @instance
*/
function setPlaybackRate(value) {
getVideoElement().playbackRate = value;
}
/**
* Returns the current playback rate.
* @returns {number}
* @memberof module:MediaPlayer
* @instance
*/
function getPlaybackRate() {
return getVideoElement().playbackRate;
}
/**
* Use this method to set the native Video Element's muted state. Takes a Boolean that determines whether audio is muted. true if the audio is muted and false otherwise.
* @param {boolean} value
* @memberof module:MediaPlayer
* @throws {@link Constants#BAD_ARGUMENT_ERROR BAD_ARGUMENT_ERROR} if called with an invalid argument, not boolean type.
* @instance
*/
function setMute(value) {
checkParameterType(value, 'boolean');
getVideoElement().muted = value;
}
/**
* A Boolean that determines whether audio is muted.
* @returns {boolean}
* @memberof module:MediaPlayer
* @instance
*/
function isMuted() {
return getVideoElement().muted;
}
/**
* A double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest).
* @param {number} value
* @memberof module:MediaPlayer
* @throws {@link Constants#BAD_ARGUMENT_ERROR BAD_ARGUMENT_ERROR} if called with an invalid argument, not number type, or is NaN or not between 0 and 1.
* @instance
*/
function setVolume(value) {
if (typeof value !== 'number' || isNaN(value) || value < 0.0 || value > 1.0) {
throw Constants.BAD_ARGUMENT_ERROR;
}
getVideoElement().volume = value;
}
/**
* Returns the current audio volume, from 0.0 (silent) to 1.0 (loudest).
* @returns {number}
* @memberof module:MediaPlayer
* @instance
*/
function getVolume() {
return getVideoElement().volume;
}
/**
* The length of the buffer for a given media type, in seconds. Valid media
* types are "video", "audio" and "fragmentedText". If no type is passed
* in, then the minimum of video, audio and fragmentedText buffer length is
* returned. NaN is returned if an invalid type is requested, the
* presentation does not contain that type, or if no arguments are passed
* and the presentation does not include any adaption sets of valid media
* type.
*
* @param {MediaType} type - 'video', 'audio' or 'fragmentedText'
* @returns {number} The length of the buffer for the given media type, in
* seconds, or NaN
* @memberof module:MediaPlayer
* @instance
*/
function getBufferLength(type) {
const types = [Constants.VIDEO, Constants.AUDIO, Constants.FRAGMENTED_TEXT];
if (!type) {
const buffer = types.map(
t => getTracksFor(t).length > 0 ? getDashMetrics().getCurrentBufferLevel(t) : Number.MAX_VALUE
).reduce(
(p, c) => Math.min(p, c)
);
return buffer === Number.MAX_VALUE ? NaN : buffer;
} else {
if (types.indexOf(type) !== -1) {
const buffer = getDashMetrics().getCurrentBufferLevel(type);
return buffer ? buffer : NaN;
} else {
logger.warn('getBufferLength requested for invalid type');
return NaN;
}
}
}
/**
* The timeShiftBufferLength (DVR Window), in seconds.
*
* @returns {number} The window of allowable play time behind the live point of a live stream.
* @memberof module:MediaPlayer
* @instance
*/
function getDVRWindowSize() {
let metric = dashMetrics.getCurrentDVRInfo();
if (!metric) {
return 0;
}
return metric.manifestInfo.DVRWindowSize;
}
/**
* This method should only be used with a live stream that has a valid timeShiftBufferLength (DVR Window).
* NOTE - If you do not need the raw offset value (i.e. media analytics, tracking, etc) consider using the {@link module:MediaPlayer#seek seek()} method
* which will calculate this value for you and set the video element's currentTime property all in one simple call.
*
* @param {number} value - A relative time, in seconds, based on the return value of the {@link module:MediaPlayer#duration duration()} method is expected.
* @returns {number} A value that is relative the available range within the timeShiftBufferLength (DVR Window).
* @see {@link module:MediaPlayer#seek seek()}
* @memberof module:MediaPlayer
* @instance
*/
function getDVRSeekOffset(value) {
let metric = dashMetrics.getCurrentDVRInfo();
if (!metric) {
return 0;
}
let liveDelay = playbackController.getLiveDelay();
let val = metric.range.start + value;
if (val > (metric.range.end - liveDelay)) {
val = metric.range.end - liveDelay;
}
return val;
}
/**
* Current time of the playhead, in seconds.
*
* If called with no arguments then the returned time value is time elapsed since the start point of the first stream, or if it is a live stream, then the time will be based on the return value of the {@link module:MediaPlayer#duration duration()} method.
* However if a stream ID is supplied then time is relative to the start of that stream, or is null if there is no such stream id in the manifest.
*
* @param {string} streamId - The ID of a stream that the returned playhead time must be relative to the start of. If undefined, then playhead time is relative to the first stream.
* @returns {number} The current playhead time of the media, or null.
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @memberof module:MediaPlayer
* @instance
*/
function time(streamId) {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
let t = getVideoElement().currentTime;
if (streamId !== undefined) {
t = streamController.getTimeRelativeToStreamId(t, streamId);
} else if (playbackController.getIsDynamic()) {
let metric = dashMetrics.getCurrentDVRInfo();
t = (metric === null) ? 0 : duration() - (metric.range.end - metric.time);
}
return t;
}
/**
* Duration of the media's playback, in seconds.
*
* @returns {number} The current duration of the media.
* @memberof module:MediaPlayer
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @instance
*/
function duration() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
let d = getVideoElement().duration;
if (playbackController.getIsDynamic()) {
let metric = dashMetrics.getCurrentDVRInfo();
let range;
if (!metric) {
return 0;
}
range = metric.range.end - metric.range.start;
d = range < metric.manifestInfo.DVRWindowSize ? range : metric.manifestInfo.DVRWindowSize;
}
return d;
}
/**
* Use this method to get the current playhead time as an absolute value, the time in seconds since midnight UTC, Jan 1 1970.
* Note - this property only has meaning for live streams. If called before play() has begun, it will return a value of NaN.
*
* @returns {number} The current playhead time as UTC timestamp.
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @memberof module:MediaPlayer
* @instance
*/
function timeAsUTC() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
if (time() < 0) {
return NaN;
}
return getAsUTC(time());
}
/**
* Use this method to get the current duration as an absolute value, the time in seconds since midnight UTC, Jan 1 1970.
* Note - this property only has meaning for live streams.
*
* @returns {number} The current duration as UTC timestamp.
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @memberof module:MediaPlayer
* @instance
*/
function durationAsUTC() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
return getAsUTC(duration());
}
/*
---------------------------------------------------------------------------
AUTO BITRATE
---------------------------------------------------------------------------
*/
/**
* Gets the top quality BitrateInfo checking portal limit and max allowed.
* It calls getTopQualityIndexFor internally
*
* @param {MediaType} type - 'video' or 'audio'
* @memberof module:MediaPlayer
* @returns {BitrateInfo | null}
* @throws {@link module:MediaPlayer~STREAMING_NOT_INITIALIZED_ERROR STREAMING_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @instance
*/
function getTopBitrateInfoFor(type) {
if (!streamingInitialized) {
throw STREAMING_NOT_INITIALIZED_ERROR;
}
return abrController.getTopBitrateInfoFor(type);
}
/**
* Gets the current download quality for media type video, audio or images. For video and audio types the ABR
* rules update this value before every new download unless setAutoSwitchQualityFor(type, false) is called. For 'image'
* type, thumbnails, there is no ABR algorithm and quality is set manually.
*
* @param {MediaType} type - 'video', 'audio' or 'image' (thumbnails)
* @returns {number} the quality index, 0 corresponding to the lowest bitrate
* @memberof module:MediaPlayer
* @see {@link module:MediaPlayer#setAutoSwitchQualityFor setAutoSwitchQualityFor()}
* @see {@link module:MediaPlayer#setQualityFor setQualityFor()}
* @throws {@link module:MediaPlayer~STREAMING_NOT_INITIALIZED_ERROR STREAMING_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @instance
*/
function getQualityFor(type) {
if (!streamingInitialized) {
throw STREAMING_NOT_INITIALIZED_ERROR;
}
if (type === Constants.IMAGE) {
const activeStream = getActiveStream();
if (!activeStream) {
return -1;
}
const thumbnailController = activeStream.getThumbnailController();
return !thumbnailController ? -1 : thumbnailController.getCurrentTrackIndex();
}
return abrController.getQualityFor(type);
}
/**
* Sets the current quality for media type instead of letting the ABR Heuristics automatically selecting it.
* This value will be overwritten by the ABR rules unless setAutoSwitchQualityFor(type, false) is called.
*
* @param {MediaType} type - 'video', 'audio' or 'image'
* @param {number} value - the quality index, 0 corresponding to the lowest bitrate
* @memberof module:MediaPlayer
* @see {@link module:MediaPlayer#setAutoSwitchQualityFor setAutoSwitchQualityFor()}
* @see {@link module:MediaPlayer#getQualityFor getQualityFor()}
* @throws {@link module:MediaPlayer~STREAMING_NOT_INITIALIZED_ERROR STREAMING_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @instance
*/
function setQualityFor(type, value) {
if (!streamingInitialized) {
throw STREAMING_NOT_INITIALIZED_ERROR;
}
if (type === Constants.IMAGE) {
const activeStream = getActiveStream();
if (!activeStream) {
return;
}
const thumbnailController = activeStream.getThumbnailController();
if (thumbnailController) {
thumbnailController.setTrackByIndex(value);
}
}
abrController.setPlaybackQuality(type, streamController.getActiveStreamInfo(), value);
}
/**
* Update the video element size variables
* Should be called on window resize (or any other time player is resized). Fullscreen does trigger a window resize event.
*
* Once windowResizeEventCalled = true, abrController.checkPortalSize() will use element size variables rather than querying clientWidth every time.
*
* @memberof module:MediaPlayer
* @instance
*/
function updatePortalSize() {
abrController.setElementSize();
abrController.setWindowResizeEventCalled(true);
}
/*
---------------------------------------------------------------------------
MEDIA PLAYER CONFIGURATION
---------------------------------------------------------------------------
*/
/**
* <p>Set to false to prevent stream from auto-playing when the view is attached.</p>
*
* @param {boolean} value
* @default true
* @memberof module:MediaPlayer
* @see {@link module:MediaPlayer#attachView attachView()}
* @throws {@link Constants#BAD_ARGUMENT_ERROR BAD_ARGUMENT_ERROR} if called with an invalid argument, not boolean type.
* @instance
*
*/
function setAutoPlay(value) {
checkParameterType(value, 'boolean');
autoPlay = value;
}
/**
* @returns {boolean} The current autoPlay state.
* @memberof module:MediaPlayer
* @instance
*/
function getAutoPlay() {
return autoPlay;
}
/**
* @memberof module:MediaPlayer
* @instance
* @returns {number|NaN} Current live stream latency in seconds. It is the difference between current time and time position at the playback head.
* @throws {@link module:MediaPlayer~MEDIA_PLAYER_NOT_INITIALIZED_ERROR MEDIA_PLAYER_NOT_INITIALIZED_ERROR} if called before initialize function
*/
function getCurrentLiveLatency() {
if (!mediaPlayerInitialized) {
throw MEDIA_PLAYER_NOT_INITIALIZED_ERROR;
}
if (!playbackInitialized) {
return NaN;
}
return playbackController.getCurrentLiveLatency();
}
/**
* Add a custom ABR Rule
* Rule will be apply on next stream if a stream is being played
*
* @param {string} type - rule type (one of ['qualitySwitchRules','abandonFragmentRules'])
* @param {string} rulename - name of rule (used to identify custom rule). If one rule of same name has been added, then existing rule will be updated
* @param {object} rule - the rule object instance
* @memberof module:MediaPlayer
* @throws {@link Constants#BAD_ARGUMENT_ERROR BAD_ARGUMENT_ERROR} if called with invalid arguments.
* @instance
*/
function addABRCustomRule(type, rulename, rule) {
mediaPlayerModel.addABRCustomRule(type, rulename, rule);
}
/**
* Remove a custom ABR Rule
*
* @param {string} rulename - name of the rule to be removed
* @memberof module:MediaPlayer
* @instance
*/
function removeABRCustomRule(rulename) {
mediaPlayerModel.removeABRCustomRule(rulename);
}
/**
* Remove all custom rules
* @memberof module:MediaPlayer
* @instance
*/
function removeAllABRCustomRule() {
mediaPlayerModel.removeABRCustomRule();
}
/**
* <p>Allows you to set a scheme and server source for UTC live edge detection for dynamic streams.
* If UTCTiming is defined in the manifest, it will take precedence over any time source manually added.</p>
* <p>If you have exposed the Date header, use the method {@link module:MediaPlayer#clearDefaultUTCTimingSources clearDefaultUTCTimingSources()}.
* This will allow the date header on the manifest to be used instead of a time server</p>
* @param {string} schemeIdUri - <ul>
* <li>urn:mpeg:dash:utc:http-head:2014</li>
* <li>urn:mpeg:dash:utc:http-xsdate:2014</li>
* <li>urn:mpeg:dash:utc:http-iso:2014</li>
* <li>urn:mpeg:dash:utc:direct:2014</li>
* </ul>
* <p>Some specs referencing early ISO23009-1 drafts incorrectly use
* 2012 in the URI, rather than 2014. support these for now.</p>
* <ul>
* <li>urn:mpeg:dash:utc:http-head:2012</li>
* <li>urn:mpeg:dash:utc:http-xsdate:2012</li>
* <li>urn:mpeg:dash:utc:http-iso:2012</li>
* <li>urn:mpeg:dash:utc:direct:2012</li>
* </ul>
* @param {string} value - Path to a time source.
* @default
* <ul>
* <li>schemeIdUri:urn:mpeg:dash:utc:http-xsdate:2014</li>
* <li>value:http://time.akamai.com/?iso&ms/li>
* </ul>