-
Notifications
You must be signed in to change notification settings - Fork 9
/
canvas-instance.ts
2125 lines (1787 loc) · 64.6 KB
/
canvas-instance.ts
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
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/ban-ts-ignore */
import { convertToPercentage } from '../helpers/convert-to-percentage';
const $ = require('jquery');
import { Annotation, AnnotationBody, Canvas, Duration, Range, Utils } from 'manifesto.js';
import { Behavior, MediaType } from '@iiif/vocabulary/dist-commonjs';
import { BaseComponent, IBaseComponentOptions } from '@iiif/base-component';
import { IAVCanvasInstanceData } from '../interfaces/canvas-instance-data';
import { MediaElement } from '../elements/media-element';
import { TimePlanPlayer } from '../elements/timeplan-player';
import { VolumeEvents } from '../events/volume-events';
import { extractMediaFromAnnotationBodies } from '../helpers/extract-media-from-annotation-bodies';
import { AVVolumeControl } from './volume-control';
import { CompositeMediaElement } from '../elements/composite-media-element';
import { createTimePlansFromManifest } from '../helpers/create-time-plans-from-manifest';
import { getMediaSourceFromAnnotationBody } from '../helpers/get-media-source-from-annotation-body';
import { CanvasInstanceEvents } from '../events/canvas-instance-events';
import { AVComponent } from './av-component';
import { VirtualCanvas } from '../elements/virtual-canvas';
import { Events } from '../events/av-component-events';
import { isHLSFormat } from '../helpers/is-hls-format';
import { isMpegDashFormat } from '../helpers/is-mpeg-dash-format';
import { retargetTemporalComponent } from '../helpers/retarget-temporal-component';
import { getSpatialComponent } from '../helpers/get-spatial-component';
import { canPlayHls } from '../helpers/can-play-hls';
import { formatTime } from '../helpers/format-time';
import { isSafari } from '../helpers/is-safari';
import { diffData } from '../helpers/diff-data';
import { isVirtual } from '../helpers/is-virtual';
import { addTime, fromMs, minusTime, timelineTime, TimelineTime, TimelineTimeMs, toMs } from '../helpers/relative-time';
import { Logger } from '../helpers/logger';
import { getHls } from '../helpers/get-hls';
import 'waveform-panel';
import { WaveformPanel } from 'waveform-panel';
export class CanvasInstance extends BaseComponent {
private _$canvasContainer: JQuery;
private _$canvasDuration: JQuery;
private _$canvasHoverHighlight: JQuery;
private _$canvasHoverPreview: JQuery;
private _$canvasTime: JQuery;
private _$canvasTimelineContainer: JQuery;
private _$controlsContainer: JQuery;
private _$durationHighlight: JQuery;
private _$hoverPreviewTemplate: JQuery;
private _$nextButton: JQuery;
private _$fastForward: JQuery;
private _$fastRewind: JQuery;
private _$optionsContainer: JQuery;
private _$playButton: JQuery;
private _$prevButton: JQuery;
private _$rangeHoverHighlight: JQuery;
private _$rangeHoverPreview: JQuery;
private _$rangeTimelineContainer: JQuery;
private _$timeDisplay: JQuery;
private _$timelineItemContainer: JQuery;
private _canvasClockFrequency = 25;
private _canvasClockInterval: number;
private _canvasClockStartDate: TimelineTimeMs = 0 as TimelineTimeMs;
private _canvasClockTime: TimelineTime = 0 as TimelineTime;
private _canvasHeight = 0;
private _canvasWidth = 0;
private _waveformPanel?: WaveformPanel;
private _contentAnnotations: any[]; // todo: type as HTMLMediaElement?
private _data: IAVCanvasInstanceData = this.data();
private _highPriorityFrequency = 25;
private _highPriorityInterval: number;
private _isPlaying = false;
private _isStalled = false;
//private _lastCanvasHeight: number | undefined;
//private _lastCanvasWidth: number | undefined;
private _lowPriorityFrequency = 250;
private _lowPriorityInterval: number;
private _mediaSyncMarginSecs = 1;
private _rangeSpanPadding = 0.25;
private _readyMediaCount = 0;
private _stallRequestedBy: any[] = []; //todo: type
private _volume: AVVolumeControl;
private _wasPlaying = false;
public ranges: Range[] = [];
public waveforms: string[] = [];
public waveformSources: { source: string; canvas: string; start: number; end: number; itemData: any }[] = [];
private _buffering = false;
private _bufferShown = false;
public $playerElement: JQuery;
public _$element: JQuery;
public isOnlyCanvasInstance = false;
public logMessage: (message: string) => void;
public timePlanPlayer: TimePlanPlayer;
constructor(options: IBaseComponentOptions) {
super(options);
this._$element = $(this.options.target);
this._data = this.options.data;
this.$playerElement = $('<div class="player player--loading"></div>');
this.$playerElement.hide();
}
public loaded(): void {
setTimeout(() => {
this.$playerElement.removeClass('player--loading');
}, 500);
}
public isPlaying(): boolean {
return this._isPlaying;
}
public getClockTime(): TimelineTime {
return this._canvasClockTime;
}
public createTimeStops() {
const helper = this._data.helper;
const virtualCanvas = this._data.canvas as VirtualCanvas;
if (!helper || !virtualCanvas) {
return;
}
this.ranges = [];
this._contentAnnotations = [];
const canvases = virtualCanvas.canvases;
const mediaElements: MediaElement[] = [];
for (const canvas of canvases) {
const annotations = canvas.getContent();
for (const annotation of annotations) {
const annotationBody = extractMediaFromAnnotationBodies(annotation);
if (!annotationBody) {
continue;
}
const mediaSource = getMediaSourceFromAnnotationBody(annotation, annotationBody, {
id: canvas.id,
duration: canvas.getDuration() || 0,
height: canvas.getHeight(),
width: canvas.getWidth(),
});
const mediaElement = new MediaElement(mediaSource, {
adaptiveAuthEnabled: this._data.adaptiveAuthEnabled,
probed: this.options.data?.canvas?.externalResource?.isProbed,
});
mediaElement.setSize(
this._convertToPercentage(mediaSource.x || 0, canvas.getHeight()),
this._convertToPercentage(mediaSource.y || 0, canvas.getWidth()),
this._convertToPercentage(mediaSource.width || canvas.getWidth(), canvas.getWidth()),
this._convertToPercentage(mediaSource.height || canvas.getHeight(), canvas.getHeight())
);
mediaElements.push(mediaElement);
const seeAlso: any = annotation.getProperty('seeAlso');
if (seeAlso && seeAlso.length) {
const dat: string = seeAlso[0].id;
this.waveforms.push(dat);
const temporalOffsets: RegExpExecArray | null = /t=([^&]+)/g.exec(annotation.__jsonld.target);
const [start, end] = ((temporalOffsets || [])[1] || '').split(',').map((i) => parseFloat(i));
this.waveformSources.push({
source: dat,
canvas: canvas.id,
start,
end,
itemData: { start, end, source: annotation.id },
});
}
}
}
if (mediaElements.length === 0) {
// Since this is a constructor call.
setTimeout(() => {
this.fire(Events.MEDIA_ERROR, this._data?.content?.noMediaMessage || 'No media available to play');
}, 200);
}
const compositeMediaElement = new CompositeMediaElement(mediaElements);
compositeMediaElement.appendTo(this.$playerElement);
compositeMediaElement.load().then(() => {
// this._updateDurationDisplay();
this.fire(Events.MEDIA_READY);
});
// this._renderSyncIndicator(data)
// @ts-ignore
const plan = createTimePlansFromManifest(helper.manifest as any, mediaElements);
// @ts-ignore
window.timePlanPlayer = this.timePlanPlayer = new TimePlanPlayer(
compositeMediaElement,
plan,
(rangeId) => {
this.setCurrentRangeId(rangeId, { autoChanged: true });
},
(time) => {
this._canvasClockTime = time;
},
(isPlaying) => {
if (this._buffering) {
return;
}
if (isPlaying) {
this.play(true);
} else {
this.pause(true);
}
},
() => {
this._buffering = true;
}
);
}
public init() {
if (!this._data || !this._data.content || !this._data.canvas) {
Logger.warn('unable to initialise, missing canvas or content');
return;
}
this._$hoverPreviewTemplate = $(
'<div class="hover-preview"><div class="label"></div><div class="pointer"><span class="arrow"></span></div></div>'
);
this._$canvasContainer = $('<div class="canvas-container"></div>');
this._$optionsContainer = $('<div class="options-container"></div>');
this._$rangeTimelineContainer = $('<div class="range-timeline-container"></div>');
this._$canvasTimelineContainer = $('<div class="canvas-timeline-container"></div>');
this._$canvasHoverPreview = this._$hoverPreviewTemplate.clone();
this._$canvasHoverHighlight = $('<div class="hover-highlight"></div>');
this._$rangeHoverPreview = this._$hoverPreviewTemplate.clone();
this._$rangeHoverHighlight = $('<div class="hover-highlight"></div>');
this._$durationHighlight = $('<div class="duration-highlight"></div>');
this._$timelineItemContainer = $('<div class="timeline-item-container"></div>');
this._$controlsContainer = $('<div class="controls-container"></div>');
this._$prevButton = $(`
<button class="btn" title="${this._data.content.previous}">
<i class="av-icon av-icon-previous" aria-hidden="true"></i>
<span class="sr-only>${this._data.content.previous}</span>
</button>`);
this._$playButton = $(`
<button class="btn" title="${this._data.content.play}">
<i class="av-icon av-icon-play play" aria-hidden="true"></i>
<span class="sr-only>${this._data.content.play}</span>
</button>`);
this._$nextButton = $(`
<button class="btn" title="${this._data.content.next}">
<i class="av-icon av-icon-next" aria-hidden="true"></i>
<span class="sr-only>${this._data.content.next}</span>
</button>`);
this._$fastForward = $(`
<button class="btn" title="${this._data.content.fastForward}">
<i class="av-icon av-icon-fast-forward" aria-hidden="true"></i>
<span class="sr-only>
${this._data.content.fastForward || ''}
</span>
</button>`);
this._$fastRewind = $(`
<button class="btn" title="${this._data.content.fastRewind}">
<i class="av-icon av-icon-fast-rewind" aria-hidden="true"></i>
<span class="sr-only>
${this._data.content.fastRewind || ''}
</span>
</button>`);
this._$timeDisplay = $(
'<div class="time-display"><span class="canvas-time"></span> / <span class="canvas-duration"></span></div>'
);
this._$canvasTime = this._$timeDisplay.find('.canvas-time');
this._$canvasDuration = this._$timeDisplay.find('.canvas-duration');
if (this.isVirtual()) {
this.$playerElement.addClass('virtual');
}
const $volume: JQuery = $('<div class="volume"></div>');
this._volume = new AVVolumeControl({
target: $volume[0] as HTMLElement,
data: Object.assign({}, this._data),
});
this._volume.on(
VolumeEvents.VOLUME_CHANGED,
(value: number) => {
this.fire(VolumeEvents.VOLUME_CHANGED, value);
},
false
);
// @todo make the buttons for FF and FR configurable.
this._$controlsContainer.append(
this._$prevButton,
this._data.enableFastRewind ? this._$fastRewind : null,
this._$playButton,
this._data.enableFastForward ? this._$fastForward : null,
this._$nextButton,
this._$timeDisplay,
$volume
);
this._$canvasTimelineContainer.append(
this._$canvasHoverPreview,
this._$canvasHoverHighlight,
this._$durationHighlight
);
this._$rangeTimelineContainer.append(this._$rangeHoverPreview, this._$rangeHoverHighlight);
this._$optionsContainer.append(
this._$canvasTimelineContainer,
this._$rangeTimelineContainer,
this._$controlsContainer
);
this.$playerElement.append(this._$canvasContainer, this._$optionsContainer);
this._$canvasHoverPreview.hide();
this._$rangeHoverPreview.hide();
const newRanges = this.isVirtual() && AVComponent.newRanges;
// Should bootstrap ranges and content.
if (newRanges) {
this.createTimeStops();
}
if (!newRanges) {
if (this._data && this._data.helper && this._data.canvas) {
let ranges: Range[] = [];
// if the canvas is virtual, get the ranges for all sub canvases
if (isVirtual(this._data.canvas)) {
this._data.canvas.canvases.forEach((canvas: Canvas) => {
if (this._data && this._data.helper) {
// @ts-ignore
const r: Range[] = this._data.helper.getCanvasRanges(canvas);
const clonedRanges: Range[] = [];
// shift the range targets forward by the duration of their previous canvases
r.forEach((range: Range) => {
const clonedRange = jQuery.extend(true, {}, range);
clonedRanges.push(clonedRange);
if (clonedRange.canvases && clonedRange.canvases.length) {
for (let i = 0; i < clonedRange.canvases.length; i++) {
if (isVirtual(this._data.canvas)) {
clonedRange.canvases[i] = retargetTemporalComponent(
this._data.canvas.canvases,
clonedRange.__jsonld.items[i].id
);
}
}
}
});
ranges.push(...clonedRanges);
}
});
} else {
// @ts-ignore
ranges = ranges.concat(this._data.helper.getCanvasRanges(this._data.canvas as Canvas));
}
ranges.forEach((range: Range) => {
this.ranges.push(range);
});
}
}
const canvasWidth: number = this._data.canvas.getWidth();
const canvasHeight: number = this._data.canvas.getHeight();
if (!canvasWidth) {
this._canvasWidth = this.$playerElement.parent().width(); // this._data.defaultCanvasWidth;
} else {
this._canvasWidth = canvasWidth;
}
if (!canvasHeight) {
this._canvasHeight = this._canvasWidth * (this._data.defaultAspectRatio || 1); //this._data.defaultCanvasHeight;
} else {
this._canvasHeight = canvasHeight;
}
// eslint-disable-next-line @typescript-eslint/no-this-alias
const that = this;
let prevClicks = 0;
let prevTimeout = 0;
this._$prevButton.on('touchstart click', (e) => {
e.preventDefault();
prevClicks++;
if (prevClicks === 1) {
// single click
this._previous(false);
prevTimeout = setTimeout(() => {
prevClicks = 0;
prevTimeout = 0;
}, this._data.doubleClickMS) as any;
} else {
// double click
this._previous(true);
clearTimeout(prevTimeout);
prevClicks = 0;
prevTimeout = 0;
}
});
this._$playButton.on('touchstart click', (e) => {
e.preventDefault();
if (this._isPlaying) {
this.pause();
} else {
this.play();
}
});
this._$nextButton.on('touchstart click', (e) => {
e.preventDefault();
this._next();
});
this._$fastForward.on('touchstart click', (e) => {
const { end } = this.getRangeTiming();
const goToTime = addTime(this.getClockTime(), 20 as TimelineTime);
if (goToTime < end) {
return this._setCurrentTime(goToTime);
}
return this._setCurrentTime(end);
});
this._$fastRewind.on('touchstart click', (e) => {
const { start } = this.getRangeTiming();
const goToTime = minusTime(this.getClockTime(), 20 as TimelineTime);
if (goToTime >= start) {
return this._setCurrentTime(goToTime);
}
return this._setCurrentTime(start);
});
if (newRanges) {
this._$canvasTimelineContainer.slider({
value: 0,
step: 0.01,
orientation: 'horizontal',
range: 'min',
min: 0,
max: this.timePlanPlayer.getDuration(),
animate: false,
slide: (evt: any, ui: any) => {
this._setCurrentTime(this.timePlanPlayer.plan.start + ui.value);
},
});
} else {
this._$canvasTimelineContainer.slider({
value: 0,
step: 0.01,
orientation: 'horizontal',
range: 'min',
max: that._getDuration(),
animate: false,
create: function (evt: any, ui: any) {
// on create
},
slide: function (evt: any, ui: any) {
that._setCurrentTime(ui.value);
},
stop: function (evt: any, ui: any) {
//this._setCurrentTime(ui.value);
},
});
}
this._$canvasTimelineContainer.mouseout(() => {
that._$canvasHoverHighlight.width(0);
that._$canvasHoverPreview.hide();
});
this._$rangeTimelineContainer.mouseout(() => {
that._$rangeHoverHighlight.width(0);
that._$rangeHoverPreview.hide();
});
this._$canvasTimelineContainer.on('mousemove', (e) => {
if (newRanges) {
this._updateHoverPreview(e, this._$canvasTimelineContainer, this.timePlanPlayer.getDuration());
} else {
this._updateHoverPreview(e, this._$canvasTimelineContainer, this._getDuration());
}
});
this._$rangeTimelineContainer.on('mousemove', (e) => {
if (newRanges) {
this._updateHoverPreview(e, this._$canvasTimelineContainer, this.timePlanPlayer.getDuration());
} else if (this._data.range) {
const duration: Duration | undefined = this._data.range.getDuration();
this._updateHoverPreview(e, this._$rangeTimelineContainer, duration ? duration.getLength() : 0);
}
});
if (newRanges) {
return;
}
// create annotations
this._contentAnnotations = [];
const items: Annotation[] = this._data.canvas.getContent(); // (<any>this._data.canvas).__jsonld.content[0].items;
// always hide timelineItemContainer for now
this._$timelineItemContainer.hide();
for (let i = 0; i < items.length; i++) {
const item: Annotation = items[i];
let mediaSource: any;
const bodies: AnnotationBody[] = item.getBody();
if (!bodies.length) {
Logger.warn('item has no body');
return;
}
const body: AnnotationBody | null = this._getBody(bodies);
if (!body) {
// if no suitable format was found for the current browser, skip this item.
Logger.warn('unable to find suitable format for', item.id);
continue;
}
const type: string | null = body.getType();
const format = body.getFormat();
if (type && type.toString() === 'textualbody') {
//mediaSource = (<any>body).value;
} else {
mediaSource = body.id.split('#')[0];
}
const target: string | null = item.getTarget();
if (!target) {
Logger.warn('item has no target');
return;
}
let xywh: number[] | null = getSpatialComponent(target);
let t: number[] | null = Utils.getTemporalComponent(target);
if (!xywh) {
xywh = [0, 0, this._canvasWidth, this._canvasHeight];
}
if (!t) {
t = [0, this._getDuration()];
}
const positionLeft = parseInt(String(xywh[0])),
positionTop = parseInt(String(xywh[1])),
mediaWidth = parseInt(String(xywh[2])),
mediaHeight = parseInt(String(xywh[3])),
startTime = parseInt(String(t[0])),
endTime = parseInt(String(t[1]));
const percentageTop = this._convertToPercentage(positionTop, this._canvasHeight),
percentageLeft = this._convertToPercentage(positionLeft, this._canvasWidth),
percentageWidth = this._convertToPercentage(mediaWidth, this._canvasWidth),
percentageHeight = this._convertToPercentage(mediaHeight, this._canvasHeight);
const temporalOffsets: RegExpExecArray | null = /t=([^&]+)/g.exec(body.id);
let ot;
if (temporalOffsets && temporalOffsets[1]) {
ot = temporalOffsets[1].split(',');
} else {
ot = [null, null];
}
const offsetStart = ot[0] ? parseInt(ot[0]) : ot[0],
offsetEnd = ot[1] ? parseInt(ot[1]) : ot[1];
// todo: type this
const itemData: any = {
active: false,
end: endTime,
endOffset: offsetEnd,
format: format,
height: percentageHeight,
left: percentageLeft,
source: mediaSource,
start: startTime,
startOffset: offsetStart,
top: percentageTop,
type: type,
width: percentageWidth,
};
this._renderMediaElement(itemData);
// waveform
// todo: create annotation.getSeeAlso
const seeAlso: any = item.getProperty('seeAlso');
if (seeAlso && seeAlso.length) {
const dat: string = seeAlso[0].id;
this.waveforms.push(dat);
this.waveformSources.push({
canvas: this._data.canvas.id,
source: dat,
start: 0,
end: itemData.end - itemData.start,
itemData,
});
}
}
}
private _getBody(bodies: AnnotationBody[]): AnnotationBody | null {
// if there's an HLS format and HLS is supported in this browser
for (let i = 0; i < bodies.length; i++) {
const body: AnnotationBody = bodies[i];
const format: MediaType | null = body.getFormat();
if (format) {
if (isHLSFormat(format) && canPlayHls()) {
return body;
}
}
}
// if there's a Dash format and the browser isn't Safari
for (let i = 0; i < bodies.length; i++) {
const body: AnnotationBody = bodies[i];
const format: MediaType | null = body.getFormat();
if (format) {
if (isMpegDashFormat(format) && !isSafari()) {
return body;
}
}
}
// otherwise, return the first format that isn't HLS or Dash
for (let i = 0; i < bodies.length; i++) {
const body: AnnotationBody = bodies[i];
const format: MediaType | null = body.getFormat();
if (format) {
if (!isHLSFormat(format) && !isMpegDashFormat(format)) {
return body;
}
}
}
// couldn't find a suitable format
return null;
}
private _getDuration(): TimelineTime {
if (this.isVirtual() && AVComponent.newRanges) {
return this.timePlanPlayer.getDuration();
}
if (this._data && this._data.canvas) {
return Math.floor(this._data.canvas.getDuration() as number) as TimelineTime;
}
return 0 as TimelineTime;
}
public data(): IAVCanvasInstanceData {
return {
waveformColor: '#fff',
waveformBarSpacing: 4,
waveformBarWidth: 2,
volume: 1,
};
}
/**
* @deprecated
*/
public isVirtual(): boolean {
return this._data.canvas instanceof VirtualCanvas;
}
public isVisible(): boolean {
return !!this._data.visible;
}
public includesVirtualSubCanvas(canvasId: string): boolean {
if (isVirtual(this._data.canvas) && this._data.canvas && this._data.canvas.canvases) {
for (let i = 0; i < this._data.canvas.canvases.length; i++) {
const canvas: Canvas = this._data.canvas.canvases[i];
if (Utils.normaliseUrl(canvas.id) === canvasId) {
return true;
}
}
}
return false;
}
setVisibility(visibility: boolean) {
if (this._data.visible === visibility) {
return;
}
this._data.visible = visibility;
if (visibility) {
this._rewind();
this.$playerElement.show();
} else {
this.$playerElement.hide();
this.pause();
}
this.resize();
}
viewRange(rangeId: string) {
if (this.currentRange !== rangeId) {
Logger.log(`Switching range from ${this.currentRange} to ${rangeId}`);
this.setCurrentRangeId(rangeId, { noRender: true });
// Entrypoint for changing a range. Only get's called when change came from external source.
if (AVComponent.newRanges && this.isVirtual()) {
this._setCurrentTime(this.timePlanPlayer.setRange(rangeId), true);
} else {
// this is called when timePlanPlayer isn't available (it's not a virtual canvas)
const range = this._data!.helper!.getRangeById(rangeId);
this.set({
range: jQuery.extend(true, { autoChanged: true }, range),
});
}
this._render();
}
}
limitToRange: boolean;
autoAdvanceRanges = true;
currentRange?: string;
setCurrentRangeId(
range: null | string,
{
autoChanged = false,
limitToRange = false,
noRender = false,
}: { autoChanged?: boolean; limitToRange?: boolean; noRender?: boolean } = {}
) {
if (autoChanged && !this.autoAdvanceRanges) {
return;
}
Logger.log('Setting current range id', range);
// This is the end of the chain for changing a range.
if (range && this.currentRange !== range) {
this.currentRange = range;
this.fire(Events.RANGE_CHANGED, range);
} else if (range === null) {
this.currentRange = undefined;
this.fire(Events.RANGE_CHANGED, null);
}
if (!noRender) {
this._render();
}
}
setVolume(volume: number) {
this._volume.set({ volume });
if (AVComponent.newRanges && this.isVirtual()) {
this.timePlanPlayer.setVolume(volume);
}
}
setLimitToRange(limitToRange: boolean) {
Logger.log(this._data.constrainNavigationToRange);
if (this.limitToRange !== limitToRange) {
this.limitToRange = limitToRange;
this._render();
}
}
public set(data: IAVCanvasInstanceData): void {
// Simplification of setting state.
if (AVComponent.newRanges && this.isVirtual()) {
if (typeof data.range !== 'undefined') {
this.setCurrentRangeId(data.range.id, {
limitToRange: data.limitToRange,
});
}
if (typeof data.rangeId !== 'undefined') {
this.setCurrentRangeId(data.rangeId, {
limitToRange: data.limitToRange,
});
}
if (typeof data.volume !== 'undefined') {
this.setVolume(data.volume);
}
if (typeof data.limitToRange !== 'undefined') {
this.setLimitToRange(data.limitToRange);
}
if (typeof data.visible !== 'undefined') {
this.setVisibility(data.visible);
}
return;
}
const oldData: IAVCanvasInstanceData = Object.assign({}, this._data);
this._data = Object.assign(this._data, data);
const diff: string[] = diffData(oldData, this._data);
if (diff.includes('visible')) {
if (this._data.canvas) {
if (this._data.visible) {
this._rewind();
this.$playerElement.show();
} else {
this.$playerElement.hide();
this.pause();
}
this.resize();
}
}
if (diff.includes('volume')) {
this._contentAnnotations.forEach(($mediaElement: any) => {
const volume: number = this._data.volume !== undefined ? this._data.volume : 1;
$($mediaElement.element).prop('volume', volume);
this._volume.set({
volume: this._data.volume,
});
});
} else {
if (this.isVisible()) {
this._render();
}
}
if (diff.includes('range')) {
if (this._data.helper) {
if (!this._data.range) {
this.fire(Events.RANGE_CHANGED, null);
} else {
const duration: Duration | undefined = this._data.range.getDuration();
if (duration) {
if (typeof duration !== 'undefined') {
// Only change the current time if the current time is outside of the current time.
if (duration.start >= this._canvasClockTime || duration.end <= this._canvasClockTime) {
this._setCurrentTime(duration.start as TimelineTime);
}
if (this._data.autoPlay) {
this.play();
}
this.fire(Events.RANGE_CHANGED, this._data.range.id, this._data.range);
}
}
}
}
if (diff.includes('limitToRange')) {
this._render();
}
}
}
private _hasRangeChanged(): void {
if (this.isVirtual() && AVComponent.newRanges) {
return;
}
const range: Range | undefined = this._getRangeForCurrentTime();
if (
range &&
!this._data.limitToRange &&
(!this._data.range || (this._data.range && range.id !== this._data.range.id))
) {
this.set({
range: jQuery.extend(true, { autoChanged: true }, range),
});
}
}
private _getRangeForCurrentTime(parentRange?: Range): Range | undefined {
let ranges: Range[];
if (!parentRange) {
ranges = this.ranges;
} else {
ranges = parentRange.getRanges();
}
for (let i = 0; i < ranges.length; i++) {
const range: Range = ranges[i];
const rangeBehavior = range.getBehavior();
if (rangeBehavior && rangeBehavior !== 'no-nav') {
continue;
}
// if the range spans the current time, and is navigable, return it.
// otherwise, try to find a navigable child range.
if (this._rangeSpansCurrentTime(range)) {
if (this._rangeNavigable(range)) {
return range;
}
const childRanges: Range[] = range.getRanges();
// if a child range spans the current time, recurse into it
for (let j = 0; j < childRanges.length; j++) {
const childRange: Range = childRanges[j];
if (this._rangeSpansCurrentTime(childRange)) {
return this._getRangeForCurrentTime(childRange);
}
}
// this range isn't navigable, and couldn't find a navigable child range.
// therefore return the parent range (if any).
return range.parentRange;
}
}
return undefined;
}
private _rangeSpansCurrentTime(range: Range): boolean {
if (range.spansTime(Math.ceil(this._canvasClockTime) + this._rangeSpanPadding)) {
return true;
}
return false;
}
private _rangeNavigable(range: Range): boolean {
const behavior: Behavior | null = range.getBehavior();
if (behavior && behavior.toString() === 'no-nav') {
return false;
}
return true;
}
private _render(): void {
if (this.isVirtual() && AVComponent.newRanges && this.isVisible()) {
Logger.groupCollapsed('CanvasInstance._render()');
Logger.log({
dataRange: this._data.rangeId,
range: this.currentRange,
newLimitToRange: this.limitToRange,
constraintToRange: this._data.constrainNavigationToRange,
autoSelectRange: this._data.autoSelectRange,
});
// 3 ways to render:
// Limit to range + no id = show everything
// Limit to range + id = show everything in context
// No limit to range = show everything
// No limit -> Limit (+ range) = show just range
// - Range id + limitToRange
// - Range id
// - nothing
if (this.limitToRange && this.currentRange) {
Logger.log('Selecting plan...', this.currentRange);
this.timePlanPlayer.selectPlan({ rangeId: this.currentRange });
} else {
Logger.log('Resetting...');
this.timePlanPlayer.selectPlan({ reset: true });
}
const ratio = this._$canvasTimelineContainer.width() / this.timePlanPlayer.getDuration();
this._$durationHighlight.show();
const { start, duration } = this.timePlanPlayer.getCurrentRange();
this._$canvasTimelineContainer.slider({
value: this._canvasClockTime - this.timePlanPlayer.plan.start,
max: this.timePlanPlayer.getDuration(),