xyz.gianlu.librespot.player.Player Maven / Gradle / Ivy
The newest version!
/*
* Copyright 2022 devgianlu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.gianlu.librespot.player;
import com.google.gson.JsonObject;
import com.google.protobuf.InvalidProtocolBufferException;
import com.spotify.context.ContextTrackOuterClass.ContextTrack;
import com.spotify.metadata.Metadata;
import com.spotify.transfer.TransferStateOuterClass;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Range;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.gianlu.librespot.audio.AbsChunkedInputStream;
import xyz.gianlu.librespot.audio.MetadataWrapper;
import xyz.gianlu.librespot.audio.PlayableContentFeeder;
import xyz.gianlu.librespot.common.NameThreadFactory;
import xyz.gianlu.librespot.core.Session;
import xyz.gianlu.librespot.dacp.DacpMetadataPipe;
import xyz.gianlu.librespot.json.StationsWrapper;
import xyz.gianlu.librespot.mercury.MercuryClient;
import xyz.gianlu.librespot.mercury.MercuryRequests;
import xyz.gianlu.librespot.metadata.ImageId;
import xyz.gianlu.librespot.metadata.PlayableId;
import xyz.gianlu.librespot.player.StateWrapper.NextPlayable;
import xyz.gianlu.librespot.player.contexts.AbsSpotifyContext;
import xyz.gianlu.librespot.player.decoders.Decoder;
import xyz.gianlu.librespot.player.metrics.NewPlaybackIdEvent;
import xyz.gianlu.librespot.player.metrics.NewSessionIdEvent;
import xyz.gianlu.librespot.player.metrics.PlaybackMetrics;
import xyz.gianlu.librespot.player.metrics.PlayerMetrics;
import xyz.gianlu.librespot.player.mixing.AudioSink;
import xyz.gianlu.librespot.player.playback.PlayerSession;
import xyz.gianlu.librespot.player.state.DeviceStateHandler;
import xyz.gianlu.librespot.player.state.DeviceStateHandler.PlayCommandHelper;
import java.io.Closeable;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
/**
* @author Gianlu
*/
public class Player implements Closeable {
public static final int VOLUME_MAX = 65536;
private static final Logger LOGGER = LoggerFactory.getLogger(Player.class);
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new NameThreadFactory((r) -> "release-line-scheduler-" + r.hashCode()));
private final Session session;
private final PlayerConfiguration conf;
private final EventsDispatcher events;
private final AudioSink sink;
private final Map metrics = new HashMap<>(5);
private StateWrapper state;
private PlayerSession playerSession;
private ScheduledFuture> releaseLineFuture = null;
private DeviceStateHandler.Listener deviceStateListener;
public Player(@NotNull PlayerConfiguration conf, @NotNull Session session) {
this.conf = conf;
this.session = session;
this.events = new EventsDispatcher(conf);
this.sink = new AudioSink(conf, ex -> {
LOGGER.error("Sink error!", ex);
panicState(PlaybackMetrics.Reason.TRACK_ERROR);
});
initState();
}
public void addEventsListener(@NotNull EventsListener listener) {
events.listeners.add(listener);
}
public void removeEventsListener(@NotNull EventsListener listener) {
events.listeners.remove(listener);
}
private void initState() {
this.state = new StateWrapper(session, this, conf);
state.addListener(deviceStateListener = new DeviceStateHandler.Listener() {
@Override
public void ready() {
events.volumeChanged(state.getVolume());
}
@Override
public void command(DeviceStateHandler.@NotNull Endpoint endpoint, @NotNull DeviceStateHandler.CommandBody data) throws InvalidProtocolBufferException {
LOGGER.debug("Received command: " + endpoint);
switch (endpoint) {
case Play:
handlePlay(data.obj());
break;
case Transfer:
handleTransferState(TransferStateOuterClass.TransferState.parseFrom(data.data()));
break;
case Resume:
handleResume();
break;
case Pause:
handlePause();
break;
case SeekTo:
handleSeek(data.valueInt());
break;
case SkipNext:
handleSkipNext(data.obj(), TransitionInfo.skippedNext(state));
break;
case SkipPrev:
handleSkipPrev();
break;
case SetRepeatingContext:
state.setRepeatingContext(data.valueBool());
state.updated();
break;
case SetRepeatingTrack:
state.setRepeatingTrack(data.valueBool());
state.updated();
break;
case SetShufflingContext:
state.setShufflingContext(data.valueBool());
state.updated();
break;
case AddToQueue:
handleAddToQueue(data.obj());
break;
case SetQueue:
handleSetQueue(data.obj());
break;
case UpdateContext:
state.updateContext(PlayCommandHelper.getContext(data.obj()));
state.updated();
break;
default:
LOGGER.warn("Endpoint left unhandled: " + endpoint);
break;
}
}
@Override
public void volumeChanged() {
int vol = state.getVolume();
if (!conf.bypassSinkVolume) sink.setVolume(vol);
events.volumeChanged(vol);
}
@Override
public void notActive() {
events.inactiveSession(false);
sink.pause(true);
}
});
}
// ================================ //
// =========== Commands =========== //
// ================================ //
public void volumeUp() {
this.volumeUp(1);
}
public void volumeUp(int steps) {
if (state == null) return;
setVolume(Math.min(Player.VOLUME_MAX, state.getVolume() + steps * oneVolumeStep()));
}
public void volumeDown() {
this.volumeDown(1);
}
public void volumeDown(int steps) {
if (state == null) return;
setVolume(Math.max(0, state.getVolume() - steps * oneVolumeStep()));
}
private int oneVolumeStep() {
return Player.VOLUME_MAX / conf.volumeSteps;
}
public void setVolume(int val) {
if (val < 0 || val > VOLUME_MAX)
throw new IllegalArgumentException(String.valueOf(val));
if (state == null) return;
state.setVolume(val);
}
public void setShuffle(boolean val) {
state.setShufflingContext(val);
state.updated();
}
public void setRepeat(boolean track, boolean context) {
if (track && context)
throw new IllegalArgumentException("Cannot repeat track and context simultaneously.");
if (track) {
state.setRepeatingTrack(true);
} else if (context) {
state.setRepeatingContext(true);
} else {
state.setRepeatingContext(false);
state.setRepeatingTrack(false);
}
state.updated();
}
public void play() {
handleResume();
}
public void playPause() {
if (state.isPaused()) handleResume();
else handlePause();
}
public void pause() {
handlePause();
}
public void next() {
handleSkipNext(null, TransitionInfo.skippedNext(state));
}
public void previous() {
handleSkipPrev();
}
public void seek(int pos) {
handleSeek(pos);
}
public void load(@NotNull String uri, boolean play, boolean shuffle) {
try {
String sessionId = state.loadContext(uri);
events.contextChanged();
state.setShufflingContext(shuffle);
loadSession(sessionId, play, true);
} catch (IOException | MercuryClient.MercuryException ex) {
LOGGER.error("Failed loading context!", ex);
panicState(null);
} catch (AbsSpotifyContext.UnsupportedContextException ex) {
LOGGER.error("Cannot play context!", ex);
panicState(null);
}
}
public void addToQueue(@NotNull String uri) {
state.addToQueue(ContextTrack.newBuilder().setUri(uri).build());
state.updated();
}
public void removeFromQueue(@NotNull String uri) {
state.removeFromQueue(uri);
state.updated();
}
@NotNull
public Future ready() {
CompletableFuture future = new CompletableFuture<>();
if (isReady()) {
future.complete(this);
return future;
}
state.addListener(new DeviceStateHandler.Listener() {
@Override
public void ready() {
state.removeListener(this);
future.complete(Player.this);
}
@Override
public void command(@NotNull DeviceStateHandler.Endpoint endpoint, @NotNull DeviceStateHandler.CommandBody data) {
}
@Override
public void volumeChanged() {
}
@Override
public void notActive() {
}
});
return future;
}
public void waitReady() throws InterruptedException {
try {
ready().get();
} catch (ExecutionException ignored) {
}
}
// ================================ //
// ======== Internal state ======== //
// ================================ //
/**
* Enter a "panic" state where everything is stopped.
*
* @param reason Why we entered this state
*/
private void panicState(@Nullable PlaybackMetrics.Reason reason) {
sink.pause(true);
state.setState(false, false, false);
state.updated();
if (reason == null) {
metrics.clear();
} else if (playerSession != null) {
endMetrics(playerSession.currentPlaybackId(), reason, playerSession.currentMetrics(), state.getPosition());
}
events.panicState();
}
/**
* Loads a new session by creating a new {@link PlayerSession}. Will also trigger {@link Player#loadTrack(boolean, TransitionInfo)}.
*
* @param sessionId The new session ID
* @param play Whether the playback should start immediately
*/
private void loadSession(@NotNull String sessionId, boolean play, boolean withSkip) {
LOGGER.debug("Loading session, id: {}, play: {}", sessionId, play);
TransitionInfo trans = TransitionInfo.contextChange(state, withSkip);
if (playerSession != null) {
endMetrics(playerSession.currentPlaybackId(), trans.endedReason, playerSession.currentMetrics(), trans.endedWhen);
playerSession.close();
playerSession = null;
}
playerSession = new PlayerSession(session, sink, conf, sessionId, new PlayerSession.Listener() {
@Override
public void startedLoading() {
if (!state.isPaused()) {
state.setBuffering(true);
state.updated();
}
events.startedLoading();
}
@Override
public void finishedLoading(@NotNull MetadataWrapper metadata) {
state.enrichWithMetadata(metadata);
state.setBuffering(false);
state.updated();
events.finishedLoading();
events.metadataAvailable();
}
@Override
public void loadingError(@NotNull Exception ex) {
events.playbackFailed(ex);
if (ex instanceof PlayableContentFeeder.ContentRestrictedException) {
LOGGER.error("Can't load track (content restricted).", ex);
} else {
LOGGER.error("Failed loading track.", ex);
panicState(PlaybackMetrics.Reason.TRACK_ERROR);
}
}
@Override
public void playbackError(@NotNull Exception ex) {
if (ex instanceof AbsChunkedInputStream.ChunkException)
LOGGER.error("Failed retrieving chunk, playback failed!", ex);
else
LOGGER.error("Playback error!", ex);
panicState(PlaybackMetrics.Reason.TRACK_ERROR);
}
@Override
public void trackChanged(@NotNull String playbackId, @Nullable MetadataWrapper metadata, int pos, @NotNull PlaybackMetrics.Reason startedReason) {
if (metadata != null) state.enrichWithMetadata(metadata);
state.setPlaybackId(playbackId);
state.setPosition(pos);
state.updated();
events.trackChanged(false);
events.metadataAvailable();
session.eventService().sendEvent(new NewPlaybackIdEvent(state.getSessionId(), playbackId));
startMetrics(playbackId, startedReason, pos);
}
@Override
public void trackPlayed(@NotNull String playbackId, @NotNull PlaybackMetrics.Reason endReason, @NotNull PlayerMetrics playerMetrics, int when) {
endMetrics(playbackId, endReason, playerMetrics, when);
events.playbackEnded();
}
@Override
public void playbackHalted(int chunk) {
LOGGER.debug("Playback halted on retrieving chunk {}.", chunk);
state.setBuffering(true);
state.updated();
events.playbackHaltStateChanged(true);
}
@Override
public void playbackResumedFromHalt(int chunk, long diff) {
LOGGER.debug("Playback resumed, chunk {} retrieved, took {}ms.", chunk, diff);
state.setPosition(state.getPosition() - diff);
state.setBuffering(false);
state.updated();
events.playbackHaltStateChanged(false);
}
@Override
public @NotNull PlayableId currentPlayable() {
return state.getCurrentPlayableOrThrow();
}
@Override
public @Nullable PlayableId nextPlayable() {
NextPlayable next = state.nextPlayable(conf.autoplayEnabled);
if (next == NextPlayable.AUTOPLAY) {
loadAutoplay();
return null;
}
if (next.isOk()) {
if (next != NextPlayable.OK_PLAY && next != NextPlayable.OK_REPEAT)
sink.pause(false);
return state.getCurrentPlayableOrThrow();
} else {
LOGGER.error("Failed loading next song: " + next);
panicState(PlaybackMetrics.Reason.END_PLAY);
return null;
}
}
@Override
public @Nullable PlayableId nextPlayableDoNotSet() {
return state.nextPlayableDoNotSet();
}
@Override
public @NotNull Optional
© 2015 - 2025 Weber Informatics LLC | Privacy Policy