Skip to content

Commit

Permalink
Fix some crashes / issues after player refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
Stypox committed Apr 9, 2022
1 parent b2bcdd0 commit 30b9e0f
Show file tree
Hide file tree
Showing 8 changed files with 184 additions and 107 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -239,10 +239,6 @@ public void onServiceConnected(final Player connectedPlayer,
playerUi.ifPresent(MainPlayerUi::toggleFullscreen);
}

if (playerIsNotStopped() && player.videoPlayerSelected()) {
addVideoPlayerView();
}

//noinspection SimplifyOptionalCallChains
if (playAfterConnect
|| (currentInfo != null
Expand Down Expand Up @@ -334,6 +330,9 @@ public void onPause() {
@Override
public void onResume() {
super.onResume();
if (DEBUG) {
Log.d(TAG, "onResume() called");
}

activity.sendBroadcast(new Intent(ACTION_VIDEO_FRAGMENT_RESUMED));

Expand Down Expand Up @@ -1218,6 +1217,7 @@ private void openMainPlayer() {
}

final PlayQueue queue = setupPlayQueueForIntent(false);
addVideoPlayerView(); // TODO TODO why remove it when switching video?!?

final Intent playerIntent = NavigationHelper.getPlayerIntent(requireContext(),
PlayerService.class, queue, true, autoPlayEnabled);
Expand Down Expand Up @@ -1302,22 +1302,14 @@ private void addVideoPlayerView() {
if (!isPlayerAvailable() || getView() == null) {
return;
}

final Optional<View> root = player.UIs().get(VideoPlayerUi.class)
.map(VideoPlayerUi::getBinding)
.map(ViewBinding::getRoot);

// Check if viewHolder already contains a child TODO TODO whaat
/*if (playerService != null
&& root.map(View::getParent).orElse(null) != binding.playerPlaceholder) {
playerService.removeViewFromParent();
}*/
setHeightThumbnail();

// Prevent from re-adding a view multiple times
if (root.isPresent() && root.get().getParent() == null) {
binding.playerPlaceholder.addView(root.get());
}
new Handler().post(() -> player.UIs().get(MainPlayerUi.class).ifPresent(playerUi -> {
playerUi.removeViewFromParent();
binding.playerPlaceholder.addView(playerUi.getBinding().getRoot());
playerUi.setupVideoSurfaceIfNeeded();
}));
}

private void removeVideoPlayerView() {
Expand Down Expand Up @@ -1800,9 +1792,6 @@ private void showPlaybackProgress(final long progress, final long duration) {

@Override
public void onViewCreated() {
// Video view can have elements visible from popup,
// We hide it here but once it ready the view will be shown in handleIntent()
getRoot().ifPresent(view -> view.setVisibility(View.GONE));
addVideoPlayerView();
}

Expand Down
6 changes: 5 additions & 1 deletion app/src/main/java/org/schabi/newpipe/player/Player.java
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,10 @@ private void initUIsForCurrentPlayerType() {
// make sure UIs know whether a service is connected or not
UIs.call(PlayerUi::onFragmentListenerSet);
}
if (!exoPlayerIsNull()) {
UIs.call(PlayerUi::initPlayer);
UIs.call(PlayerUi::initPlayback);
}
}

private void initPlayback(@NonNull final PlayQueue queue,
Expand Down Expand Up @@ -577,7 +581,7 @@ public void destroy() {
progressUpdateDisposable.set(null);
PicassoHelper.cancelTag(PicassoHelper.PLAYER_THUMBNAIL_TAG); // cancel thumbnail loading

UIs.call(PlayerUi::destroy);
UIs.destroyAll(Object.class); // destroy every UI: obviously every UI extends Object
}

public void setRecovery() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package org.schabi.newpipe.player.gesture

import android.app.Activity
import android.content.Context
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import org.schabi.newpipe.MainActivity
import org.schabi.newpipe.R
Expand All @@ -29,8 +29,6 @@ import kotlin.math.min
class MainPlayerGestureListener(
private val playerUi: MainPlayerUi
) : BasePlayerGestureListener(playerUi), OnTouchListener {
private val maxVolume: Int = player.audioReactor.maxVolume

private var isMoving = false

override fun onTouch(v: View, event: MotionEvent): Boolean {
Expand All @@ -41,11 +39,11 @@ class MainPlayerGestureListener(
}
return when (event.action) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
v.parent.requestDisallowInterceptTouchEvent(playerUi.isFullscreen)
v.parent?.requestDisallowInterceptTouchEvent(playerUi.isFullscreen)
true
}
MotionEvent.ACTION_UP -> {
v.parent.requestDisallowInterceptTouchEvent(false)
v.parent?.requestDisallowInterceptTouchEvent(false)
false
}
else -> true
Expand All @@ -69,7 +67,7 @@ class MainPlayerGestureListener(
binding.volumeProgressBar.incrementProgressBy(distanceY.toInt())
val currentProgressPercent: Float =
binding.volumeProgressBar.progress.toFloat() / MAX_GESTURE_LENGTH
val currentVolume = (maxVolume * currentProgressPercent).toInt()
val currentVolume = (player.audioReactor.maxVolume * currentProgressPercent).toInt()
player.audioReactor.volume = currentVolume
if (DEBUG) {
Log.d(TAG, "onScroll().volumeControl, currentVolume = $currentVolume")
Expand All @@ -96,7 +94,7 @@ class MainPlayerGestureListener(
}

private fun onScrollBrightness(distanceY: Float) {
val parent: Activity = playerUi.parentActivity
val parent: AppCompatActivity = playerUi.parentActivity.orElse(null) ?: return
val window = parent.window
val layoutParams = window.attributes
val bar: ProgressBar = binding.brightnessProgressBar
Expand Down
97 changes: 62 additions & 35 deletions app/src/main/java/org/schabi/newpipe/player/ui/MainPlayerUi.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

Expand Down Expand Up @@ -68,8 +69,9 @@

import java.util.List;
import java.util.Objects;
import java.util.Optional;

public final class MainPlayerUi extends VideoPlayerUi {
public final class MainPlayerUi extends VideoPlayerUi implements View.OnLayoutChangeListener {
private static final String TAG = MainPlayerUi.class.getSimpleName();

private boolean isFullscreen = false;
Expand Down Expand Up @@ -113,7 +115,6 @@ public void setupAfterIntent() {

super.setupAfterIntent();

binding.getRoot().setVisibility(View.VISIBLE);
initVideoPlayer();
// Android TV: without it focus will frame the whole player
binding.playPauseButton.requestFocus();
Expand All @@ -139,7 +140,8 @@ protected void initListeners() {
binding.segmentsButton.setOnClickListener(v -> onSegmentsClicked());

binding.addToPlaylistButton.setOnClickListener(v ->
player.onAddToPlaylistClicked(getParentActivity().getSupportFragmentManager()));
getParentActivity().map(FragmentActivity::getSupportFragmentManager)
.ifPresent(player::onAddToPlaylistClicked));

settingsContentObserver = new ContentObserver(new Handler()) {
@Override
Expand All @@ -151,7 +153,20 @@ public void onChange(final boolean selfChange) {
Settings.System.getUriFor(Settings.System.ACCELEROMETER_ROTATION), false,
settingsContentObserver);

binding.getRoot().addOnLayoutChangeListener(this::onLayoutChange);
binding.getRoot().addOnLayoutChangeListener(this);
}

@Override
protected void deinitListeners() {
super.deinitListeners();

binding.queueButton.setOnClickListener(null);
binding.segmentsButton.setOnClickListener(null);
binding.addToPlaylistButton.setOnClickListener(null);

context.getContentResolver().unregisterContentObserver(settingsContentObserver);

binding.getRoot().removeOnLayoutChangeListener(this);
}

@Override
Expand All @@ -178,7 +193,6 @@ public void removeViewFromParent() {
@Override
public void destroy() {
super.destroy();
context.getContentResolver().unregisterContentObserver(settingsContentObserver);

// Exit from fullscreen when user closes the player via notification
if (isFullscreen) {
Expand Down Expand Up @@ -324,9 +338,10 @@ private void onFragmentStopped() {
player.useVideoSource(false);
break;
case MINIMIZE_ON_EXIT_MODE_POPUP:
player.setRecovery();
NavigationHelper.playOnPopupPlayer(getParentActivity(),
player.getPlayQueue(), true);
getParentActivity().ifPresent(activity -> {
player.setRecovery();
NavigationHelper.playOnPopupPlayer(activity, player.getPlayQueue(), true);
});
break;
case MINIMIZE_ON_EXIT_MODE_NONE: default:
player.pause();
Expand Down Expand Up @@ -384,16 +399,17 @@ protected void showOrHideButtons() {
@Override
public void showSystemUIPartially() {
if (isFullscreen) {
final AppCompatActivity activity = getParentActivity();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
activity.getWindow().setNavigationBarColor(Color.TRANSPARENT);
}
final int visibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
activity.getWindow().getDecorView().setSystemUiVisibility(visibility);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getParentActivity().ifPresent(activity -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
activity.getWindow().setNavigationBarColor(Color.TRANSPARENT);
}
final int visibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
activity.getWindow().getDecorView().setSystemUiVisibility(visibility);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
});
}
}

Expand Down Expand Up @@ -477,8 +493,9 @@ protected void setupSubtitleView(float captionScale) {
//region Gestures

@SuppressWarnings("checkstyle:ParameterNumber")
private void onLayoutChange(final View view, final int l, final int t, final int r, final int b,
final int ol, final int ot, final int or, final int ob) {
@Override
public void onLayoutChange(final View view, final int l, final int t, final int r, final int b,
final int ol, final int ot, final int or, final int ob) {
if (l != ol || t != ot || r != or || b != ob) {
// Use smaller value to be consistent between screen orientations
// (and to make usage easier)
Expand All @@ -502,9 +519,8 @@ private void onLayoutChange(final View view, final int l, final int t, final int

private void setInitialGestureValues() {
if (player.getAudioReactor() != null) {
final float currentVolumeNormalized =
(float) player.getAudioReactor().getVolume()
/ player.getAudioReactor().getMaxVolume();
final float currentVolumeNormalized = (float) player.getAudioReactor().getVolume()
/ player.getAudioReactor().getMaxVolume();
binding.volumeProgressBar.setProgress(
(int) (binding.volumeProgressBar.getMax() * currentVolumeNormalized));
}
Expand All @@ -516,8 +532,6 @@ private void setInitialGestureValues() {
// Play queue, segments and streams
//////////////////////////////////////////////////////////////////////////*/
//region Play queue, segments and streams


@Override
public void onMetadataChanged(@NonNull final MediaSourceTag tag) {
super.onMetadataChanged(tag);
Expand Down Expand Up @@ -718,7 +732,7 @@ public void selected(final PlayQueueItem item, final View view) {
@Override
public void held(final PlayQueueItem item, final View view) {
@Nullable final PlayQueue playQueue = player.getPlayQueue();
@Nullable final AppCompatActivity parentActivity = getParentActivity();
@Nullable final AppCompatActivity parentActivity = getParentActivity().orElse(null);
if (playQueue != null && parentActivity != null && playQueue.indexOf(item) != -1) {
openPopupMenu(player.getPlayQueue(), item, view, true,
parentActivity.getSupportFragmentManager(), context);
Expand Down Expand Up @@ -805,10 +819,15 @@ public void onClick(final View v) {

@Override
protected void onPlaybackSpeedClicked() {
final AppCompatActivity activity = getParentActivity().orElse(null);
if (activity == null) {
return;
}

PlaybackParameterDialog.newInstance(player.getPlaybackSpeed(), player.getPlaybackPitch(),
player.getPlaybackSkipSilence(), (speed, pitch, skipSilence)
-> player.setPlaybackParameters(speed, pitch, skipSilence))
.show(getParentActivity().getSupportFragmentManager(), null);
.show(activity.getSupportFragmentManager(), null);
}

@Override
Expand Down Expand Up @@ -880,15 +899,15 @@ public void toggleFullscreen() {
}

isFullscreen = !isFullscreen;
if (!isFullscreen) {
// Apply window insets because Android will not do it when orientation changes
// from landscape to portrait (open vertical video to reproduce)
binding.playbackControlRoot.setPadding(0, 0, 0, 0);
} else {
if (isFullscreen) {
// Android needs tens milliseconds to send new insets but a user is able to see
// how controls changes it's position from `0` to `nav bar height` padding.
// So just hide the controls to hide this visual inconsistency
hideControls(0, 0);
} else {
// Apply window insets because Android will not do it when orientation changes
// from landscape to portrait (open vertical video to reproduce)
binding.playbackControlRoot.setPadding(0, 0, 0, 0);
}
fragmentListener.onFullscreenStateChanged(isFullscreen);

Expand Down Expand Up @@ -928,14 +947,22 @@ public PlayerBinding getBinding() {
return binding;
}

public AppCompatActivity getParentActivity() {
return (AppCompatActivity) ((ViewGroup) binding.getRoot().getParent()).getContext();
public Optional<AppCompatActivity> getParentActivity() {
final ViewParent rootParent = binding.getRoot().getParent();
if (rootParent instanceof ViewGroup) {
final Context activity = ((ViewGroup) rootParent).getContext();
if (activity instanceof AppCompatActivity) {
return Optional.of((AppCompatActivity) activity);
}
}
return Optional.empty();
}

public boolean isLandscape() {
// DisplayMetrics from activity context knows about MultiWindow feature
// while DisplayMetrics from app context doesn't
return DeviceUtils.isLandscape(getParentActivity());
return DeviceUtils.isLandscape(
getParentActivity().map(Context.class::cast).orElse(player.getService()));
}
//endregion
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public void onBroadcastReceived(final Intent intent) {
if (Intent.ACTION_CONFIGURATION_CHANGED.equals(intent.getAction())) {
assureCorrectAppLanguage(player.getService());
if (DEBUG) {
Log.d(TAG, "onConfigurationChanged() called");
Log.d(TAG, "ACTION_CONFIGURATION_CHANGED received");
}
}
}
Expand Down
Loading

0 comments on commit 30b9e0f

Please sign in to comment.