-
-
Notifications
You must be signed in to change notification settings - Fork 543
/
player.js
1319 lines (1136 loc) · 56.9 KB
/
player.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*------------------------------------------------------------------------------
AUTOPLAY DISABLE
------------------------------------------------------------------------------*/
ImprovedTube.autoplayDisable = function () {
var video = ImprovedTube.elements.player;
if (ImprovedTube.video_url !== location.href) {
this.user_interacted = false;
}
// if (allow autoplay is false) and (no ads playing) and
// ( there is a video and ( (it is not in a playlist and auto play is off ) or ( playlist auto play is off and it is not in a playlist ) ) ) or (if we are in a channel and the channel trailer autoplay is off) )
if (!this.user_interacted && video.classList.contains('ad-showing') === false &&
(
// quick fix #1703 thanks to @AirRaid#9957
(/* document.documentElement.dataset.pageType === "video" */ location.href.indexOf('/watch?') !== -1 && ((location.href.indexOf('list=') === -1 && ImprovedTube.storage.player_autoplay_disable) || (ImprovedTube.storage.playlist_autoplay === false && location.href.indexOf('list=') !== -1))) ||
(/* document.documentElement.dataset.pageType === "channel" */ ImprovedTube.regex.channel.test(location.href) && ImprovedTube.storage.channel_trailer_autoplay === false)
)
)
{if (!ImprovedTube.autoplayDeniedOnce) {
setTimeout(function () { video.pauseVideo(); });
ImprovedTube.autoplayDeniedOnce = true;
} else { console.log("autoplay:off - should we pause here again?"); } }
};
/*------------------------------------------------------------------------------
FORCED PLAY VIDEO FROM THE BEGINNING
------------------------------------------------------------------------------*/
ImprovedTube.forcedPlayVideoFromTheBeginning = function () {
if (this.storage.forced_play_video_from_the_beginning === true && document.documentElement.dataset.pageType === 'video' && !this.video_url.match(this.regex.video_time)?.[1]) {
this.elements.player.seekTo(0);
}
};
/*------------------------------------------------------------------------------
AUTOPAUSE WHEN SWITCHING TABS
------------------------------------------------------------------------------*/
ImprovedTube.playerAutopauseWhenSwitchingTabs = function () {
var player = ImprovedTube.elements.player;
if (this.storage.player_autopause_when_switching_tabs === true && player) {
if (this.focus === false) {
this.played_before_blur = player.getPlayerState() === 1;
player.pauseVideo();
} else if (this.focus === true && this.played_before_blur === true) {
player.playVideo();
}
}
};
/*------------------------------------------------------------------------------
AUTO PIP WHEN SWITCHING TABS
------------------------------------------------------------------------------*/
ImprovedTube.playerAutoPip = function () {
const video = ImprovedTube.elements.video;
if (this.storage.player_autoPip === true && video) {
(async () => {
try {
await video.requestPictureInPicture();
} catch (error) {
console.error('Failed to enter Picture-in-Picture mode', error);
}
})();
}
}
/*------------------------------------------------------------------------------
FORCED PLAYBACK SPEED
------------------------------------------------------------------------------*/
ImprovedTube.playerPlaybackSpeed = function () { if (this.storage.player_forced_playback_speed === true) {
var player = this.elements.player,
video = player.querySelector('video'),
option = this.storage.player_playback_speed;
if (this.isset(option) === false) { option = 1; }
else if ( option !== 1 && video.playbackRate !== option && (video.playbackRate > 1 || video.playbackRate < 1) )
{ console.log("skipping permanent speed, since speed was manually set differently for this video to:" + video.playbackRate); return; }
if ( !player.getVideoData().isLive || player.getVideoData().isLive === false)
{ player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); // #1729 q2 // hi! @raszpl
if ( (this.storage.player_force_speed_on_music !== true || this.storage.player_dont_speed_education === true)
&& option !== 1) {
ImprovedTube.speedException = function () {
if (this.storage.player_dont_speed_education === true && DATA.genre === 'Education')
{player.setPlaybackRate(Number(1)); video.playbackRate = Number(1); return;}
if (this.storage.player_force_speed_on_music === true)
{ //player.setPlaybackRate(Number(option)); video.playbackRate = Number(option);
return;}
if (DATA.keywords && !keywords) { keywords = DATA.keywords.join(', ') || ''; }
if (keywords === 'video, sharing, camera phone, video phone, free, upload') { keywords = ''; }
var musicIdentifiers = /(official|music|lyrics?)[ -]video|(cover|studio|radio|album|alternate)[- ]version|soundtrack|unplugged|\bmedley\b|\blo-fi\b|\blofi\b|a(lla)? cappella|feat\.|(piano|guitar|jazz|ukulele|violin|reggae)[- ](version|cover)|karaok|backing[- ]track|instrumental|(sing|play)[- ]?along|卡拉OK|卡拉OK|الكاريوكي|караоке|カラオケ|노래방|bootleg|mashup|Radio edit|Guest (vocals|musician)|(title|opening|closing|bonus|hidden)[ -]track|live acoustic|interlude|featuring|recorded (at|live)/i;
var musicIdentifiersTitleOnly = /lyrics|theme song|\bremix|\bAMV ?[^a-z0-9]|[^a-z0-9] ?AMV\b|\bfull song\b|\bsong:|\bsong[\!$]|^song\b|( - .*\bSong\b|\bSong\b.* - )|cover ?[^a-z0-9]|[^a-z0-9] ?cover|\bconcert\b/i;
var musicIdentifiersTitle = new RegExp(musicIdentifiersTitleOnly.source + '|' + musicIdentifiers.source, "i");
var musicRegexMatch = musicIdentifiersTitle.test(DATA.title);
if (!musicRegexMatch) {
var musicIdentifiersTagsOnly = /, (lyrics|remix|song|music|AMV|theme song|full song),|\(Musical Genre\)|, jazz|, reggae/i;
var musicIdentifiersTags = new RegExp(musicIdentifiersTagsOnly.source + '|' + musicIdentifiers.source, "i");
keywordsAmount = 1 + ((keywords || '').match(/,/) || []).length;
if ( ((keywords || '').match(musicIdentifiersTags) || []).length / keywordsAmount > 0.08) {
musicRegexMatch = true}}
notMusicRegexMatch = /\bdo[ck]u|interv[iyj]|back[- ]?stage|インタビュー|entrevista|面试|面試|회견|wawancara|مقابلة|интервью|entretien|기록한 것|记录|記錄|ドキュメンタリ|وثائقي|документальный/i.test(DATA.title + " " + keywords);
// (Tags/keywords shouldnt lie & very few songs titles might have these words)
if (DATA.duration) {
function parseDuration(duration) { const [_, h = 0, m = 0, s = 0] = duration.match(/PT(?:(\d+)?H)?(?:(\d+)?M)?(\d+)?S?/).map(part => parseInt(part) || 0);
return h * 3600 + m * 60 + s; }
DATA.lengthSeconds = parseDuration(DATA.duration); }
function testSongDuration(s, ytMusic) {
if (135 <= s && s <= 260) {return 'veryCommon';}
if (105 <= s && s <= 420) {return 'common';}
if (420 <= s && s <= 720) {return 'long';}
if (45 <= s && s <= 105) {return 'short';}
if (ytMusic && ytMusic > 1 && (85 <= s / ytMusic && (s / ytMusic <= 375 || ytMusic == 10))) {return 'multiple';}
//does Youtube ever show more than 10 songs below the description?
}
var songDurationType = testSongDuration(DATA.lengthSeconds);
console.log("genre: " + DATA.genre + "//title: " + DATA.title + "//keywords: " + keywords + "//music word match: " + musicRegexMatch + "// not music word match:" + notMusicRegexMatch + "//duration: " + DATA.lengthSeconds + "//song duration type: " + songDurationType);
// check if the video is PROBABLY MUSIC:
if ( ( DATA.genre === 'Music' && (!notMusicRegexMatch || songDurationType === 'veryCommon'))
|| ( musicRegexMatch && !notMusicRegexMatch && (typeof songDurationType !== 'undefined'
|| (/album|Álbum|专辑|專輯|एलबम|البوم|アルバム|альбом|앨범|mixtape|concert|playlist|\b(live|cd|vinyl|lp|ep|compilation|collection|symphony|suite|medley)\b/i.test(DATA.title + " " + keywords)
&& 1150 <= DATA.lengthSeconds && DATA.lengthSeconds <= 5000)) )
|| ( DATA.genre === 'Music' && musicRegexMatch && (typeof songDurationType !== 'undefined'
|| (/album|Álbum|专辑|專輯|एलबम|البوم|アルバム|альбом|앨범|mixtape|concert|playlist|\b(live|cd|vinyl|lp|ep|compilation|collection|symphony|suite|medley)\b/i.test(DATA.title + " " + keywords)
&& 1150 <= DATA.lengthSeconds && DATA.lengthSeconds <= 5000)) )
|| (amountOfSongs && testSongDuration(DATA.lengthSeconds, amountOfSongs ) !== 'undefined')
// || location.href.indexOf('music.') !== -1 // (=currently we are only running on www.youtube.com anyways)
) { player.setPlaybackRate(1); video.playbackRate = 1; console.log ("...,thus must be music?"); }
else { // Now this video might rarely be music
// - however we can make extra-sure after waiting for the video descripion to load... (#1539)
var tries = 0; var intervalMs = 210; if (location.href.indexOf('/watch?') !== -1) {var maxTries = 10;} else {var maxTries = 0;}
// ...except when it is an embedded player?
var waitForDescription = setInterval(() => {
if (++tries >= maxTries) {
subtitle = document.querySelector('#title + #subtitle:last-of-type')
if ( subtitle && 1 <= Number((subtitle?.innerHTML?.match(/^\d+/) || [])[0]) // indicates buyable/registered music (amount of songs)
&& typeof testSongDuration(DATA.lengthSeconds, Number((subtitle?.innerHTML?.match(/^\d+/) || [])[0]) ) !== 'undefined' ) // resonable duration
{player.setPlaybackRate(1); video.playbackRate = 1; console.log("...but YouTube shows music below the description!"); clearInterval(waitForDescription); }
intervalMs *= 1.11; }}, intervalMs);
window.addEventListener('load', () => { setTimeout(() => { clearInterval(waitForDescription); }, 1234); });
}
}
//DATA (TO-DO: make the Data available to more/all features? #1452 #1763 (Then can replace ImprovedTube.elements.category === 'music', VideoID is also used elsewhere)
DATA = {};
defaultKeywords = "video,sharing,camera,phone,video phone,free,upload";
DATA.keywords = false; keywords = false; amountOfSongs = false;
DATA.videoID = ImprovedTube.videoId() || false;
ImprovedTube.fetchDOMData = function () {
// if (history.length > 1 && history.state.endpoint.watchEndpoint) {
try { DATA = JSON.parse(document.querySelector('#microformat script')?.textContent) ?? false; DATA.title = DATA.name;}
catch { DATA.genre = false; DATA.keywords = false; DATA.lengthSeconds = false;
try {
DATA.title = document.getElementsByTagName('meta')?.title?.content || false;
DATA.genre = document.querySelector('meta[itemprop=genre]')?.content || false;
DATA.duration = document.querySelector('meta[itemprop=duration]')?.content || false;
} catch {}} if ( DATA.title === ImprovedTube.videoTitle() )
{ keywords = document.getElementsByTagName('meta')?.keywords?.content || false; if(!keywords){keyword=''} ImprovedTube.speedException(); }
else { keywords = ''; (async function () { try { const response = await fetch(`https://www.youtube.com/watch?v=${DATA.videoID}`);
const htmlContent = await response.text();
const metaRegex = /<meta[^>]+name=["'](keywords|genre|duration)["'][^>]+content=["']([^"']+)["'][^>]*>/gi;
let match; while ((match = metaRegex.exec(htmlContent)) !== null) {
const [, property, value] = match;
if (property === 'keywords') { keywords = value;} else {DATA[property] = value;}
}
amountOfSongs = (htmlContent.slice(-80000).match(/},"subtitle":{"simpleText":"(\d*)\s/) || [])[1] || false;
if (keywords) { ImprovedTube.speedException(); }
} catch (error) { console.error('Error: fetching from https://Youtube.com/watch?v=${DATA.videoID}', error); keywords = ''; }
})();
}
};
if ( (history && history.length === 1) || !history?.state?.endpoint?.watchEndpoint) { ImprovedTube.fetchDOMData();}
else {
//Invidious instances (Nov2023)
const invidiousInstances = ['iv.datura.network', 'vid.puffyan.us', 'invidious.perennialte.ch', 'iv.melmac.space', 'inv.in.projectsegfau.lt', 'invidious.asir.dev', 'inv.zzls.xyz', 'invidious.io.lol', 'onion.tube', 'yewtu.be', 'invidious.protokolla.fi', 'inv.citw.lgbt', 'anontube.lvkaszus.pl', 'iv.nboeck.de', 'invidious.no-logs.com', 'vid.priv.au', 'yt.cdaut.de', 'invidious.slipfox.xyz', 'yt.artemislena.eu', 'invidious.drgns.space', 'invidious.einfachzocken.eu', 'invidious.projectsegfau.lt', 'invidious.nerdvpn.de', 'invidious.private.coffee', 'invidious.lunar.icu', 'invidious.privacydev.net', 'invidious.fdn.fr', 'yt.oelrichsgarcia.de', 'iv.ggtyler.dev', 'inv.tux.pizza', 'yt.drgnz.club', 'inv.us.projectsegfau.lt'];
function getRandomInvidiousInstance() { return invidiousInstances[Math.floor(Math.random() * invidiousInstances.length)];}
(async function () { let retries = 5; let invidiousFetched = false;
async function fetchInvidiousData() {
try {const response = await fetch(`https://${getRandomInvidiousInstance()}/api/v1/videos/${DATA.videoID}?fields=genre,title,lengthSeconds,keywords`);
DATA = await response.json();
if (DATA.genre && DATA.title && DATA.keywords && DATA.lengthSeconds) { if (DATA.keywords.toString() === defaultKeywords ) {DATA.keywords = ''}
ImprovedTube.speedException(); invidiousFetched = true; }
} catch (error) { console.error('Error: Invidious API: ', error); }
}
while (retries > 0 && !invidiousFetched) { await fetchInvidiousData();
if (!invidiousFetched) { await new Promise(resolve => setTimeout(resolve, retries === 5 ? 1234 : 432)); retries--; } }
if(!invidiousFetched){ if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', ImprovedTube.fetchDOMData())}
else { ImprovedTube.fetchDOMData();} }
})();
}
} // else { }
}
}
}
/*------------------------------------------------------------------------------
SUBTITLES
------------------------------------------------------------------------------*/
ImprovedTube.subtitles = function () {
if (this.storage.player_subtitles === true) {
var player = this.elements.player;
if (player && player.toggleSubtitlesOn) {
player.toggleSubtitlesOn();
}
}
};
/*------------------------------------------------------------------------------
SUBTITLES LANGUAGE
------------------------------------------------------------------------------*/
ImprovedTube.subtitlesLanguage = function () {
var option = this.storage.subtitles_language;
if (this.isset(option) && option !== 'default') {
var player = this.elements.player,
button = this.elements.player_subtitles_button;
if (player && player.getOption && button && button.getAttribute('aria-pressed') === 'true') {
var tracklist = this.elements.player.getOption('captions', 'tracklist', {
includeAsr: true
});
var matchTrack = false;
for (var i =0, l = tracklist.length; i<l; i++){
if (tracklist[i].languageCode.includes(option)) {
if( false === tracklist[i].vss_id.includes("a.") || true === this.storage.auto_generate){
this.elements.player.setOption('captions', 'track', tracklist[i]);
matchTrack = true; break;
}
}
}
// if (!matchTrack){ player.toggleSubtitles(); }
}
}
};
/*------------------------------------------------------------------------------
SUBTITLES FONT FAMILY
------------------------------------------------------------------------------*/
ImprovedTube.subtitlesFontFamily = function () {
var option = this.storage.subtitles_font_family;
if (this.isset(option)) {
var player = this.elements.player,
button = this.elements.player_subtitles_button;
if (player && player.getSubtitlesUserSettings && button && button.getAttribute('aria-pressed') === 'true') {
var settings = player.getSubtitlesUserSettings();
if (settings) {
settings.fontFamily = Number(option);
player.updateSubtitlesUserSettings(settings);
}
}
}
};
/*------------------------------------------------------------------------------
SUBTITLES FONT COLOR
------------------------------------------------------------------------------*/
ImprovedTube.subtitlesFontColor = function () {
var option = this.storage.subtitles_font_color;
if (this.isset(option)) {
var player = this.elements.player,
button = this.elements.player_subtitles_button;
if (player && player.getSubtitlesUserSettings && button && button.getAttribute('aria-pressed') === 'true') {
var settings = player.getSubtitlesUserSettings();
if (settings) {
settings.color = option;
player.updateSubtitlesUserSettings(settings);
}
}
}
};
/*------------------------------------------------------------------------------
SUBTITLES FONT SIZE
------------------------------------------------------------------------------*/
ImprovedTube.subtitlesFontSize = function () {
var option = this.storage.subtitles_font_size;
if (this.isset(option)) {
var player = this.elements.player,
button = this.elements.player_subtitles_button;
if (player && player.getSubtitlesUserSettings && button && button.getAttribute('aria-pressed') === 'true') {
var settings = player.getSubtitlesUserSettings();
if (settings) {
settings.fontSizeIncrement = Number(option);
player.updateSubtitlesUserSettings(settings);
}
}
}
};
/*------------------------------------------------------------------------------
SUBTITLES BACKGROUND COLOR
------------------------------------------------------------------------------*/
ImprovedTube.subtitlesBackgroundColor = function () {
var option = this.storage.subtitles_background_color;
if (this.isset(option)) {
var player = this.elements.player,
button = this.elements.player_subtitles_button;
if (player && player.getSubtitlesUserSettings && button && button.getAttribute('aria-pressed') === 'true') {
var settings = player.getSubtitlesUserSettings();
if (settings) {
settings.background = option;
player.updateSubtitlesUserSettings(settings);
}
}
}
};
/*------------------------------------------------------------------------------
SUBTITLES BACKGROUND OPACITY
------------------------------------------------------------------------------*/
ImprovedTube.subtitlesBackgroundOpacity = function () {
var option = this.storage.subtitles_background_opacity;
if (this.isset(option)) {
var player = this.elements.player,
button = this.elements.player_subtitles_button;
if (player && player.getSubtitlesUserSettings && button && button.getAttribute('aria-pressed') === 'true') {
var settings = player.getSubtitlesUserSettings();
if (settings) {
settings.backgroundOpacity = option / 100;
player.updateSubtitlesUserSettings(settings);
}
}
}
};
/*------------------------------------------------------------------------------
SUBTITLES WINDOW COLOR
------------------------------------------------------------------------------*/
ImprovedTube.subtitlesWindowColor = function () {
var option = this.storage.subtitles_window_color;
if (this.isset(option)) {
var player = this.elements.player,
button = this.elements.player_subtitles_button;
if (player && player.getSubtitlesUserSettings && button && button.getAttribute('aria-pressed') === 'true') {
var settings = player.getSubtitlesUserSettings();
if (settings) {
settings.windowColor = option;
player.updateSubtitlesUserSettings(settings);
}
}
}
};
/*------------------------------------------------------------------------------
SUBTITLES WINDOW OPACITY
------------------------------------------------------------------------------*/
ImprovedTube.subtitlesWindowOpacity = function () {
var option = this.storage.subtitles_window_opacity;
if (this.isset(option)) {
var player = this.elements.player,
button = this.elements.player_subtitles_button;
if (player && player.getSubtitlesUserSettings && button && button.getAttribute('aria-pressed') === 'true') {
var settings = player.getSubtitlesUserSettings();
if (settings) {
settings.windowOpacity = Number(option) / 100;
player.updateSubtitlesUserSettings(settings);
}
}
}
};
/*------------------------------------------------------------------------------
SUBTITLES CHARACTER EDGE STYLE
------------------------------------------------------------------------------*/
ImprovedTube.subtitlesCharacterEdgeStyle = function () {
var option = this.storage.subtitles_character_edge_style;
if (this.isset(option)) {
var player = this.elements.player,
button = this.elements.player_subtitles_button;
if (player && player.getSubtitlesUserSettings && button && button.getAttribute('aria-pressed') === 'true') {
var settings = player.getSubtitlesUserSettings();
if (settings) {
settings.charEdgeStyle = Number(option);
player.updateSubtitlesUserSettings(settings);
}
}
}
};
/*------------------------------------------------------------------------------
SUBTITLES FONT OPACITY
------------------------------------------------------------------------------*/
ImprovedTube.subtitlesFontOpacity = function () {
var option = this.storage.subtitles_font_opacity;
if (this.isset(option)) {
var player = this.elements.player,
button = this.elements.player_subtitles_button;
if (player && player.getSubtitlesUserSettings && button && button.getAttribute('aria-pressed') === 'true') {
var settings = player.getSubtitlesUserSettings();
if (settings) {
settings.textOpacity = option / 100;
player.updateSubtitlesUserSettings(settings);
}
}
}
};
/*------------------------------------------------------------------------------
SUBTITLES DISABLE SUBTILES FOR LYRICS
------------------------------------------------------------------------------*/
ImprovedTube.subtitlesDisableLyrics = function () {
if (this.storage.subtitles_disable_lyrics === true) {
var player = this.elements.player,
button = this.elements.player_subtitles_button;
if (player && player.toggleSubtitles && button && button.getAttribute('aria-pressed') === 'true') {
// Music detection only uses 3 identifiers for Lyrics: lyrics, sing-along, karaoke.
// Easier to simply use those here. Can replace with music detection later.
const terms = ["sing along", "sing-along", "karaoke", "lyric", "卡拉OK", "卡拉OK", "الكاريوكي", "караоке", "カラオケ","노래방"];
if (terms.some(term => ImprovedTube.videoTitle().toLowerCase().includes(term))) {
player.toggleSubtitles();
}
}
}
};
/*------------------------------------------------------------------------------
UP NEXT AUTOPLAY
------------------------------------------------------------------------------*/
ImprovedTube.upNextAutoplay = function () {
var option = this.storage.up_next_autoplay;
if (this.isset(option)) {
var toggle = document.querySelector('.ytp-autonav-toggle-button');
if (toggle) {
if (option !== (toggle.getAttribute('aria-checked') === 'true')) {
toggle.click();
}
}
}
};
/*------------------------------------------------------------------------------
ADS
------------------------------------------------------------------------------*/
ImprovedTube.playerAds = function (parent) {
let button = parent.querySelector('.ytp-ad-skip-button-modern.ytp-button,[class*="ytp-ad-skip-button"].ytp-button') || parent;
// TODO: Replace this with centralized video element pointer
let video = document.querySelector('.video-stream.html5-main-video') || false;
function skipAd() {
if (video) video.currentTime = video.duration;
if (button) button.click();
}
if (this.storage.ads === 'block_all') {
skipAd();
} else if (this.storage.ads === 'subscribed_channels') {
if (!parent.querySelector('#meta paper-button[subscribed]')) {
skipAd();
}
} else if (this.storage.ads === 'block_music') {
if (ImprovedTube.elements.category === 'music') {
skipAd();
}
} else if (this.storage.ads === 'small_creators'){
let userDefiniedLimit = this.storage.smallCreatorsCount * parseInt(this.storage.smallCreatorsUnit);
let subscribersNumber = ImprovedTube.subscriberCount;
if(subscribersNumber > userDefiniedLimit){
skipAd();
}
}
};
/*------------------------------------------------------------------------------
AUTO FULLSCREEN
------------------------------------------------------------------------------*/
ImprovedTube.playerAutofullscreen = function () {
if (
this.storage.player_autofullscreen === true &&
document.documentElement.dataset.pageType === 'video' &&
!document.fullscreenElement
) {
this.elements.player.toggleFullscreen();
}
};
/*------------------------------------------------------------------------------
QUALITY
------------------------------------------------------------------------------*/
ImprovedTube.playerQuality = function () {
function closest (num, arr) {
let curr = arr[0];
let diff = Math.abs (num - curr);
for (let val = 0; val < arr.length; val++) {
let newdiff = Math.abs (num - arr[val]);
if (newdiff < diff) {
diff = newdiff;
curr = arr[val];
}
}
return curr;
};
var player = this.elements.player,
quality = this.storage.player_quality;
if (player && player.getAvailableQualityLevels && !player.dataset.defaultQuality) {
var available_quality_levels = player.getAvailableQualityLevels();
if (quality && quality !== 'auto') {
if (available_quality_levels.includes(quality) === false) {
let label = ['tiny', 'small', 'medium', 'large', 'hd720', 'hd1080', 'hd1440', 'hd2160', 'hd2880', 'highres'];
let resolution = ['144', '240', '360', '480', '720', '1080', '1440', '2160', '2880', '4320'];
let availableresolutions = available_quality_levels.reduce(function (array, elem) {
array.push(resolution[label.indexOf(elem)]); return array;
}, []);
quality = closest (resolution[label.indexOf(quality)], availableresolutions);
quality = label[resolution.indexOf(quality)];
}
player.setPlaybackQualityRange(quality);
player.setPlaybackQuality(quality);
player.dataset.defaultQuality = quality;
}
}
};
/*------------------------------------------------------------------------------
FORCED VOLUME
------------------------------------------------------------------------------*/
ImprovedTube.playerVolume = function () {
if (this.storage.player_forced_volume === true) {
var volume = this.storage.player_volume;
if (!this.isset(volume)) {
volume = 100;
} else {
volume = Number(volume);
}
if (!this.audioContextGain && volume <= 100) {
if (this.audioContext) {
this.audioContext.close();
}
this.elements.player.setVolume(volume);
} else {
if (!this.audioContext) {
this.audioContext = new AudioContext();
this.audioContextSource = this.audioContext.createMediaElementSource(document.querySelector('video'));
this.audioContextGain = this.audioContext.createGain();
this.audioContextGain.gain.value = 1;
this.audioContextSource.connect(this.audioContextGain);
this.audioContextGain.connect(this.audioContext.destination)
}
if (this.elements.player.getVolume() !== 100) { this.elements.player.setVolume(100);}
this.audioContextGain.gain.value = volume / 100;
}
}
};
/*------------------------------------------------------------------------------
LOUDNESS NORMALIZATION
------------------------------------------------------------------------------*/
ImprovedTube.onvolumechange = function (event) {
if (document.querySelector('.ytp-volume-panel') && ImprovedTube.storage.player_loudness_normalization === false) {
var volume = Number(document.querySelector('.ytp-volume-panel').getAttribute('aria-valuenow'));
this.volume = volume / 100;
}
};
ImprovedTube.playerLoudnessNormalization = function () {
var video = this.elements.video;
if (video) {
video.removeEventListener('volumechange', this.onvolumechange);
video.addEventListener('volumechange', this.onvolumechange);
}
if (this.storage.player_loudness_normalization === false) {
try {
var local_storage = localStorage['yt-player-volume'];
if (this.isset(Number(this.storage.player_volume)) && this.storage.player_forced_volume === true) {
} else if (local_storage) {
local_storage = JSON.parse(JSON.parse(local_storage).data);
local_storage = Number(local_storage.volume);
video.volume = local_storage / 100;
} else {
video.volume = 100;
}
} catch (err) {}
}
};
/*------------------------------------------------------------------------------
SCREENSHOT
------------------------------------------------------------------------------*/
ImprovedTube.screenshot = function () {
var video = ImprovedTube.elements.video,
style = document.createElement('style'),
cvs = document.createElement('canvas'),
ctx = cvs.getContext('2d');
style.textContent = 'video{width:' + video.videoWidth + 'px !important;height:' + video.videoHeight + 'px !important}';
cvs.width = video.videoWidth;
cvs.height = video.videoHeight;
document.body.appendChild(style);
setTimeout(function () {
ctx.drawImage(video, 0, 0, cvs.width, cvs.height);
var subText = '';
var captionElements = document.querySelectorAll('.captions-text .ytp-caption-segment');
captionElements.forEach(function (caption) {subText += caption.textContent.trim() + ' ';});
if(ImprovedTube.storage.embed_subtitle === true){ImprovedTube.renderSubtitle(ctx,captionElements);}
cvs.toBlob(function (blob) {
if (ImprovedTube.storage.player_screenshot_save_as !== 'clipboard') {
var a = document.createElement('a');
a.href = URL.createObjectURL(blob); console.log("screeeeeeenshot tada!");
a.download = (ImprovedTube.videoId() || location.href.match) + ' ' + new Date(ImprovedTube.elements.player.getCurrentTime() * 1000).toISOString().substr(11, 8).replace(/:/g, '-') + ' ' + ImprovedTube.videoTitle() + (subText ? ' - ' + subText.trim() : '') + '.png';
a.click();
} else {
navigator.clipboard.write([
new ClipboardItem({
'image/png': blob
})
]);
}
});
style.remove();
});
};
ImprovedTube.renderSubtitle = function (ctx,captionElements) {
if (ctx && captionElements) {
captionElements.forEach(function (captionElement, index) {
var captionText = captionElement.textContent.trim();
var captionStyles = window.getComputedStyle(captionElement);
ctx.fillStyle = captionStyles.color;
ctx.font = captionStyles.font;
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
var txtWidth = ctx.measureText(captionText).width;
var txtHeight = parseFloat(captionStyles.fontSize);
var xOfset = (ctx.canvas.width - txtWidth) / 2;
var padding = 5; // Adjust the padding as needed
var yofset = ctx.canvas.height - (captionElements.length - index) * (txtHeight + 2 * padding);
ctx.fillStyle = captionStyles.backgroundColor;
ctx.fillRect(xOfset - padding, yofset - txtHeight - padding, txtWidth + 2 * padding, txtHeight + 2 * padding);
ctx.fillStyle = captionStyles.color;
ctx.fillText(captionText, xOfset + txtWidth / 2, yofset);
});
}
};
ImprovedTube.playerScreenshotButton = function () {
if (this.storage.player_screenshot_button === true) {
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
svg.setAttributeNS(null, 'viewBox', '0 0 24 24');
path.setAttributeNS(null, 'd', 'M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z');
svg.appendChild(path);
this.createPlayerButton({
id: 'it-screenshot-button',
child: svg,
opacity: 0.64,
onclick: this.screenshot,
title: 'Screenshot'
});
}
};
/*------------------------------------------------------------------------------
REPEAT
-------------------------------------------------------------------------------*/
ImprovedTube.playerRepeat = function () {
setTimeout(function () {
if (!/ad-showing/.test(ImprovedTube.elements.player.className)) {
ImprovedTube.elements.video.setAttribute('loop', '');
}
//ImprovedTube.elements.buttons['it-repeat-styles'].style.opacity = '1'; //old class from version 3.x? that both repeat buttons could have
}, 200);
}
/*------------------------------------------------------------------------------
REPEAT BUTTON
------------------------------------------------------------------------------*/
ImprovedTube.playerRepeatButton = function (node) {
if (this.storage.player_repeat_button === true) {
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
svg.setAttributeNS(null, 'viewBox', '0 0 24 24');
path.setAttributeNS(null, 'd', 'M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4zm-4-2V9h-1l-2 1v1h1.5v4H13z');
svg.appendChild(path);
var transparentOrOn = 0.5; if (this.storage.player_always_repeat === true ) { transparentOrOn = 1; }
this.createPlayerButton({
id: 'it-repeat-button',
child: svg,
opacity: transparentOrOn,
onclick: function () {
var video = ImprovedTube.elements.video;
function matchLoopState(opacity) {
var thisButton = document.querySelector('#it-repeat-button');
thisButton.style.opacity = opacity;
if (ImprovedTube.storage.below_player_loop !== false) {
var otherButton = document.querySelector('#it-below-player-loop');
otherButton.children[0].style.opacity = opacity;
}
} if (video.hasAttribute('loop')) {
video.removeAttribute('loop');
matchLoopState('.5')
} else if (!/ad-showing/.test(ImprovedTube.elements.player.className)) {
video.setAttribute('loop', '');
matchLoopState('1')
}
},
title: 'Repeat',
});
}
};
/*------------------------------------------------------------------------------
ROTATE
------------------------------------------------------------------------------*/
ImprovedTube.playerRotateButton = function () {
if (this.storage.player_rotate_button === true) {
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
svg.setAttributeNS(null, 'viewBox', '0 0 24 24');
path.setAttributeNS(null, 'd', 'M15.55 5.55L11 1v3.07a8 8 0 0 0 0 15.86v-2.02a6 6 0 0 1 0-11.82V10l4.55-4.45zM19.93 11a7.9 7.9 0 0 0-1.62-3.89l-1.42 1.42c.54.75.88 1.6 1.02 2.47h2.02zM13 17.9v2.02a7.92 7.92 0 0 0 3.9-1.61l-1.44-1.44c-.75.54-1.59.89-2.46 1.03zm3.89-2.42l1.42 1.41A7.9 7.9 0 0 0 19.93 13h-2.02a5.9 5.9 0 0 1-1.02 2.48z');
svg.appendChild(path);
this.createPlayerButton({
id: 'it-rotate-button',
child: svg,
opacity: 0.85,
onclick: function () {
var player = ImprovedTube.elements.player,
video = ImprovedTube.elements.video,
rotate = Number(document.body.dataset.itRotate) || 0,
transform = '';
rotate += 90;
if (rotate === 360) {
rotate = 0;
}
document.body.dataset.itRotate = rotate;
transform += 'rotate(' + rotate + 'deg)';
if (rotate == 90 || rotate == 270) {
var is_vertical_video = video.videoHeight > video.videoWidth;
transform += ' scale(' + (is_vertical_video ? player.clientWidth : player.clientHeight) / (is_vertical_video ? player.clientHeight : player.clientWidth) + ')';
}
if (!ImprovedTube.elements.buttons['it-rotate-styles']) {
var style = document.createElement('style');
ImprovedTube.elements.buttons['it-rotate-styles'] = style;
document.body.appendChild(style);
}
ImprovedTube.elements.buttons['it-rotate-styles'].textContent = 'video{transform:' + transform + '}';
},
title: 'Rotate'
});
}
};
/*------------------------------------------------------------------------------
FIT-TO-WIN BUTTON
------------------------------------------------------------------------------*/
ImprovedTube.playerFitToWinButton = function () {
if (this.storage.player_fit_to_win_button === true && (/watch\?/.test(location.href))) {
let tempContainer = document.createElement("div");
tempContainer.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" id="ftw-icon">
<path d="M21 3 9 15"/><path d="M12 3H3v18h18v-9"/><path d="M16 3h5v5"/><path d="M14 15H9v-5"/></svg>`;
const svg = tempContainer.firstChild;
this.createPlayerButton({
id: 'it-fit-to-win-player-button',
child: svg,
opacity: 0.85,
position: "right",
onclick: function () {
let previousSize = ImprovedTube.storage.player_size === "fit_to_window" ? "do_not_change" : (ImprovedTube.storage.player_size ?? "do_not_change");
let isFTW = document.querySelector("html").getAttribute("it-player-size") === "fit_to_window"
if (isFTW) {
document.querySelector("html").setAttribute("it-player-size", previousSize);
} else {
document.querySelector("html").setAttribute("it-player-size", "fit_to_window");
}
window.dispatchEvent(new Event("resize"));
},
title: 'Fit To Window'
});
}
};
/*------------------------------------------------------------------------------
HAMBURGER MENU
------------------------------------------------------------------------------*/
ImprovedTube.playerHamburgerButton = function () { if(this.storage.player_hamburger_button === true){
const videoPlayer = document.querySelector('.html5-video-player');
if (!videoPlayer) {
return;
}
const controlsContainer = videoPlayer.querySelector('.ytp-right-controls');
if (!controlsContainer) {
return;
}
let hamburgerMenu = document.querySelector('.custom-hamburger-menu');
if (!hamburgerMenu) {
hamburgerMenu = document.createElement('div');
hamburgerMenu.className = 'custom-hamburger-menu';
hamburgerMenu.style.position = 'absolute';
hamburgerMenu.style.right = '0';
hamburgerMenu.style.marginTop = '8px';
hamburgerMenu.style.cursor = 'pointer';
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttributeNS(null, 'viewBox', '0 0 24 24');
svg.setAttribute('style', 'width: 32px; height: 32px;');
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttributeNS(null, 'd', 'M3 18h18v-2H3v2zM3 13h18v-2H3v2zM3 6v2h18V6H3z');
path.setAttributeNS(null, 'fill', 'white');
svg.appendChild(path);
hamburgerMenu.appendChild(svg);
controlsContainer.style.paddingRight = '40px';
controlsContainer.parentNode.appendChild(hamburgerMenu);
let controlsVisible = true;
controlsContainer.style.display = controlsVisible ? 'none' : 'flex';
controlsVisible = false;
hamburgerMenu.addEventListener('click', function () {
controlsContainer.style.display = controlsVisible ? 'none' : 'flex';
controlsVisible = !controlsVisible;
// Change the opacity of hamburgerMenu based on controls visibility
hamburgerMenu.style.opacity = controlsVisible ? '0.85' : '0.65';
});
}
}
};
/*------------------------------------------------------------------------------
POPUP PLAYER
------------------------------------------------------------------------------*/
ImprovedTube.playerPopupButton = function () {
if (this.storage.player_popup_button === true && location.href.indexOf('youtube.com/embed') === -1 ){
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
svg.setAttributeNS(null, 'viewBox', '0 0 24 24');
path.setAttributeNS(null, 'd', 'M19 7h-8v6h8V7zm2-4H3C2 3 1 4 1 5v14c0 1 1 2 2 2h18c1 0 2-1 2-2V5c0-1-1-2-2-2zm0 16H3V5h18v14z');
svg.appendChild(path);
this.createPlayerButton({
id: 'it-popup-player-button',
child: svg,
opacity: 0.8,
onclick: function () {
"use strict";
const ytPlayer = ImprovedTube.elements.player;
ytPlayer.pauseVideo();
const videoID = location.search.match(ImprovedTube.regex.video_id)[1],
listMatch = location.search.match(ImprovedTube.regex.playlist_id),
popup = window.open(
`${location.protocol}//www.youtube.com/embed/${videoID}?start=${parseInt(ytPlayer.getCurrentTime())}&autoplay=${ImprovedTube.storage.player_autoplay_disable ? '0' : '1'}${listMatch?`&list=${listMatch[1]}`:''}`,
'_blank',
`directories=no,toolbar=no,location=no,menubar=no,status=no,titlebar=no,scrollbars=no,resizable=no,width=${ytPlayer.offsetWidth / 3},height=${ytPlayer.offsetHeight / 3}`
);
if(popup && listMatch){
//! If the video is not in the playlist or not within the first 200 entries, then it automatically selects the first video in the list.
popup.addEventListener('load', function () {
"use strict";
//~ check if the video ID in the link of the video title matches the original video ID in the URL and if not remove the playlist from the URL (reloads the page).
const videoLink = this.document.querySelector('div#player div.ytp-title-text>a[href]');
if (videoLink && videoLink.href.match(ImprovedTube.regex.video_id)[1] !== videoID) this.location.search = this.location.search.replace(/(\?)list=[^&]+&|&list=[^&]+/, '$1');
}, {passive: true, once: true});
}
//~ change focused tab to URL-less popup
ImprovedTube.messages.send({
action: 'fixPopup',
width: ytPlayer.offsetWidth * 0.75,
height: ytPlayer.offsetHeight * 0.75,
title: document.title
});
},
title: 'Popup'
});
}
};
/*------------------------------------------------------------------------------
Force SDR
------------------------------------------------------------------------------*/
ImprovedTube.playerSDR = function () {
if (this.storage.player_SDR === true) {
Object.defineProperty(window.screen, 'pixelDepth', {
enumerable: true,
configurable: true,
value: 24
});
}
};
/*------------------------------------------------------------------------------
Hide controls
------------------------------------------------------------------------------*/
ImprovedTube.playerControls = function (pause=false) {
var player = this.elements.player; if (player) {
let hide = this.storage.player_hide_controls;
if (hide === 'always') {
player.hideControls();
} else if(hide === 'off') {
player.showControls();
} else if(hide === 'when_paused') {
if(this.elements.video.paused){
player.hideControls( );
ImprovedTube.elements.player.parentNode.addEventListener('mouseenter', function () {
player.showControls();});
ImprovedTube.elements.player.parentNode.addEventListener('mouseleave', function () {
player.hideControls( );});
ImprovedTube.elements.player.parentNode.onmousemove = (function() {
let onmousestop = function() {
player.hideControls( );
}, thread;
return function() {
player.showControls();
clearTimeout(thread);
thread = setTimeout(onmousestop, 1000);
};
})();
}} else { player.showControls(); }
}
};
/*# HIDE VIDEO TITLE IN FULLSCREEN */ // Easier with CSS only (see player.css)
//ImprovedTube.hideVideoTitleFullScreen = function (){ if (ImprovedTube.storage.hide_video_title_fullScreen === true) {
//document.addEventListener('fullscreenchange', function (){ document.querySelector(".ytp-title-text > a")?.style.setProperty('display', 'none'); }) }};
/*------------------------------------------------------------------------------
CUSTOM MINI-PLAYER
------------------------------------------------------------------------------*/
ImprovedTube.mini_player__setSize = function (width, height, keep_ar, keep_area) {
if (keep_ar) {
const aspect_ratio = ImprovedTube.elements.video.style.width.replace('px', '') / ImprovedTube.elements.video.style.height.replace('px', '');
if (keep_area) {
height = Math.sqrt((width * height) / aspect_ratio);
width = height * aspect_ratio;
} else {
height = width / aspect_ratio;
}
}
ImprovedTube.elements.player.style.width = width + 'px';
ImprovedTube.elements.player.style.height = height + 'px';
};
ImprovedTube.miniPlayer_scroll = function () {
if (window.scrollY >= 256 && ImprovedTube.mini_player__mode === false && ImprovedTube.elements.player.classList.contains('ytp-player-minimized') === false) {
ImprovedTube.mini_player__mode = true;