-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBoosteroid-Optimizer-Plus.user.js
More file actions
6650 lines (5795 loc) · 285 KB
/
Boosteroid-Optimizer-Plus.user.js
File metadata and controls
6650 lines (5795 loc) · 285 KB
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
// ==UserScript==
// @name Boosteroid Optimizer Plus by Derfog
// @name:fr Boosteroid Optimizer Plus par Derfog
// @namespace https://github.com/derfog
// @version 3.7.2
// @description Ultimate Boosteroid optimizer: SLIM & FAST, Smart Resolution, 5 Presets, requestIdleCallback, Zero VRAM leak
// @description:fr Optimiseur ultime Boosteroid: SLIM & FAST, Résolution intelligente, 5 Presets, requestIdleCallback, Zéro fuite VRAM
// @author Derfog
// @license MIT
// @copyright 2024-2025, Derfog (https://github.com/derfog)
// @homepageURL https://github.com/derfog/boosteroid-optimizer-plus
// @supportURL https://github.com/derfog/boosteroid-optimizer-plus/issues
// @match https://cloud.boosteroid.com/*
// @match https://*.boosteroid.com/*
// @icon https://www.google.com/s2/favicons?sz=64&domain_url=https%3A%2F%2Fboosteroid.com
// @run-at document-start
// @grant unsafeWindow
// @grant GM_registerMenuCommand
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_addStyle
// ==/UserScript==
/**
* BOOSTEROID OPTIMIZER PLUS v3.7.2 "Smart Quality" by DERFOG
* Copyright (c) 2024-2025 Derfog - MIT License
*
* v3.7.2: Smart Quality Edition
* - NEW: Presets désactivés par défaut (tier OFF) - l'utilisateur choisit
* - NEW: getScreenDetails API for screen detection
* - SECURITY: Removed global SmartResolutionDetector exposure (XSS prevention)
* - Upscale Only + SUPPORTED_RESOLUTIONS whitelist
* - Retry system for filter presets
*/
(function () {
'use strict';
// ===============================================================================
// AXE 1: ENVIRONMENT DETECTION & PROFILING (avec fallbacks robustes)
// ===============================================================================
const ENV_PROFILE = (function() {
// Helpers pour accès sécurisé aux APIs navigateur
const safeGet = (fn, fallback) => {
try { return fn() ?? fallback; } catch (e) { return fallback; }
};
const ua = navigator.userAgent || '';
const cores = safeGet(() => navigator.hardwareConcurrency, 4);
const memory = safeGet(() => navigator.deviceMemory, 4); // GB - non supporté sur Firefox/Safari
// matchMedia peut échouer sur certains navigateurs TV
let isTouch = false;
try {
isTouch = window.matchMedia && matchMedia('(pointer: coarse)').matches;
} catch (e) {
isTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
}
const width = safeGet(() => window.innerWidth || document.documentElement.clientWidth, 1920);
const height = safeGet(() => window.innerHeight || document.documentElement.clientHeight, 1080);
const dpr = safeGet(() => window.devicePixelRatio, 1);
// Network Information API (non supportée partout)
let connection = null;
let effectiveType = '4g';
let downlink = null;
let saveData = false;
try {
connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
if (connection) {
effectiveType = connection.effectiveType || '4g';
downlink = connection.downlink || null;
saveData = connection.saveData || false;
}
} catch (e) {
console.log('[Optimizer+] Network API non disponible, utilisation des valeurs par défaut');
}
// Détection UA
const isMobile = /Android|iPhone|iPad|iPod|Windows Phone/i.test(ua);
const isTablet = /iPad|Android(?!.*Mobile)/i.test(ua);
// Fix: Ajout patterns TV modernes (Steam Link, Shield, Chromecast, Android TV, tvOS)
const isTVByUA = /SmartTV|Tizen|WebOS|NetCast|HbbTV|BRAVIA|AFT|Fire TV|Hisense|VIDAA|Roku|PlayStation|Xbox|Steam Link|SHIELD|Chromecast|Android TV|tvOS|GoogleTV|Apple TV/i.test(ua);
// Heuristique: Grand écran (>1920) + DPR 1.0 + pas mobile/tablet = probablement TV
const isTVByHeuristic = (width > 1920 && height > 1080 && dpr === 1.0 && !isMobile && !isTablet);
const isTV = isTVByUA || isTVByHeuristic;
const isFirefox = /Firefox/i.test(ua);
const isChrome = /Chrome|Chromium|CriOS/i.test(ua);
const isSafari = /Safari/i.test(ua) && !/Chrome/i.test(ua);
const isEdge = /Edg/i.test(ua);
const isOldBrowser = /MSIE|Trident|Edge\/\d+\./i.test(ua); // Ancien Edge non-Chromium
// Fix: Ne pas utiliser effectiveType pour classifier Low-End sur desktop (faux positifs '4g')
const isSlowByNetwork = isMobile && (effectiveType === '3g' || effectiveType === '2g');
// Classification de puissance (avec logique améliorée)
const isLowEnd = cores <= 4 || memory <= 4 || isSlowByNetwork || isOldBrowser;
const isHighEnd = cores > 8 && memory > 8 && !isMobile && !isTablet;
const isMidRange = !isLowEnd && !isHighEnd;
// Classification d'écran
const isSmallScreen = width < 1280 || height < 720;
const isMediumScreen = width >= 1280 && width < 1920;
const isLargeScreen = width >= 1920 && height >= 1080;
return {
// Device type
isMobile, isTablet, isTV, isSmallScreen, isMediumScreen, isLargeScreen,
// Performance class
cores, memory, isLowEnd, isMidRange, isHighEnd, isOldBrowser,
// Browser & rendering
isFirefox, isChrome, isSafari, isEdge,
// Network
effectiveType, downlink, saveData,
// Fix: isSlowNetwork utilise downlink en priorité, effectiveType seulement sur mobile
isSlowNetwork: (downlink !== null && downlink > 0 && downlink < 5) || (isMobile && (effectiveType === '3g' || effectiveType === '2g')),
isFastNetwork: (downlink !== null && downlink >= 15) || (!isMobile && effectiveType === '4g'),
// Display
width, height, dpr,
// Input
isTouch,
// Summary string for logging
summary() {
const device = this.isTV ? 'TV' : (this.isMobile ? 'Mobile' : (this.isTablet ? 'Tablet' : 'Desktop'));
const perf = this.isLowEnd ? 'Low-End' : (this.isHighEnd ? 'High-End' : 'Mid-Range');
const net = this.isSlowNetwork ? 'Slow' : (this.isFastNetwork ? 'Fast' : 'Normal');
return `${device} | ${perf} (${this.cores}c/${this.memory}GB) | ${net} | ${this.width}x${this.height}`;
}
};
})();
console.log('[Optimizer+] =======================================');
console.log('[Optimizer+] Device Profile:', ENV_PROFILE.summary());
// ===============================================================================
// SIGNATURE & PROTECTION
// ===============================================================================
const SCRIPT_SIGNATURE = {
author: 'Derfog',
version: '3.7.2',
hash: 'BOP372SQ2025', // Smart Quality - v3.7.2
verify: () => {
const meta = document.querySelector('meta[name="optimizer-author"]');
if (!meta) {
const m = document.createElement('meta');
m.name = 'optimizer-author';
m.content = 'Derfog';
document.head.appendChild(m);
}
return true;
}
};
SCRIPT_SIGNATURE.verify();
// ===============================================================================
// BASE CONFIGURATION (High-End defaults)
// ===============================================================================
const CONFIG = {
// Résolution forcée - v3.7.2: isAuto=true utilise la résolution native de l'écran
resolution: {
width: 3840,
height: 2160,
pixelRatio: 2,
isAuto: true // v3.7.2: Mode auto par défaut = résolution native
},
// Codec préférences
codecs: {
forceAV1: true,
forceHEVC: true,
forceVP9: true,
preferHardware: true
},
// Bitrate et qualité
streaming: {
maxBitrate: 50000000,
minBitrate: 15000000,
targetBitrate: 35000000,
bufferSize: 2000,
forceHighQuality: true,
interceptorEnabled: false // Opt-in: Stream Interceptor désactivé par défaut
},
// PERFORMANCE & LATENCE
performance: {
lowLatencyMode: true,
targetLatency: 12,
jitterBufferTarget: 40,
jitterBufferMax: 80,
decodeLatencyTarget: 4,
prioritizeFramerate: true,
gpuAcceleration: true,
reducedFiltersInGame: true,
// v3.6.1: maxFiltersActive dynamique selon profil matériel
maxFiltersActive: ENV_PROFILE.isHighEnd ? 5 : (ENV_PROFILE.isMidRange ? 3 : 2),
disableLogsInGame: true,
adaptiveQuality: true,
fpsThreshold: 55,
streamInterceptor: true // Opt-in: intercepte configs pour forcer HW decode
},
// Video Enhancer
enhancer: {
enabled: false, // v3.7.2: Désactivé par défaut - l'utilisateur choisit
sharpness: 0.45,
contrast: 1.0, // Valeurs neutres
saturation: 1.0,
brightness: 1.0
},
// Filtres vidéo avancés
filters: {
enabled: false, // v3.7.2: Désactivé par défaut - l'utilisateur choisit
preset: null, // v3.7.2: Aucun preset actif par défaut
usm: { enabled: false, amount: 0.35, radius: 0.9, threshold: 0.04 },
cas: { enabled: false, sharpness: 0.45 },
clarity: { enabled: false, amount: 0.2 },
denoise: { enabled: false, strength: 0.2 },
vibrance: { enabled: false, amount: 0.2 },
gamma: { enabled: false, value: 1.0 },
exposure: { enabled: false, value: 0 },
deband: { enabled: false, strength: 0.3 }
},
// DRM Bypass
drm: {
forceDolbyVision: false,
forceHDCP: false,
forceUHD: true,
forceALL: false
},
// Display & Ultrawide (v3.6)
display: {
ultrawideMode: false, // Ultrawide stretch mode toggle
autoDetect: true, // Auto-activer ultrawide si écran 21:9+
performanceMode: false // Mode performance: désactive les filtres lourds
},
// Langue (auto-détectée ou choisie)
language: 'auto'
};
// Valeurs par défaut pour le Reset (copie immutable)
const DEFAULT_CONFIG = {
resolution: { width: 3840, height: 2160, pixelRatio: 2, isAuto: true },
enhancer: { enabled: true, sharpness: 0.45, contrast: 1.04, saturation: 1.01, brightness: 1.0 },
filters: {
enabled: true, preset: 'default',
usm: { enabled: true, amount: 0.35, radius: 0.9, threshold: 0.04 },
cas: { enabled: true, sharpness: 0.45 },
clarity: { enabled: false, amount: 0.2 },
denoise: { enabled: false, strength: 0.2 },
vibrance: { enabled: false, amount: 0.2 },
gamma: { enabled: false, value: 1.0 },
exposure: { enabled: false, value: 0 },
deband: { enabled: false, strength: 0.3 }
},
language: 'auto'
};
// ===============================================================================
// AXE 1: ADAPTIVE CONFIG BUILDER
// ===============================================================================
function buildAdaptiveConfig(baseConfig, envProfile) {
const cfg = JSON.parse(JSON.stringify(baseConfig));
// -------------------------------------------------------------------------
// Tier 1 : Low-End / Slow Network
// -------------------------------------------------------------------------
if (envProfile.isLowEnd || envProfile.isSlowNetwork) {
console.log('[Optimizer+] Adapting to Low-End/Slow profile');
cfg.resolution = { width: 1920, height: 1080, pixelRatio: 1, isAuto: false };
cfg.streaming = {
maxBitrate: 15000000, minBitrate: 8000000, targetBitrate: 12000000,
bufferSize: 3000, forceHighQuality: true
};
cfg.performance.maxFiltersActive = 2;
cfg.performance.adaptiveQuality = true;
cfg.filters.usm.amount = 0.25;
cfg.filters.cas.sharpness = 0.35;
cfg.filters.clarity.enabled = false;
cfg.filters.denoise.enabled = false;
cfg.filters.vibrance.enabled = false;
cfg.filters.deband.enabled = false;
}
// -------------------------------------------------------------------------
// Tier 2 : Mid-Range
// -------------------------------------------------------------------------
else if (envProfile.isMidRange) {
console.log('[Optimizer+] Adapting to Mid-Range profile');
cfg.resolution = { width: 2560, height: 1440, pixelRatio: 1, isAuto: false };
cfg.streaming = {
maxBitrate: 30000000, minBitrate: 12000000, targetBitrate: 25000000,
bufferSize: 2500, forceHighQuality: true
};
cfg.performance.maxFiltersActive = 4;
cfg.filters.usm.amount = 0.35;
cfg.filters.cas.sharpness = 0.45;
cfg.filters.clarity.enabled = true;
cfg.filters.deband.enabled = true;
}
// Tier 3 : High-End = config par défaut (isAuto: true)
// -------------------------------------------------------------------------
// Device-specific overrides
// -------------------------------------------------------------------------
if (envProfile.isMobile || envProfile.isTablet) {
cfg.streaming.maxBitrate = Math.min(cfg.streaming.maxBitrate, 20000000);
cfg.streaming.targetBitrate = Math.min(cfg.streaming.targetBitrate, 18000000);
cfg.performance.maxFiltersActive = Math.min(cfg.performance.maxFiltersActive, 3);
}
if (envProfile.isTV) {
cfg.performance.lowLatencyMode = true;
cfg.performance.targetLatency = 10;
cfg.performance.jitterBufferTarget = 30;
}
if (envProfile.isSmallScreen) {
cfg.resolution.width = Math.min(cfg.resolution.width, 1920);
cfg.resolution.height = Math.min(cfg.resolution.height, 1080);
}
if (envProfile.isSafari) {
cfg.performance.preferHardware = false;
}
if (envProfile.saveData) {
cfg.streaming.maxBitrate = Math.round(cfg.streaming.maxBitrate * 0.7);
cfg.filters.enabled = false;
}
return cfg;
}
// Appliquer la configuration adaptative
const EFFECTIVE_CONFIG = buildAdaptiveConfig(CONFIG, ENV_PROFILE);
// Remplacer CONFIG par EFFECTIVE_CONFIG pour le reste du script
Object.assign(CONFIG, EFFECTIVE_CONFIG);
console.log('[Optimizer+] Adaptive config applied:',
`${CONFIG.resolution.width}x${CONFIG.resolution.height}`,
`@ ${Math.round(CONFIG.streaming.maxBitrate/1000000)}Mbps`
);
// ===============================================================================
// AXE 3: FILTER TIERING SYSTEM
// ===============================================================================
const FilterTiers = {
// v3.7.2: OFF = aucun filtre activé par défaut, l'utilisateur choisit
OFF: {
name: 'Désactivé',
filters: {
usm: { enabled: false }, cas: { enabled: false },
clarity: { enabled: false }, denoise: { enabled: false },
vibrance: { enabled: false }, gamma: { enabled: false },
exposure: { enabled: false }, deband: { enabled: false }
},
enhancer: { contrast: 1.0, saturation: 1.0, brightness: 1.0 }
},
SAFE: {
name: 'Safe Mode',
filters: {
usm: { enabled: false }, cas: { enabled: false },
clarity: { enabled: false }, denoise: { enabled: false },
vibrance: { enabled: false }, gamma: { enabled: false },
exposure: { enabled: false }, deband: { enabled: false }
},
enhancer: { contrast: 1.02, saturation: 1.01, brightness: 1.0 }
},
LIGHT: {
name: 'Light',
filters: {
usm: { enabled: true, amount: 0.25 }, cas: { enabled: true, sharpness: 0.35 },
clarity: { enabled: false }, denoise: { enabled: false },
vibrance: { enabled: false }, gamma: { enabled: false },
exposure: { enabled: false }, deband: { enabled: false }
},
enhancer: { contrast: 1.04, saturation: 1.01, brightness: 1.0 }
},
NORMAL: {
name: 'Balanced',
filters: {
usm: { enabled: true, amount: 0.35 }, cas: { enabled: true, sharpness: 0.45 },
clarity: { enabled: true, amount: 0.2 }, denoise: { enabled: false },
vibrance: { enabled: false }, gamma: { enabled: false },
exposure: { enabled: false }, deband: { enabled: true, strength: 0.2 }
},
enhancer: { contrast: 1.04, saturation: 1.01, brightness: 1.0 }
},
ULTRA: {
name: 'Ultra',
filters: {
usm: { enabled: true, amount: 0.45 }, cas: { enabled: true, sharpness: 0.55 },
clarity: { enabled: true, amount: 0.3 }, denoise: { enabled: true, strength: 0.15 },
vibrance: { enabled: true, amount: 0.15 }, gamma: { enabled: false },
exposure: { enabled: false }, deband: { enabled: true, strength: 0.3 }
},
enhancer: { contrast: 1.05, saturation: 1.02, brightness: 1.0 }
}
};
// v3.7.2: Par défaut, aucun preset actif - l'utilisateur choisit
function getInitialFilterTier(envProfile) {
// Retourner OFF par défaut - l'utilisateur active manuellement le preset souhaité
return 'OFF';
}
const FilterState = {
currentTier: getInitialFilterTier(ENV_PROFILE),
adaptiveEnabled: CONFIG.performance.adaptiveQuality,
fpsHistory: [],
fpsThreshold: CONFIG.performance.fpsThreshold || 55,
lastAutoChange: 0, // v3.6.2: Cooldown pour éviter boucle infinie
updateTierBasedOnFps(currentFps) {
if (!this.adaptiveEnabled) return;
// v3.6.2: Cooldown de 10 secondes entre changements auto
if (Date.now() - this.lastAutoChange < 10000) return;
this.fpsHistory.push(currentFps);
// v3.6.4: Limiter à 20 éléments pour éviter memory leak
if (this.fpsHistory.length > 20) this.fpsHistory.shift();
const avgFps = this.fpsHistory.reduce((a, b) => a + b, 0) / this.fpsHistory.length;
// v3.6.2: Auto-activation du Performance Mode si FPS critiques
if (avgFps < this.fpsThreshold && !CONFIG.display.performanceMode) {
console.warn('[Optimizer+] [!] FPS critique (' + Math.round(avgFps) + '), activation auto du Performance Mode');
CONFIG.display.performanceMode = true;
// Désactiver les filtres lourds
CONFIG.filters.clarity.enabled = false;
CONFIG.filters.denoise.enabled = false;
CONFIG.filters.deband.enabled = false;
CONFIG.performance.gpuAcceleration = false;
// Forcer le tier SAFE
this.setFilterTier('SAFE');
// Mettre à jour les filtres
if (typeof videoEnhancer !== 'undefined' && videoEnhancer.updateFilterString) {
videoEnhancer.updateFilterString();
videoEnhancer.applyFiltersToAllVideos();
}
// Notification utilisateur
if (typeof showNotification === 'function') {
showNotification(' Performance Mode auto-activé (FPS < ' + this.fpsThreshold + ')');
}
// Mettre à jour le toggle UI si présent
const toggle = document.getElementById('optimizer-performance-mode');
if (toggle) toggle.checked = true;
return; // Ne pas continuer le calcul de tier
}
const newTier = this.calculateOptimalTier(avgFps);
if (newTier !== this.currentTier) {
this.setFilterTier(newTier);
this.lastAutoChange = Date.now(); // v3.6.2: Reset cooldown
}
},
calculateOptimalTier(avgFps) {
if (avgFps >= this.fpsThreshold) {
if (this.currentTier === 'SAFE') return 'LIGHT';
if (this.currentTier === 'LIGHT') return 'NORMAL';
if (this.currentTier === 'NORMAL') return 'ULTRA';
} else if (avgFps < this.fpsThreshold * 0.7) {
if (this.currentTier === 'ULTRA') return 'NORMAL';
if (this.currentTier === 'NORMAL') return 'LIGHT';
if (this.currentTier === 'LIGHT') return 'SAFE';
}
return this.currentTier;
},
// v3.7.0: Pending tier pour retry si videoEnhancer n'existe pas encore
_pendingTier: null,
_retryCount: 0,
_maxRetries: 50, // 50 * 100ms = 5 secondes max
setFilterTier(tierName) {
if (tierName === this.currentTier) return;
const tier = FilterTiers[tierName];
if (!tier) return;
console.log(`[Optimizer+] Filter tier: ${this.currentTier} -> ${tierName}`);
this.currentTier = tierName;
// Si OFF, désactiver tous les filtres et ne rien appliquer
if (tierName === 'OFF') {
Object.keys(tier.filters).forEach(filterName => {
if (CONFIG.filters[filterName]) {
CONFIG.filters[filterName].enabled = false;
}
});
Object.assign(CONFIG.enhancer, tier.enhancer);
// Retirer les filtres des vidéos existantes
if (typeof videoEnhancer !== 'undefined' && videoEnhancer.removeFiltersFromAllVideos) {
videoEnhancer.removeFiltersFromAllVideos();
} else {
// Fallback: retirer manuellement les filtres
document.querySelectorAll('video').forEach(video => {
video.style.filter = '';
});
}
console.log('[Optimizer+] [OK] Tous les filtres désactivés');
return;
}
// Appliquer les filtres du tier en mémoire
Object.keys(tier.filters).forEach(filterName => {
if (CONFIG.filters[filterName]) {
Object.assign(CONFIG.filters[filterName], tier.filters[filterName]);
}
});
Object.assign(CONFIG.enhancer, tier.enhancer);
// v3.7.0: Système de retry robuste
this._pendingTier = tierName;
this._retryCount = 0;
this._applyWithRetry();
},
// v3.7.0: Appliquer les filtres avec retry automatique
_applyWithRetry() {
if (!this._pendingTier) return;
if (typeof videoEnhancer !== 'undefined' && videoEnhancer.updateFilterString) {
// videoEnhancer existe, appliquer les filtres
videoEnhancer.updateFilterString();
videoEnhancer.updateSVGFilters();
videoEnhancer.applyFiltersToAllVideos();
// Valider que les filtres sont appliqués
setTimeout(() => this._validateFiltersApplied(), 200);
this._pendingTier = null;
this._retryCount = 0;
console.log('[Optimizer+] [OK] Filters applied successfully');
} else if (this._retryCount < this._maxRetries) {
// Retry après 100ms
this._retryCount++;
setTimeout(() => this._applyWithRetry(), 100);
if (this._retryCount === 1) {
console.log('[Optimizer+] videoEnhancer not ready, retrying...');
}
} else {
// Timeout après 5 secondes
console.warn('[Optimizer+] [!] Failed to apply filters after 5s - videoEnhancer not available');
this._pendingTier = null;
this._retryCount = 0;
}
},
// v3.7.0: Valider que les filtres sont vraiment appliqués
_validateFiltersApplied() {
const videos = document.querySelectorAll('video');
if (videos.length === 0) return; // Pas de vidéo encore
let allValid = true;
videos.forEach(video => {
const hasFilter = video.style.filter && video.style.filter.includes('url(#optimizer-');
const svgExists = document.getElementById('optimizer-usm-filter');
if (!hasFilter && !svgExists) {
allValid = false;
}
});
if (!allValid && this._retryCount < 10) {
// Retry l'application
this._retryCount++;
if (typeof videoEnhancer !== 'undefined') {
videoEnhancer.applyFiltersToAllVideos();
}
setTimeout(() => this._validateFiltersApplied(), 300);
}
}
};
console.log('[Optimizer+] Initial filter tier:', FilterState.currentTier);
// ===============================================================================
// AXE 3: FPS MONITOR CLASS
// ===============================================================================
class FpsMonitor {
constructor() {
this.fps = 0;
this.lastTime = performance.now();
this.frameCount = 0;
this.animationFrameId = null;
this.enabled = false;
this.callbacks = [];
}
start() {
if (this.enabled) return;
this.enabled = true;
const loop = () => {
this.frameCount++;
const now = performance.now();
const elapsed = now - this.lastTime;
// v3.6.1: Intervalle adaptatif - 1000ms si fps < 55, sinon 500ms
const updateInterval = this.fps > 0 && this.fps < 55 ? 1000 : 500;
if (elapsed >= updateInterval) {
this.fps = Math.round((this.frameCount * 1000) / elapsed);
this.frameCount = 0;
this.lastTime = now;
// Adapter le tier de filtres
FilterState.updateTierBasedOnFps(this.fps);
// Exécuter les callbacks
this.callbacks.forEach(cb => cb(this.fps));
}
if (this.enabled) {
this.animationFrameId = requestAnimationFrame(loop);
}
};
this.animationFrameId = requestAnimationFrame(loop);
console.log('[Optimizer+] FPS monitor started');
}
stop() {
if (!this.enabled) return;
this.enabled = false;
if (this.animationFrameId) {
cancelAnimationFrame(this.animationFrameId);
this.animationFrameId = null;
}
console.log('[Optimizer+] FPS monitor stopped');
}
onFpsUpdate(callback) {
this.callbacks.push(callback);
}
getFps() {
return this.fps;
}
}
// Instance globale du FPS Monitor (sera démarré en streaming)
let fpsMonitor = null;
// ===============================================================================
// v3.5 AXE 1: STREAM INTERCEPTOR - Force HW Decode + GPU Acceleration
// Inspiré de BetterXCloud pattern pour intercepter les configs streaming
// ===============================================================================
const StreamInterceptor = {
originalFetch: null,
enabled: false,
/**
* Intercepter les réponses de configuration pour forcer HW decode
*/
enable() {
if (this.enabled) return;
this.enabled = true;
// Sauvegarder le fetch original
this.originalFetch = window.fetch;
const self = this;
window.fetch = async function(...args) {
const request = args[0];
const url = typeof request === 'string' ? request : request?.url;
// Intercepter /configuration pour forcer décodage HW
if (url && (url.includes('/configuration') || url.includes('/session') || url.includes('/streaming'))) {
try {
const response = await self.originalFetch.apply(window, args);
if (response.ok) {
const clonedResponse = response.clone();
try {
const config = await clonedResponse.json();
// Force HW decoding + GPU accel
if (config) {
if (!config.clientStreamingConfigOverrides) {
config.clientStreamingConfigOverrides = '{}';
}
let overrides = {};
try {
overrides = JSON.parse(config.clientStreamingConfigOverrides);
} catch (e) {
overrides = {};
}
// [*] Force codec le plus performant
overrides.videoConfiguration = overrides.videoConfiguration || {};
overrides.videoConfiguration.enableHardwareDecoding = true;
overrides.videoConfiguration.hardwareDecoderProfile = 'high';
overrides.videoConfiguration.enableRtcStatsCollection = true;
overrides.videoConfiguration.preferredCodec = 'av1'; // AV1 si supporté
// Force high bitrate settings
overrides.bitrateConfiguration = overrides.bitrateConfiguration || {};
overrides.bitrateConfiguration.maxBitrate = CONFIG.streaming.maxBitrate;
overrides.bitrateConfiguration.targetBitrate = CONFIG.streaming.targetBitrate;
config.clientStreamingConfigOverrides = JSON.stringify(overrides);
console.log('[Optimizer+] [OK] StreamInterceptor: Config enrichie avec HW decode + codec optimisé');
return new Response(JSON.stringify(config), {
status: response.status,
statusText: response.statusText,
headers: response.headers
});
}
} catch (parseError) {
// Pas du JSON, retourner la réponse originale
}
}
return response;
} catch (e) {
console.warn('[Optimizer+] StreamInterceptor fetch error:', e);
return self.originalFetch.apply(window, args);
}
}
return self.originalFetch.apply(window, args);
};
console.log('[Optimizer+] [OK] StreamInterceptor enabled (HW decode + GPU accel)');
},
disable() {
if (!this.enabled) return;
this.enabled = false;
if (this.originalFetch) {
window.fetch = this.originalFetch;
this.originalFetch = null;
}
console.log('[Optimizer+] StreamInterceptor disabled');
}
};
// ===============================================================================
// v3.6 AXE 6: ULTRAWIDE & ASPECT RATIO EXPANSION
// Full-screen support for 21:9, 32:9+ displays - Game-changing feature!
// ===============================================================================
const UltrawideSupport = {
enabled: false,
styleElement: null,
resizeHandler: null,
/**
* Calculer l'aspect ratio de l'écran
*/
getScreenAspectRatio() {
const width = window.innerWidth;
const height = window.innerHeight;
return (width / height).toFixed(2);
},
/**
* Déterminer si l'écran est "ultrawide" (> 1.7 ratio)
*/
isUltrawideScreen() {
const ratio = parseFloat(this.getScreenAspectRatio());
return ratio > 1.7; // 16:9 = 1.78, 21:9 = 2.33, 32:9 = 3.56
},
/**
* Obtenir les infos de l'écran pour logging
*/
getScreenInfo() {
const ratio = parseFloat(this.getScreenAspectRatio());
let screenType = '16:9 (Standard)';
if (ratio >= 3.4) screenType = '32:9 (Super Ultrawide)';
else if (ratio >= 2.2) screenType = '21:9 (Ultrawide)';
else if (ratio >= 1.8) screenType = '16:10 (Widescreen)';
else if (ratio <= 1.3) screenType = 'Tablet / Vertical';
return {
ratio: ratio.toFixed(2),
type: screenType,
width: window.innerWidth,
height: window.innerHeight,
isUltrawide: this.isUltrawideScreen()
};
},
/**
* CSS pour le mode ultrawide - ÉTIREMENT INTELLIGENT
* Garde les filtres vidéo (sharpness, contrast, etc.) fonctionnels
* PRÉSERVE les fenêtres flottantes de Boosteroid
*/
getUltrawideCSS() {
return `
/* =================================================================== */
/* ULTRAWIDE MODE v3.6.0 - ÉTIREMENT (object-fit: fill) */
/* L'image 16:9 est ÉTIRÉE horizontalement pour remplir le 21:9/32:9 */
/* PAS de zoom, PAS de crop - juste un étirement des côtés */
/* =================================================================== */
html.optimizer-ultrawide-mode,
html.optimizer-ultrawide-mode body {
overflow: hidden !important;
margin: 0 !important;
padding: 0 !important;
background: #000 !important;
}
/* ================================================================ */
/* VIDÉO: object-fit: fill = ÉTIRE pour remplir (pas de zoom) */
/* ================================================================ */
html.optimizer-ultrawide-mode video {
position: fixed !important;
top: 0 !important;
left: 0 !important;
width: 100vw !important;
height: 100vh !important;
max-width: 100vw !important;
max-height: 100vh !important;
object-fit: fill !important;
background: #000 !important;
}
/* Canvas (WebRTC) - même traitement */
html.optimizer-ultrawide-mode canvas {
position: fixed !important;
top: 0 !important;
left: 0 !important;
width: 100vw !important;
height: 100vh !important;
max-width: 100vw !important;
max-height: 100vh !important;
}
/* Conteneurs stream */
html.optimizer-ultrawide-mode [class*="player"],
html.optimizer-ultrawide-mode [class*="Player"],
html.optimizer-ultrawide-mode [class*="stream"],
html.optimizer-ultrawide-mode [class*="Stream"] {
position: fixed !important;
top: 0 !important;
left: 0 !important;
width: 100vw !important;
height: 100vh !important;
margin: 0 !important;
padding: 0 !important;
overflow: visible !important;
}
/* Fenêtres flottantes Boosteroid - toujours au-dessus */
html.optimizer-ultrawide-mode [class*="modal"],
html.optimizer-ultrawide-mode [class*="Modal"],
html.optimizer-ultrawide-mode [class*="popup"],
html.optimizer-ultrawide-mode [class*="Popup"],
html.optimizer-ultrawide-mode [class*="dialog"],
html.optimizer-ultrawide-mode [class*="Dialog"],
html.optimizer-ultrawide-mode [class*="menu"],
html.optimizer-ultrawide-mode [class*="Menu"],
html.optimizer-ultrawide-mode [class*="panel"],
html.optimizer-ultrawide-mode [class*="Panel"],
html.optimizer-ultrawide-mode [class*="settings"],
html.optimizer-ultrawide-mode [class*="Settings"],
html.optimizer-ultrawide-mode [role="dialog"],
html.optimizer-ultrawide-mode [role="menu"] {
z-index: 100000 !important;
}
/* Optimizer UI */
html.optimizer-ultrawide-mode #optimizer-section {
z-index: 100001 !important;
}
/* Indicateur */
html.optimizer-ultrawide-mode::after {
content: 'ULTRAWIDE';
position: fixed;
top: 10px;
right: 10px;
background: rgba(0, 163, 255, 0.9);
color: white;
padding: 5px 10px;
border-radius: 4px;
font-size: 11px;
font-weight: bold;
z-index: 100002;
pointer-events: none;
animation: ultrawide-fade 3s ease-out forwards;
}
@keyframes ultrawide-fade {
0%, 70% { opacity: 1; }
100% { opacity: 0; }
}
`;
},
/**
* Activer le mode ultrawide
*/
enable() {
if (this.enabled) return;
console.log('[Optimizer+] Ultrawide mode: ENABLING');
const screenInfo = this.getScreenInfo();
this.enabled = true;
CONFIG.display.ultrawideMode = true;
// v3.6.1: "Cheap mode" - Désactiver les filtres lourds si prioritizeFramerate
if (CONFIG.performance.prioritizeFramerate || CONFIG.display.performanceMode) {
console.log('[Optimizer+] Ultrawide: Mode performance - désactivation filtres lourds');
CONFIG.filters.clarity.enabled = false;
CONFIG.filters.denoise.enabled = false;
CONFIG.filters.deband.enabled = false;
if (typeof videoEnhancer !== 'undefined' && videoEnhancer.updateFilterString) {
videoEnhancer.updateFilterString();
videoEnhancer.applyFiltersToAllVideos();
}
}
// Injecter le CSS ultrawide
if (!this.styleElement) {
this.styleElement = document.createElement('style');
this.styleElement.id = 'optimizer-ultrawide-styles';
this.styleElement.textContent = this.getUltrawideCSS();
document.head.appendChild(this.styleElement);
}
// Ajouter la classe de base
document.documentElement.classList.add('optimizer-ultrawide-mode');
console.log('[Optimizer+] [OK] Ultrawide mode activated');
console.log(`[Optimizer+] Screen: ${screenInfo.width}x${screenInfo.height} (${screenInfo.type})`);
// Notifier
if (typeof showNotification === 'function') {
showNotification(`Ultrawide: ${screenInfo.type}`);
}
// Écouter les changements de taille de fenêtre
this.resizeHandler = () => this.onWindowResize();
window.addEventListener('resize', this.resizeHandler);
// Sauvegarder la config
if (typeof Storage !== 'undefined' && Storage.set) {
Storage.set('config', CONFIG);
}
},
/**
* Désactiver le mode ultrawide
*/
disable() {
if (!this.enabled) return;
console.log('[Optimizer+] Ultrawide mode: DISABLING');
this.enabled = false;
CONFIG.display.ultrawideMode = false;
// Retirer la classe CSS
document.documentElement.classList.remove('optimizer-ultrawide-mode');
// Retirer le style element
if (this.styleElement && this.styleElement.parentNode) {
this.styleElement.parentNode.removeChild(this.styleElement);
this.styleElement = null;
}
// Retirer le listener resize
if (this.resizeHandler) {
window.removeEventListener('resize', this.resizeHandler);
this.resizeHandler = null;
}
console.log('[Optimizer+] [OK] Ultrawide mode deactivated');
if (typeof showNotification === 'function') {
showNotification('Ultrawide désactivé');
}
// Sauvegarder la config
if (typeof Storage !== 'undefined' && Storage.set) {
Storage.set('config', CONFIG);
}