-
Notifications
You must be signed in to change notification settings - Fork 863
Expand file tree
/
Copy pathFullScreenPlayer.kt
More file actions
2650 lines (2320 loc) · 105 KB
/
FullScreenPlayer.kt
File metadata and controls
2650 lines (2320 loc) · 105 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
package com.lagradost.cloudstream3.ui.player
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.content.pm.ActivityInfo
import android.content.res.ColorStateList
import android.content.res.Configuration
import android.graphics.Color
import android.graphics.Matrix
import android.media.AudioManager
import android.media.audiofx.LoudnessEnhancer
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.text.Editable
import android.text.format.DateUtils
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.Surface
import android.view.View
import android.view.ViewGroup
import android.view.WindowInsets
import android.view.WindowManager
import android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.LinearLayout
import androidx.annotation.OptIn
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.core.graphics.blue
import androidx.core.graphics.green
import androidx.core.graphics.red
import androidx.core.view.children
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import androidx.media3.common.MimeTypes
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.AspectRatioFrameLayout
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.google.android.material.button.MaterialButton
import com.lagradost.api.BuildConfig
import com.lagradost.cloudstream3.CommonActivity.keyEventListener
import com.lagradost.cloudstream3.CommonActivity.playerEventListener
import com.lagradost.cloudstream3.CommonActivity.screenHeightWithOrientation
import com.lagradost.cloudstream3.CommonActivity.screenWidthWithOrientation
import com.lagradost.cloudstream3.CommonActivity.showToast
import com.lagradost.cloudstream3.LoadResponse
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.databinding.PlayerCustomLayoutBinding
import com.lagradost.cloudstream3.databinding.SpeedDialogBinding
import com.lagradost.cloudstream3.databinding.SubtitleOffsetBinding
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.mvvm.safe
import com.lagradost.cloudstream3.ui.player.GeneratorPlayer.Companion.subsProvidersIsActive
import com.lagradost.cloudstream3.ui.player.source_priority.QualityDataHelper
import com.lagradost.cloudstream3.ui.settings.Globals.EMULATOR
import com.lagradost.cloudstream3.ui.settings.Globals.PHONE
import com.lagradost.cloudstream3.ui.settings.Globals.TV
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
import com.lagradost.cloudstream3.utils.AppContextUtils.isUsingMobileData
import com.lagradost.cloudstream3.utils.BackPressedCallbackHelper.attachBackPressedCallback
import com.lagradost.cloudstream3.utils.BackPressedCallbackHelper.detachBackPressedCallback
import com.lagradost.cloudstream3.utils.DataStoreHelper
import com.lagradost.cloudstream3.utils.UIHelper.colorFromAttribute
import com.lagradost.cloudstream3.utils.UIHelper.dismissSafe
import com.lagradost.cloudstream3.utils.UIHelper.fixSystemBarsPadding
import com.lagradost.cloudstream3.utils.UIHelper.getNavigationBarHeight
import com.lagradost.cloudstream3.utils.UIHelper.getStatusBarHeight
import com.lagradost.cloudstream3.utils.UIHelper.hideSystemUI
import com.lagradost.cloudstream3.utils.UIHelper.popCurrentPage
import com.lagradost.cloudstream3.utils.UIHelper.showSystemUI
import com.lagradost.cloudstream3.utils.UIHelper.toPx
import com.lagradost.cloudstream3.utils.UserPreferenceDelegate
import com.lagradost.cloudstream3.utils.Vector2
import com.lagradost.cloudstream3.utils.setText
import com.lagradost.cloudstream3.utils.txt
import kotlin.math.abs
import kotlin.math.absoluteValue
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.min
import kotlin.math.round
import kotlin.math.roundToInt
// You can zoom out more than 100%, but it will zoom back into 100%
const val MINIMUM_ZOOM = 0.95f
// How sensitive the auto zoom is to center at the min zoom
const val ZOOM_SNAP_SENSITIVITY = 0.07f
// Maximum zoom to avoid getting lost
const val MAXIMUM_ZOOM = 4.0f
const val MINIMUM_SEEK_TIME = 7000L // when swipe seeking
const val MINIMUM_VERTICAL_SWIPE = 2.0f // in percentage
const val MINIMUM_HORIZONTAL_SWIPE = 2.0f // in percentage
const val VERTICAL_MULTIPLIER = 2.0f
const val HORIZONTAL_MULTIPLIER = 2.0f
const val DOUBLE_TAB_MAXIMUM_HOLD_TIME = 200L
const val DOUBLE_TAB_MINIMUM_TIME_BETWEEN = 200L // this also affects the UI show response time
const val DOUBLE_TAB_PAUSE_PERCENTAGE = 0.15 // in both directions
private const val SUBTITLE_DELAY_BUNDLE_KEY = "subtitle_delay"
// All the UI Logic for the player
@OptIn(UnstableApi::class)
open class FullScreenPlayer : AbstractPlayerFragment() {
private var isVerticalOrientation: Boolean = false
protected open var lockRotation = true
protected open var isFullScreenPlayer = true
protected var playerBinding: PlayerCustomLayoutBinding? = null
protected var brightnessOverlay: View? = null
private var durationMode: Boolean by UserPreferenceDelegate("duration_mode", false)
// state of player UI
protected var isShowing = false
private var uiShowingBeforeGesture = false
protected var isLocked = false
protected var timestampShowState = false
protected var hasEpisodes = false
private set
// protected val hasEpisodes
// get() = episodes.isNotEmpty()
// options for player
/**
* Default profile 1
* Decides how links should be sorted based on a priority system.
* This will be set in runtime based on settings.
**/
protected var currentQualityProfile = 1
// protected var currentPrefQuality =
// Qualities.P2160.value // preferred maximum quality, used for ppl w bad internet or on cell
protected var extraBrightnessEnabled = false
protected var fastForwardTime = 10000L
protected var androidTVInterfaceOffSeekTime = 10000L
protected var androidTVInterfaceOnSeekTime = 30000L
protected var swipeHorizontalEnabled = false
protected var swipeVerticalEnabled = false
protected var playBackSpeedEnabled = false
protected var playerResizeEnabled = false
protected var doubleTapEnabled = false
protected var doubleTapPauseEnabled = true
protected var playerRotateEnabled = false
protected var rotatedManually = false
protected var autoPlayerRotateEnabled = false
private var hideControlsNames = false
protected var speedupEnabled = false
protected var subtitleDelay
set(value) = try {
player.setSubtitleOffset(-value)
} catch (e: Exception) {
logError(e)
}
get() = try {
-player.getSubtitleOffset()
} catch (e: Exception) {
logError(e)
0L
}
// private var useSystemBrightness = false
protected var useTrueSystemBrightness = true
private val fullscreenNotch = true // TODO SETTING
private var statusBarHeight: Int? = null
private var navigationBarHeight: Int? = null
private val brightnessIcons = listOf(
R.drawable.sun_1,
R.drawable.sun_2,
R.drawable.sun_3,
R.drawable.sun_4,
R.drawable.sun_5,
R.drawable.sun_6,
R.drawable.sun_7,
// R.drawable.ic_baseline_brightness_1_24,
// R.drawable.ic_baseline_brightness_2_24,
// R.drawable.ic_baseline_brightness_3_24,
// R.drawable.ic_baseline_brightness_4_24,
// R.drawable.ic_baseline_brightness_5_24,
// R.drawable.ic_baseline_brightness_6_24,
// R.drawable.ic_baseline_brightness_7_24,
)
private val volumeIcons = listOf(
R.drawable.ic_baseline_volume_mute_24,
R.drawable.ic_baseline_volume_down_24,
R.drawable.ic_baseline_volume_up_24,
)
private var isShowingEpisodeOverlay: Boolean = false
private var previousPlayStatus: Boolean = false
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = super.onCreateView(inflater, container, savedInstanceState) ?: return null
playerBinding = PlayerCustomLayoutBinding.bind(root.findViewById(R.id.player_holder))
// Inject the overlay from a separate XML into the PlayerView content frame
safe {
val pv = root.findViewById<androidx.media3.ui.PlayerView>(R.id.player_view)
val packageName = context?.packageName ?: return@safe
val contentId = resources.getIdentifier("exo_content_frame", "id", packageName)
val contentFrame = pv?.findViewById<ViewGroup>(contentId)
if (contentFrame != null) {
brightnessOverlay = contentFrame.findViewById<View>(R.id.extra_brightness_overlay)
brightnessOverlay = LayoutInflater.from(context).inflate(
R.layout.extra_brightness_overlay,
contentFrame,
false
)
contentFrame.addView(brightnessOverlay)
requestUpdateBrightnessOverlayOnNextLayout()
}
}
return root
}
@SuppressLint("UnsafeOptInUsageError")
override fun playerUpdated(player: Any?) {
super.playerUpdated(player)
}
override fun onDestroyView() {
// Clean up brightness overlay if created
safe {
// remove overlay if present
brightnessOverlay?.let { overlay ->
val oParent = overlay.parent as? ViewGroup
oParent?.removeView(overlay)
}
}
brightnessOverlay = null
playerBinding = null
super.onDestroyView()
}
/**
* Resize/position the brightness overlay to exactly match the visible video surface.
* This copies the video surface size, scale and translation so the overlay won't cover
* letterbox/pillarbox areas when zooming or panning.
*/
private fun updateBrightnessOverlayBounds() {
val overlay = brightnessOverlay ?: return
val pv = playerView ?: return
val video = pv.videoSurfaceView ?: return
// Compute accurate transformed bounding box of the video view after scale+translation
val vw = video.width.toFloat()
val vh = video.height.toFloat()
val sx = video.scaleX
val sy = video.scaleY
if (vw > 0f && vh > 0f) {
// pivot defaults to center if not set
val pivotX = if (video.pivotX != 0f) video.pivotX else vw * 0.5f
val pivotY = if (video.pivotY != 0f) video.pivotY else vh * 0.5f
// Use view position (includes translation) as base; avoid double-counting translation
val tx = video.x
val ty = video.y
// transform function for a local point (lx,ly)
fun transform(lx: Float, ly: Float): Pair<Float, Float> {
val gx = tx + pivotX + (lx - pivotX) * sx
val gy = ty + pivotY + (ly - pivotY) * sy
return Pair(gx, gy)
}
val p0 = transform(0f, 0f)
val p1 = transform(vw, 0f)
val p2 = transform(0f, vh)
val p3 = transform(vw, vh)
val minX = min(min(p0.first, p1.first), min(p2.first, p3.first))
val maxX = max(max(p0.first, p1.first), max(p2.first, p3.first))
val minY = min(min(p0.second, p1.second), min(p2.second, p3.second))
val maxY = max(max(p0.second, p1.second), max(p2.second, p3.second))
val newW = ceil(maxX - minX).toInt().coerceAtLeast(0)
val newH = ceil(maxY - minY).toInt().coerceAtLeast(0)
val lp = overlay.layoutParams
if (lp == null) {
overlay.layoutParams = ViewGroup.LayoutParams(newW, newH)
} else {
if (lp.width != newW || lp.height != newH) {
lp.width = newW
lp.height = newH
overlay.layoutParams = lp
}
}
overlay.scaleX = 1.0f
overlay.scaleY = 1.0f
overlay.x = minX
overlay.y = minY
}
}
/**
* Ensure the overlay is updated once the next layout pass completes.
* Adds a one-time global layout listener (PiP/resizing/rotation frames).
*/
private fun requestUpdateBrightnessOverlayOnNextLayout() {
val pv = playerView ?: return
safe {
val obs = pv.viewTreeObserver
val listener = object : android.view.ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
safe {
updateBrightnessOverlayBounds()
}
if (obs.isAlive) {
obs.removeOnGlobalLayoutListener(this)
}
}
}
if (obs.isAlive) obs.addOnGlobalLayoutListener(listener)
}
}
open fun showMirrorsDialogue() {
throw NotImplementedError()
}
open fun showTracksDialogue() {
throw NotImplementedError()
}
open fun openOnlineSubPicker(
context: Context,
loadResponse: LoadResponse?,
dismissCallback: (() -> Unit)
) {
throw NotImplementedError()
}
open fun showEpisodesOverlay() {
throw NotImplementedError()
}
open fun isThereEpisodes(): Boolean {
return false
}
/**
* [isValidTouch] should be called on a [View] spanning across the screen for reliable results.
*
* Android has supported gesture navigation properly since API-30. We get the absolute screen dimens using
* [WindowManager.getCurrentWindowMetrics] and remove the stable insets
* {[WindowInsets.getInsetsIgnoringVisibility]} to get a safe perimeter.
* This approach supports any and all types of necessary system insets.
*
* @return false if the touch is on the status bar or navigation bar
* */
private fun View.isValidTouch(rawX: Float, rawY: Float): Boolean {
// NOTE: screenWidth is without the navbar width when 3button nav is turned on.
if (Build.VERSION.SDK_INT >= 30) {
// real = absolute dimen without any default deductions like navbar width
val windowMetrics =
(context?.getSystemService(Context.WINDOW_SERVICE) as? WindowManager)?.currentWindowMetrics
val realScreenHeight =
windowMetrics?.let { windowMetrics.bounds.bottom - windowMetrics.bounds.top }
?: screenHeightWithOrientation
val realScreenWidth =
windowMetrics?.let { windowMetrics.bounds.right - windowMetrics.bounds.left }
?: screenWidthWithOrientation
val insets =
rootWindowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars())
val isOutsideHeight = rawY < insets.top || rawY > (realScreenHeight - insets.bottom)
val isOutsideWidth = if (windowMetrics == null) {
rawX < screenWidthWithOrientation
} else rawX < insets.left || rawX > realScreenWidth - insets.right
return !(isOutsideWidth || isOutsideHeight)
} else {
val statusHeight = statusBarHeight ?: 0
return rawY > statusHeight && rawX < screenWidthWithOrientation
}
}
override fun exitedPipMode() {
animateLayoutChanges()
}
private fun animateLayoutChangesForSubtitles() =
// Post here as bottomPlayerBar is gone the first frame => bottomPlayerBar.height = 0
playerBinding?.bottomPlayerBar?.post {
val sView = subView ?: return@post
val sStyle = CustomDecoder.style
val binding = playerBinding ?: return@post
val move = if (isShowing) minOf(
// We do not want to drag down subtitles if the subtitle elevation is large
-sStyle.elevation.toPx,
// The lib uses Invisible instead of Gone for no reason
binding.previewFrameLayout.height - binding.bottomPlayerBar.height
) else -sStyle.elevation.toPx
ObjectAnimator.ofFloat(sView, "translationY", move.toFloat()).apply {
duration = 200
start()
}
}
protected fun animateLayoutChanges() {
if (isLayout(PHONE)) { // isEnabled also disables the onKeyDown
playerBinding?.exoProgress?.isEnabled = isShowing // Prevent accidental clicks/drags
}
if (isShowing) {
updateUIVisibility()
} else {
toggleEpisodesOverlay(false)
playerBinding?.playerHolder?.postDelayed({ updateUIVisibility() }, 200)
}
val titleMove = if (isShowing) 0f else -50.toPx.toFloat()
playerBinding?.playerVideoTitleHolder?.let {
ObjectAnimator.ofFloat(it, "translationY", titleMove).apply {
duration = 200
start()
}
}
playerBinding?.playerVideoInfo?.let {
ObjectAnimator.ofFloat(it, "translationY", titleMove).apply {
duration = 200
start()
}
}
val playerBarMove = if (isShowing) 0f else 50.toPx.toFloat()
playerBinding?.bottomPlayerBar?.let {
ObjectAnimator.ofFloat(it, "translationY", playerBarMove).apply {
duration = 200
start()
}
}
if (isLayout(PHONE)) {
playerBinding?.playerEpisodesButton?.let {
ObjectAnimator.ofFloat(it, "translationX", if (isShowing) 0f else 50.toPx.toFloat())
.apply {
duration = 200
start()
}
}
}
val fadeTo = if (isShowing) 1f else 0f
val fadeAnimation = AlphaAnimation(1f - fadeTo, fadeTo)
fadeAnimation.duration = 100
fadeAnimation.fillAfter = true
animateLayoutChangesForSubtitles()
val playerSourceMove = if (isShowing) 0f else -50.toPx.toFloat()
playerBinding?.apply {
playerOpenSource.let {
ObjectAnimator.ofFloat(it, "translationY", playerSourceMove).apply {
duration = 200
start()
}
}
if (!isLocked) {
playerFfwdHolder.alpha = 1f
playerRewHolder.alpha = 1f
// player_pause_play_holder?.alpha = 1f
shadowOverlay.isVisible = true
shadowOverlay.startAnimation(fadeAnimation)
playerFfwdHolder.startAnimation(fadeAnimation)
playerRewHolder.startAnimation(fadeAnimation)
playerPausePlay.startAnimation(fadeAnimation)
downloadBothHeader.startAnimation(fadeAnimation)
/*if (isBuffering) {
player_pause_play?.isVisible = false
player_pause_play_holder?.isVisible = false
} else {
player_pause_play?.isVisible = true
player_pause_play_holder?.startAnimation(fadeAnimation)
player_pause_play?.startAnimation(fadeAnimation)
}*/
// player_buffering?.startAnimation(fadeAnimation)
}
bottomPlayerBar.startAnimation(fadeAnimation)
playerOpenSource.startAnimation(fadeAnimation)
playerTopHolder.startAnimation(fadeAnimation)
}
}
override fun subtitlesChanged() {
val tracks = player.getVideoTracks()
val isBuiltinSubtitles = tracks.currentTextTracks.all { track ->
track.sampleMimeType == MimeTypes.APPLICATION_MEDIA3_CUES
}
// Subtitle offset is not possible on built-in media3 tracks
playerBinding?.playerSubtitleOffsetBtt?.isGone =
isBuiltinSubtitles || tracks.currentTextTracks.isEmpty()
}
private fun restoreOrientationWithSensor(activity: Activity) {
val currentOrientation = activity.resources.configuration.orientation
val orientation = when (currentOrientation) {
Configuration.ORIENTATION_LANDSCAPE ->
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
Configuration.ORIENTATION_PORTRAIT ->
ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
else -> dynamicOrientation()
}
activity.requestedOrientation = orientation
}
private fun toggleOrientationWithSensor(activity: Activity) {
val currentOrientation = activity.resources.configuration.orientation
val orientation: Int = when (currentOrientation) {
Configuration.ORIENTATION_LANDSCAPE ->
ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
Configuration.ORIENTATION_PORTRAIT ->
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
else -> dynamicOrientation()
}
activity.requestedOrientation = orientation
}
open fun lockOrientation(activity: Activity) {
@Suppress("DEPRECATION")
val display = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R)
(activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
else activity.display!!
val rotation = display.rotation
val currentOrientation = activity.resources.configuration.orientation
val orientation: Int
when (currentOrientation) {
Configuration.ORIENTATION_LANDSCAPE ->
orientation =
if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90)
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
else
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
Configuration.ORIENTATION_PORTRAIT ->
orientation =
if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_270)
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
else
ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT
else -> orientation = dynamicOrientation()
}
activity.requestedOrientation = orientation
}
private fun updateOrientation(ignoreDynamicOrientation: Boolean = false) {
activity?.apply {
if (lockRotation) {
if (isLocked) {
lockOrientation(this)
} else {
if (ignoreDynamicOrientation || rotatedManually) {
// restore when lock is disabled
restoreOrientationWithSensor(this)
} else {
this.requestedOrientation = dynamicOrientation()
}
}
}
}
}
protected fun enterFullscreen() {
if (isFullScreenPlayer) {
activity?.hideSystemUI()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && fullscreenNotch) {
val params = activity?.window?.attributes
params?.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
activity?.window?.attributes = params
}
}
updateOrientation()
}
protected fun exitFullscreen() {
resetZoomToDefault()
// if (lockRotation)
activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_USER
// simply resets brightness and notch settings that might have been overridden
val lp = activity?.window?.attributes
lp?.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
lp?.layoutInDisplayCutoutMode =
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT
}
activity?.window?.attributes = lp
activity?.showSystemUI()
}
private fun resetZoomToDefault() {
if (zoomMatrix != null) resize(PlayerResize.Fit, false)
}
override fun onResume() {
enterFullscreen()
verifyVolume()
activity?.attachBackPressedCallback("FullScreenPlayer") {
if (isShowingEpisodeOverlay) {
// isShowingEpisodeOverlay pauses, so this makes it easier to unpause
if (isLayout(TV or EMULATOR)) {
playerPausePlay?.requestFocus()
}
toggleEpisodesOverlay(show = false)
return@attachBackPressedCallback
} else if (isShowing && isLayout(TV or EMULATOR)) {
// netflix capture back and hide ~monke
onClickChange()
} else {
activity?.popCurrentPage("FullScreenPlayer")
}
}
requestUpdateBrightnessOverlayOnNextLayout()
super.onResume()
}
override fun onStop() {
activity?.detachBackPressedCallback("FullScreenPlayer")
super.onStop()
}
override fun onDestroy() {
exitFullscreen()
super.onDestroy()
}
private fun setPlayBackSpeed(speed: Float) {
try {
DataStoreHelper.playBackSpeed = speed
playerBinding?.playerSpeedBtt?.text =
getString(R.string.player_speed_text_format).format(speed)
.replace(".0x", "x")
} catch (e: Exception) {
// the format string was wrong
logError(e)
}
player.setPlaybackSpeed(speed)
}
private fun skipOp() {
player.seekTime(85000) // skip 85s
}
private fun showSubtitleOffsetDialog() {
val ctx = context ?: return
// Pause player because the subtitles cannot be continuously updated to follow playback.
player.handleEvent(
CSPlayerEvent.Pause,
PlayerEventSource.UI
)
val binding = SubtitleOffsetBinding.inflate(LayoutInflater.from(ctx), null, false)
// Use dialog as opposed to alertdialog to get fullscreen
val dialog = Dialog(ctx, R.style.DialogFullscreenPlayer).apply {
setContentView(binding.root)
}
dialog.show()
val isPortrait =
ctx.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
fixSystemBarsPadding(binding.root, fixIme = isPortrait)
var currentOffset = subtitleDelay
binding.apply {
var subtitleAdapter: SubtitleOffsetItemAdapter? = null
subtitleOffsetInput.doOnTextChanged { text, _, _, _ ->
text?.toString()?.toLongOrNull()?.let { time ->
currentOffset = time
// Scroll to the first active subtitle
val playerPosition = player.getPosition() ?: 0
val totalPosition = playerPosition - currentOffset
subtitleAdapter?.updateTime(totalPosition)
subtitleAdapter?.getLatestActiveItem(totalPosition)
?.let { subtitlePos ->
subtitleOffsetRecyclerview.scrollToPosition(subtitlePos)
}
val str = when {
time > 0L -> {
txt(R.string.subtitle_offset_extra_hint_later_format, time)
}
time < 0L -> {
txt(R.string.subtitle_offset_extra_hint_before_format, -time)
}
else -> {
txt(R.string.subtitle_offset_extra_hint_none_format)
}
}
subtitleOffsetSubTitle.setText(str)
}
}
subtitleOffsetInput.text =
Editable.Factory.getInstance()?.newEditable(currentOffset.toString())
val subtitles = player.getSubtitleCues().toMutableList()
subtitleOffsetRecyclerview.isVisible = subtitles.isNotEmpty()
noSubtitlesLoadedNotice.isVisible = subtitles.isEmpty()
val initialSubtitlePosition = (player.getPosition() ?: 0) - currentOffset
subtitleAdapter =
SubtitleOffsetItemAdapter(initialSubtitlePosition) { subtitleCue ->
val playerPosition = player.getPosition() ?: 0
subtitleOffsetInput.text = Editable.Factory.getInstance()
?.newEditable((playerPosition - subtitleCue.startTimeMs).toString())
}.apply {
submitList(subtitles)
}
subtitleOffsetRecyclerview.adapter = subtitleAdapter
// Prevent flashing changes when changing items
(subtitleOffsetRecyclerview.itemAnimator as? SimpleItemAnimator)?.supportsChangeAnimations =
false
val firstSubtitle = subtitleAdapter.getLatestActiveItem(initialSubtitlePosition)
subtitleOffsetRecyclerview.scrollToPosition(firstSubtitle)
val buttonChange = 100L
val buttonChangeMore = 1000L
fun changeBy(by: Long) {
val current = (subtitleOffsetInput.text?.toString()?.toLongOrNull() ?: 0) + by
subtitleOffsetInput.text =
Editable.Factory.getInstance()?.newEditable(current.toString())
}
subtitleOffsetAdd.setOnClickListener {
changeBy(buttonChange)
}
subtitleOffsetAddMore.setOnClickListener {
changeBy(buttonChangeMore)
}
subtitleOffsetSubtract.setOnClickListener {
changeBy(-buttonChange)
}
subtitleOffsetSubtractMore.setOnClickListener {
changeBy(-buttonChangeMore)
}
dialog.setOnDismissListener {
if (isFullScreenPlayer)
activity?.hideSystemUI()
}
applyBtt.setOnClickListener {
subtitleDelay = currentOffset
dialog.dismissSafe(activity)
player.seekTime(1L)
}
resetBtt.setOnClickListener {
subtitleDelay = 0
dialog.dismissSafe(activity)
player.seekTime(1L)
}
cancelBtt.setOnClickListener {
dialog.dismissSafe(activity)
}
}
}
@SuppressLint("SetTextI18n")
fun updateSpeedDialogBinding(binding: SpeedDialogBinding) {
val speed = player.getPlaybackSpeed()
binding.speedText.text = "%.2fx".format(speed).replace(".0x", "x")
// Android crashes if you don't round to an exact step size
binding.speedBar.value =
(speed.coerceIn(0.1f, 2.0f) / binding.speedBar.stepSize).roundToInt()
.toFloat() * binding.speedBar.stepSize
}
private fun showSpeedDialog() {
val act = activity ?: return
val isPlaying = player.getIsPlaying()
player.handleEvent(CSPlayerEvent.Pause, PlayerEventSource.UI)
val binding: SpeedDialogBinding = SpeedDialogBinding.inflate(
LayoutInflater.from(act)
)
updateSpeedDialogBinding(binding)
for ((view, speed) in arrayOf(
binding.speed25 to 0.25f,
binding.speed100 to 1.0f,
binding.speed125 to 1.25f,
binding.speed150 to 1.5f,
binding.speed200 to 2.0f,
)) {
view.setOnClickListener {
setPlayBackSpeed(speed)
updateSpeedDialogBinding(binding)
}
}
binding.speedMinus.setOnClickListener {
setPlayBackSpeed(maxOf((player.getPlaybackSpeed() - 0.1f), 0.1f))
updateSpeedDialogBinding(binding)
}
binding.speedPlus.setOnClickListener {
setPlayBackSpeed(minOf((player.getPlaybackSpeed() + 0.1f), 2.0f))
updateSpeedDialogBinding(binding)
}
binding.speedBar.addOnChangeListener { slider, value, fromUser ->
if (fromUser) {
setPlayBackSpeed(value)
updateSpeedDialogBinding(binding)
}
}
val dismiss = DialogInterface.OnDismissListener {
if (isFullScreenPlayer)
activity?.hideSystemUI()
if (isPlaying) {
player.handleEvent(CSPlayerEvent.Play, PlayerEventSource.UI)
}
}
// if (isLayout(PHONE)) {
// val builder =
// BottomSheetDialog(act, R.style.AlertDialogCustom)
// builder.setContentView(binding.root)
// builder.setOnDismissListener(dismiss)
// builder.show()
//} else {
val builder =
AlertDialog.Builder(act, R.style.AlertDialogCustom)
.setView(binding.root)
builder.setOnDismissListener(dismiss)
val dialog = builder.create()
dialog.show()
//}
}
fun resetRewindText() {
playerBinding?.exoRewText?.text =
getString(R.string.rew_text_regular_format).format(fastForwardTime / 1000)
}
fun resetFastForwardText() {
playerBinding?.exoFfwdText?.text =
getString(R.string.ffw_text_regular_format).format(fastForwardTime / 1000)
}
private fun rewind() {
try {
playerBinding?.apply {
playerCenterMenu.isGone = false
playerRewHolder.alpha = 1f
val rotateLeft = AnimationUtils.loadAnimation(context, R.anim.rotate_left)
playerRew.startAnimation(rotateLeft)
val goLeft = AnimationUtils.loadAnimation(context, R.anim.go_left)
goLeft.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation?) {}
override fun onAnimationRepeat(animation: Animation?) {}
override fun onAnimationEnd(animation: Animation?) {
exoRewText.post {
resetRewindText()
playerCenterMenu.isGone = !isShowing
playerRewHolder.alpha = if (isShowing) 1f else 0f
}
}
})
exoRewText.startAnimation(goLeft)
exoRewText.text =
getString(R.string.rew_text_format).format(fastForwardTime / 1000)
}
player.seekTime(-fastForwardTime)
} catch (e: Exception) {
logError(e)
}
}
private fun fastForward() {
try {
playerBinding?.apply {
playerCenterMenu.isGone = false
playerFfwdHolder.alpha = 1f
val rotateRight = AnimationUtils.loadAnimation(context, R.anim.rotate_right)
playerFfwd.startAnimation(rotateRight)
val goRight = AnimationUtils.loadAnimation(context, R.anim.go_right)
goRight.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation?) {}
override fun onAnimationRepeat(animation: Animation?) {}
override fun onAnimationEnd(animation: Animation?) {
exoFfwdText.post {
resetFastForwardText()
playerCenterMenu.isGone = !isShowing
playerFfwdHolder.alpha = if (isShowing) 1f else 0f
}
}
})
exoFfwdText.startAnimation(goRight)
exoFfwdText.text =
getString(R.string.ffw_text_format).format(fastForwardTime / 1000)
}
player.seekTime(fastForwardTime)
} catch (e: Exception) {
logError(e)
}
}
private fun onClickChange() {
isShowing = !isShowing
if (isShowing) {
playerBinding?.playerIntroPlay?.isGone = true
autoHide()
}
if (isFullScreenPlayer)
activity?.hideSystemUI()
animateLayoutChanges()
if (playerBinding?.playerEpisodeOverlay?.isGone == true) playerBinding?.playerPausePlay?.requestFocus()
}
private fun toggleLock() {
if (!isShowing) {
onClickChange()
}
isLocked = !isLocked
updateOrientation(true) // set true to ignore auto rotate to stay in current orientation
if (isLocked && isShowing) {
playerBinding?.playerHolder?.postDelayed({
if (isLocked && isShowing) {
onClickChange()
}
}, 200)
}
val fadeTo = if (isLocked) 0f else 1f
playerBinding?.apply {
val fadeAnimation = AlphaAnimation(playerVideoTitleHolder.alpha, fadeTo).apply {
duration = 100
fillAfter = true
}
updateUIVisibility()
// MENUS
// centerMenu.startAnimation(fadeAnimation)
playerPausePlay.startAnimation(fadeAnimation)
playerFfwdHolder.startAnimation(fadeAnimation)
playerRewHolder.startAnimation(fadeAnimation)
downloadBothHeader.startAnimation(fadeAnimation)
if (hasEpisodes)
playerEpisodesButton.startAnimation(fadeAnimation)
// player_media_route_button?.startAnimation(fadeAnimation)
// video_bar.startAnimation(fadeAnimation)