1
0
mirror of https://github.com/TeamNewPipe/NewPipe synced 2024-06-30 00:53:19 +00:00

fix: small codestyle fixes

This commit is contained in:
ThetaDev 2023-04-21 23:15:37 +02:00
parent 2edc223e77
commit b567d428ad
7 changed files with 80 additions and 52 deletions

View File

@ -103,7 +103,7 @@ public class DownloadDialog extends DialogFragment
@State @State
AudioTracksWrapper wrappedAudioTracks; AudioTracksWrapper wrappedAudioTracks;
@State @State
int selectedAudioStreamIndex; int selectedAudioTrackIndex;
@State @State
int selectedVideoIndex; // set in the constructor int selectedVideoIndex; // set in the constructor
@State @State
@ -173,7 +173,7 @@ public class DownloadDialog extends DialogFragment
final List<List<AudioStream>> groupedAudioStreams = final List<List<AudioStream>> groupedAudioStreams =
ListHelper.getGroupedAudioStreams(context, audioStreams); ListHelper.getGroupedAudioStreams(context, audioStreams);
this.wrappedAudioTracks = new AudioTracksWrapper(groupedAudioStreams, context); this.wrappedAudioTracks = new AudioTracksWrapper(groupedAudioStreams, context);
this.selectedAudioStreamIndex = this.selectedAudioTrackIndex =
ListHelper.getDefaultAudioTrackGroup(context, groupedAudioStreams); ListHelper.getDefaultAudioTrackGroup(context, groupedAudioStreams);
// TODO: Adapt this code when the downloader support other types of stream deliveries // TODO: Adapt this code when the downloader support other types of stream deliveries
@ -433,7 +433,7 @@ public class DownloadDialog extends DialogFragment
} }
dialogBinding.audioTrackSpinner.setAdapter(audioTrackAdapter); dialogBinding.audioTrackSpinner.setAdapter(audioTrackAdapter);
dialogBinding.audioTrackSpinner.setSelection(selectedAudioStreamIndex); dialogBinding.audioTrackSpinner.setSelection(selectedAudioTrackIndex);
} }
private void setupAudioSpinner() { private void setupAudioSpinner() {
@ -619,8 +619,8 @@ public class DownloadDialog extends DialogFragment
onItemSelectedSetFileName(); onItemSelectedSetFileName();
break; break;
case R.id.audio_track_spinner: case R.id.audio_track_spinner:
final boolean trackChanged = selectedAudioStreamIndex != position; final boolean trackChanged = selectedAudioTrackIndex != position;
selectedAudioStreamIndex = position; selectedAudioTrackIndex = position;
if (trackChanged) { if (trackChanged) {
updateSecondaryStreams(); updateSecondaryStreams();
fetchStreamsSize(); fetchStreamsSize();
@ -726,10 +726,10 @@ public class DownloadDialog extends DialogFragment
} }
private StreamSizeWrapper<AudioStream> getWrappedAudioStreams() { private StreamSizeWrapper<AudioStream> getWrappedAudioStreams() {
if (selectedAudioStreamIndex < 0 || selectedAudioStreamIndex > wrappedAudioTracks.size()) { if (selectedAudioTrackIndex < 0 || selectedAudioTrackIndex > wrappedAudioTracks.size()) {
return StreamSizeWrapper.empty(); return StreamSizeWrapper.empty();
} }
return wrappedAudioTracks.getTracksList().get(selectedAudioStreamIndex); return wrappedAudioTracks.getTracksList().get(selectedAudioTrackIndex);
} }
private int getSubtitleIndexBy(@NonNull final List<SubtitlesStream> streams) { private int getSubtitleIndexBy(@NonNull final List<SubtitlesStream> streams) {

View File

@ -667,11 +667,8 @@ public final class PlayQueueActivity extends AppCompatActivity
return; return;
} }
player.saveStreamProgressState();
final String newAudioTrack = availableStreams.get(itemId).getAudioTrackId(); final String newAudioTrack = availableStreams.get(itemId).getAudioTrackId();
player.setRecovery();
player.setAudioTrack(newAudioTrack); player.setAudioTrack(newAudioTrack);
player.reloadPlayQueueManager();
}); });
} }
} }

View File

