This repository was archived by the owner on Mar 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathPlayerController.java
More file actions
591 lines (499 loc) · 21.7 KB
/
PlayerController.java
File metadata and controls
591 lines (499 loc) · 21.7 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
package pl.jakubweg;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.apps.youtube.app.YouTubeTikTokRoot_Application;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
import fi.vanced.libraries.youtube.player.VideoInformation;
import pl.jakubweg.objects.SponsorSegment;
import pl.jakubweg.requests.Requester;
import static pl.jakubweg.SponsorBlockSettings.skippedSegments;
import static pl.jakubweg.SponsorBlockSettings.skippedTime;
@SuppressLint({"LongLogTag"})
public class PlayerController {
public static final String TAG = "jakubweg.PlayerController";
public static final boolean VERBOSE = false;
@SuppressWarnings("PointlessBooleanExpression")
public static final boolean VERBOSE_DRAW_OPTIONS = false && VERBOSE;
private static final Timer sponsorTimer = new Timer("sponsor-skip-timer");
public static WeakReference<Activity> playerActivity = new WeakReference<>(null);
public static SponsorSegment[] sponsorSegmentsOfCurrentVideo;
private static WeakReference<Object> currentPlayerController = new WeakReference<>(null);
private static Method setMillisecondMethod;
private static Method setVolumeMethod;
private static Method getVolumeMethod;
private static long allowNextSkipRequestTime = 0L;
private static String currentVideoId;
private static long currentVideoLength = 1L;
private static long lastKnownVideoTime = -1L;
private static long lastKnownVolume = -1L;
private static boolean currentlyMuted = false;
private static long muteEndTime = -1L;
private static final Runnable findAndSkipSegmentRunnable = () -> {
// Log.d(TAG, "findAndSkipSegmentRunnable");
findAndSkipSegment(false);
};
private static float sponsorBarLeft = 1f;
private static float sponsorBarRight = 1f;
private static float sponsorBarThickness = 2f;
private static TimerTask skipSponsorTask = null;
public static String getCurrentVideoId() {
return currentVideoId;
}
public static void setCurrentVideoId(final String videoId) {
if (videoId == null) {
currentVideoId = null;
sponsorSegmentsOfCurrentVideo = null;
return;
}
VideoInformation.currentVideoId = videoId;
Context context = YouTubeTikTokRoot_Application.getAppContext();
if(context == null){
Log.e(TAG, "context is null");
return;
}
SponsorBlockSettings.update(context);
if (!SponsorBlockSettings.isSponsorBlockEnabled) {
currentVideoId = null;
return;
}
if (videoId.equals(currentVideoId))
return;
currentVideoId = videoId;
sponsorSegmentsOfCurrentVideo = null;
if (VERBOSE)
Log.d(TAG, "setCurrentVideoId: videoId=" + videoId);
sponsorTimer.schedule(new TimerTask() {
@Override
public void run() {
executeDownloadSegments(currentVideoId);
}
}, 0);
}
/**
* Called when creating some kind of youtube internal player controlled, every time when new video starts to play
*/
public static void onCreate(final Object o) {
// "Plugin.printStackTrace();
if (o == null) {
Log.e(TAG, "onCreate called with null object");
return;
}
if (VERBOSE)
Log.i(TAG, String.format("onCreate called with object %s on thread %s", o.toString(), Thread.currentThread().toString()));
try {
setMillisecondMethod = o.getClass().getMethod("replaceMeWithsetMillisecondMethod", Long.TYPE);
setMillisecondMethod.setAccessible(true);
setVolumeMethod = o.getClass().getMethod("replaceMeWithsetVolumeMethod", Long.TYPE);
setVolumeMethod.setAccessible(true);
getVolumeMethod = o.getClass().getMethod("replaceMeWithgetVolumeMethod");
getVolumeMethod.setAccessible(true);
lastKnownVideoTime = 0;
VideoInformation.lastKnownVideoTime = 0;
currentVideoLength = 1;
currentPlayerController = new WeakReference<>(o);
SkipSegmentView.hide();
NewSegmentHelperLayout.hide();
} catch (Exception e) {
Log.e(TAG, "Exception while initializing skip method", e);
}
}
public static void executeDownloadSegments(String videoId) {
SponsorSegment[] segments = Requester.getSegments(videoId);
Arrays.sort(segments);
if (VERBOSE)
for (SponsorSegment segment : segments) {
Log.v(TAG, "Detected segment: " + segment.toString());
}
sponsorSegmentsOfCurrentVideo = segments;
// new Handler(Looper.getMainLooper()).post(findAndSkipSegmentRunnable);
}
/**
* Works in 14.x, waits some time of object to me filled with data,
* No longer used, i've found another way to get faster videoId
*/
@Deprecated
public static void asyncGetVideoLinkFromObject(final Object o) {
// code no longer used
// if (currentVideoLink != null) {
// if (VERBOSE)
// Log.w(TAG, "asyncGetVideoLinkFromObject: currentVideoLink != null probably share button was clicked");
// return;
// }
//
// new Thread(new Runnable() {
// @Override
// public void run() {
// try {
// // It used to be "b" in 14.x version, it's "a" in 15.x
// Field b = o.getClass().getDeclaredField("b");
//
// int attempts = 0;
// String videoUrl = null;
// while (true) {
// Object objLink = b.get(o);
// if (objLink == null) {
// if (VERBOSE)
// Log.e(TAG, "asyncGetVideoLinkFromObject: objLink is null");
// } else {
// videoUrl = objLink.toString();
// if (videoUrl.isEmpty())
// videoUrl = null;
// }
//
// if (videoUrl != null)
// break;
//
// if (attempts++ > 5) {
// Log.w(TAG, "asyncGetVideoLinkFromObject: attempts++ > 5");
// return;
// }
// Thread.sleep(50);
// }
//
// if (currentVideoLink == null) {
// currentVideoLink = videoUrl;
// if (VERBOSE)
// Log.d(TAG, "asyncGetVideoLinkFromObject: link set to " + videoUrl);
//
// executeDownloadSegments(substringVideoIdFromLink(videoUrl), false);
// }
//
// } catch (Exception e) {
// Log.e(TAG, "Cannot get link from object", e);
// }
// }
// }).start();
//
// Activity activity = playerActivity.get();
// if (activity != null)
// SponsorBlockUtils.addImageButton(activity);
}
/**
* Called when it's time to update the UI with new second, about once per second, only when playing, also in background
*/
public static void setCurrentVideoTime(long millis) {
if (VERBOSE)
Log.v(TAG, "setCurrentVideoTime: current video time: " + millis);
VideoInformation.lastKnownVideoTime = millis;
if (!SponsorBlockSettings.isSponsorBlockEnabled) return;
lastKnownVideoTime = millis;
if (millis <= 0) return;
//findAndSkipSegment(false);
if (millis == currentVideoLength) {
SponsorBlockUtils.hideShieldButton();
SponsorBlockUtils.hideVoteButton();
return;
}
SponsorSegment[] segments = sponsorSegmentsOfCurrentVideo;
if (segments == null || segments.length == 0) return;
final long START_TIMER_BEFORE_SEGMENT_MILLIS = 1200;
final long startTimerAtMillis = millis + START_TIMER_BEFORE_SEGMENT_MILLIS;
for (final SponsorSegment segment : segments) {
if (segment.start > millis) {
long scheduleTime = segment.start;
if (muteEndTime > millis && muteEndTime < segment.start) {
scheduleTime = muteEndTime;
}
if (scheduleTime > startTimerAtMillis)
break; // it's more then START_TIMER_BEFORE_SEGMENT_MILLIS far away
if (!segment.category.behaviour.skip)
break;
if (skipSponsorTask == null) {
if (VERBOSE)
Log.d(TAG, "Scheduling skipSponsorTask");
skipSponsorTask = new TimerTask() {
@Override
public void run() {
skipSponsorTask = null;
lastKnownVideoTime = scheduleTime + 1;
VideoInformation.lastKnownVideoTime = lastKnownVideoTime;
new Handler(Looper.getMainLooper()).post(findAndSkipSegmentRunnable);
}
};
sponsorTimer.schedule(skipSponsorTask, scheduleTime - millis);
} else {
if (VERBOSE)
Log.d(TAG, "skipSponsorTask is already scheduled...");
}
break;
}
if (segment.end < millis)
continue;
// we are in the segment!
if (segment.category.behaviour.skip) {
sendViewRequestAsync(millis, segment);
skipSegment(segment, false);
break;
} else {
SkipSegmentView.show();
return;
}
}
SkipSegmentView.hide();
}
private static void sendViewRequestAsync(final long millis, final SponsorSegment segment) {
if (segment.category != SponsorBlockSettings.SegmentInfo.UNSUBMITTED) {
Context context = YouTubeTikTokRoot_Application.getAppContext();
if (context != null) {
SharedPreferences preferences = SponsorBlockSettings.getPreferences(context);
long newSkippedTime = skippedTime + (segment.end - segment.start);
preferences.edit().putInt(SponsorBlockSettings.PREFERENCES_KEY_SKIPPED_SEGMENTS, skippedSegments + 1).apply();
preferences.edit().putLong(SponsorBlockSettings.PREFERENCES_KEY_SKIPPED_SEGMENTS_TIME, newSkippedTime).apply();
}
}
new Thread(() -> {
if (SponsorBlockSettings.countSkips &&
segment.category != SponsorBlockSettings.SegmentInfo.UNSUBMITTED &&
millis - segment.start < 2000) {
// Only skips from the start should count as a view
Requester.sendViewCountRequest(segment);
}
}).start();
}
/**
* Called very high frequency (once every about 100ms), also in background. It sometimes triggers when a video is paused (couple times in the row with the same value)
*/
public static void setCurrentVideoTimeHighPrecision(final long millis) {
if ((millis < lastKnownVideoTime && lastKnownVideoTime >= currentVideoLength) || millis == 0) {
SponsorBlockUtils.showShieldButton(); // skipping from end to the video will show the buttons again
SponsorBlockUtils.showVoteButton();
}
if (lastKnownVideoTime > 0) {
lastKnownVideoTime = millis;
VideoInformation.lastKnownVideoTime = lastKnownVideoTime;
}
else
setCurrentVideoTime(millis);
}
public static long getCurrentVideoLength() {
return currentVideoLength;
}
public static long getLastKnownVideoTime() {
return lastKnownVideoTime;
}
/**
* Called before onDraw method on time bar object, sets video length in millis
*/
public static void setVideoLength(final long length) {
if (VERBOSE_DRAW_OPTIONS)
Log.d(TAG, "setVideoLength: length=" + length);
currentVideoLength = length;
}
public static void setSponsorBarAbsoluteLeft(final Rect rect) {
setSponsorBarAbsoluteLeft(rect.left);
}
public static void setSponsorBarAbsoluteLeft(final float left) {
if (VERBOSE_DRAW_OPTIONS)
Log.d(TAG, String.format("setSponsorBarLeft: left=%.2f", left));
sponsorBarLeft = left;
}
public static void setSponsorBarRect(final Object self) {
try {
Field field = self.getClass().getDeclaredField("replaceMeWithsetSponsorBarRect");
field.setAccessible(true);
Rect rect = (Rect) field.get(self);
if (rect != null) {
setSponsorBarAbsoluteLeft(rect.left);
setSponsorBarAbsoluteRight(rect.right);
}
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
}
public static void setSponsorBarAbsoluteRight(final Rect rect) {
setSponsorBarAbsoluteRight(rect.right);
}
public static void setSponsorBarAbsoluteRight(final float right) {
if (VERBOSE_DRAW_OPTIONS)
Log.d(TAG, String.format("setSponsorBarRight: right=%.2f", right));
sponsorBarRight = right;
}
public static void setSponsorBarThickness(final int thickness) {
setSponsorBarThickness((float) thickness);
}
public static void setSponsorBarThickness(final float thickness) {
// if (VERBOSE_DRAW_OPTIONS)
// Log.d(TAG, String.format("setSponsorBarThickness: thickness=%.2f", thickness));
sponsorBarThickness = thickness;
}
public static void onSkipSponsorClicked() {
if (VERBOSE)
Log.d(TAG, "Skip segment clicked");
findAndSkipSegment(true);
}
public static void addSkipSponsorView15(final View view) {
playerActivity = new WeakReference<>((Activity) view.getContext());
if (VERBOSE)
Log.d(TAG, "addSkipSponsorView15: view=" + view.toString());
new Handler(Looper.getMainLooper()).postDelayed(() -> {
final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) view).getChildAt(2);
Activity context = ((Activity) viewGroup.getContext());
NewSegmentHelperLayout.context = context;
}, 500);
}
public static void addSkipSponsorView14(final View view) {
playerActivity = new WeakReference<>((Activity) view.getContext());
if (VERBOSE)
Log.d(TAG, "addSkipSponsorView14: view=" + view.toString());
new Handler(Looper.getMainLooper()).postDelayed(() -> {
final ViewGroup viewGroup = (ViewGroup) view.getParent();
Activity activity = (Activity) viewGroup.getContext();
NewSegmentHelperLayout.context = activity;
}, 500);
}
/**
* Called when it's time to draw time bar
*/
public static void drawSponsorTimeBars(final Canvas canvas, final float posY) {
if (sponsorBarThickness < 0.1) return;
if (sponsorSegmentsOfCurrentVideo == null) return;
final float thicknessDiv2 = sponsorBarThickness / 2;
final float top = posY - thicknessDiv2;
final float bottom = posY + thicknessDiv2;
final float absoluteLeft = sponsorBarLeft;
final float absoluteRight = sponsorBarRight;
final float tmp1 = 1f / (float) currentVideoLength * (absoluteRight - absoluteLeft);
for (SponsorSegment segment : sponsorSegmentsOfCurrentVideo) {
float left = segment.start * tmp1 + absoluteLeft;
float right = segment.end * tmp1 + absoluteLeft;
canvas.drawRect(left, top, right, bottom, segment.category.paint);
}
}
// private final static Pattern videoIdRegex = Pattern.compile(".*\\.be\\/([A-Za-z0-9_\\-]{0,50}).*");
public static String substringVideoIdFromLink(String link) {
return link.substring(link.lastIndexOf('/') + 1);
}
public static void skipRelativeMilliseconds(int millisRelative) {
skipToMillisecond(lastKnownVideoTime + millisRelative);
}
public static void skipToMillisecond(long millisecond) {
// in 15.x if sponsor clip hits the end, then it crashes the app, because of too many function invocations
// I put this block so that skip can be made only once per some time
long now = System.currentTimeMillis();
if (now < allowNextSkipRequestTime) {
if (VERBOSE)
Log.w(TAG, "skipToMillisecond: to fast, slow down, because you'll fail");
return;
}
allowNextSkipRequestTime = now + 100;
if (setMillisecondMethod == null) {
Log.e(TAG, "setMillisecondMethod is null");
return;
}
final Object currentObj = currentPlayerController.get();
if (currentObj == null) {
Log.e(TAG, "currentObj is null (might have been collected by GC)");
return;
}
if (VERBOSE)
Log.d(TAG, String.format("Requesting skip to millis=%d on thread %s", millisecond, Thread.currentThread().toString()));
final long finalMillisecond = millisecond;
new Handler(Looper.getMainLooper()).post(() -> {
try {
if (VERBOSE)
Log.i(TAG, "Skipping to millis=" + finalMillisecond);
lastKnownVideoTime = finalMillisecond;
VideoInformation.lastKnownVideoTime = lastKnownVideoTime;
setMillisecondMethod.invoke(currentObj, finalMillisecond);
} catch (Exception e) {
Log.e(TAG, "Cannot skip to millisecond", e);
}
});
}
public static void setMute(final boolean value) {
if (setVolumeMethod == null || getVolumeMethod == null) {
Log.e(TAG, "setVolumeMethod or getVolumeMethod is null");
return;
}
final Object currentObj = currentPlayerController.get();
if (currentObj == null) {
Log.e(TAG, "currentObj is null (might have been collected by GC)");
return;
}
if (VERBOSE)
Log.d(TAG, String.format("Requesting set mute to %b on thread %s", value, Thread.currentThread().toString()));
new Handler(Looper.getMainLooper()).post(() -> {
try {
if (VERBOSE)
Log.i(TAG, "Setting to mute=" + value);
long currentVolume = getVolumeMethod.invoke(currentObj);
if (value && currentVolume > 0) {
lastKnownVolume = currentVolume;
}
if (value) {
setVolumeMethod.invoke(currentObj, 0);
} else {
setVolumeMethod.invoke(currentObj, lastKnownVolume);
}
currentlyMuted = value;
} catch (Exception e) {
Log.e(TAG, "Cannot skip to millisecond", e);
}
});
}
private static void findAndSkipSegment(boolean wasClicked) {
if (sponsorSegmentsOfCurrentVideo == null)
return;
final long millis = lastKnownVideoTime;
for (SponsorSegment segment : sponsorSegmentsOfCurrentVideo) {
if (currentlyMuted) {
setMute(false);
muteEndTime = -1;
}
if (segment.start > millis)
break;
if (segment.end < millis)
continue;
SkipSegmentView.show(segment.actionType == SponsorBlockSettings.ActionType.MUTE);
if (!(segment.category.behaviour.skip || wasClicked))
return;
sendViewRequestAsync(millis, segment);
skipSegment(segment, wasClicked);
break;
}
SkipSegmentView.hide();
}
private static void skipSegment(SponsorSegment segment, boolean wasClicked) {
// if (lastSkippedSegment == segment) return;
// lastSkippedSegment = segment;
if (VERBOSE) {
if (segment.actionType == SponsorBlockSettings.ActionType.SKIP) {
Log.d(TAG, "Skipping segment: " + segment.toString());
} else if (segment.actionType == SponsorBlockSettings.ActionType.MUTE) {
Log.d(TAG, "Muting segment: " + segment.toString());
}
}
if (SponsorBlockSettings.showToastWhenSkippedAutomatically && !wasClicked)
SkipSegmentView.notifySkipped(segment);
if (segment.actionType == SponsorBlockSettings.ActionType.SKIP) {
skipToMillisecond(segment.end + 2);
} else if (segment.actionType == SponsorBlockSettings.ActionType.MUTE) {
setMute(true);
if (segment.end > muteEndTime) muteEndTime = segment.end;
}
SkipSegmentView.hide();
if (segment.category == SponsorBlockSettings.SegmentInfo.UNSUBMITTED) {
SponsorSegment[] newSegments = new SponsorSegment[sponsorSegmentsOfCurrentVideo.length - 1];
int i = 0;
for (SponsorSegment sponsorSegment : sponsorSegmentsOfCurrentVideo) {
if (sponsorSegment != segment)
newSegments[i++] = sponsorSegment;
}
sponsorSegmentsOfCurrentVideo = newSegments;
}
}
}