Mulberry/android/src/com/mulberry/player/MusicService.java
astar76 c0dc2c68c3 Android 2.0.5: ListenBrainz and a scrobble queue that can't get stuck
- Connect ListenBrainz with a user token (checked), disconnect, send now
- Listens carry MusicBrainz ids, ISRC, disc, tags, release artist read from the file
- Last.fm: dead sessions sign out and keep the queue; rejected data is dropped;
  >14-day-old scrobbles dropped; recording MBID sent
- Each service flushes on its own

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-03 08:33:13 -06:00

1954 lines
74 KiB
Java

package com.mulberry.player;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.Icon;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.media.MediaDescription;
import android.media.MediaMetadata;
import android.media.MediaPlayer;
import android.media.browse.MediaBrowser;
import android.media.session.MediaSession;
import android.media.session.PlaybackState;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.SystemClock;
import android.service.media.MediaBrowserService;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import org.jaudiotagger.audio.flac.FlacTagCreator;
import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM;
import org.json.JSONArray;
import org.json.JSONObject;
/* JADX INFO: loaded from: classes.dex */
public class MusicService extends MediaBrowserService implements AudioManager.OnAudioFocusChangeListener {
public static final String ACT_FAV = "com.mulberry.player.FAV";
public static final String ACT_NEXT = "com.mulberry.player.NEXT";
public static final String ACT_PAUSE = "com.mulberry.player.PAUSE";
public static final String ACT_PLAY = "com.mulberry.player.PLAY";
public static final String ACT_PREV = "com.mulberry.player.PREV";
public static final String ACT_REFRESH = "com.mulberry.player.REFRESH";
public static final String ACT_REPEAT = "com.mulberry.player.REPEAT";
public static final String ACT_SHUFFLE = "com.mulberry.player.SHUFFLE";
public static final String ACT_STOP = "com.mulberry.player.STOP";
public static final String ACT_TOGGLE = "com.mulberry.player.TOGGLE";
public static final String EXTRA_FG = "fg";
public static MusicService INSTANCE = null;
static final int NOTIF_ID = 7;
private AudioManager am;
private Bitmap art;
private int artToken;
private boolean countedPlay;
private MediaPlayer cur;
private boolean curPrepared;
private int errorStreak;
private int fadeToken;
private MediaPlayer fadingOut;
private boolean focusLossTransient;
private AudioFocusRequest focusReq;
private boolean foreground;
private boolean held;
private boolean heldPlaying;
private long heldPos;
private long lastSavedPos;
private long lastTick;
private long listenedMs;
public Lyrics.Result lyrics;
private boolean noisyRegistered;
private boolean notifShown;
private MediaPlayer nxt;
private boolean nxtLinked;
private boolean nxtPrepared;
private boolean playWhenLibrary;
private boolean playWhenReady;
private PowerManager pm;
volatile long pubPos;
private int repeat;
private long sampleAt;
private boolean samplePlaying;
private long samplePos;
private int saveCounter;
private boolean scrobbled;
private boolean selfStarted;
private MediaSession session;
private boolean shuffle;
private long sleepAt;
private boolean sleepEndOfTrack;
public final Spectrum spectrum;
private long startedSec;
private int xfMs;
private long xfStart;
private final LocalBinder binder = new LocalBinder();
private final CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<>();
private int nxtIndex = -1;
private List<Song> queue = new ArrayList();
private List<Song> original = new ArrayList();
private int index = -1;
private long pendingSeek = -1;
private float duckVol = 1.0f;
private int widgetLine = -2;
private final Library.Listener libListener = new Library.Listener() { // from class: com.mulberry.player.MusicService.2
@Override // com.mulberry.player.Library.Listener
public void onLibraryChanged() {
if (MusicService.this.playWhenLibrary && MusicService.this.queue.isEmpty() && !App.I.library.songs.isEmpty()) {
MusicService.this.playWhenLibrary = false;
MusicService.this.playShuffled(new ArrayList(App.I.library.songs));
}
}
};
private final MediaPlayer.OnErrorListener errors = new MediaPlayer.OnErrorListener() { // from class: com.mulberry.player.MusicService.4
@Override // android.media.MediaPlayer.OnErrorListener
public boolean onError(MediaPlayer mediaPlayer, int i, int i2) {
MusicService.this.handleError(mediaPlayer);
return true;
}
};
private final MediaPlayer.OnCompletionListener completion = new MediaPlayer.OnCompletionListener() { // from class: com.mulberry.player.MusicService.7
@Override // android.media.MediaPlayer.OnCompletionListener
public void onCompletion(MediaPlayer mediaPlayer) {
if (mediaPlayer == MusicService.this.cur) {
Song songCurrent = MusicService.this.current();
if (songCurrent != null) {
ScrobbleBridge.send(MusicService.this, songCurrent, 3);
}
MusicService.this.finishListen(true);
if (MusicService.this.sleepEndOfTrack) {
MusicService.this.sleepEndOfTrack = false;
MusicService.this.sleepAt = 0L;
int iNextIndex = MusicService.this.nextIndex(false);
if (iNextIndex >= 0) {
MusicService.this.load(iNextIndex, false, 0L);
return;
} else {
MusicService.this.stopPlayback();
return;
}
}
if (MusicService.this.nxt == null || !MusicService.this.nxtPrepared || !MusicService.this.nxtLinked || MusicService.this.nxtIndex < 0) {
int iNextIndex2 = MusicService.this.nextIndex(false);
if (iNextIndex2 < 0) {
MusicService.this.releasePlayers();
MusicService.this.playWhenReady = false;
MusicService.this.index = 0;
if (!MusicService.this.queue.isEmpty()) {
MusicService.this.load(0, false, 0L);
}
MusicService.this.abandonFocus();
MusicService.this.stopFg(false);
MusicService.this.notifyState();
return;
}
MusicService.this.load(iNextIndex2, true, 0L);
return;
}
MediaPlayer mediaPlayer2 = MusicService.this.cur;
MusicService.this.cur = MusicService.this.nxt;
MusicService.this.curPrepared = true;
MusicService.this.index = MusicService.this.nxtIndex;
MusicService.this.nxt = null;
MusicService.this.nxtPrepared = false;
MusicService.this.nxtLinked = false;
MusicService.this.nxtIndex = -1;
try {
mediaPlayer2.release();
} catch (Exception e) {
}
MusicService.this.cur.setOnCompletionListener(MusicService.this.completion);
MusicService.this.cur.setOnErrorListener(MusicService.this.errors);
try {
MusicService.this.cur.setLooping(MusicService.this.repeat == 2);
} catch (Exception e2) {
}
Song songCurrent2 = MusicService.this.current();
if (songCurrent2 != null && songCurrent2.duration <= 0) {
songCurrent2.duration = Math.max(0, MusicService.this.cur.getDuration());
}
if (MusicService.this.spectrum != null && songCurrent2 != null) {
MusicService.this.spectrum.start(songCurrent2, songCurrent2.duration);
}
MusicService.this.beginListen(songCurrent2);
MusicService.this.onStarted();
MusicService.this.notifyTrack();
MusicService.this.loadArtAndLyrics(songCurrent2);
MusicService.this.prepareNext();
MusicService.this.saveQueueLater();
}
}
};
private float gain = 1.0f;
private float xfIn = 1.0f;
private float xfOut = 0.0f;
private final Runnable xfWatch = new Runnable() { // from class: com.mulberry.player.MusicService.10
@Override // java.lang.Runnable
public void run() {
int iCrossfadeMs = MusicService.this.crossfadeMs();
if (iCrossfadeMs > 0 && MusicService.this.isPlaying()) {
if (MusicService.this.fadingOut == null && MusicService.this.repeat != 2 && !MusicService.this.sleepEndOfTrack && MusicService.this.nxt != null && MusicService.this.nxtPrepared && MusicService.this.nxtIndex >= 0) {
long jDuration = MusicService.this.duration();
long jPosition = MusicService.this.position();
if (jDuration > ((long) iCrossfadeMs) * 2 && jDuration - jPosition <= iCrossfadeMs) {
MusicService.this.beginCrossfade((int) Math.max(500L, jDuration - jPosition));
}
}
App.MAIN.postDelayed(this, 100L);
}
}
};
private final Runnable xfRamp = new Runnable() { // from class: com.mulberry.player.MusicService.13
@Override // java.lang.Runnable
public void run() {
if (MusicService.this.fadingOut != null) {
float fMin = Math.min(1.0f, (SystemClock.elapsedRealtime() - MusicService.this.xfStart) / Math.max(1, MusicService.this.xfMs));
MusicService.this.xfIn = (float) Math.sin((((double) fMin) * 3.141592653589793d) / 2.0d);
MusicService.this.xfOut = (float) Math.cos((((double) fMin) * 3.141592653589793d) / 2.0d);
MusicService.this.applyVolume();
if (fMin >= 1.0f) {
MusicService.this.endCrossfade();
MusicService.this.prepareNext();
} else {
App.MAIN.postDelayed(this, 40L);
}
}
}
};
private final Runnable sleepTask = new Runnable() { // from class: com.mulberry.player.MusicService.15
@Override // java.lang.Runnable
public void run() {
MusicService.this.sleepAt = 0L;
MusicService.this.fadeOutAndPause();
}
};
private final Runnable ticker = new Runnable() { // from class: com.mulberry.player.MusicService.17
@Override // java.lang.Runnable
public void run() {
if (MusicService.this.isPlaying()) {
MusicService.this.pubPos = MusicService.this.position();
MusicService.this.tickListen();
if (MusicService.this.pm == null || MusicService.this.pm.isInteractive()) {
Widgets.tick(MusicService.this);
}
if (MusicService.access$4804(MusicService.this) % 10 == 0) {
MusicService.this.savePosition();
}
App.MAIN.postDelayed(this, 1000L);
}
}
};
private final BroadcastReceiver noisy = new BroadcastReceiver() { // from class: com.mulberry.player.MusicService.18
@Override // android.content.BroadcastReceiver
public void onReceive(Context context, Intent intent) {
if (!"android.media.AUDIO_BECOMING_NOISY".equals(intent.getAction()) || !App.I.prefs.getBool(Prefs.PAUSE_ON_DETACH, true)) {
return;
}
MusicService.this.pause();
}
};
private final Runnable saveLater = new Runnable() { // from class: com.mulberry.player.MusicService.22
@Override // java.lang.Runnable
public void run() {
MusicService.this.saveQueue();
}
};
public interface Listener {
void onLyrics();
void onQueueChanged();
void onStateChanged();
void onTrackChanged();
}
static /* synthetic */ int access$4804(MusicService musicService) {
int i = musicService.saveCounter + 1;
musicService.saveCounter = i;
return i;
}
public class LocalBinder extends Binder {
public LocalBinder() {
}
public MusicService service() {
return MusicService.this;
}
}
public MusicService() {
this.spectrum = App.I == null ? null : new Spectrum(App.I);
}
@Override // android.service.media.MediaBrowserService, android.app.Service
public void onCreate() {
super.onCreate();
INSTANCE = this;
this.am = (AudioManager) getSystemService("audio");
this.pm = (PowerManager) getSystemService("power");
this.shuffle = App.I.prefs.getBool(Prefs.SHUFFLE, false);
this.repeat = App.I.prefs.getInt(Prefs.REPEAT, 0);
if (this.spectrum != null) {
this.spectrum.setClock(new Spectrum.Clock() { // from class: com.mulberry.player.MusicService.1
@Override // com.mulberry.player.Spectrum.Clock
public long positionMs() {
return MusicService.this.pubPos;
}
});
}
this.session = new MediaSession(this, "Mulberry");
this.session.setFlags(3);
this.session.setCallback(new SessionCb());
this.session.setSessionActivity(PendingIntent.getActivity(this, 1, new Intent(this, (Class<?>) MainActivity.class).addFlags(536870912), 201326592));
this.session.setMediaButtonReceiver(PendingIntent.getBroadcast(this, 2, new Intent("android.intent.action.MEDIA_BUTTON").setClass(this, MediaButtonReceiver.class), 67108864));
setSessionToken(this.session.getSessionToken());
restoreQueue();
updateSession();
App.I.library.addListener(this.libListener);
if (!App.I.library.loaded) {
App.I.library.refresh();
}
}
@Override // android.service.media.MediaBrowserService, android.app.Service
public IBinder onBind(Intent intent) {
return "android.media.browse.MediaBrowserService".equals(intent.getAction()) ? super.onBind(intent) : this.binder;
}
@Override // android.app.Service
public int onStartCommand(Intent intent, int i, int i2) {
if (intent != null && intent.getBooleanExtra(EXTRA_FG, false)) {
goForeground(true);
}
if (intent != null && intent.getAction() != null) {
handleAction(intent.getAction());
} else if (intent != null && "android.intent.action.MEDIA_BUTTON".equals(intent.getAction())) {
toggle();
}
if (intent != null && intent.getBooleanExtra(EXTRA_FG, false) && !isPlaying() && !this.playWhenReady && !this.playWhenLibrary) {
stopFg(false);
return 2;
}
return 2;
}
void handleAction(String str) {
if (!ACT_TOGGLE.equals(str)) {
if (!ACT_PLAY.equals(str)) {
if (!ACT_PAUSE.equals(str)) {
if (!ACT_NEXT.equals(str)) {
if (!ACT_PREV.equals(str)) {
if (!ACT_SHUFFLE.equals(str)) {
if (!ACT_REPEAT.equals(str)) {
if (ACT_FAV.equals(str)) {
Song songCurrent = current();
if (songCurrent != null) {
PlayStats.setFav(songCurrent, PlayStats.fav(songCurrent) ? false : true);
refreshUi();
return;
}
return;
}
if (!ACT_STOP.equals(str)) {
if (ACT_REFRESH.equals(str)) {
refreshUi();
return;
}
return;
}
stopAndQuit();
return;
}
cycleRepeat();
return;
}
setShuffle(this.shuffle ? false : true);
return;
}
prev();
return;
}
next();
return;
}
pause();
return;
}
play();
return;
}
toggle();
}
@Override // android.app.Service
public void onTaskRemoved(Intent intent) {
if (!isPlaying()) {
stopAndQuit();
}
}
@Override // android.app.Service
public void onDestroy() {
NotificationManager notificationManager;
saveQueue();
PlayStats.save();
App.MAIN.removeCallbacks(this.ticker);
App.MAIN.removeCallbacks(this.sleepTask);
releasePlayers();
if (this.spectrum != null) {
this.spectrum.stop();
}
abandonFocus();
unregisterNoisy();
App.I.library.removeListener(this.libListener);
this.session.setActive(false);
this.session.release();
INSTANCE = null;
if (!this.foreground && (notificationManager = (NotificationManager) getSystemService("notification")) != null) {
notificationManager.cancel(7);
}
Widgets.updateAll(this);
super.onDestroy();
}
public void addListener(Listener listener) {
this.listeners.add(listener);
}
public void removeListener(Listener listener) {
this.listeners.remove(listener);
}
public List<Song> queue() {
return Collections.unmodifiableList(this.queue);
}
public int index() {
return this.index;
}
public Song current() {
if (this.index < 0 || this.index >= this.queue.size()) {
return null;
}
return this.queue.get(this.index);
}
public boolean shuffle() {
return this.shuffle;
}
public int repeat() {
return this.repeat;
}
public void playList(List<Song> list, int i) {
if (list != null && !list.isEmpty()) {
this.original = new ArrayList(list);
this.queue = new ArrayList(list);
this.index = Math.max(0, Math.min(i, list.size() - 1));
if (this.shuffle) {
shuffleKeepingCurrent();
}
this.errorStreak = 0;
notifyQueue();
load(this.index, true, 0L);
}
}
public void playShuffled(List<Song> list) {
if (list != null && !list.isEmpty()) {
if (!this.shuffle) {
this.shuffle = true;
App.I.prefs.setBool(Prefs.SHUFFLE, true);
}
playList(list, new Random().nextInt(list.size()));
}
}
public void playNext(List<Song> list) {
if (!list.isEmpty()) {
if (!this.queue.isEmpty()) {
this.queue.addAll(this.index + 1, list);
int iIndexOf = this.original.indexOf(current());
this.original.addAll(iIndexOf < 0 ? this.original.size() : iIndexOf + 1, list);
afterQueueEdit();
return;
}
playList(list, 0);
}
}
public void enqueue(List<Song> list) {
if (!list.isEmpty()) {
if (!this.queue.isEmpty()) {
this.queue.addAll(list);
this.original.addAll(list);
afterQueueEdit();
return;
}
playList(list, 0);
}
}
public void removeAt(int i) {
if (i >= 0 && i < this.queue.size()) {
this.original.remove(this.queue.remove(i));
if (i < this.index) {
this.index--;
} else if (i == this.index) {
if (!this.queue.isEmpty()) {
boolean z = isPlaying() || this.playWhenReady;
if (this.index >= this.queue.size()) {
this.index = 0;
if (this.repeat != 1) {
z = false;
}
}
load(this.index, z, 0L);
} else {
stopPlayback();
this.index = -1;
notifyQueue();
notifyTrack();
return;
}
}
afterQueueEdit();
}
}
public void move(int i, int i2) {
if (i >= 0 && i < this.queue.size() && i2 >= 0 && i2 < this.queue.size() && i != i2) {
this.queue.add(i2, this.queue.remove(i));
if (this.index == i) {
this.index = i2;
} else if (i < this.index && i2 >= this.index) {
this.index--;
} else if (i > this.index && i2 <= this.index) {
this.index++;
}
if (!this.shuffle) {
this.original = new ArrayList(this.queue);
}
afterQueueEdit();
}
}
public void clearQueue() {
stopPlayback();
this.queue = new ArrayList();
this.original = new ArrayList();
this.index = -1;
notifyQueue();
notifyTrack();
saveQueue();
}
public void jump(int i) {
if (i >= 0 && i < this.queue.size()) {
this.index = i;
this.errorStreak = 0;
load(i, true, 0L);
}
}
private void afterQueueEdit() {
prepareNext();
notifyQueue();
saveQueueLater();
updateSessionQueue();
}
public void setShuffle(boolean z) {
if (z != this.shuffle) {
this.shuffle = z;
App.I.prefs.setBool(Prefs.SHUFFLE, z);
Song songCurrent = current();
if (z) {
shuffleKeepingCurrent();
} else {
this.queue = new ArrayList(this.original);
this.index = songCurrent != null ? Math.max(0, this.queue.indexOf(songCurrent)) : 0;
}
afterQueueEdit();
refreshUi();
}
}
private void shuffleKeepingCurrent() {
Song songCurrent = current();
ArrayList arrayList = new ArrayList(this.queue);
if (songCurrent != null) {
arrayList.remove(this.index);
}
Collections.shuffle(arrayList);
this.queue = new ArrayList();
if (songCurrent != null) {
this.queue.add(songCurrent);
}
this.queue.addAll(arrayList);
if (songCurrent == null) {
}
this.index = 0;
}
public void cycleRepeat() {
this.repeat = (this.repeat + 1) % 3;
App.I.prefs.setInt(Prefs.REPEAT, this.repeat);
if (this.cur != null) {
try {
this.cur.setLooping(this.repeat == 2);
} catch (Exception e) {
}
}
prepareNext();
refreshUi();
}
private MediaPlayer newPlayer() {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes(new AudioAttributes.Builder().setUsage(1).setContentType(2).build());
mediaPlayer.setWakeMode(getApplicationContext(), 1);
return mediaPlayer;
}
/* JADX INFO: Access modifiers changed from: private */
public void releasePlayers() {
endCrossfade();
this.fadeToken++;
this.gain = 1.0f;
if (this.cur != null) {
try {
this.cur.release();
} catch (Exception e) {
}
this.cur = null;
}
releaseNext();
this.curPrepared = false;
}
private void releaseNext() {
if (this.nxt != null) {
if (this.cur != null && this.nxtLinked) {
try {
this.cur.setNextMediaPlayer(null);
} catch (Exception e) {
}
}
try {
this.nxt.release();
} catch (Exception e2) {
}
this.nxt = null;
}
this.nxtPrepared = false;
this.nxtLinked = false;
this.nxtIndex = -1;
}
/* JADX INFO: Access modifiers changed from: private */
public void stopPlayback() {
finishListen(false);
releasePlayers();
this.playWhenReady = false;
if (this.spectrum != null) {
this.spectrum.stop();
}
abandonFocus();
unregisterNoisy();
stopFg(false);
notifyState();
}
/* JADX INFO: Access modifiers changed from: private */
public void load(int i, boolean z, long j) {
if (i >= 0 && i < this.queue.size()) {
finishListen(false);
releasePlayers();
this.index = i;
this.playWhenReady = z;
this.pendingSeek = j;
final Song song = this.queue.get(i);
MediaPlayer mediaPlayerNewPlayer = newPlayer();
this.cur = mediaPlayerNewPlayer;
this.curPrepared = false;
mediaPlayerNewPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { // from class: com.mulberry.player.MusicService.3
@Override // android.media.MediaPlayer.OnPreparedListener
public void onPrepared(MediaPlayer mediaPlayer) {
if (mediaPlayer == MusicService.this.cur) {
MusicService.this.curPrepared = true;
MusicService.this.errorStreak = 0;
if (song.duration <= 0) {
song.duration = Math.max(0, mediaPlayer.getDuration());
}
mediaPlayer.setLooping(MusicService.this.repeat == 2);
if (MusicService.this.pendingSeek > 0) {
try {
mediaPlayer.seekTo((int) MusicService.this.pendingSeek);
} catch (Exception e) {
}
}
MusicService.this.pendingSeek = -1L;
if (MusicService.this.spectrum != null) {
MusicService.this.spectrum.start(song, Math.max(song.duration, mediaPlayer.getDuration()));
}
if (MusicService.this.playWhenReady) {
MusicService.this.startPlayback();
} else {
MusicService.this.notifyState();
}
MusicService.this.prepareNext();
}
}
});
mediaPlayerNewPlayer.setOnCompletionListener(this.completion);
mediaPlayerNewPlayer.setOnErrorListener(this.errors);
try {
mediaPlayerNewPlayer.setDataSource(getApplicationContext(), song.toUri());
mediaPlayerNewPlayer.prepareAsync();
} catch (Exception e) {
handleError(mediaPlayerNewPlayer);
}
beginListen(song);
notifyTrack();
loadArtAndLyrics(song);
saveQueueLater();
}
}
/* JADX INFO: Access modifiers changed from: private */
public void handleError(final MediaPlayer mediaPlayer) {
if (mediaPlayer != this.nxt) {
if (mediaPlayer == this.cur) {
this.errorStreak++;
Song songCurrent = current();
App.ui(new Runnable() { // from class: com.mulberry.player.MusicService.5
@Override // java.lang.Runnable
public void run() {
Iterator it = MusicService.this.listeners.iterator();
while (it.hasNext()) {
((Listener) it.next()).onStateChanged();
}
}
});
if (songCurrent != null) {
MainActivity.toast("Can't play “" + songCurrent.displayTitle() + "” — skipping");
}
if (this.errorStreak >= Math.min(8, Math.max(1, this.queue.size()))) {
this.errorStreak = 0;
stopPlayback();
return;
} else {
final boolean z = this.playWhenReady || isPlaying();
App.MAIN.postDelayed(new Runnable() { // from class: com.mulberry.player.MusicService.6
@Override // java.lang.Runnable
public void run() {
if (MusicService.this.cur == mediaPlayer) {
int iNextIndex = MusicService.this.nextIndex(true);
if (iNextIndex < 0) {
MusicService.this.stopPlayback();
} else {
MusicService.this.load(iNextIndex, z, 0L);
}
}
}
}, 300L);
return;
}
}
return;
}
releaseNext();
}
/* JADX INFO: Access modifiers changed from: private */
public int nextIndex(boolean z) {
if (this.queue.isEmpty()) {
return -1;
}
if (this.index + 1 < this.queue.size()) {
return this.index + 1;
}
return (this.repeat == 1 || (z && this.repeat != 0)) ? 0 : -1;
}
/* JADX INFO: Access modifiers changed from: private */
public void prepareNext() {
int iNextIndex;
releaseNext();
if (this.cur != null && this.curPrepared && this.repeat != 2 && !this.sleepEndOfTrack) {
if (((crossfadeMs() > 0) || App.I.prefs.getBool(Prefs.GAPLESS, true)) && (iNextIndex = nextIndex(false)) >= 0 && iNextIndex != this.index) {
Song song = this.queue.get(iNextIndex);
if (!song.isStream()) {
MediaPlayer mediaPlayerNewPlayer = newPlayer();
this.nxt = mediaPlayerNewPlayer;
this.nxtIndex = iNextIndex;
mediaPlayerNewPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { // from class: com.mulberry.player.MusicService.8
@Override // android.media.MediaPlayer.OnPreparedListener
public void onPrepared(MediaPlayer mediaPlayer) {
if (mediaPlayer == MusicService.this.nxt && MusicService.this.cur != null) {
MusicService.this.nxtPrepared = true;
if (MusicService.this.crossfadeMs() <= 0) {
try {
MusicService.this.cur.setNextMediaPlayer(mediaPlayer);
MusicService.this.nxtLinked = true;
} catch (Exception e) {
MusicService.this.nxtLinked = false;
}
}
}
}
});
mediaPlayerNewPlayer.setOnErrorListener(this.errors);
try {
mediaPlayerNewPlayer.setDataSource(getApplicationContext(), song.toUri());
mediaPlayerNewPlayer.prepareAsync();
} catch (Exception e) {
releaseNext();
}
}
}
}
}
public boolean isPlaying() {
try {
return this.playWhenReady && this.cur != null && this.curPrepared && this.cur.isPlaying();
} catch (Exception e) {
return false;
}
}
public boolean isLoading() {
return (this.cur == null || this.curPrepared || !this.playWhenReady) ? false : true;
}
public long position() {
try {
if (this.cur != null && this.curPrepared) {
return this.cur.getCurrentPosition();
}
} catch (Exception e) {
}
if (this.pendingSeek > 0) {
return this.pendingSeek;
}
return 0L;
}
public long positionFast() {
long jElapsedRealtime = SystemClock.elapsedRealtime();
if (jElapsedRealtime - this.sampleAt <= 250 && this.sampleAt != 0) {
if (!this.samplePlaying) {
return this.samplePos;
}
return (jElapsedRealtime - this.sampleAt) + this.samplePos;
}
this.samplePos = position();
this.samplePlaying = isPlaying();
this.sampleAt = jElapsedRealtime;
this.pubPos = this.samplePos;
return this.samplePos;
}
public long duration() {
int duration;
Song songCurrent = current();
try {
if (this.cur != null && this.curPrepared && (duration = this.cur.getDuration()) > 0) {
return duration;
}
} catch (Exception e) {
}
if (songCurrent == null) {
return 0L;
}
return songCurrent.duration;
}
public void toggle() {
if (isPlaying() || isLoading()) {
pause();
} else {
play();
}
}
public void play() {
if (this.queue.isEmpty()) {
List<Song> list = App.I.library.songs;
if (list.isEmpty()) {
this.playWhenLibrary = true;
if (App.I.library.loaded) {
MainActivity.toast("No music found on this phone");
return;
} else {
App.I.library.refresh();
return;
}
}
playShuffled(new ArrayList(list));
return;
}
if (this.cur != null) {
this.playWhenReady = true;
if (this.curPrepared) {
startPlayback();
return;
} else {
notifyState();
return;
}
}
load(Math.max(0, this.index), true, this.lastSavedPos);
this.lastSavedPos = 0L;
}
/* JADX INFO: Access modifiers changed from: private */
public void startPlayback() {
if (requestFocus()) {
boolean z = App.I.prefs.getBool(Prefs.FADE_PAUSE, true) && !App.lowPower();
this.fadeToken++;
try {
this.gain = z ? 0.0f : 1.0f;
applyVolume();
this.cur.start();
if (z) {
ramp(0.0f, 1.0f, 350, null);
}
onStarted();
return;
} catch (Exception e) {
handleError(this.cur);
return;
}
}
this.playWhenReady = false;
notifyState();
}
public void playbackSettingsChanged() {
prepareNext();
App.MAIN.removeCallbacks(this.xfWatch);
if (crossfadeMs() <= 0 || !isPlaying()) {
return;
}
App.MAIN.post(this.xfWatch);
}
int crossfadeMs() {
return Math.max(0, Math.min(12, App.I.prefs.getInt(Prefs.CROSSFADE, 0))) * 1000;
}
/* JADX INFO: Access modifiers changed from: private */
public void applyVolume() {
float f = this.duckVol * this.gain * this.xfIn;
if (this.cur != null) {
try {
this.cur.setVolume(f, f);
} catch (Exception e) {
}
}
if (this.fadingOut != null) {
float f2 = this.duckVol * this.xfOut;
try {
this.fadingOut.setVolume(f2, f2);
} catch (Exception e2) {
}
}
}
private void ramp(final float f, final float f2, final int i, final Runnable runnable) {
final int i2 = this.fadeToken + 1;
this.fadeToken = i2;
final long jElapsedRealtime = SystemClock.elapsedRealtime();
App.MAIN.post(new Runnable() { // from class: com.mulberry.player.MusicService.9
@Override // java.lang.Runnable
public void run() {
if (i2 == MusicService.this.fadeToken) {
float fMin = Math.min(1.0f, (SystemClock.elapsedRealtime() - jElapsedRealtime) / i);
MusicService.this.gain = f + ((f2 - f) * fMin);
MusicService.this.applyVolume();
if (fMin >= 1.0f) {
if (runnable != null) {
runnable.run();
return;
}
return;
}
App.MAIN.postDelayed(this, 25L);
}
}
});
}
/* JADX INFO: Access modifiers changed from: private */
public void beginCrossfade(int i) {
Song songCurrent = current();
if (songCurrent != null) {
ScrobbleBridge.send(this, songCurrent, 3);
}
finishListen(true);
MediaPlayer mediaPlayer = this.cur;
this.fadingOut = mediaPlayer;
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { // from class: com.mulberry.player.MusicService.11
@Override // android.media.MediaPlayer.OnCompletionListener
public void onCompletion(MediaPlayer mediaPlayer2) {
if (mediaPlayer2 == MusicService.this.fadingOut) {
MusicService.this.endCrossfade();
}
}
});
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { // from class: com.mulberry.player.MusicService.12
@Override // android.media.MediaPlayer.OnErrorListener
public boolean onError(MediaPlayer mediaPlayer2, int i2, int i3) {
if (mediaPlayer2 != MusicService.this.fadingOut) {
return true;
}
MusicService.this.endCrossfade();
return true;
}
});
this.cur = this.nxt;
this.curPrepared = true;
this.index = this.nxtIndex;
this.nxt = null;
this.nxtPrepared = false;
this.nxtLinked = false;
this.nxtIndex = -1;
this.cur.setOnCompletionListener(this.completion);
this.cur.setOnErrorListener(this.errors);
try {
this.cur.setLooping(this.repeat == 2);
} catch (Exception e) {
}
this.xfIn = 0.0f;
this.xfOut = 1.0f;
this.gain = 1.0f;
applyVolume();
try {
this.cur.start();
this.xfStart = SystemClock.elapsedRealtime();
this.xfMs = i;
App.MAIN.post(this.xfRamp);
Song songCurrent2 = current();
if (songCurrent2 != null && songCurrent2.duration <= 0) {
songCurrent2.duration = Math.max(0, this.cur.getDuration());
}
if (this.spectrum != null && songCurrent2 != null) {
this.spectrum.start(songCurrent2, songCurrent2.duration);
}
beginListen(songCurrent2);
onStarted();
notifyTrack();
loadArtAndLyrics(songCurrent2);
saveQueueLater();
} catch (Exception e2) {
endCrossfade();
handleError(this.cur);
}
}
/* JADX INFO: Access modifiers changed from: private */
public void endCrossfade() {
App.MAIN.removeCallbacks(this.xfRamp);
if (this.fadingOut != null) {
try {
this.fadingOut.release();
} catch (Exception e) {
}
this.fadingOut = null;
}
this.xfIn = 1.0f;
this.xfOut = 0.0f;
applyVolume();
}
/* JADX INFO: Access modifiers changed from: private */
public void onStarted() {
this.playWhenReady = true;
if (!this.selfStarted) {
try {
startService(new Intent(this, (Class<?>) MusicService.class));
this.selfStarted = true;
} catch (Exception e) {
}
}
this.lastTick = SystemClock.elapsedRealtime();
registerNoisy();
goForeground(false);
App.MAIN.removeCallbacks(this.ticker);
App.MAIN.post(this.ticker);
App.MAIN.removeCallbacks(this.xfWatch);
if (crossfadeMs() > 0) {
App.MAIN.postDelayed(this.xfWatch, 200L);
}
Song songCurrent = current();
if (songCurrent != null) {
ScrobbleBridge.send(this, songCurrent, this.listenedMs <= 0 ? 0 : 1);
}
notifyState();
}
public void pause() {
pause(false);
}
void pause(boolean z) {
this.playWhenReady = false;
endCrossfade();
final MediaPlayer mediaPlayer = this.cur;
if (!z && App.I.prefs.getBool(Prefs.FADE_PAUSE, true) && !App.lowPower() && isPlaying()) {
ramp(this.gain, 0.0f, 220, new Runnable() { // from class: com.mulberry.player.MusicService.14
@Override // java.lang.Runnable
public void run() {
try {
if (mediaPlayer != MusicService.this.cur || MusicService.this.playWhenReady || !mediaPlayer.isPlaying()) {
return;
}
mediaPlayer.pause();
} catch (Exception e) {
}
}
});
} else {
this.fadeToken++;
try {
if (this.cur != null && this.curPrepared && this.cur.isPlaying()) {
this.cur.pause();
}
} catch (Exception e) {
}
}
tickListen();
Song songCurrent = current();
if (songCurrent != null) {
ScrobbleBridge.send(this, songCurrent, 2);
}
unregisterNoisy();
if (z) {
updateNotification();
} else {
stopFg(false);
}
savePosition();
notifyState();
}
public void next() {
int iNextIndex = nextIndex(true);
if (iNextIndex < 0) {
iNextIndex = 0;
}
if (!this.queue.isEmpty()) {
this.errorStreak = 0;
load(iNextIndex, true, 0L);
}
}
public void prev() {
if (this.queue.isEmpty()) {
return;
}
if (position() <= 4000) {
int size = this.index - 1;
if (size < 0) {
size = this.repeat == 1 ? this.queue.size() - 1 : 0;
}
this.errorStreak = 0;
load(size, true, 0L);
return;
}
seek(0L);
}
public void seek(long j) {
if (this.cur != null && this.curPrepared) {
try {
this.cur.seekTo((int) Math.max(0L, j));
} catch (Exception e) {
}
} else {
this.pendingSeek = j;
}
if (this.spectrum != null) {
this.spectrum.seek(j);
}
this.sampleAt = 0L;
this.pubPos = j;
this.lastTick = SystemClock.elapsedRealtime();
this.widgetLine = -2;
notifyState();
}
public void stopAndQuit() {
stopPlayback();
saveQueue();
NotificationManager notificationManager = (NotificationManager) getSystemService("notification");
if (notificationManager != null) {
notificationManager.cancel(7);
}
this.notifShown = false;
stopSelf();
}
public void sleepIn(int i) {
App.MAIN.removeCallbacks(this.sleepTask);
boolean z = this.sleepEndOfTrack;
this.sleepEndOfTrack = false;
if (z) {
prepareNext();
}
if (i > 0) {
this.sleepAt = SystemClock.elapsedRealtime() + (((long) i) * 60000);
App.MAIN.postDelayed(this.sleepTask, ((long) i) * 60000);
} else {
this.sleepAt = 0L;
}
}
public void sleepAtEndOfTrack() {
App.MAIN.removeCallbacks(this.sleepTask);
this.sleepAt = 0L;
this.sleepEndOfTrack = true;
releaseNext();
}
public long sleepRemaining() {
if (this.sleepAt == 0) {
return this.sleepEndOfTrack ? -1 : 0;
}
return Math.max(0L, this.sleepAt - SystemClock.elapsedRealtime());
}
/* JADX INFO: Access modifiers changed from: private */
public void fadeOutAndPause() {
if (isPlaying()) {
ramp(this.gain, 0.0f, FlacTagCreator.DEFAULT_PADDING, new Runnable() { // from class: com.mulberry.player.MusicService.16
@Override // java.lang.Runnable
public void run() {
MusicService.this.pause();
}
});
}
}
/* JADX INFO: Access modifiers changed from: private */
public void beginListen(Song song) {
this.listenedMs = 0L;
this.scrobbled = false;
this.countedPlay = false;
this.startedSec = System.currentTimeMillis() / 1000;
this.lastTick = SystemClock.elapsedRealtime();
if (song == null || !LastFm.anyOn()) {
return;
}
LastFm.nowPlaying(song);
}
/* JADX INFO: Access modifiers changed from: private */
public void tickListen() {
long jElapsedRealtime = SystemClock.elapsedRealtime();
if (isPlaying()) {
this.listenedMs += Math.min(5000L, jElapsedRealtime - this.lastTick);
}
this.lastTick = jElapsedRealtime;
Song songCurrent = current();
if (songCurrent != null) {
long jDuration = duration();
if (!this.countedPlay && jDuration > 0 && this.listenedMs >= Math.min(jDuration / 2, 240000L)) {
this.countedPlay = true;
PlayStats.played(songCurrent);
}
if (!this.scrobbled && jDuration >= 30000 && this.listenedMs >= Math.min(jDuration / 2, 240000L)) {
this.scrobbled = true;
LastFm.scrobble(songCurrent, this.startedSec);
}
}
}
/* JADX INFO: Access modifiers changed from: private */
public void finishListen(boolean z) {
tickListen();
this.listenedMs = 0L;
}
boolean lyricLineChanged() {
Lyrics.Result result = this.lyrics;
int iLineAt = (result == null || !result.synced || result.lines.isEmpty()) ? -1 : Lyrics.lineAt(result.lines, position() + 250);
if (iLineAt == this.widgetLine) {
return false;
}
this.widgetLine = iLineAt;
return true;
}
private boolean requestFocus() {
int iRequestAudioFocus;
if (this.am == null) {
return true;
}
if (Build.VERSION.SDK_INT >= 26) {
if (this.focusReq == null) {
this.focusReq = new AudioFocusRequest.Builder(1).setAudioAttributes(new AudioAttributes.Builder().setUsage(1).setContentType(2).build()).setOnAudioFocusChangeListener(this).setWillPauseWhenDucked(false).build();
}
iRequestAudioFocus = this.am.requestAudioFocus(this.focusReq);
} else {
iRequestAudioFocus = this.am.requestAudioFocus(this, 3, 1);
}
return iRequestAudioFocus == 1;
}
/* JADX INFO: Access modifiers changed from: private */
public void abandonFocus() {
if (this.am != null) {
if (Build.VERSION.SDK_INT < 26) {
this.am.abandonAudioFocus(this);
} else if (this.focusReq != null) {
this.am.abandonAudioFocusRequest(this.focusReq);
}
}
}
@Override // android.media.AudioManager.OnAudioFocusChangeListener
public void onAudioFocusChange(int i) {
switch (i) {
case -3:
this.duckVol = 0.3f;
applyVolume();
break;
case Ui.WRAP /* -2 */:
if (isPlaying()) {
this.focusLossTransient = true;
pause(true);
}
break;
case Ui.MATCH /* -1 */:
boolean z = this.focusLossTransient;
this.focusLossTransient = false;
pause();
if (z) {
stopFg(false);
}
break;
case 1:
this.duckVol = 1.0f;
applyVolume();
if (this.focusLossTransient) {
this.focusLossTransient = false;
play();
}
break;
}
}
private void registerNoisy() {
if (!this.noisyRegistered) {
registerReceiver(this.noisy, new IntentFilter("android.media.AUDIO_BECOMING_NOISY"));
this.noisyRegistered = true;
}
}
private void unregisterNoisy() {
if (this.noisyRegistered) {
try {
unregisterReceiver(this.noisy);
} catch (Exception e) {
}
this.noisyRegistered = false;
}
}
public Bitmap art() {
return this.art;
}
/* JADX INFO: Access modifiers changed from: private */
public void loadArtAndLyrics(Song song) {
final int i = this.artToken + 1;
this.artToken = i;
this.art = null;
this.lyrics = null;
this.widgetLine = -2;
if (song != null) {
Covers.load(song, App.I.lowRam ? 400 : 800, true, new Covers.Cb() { // from class: com.mulberry.player.MusicService.19
@Override // com.mulberry.player.Covers.Cb
public void done(Bitmap bitmap) {
if (i == MusicService.this.artToken) {
MusicService.this.art = bitmap;
if ("album".equals(App.I.prefs.getStr(Prefs.COLOR_SOURCE, "system"))) {
App.I.palette = Palette.build(MusicService.this, bitmap == null ? null : Palette.dominant(bitmap));
}
MusicService.this.updateSession();
MusicService.this.updateNotification();
Widgets.updateAll(MusicService.this);
Iterator it = MusicService.this.listeners.iterator();
while (it.hasNext()) {
((Listener) it.next()).onTrackChanged();
}
}
}
});
Lyrics.load(song, false, new Lyrics.Cb() { // from class: com.mulberry.player.MusicService.20
@Override // com.mulberry.player.Lyrics.Cb
public void done(Lyrics.Result result) {
if (i == MusicService.this.artToken) {
MusicService.this.lyrics = result;
MusicService.this.widgetLine = -2;
Widgets.updateAll(MusicService.this);
Iterator it = MusicService.this.listeners.iterator();
while (it.hasNext()) {
((Listener) it.next()).onLyrics();
}
}
}
});
}
}
public void reloadLyrics(boolean z) {
Song songCurrent = current();
if (songCurrent != null) {
final int i = this.artToken;
this.lyrics = null;
Iterator<Listener> it = this.listeners.iterator();
while (it.hasNext()) {
it.next().onLyrics();
}
Lyrics.load(songCurrent, z, new Lyrics.Cb() { // from class: com.mulberry.player.MusicService.21
@Override // com.mulberry.player.Lyrics.Cb
public void done(Lyrics.Result result) {
if (i == MusicService.this.artToken) {
MusicService.this.lyrics = result;
MusicService.this.widgetLine = -2;
Widgets.updateAll(MusicService.this);
Iterator it2 = MusicService.this.listeners.iterator();
while (it2.hasNext()) {
((Listener) it2.next()).onLyrics();
}
}
}
});
}
}
public void holdForEdit(Set<String> set) {
Song songCurrent = current();
if (this.nxtIndex >= 0 && this.nxtIndex < this.queue.size() && set.contains(this.queue.get(this.nxtIndex).key())) {
releaseNext();
}
if (songCurrent != null && set.contains(songCurrent.key()) && this.cur != null) {
this.held = true;
this.heldPlaying = isPlaying() || this.playWhenReady;
this.heldPos = position();
tickListen();
releasePlayers();
if (this.spectrum != null) {
this.spectrum.stop();
}
notifyState();
}
}
public void resumeAfterEdit() {
if (this.held) {
this.held = false;
if (this.index >= 0 && this.index < this.queue.size()) {
long j = this.listenedMs;
boolean z = this.scrobbled;
boolean z2 = this.countedPlay;
long j2 = this.startedSec;
load(this.index, this.heldPlaying, this.heldPos);
this.listenedMs = j;
this.scrobbled = z;
this.countedPlay = z2;
this.startedSec = j2;
return;
}
return;
}
prepareNext();
}
public void songEdited() {
Song songCurrent = current();
if (songCurrent != null) {
loadArtAndLyrics(songCurrent);
}
refreshUi();
notifyQueue();
}
/* JADX INFO: Access modifiers changed from: private */
public void notifyTrack() {
updateSession();
updateNotification();
Widgets.updateAll(this);
Iterator<Listener> it = this.listeners.iterator();
while (it.hasNext()) {
it.next().onTrackChanged();
}
}
/* JADX INFO: Access modifiers changed from: private */
public void notifyState() {
updateSession();
updateNotification();
Widgets.updateAll(this);
Iterator<Listener> it = this.listeners.iterator();
while (it.hasNext()) {
it.next().onStateChanged();
}
}
private void notifyQueue() {
updateSessionQueue();
Iterator<Listener> it = this.listeners.iterator();
while (it.hasNext()) {
it.next().onQueueChanged();
}
}
public void refreshUi() {
updateSession();
updateNotification();
Widgets.updateAll(this);
Iterator<Listener> it = this.listeners.iterator();
while (it.hasNext()) {
it.next().onStateChanged();
}
}
/* JADX INFO: Access modifiers changed from: private */
public void updateSession() {
int i;
Song songCurrent = current();
MediaMetadata.Builder builder = new MediaMetadata.Builder();
if (songCurrent != null) {
builder.putString("android.media.metadata.TITLE", songCurrent.displayTitle());
builder.putString("android.media.metadata.ARTIST", songCurrent.displayArtist());
builder.putString("android.media.metadata.ALBUM", songCurrent.album);
builder.putString("android.media.metadata.ALBUM_ARTIST", songCurrent.albumArtist.length() > 0 ? songCurrent.albumArtist : songCurrent.displayArtist());
builder.putString("android.media.metadata.MEDIA_ID", songCurrent.key());
builder.putLong("android.media.metadata.DURATION", duration());
if (songCurrent.track > 0) {
builder.putLong("android.media.metadata.TRACK_NUMBER", songCurrent.track);
}
if (songCurrent.year > 0) {
builder.putLong("android.media.metadata.YEAR", songCurrent.year);
}
builder.putLong("android.media.metadata.NUM_TRACKS", this.queue.size());
if (this.art != null) {
builder.putBitmap("android.media.metadata.ALBUM_ART", this.art);
}
}
this.session.setMetadata(builder.build());
if (isPlaying()) {
i = 3;
} else if (isLoading()) {
i = 6;
} else {
i = songCurrent == null ? 0 : 2;
}
PlaybackState.Builder activeQueueItemId = new PlaybackState.Builder().setActions(5943L).setState(i, position(), isPlaying() ? 1.0f : 0.0f, SystemClock.elapsedRealtime()).setActiveQueueItemId(this.index);
if (this.shuffle) {
}
activeQueueItemId.addCustomAction(new PlaybackState.CustomAction.Builder(ACT_SHUFFLE, "Shuffle", R.drawable.ic_shuffle).build());
activeQueueItemId.addCustomAction(new PlaybackState.CustomAction.Builder(ACT_REPEAT, "Repeat", this.repeat == 2 ? R.drawable.ic_repeat_one : R.drawable.ic_repeat).build());
this.session.setPlaybackState(activeQueueItemId.build());
if (songCurrent == null || this.session.isActive()) {
return;
}
this.session.setActive(true);
}
private void updateSessionQueue() {
ArrayList arrayList = new ArrayList();
int iMax = Math.max(0, this.index - 20);
int iMin = Math.min(this.queue.size(), iMax + 100);
for (int i = iMax; i < iMin; i++) {
Song song = this.queue.get(i);
arrayList.add(new MediaSession.QueueItem(new MediaDescription.Builder().setMediaId(song.key()).setTitle(song.displayTitle()).setSubtitle(song.displayArtist()).build(), i));
}
this.session.setQueue(arrayList);
this.session.setQueueTitle("Queue");
}
private PendingIntent svcIntent(String str, int i) {
Intent action = new Intent(this, (Class<?>) MusicService.class).setAction(str);
if (Build.VERSION.SDK_INT < 26 || ACT_STOP.equals(str)) {
return PendingIntent.getService(this, i, action, 201326592);
}
action.putExtra(EXTRA_FG, true);
return PendingIntent.getForegroundService(this, i, action, 201326592);
}
public PendingIntent actionIntent(String str, int i) {
return svcIntent(str, i);
}
Notification buildNotification() {
Song songCurrent = current();
Notification.Builder builder = Build.VERSION.SDK_INT >= 26 ? new Notification.Builder(this, App.CHANNEL) : new Notification.Builder(this);
boolean z = isPlaying() || isLoading();
builder.setSmallIcon(R.drawable.ic_music_note).setContentTitle(songCurrent == null ? "Mulberry" : songCurrent.displayTitle()).setContentText(songCurrent == null ? FrameBodyCOMM.DEFAULT : songCurrent.displayArtist()).setSubText(songCurrent == null ? null : songCurrent.album).setLargeIcon(this.art).setVisibility(1).setShowWhen(false).setOnlyAlertOnce(true).setOngoing(z).setColor(App.I.palette.primary).setContentIntent(this.session.getController().getSessionActivity()).setDeleteIntent(PendingIntent.getService(this, 20, new Intent(this, (Class<?>) MusicService.class).setAction(ACT_STOP), 67108864));
builder.addAction(new Notification.Action.Builder(Icon.createWithResource(this, PlayStats.fav(songCurrent == null ? new Song() : songCurrent) ? R.drawable.ic_favorite_fill : R.drawable.ic_favorite), "Favourite", svcIntent(ACT_FAV, 15)).build());
builder.addAction(new Notification.Action.Builder(Icon.createWithResource(this, R.drawable.ic_skip_previous_fill), "Previous", svcIntent(ACT_PREV, 11)).build());
builder.addAction(new Notification.Action.Builder(Icon.createWithResource(this, z ? R.drawable.ic_pause_fill : R.drawable.ic_play_arrow_fill), z ? "Pause" : "Play", svcIntent(ACT_TOGGLE, 12)).build());
builder.addAction(new Notification.Action.Builder(Icon.createWithResource(this, R.drawable.ic_skip_next_fill), "Next", svcIntent(ACT_NEXT, 13)).build());
builder.addAction(new Notification.Action.Builder(Icon.createWithResource(this, R.drawable.ic_close), "Close", PendingIntent.getService(this, 14, new Intent(this, (Class<?>) MusicService.class).setAction(ACT_STOP), 67108864)).build());
builder.setStyle(new Notification.MediaStyle().setMediaSession(this.session.getSessionToken()).setShowActionsInCompactView(1, 2, 3));
if (Build.VERSION.SDK_INT >= 31) {
builder.setForegroundServiceBehavior(1);
}
return builder.build();
}
/* JADX INFO: Access modifiers changed from: private */
public void updateNotification() {
NotificationManager notificationManager;
if (current() != null) {
if ((this.notifShown || this.foreground || this.playWhenReady) && (notificationManager = (NotificationManager) getSystemService("notification")) != null) {
try {
notificationManager.notify(7, buildNotification());
} catch (Exception e) {
}
}
}
}
private void goForeground(boolean z) {
if (!this.foreground || z) {
try {
Notification notificationBuildNotification = buildNotification();
if (Build.VERSION.SDK_INT >= 29) {
startForeground(7, notificationBuildNotification, 2);
} else {
startForeground(7, notificationBuildNotification);
}
this.foreground = true;
this.notifShown = true;
return;
} catch (Exception e) {
updateNotification();
return;
}
}
updateNotification();
}
/* JADX INFO: Access modifiers changed from: private */
public void stopFg(boolean z) {
if (this.foreground) {
if (Build.VERSION.SDK_INT >= 24) {
stopForeground(z ? 1 : 2);
} else {
stopForeground(z);
}
this.foreground = false;
}
if (current() == null) {
NotificationManager notificationManager = (NotificationManager) getSystemService("notification");
if (notificationManager != null) {
notificationManager.cancel(7);
return;
}
return;
}
if (!z) {
updateNotification();
}
}
/* JADX INFO: Access modifiers changed from: private */
public File queueFile() {
return new File(getFilesDir(), "queue.json");
}
/* JADX INFO: Access modifiers changed from: private */
public void saveQueueLater() {
App.MAIN.removeCallbacks(this.saveLater);
App.MAIN.postDelayed(this.saveLater, 2000L);
}
void savePosition() {
App.I.prefs.raw().edit().putInt("q_index", this.index).putLong("q_pos", position()).apply();
}
void saveQueue() {
savePosition();
final ArrayList arrayList = new ArrayList(this.queue);
final ArrayList arrayList2 = new ArrayList(this.original);
final int i = this.index;
final long jPosition = position();
App.IO.execute(new Runnable() { // from class: com.mulberry.player.MusicService.23
@Override // java.lang.Runnable
public void run() {
try {
JSONObject jSONObject = new JSONObject();
JSONArray jSONArray = new JSONArray();
Iterator it = arrayList.iterator();
while (it.hasNext()) {
jSONArray.put(((Song) it.next()).toJson());
}
jSONObject.put("q", jSONArray);
if (MusicService.this.shuffle) {
IdentityHashMap identityHashMap = new IdentityHashMap();
for (int i2 = 0; i2 < arrayList.size(); i2++) {
if (!identityHashMap.containsKey(arrayList.get(i2))) {
identityHashMap.put((Song) arrayList.get(i2), Integer.valueOf(i2));
}
}
JSONArray jSONArray2 = new JSONArray();
Iterator it2 = arrayList2.iterator();
while (it2.hasNext()) {
Integer num = (Integer) identityHashMap.get((Song) it2.next());
jSONArray2.put(num == null ? -1 : num.intValue());
}
jSONObject.put("o", jSONArray2);
}
jSONObject.put("i", i);
jSONObject.put("pos", jPosition);
synchronized (MusicService.class) {
try {
File file = new File(MusicService.this.queueFile().getPath() + ".tmp");
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(jSONObject.toString().getBytes("UTF-8"));
fileOutputStream.close();
file.renameTo(MusicService.this.queueFile());
} catch (Throwable th) {
throw th;
}
}
} catch (Exception e) {
}
}
});
}
private void restoreQueue() {
try {
File fileQueueFile = queueFile();
if (fileQueueFile.exists()) {
FileInputStream fileInputStream = new FileInputStream(fileQueueFile);
JSONObject jSONObject = new JSONObject(new String(Net.readAll(fileInputStream), "UTF-8"));
fileInputStream.close();
JSONArray jSONArray = jSONObject.getJSONArray("q");
ArrayList arrayList = new ArrayList();
for (int i = 0; i < jSONArray.length(); i++) {
arrayList.add(Playlists.relink(Song.fromJson(jSONArray.getJSONObject(i))));
}
ArrayList arrayList2 = new ArrayList(arrayList);
JSONArray jSONArrayOptJSONArray = jSONObject.optJSONArray("o");
if (jSONArrayOptJSONArray != null && jSONArrayOptJSONArray.length() == arrayList.size()) {
ArrayList arrayList3 = new ArrayList();
for (int i2 = 0; i2 < jSONArrayOptJSONArray.length(); i2++) {
int i3 = jSONArrayOptJSONArray.getInt(i2);
if (i3 >= 0 && i3 < arrayList.size()) {
arrayList3.add((Song) arrayList.get(i3));
}
}
arrayList2 = arrayList3.size() != arrayList.size() ? new ArrayList(arrayList) : arrayList3;
}
this.queue = arrayList;
this.original = arrayList2;
int iMin = App.I.prefs.getInt("q_index", -1);
if (iMin < 0 || iMin >= arrayList.size()) {
iMin = Math.min(jSONObject.optInt("i", 0), arrayList.size() - 1);
}
this.index = iMin;
long jOptLong = App.I.prefs.getLong("q_pos", -1L);
if (!App.I.prefs.getBool(Prefs.RESUME, true)) {
jOptLong = 0;
} else if (jOptLong < 0) {
jOptLong = jSONObject.optLong("pos", 0L);
}
this.lastSavedPos = jOptLong;
if (this.index >= 0) {
loadArtAndLyrics(current());
updateSessionQueue();
}
}
} catch (Exception e) {
}
}
public long resumePosition() {
return this.cur == null ? this.lastSavedPos : position();
}
private class SessionCb extends MediaSession.Callback {
private SessionCb() {
}
@Override // android.media.session.MediaSession.Callback
public void onPlay() {
MusicService.this.play();
}
@Override // android.media.session.MediaSession.Callback
public void onPause() {
MusicService.this.pause();
}
@Override // android.media.session.MediaSession.Callback
public void onSkipToNext() {
MusicService.this.next();
}
@Override // android.media.session.MediaSession.Callback
public void onSkipToPrevious() {
MusicService.this.prev();
}
@Override // android.media.session.MediaSession.Callback
public void onStop() {
MusicService.this.pause();
}
@Override // android.media.session.MediaSession.Callback
public void onSeekTo(long j) {
MusicService.this.seek(j);
}
@Override // android.media.session.MediaSession.Callback
public void onSkipToQueueItem(long j) {
MusicService.this.jump((int) j);
}
@Override // android.media.session.MediaSession.Callback
public void onCustomAction(String str, Bundle bundle) {
MusicService.this.handleAction(str);
}
@Override // android.media.session.MediaSession.Callback
public void onPlayFromMediaId(String str, Bundle bundle) {
MusicService.this.playMediaId(str);
}
@Override // android.media.session.MediaSession.Callback
public void onPlayFromSearch(String str, Bundle bundle) {
List<Song> listSearch = (str == null || str.length() == 0) ? App.I.library.songs : App.I.library.search(str);
if (!listSearch.isEmpty()) {
MusicService.this.playList(listSearch, 0);
}
}
}
@Override // android.service.media.MediaBrowserService
public MediaBrowserService.BrowserRoot onGetRoot(String str, int i, Bundle bundle) {
return new MediaBrowserService.BrowserRoot("root", null);
}
@Override // android.service.media.MediaBrowserService
public void onLoadChildren(String str, MediaBrowserService.Result<List<MediaBrowser.MediaItem>> result) {
ArrayList arrayList = new ArrayList();
Library library = App.I.library;
if ("root".equals(str)) {
arrayList.add(browsable("shuffle_all", "Shuffle all", library.songs.size() + " songs", true));
arrayList.add(browsable("albums", "Albums", null, false));
arrayList.add(browsable("artists", "Artists", null, false));
arrayList.add(browsable("playlists", "Playlists", null, false));
} else if ("albums".equals(str) || "artists".equals(str)) {
List<Library.Group> list = "albums".equals(str) ? library.albums : library.artists;
for (int i = 0; i < list.size() && i < 500; i++) {
arrayList.add(browsable(str + "/" + i, list.get(i).title, list.get(i).subtitle, false));
}
} else if ("playlists".equals(str)) {
List<Playlists.PL> listAll = Playlists.all();
for (int i2 = 0; i2 < listAll.size(); i2++) {
arrayList.add(browsable("pl/" + i2, listAll.get(i2).name, listAll.get(i2).songs.size() + " songs", false));
}
} else {
List<Song> listSongsFor = songsFor(str);
for (int i3 = 0; i3 < listSongsFor.size() && i3 < 500; i3++) {
Song song = listSongsFor.get(i3);
arrayList.add(new MediaBrowser.MediaItem(new MediaDescription.Builder().setMediaId(str + "#" + i3).setTitle(song.displayTitle()).setSubtitle(song.displayArtist()).build(), 2));
}
}
result.sendResult(arrayList);
}
private MediaBrowser.MediaItem browsable(String str, String str2, String str3, boolean z) {
return new MediaBrowser.MediaItem(new MediaDescription.Builder().setMediaId(str).setTitle(str2).setSubtitle(str3).build(), z ? 2 : 1);
}
// Rewritten by hand from the bytecode: the decompiler could not rebuild this method.
private List<Song> songsFor(String str) {
Library library = App.I.library;
try {
if (str.startsWith("albums/")) {
return library.albums.get(Integer.parseInt(str.substring(7))).songs;
}
if (str.startsWith("artists/")) {
return library.artists.get(Integer.parseInt(str.substring(8))).songs;
}
if (str.startsWith("pl/")) {
return ((Playlists.PL) Playlists.all().get(Integer.parseInt(str.substring(3)))).songs;
}
} catch (Exception e) {
}
return new ArrayList<>();
}
/* JADX INFO: Access modifiers changed from: private */
public void playMediaId(String str) {
if (str != null) {
if (!"shuffle_all".equals(str)) {
int iLastIndexOf = str.lastIndexOf(35);
if (iLastIndexOf > 0) {
try {
playList(songsFor(str.substring(0, iLastIndexOf)), Integer.parseInt(str.substring(iLastIndexOf + 1)));
return;
} catch (Exception e) {
return;
}
}
playList(songsFor(str), 0);
return;
}
playShuffled(App.I.library.songs);
}
}
public static void ensureStarted(Context context) {
Intent intent = new Intent(context, (Class<?>) MusicService.class);
try {
context.startService(intent);
} catch (Exception e) {
if (Build.VERSION.SDK_INT >= 26) {
try {
context.startForegroundService(intent.putExtra(EXTRA_FG, true));
} catch (Exception e2) {
}
}
}
}
public static ComponentName component(Context context) {
return new ComponentName(context, (Class<?>) MusicService.class);
}
}