@ -180,13 +180,18 @@ public final class Player implements PlaybackListener, Listener {
//////////////////////////////////////////////////////////////////////////*/ //////////////////////////////////////////////////////////////////////////*/
// play queue might be null e.g. while player is starting // play queue might be null e.g. while player is starting
@Nullable private PlayQueue playQueue; @Nullable
private PlayQueue playQueue;
@Nullable private MediaSourceManager playQueueManager; @Nullable
private MediaSourceManager playQueueManager;
@Nullable private PlayQueueItem currentItem; @Nullable
@Nullable private MediaItemTag currentMetadata; private PlayQueueItem currentItem;
@Nullable private Bitmap currentThumbnail; @Nullable
private MediaItemTag currentMetadata;
@Nullable
private Bitmap currentThumbnail;
/*////////////////////////////////////////////////////////////////////////// /*//////////////////////////////////////////////////////////////////////////
// Player // Player
@ -195,12 +200,17 @@ public final class Player implements PlaybackListener, Listener {
private ExoPlayer simpleExoPlayer; private ExoPlayer simpleExoPlayer;
private AudioReactor audioReactor; private AudioReactor audioReactor;
@NonNull private final DefaultTrackSelector trackSelector; @NonNull
@NonNull private final LoadController loadController; private final DefaultTrackSelector trackSelector;
@NonNull private final DefaultRenderersFactory renderFactory; @NonNull
private final LoadController loadController;
@NonNull
private final DefaultRenderersFactory renderFactory;
@NonNull private final VideoPlaybackResolver videoResolver; @NonNull
@NonNull private final AudioPlaybackResolver audioResolver; private final VideoPlaybackResolver videoResolver;
@NonNull
private final AudioPlaybackResolver audioResolver;
private final PlayerService service; //TODO try to remove and replace everything with context private final PlayerService service; //TODO try to remove and replace everything with context
@ -225,24 +235,32 @@ public final class Player implements PlaybackListener, Listener {
private BroadcastReceiver broadcastReceiver; private BroadcastReceiver broadcastReceiver;
private IntentFilter intentFilter; private IntentFilter intentFilter;
@Nullable private PlayerServiceEventListener fragmentListener = null; @Nullable
@Nullable private PlayerEventListener activityListener = null; private PlayerServiceEventListener fragmentListener = null;
@Nullable
private PlayerEventListener activityListener = null;
@NonNull private final SerialDisposable progressUpdateDisposable = new SerialDisposable(); @NonNull
@NonNull private final CompositeDisposable databaseUpdateDisposable = new CompositeDisposable(); private final SerialDisposable progressUpdateDisposable = new SerialDisposable();
@NonNull
private final CompositeDisposable databaseUpdateDisposable = new CompositeDisposable();
// This is the only listener we need for thumbnail loading, since there is always at most only // This is the only listener we need for thumbnail loading, since there is always at most only
// one thumbnail being loaded at a time. This field is also here to maintain a strong reference, // one thumbnail being loaded at a time. This field is also here to maintain a strong reference,
// which would otherwise be garbage collected since Picasso holds weak references to targets. // which would otherwise be garbage collected since Picasso holds weak references to targets.
@NonNull private final Target currentThumbnailTarget; @NonNull
private final Target currentThumbnailTarget;
/*////////////////////////////////////////////////////////////////////////// /*//////////////////////////////////////////////////////////////////////////
// Utils // Utils
//////////////////////////////////////////////////////////////////////////*/ //////////////////////////////////////////////////////////////////////////*/
@NonNull private final Context context; @NonNull
@NonNull private final SharedPreferences prefs; private final Context context;
@NonNull private final HistoryRecordManager recordManager; @NonNull
private final SharedPreferences prefs;
@NonNull
private final HistoryRecordManager recordManager;
/*////////////////////////////////////////////////////////////////////////// /*//////////////////////////////////////////////////////////////////////////
@ -334,7 +352,7 @@ public final class Player implements PlaybackListener, Listener {
isAudioOnly = audioPlayerSelected(); isAudioOnly = audioPlayerSelected();
if (intent.hasExtra(PLAYBACK_QUALITY)) { if (intent.hasExtra(PLAYBACK_QUALITY)) {
setPlaybackQuality(intent.getStringExtra(PLAYBACK_QUALITY)); videoResolver.setPlaybackQuality(intent.getStringExtra(PLAYBACK_QUALITY));
} }
// Resolve enqueue intents // Resolve enqueue intents
@ -342,7 +360,7 @@ public final class Player implements PlaybackListener, Listener {
playQueue.append(newQueue.getStreams()); playQueue.append(newQueue.getStreams());
return; return;
// Resolve enqueue next intents // Resolve enqueue next intents
} else if (intent.getBooleanExtra(ENQUEUE_NEXT, false) && playQueue != null) { } else if (intent.getBooleanExtra(ENQUEUE_NEXT, false) && playQueue != null) {
final int currentIndex = playQueue.getIndex(); final int currentIndex = playQueue.getIndex();
playQueue.append(newQueue.getStreams()); playQueue.append(newQueue.getStreams());
@ -914,7 +932,7 @@ public final class Player implements PlaybackListener, Listener {
private Disposable getProgressUpdateDisposable() { private Disposable getProgressUpdateDisposable() {
return Observable.interval(PROGRESS_LOOP_INTERVAL_MILLIS, MILLISECONDS, return Observable.interval(PROGRESS_LOOP_INTERVAL_MILLIS, MILLISECONDS,
AndroidSchedulers.mainThread()) AndroidSchedulers.mainThread())
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe(ignored -> triggerProgressUpdate(), .subscribe(ignored -> triggerProgressUpdate(),
error -> Log.e(TAG, "Progress update failure: ", error)); error -> Log.e(TAG, "Progress update failure: ", error));
@ -923,7 +941,6 @@ public final class Player implements PlaybackListener, Listener {
//endregion //endregion
/*////////////////////////////////////////////////////////////////////////// /*//////////////////////////////////////////////////////////////////////////
// Playback states // Playback states
//////////////////////////////////////////////////////////////////////////*/ //////////////////////////////////////////////////////////////////////////*/
@ -1247,7 +1264,7 @@ public final class Player implements PlaybackListener, Listener {
.flatMap(MediaItemTag::getMaybeStreamInfo).orElse(null); .flatMap(MediaItemTag::getMaybeStreamInfo).orElse(null);
final MediaItemTag.AudioTrack previousAudioTrack = final MediaItemTag.AudioTrack previousAudioTrack =
Optional.ofNullable(currentMetadata) Optional.ofNullable(currentMetadata)
.flatMap(MediaItemTag::getMaybeAudioTrack).orElse(null); .flatMap(MediaItemTag::getMaybeAudioTrack).orElse(null);
currentMetadata = tag; currentMetadata = tag;
if (!currentMetadata.getErrors().isEmpty()) { if (!currentMetadata.getErrors().isEmpty()) {
@ -1270,9 +1287,9 @@ public final class Player implements PlaybackListener, Listener {
updateMetadataWith(info); updateMetadataWith(info);
} else if (previousAudioTrack == null } else if (previousAudioTrack == null
|| tag.getMaybeAudioTrack() || tag.getMaybeAudioTrack()
.map(t -> t.getSelectedAudioStreamIndex() .map(t -> t.getSelectedAudioStreamIndex()
!= previousAudioTrack.getSelectedAudioStreamIndex()) != previousAudioTrack.getSelectedAudioStreamIndex())
.orElse(false)) { .orElse(false)) {
notifyAudioTrackUpdateToListeners(); notifyAudioTrackUpdateToListeners();
} }
}); });
@ -1361,6 +1378,7 @@ public final class Player implements PlaybackListener, Listener {
// Errors // Errors
//////////////////////////////////////////////////////////////////////////*/ //////////////////////////////////////////////////////////////////////////*/
//region Errors //region Errors
/** /**
* Process exceptions produced by {@link com.google.android.exoplayer2.ExoPlayer ExoPlayer}. * Process exceptions produced by {@link com.google.android.exoplayer2.ExoPlayer ExoPlayer}.
* <p>There are multiple types of errors:</p> * <p>There are multiple types of errors:</p>
@ -1387,8 +1405,9 @@ public final class Player implements PlaybackListener, Listener {
* For any error above that is <b>not</b> explicitly <b>catchable</b>, the player will * For any error above that is <b>not</b> explicitly <b>catchable</b>, the player will
* create a notification so users are aware. * create a notification so users are aware.
* </ul> * </ul>
*
* @see com.google.android.exoplayer2.Player.Listener#onPlayerError(PlaybackException) * @see com.google.android.exoplayer2.Player.Listener#onPlayerError(PlaybackException)
* */ */
// Any error code not explicitly covered here are either unrelated to NewPipe use case // Any error code not explicitly covered here are either unrelated to NewPipe use case
// (e.g. DRM) or not recoverable (e.g. Decoder error). In both cases, the player should // (e.g. DRM) or not recoverable (e.g. Decoder error). In both cases, the player should
// shutdown. // shutdown.
@ -2141,7 +2160,7 @@ public final class Player implements PlaybackListener, Listener {
// because the stream source will be probably the same as the current played // because the stream source will be probably the same as the current played
if (sourceType == SourceType.VIDEO_WITH_SEPARATED_AUDIO if (sourceType == SourceType.VIDEO_WITH_SEPARATED_AUDIO
|| (sourceType == SourceType.VIDEO_WITH_AUDIO_OR_AUDIO_ONLY || (sourceType == SourceType.VIDEO_WITH_AUDIO_OR_AUDIO_ONLY
&& isNullOrEmpty(streamInfo.getAudioStreams()))) { && isNullOrEmpty(streamInfo.getAudioStreams()))) {
// It's not needed to reload the play queue manager only if the content's stream type // It's not needed to reload the play queue manager only if the content's stream type
// is a video stream, a live stream or an ended live stream // is a video stream, a live stream or an ended live stream
return !StreamTypeUtil.isVideo(streamType); return !StreamTypeUtil.isVideo(streamType);
@ -2203,12 +2222,18 @@ public final class Player implements PlaybackListener, Listener {
} }
public void setPlaybackQuality(@Nullable final String quality) { public void setPlaybackQuality(@Nullable final String quality) {
saveStreamProgressState();
setRecovery();
videoResolver.setPlaybackQuality(quality); videoResolver.setPlaybackQuality(quality);
reloadPlayQueueManager();
} }
public void setAudioTrack(@Nullable final String audioTrackId) { public void setAudioTrack(@Nullable final String audioTrackId) {
saveStreamProgressState();
setRecovery();
videoResolver.setAudioTrack(audioTrackId); videoResolver.setAudioTrack(audioTrackId);
audioResolver.setAudioTrack(audioTrackId); audioResolver.setAudioTrack(audioTrackId);
reloadPlayQueueManager();
} }
@ -2286,7 +2311,7 @@ public final class Player implements PlaybackListener, Listener {
/** /**
* Get the video renderer index of the current playing stream. * Get the video renderer index of the current playing stream.
* * <p>
* This method returns the video renderer index of the current * This method returns the video renderer index of the current
* {@link MappingTrackSelector.MappedTrackInfo} or {@link #RENDERER_UNAVAILABLE} if the current * {@link MappingTrackSelector.MappedTrackInfo} or {@link #RENDERER_UNAVAILABLE} if the current
* {@link MappingTrackSelector.MappedTrackInfo} is null or if there is no video renderer index. * {@link MappingTrackSelector.MappedTrackInfo} is null or if there is no video renderer index.

View File

@ -38,6 +38,13 @@ public class AudioPlaybackResolver implements PlaybackResolver {
this.dataSource = dataSource; this.dataSource = dataSource;
} }
/**
* Get a media source providing audio. If a service has no separate {@link AudioStream}s we
* use a video stream as audio source to support audio background playback.
*
* @param info of the stream
* @return the audio source to use or null if none could be found
*/
@Override @Override
@Nullable @Nullable
public MediaSource resolve(@NonNull final StreamInfo info) { public MediaSource resolve(@NonNull final StreamInfo info) {

View File

@ -110,7 +110,8 @@ public abstract class VideoPlayerUi extends PlayerUi implements SeekBar.OnSeekBa
protected PlayerBinding binding; protected PlayerBinding binding;
private final Handler controlsVisibilityHandler = new Handler(Looper.getMainLooper()); private final Handler controlsVisibilityHandler = new Handler(Looper.getMainLooper());
@Nullable private SurfaceHolderCallback surfaceHolderCallback; @Nullable
private SurfaceHolderCallback surfaceHolderCallback;
boolean surfaceIsSetup = false; boolean surfaceIsSetup = false;
@ -533,6 +534,7 @@ public abstract class VideoPlayerUi extends PlayerUi implements SeekBar.OnSeekBa
/** /**
* Sets the current duration into the corresponding elements. * Sets the current duration into the corresponding elements.
*
* @param currentProgress the current progress, in milliseconds * @param currentProgress the current progress, in milliseconds
*/ */
private void updatePlayBackElementsCurrentDuration(final int currentProgress) { private void updatePlayBackElementsCurrentDuration(final int currentProgress) {
@ -545,6 +547,7 @@ public abstract class VideoPlayerUi extends PlayerUi implements SeekBar.OnSeekBa
/** /**
* Sets the video duration time into all control components (e.g. seekbar). * Sets the video duration time into all control components (e.g. seekbar).
*
* @param duration the video duration, in milliseconds * @param duration the video duration, in milliseconds
*/ */
private void setVideoDurationToControls(final int duration) { private void setVideoDurationToControls(final int duration) {
@ -1261,11 +1264,8 @@ public abstract class VideoPlayerUi extends PlayerUi implements SeekBar.OnSeekBa
return; return;
} }
player.saveStreamProgressState();
final String newResolution = availableStreams.get(menuItemIndex).getResolution(); final String newResolution = availableStreams.get(menuItemIndex).getResolution();
player.setRecovery();
player.setPlaybackQuality(newResolution); player.setPlaybackQuality(newResolution);
player.reloadPlayQueueManager();
binding.qualityTextView.setText(menuItem.getTitle()); binding.qualityTextView.setText(menuItem.getTitle());
} }
@ -1285,11 +1285,8 @@ public abstract class VideoPlayerUi extends PlayerUi implements SeekBar.OnSeekBa
return; return;
} }
player.saveStreamProgressState();
final String newAudioTrack = availableStreams.get(menuItemIndex).getAudioTrackId(); final String newAudioTrack = availableStreams.get(menuItemIndex).getAudioTrackId();
player.setRecovery();
player.setAudioTrack(newAudioTrack); player.setAudioTrack(newAudioTrack);
player.reloadPlayQueueManager();
binding.audioTrackTextView.setText(menuItem.getTitle()); binding.audioTrackTextView.setText(menuItem.getTitle());
} }

View File

@ -715,9 +715,9 @@ public final class ListHelper {
/** /**
* Get a {@link Comparator} to compare {@link AudioStream}s by their tracks. * Get a {@link Comparator} to compare {@link AudioStream}s by their tracks.
* *
* <p>In this order:</p> * <p>Tracks will be compared this order:</p>
* <ol> * <ol>
* <li>If {@code preferOriginalAudio}: is original audio</li> * <li>If {@code preferOriginalAudio}: use original audio</li>
* <li>Language matches {@code preferredLanguage}</li> * <li>Language matches {@code preferredLanguage}</li>
* <li> * <li>
* Track type ranks highest in this order: * Track type ranks highest in this order:
@ -752,9 +752,9 @@ public final class ListHelper {
/** /**
* Get a {@link Comparator} to compare {@link AudioStream}s by their tracks. * Get a {@link Comparator} to compare {@link AudioStream}s by their tracks.
* *
* <p>In this order:</p> * <p>Tracks will be compared this order:</p>
* <ol> * <ol>
* <li>If {@code preferOriginalAudio}: is original audio</li> * <li>If {@code preferOriginalAudio}: use original audio</li>
* <li>Language matches {@code preferredLanguage}</li> * <li>Language matches {@code preferredLanguage}</li>
* <li> * <li>
* Track type ranks highest in this order: * Track type ranks highest in this order:

View File

@ -224,6 +224,8 @@ public class StreamItemAdapter<T extends Stream, U extends Stream> extends BaseA
public static class StreamSizeWrapper<T extends Stream> implements Serializable { public static class StreamSizeWrapper<T extends Stream> implements Serializable {
private static final StreamSizeWrapper<Stream> EMPTY = private static final StreamSizeWrapper<Stream> EMPTY =
new StreamSizeWrapper<>(Collections.emptyList(), null); new StreamSizeWrapper<>(Collections.emptyList(), null);
private static final int SIZE_UNSET = -2;
private final List<T> streamsList; private final List<T> streamsList;
private final long[] streamSizes; private final long[] streamSizes;
private final String unknownSize; private final String unknownSize;
@ -251,7 +253,7 @@ public class StreamItemAdapter<T extends Stream, U extends Stream> extends BaseA
final Callable<Boolean> fetchAndSet = () -> { final Callable<Boolean> fetchAndSet = () -> {
boolean hasChanged = false; boolean hasChanged = false;
for (final X stream : streamsWrapper.getStreamsList()) { for (final X stream : streamsWrapper.getStreamsList()) {
if (streamsWrapper.getSizeInBytes(stream) > -2) { if (streamsWrapper.getSizeInBytes(stream) > SIZE_UNSET) {
continue; continue;
} }
@ -270,7 +272,7 @@ public class StreamItemAdapter<T extends Stream, U extends Stream> extends BaseA
} }
public void resetSizes() { public void resetSizes() {
Arrays.fill(streamSizes, -2); Arrays.fill(streamSizes, SIZE_UNSET);
} }
public static <X extends Stream> StreamSizeWrapper<X> empty() { public static <X extends Stream> StreamSizeWrapper<X> empty() {