-
Notifications
You must be signed in to change notification settings - Fork 884
/
ft-shaka-video-player.js
2884 lines (2350 loc) · 89.9 KB
/
ft-shaka-video-player.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'fs/promises'
import path from 'path'
import { computed, defineComponent, onBeforeUnmount, onMounted, reactive, ref, shallowRef, watch } from 'vue'
import shaka from 'shaka-player'
import { useI18n } from '../../composables/use-i18n-polyfill'
import store from '../../store/index'
import { IpcChannels, KeyboardShortcuts } from '../../../constants'
import { AudioTrackSelection } from './player-components/AudioTrackSelection'
import { FullWindowButton } from './player-components/FullWindowButton'
import { LegacyQualitySelection } from './player-components/LegacyQualitySelection'
import { ScreenshotButton } from './player-components/ScreenshotButton'
import { StatsButton } from './player-components/StatsButton'
import { TheatreModeButton } from './player-components/TheatreModeButton'
import {
findMostSimilarAudioBandwidth,
getSponsorBlockSegments,
logShakaError,
repairInvidiousManifest,
sortCaptions,
translateSponsorBlockCategory
} from '../../helpers/player/utils'
import {
addKeyboardShortcutToActionTitle,
getPicturesPath,
showToast,
writeFileWithPicker
} from '../../helpers/utils'
import { pathExists } from '../../helpers/filesystem'
/** @typedef {import('../../helpers/sponsorblock').SponsorBlockCategory} SponsorBlockCategory */
// The UTF-8 characters "h", "t", "t", and "p".
const HTTP_IN_HEX = 0x68747470
const USE_OVERFLOW_MENU_WIDTH_THRESHOLD = 600
const RequestType = shaka.net.NetworkingEngine.RequestType
const AdvancedRequestType = shaka.net.NetworkingEngine.AdvancedRequestType
const TrackLabelFormat = shaka.ui.Overlay.TrackLabelFormat
/*
Mapping of Shaka localization keys for control labels to FreeTube shortcuts.
See: https://github.com/shaka-project/shaka-player/blob/main/ui/locales/en.json
*/
const shakaControlKeysToShortcuts = {
MUTE: KeyboardShortcuts.VIDEO_PLAYER.GENERAL.MUTE,
UNMUTE: KeyboardShortcuts.VIDEO_PLAYER.GENERAL.MUTE,
PLAY: KeyboardShortcuts.VIDEO_PLAYER.PLAYBACK.PLAY,
PAUSE: KeyboardShortcuts.VIDEO_PLAYER.PLAYBACK.PLAY,
PICTURE_IN_PICTURE: KeyboardShortcuts.VIDEO_PLAYER.GENERAL.PICTURE_IN_PICTURE,
ENTER_PICTURE_IN_PICTURE: KeyboardShortcuts.VIDEO_PLAYER.GENERAL.PICTURE_IN_PICTURE,
EXIT_PICTURE_IN_PICTURE: KeyboardShortcuts.VIDEO_PLAYER.GENERAL.PICTURE_IN_PICTURE,
CAPTIONS: KeyboardShortcuts.VIDEO_PLAYER.GENERAL.CAPTIONS,
FULL_SCREEN: KeyboardShortcuts.VIDEO_PLAYER.GENERAL.FULLSCREEN,
EXIT_FULL_SCREEN: KeyboardShortcuts.VIDEO_PLAYER.GENERAL.FULLSCREEN
}
/** @type {Map<string, string>} */
const LOCALE_MAPPINGS = new Map(process.env.SHAKA_LOCALE_MAPPINGS)
export default defineComponent({
name: 'FtShakaVideoPlayer',
props: {
format: {
type: String,
required: true
},
manifestSrc: {
type: String,
required: true
},
manifestMimeType: {
type: String,
required: true
},
legacyFormats: {
type: Array,
default: () => ([])
},
startTime: {
type: Number,
default: null
},
captions: {
type: Array,
default: () => ([])
},
chapters: {
type: Array,
default: () => ([])
},
currentChapterIndex: {
type: Number,
default: 0
},
storyboardSrc: {
type: String,
default: ''
},
videoId: {
type: String,
default: ''
},
title: {
type: String,
default: ''
},
thumbnail: {
type: String,
default: ''
},
theatrePossible: {
type: Boolean,
default: false
},
useTheatreMode: {
type: Boolean,
default: false
},
vrProjection: {
type: String,
default: null
},
currentPlaybackRate: {
type: Number,
default: 1
},
},
emits: [
'error',
'loaded',
'ended',
'timeupdate',
'toggle-theatre-mode',
'playback-rate-updated'
],
setup: function (props, { emit, expose }) {
const { locale, t } = useI18n()
/** @type {shaka.Player|null} */
let player = null
/** @type {shaka.ui.Overlay|null} */
let ui = null
const events = new EventTarget()
/** @type {import('vue').Ref<HTMLDivElement | null>} */
const container = ref(null)
/** @type {import('vue').Ref<HTMLVideoElement | null>} */
const video = ref(null)
/** @type {import('vue').Ref<HTMLCanvasElement | null>} */
const vrCanvas = ref(null)
const hasLoaded = ref(false)
const hasMultipleAudioTracks = ref(false)
const isLive = ref(false)
const useOverFlowMenu = ref(false)
const fullWindowEnabled = ref(false)
const forceAspectRatio = ref(false)
const activeLegacyFormat = shallowRef(null)
/**
* @type {{
* url: string,
* label: string,
* language: string,
* mimeType: string,
* isAutotranslated?: boolean
* }[]}
*/
let sortedCaptions
// we don't need to sort if we only have one caption or don't have any
if (props.captions.length > 1) {
// theoretically we would resort when the language changes, but we can't remove captions that we already added to the player
sortedCaptions = sortCaptions(props.captions)
} else if (props.captions.length === 1) {
sortedCaptions = props.captions
} else {
sortedCaptions = []
}
/** @type {number|null} */
let restoreCaptionIndex = null
if (store.getters.getEnableSubtitlesByDefault && sortedCaptions.length > 0) {
restoreCaptionIndex = 0
}
const showStats = ref(false)
const stats = reactive({
resolution: {
width: 0,
height: 0,
frameRate: 0
},
playerDimensions: {
width: 0,
height: 0
},
bitrate: '0',
volume: '100',
bandwidth: '0',
buffered: '0',
frames: {
totalFrames: 0,
droppedFrames: 0
},
codecs: {
audioItag: '',
audioCodec: '',
videoItag: '',
videoCodec: ''
}
})
// #region settings
/** @type {import('vue').ComputedRef<boolean>} */
const autoplayVideos = computed(() => {
return store.getters.getAutoplayVideos
})
/** @type {import('vue').ComputedRef<boolean>} */
const displayVideoPlayButton = computed(() => {
return store.getters.getDisplayVideoPlayButton
})
watch(displayVideoPlayButton, (newValue) => {
ui.configure({
addBigPlayButton: newValue
})
})
/** @type {import('vue').ComputedRef<number>} */
const defaultSkipInterval = computed(() => {
return store.getters.getDefaultSkipInterval
})
watch(defaultSkipInterval, (newValue) => {
ui.configure({
tapSeekDistance: newValue
})
})
/** @type {import('vue').ComputedRef<number | 'auto'>} */
const defaultQuality = computed(() => {
const value = store.getters.getDefaultQuality
if (value === 'auto') { return value }
return parseInt(value)
})
/** @type {import('vue').ComputedRef<boolean>} */
const enterFullscreenOnDisplayRotate = computed(() => {
return store.getters.getEnterFullscreenOnDisplayRotate
})
watch(enterFullscreenOnDisplayRotate, (newValue) => {
ui.configure({
enableFullscreenOnRotation: newValue
})
})
const maxVideoPlaybackRate = computed(() => {
return parseInt(store.getters.getMaxVideoPlaybackRate)
})
const videoPlaybackRateInterval = computed(() => {
return parseFloat(store.getters.getVideoPlaybackRateInterval)
})
const playbackRates = computed(() => {
const interval = videoPlaybackRateInterval.value
const playbackRates = []
let i = interval
while (i <= maxVideoPlaybackRate.value) {
playbackRates.unshift(i)
i += interval
i = parseFloat(i.toFixed(2))
}
return playbackRates
})
watch(playbackRates, (newValue) => {
ui.configure({
playbackRates: newValue
})
})
/** @type {import('vue').ComputedRef<boolean>} */
const enableScreenshot = computed(() => {
return store.getters.getEnableScreenshot
})
/** @type {import('vue').ComputedRef<string>} */
const screenshotFormat = computed(() => {
return store.getters.getScreenshotFormat
})
/** @type {import('vue').ComputedRef<number>} */
const screenshotQuality = computed(() => {
return store.getters.getScreenshotQuality
})
/** @type {import('vue').ComputedRef<boolean>} */
const screenshotAskPath = computed(() => {
return store.getters.getScreenshotAskPath
})
/** @type {import('vue').ComputedRef<string>} */
const screenshotFolder = computed(() => {
return store.getters.getScreenshotFolderPath
})
/** @type {import('vue').ComputedRef<boolean>} */
const videoVolumeMouseScroll = computed(() => {
return store.getters.getVideoVolumeMouseScroll
})
/** @type {import('vue').ComputedRef<boolean>} */
const videoPlaybackRateMouseScroll = computed(() => {
return store.getters.getVideoPlaybackRateMouseScroll
})
/** @type {import('vue').ComputedRef<boolean>} */
const videoSkipMouseScroll = computed(() => {
return store.getters.getVideoSkipMouseScroll
})
/** @type {import('vue').ComputedRef<boolean>} */
const useSponsorBlock = computed(() => {
return store.getters.getUseSponsorBlock
})
/** @type {import('vue').ComputedRef<boolean>} */
const sponsorBlockShowSkippedToast = computed(() => {
return store.getters.getSponsorBlockShowSkippedToast
})
const sponsorSkips = computed(() => {
// save some work when sponsorblock is disabled
if (!useSponsorBlock.value) {
return {}
}
/** @type {SponsorBlockCategory[]} */
const sponsorCategories = ['sponsor',
'selfpromo',
'interaction',
'intro',
'outro',
'preview',
'music_offtopic',
'filler'
]
/** @type {Set<SponsorBlockCategory>} */
const autoSkip = new Set()
/** @type {SponsorBlockCategory[]} */
const seekBar = []
/** @type {Set<SponsorBlockCategory>} */
const promptSkip = new Set()
/**
* @type {{
* [key in SponsorBlockCategory]: {
* color: string,
* skip: 'autoSkip' | 'promptToSkip' | 'showInSeekBar' | 'doNothing'
* }
}} */
const categoryData = {}
sponsorCategories.forEach(x => {
let sponsorVal = {}
switch (x) {
case 'sponsor':
sponsorVal = store.getters.getSponsorBlockSponsor
break
case 'selfpromo':
sponsorVal = store.getters.getSponsorBlockSelfPromo
break
case 'interaction':
sponsorVal = store.getters.getSponsorBlockInteraction
break
case 'intro':
sponsorVal = store.getters.getSponsorBlockIntro
break
case 'outro':
sponsorVal = store.getters.getSponsorBlockOutro
break
case 'preview':
sponsorVal = store.getters.getSponsorBlockRecap
break
case 'music_offtopic':
sponsorVal = store.getters.getSponsorBlockMusicOffTopic
break
case 'filler':
sponsorVal = store.getters.getSponsorBlockFiller
break
}
if (sponsorVal.skip !== 'doNothing') {
seekBar.push(x)
}
if (sponsorVal.skip === 'autoSkip') {
autoSkip.add(x)
}
if (sponsorVal.skip === 'promptToSkip') {
promptSkip.add(x)
}
categoryData[x] = sponsorVal
})
return { autoSkip, seekBar, promptSkip, categoryData }
})
// #endregion settings
// #region SponsorBlock
/**
* @type {{
* uuid: string
* category: SponsorBlockCategory
* startTime: number,
* endTime: number
* }[]}
*/
let sponsorBlockSegments = []
let sponsorBlockAverageVideoDuration = 0
/**
* Yes a map would be much more suitable for this (unlike objects they retain the order that items were inserted),
* but Vue 2 doesn't support reactivity on Maps, so we have to use an array instead
* @type {import('vue').Ref<{uuid: string, translatedCategory: string, timeoutId: number}[]>}
*/
const skippedSponsorBlockSegments = ref([])
async function setupSponsorBlock() {
let segments, averageDuration
try {
({ segments, averageDuration } = await getSponsorBlockSegments(props.videoId, sponsorSkips.value.seekBar))
} catch (e) {
console.error(e)
segments = []
}
// check if the component is already getting destroyed
// which is possible because this function runs asynchronously
if (!ui || !player) {
return
}
if (segments.length > 0) {
sponsorBlockSegments = segments
sponsorBlockAverageVideoDuration = averageDuration
createSponsorBlockMarkers(averageDuration)
}
}
/**
* @param {number} currentTime
*/
function skipSponsorBlockSegments(currentTime) {
const { autoSkip } = sponsorSkips.value
if (autoSkip.size === 0) {
return
}
const video_ = video.value
let newTime = 0
const skippedSegments = []
sponsorBlockSegments.forEach(segment => {
if (autoSkip.has(segment.category) && currentTime < segment.endTime &&
(segment.startTime <= currentTime ||
// if we already have a segment to skip, check if there are any that are less than 150ms later,
// so that we can skip them all in one go (especially useful on slow connections)
(newTime > 0 && (segment.startTime < newTime || segment.startTime - newTime <= 0.150) && segment.endTime > newTime))) {
newTime = segment.endTime
skippedSegments.push(segment)
}
})
if (newTime === 0 || video_.ended) {
return
}
const videoEnd = player.seekRange().end
if (Math.abs(videoEnd - currentTime) < 1 || video_.ended) {
return
}
if (newTime > videoEnd || Math.abs(videoEnd - newTime) < 1) {
newTime = videoEnd
}
video_.currentTime = newTime
if (sponsorBlockShowSkippedToast.value) {
skippedSegments.forEach(({ uuid, category }) => {
// if the element already exists, just update the timeout, instead of creating a duplicate
// can happen at the end of the video sometimes
const existingSkip = skippedSponsorBlockSegments.value.find(skipped => skipped.uuid === uuid)
if (existingSkip) {
clearTimeout(existingSkip.timeoutId)
existingSkip.timeoutId = setTimeout(() => {
const index = skippedSponsorBlockSegments.value.findIndex(skipped => skipped.uuid === uuid)
skippedSponsorBlockSegments.value.splice(index, 1)
}, 2000)
} else {
skippedSponsorBlockSegments.value.push({
uuid,
translatedCategory: translateSponsorBlockCategory(category),
timeoutId: setTimeout(() => {
const index = skippedSponsorBlockSegments.value.findIndex(skipped => skipped.uuid === uuid)
skippedSponsorBlockSegments.value.splice(index, 1)
}, 2000)
})
}
})
}
}
// #endregion SponsorBlock
// #region player config
const seekingIsPossible = computed(() => {
if (props.manifestMimeType !== 'application/x-mpegurl') {
return true
}
const match = props.manifestSrc.match(/\/(?:manifest|playlist)_duration\/(\d+)\//)
// Check how many seconds we are allowed to seek, 30 is too short, 3600 is an hour which is great
return match != null && parseInt(match[1] || '0') > 30
})
/**
* @param {'dash'|'audio'|'legacy'} format
* @param {boolean} useAutoQuality
* @returns {shaka.extern.PlayerConfiguration}
*/
function getPlayerConfig(format, useAutoQuality = false) {
return {
// YouTube uses these values and they seem to work well in FreeTube too,
// so we might as well use them
streaming: {
bufferingGoal: 180,
rebufferingGoal: 0.02,
bufferBehind: 300
},
manifest: {
disableVideo: format === 'audio',
// makes captions work for live streams and doesn't seem to have any negative affect on VOD videos
segmentRelativeVttTiming: true,
dash: {
manifestPreprocessorTXml: manifestPreprocessorTXml
},
},
abr: {
enabled: useAutoQuality,
// This only affects the "auto" quality, users can still manually select whatever quality they want.
restrictToElementSize: true
},
autoShowText: shaka.config.AutoShowText.NEVER,
// Prioritise variants that are predicted to play:
// - `smooth`: without dropping frames
// - `powerEfficient` the spec is quite vague but in Chromium it should prioritise hardware decoding when available
// https://developer.mozilla.org/en-US/docs/Web/API/MediaCapabilities/decodingInfo
preferredDecodingAttributes: format === 'dash' ? ['smooth', 'powerEfficient'] : [],
// Electron doesn't like YouTube's vp9 VR video streams and throws:
// "CHUNK_DEMUXER_ERROR_APPEND_FAILED: Projection element is incomplete; ProjectionPoseYaw required."
// So use the AV1 and h264 codecs instead which it doesn't reject
preferredVideoCodecs: typeof props.vrProjection === 'string' ? ['av01', 'avc1'] : []
}
}
/**
* @param {shaka.extern.xml.Node} mpdNode
*/
function manifestPreprocessorTXml(mpdNode) {
/** @type {shaka.extern.xml.Node[]} */
const periods = mpdNode.children?.filter(child => typeof child !== 'string' && child.tagName === 'Period') ?? []
sortAdapationSetsByCodec(periods)
if (mpdNode.attributes.type === 'dynamic') {
// fix live stream loading issues
// YouTube uses a 12 second delay on the official website for normal streams
// and a shorter one for low latency streams
// If we don't add a little bit of a delay, we get presented with a loading symbol every 5 seconds,
// while shaka-player processes the new manifest and segments
const minimumUpdatePeriod = parseFloat(mpdNode.attributes.minimumUpdatePeriod.match(/^PT(\d+(?:\.\d+)?)S$/)[1])
mpdNode.attributes.suggestedPresentationDelay = `PT${(minimumUpdatePeriod * 2).toFixed(3)}S`
// fix live streams with subtitles having duplicate Representation ids
// shaka-player throws DASH_DUPLICATE_REPRESENTATION_ID if we don't fix it
for (const period of periods) {
/** @type {shaka.extern.xml.Node[]} */
const representations = []
for (const periodChild of period.children) {
if (typeof periodChild !== 'string' && periodChild.tagName === 'AdaptationSet') {
for (const adaptationSetChild of periodChild.children) {
if (typeof adaptationSetChild !== 'string' && adaptationSetChild.tagName === 'Representation') {
representations.push(adaptationSetChild)
}
}
}
}
const knownIds = new Set()
let counter = 0
for (const representation of representations) {
const id = representation.attributes.id
if (knownIds.has(id)) {
const newId = `${id}-ft-fix-${counter}`
representation.attributes.id = newId
knownIds.add(newId)
counter++
} else {
knownIds.add(id)
}
}
}
} else if (!process.env.SUPPORTS_LOCAL_API) {
repairInvidiousManifest(periods)
}
}
/**
* @param {shaka.extern.xml.Node[]} periods
*/
function sortAdapationSetsByCodec(periods) {
/** @param {shaka.extern.xml.Node} adaptationSet */
const getCodecsPrefix = (adaptationSet) => {
const codecs = adaptationSet.attributes.codecs ??
adaptationSet.children
.find(child => typeof child !== 'string' && child.tagName === 'Representation').attributes.codecs
return codecs.split('.')[0]
}
const codecPriorities = [
// audio
'opus',
'mp4a',
'ec-3',
'ac-3',
// video
'av01',
'vp09',
'vp9',
'avc1'
]
for (const period of periods) {
period.children
?.sort((
/** @type {shaka.extern.xml.Node | string} */ a,
/** @type {shaka.extern.xml.Node | string} */ b
) => {
if (typeof a === 'string' || a.tagName !== 'AdaptationSet' ||
typeof b === 'string' || b.tagName !== 'AdaptationSet') {
return 0
}
const typeA = a.attributes.contentType || a.attributes.mimeType.split('/')[0]
const typeB = b.attributes.contentType || b.attributes.mimeType.split('/')[0]
// always place image and text tracks AdaptionSets last in the manifest
if (typeA !== 'video' && typeA !== 'audio') {
return 1
}
if (typeB !== 'video' && typeB !== 'audio') {
return -1
}
const codecsPrefixA = getCodecsPrefix(a)
const codecsPrefixB = getCodecsPrefix(b)
return codecPriorities.indexOf(codecsPrefixA) - codecPriorities.indexOf(codecsPrefixB)
})
}
}
// #endregion player config
// #region UI config
const useVrMode = computed(() => {
return props.format === 'dash' && props.vrProjection === 'EQUIRECTANGULAR'
})
const uiConfig = computed(() => {
/** @type {shaka.extern.UIConfiguration} */
const uiConfig = {
controlPanelElements: [
'play_pause',
'mute',
'volume',
'time_and_duration',
'spacer'
],
overflowMenuButtons: [],
// only set this to label when we actually have labels, so that the warning doesn't show up
// about it being set to labels, but that the audio tracks don't have labels
trackLabelFormat: hasMultipleAudioTracks.value ? TrackLabelFormat.LABEL : TrackLabelFormat.LANGUAGE,
// Only set it to label if we added the captions ourselves,
// some live streams come with subtitles in the DASH manifest, but without labels
textTrackLabelFormat: sortedCaptions.length > 0 ? TrackLabelFormat.LABEL : TrackLabelFormat.LANGUAGE,
displayInVrMode: useVrMode.value
}
/** @type {string[]} */
let elementList = []
if (useOverFlowMenu.value) {
uiConfig.overflowMenuButtons = [
'ft_screenshot',
'playback_rate',
'loop',
'ft_audio_tracks',
'captions',
'picture_in_picture',
'ft_full_window',
props.format === 'legacy' ? 'ft_legacy_quality' : 'quality',
'recenter_vr',
'toggle_stereoscopic',
]
elementList = uiConfig.overflowMenuButtons
uiConfig.controlPanelElements.push('overflow_menu')
} else {
uiConfig.controlPanelElements.push(
'recenter_vr',
'toggle_stereoscopic',
'ft_screenshot',
'playback_rate',
'loop',
'ft_audio_tracks',
'captions',
'picture_in_picture',
'ft_theatre_mode',
'ft_full_window',
props.format === 'legacy' ? 'ft_legacy_quality' : 'quality'
)
elementList = uiConfig.controlPanelElements
}
uiConfig.controlPanelElements.push('fullscreen')
if (!enableScreenshot.value || props.format === 'audio') {
const index = elementList.indexOf('ft_screenshot')
elementList.splice(index, 1)
}
if (!props.theatrePossible) {
const index = elementList.indexOf('ft_theatre_mode')
// doesn't exist in overflow menu, as theatre mode only works on wide screens
if (index !== -1) {
elementList.splice(index, 1)
}
}
if (props.format === 'audio') {
const index = elementList.indexOf('picture_in_picture')
elementList.splice(index, 1)
}
if (isLive.value) {
const index = elementList.indexOf('loop')
elementList.splice(index, 1)
}
if (!useVrMode.value) {
const indexRecenterVr = elementList.indexOf('recenter_vr')
elementList.splice(indexRecenterVr, 1)
const indexToggleStereoscopic = elementList.indexOf('toggle_stereoscopic')
elementList.splice(indexToggleStereoscopic, 1)
}
return uiConfig
})
/**
* For the first call we want to set initial values for options that may change later,
* as well as setting the options that we won't change again.
*
* For all subsequent calls we only want to reconfigure the options that have changed.
* e.g. due to the active format changing or the user changing settings
* @param {boolean} firstTime
*/
function configureUI(firstTime = false) {
if (firstTime) {
const firstTimeConfig = {
addSeekBar: seekingIsPossible.value,
customContextMenu: true,
contextMenuElements: ['ft_stats'],
enableTooltips: true,
seekBarColors: {
played: 'var(--primary-color)'
},
volumeBarColors: {
level: 'var(--primary-color)'
},
// these have their own watchers
addBigPlayButton: displayVideoPlayButton.value,
enableFullscreenOnRotation: enterFullscreenOnDisplayRotate.value,
playbackRates: playbackRates.value,
tapSeekDistance: defaultSkipInterval.value,
// we have our own ones (shaka-player's ones are quite limited)
enableKeyboardPlaybackControls: false,
// TODO: enable this when electron gets document PiP support
// https://github.com/electron/electron/issues/39633
preferDocumentPictureInPicture: false
}
// Combine the config objects so we only need to do one configure call
// as shaka-player recreates the UI when you call configure
Object.assign(firstTimeConfig, uiConfig.value)
ui.configure(firstTimeConfig)
} else {
ui.configure(uiConfig.value)
}
}
/**
* @param {WheelEvent} event
*/
function handleControlsContainerWheel(event) {
/** @type {DOMTokenList} */
const classList = event.target.classList
if (classList.contains('shaka-scrim-container') ||
classList.contains('shaka-fast-foward-container') ||
classList.contains('shaka-rewind-container') ||
classList.contains('shaka-play-button-container') ||
classList.contains('shaka-play-button')) {
//
if (event.ctrlKey || event.metaKey) {
if (videoPlaybackRateMouseScroll.value) {
mouseScrollPlaybackRate(event)
}
} else {
if (videoVolumeMouseScroll.value) {
mouseScrollVolume(event)
} else if (videoSkipMouseScroll.value) {
mouseScrollSkip(event)
}
}
}
}
/**
* @param {MouseEvent} event
*/
function handleControlsContainerClick(event) {
if (event.ctrlKey || event.metaKey) {
// stop shaka-player's click handler firing
event.stopPropagation()
video.value.playbackRate = props.currentPlaybackRate
video.value.defaultPlaybackRate = props.currentPlaybackRate
}
}
function addUICustomizations() {
/** @type {HTMLDivElement} */
const controlsContainer = ui.getControls().getControlsContainer()
controlsContainer.removeEventListener('wheel', handleControlsContainerWheel)
controlsContainer.removeEventListener('click', handleControlsContainerClick, true)
if (!useVrMode.value) {
if (videoVolumeMouseScroll.value || videoSkipMouseScroll.value || videoPlaybackRateMouseScroll.value) {
controlsContainer.addEventListener('wheel', handleControlsContainerWheel)
}
if (videoPlaybackRateMouseScroll.value) {
controlsContainer.addEventListener('click', handleControlsContainerClick, true)
}
}
// make scrolling over volume slider change the volume
container.value.querySelector('.shaka-volume-bar').addEventListener('wheel', mouseScrollVolume)
// title overlay when the video is fullscreened
// placing this inside the controls container so that we can fade it in and out at the same time as the controls
const fullscreenTitleOverlay = document.createElement('h1')
fullscreenTitleOverlay.textContent = props.title
fullscreenTitleOverlay.className = 'playerFullscreenTitleOverlay'
controlsContainer.appendChild(fullscreenTitleOverlay)
if (hasLoaded.value && props.chapters.length > 0) {
createChapterMarkers()
}
if (useSponsorBlock.value && sponsorBlockSegments.length > 0) {
let duration
if (hasLoaded.value) {
const seekRange = player.seekRange()
duration = seekRange.end - seekRange.start
} else {
duration = sponsorBlockAverageVideoDuration
}
createSponsorBlockMarkers(duration)
}
}
watch(uiConfig, (newValue, oldValue) => {
if (newValue !== oldValue && ui) {
configureUI()
}
})
watch(videoVolumeMouseScroll, (newValue, oldValue) => {
if (newValue !== oldValue && ui) {
configureUI()
}
})
watch(videoPlaybackRateMouseScroll, (newValue, oldValue) => {
if (newValue !== oldValue && ui) {
configureUI()
}
})
watch(videoSkipMouseScroll, (newValue, oldValue) => {
if (newValue !== oldValue && ui) {
configureUI()
}
})
/** @type {ResizeObserver|null} */
let resizeObserver = null
/** @type {ResizeObserverCallback} */
function resized(entries) {
useOverFlowMenu.value = entries[0].contentBoxSize[0].inlineSize <= USE_OVERFLOW_MENU_WIDTH_THRESHOLD
}
// #endregion UI config
// #region player locales
// shaka-player ships with some locales prebundled and already loaded
const loadedLocales = new Set(process.env.SHAKA_LOCALES_PREBUNDLED)
/**
* @param {string} locale
*/
async function setLocale(locale) {
// For most of FreeTube's locales, there is an equivalent one in shaka-player,
// however if there isn't one we should fall back to US English.
// At the time of writing "et", "eu", "gl", "is" don't have any translations
const shakaLocale = LOCALE_MAPPINGS.get(locale) ?? 'en'