v0.62.0: andTunes 0.4.0 — speakers (AirPlay, Chromecast), a list for a menu, icon pills, full-screen art
Now Playing: tap the art for it full screen, the title or artist line for its album; shuffle, repeat and a new speakers button are icon pills. The main menu is a list (Now Playing on top, Settings at the bottom, six rows to a screen). The speakers button lists this Rabbit plus every AirPlay speaker and Chromecast on the Wi-Fi: AirPlayRemote is the desktop's RAOP sender in Java (verified from the R1 against shairport-sync), CastRemote speaks the Cast protocol directly to the Default Media Receiver and serves the file over HTTP (not yet tried on a real Chromecast).
This commit is contained in:
@@ -11,6 +11,12 @@
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- Speakers: finding them (mDNS), talking to them, staying awake while
|
||||
a song streams from here to one. -->
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||
|
||||
<application
|
||||
android:label="andTunes"
|
||||
@@ -34,6 +40,10 @@
|
||||
<activity android:name=".NowPlayingActivity" android:exported="false"
|
||||
android:launchMode="singleTop" />
|
||||
|
||||
<activity android:name=".SettingsActivity" android:exported="false" />
|
||||
|
||||
<activity android:name=".SpeakersActivity" android:exported="false" />
|
||||
|
||||
<service android:name=".PlaybackService" android:exported="false"
|
||||
android:foregroundServiceType="mediaPlayback" />
|
||||
</application>
|
||||
|
||||
@@ -0,0 +1,765 @@
|
||||
package me.teafry.andtunes;
|
||||
|
||||
import android.media.MediaCodec;
|
||||
import android.media.MediaExtractor;
|
||||
import android.media.MediaFormat;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* AirPlay 1 (RAOP) playback: the desktop's lintunes/airplay/raop.py in Java,
|
||||
* which reproduces libraop's RAOP client — what Music Assistant's cliairplay
|
||||
* plays third-party speakers (a WiiM) with:
|
||||
*
|
||||
* <ul>
|
||||
* <li>one RTSP session: auth-setup when {@code et} lists 4, ANNOUNCE
|
||||
* AppleLossless, SETUP, RECORD carrying RTP-Info, no FLUSH before audio;
|
||||
* OPTIONS every 25 s; pause and seek are FLUSH + a fresh start;
|
||||
* <li>a 2 s buffer ({@link #LATENCY_FRAMES} plus the 11025 every receiver
|
||||
* adds), RTP timestamps on the NTP clock, a start {@link #LEAD_MS} out so
|
||||
* the first two seconds go at once;
|
||||
* <li>the NTP timing responder, resends from a 512-packet backlog, a sync
|
||||
* packet a second.
|
||||
* </ul>
|
||||
*
|
||||
* Audio is decoded here (MediaExtractor + MediaCodec, so whatever the Rabbit
|
||||
* plays), made 44.1 kHz 16-bit stereo, and sent as uncompressed ALAC frames.
|
||||
*/
|
||||
final class AirPlayRemote implements Remote {
|
||||
static final int FRAMES = 352, RATE = 44100;
|
||||
static final int LATENCY_MIN = 11025, LATENCY_FRAMES = 88200;
|
||||
static final int LEAD_MS = 200;
|
||||
private static final int BACKLOG = 512;
|
||||
private static final String UA = "iTunes/7.6.2 (Windows; N;)";
|
||||
private static final long KEEPALIVE_MS = 25000;
|
||||
|
||||
private final String name, host;
|
||||
private final int port;
|
||||
private final Map<String, String> txt;
|
||||
private final Handler main = new Handler(Looper.getMainLooper());
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private Events events;
|
||||
|
||||
// RTSP
|
||||
private Socket rtsp;
|
||||
private InputStream rtspIn;
|
||||
private OutputStream rtspOut;
|
||||
private String url, session, localIp;
|
||||
private int cseq;
|
||||
private final String clientInstance, dacpId, activeRemote;
|
||||
private final Object rtspLock = new Object();
|
||||
|
||||
// UDP
|
||||
private DatagramSocket timing, control, audioSock;
|
||||
private InetAddress peer;
|
||||
private int serverPort, controlPort;
|
||||
|
||||
// Stream state (guarded by this)
|
||||
private int latency = LATENCY_FRAMES;
|
||||
private long headTs;
|
||||
private int seq;
|
||||
private final int ssrc;
|
||||
private boolean streaming, first;
|
||||
private final byte[][] backlog = new byte[BACKLOG][];
|
||||
private final int[] backlogSeq = new int[BACKLOG];
|
||||
|
||||
private volatile boolean closed;
|
||||
private volatile float volume = 0.5f;
|
||||
private long lastKeepalive;
|
||||
|
||||
// The current song (main thread owns these).
|
||||
private Library.Track track;
|
||||
private Streamer streamer;
|
||||
private int startMs; // where the current stretch began
|
||||
private long firstSentAt; // elapsedRealtime of its first packet, 0 = none
|
||||
private int framesSent;
|
||||
private int pausedAt = -1; // position while paused
|
||||
|
||||
AirPlayRemote(String name, String host, int port, Map<String, String> txt) {
|
||||
this.name = name;
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
this.txt = txt != null ? txt : new HashMap<>();
|
||||
byte[] b = new byte[8];
|
||||
random.nextBytes(b);
|
||||
clientInstance = hex(b);
|
||||
random.nextBytes(b);
|
||||
dacpId = hex(b).toUpperCase(Locale.ROOT);
|
||||
activeRemote = String.valueOf(random.nextInt() & 0x7FFFFFFF);
|
||||
ssrc = random.nextInt();
|
||||
seq = random.nextInt(1 << 16);
|
||||
}
|
||||
|
||||
@Override public String name() { return name; }
|
||||
|
||||
@Override public void setEvents(Events e) { events = e; }
|
||||
|
||||
// ---- clocks ----
|
||||
|
||||
static long ntpNow() {
|
||||
long ms = System.currentTimeMillis();
|
||||
long sec = ms / 1000, frac = ((ms % 1000) << 32) / 1000;
|
||||
return (sec << 32) | frac;
|
||||
}
|
||||
|
||||
static long ntp2ts(long ntp) { return ((ntp >>> 16) * RATE) >>> 16; }
|
||||
|
||||
static long ts2ntp(long ts) { return ((ts << 16) / RATE) << 16; }
|
||||
|
||||
int totalLatency() { return latency + LATENCY_MIN; }
|
||||
|
||||
// ---- connecting (blocking; off the main thread) ----
|
||||
|
||||
void connect() throws IOException {
|
||||
peer = InetAddress.getByName(host);
|
||||
rtsp = new Socket();
|
||||
rtsp.connect(new InetSocketAddress(peer, port), 8000);
|
||||
rtsp.setSoTimeout(10000);
|
||||
rtspIn = new BufferedInputStream(rtsp.getInputStream());
|
||||
rtspOut = rtsp.getOutputStream();
|
||||
localIp = rtsp.getLocalAddress().getHostAddress();
|
||||
String sid = String.format(Locale.ROOT, "%010d", (random.nextLong() >>> 1) % 10000000000L);
|
||||
url = "rtsp://" + host + "/" + sid;
|
||||
try {
|
||||
String et = txt.getOrDefault("et", "");
|
||||
if (et.contains("4")) {
|
||||
// 0x01 + a 32-byte public key; libraop carries on whatever the
|
||||
// answer, and so does this.
|
||||
byte[] body = new byte[33];
|
||||
random.nextBytes(body);
|
||||
body[0] = 1;
|
||||
request("POST", "/auth-setup", null, "application/octet-stream", body, false);
|
||||
}
|
||||
timing = new DatagramSocket(0, InetAddress.getByName(localIp));
|
||||
daemon(this::timingLoop, "andTunes-raop-timing");
|
||||
String sdp = "v=0\r\n"
|
||||
+ "o=iTunes " + sid + " 0 IN IP4 " + localIp + "\r\n"
|
||||
+ "s=iTunes\r\n"
|
||||
+ "c=IN IP4 " + host + "\r\n"
|
||||
+ "t=0 0\r\n"
|
||||
+ "m=audio 0 RTP/AVP 96\r\n"
|
||||
+ "a=rtpmap:96 AppleLossless\r\n"
|
||||
+ "a=fmtp:96 " + FRAMES + " 0 16 40 10 14 2 255 0 0 " + RATE + "\r\n";
|
||||
request("ANNOUNCE", null, null, "application/sdp",
|
||||
sdp.getBytes(StandardCharsets.UTF_8), true);
|
||||
control = new DatagramSocket(0, InetAddress.getByName(localIp));
|
||||
audioSock = new DatagramSocket(0, InetAddress.getByName(localIp));
|
||||
Map<String, String> h = request("SETUP", null, new String[] {"Transport",
|
||||
"RTP/AVP/UDP;unicast;interleaved=0-1;mode=record;control_port="
|
||||
+ control.getLocalPort() + ";timing_port=" + timing.getLocalPort()},
|
||||
null, null, true);
|
||||
session = h.get("session");
|
||||
for (String part : h.getOrDefault("transport", "").split(";")) {
|
||||
String[] kv = part.split("=", 2);
|
||||
if (kv.length < 2) continue;
|
||||
try {
|
||||
if (kv[0].trim().equals("server_port")) serverPort = Integer.parseInt(kv[1].trim());
|
||||
if (kv[0].trim().equals("control_port")) controlPort = Integer.parseInt(kv[1].trim());
|
||||
} catch (NumberFormatException ignored) { }
|
||||
}
|
||||
if (session == null || serverPort == 0 || controlPort == 0) {
|
||||
throw new IOException("the speaker's SETUP answer had no ports");
|
||||
}
|
||||
h = request("RECORD", null, new String[] {"Range", "npt=0-", "RTP-Info",
|
||||
"seq=" + ((seq + 1) & 0xFFFF) + ";rtptime=" + (ntp2ts(ntpNow()) & 0xFFFFFFFFL)},
|
||||
null, null, true);
|
||||
try {
|
||||
latency = Math.max(latency, Integer.parseInt(h.getOrDefault("audio-latency", "0")));
|
||||
} catch (NumberFormatException ignored) { }
|
||||
lastKeepalive = SystemClock.elapsedRealtime();
|
||||
daemon(this::controlLoop, "andTunes-raop-control");
|
||||
sendVolume();
|
||||
} catch (IOException e) {
|
||||
shutdown();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> request(String method, String path, String[] headers,
|
||||
String type, byte[] body, boolean mustSucceed)
|
||||
throws IOException {
|
||||
synchronized (rtspLock) {
|
||||
if (rtsp == null || rtsp.isClosed()) throw new IOException("not connected");
|
||||
StringBuilder m = new StringBuilder();
|
||||
m.append(method).append(' ').append(path != null ? path : url).append(" RTSP/1.0\r\n");
|
||||
for (int i = 0; headers != null && i + 1 < headers.length; i += 2) {
|
||||
m.append(headers[i]).append(": ").append(headers[i + 1]).append("\r\n");
|
||||
}
|
||||
if (type != null && body != null) {
|
||||
m.append("Content-Type: ").append(type).append("\r\n");
|
||||
m.append("Content-Length: ").append(body.length).append("\r\n");
|
||||
}
|
||||
m.append("CSeq: ").append(++cseq).append("\r\n");
|
||||
m.append("User-Agent: ").append(UA).append("\r\n");
|
||||
m.append("Client-Instance: ").append(clientInstance).append("\r\n");
|
||||
m.append("DACP-ID: ").append(dacpId).append("\r\n");
|
||||
m.append("Active-Remote: ").append(activeRemote).append("\r\n");
|
||||
if (session != null) m.append("Session: ").append(session).append("\r\n");
|
||||
m.append("\r\n");
|
||||
rtspOut.write(m.toString().getBytes(StandardCharsets.ISO_8859_1));
|
||||
if (body != null) rtspOut.write(body);
|
||||
rtspOut.flush();
|
||||
String status = readLine();
|
||||
if (status == null) throw new IOException("the speaker closed the connection");
|
||||
String[] parts = status.split(" ");
|
||||
int code = parts.length > 1 ? parseInt(parts[1]) : 0;
|
||||
Map<String, String> h = new HashMap<>();
|
||||
String line;
|
||||
while ((line = readLine()) != null && !line.isEmpty()) {
|
||||
int colon = line.indexOf(':');
|
||||
if (colon > 0) {
|
||||
h.put(line.substring(0, colon).trim().toLowerCase(Locale.ROOT),
|
||||
line.substring(colon + 1).trim());
|
||||
}
|
||||
}
|
||||
int length = parseInt(h.getOrDefault("content-length", "0"));
|
||||
for (int i = 0; i < length; i++) if (rtspIn.read() < 0) break;
|
||||
if (mustSucceed && code != 200) {
|
||||
throw new IOException("the speaker refused " + method + " (" + code + ")");
|
||||
}
|
||||
return h;
|
||||
}
|
||||
}
|
||||
|
||||
private String readLine() throws IOException {
|
||||
ByteArrayOutputStream b = new ByteArrayOutputStream();
|
||||
int c;
|
||||
while ((c = rtspIn.read()) >= 0) {
|
||||
if (c == '\n') break;
|
||||
if (c != '\r') b.write(c);
|
||||
}
|
||||
if (c < 0 && b.size() == 0) return null;
|
||||
return b.toString("ISO-8859-1");
|
||||
}
|
||||
|
||||
// ---- Remote ----
|
||||
|
||||
@Override public void load(Library.Track t, int startMs, boolean play) {
|
||||
track = t;
|
||||
pausedAt = startMs;
|
||||
stopStreamer(true);
|
||||
if (play) {
|
||||
startStreamer(startMs, true);
|
||||
} else {
|
||||
// Nothing to fetch ahead: AirPlay has no "loaded but paused".
|
||||
main.post(() -> { if (!closed && events != null) events.remoteReady(); });
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void play() {
|
||||
if (track == null || streamer != null) return;
|
||||
startStreamer(Math.max(0, pausedAt), false);
|
||||
}
|
||||
|
||||
@Override public void pause() {
|
||||
pausedAt = position();
|
||||
stopStreamer(true);
|
||||
}
|
||||
|
||||
@Override public void seekTo(int ms) {
|
||||
pausedAt = ms;
|
||||
if (streamer != null) {
|
||||
stopStreamer(true);
|
||||
startStreamer(ms, false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override public int position() {
|
||||
if (streamer == null) return Math.max(0, pausedAt);
|
||||
if (firstSentAt == 0) return startMs;
|
||||
long heard = SystemClock.elapsedRealtime() - firstSentAt - LEAD_MS;
|
||||
long sent = framesSent * 1000L / RATE;
|
||||
return startMs + (int) Math.max(0, Math.min(heard, sent));
|
||||
}
|
||||
|
||||
@Override public void setVolume(float level) {
|
||||
volume = Math.max(0f, Math.min(1f, level));
|
||||
new Thread(this::sendVolume, "andTunes-raop-volume").start();
|
||||
}
|
||||
|
||||
@Override public float volume() { return volume; }
|
||||
|
||||
private void sendVolume() {
|
||||
// 0..1 linear onto −30..0 dB, 0 muted: pyatv's and libraop's scale.
|
||||
float v = volume;
|
||||
double db = v <= 0 ? -144.0 : -30.0 + 30.0 * v;
|
||||
try {
|
||||
request("SET_PARAMETER", null, null, "text/parameters",
|
||||
String.format(Locale.ROOT, "volume: %f\r\n", db)
|
||||
.getBytes(StandardCharsets.US_ASCII), false);
|
||||
} catch (IOException e) {
|
||||
lost("the connection dropped");
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void close() {
|
||||
if (closed) return;
|
||||
stopStreamer(false);
|
||||
closed = true;
|
||||
new Thread(() -> {
|
||||
try {
|
||||
long head;
|
||||
int s;
|
||||
synchronized (this) { head = headTs; s = seq; }
|
||||
request("FLUSH", null, new String[] {"RTP-Info",
|
||||
"seq=" + ((s + 1) & 0xFFFF) + ";rtptime=" + ((head + 1) & 0xFFFFFFFFL)},
|
||||
null, null, false);
|
||||
request("TEARDOWN", null, null, null, null, false);
|
||||
} catch (IOException ignored) {
|
||||
} finally {
|
||||
shutdown();
|
||||
}
|
||||
}, "andTunes-raop-close").start();
|
||||
}
|
||||
|
||||
private void shutdown() {
|
||||
closed = true;
|
||||
for (DatagramSocket d : new DatagramSocket[] {timing, control, audioSock}) {
|
||||
if (d != null) d.close();
|
||||
}
|
||||
try { if (rtsp != null) rtsp.close(); } catch (IOException ignored) { }
|
||||
}
|
||||
|
||||
private void lost(String why) {
|
||||
if (closed) return;
|
||||
main.post(() -> {
|
||||
if (closed) return;
|
||||
stopStreamer(false);
|
||||
shutdown();
|
||||
if (events != null) events.remoteLost(why);
|
||||
});
|
||||
}
|
||||
|
||||
// ---- one stretch of a song ----
|
||||
|
||||
private void startStreamer(int fromMs, boolean announceReady) {
|
||||
startMs = fromMs;
|
||||
firstSentAt = 0;
|
||||
framesSent = 0;
|
||||
streamer = new Streamer(track, fromMs, announceReady);
|
||||
streamer.start();
|
||||
}
|
||||
|
||||
/** Stop the stretch; {@code flush}: and drop what the speaker queued. */
|
||||
private void stopStreamer(boolean flush) {
|
||||
Streamer s = streamer;
|
||||
streamer = null;
|
||||
if (s == null) return;
|
||||
s.cancel();
|
||||
boolean wasStreaming;
|
||||
long head;
|
||||
int sq;
|
||||
synchronized (this) {
|
||||
wasStreaming = streaming;
|
||||
streaming = false;
|
||||
head = headTs;
|
||||
sq = seq;
|
||||
}
|
||||
if (flush && wasStreaming && !closed) {
|
||||
new Thread(() -> {
|
||||
try {
|
||||
request("FLUSH", null, new String[] {"RTP-Info",
|
||||
"seq=" + ((sq + 1) & 0xFFFF) + ";rtptime=" + ((head + 1) & 0xFFFFFFFFL)},
|
||||
null, null, false);
|
||||
} catch (IOException e) {
|
||||
lost("the connection dropped");
|
||||
}
|
||||
}, "andTunes-raop-flush").start();
|
||||
}
|
||||
}
|
||||
|
||||
private final class Streamer extends Thread {
|
||||
private final Library.Track t;
|
||||
private final int fromMs;
|
||||
private final boolean announceReady;
|
||||
private volatile boolean cancelled;
|
||||
|
||||
Streamer(Library.Track t, int fromMs, boolean announceReady) {
|
||||
super("andTunes-raop-stream");
|
||||
setDaemon(true);
|
||||
this.t = t;
|
||||
this.fromMs = fromMs;
|
||||
this.announceReady = announceReady;
|
||||
}
|
||||
|
||||
void cancel() { cancelled = true; interrupt(); }
|
||||
|
||||
@Override public void run() {
|
||||
Pcm pcm;
|
||||
try {
|
||||
pcm = new Pcm(t.file().getPath(), fromMs);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
post(() -> { if (events != null) events.remoteFailed("can't decode it"); });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
byte[] packet = new byte[FRAMES * 4];
|
||||
long lastTs = -1;
|
||||
synchronized (AirPlayRemote.this) {
|
||||
headTs = ntp2ts(ntpNow() + ts2ntp(LEAD_MS * (long) RATE / 1000)) - totalLatency();
|
||||
first = true;
|
||||
streaming = true;
|
||||
}
|
||||
sendSync(true);
|
||||
if (announceReady) post(() -> { if (events != null) events.remoteReady(); });
|
||||
while (!cancelled) {
|
||||
int got = pcm.read(packet);
|
||||
if (got <= 0) break;
|
||||
for (int i = got; i < packet.length; i++) packet[i] = 0;
|
||||
long due;
|
||||
synchronized (AirPlayRemote.this) { due = headTs + FRAMES; }
|
||||
long wait = (due - ntp2ts(ntpNow())) * 1000 / RATE;
|
||||
if (wait > 0) Thread.sleep(wait);
|
||||
if (cancelled) return;
|
||||
synchronized (AirPlayRemote.this) {
|
||||
lastTs = headTs;
|
||||
sendAudio(packet);
|
||||
}
|
||||
final int frames = got / 4;
|
||||
post(() -> {
|
||||
if (streamer != this) return;
|
||||
if (firstSentAt == 0) firstSentAt = SystemClock.elapsedRealtime();
|
||||
framesSent += frames;
|
||||
});
|
||||
}
|
||||
if (cancelled || lastTs < 0) return;
|
||||
// Until the end has been heard, then the song is over.
|
||||
// Timestamps are the wall clock counted in frames.
|
||||
long endMs = ((lastTs + FRAMES + totalLatency()) * 1000L) / RATE;
|
||||
while (!cancelled) {
|
||||
long left = endMs - System.currentTimeMillis();
|
||||
if (left <= 0) break;
|
||||
Thread.sleep(Math.min(left, 250));
|
||||
}
|
||||
if (!cancelled) post(() -> {
|
||||
if (streamer != this) return;
|
||||
streamer = null;
|
||||
pausedAt = 0;
|
||||
if (events != null) events.remoteEnded();
|
||||
});
|
||||
} catch (InterruptedException ignored) {
|
||||
} catch (IOException e) {
|
||||
if (!cancelled) lost("the connection dropped");
|
||||
} catch (RuntimeException e) {
|
||||
// MediaCodec gave up mid-song
|
||||
if (!cancelled) post(() -> {
|
||||
if (streamer != this) return;
|
||||
streamer = null;
|
||||
if (events != null) events.remoteFailed("can't decode it");
|
||||
});
|
||||
} finally {
|
||||
pcm.release();
|
||||
}
|
||||
}
|
||||
|
||||
private void post(Runnable r) { main.post(() -> { if (!closed) r.run(); }); }
|
||||
}
|
||||
|
||||
/** Under the lock: one packet of 352 frames of s16be stereo. */
|
||||
private void sendAudio(byte[] pcm) throws IOException {
|
||||
seq = (seq + 1) & 0xFFFF;
|
||||
byte[] payload = alacVerbatim(pcm);
|
||||
byte[] p = new byte[12 + payload.length];
|
||||
p[0] = (byte) 0x80;
|
||||
p[1] = (byte) (first ? 0xE0 : 0x60);
|
||||
first = false;
|
||||
p[2] = (byte) (seq >>> 8); p[3] = (byte) seq;
|
||||
putInt(p, 4, (int) headTs);
|
||||
putInt(p, 8, ssrc);
|
||||
System.arraycopy(payload, 0, p, 12, payload.length);
|
||||
backlog[seq % BACKLOG] = p;
|
||||
backlogSeq[seq % BACKLOG] = seq;
|
||||
headTs += FRAMES;
|
||||
audioSock.send(new DatagramPacket(p, p.length, peer, serverPort));
|
||||
}
|
||||
|
||||
private void sendSync(boolean isFirst) {
|
||||
byte[] p = new byte[20];
|
||||
long head;
|
||||
synchronized (this) {
|
||||
if (!streaming) return;
|
||||
head = headTs;
|
||||
}
|
||||
long ntp = ts2ntp(head);
|
||||
p[0] = (byte) (isFirst ? 0x90 : 0x80);
|
||||
p[1] = (byte) 0xD4;
|
||||
p[2] = 0; p[3] = 7;
|
||||
putInt(p, 4, (int) (head - latency));
|
||||
putInt(p, 8, (int) (ntp >>> 32));
|
||||
putInt(p, 12, (int) ntp);
|
||||
putInt(p, 16, (int) head);
|
||||
try {
|
||||
control.send(new DatagramPacket(p, p.length, peer, controlPort));
|
||||
} catch (IOException ignored) { }
|
||||
}
|
||||
|
||||
/**
|
||||
* 16-bit stereo big-endian PCM as one uncompressed ALAC frame: a 23-bit
|
||||
* channel-pair header flagged "not compressed", the samples, the 3-bit
|
||||
* end tag, zero padding (support.alac_verbatim on the desktop).
|
||||
*/
|
||||
static byte[] alacVerbatim(byte[] pcm) {
|
||||
int n = pcm.length;
|
||||
byte[] out = new byte[n + 4];
|
||||
out[0] = 0x20;
|
||||
out[1] = 0x00;
|
||||
out[2] = (byte) (0x02 | ((pcm[0] >> 7) & 1));
|
||||
for (int i = 0; i < n - 1; i++) {
|
||||
out[3 + i] = (byte) ((pcm[i] << 1) | ((pcm[i + 1] >> 7) & 1));
|
||||
}
|
||||
out[2 + n] = (byte) ((pcm[n - 1] << 1) | 1);
|
||||
out[3 + n] = (byte) 0xC0;
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- the background ----
|
||||
|
||||
private void timingLoop() {
|
||||
byte[] buf = new byte[128];
|
||||
while (!closed) {
|
||||
try {
|
||||
DatagramPacket in = new DatagramPacket(buf, buf.length);
|
||||
timing.receive(in);
|
||||
if (in.getLength() < 32) continue;
|
||||
long now = ntpNow();
|
||||
byte[] r = new byte[32];
|
||||
r[0] = buf[0];
|
||||
r[1] = (byte) (0x53 | 0x80);
|
||||
r[2] = buf[2]; r[3] = buf[3];
|
||||
System.arraycopy(buf, 24, r, 8, 8); // their send time = our reference
|
||||
putInt(r, 16, (int) (now >>> 32)); putInt(r, 20, (int) now);
|
||||
putInt(r, 24, (int) (now >>> 32)); putInt(r, 28, (int) now);
|
||||
timing.send(new DatagramPacket(r, r.length, in.getSocketAddress()));
|
||||
} catch (IOException e) {
|
||||
if (closed) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void controlLoop() {
|
||||
byte[] buf = new byte[64];
|
||||
long lastSync = 0;
|
||||
try { control.setSoTimeout(250); } catch (IOException ignored) { }
|
||||
while (!closed) {
|
||||
long now = SystemClock.elapsedRealtime();
|
||||
if (now - lastSync >= 1000) {
|
||||
lastSync = now;
|
||||
sendSync(false);
|
||||
}
|
||||
if (now - lastKeepalive >= KEEPALIVE_MS) {
|
||||
lastKeepalive = now;
|
||||
try {
|
||||
request("OPTIONS", "*", null, null, null, false);
|
||||
} catch (IOException e) {
|
||||
lost("the connection dropped");
|
||||
return;
|
||||
}
|
||||
}
|
||||
try {
|
||||
DatagramPacket in = new DatagramPacket(buf, buf.length);
|
||||
control.receive(in);
|
||||
if (in.getLength() != 8 || (buf[1] & 0x7F) != 0x55) continue;
|
||||
int firstLost = ((buf[4] & 0xFF) << 8) | (buf[5] & 0xFF);
|
||||
int count = ((buf[6] & 0xFF) << 8) | (buf[7] & 0xFF);
|
||||
for (int i = 0; i < count; i++) {
|
||||
int s = (firstLost + i) & 0xFFFF;
|
||||
byte[] p;
|
||||
synchronized (this) {
|
||||
p = backlogSeq[s % BACKLOG] == s ? backlog[s % BACKLOG] : null;
|
||||
}
|
||||
if (p == null) continue;
|
||||
byte[] r = new byte[4 + p.length];
|
||||
r[0] = (byte) 0x80; r[1] = (byte) 0xD6; r[2] = 0; r[3] = 1;
|
||||
System.arraycopy(p, 0, r, 4, p.length);
|
||||
control.send(new DatagramPacket(r, r.length, peer, controlPort));
|
||||
}
|
||||
} catch (SocketTimeoutException ignored) {
|
||||
} catch (IOException e) {
|
||||
if (closed) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- decoding ----
|
||||
|
||||
/** A song as 44.1 kHz 16-bit stereo big-endian PCM, from a position. */
|
||||
static final class Pcm {
|
||||
private final MediaExtractor extractor = new MediaExtractor();
|
||||
private MediaCodec codec;
|
||||
private final MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
|
||||
private boolean inputDone, outputDone;
|
||||
private int rate = RATE, channels = 2;
|
||||
private long skipUntilUs;
|
||||
private short[] carry = new short[0]; // decoded, not yet resampled
|
||||
private double phase; // resampler position in carry
|
||||
private final ByteArrayOutputStream ready = new ByteArrayOutputStream();
|
||||
private byte[] readyBytes = new byte[0];
|
||||
private int readyPos;
|
||||
|
||||
Pcm(String path, int fromMs) throws IOException {
|
||||
extractor.setDataSource(path);
|
||||
int track = -1;
|
||||
MediaFormat format = null;
|
||||
for (int i = 0; i < extractor.getTrackCount(); i++) {
|
||||
MediaFormat f = extractor.getTrackFormat(i);
|
||||
String mime = f.getString(MediaFormat.KEY_MIME);
|
||||
if (mime != null && mime.startsWith("audio/")) { track = i; format = f; break; }
|
||||
}
|
||||
if (track < 0) throw new IOException("no audio");
|
||||
extractor.selectTrack(track);
|
||||
if (fromMs > 0) {
|
||||
extractor.seekTo(fromMs * 1000L, MediaExtractor.SEEK_TO_PREVIOUS_SYNC);
|
||||
skipUntilUs = fromMs * 1000L;
|
||||
}
|
||||
codec = MediaCodec.createDecoderByType(format.getString(MediaFormat.KEY_MIME));
|
||||
codec.configure(format, null, null, 0);
|
||||
codec.start();
|
||||
rate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
|
||||
channels = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
|
||||
}
|
||||
|
||||
/** Fill {@code out} (352 frames); returns bytes written, 0 at the end. */
|
||||
int read(byte[] out) throws IOException {
|
||||
while (readyBytes.length - readyPos < out.length && !outputDone) step();
|
||||
int n = Math.min(out.length, readyBytes.length - readyPos);
|
||||
System.arraycopy(readyBytes, readyPos, out, 0, n);
|
||||
readyPos += n;
|
||||
return n;
|
||||
}
|
||||
|
||||
private void step() throws IOException {
|
||||
if (!inputDone) {
|
||||
int in = codec.dequeueInputBuffer(10000);
|
||||
if (in >= 0) {
|
||||
ByteBuffer b = codec.getInputBuffer(in);
|
||||
int size = extractor.readSampleData(b, 0);
|
||||
if (size < 0) {
|
||||
codec.queueInputBuffer(in, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
|
||||
inputDone = true;
|
||||
} else {
|
||||
codec.queueInputBuffer(in, 0, size, extractor.getSampleTime(), 0);
|
||||
extractor.advance();
|
||||
}
|
||||
}
|
||||
}
|
||||
int outIndex = codec.dequeueOutputBuffer(info, 10000);
|
||||
if (outIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
|
||||
MediaFormat f = codec.getOutputFormat();
|
||||
rate = f.getInteger(MediaFormat.KEY_SAMPLE_RATE);
|
||||
channels = f.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
|
||||
return;
|
||||
}
|
||||
if (outIndex < 0) return;
|
||||
ByteBuffer b = codec.getOutputBuffer(outIndex);
|
||||
short[] samples = new short[info.size / 2];
|
||||
b.position(info.offset);
|
||||
b.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(samples);
|
||||
long ptsUs = info.presentationTimeUs;
|
||||
boolean end = (info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0;
|
||||
codec.releaseOutputBuffer(outIndex, false);
|
||||
if (end) outputDone = true;
|
||||
int frames = samples.length / Math.max(1, channels);
|
||||
int skip = 0;
|
||||
if (skipUntilUs > 0 && frames > 0) {
|
||||
long endUs = ptsUs + frames * 1_000_000L / rate;
|
||||
if (endUs <= skipUntilUs) return;
|
||||
if (ptsUs < skipUntilUs) skip = (int) ((skipUntilUs - ptsUs) * rate / 1_000_000L);
|
||||
skipUntilUs = 0;
|
||||
}
|
||||
append(samples, skip, frames);
|
||||
}
|
||||
|
||||
/** Decoded frames → stereo at 44.1 kHz → s16be into the ready buffer. */
|
||||
private void append(short[] s, int skip, int frames) {
|
||||
int ch = Math.max(1, channels);
|
||||
short[] stereo = new short[(carry.length / 2 + frames - skip) * 2];
|
||||
System.arraycopy(carry, 0, stereo, 0, carry.length);
|
||||
int o = carry.length;
|
||||
for (int f = skip; f < frames; f++) {
|
||||
short l = s[f * ch], r = ch > 1 ? s[f * ch + 1] : l;
|
||||
stereo[o++] = l;
|
||||
stereo[o++] = r;
|
||||
}
|
||||
int total = stereo.length / 2;
|
||||
if (rate == RATE) {
|
||||
for (int f = 0; f < total; f++) put(stereo[2 * f], stereo[2 * f + 1]);
|
||||
carry = new short[0];
|
||||
} else {
|
||||
// Linear interpolation; a rare 48 kHz file doesn't need better.
|
||||
double step = (double) rate / RATE;
|
||||
while (phase + 1 < total) {
|
||||
int i = (int) phase;
|
||||
double frac = phase - i;
|
||||
put((short) (stereo[2 * i] * (1 - frac) + stereo[2 * i + 2] * frac),
|
||||
(short) (stereo[2 * i + 1] * (1 - frac) + stereo[2 * i + 3] * frac));
|
||||
phase += step;
|
||||
}
|
||||
int keep = (int) phase;
|
||||
carry = new short[(total - keep) * 2];
|
||||
System.arraycopy(stereo, keep * 2, carry, 0, carry.length);
|
||||
phase -= keep;
|
||||
}
|
||||
byte[] fresh = ready.toByteArray();
|
||||
ready.reset();
|
||||
byte[] merged = new byte[readyBytes.length - readyPos + fresh.length];
|
||||
System.arraycopy(readyBytes, readyPos, merged, 0, readyBytes.length - readyPos);
|
||||
System.arraycopy(fresh, 0, merged, readyBytes.length - readyPos, fresh.length);
|
||||
readyBytes = merged;
|
||||
readyPos = 0;
|
||||
}
|
||||
|
||||
private void put(short l, short r) {
|
||||
ready.write(l >> 8); ready.write(l);
|
||||
ready.write(r >> 8); ready.write(r);
|
||||
}
|
||||
|
||||
void release() {
|
||||
try { codec.stop(); } catch (Exception ignored) { }
|
||||
try { codec.release(); } catch (Exception ignored) { }
|
||||
extractor.release();
|
||||
}
|
||||
}
|
||||
|
||||
// ---- small things ----
|
||||
|
||||
private static void putInt(byte[] b, int at, int v) {
|
||||
b[at] = (byte) (v >>> 24); b[at + 1] = (byte) (v >>> 16);
|
||||
b[at + 2] = (byte) (v >>> 8); b[at + 3] = (byte) v;
|
||||
}
|
||||
|
||||
private static int parseInt(String s) {
|
||||
try { return Integer.parseInt(s.trim()); } catch (NumberFormatException e) { return 0; }
|
||||
}
|
||||
|
||||
private static String hex(byte[] b) {
|
||||
StringBuilder s = new StringBuilder();
|
||||
for (byte x : b) s.append(String.format(Locale.ROOT, "%02x", x));
|
||||
return s.toString();
|
||||
}
|
||||
|
||||
private static void daemon(Runnable r, String name) {
|
||||
Thread t = new Thread(r, name);
|
||||
t.setDaemon(true);
|
||||
t.start();
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import android.widget.TextView;
|
||||
abstract class BaseActivity extends Activity implements PlaybackService.Listener {
|
||||
protected AudioManager audio;
|
||||
private TextView nowBar;
|
||||
private static android.widget.Toast volumeToast;
|
||||
|
||||
@Override protected void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
@@ -100,8 +101,22 @@ abstract class BaseActivity extends Activity implements PlaybackService.Listener
|
||||
}
|
||||
}
|
||||
|
||||
/** One wheel detent. Volume unless the screen has something to scroll. */
|
||||
/** One wheel detent. Volume unless the screen has something to scroll —
|
||||
* the speaker's own volume while playing through one. */
|
||||
protected void onWheel(int dir) {
|
||||
PlaybackService s = PlaybackService.get();
|
||||
Remote r = s != null ? s.remote() : null;
|
||||
if (r != null) {
|
||||
float level = Math.max(0f, Math.min(1f, r.volume() + dir * 0.05f));
|
||||
r.setVolume(level);
|
||||
// One toast, rewritten: a spin of the wheel would queue dozens.
|
||||
if (volumeToast != null) volumeToast.cancel();
|
||||
volumeToast = android.widget.Toast.makeText(getApplicationContext(),
|
||||
r.name() + " volume " + Math.round(level * 100) + "%",
|
||||
android.widget.Toast.LENGTH_SHORT);
|
||||
volumeToast.show();
|
||||
return;
|
||||
}
|
||||
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
|
||||
dir > 0 ? AudioManager.ADJUST_RAISE : AudioManager.ADJUST_LOWER,
|
||||
AudioManager.FLAG_SHOW_UI);
|
||||
|
||||
@@ -0,0 +1,479 @@
|
||||
package me.teafry.andtunes;
|
||||
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSocket;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
|
||||
/**
|
||||
* Chromecast playback, speaking the Cast protocol itself: TLS to port 8009,
|
||||
* each message a length-prefixed protobuf {@code CastMessage} whose payload is
|
||||
* JSON. No Google Cast SDK — it needs AndroidX and Play Services' cast
|
||||
* framework, which andTunes' Gradle-free build doesn't link — and the
|
||||
* protocol is small: connect, heartbeat, launch the Default Media Receiver,
|
||||
* hand it a URL.
|
||||
*
|
||||
* <p>The desktop's media-receiver model (lintunes/cast): the speaker fetches
|
||||
* the original file from {@link MediaServer} on the Rabbit, bit for bit.
|
||||
* A Chromecast presents a self-signed certificate, so the TLS trusts any —
|
||||
* the same as every Cast sender that isn't Google's.
|
||||
*/
|
||||
final class CastRemote implements Remote {
|
||||
private static final String RECEIVER = "receiver-0", SENDER = "sender-0";
|
||||
private static final String NS_CONNECTION = "urn:x-cast:com.google.cast.tp.connection";
|
||||
private static final String NS_HEARTBEAT = "urn:x-cast:com.google.cast.tp.heartbeat";
|
||||
private static final String NS_RECEIVER = "urn:x-cast:com.google.cast.receiver";
|
||||
private static final String NS_MEDIA = "urn:x-cast:com.google.cast.media";
|
||||
/** Google's Default Media Receiver. */
|
||||
private static final String APP_ID = "CC1AD845";
|
||||
private static final int CONNECT_TIMEOUT_MS = 8000;
|
||||
private static final long LAUNCH_TIMEOUT_MS = 12000;
|
||||
private static final long PING_MS = 5000;
|
||||
|
||||
private final String name, host;
|
||||
private final int port;
|
||||
private final Handler main = new Handler(Looper.getMainLooper());
|
||||
private Events events;
|
||||
private SSLSocket socket;
|
||||
private OutputStream out;
|
||||
private MediaServer server;
|
||||
private String localIp;
|
||||
private volatile boolean closed;
|
||||
private final Object lock = new Object();
|
||||
|
||||
// Receiver state (reader thread writes, under lock).
|
||||
private String transportId, sessionId;
|
||||
private int requestId = 1;
|
||||
private float volume = 0.5f;
|
||||
|
||||
// Media state, main thread.
|
||||
private Integer mediaSessionId;
|
||||
private int loadRequest = -1;
|
||||
private boolean awaitingReady, loaded;
|
||||
private double reportedTime; // seconds, at reportedAt
|
||||
private long reportedAt;
|
||||
private boolean reportedPlaying;
|
||||
private Library.Track track;
|
||||
|
||||
CastRemote(String name, String host, int port) {
|
||||
this.name = name;
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
@Override public String name() { return name; }
|
||||
|
||||
@Override public void setEvents(Events e) { events = e; }
|
||||
|
||||
// ---- connecting (blocking; call off the main thread) ----
|
||||
|
||||
void connect() throws IOException {
|
||||
try {
|
||||
SSLContext tls = SSLContext.getInstance("TLS");
|
||||
tls.init(null, new TrustManager[] {new X509TrustManager() {
|
||||
@Override public void checkClientTrusted(X509Certificate[] c, String a) { }
|
||||
@Override public void checkServerTrusted(X509Certificate[] c, String a) { }
|
||||
@Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
|
||||
}}, null);
|
||||
socket = (SSLSocket) tls.getSocketFactory().createSocket();
|
||||
socket.connect(new InetSocketAddress(host, port), CONNECT_TIMEOUT_MS);
|
||||
socket.startHandshake();
|
||||
} catch (IOException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new IOException(e.getMessage());
|
||||
}
|
||||
out = socket.getOutputStream();
|
||||
localIp = socket.getLocalAddress().getHostAddress();
|
||||
server = new MediaServer();
|
||||
Thread reader = new Thread(this::readLoop, "andTunes-cast");
|
||||
reader.setDaemon(true);
|
||||
reader.start();
|
||||
send(NS_CONNECTION, RECEIVER, json("type", "CONNECT"));
|
||||
Thread ping = new Thread(this::pingLoop, "andTunes-cast-ping");
|
||||
ping.setDaemon(true);
|
||||
ping.start();
|
||||
JSONObject launch = json("type", "LAUNCH");
|
||||
put(launch, "appId", APP_ID);
|
||||
request(NS_RECEIVER, RECEIVER, launch);
|
||||
long deadline = SystemClock.elapsedRealtime() + LAUNCH_TIMEOUT_MS;
|
||||
synchronized (lock) {
|
||||
while (transportId == null && !closed) {
|
||||
long left = deadline - SystemClock.elapsedRealtime();
|
||||
if (left <= 0) break;
|
||||
try { lock.wait(left); } catch (InterruptedException e) { break; }
|
||||
}
|
||||
}
|
||||
if (transportId == null) {
|
||||
close();
|
||||
throw new IOException("it didn't start the player");
|
||||
}
|
||||
send(NS_CONNECTION, transportId, json("type", "CONNECT"));
|
||||
}
|
||||
|
||||
// ---- Remote ----
|
||||
|
||||
@Override public void load(Library.Track t, int startMs, boolean play) {
|
||||
track = t;
|
||||
loaded = false;
|
||||
awaitingReady = true;
|
||||
mediaSessionId = null;
|
||||
reportedTime = startMs / 1000.0;
|
||||
reportedAt = SystemClock.elapsedRealtime();
|
||||
reportedPlaying = false;
|
||||
File file = t.file();
|
||||
String base = "http://" + localIp + ":" + server.port();
|
||||
JSONObject meta = new JSONObject();
|
||||
put(meta, "metadataType", 3); // MusicTrackMediaMetadata
|
||||
put(meta, "title", t.title);
|
||||
put(meta, "artist", t.artistLabel());
|
||||
if (!t.album.isEmpty()) put(meta, "albumName", t.album);
|
||||
if (!t.art.isEmpty()) {
|
||||
File art = new File(Library.root(), t.art);
|
||||
if (art.isFile()) {
|
||||
JSONArray images = new JSONArray();
|
||||
images.put(json("url", base + server.register(art)));
|
||||
put(meta, "images", images);
|
||||
}
|
||||
}
|
||||
JSONObject media = new JSONObject();
|
||||
put(media, "contentId", base + server.register(file));
|
||||
put(media, "streamType", "BUFFERED");
|
||||
put(media, "contentType", MediaServer.mime(file.getName()));
|
||||
put(media, "metadata", meta);
|
||||
JSONObject msg = json("type", "LOAD");
|
||||
put(msg, "media", media);
|
||||
put(msg, "autoplay", play);
|
||||
put(msg, "currentTime", startMs / 1000.0);
|
||||
loadRequest = background(NS_MEDIA, msg);
|
||||
}
|
||||
|
||||
@Override public void play() { mediaCommand("PLAY", null); }
|
||||
|
||||
@Override public void pause() {
|
||||
reportedTime = position() / 1000.0;
|
||||
reportedAt = SystemClock.elapsedRealtime();
|
||||
reportedPlaying = false;
|
||||
mediaCommand("PAUSE", null);
|
||||
}
|
||||
|
||||
@Override public void seekTo(int ms) {
|
||||
reportedTime = ms / 1000.0;
|
||||
reportedAt = SystemClock.elapsedRealtime();
|
||||
mediaCommand("SEEK", ms / 1000.0);
|
||||
}
|
||||
|
||||
@Override public int position() {
|
||||
double t = reportedTime;
|
||||
if (reportedPlaying) t += (SystemClock.elapsedRealtime() - reportedAt) / 1000.0;
|
||||
int ms = (int) Math.round(t * 1000);
|
||||
return track != null && track.secs > 0 ? Math.min(ms, track.secs * 1000) : ms;
|
||||
}
|
||||
|
||||
@Override public void setVolume(float level) {
|
||||
volume = level;
|
||||
JSONObject msg = json("type", "SET_VOLUME");
|
||||
put(msg, "volume", json("level", (double) level));
|
||||
background(NS_RECEIVER, msg);
|
||||
}
|
||||
|
||||
@Override public float volume() { return volume; }
|
||||
|
||||
@Override public void close() {
|
||||
if (closed) return;
|
||||
String session;
|
||||
synchronized (lock) { session = sessionId; }
|
||||
Thread t = new Thread(() -> {
|
||||
try {
|
||||
if (session != null) {
|
||||
JSONObject stop = json("type", "STOP");
|
||||
put(stop, "sessionId", session);
|
||||
request(NS_RECEIVER, RECEIVER, stop);
|
||||
}
|
||||
send(NS_CONNECTION, RECEIVER, json("type", "CLOSE"));
|
||||
} catch (IOException ignored) {
|
||||
} finally {
|
||||
shutdown();
|
||||
}
|
||||
}, "andTunes-cast-close");
|
||||
t.start();
|
||||
closed = true;
|
||||
synchronized (lock) { lock.notifyAll(); }
|
||||
}
|
||||
|
||||
private void shutdown() {
|
||||
closed = true;
|
||||
try { if (socket != null) socket.close(); } catch (IOException ignored) { }
|
||||
if (server != null) server.close();
|
||||
}
|
||||
|
||||
// ---- sending ----
|
||||
|
||||
private void mediaCommand(String type, Double seekTo) {
|
||||
if (mediaSessionId == null) return;
|
||||
JSONObject msg = json("type", type);
|
||||
put(msg, "mediaSessionId", mediaSessionId);
|
||||
if (seekTo != null) put(msg, "currentTime", seekTo);
|
||||
background(NS_MEDIA, msg);
|
||||
}
|
||||
|
||||
/** Send from a worker (the main thread mustn't touch the network). */
|
||||
private int background(String ns, JSONObject msg) {
|
||||
int id;
|
||||
synchronized (lock) { id = requestId++; }
|
||||
put(msg, "requestId", id);
|
||||
String dest;
|
||||
synchronized (lock) { dest = NS_RECEIVER.equals(ns) ? RECEIVER : transportId; }
|
||||
if (dest == null) return id;
|
||||
new Thread(() -> {
|
||||
try {
|
||||
send(ns, dest, msg);
|
||||
} catch (IOException e) {
|
||||
lost("the connection dropped");
|
||||
}
|
||||
}, "andTunes-cast-send").start();
|
||||
return id;
|
||||
}
|
||||
|
||||
private void request(String ns, String dest, JSONObject msg) throws IOException {
|
||||
synchronized (lock) { put(msg, "requestId", requestId++); }
|
||||
send(ns, dest, msg);
|
||||
}
|
||||
|
||||
private void send(String ns, String dest, JSONObject payload) throws IOException {
|
||||
byte[] frame = encode(SENDER, dest, ns, payload.toString());
|
||||
synchronized (this) {
|
||||
if (out == null) throw new IOException("not connected");
|
||||
out.write(new byte[] {(byte) (frame.length >>> 24), (byte) (frame.length >>> 16),
|
||||
(byte) (frame.length >>> 8), (byte) frame.length});
|
||||
out.write(frame);
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
|
||||
private void pingLoop() {
|
||||
while (!closed) {
|
||||
try {
|
||||
Thread.sleep(PING_MS);
|
||||
if (!closed) send(NS_HEARTBEAT, RECEIVER, json("type", "PING"));
|
||||
} catch (InterruptedException e) {
|
||||
return;
|
||||
} catch (IOException e) {
|
||||
lost("the connection dropped");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- receiving ----
|
||||
|
||||
private void readLoop() {
|
||||
try {
|
||||
DataInputStream in = new DataInputStream(socket.getInputStream());
|
||||
while (!closed) {
|
||||
int length = in.readInt();
|
||||
if (length <= 0 || length > 1 << 20) throw new IOException("bad frame");
|
||||
byte[] frame = new byte[length];
|
||||
in.readFully(frame);
|
||||
String[] msg = decode(frame); // source, namespace, payload
|
||||
if (msg[2] == null) continue;
|
||||
JSONObject payload;
|
||||
try { payload = new JSONObject(msg[2]); } catch (JSONException e) { continue; }
|
||||
handle(msg[0], msg[1], payload);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
if (!closed) lost("the connection dropped");
|
||||
}
|
||||
}
|
||||
|
||||
private void handle(String source, String ns, JSONObject p) throws IOException {
|
||||
String type = p.optString("type");
|
||||
if (NS_HEARTBEAT.equals(ns)) {
|
||||
if ("PING".equals(type)) send(NS_HEARTBEAT, source, json("type", "PONG"));
|
||||
return;
|
||||
}
|
||||
if (NS_CONNECTION.equals(ns) && "CLOSE".equals(type)) {
|
||||
lost("it closed the session");
|
||||
return;
|
||||
}
|
||||
if (NS_RECEIVER.equals(ns) && "RECEIVER_STATUS".equals(type)) {
|
||||
JSONObject status = p.optJSONObject("status");
|
||||
if (status == null) return;
|
||||
JSONObject vol = status.optJSONObject("volume");
|
||||
if (vol != null && vol.has("level")) volume = (float) vol.optDouble("level", volume);
|
||||
JSONArray apps = status.optJSONArray("applications");
|
||||
JSONObject ours = null;
|
||||
for (int i = 0; apps != null && i < apps.length(); i++) {
|
||||
JSONObject a = apps.optJSONObject(i);
|
||||
if (a != null && APP_ID.equals(a.optString("appId"))) ours = a;
|
||||
}
|
||||
synchronized (lock) {
|
||||
if (ours != null) {
|
||||
if (transportId == null) {
|
||||
transportId = ours.optString("transportId", null);
|
||||
sessionId = ours.optString("sessionId", null);
|
||||
lock.notifyAll();
|
||||
}
|
||||
} else if (transportId != null) {
|
||||
// Someone else's app took the speaker over.
|
||||
main.post(() -> lost("something else is playing on it"));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!NS_MEDIA.equals(ns)) return;
|
||||
final JSONObject payload = p;
|
||||
main.post(() -> onMedia(payload));
|
||||
}
|
||||
|
||||
/** Media messages, on the main thread. */
|
||||
private void onMedia(JSONObject p) {
|
||||
if (closed) return;
|
||||
String type = p.optString("type");
|
||||
int forRequest = p.optInt("requestId", 0);
|
||||
if ("LOAD_FAILED".equals(type) || "LOAD_CANCELLED".equals(type)
|
||||
|| "INVALID_REQUEST".equals(type)) {
|
||||
if (forRequest == loadRequest && awaitingReady) {
|
||||
awaitingReady = false;
|
||||
if (events != null) events.remoteFailed("it can't play this file");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!"MEDIA_STATUS".equals(type)) return;
|
||||
JSONArray list = p.optJSONArray("status");
|
||||
if (list == null || list.length() == 0) return;
|
||||
JSONObject s = list.optJSONObject(0);
|
||||
if (s == null) return;
|
||||
if (s.has("mediaSessionId")) mediaSessionId = s.optInt("mediaSessionId");
|
||||
String state = s.optString("playerState");
|
||||
if (s.has("currentTime")) {
|
||||
reportedTime = s.optDouble("currentTime", reportedTime);
|
||||
reportedAt = SystemClock.elapsedRealtime();
|
||||
}
|
||||
reportedPlaying = "PLAYING".equals(state);
|
||||
if (awaitingReady && ("PLAYING".equals(state) || "PAUSED".equals(state)
|
||||
|| "BUFFERING".equals(state))) {
|
||||
awaitingReady = false;
|
||||
loaded = true;
|
||||
if (events != null) events.remoteReady();
|
||||
return;
|
||||
}
|
||||
if ("IDLE".equals(state) && loaded) {
|
||||
String why = s.optString("idleReason");
|
||||
if ("FINISHED".equals(why)) {
|
||||
loaded = false;
|
||||
if (events != null) events.remoteEnded();
|
||||
} else if ("ERROR".equals(why)) {
|
||||
loaded = false;
|
||||
if (events != null) events.remoteFailed("it couldn't play it");
|
||||
} else if ("INTERRUPTED".equals(why) && !awaitingReady) {
|
||||
lost("something else is playing on it");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void lost(String why) {
|
||||
if (closed) return;
|
||||
main.post(() -> {
|
||||
if (closed) return;
|
||||
shutdown();
|
||||
if (events != null) events.remoteLost(why);
|
||||
});
|
||||
}
|
||||
|
||||
// ---- CastMessage, by hand ----
|
||||
// 1 protocol_version (0), 2 source_id, 3 destination_id, 4 namespace,
|
||||
// 5 payload_type (0 = string), 6 payload_utf8.
|
||||
|
||||
static byte[] encode(String source, String dest, String ns, String payload) {
|
||||
ByteArrayOutputStream b = new ByteArrayOutputStream();
|
||||
b.write(0x08); b.write(0x00);
|
||||
field(b, 2, source);
|
||||
field(b, 3, dest);
|
||||
field(b, 4, ns);
|
||||
b.write(0x28); b.write(0x00);
|
||||
field(b, 6, payload);
|
||||
return b.toByteArray();
|
||||
}
|
||||
|
||||
private static void field(ByteArrayOutputStream b, int number, String value) {
|
||||
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
|
||||
b.write((number << 3) | 2);
|
||||
varint(b, bytes.length);
|
||||
b.write(bytes, 0, bytes.length);
|
||||
}
|
||||
|
||||
private static void varint(ByteArrayOutputStream b, long v) {
|
||||
while ((v & ~0x7FL) != 0) {
|
||||
b.write((int) ((v & 0x7F) | 0x80));
|
||||
v >>>= 7;
|
||||
}
|
||||
b.write((int) v);
|
||||
}
|
||||
|
||||
/** {source, namespace, payload_utf8} (nulls where absent). */
|
||||
static String[] decode(byte[] f) {
|
||||
String[] out = new String[3];
|
||||
int i = 0;
|
||||
while (i < f.length) {
|
||||
long[] tag = readVarint(f, i);
|
||||
i = (int) tag[1];
|
||||
int number = (int) (tag[0] >>> 3), wire = (int) (tag[0] & 7);
|
||||
if (wire == 0) {
|
||||
i = (int) readVarint(f, i)[1];
|
||||
} else if (wire == 2) {
|
||||
long[] len = readVarint(f, i);
|
||||
i = (int) len[1];
|
||||
int n = (int) len[0];
|
||||
if (i + n > f.length) break;
|
||||
String s = new String(f, i, n, StandardCharsets.UTF_8);
|
||||
if (number == 2) out[0] = s;
|
||||
else if (number == 4) out[1] = s;
|
||||
else if (number == 6) out[2] = s;
|
||||
i += n;
|
||||
} else {
|
||||
break; // nothing else appears in a CastMessage
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static long[] readVarint(byte[] f, int i) {
|
||||
long v = 0;
|
||||
int shift = 0;
|
||||
while (i < f.length) {
|
||||
int b = f[i++] & 0xFF;
|
||||
v |= (long) (b & 0x7F) << shift;
|
||||
if ((b & 0x80) == 0) break;
|
||||
shift += 7;
|
||||
}
|
||||
return new long[] {v, i};
|
||||
}
|
||||
|
||||
private static JSONObject json(String key, Object value) {
|
||||
JSONObject o = new JSONObject();
|
||||
put(o, key, value);
|
||||
return o;
|
||||
}
|
||||
|
||||
private static void put(JSONObject o, String key, Object value) {
|
||||
try { o.put(key, value); } catch (JSONException ignored) { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package me.teafry.andtunes;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The Rabbit's files over HTTP, for a Chromecast to fetch: the desktop's
|
||||
* cast/server.py model, so the speaker gets the original file, bit for bit.
|
||||
*
|
||||
* <p>A URL carries an opaque random token, never a path, so nothing but what
|
||||
* was registered can be read. Range and HEAD are supported because a
|
||||
* Chromecast seeks by re-requesting ranges and won't report a duration
|
||||
* without them. The last {@link #KEEP} registrations stay valid, so the
|
||||
* previous song's tail and a cover can still be fetched after a skip.
|
||||
*/
|
||||
final class MediaServer {
|
||||
private static final int KEEP = 8;
|
||||
|
||||
private final ServerSocket socket;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final Map<String, File> files = new LinkedHashMap<String, File>() {
|
||||
@Override protected boolean removeEldestEntry(Map.Entry<String, File> e) {
|
||||
return size() > KEEP;
|
||||
}
|
||||
};
|
||||
private volatile boolean open = true;
|
||||
|
||||
MediaServer() throws IOException {
|
||||
socket = new ServerSocket(0);
|
||||
Thread accept = new Thread(this::acceptLoop, "andTunes-http");
|
||||
accept.setDaemon(true);
|
||||
accept.start();
|
||||
}
|
||||
|
||||
int port() { return socket.getLocalPort(); }
|
||||
|
||||
/** The path (with leading slash) that serves {@code file}. */
|
||||
synchronized String register(File file) {
|
||||
byte[] b = new byte[12];
|
||||
random.nextBytes(b);
|
||||
StringBuilder token = new StringBuilder();
|
||||
for (byte x : b) token.append(String.format(Locale.ROOT, "%02x", x));
|
||||
String name = file.getName();
|
||||
int dot = name.lastIndexOf('.');
|
||||
String path = "/" + token + (dot >= 0 ? name.substring(dot).toLowerCase(Locale.ROOT) : "");
|
||||
files.put(path, file);
|
||||
return path;
|
||||
}
|
||||
|
||||
void close() {
|
||||
open = false;
|
||||
try { socket.close(); } catch (IOException ignored) { }
|
||||
}
|
||||
|
||||
static String mime(String name) {
|
||||
String n = name.toLowerCase(Locale.ROOT);
|
||||
if (n.endsWith(".mp3")) return "audio/mpeg";
|
||||
if (n.endsWith(".m4a") || n.endsWith(".mp4") || n.endsWith(".aac")) return "audio/mp4";
|
||||
if (n.endsWith(".flac")) return "audio/flac";
|
||||
if (n.endsWith(".ogg") || n.endsWith(".oga") || n.endsWith(".opus")) return "audio/ogg";
|
||||
if (n.endsWith(".wav")) return "audio/wav";
|
||||
if (n.endsWith(".jpg") || n.endsWith(".jpeg")) return "image/jpeg";
|
||||
if (n.endsWith(".png")) return "image/png";
|
||||
return "application/octet-stream";
|
||||
}
|
||||
|
||||
private void acceptLoop() {
|
||||
while (open) {
|
||||
try {
|
||||
Socket client = socket.accept();
|
||||
Thread t = new Thread(() -> serve(client), "andTunes-http-client");
|
||||
t.setDaemon(true);
|
||||
t.start();
|
||||
} catch (IOException e) {
|
||||
if (!open) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized File lookup(String path) { return files.get(path); }
|
||||
|
||||
private void serve(Socket client) {
|
||||
try (Socket c = client) {
|
||||
c.setSoTimeout(30000);
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(
|
||||
c.getInputStream(), StandardCharsets.ISO_8859_1));
|
||||
OutputStream out = c.getOutputStream();
|
||||
while (true) {
|
||||
String request = in.readLine();
|
||||
if (request == null || request.isEmpty()) return;
|
||||
String[] parts = request.split(" ");
|
||||
String range = null;
|
||||
boolean keepAlive = true;
|
||||
String line;
|
||||
while ((line = in.readLine()) != null && !line.isEmpty()) {
|
||||
int colon = line.indexOf(':');
|
||||
if (colon < 0) continue;
|
||||
String key = line.substring(0, colon).trim().toLowerCase(Locale.ROOT);
|
||||
String value = line.substring(colon + 1).trim();
|
||||
if (key.equals("range")) range = value;
|
||||
if (key.equals("connection") && value.equalsIgnoreCase("close")) keepAlive = false;
|
||||
}
|
||||
if (parts.length < 2) return;
|
||||
boolean head = parts[0].equals("HEAD");
|
||||
File f = lookup(parts[1].split("\\?")[0]);
|
||||
if ((!head && !parts[0].equals("GET")) || f == null || !f.isFile()) {
|
||||
write(out, "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");
|
||||
if (!keepAlive) return;
|
||||
continue;
|
||||
}
|
||||
long size = f.length(), start = 0, end = size - 1;
|
||||
boolean partial = false;
|
||||
if (range != null && range.startsWith("bytes=")) {
|
||||
String[] se = range.substring(6).split("-", 2);
|
||||
try {
|
||||
if (se[0].isEmpty()) {
|
||||
start = Math.max(0, size - Long.parseLong(se[1]));
|
||||
} else {
|
||||
start = Long.parseLong(se[0]);
|
||||
if (se.length > 1 && !se[1].isEmpty()) end = Math.min(end, Long.parseLong(se[1]));
|
||||
}
|
||||
partial = true;
|
||||
} catch (NumberFormatException ignored) { }
|
||||
if (start > end || start >= size) {
|
||||
write(out, "HTTP/1.1 416 Range Not Satisfiable\r\nContent-Range: bytes */"
|
||||
+ size + "\r\nContent-Length: 0\r\n\r\n");
|
||||
if (!keepAlive) return;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
long length = end - start + 1;
|
||||
StringBuilder h = new StringBuilder();
|
||||
h.append(partial ? "HTTP/1.1 206 Partial Content\r\n" : "HTTP/1.1 200 OK\r\n");
|
||||
h.append("Content-Type: ").append(mime(f.getName())).append("\r\n");
|
||||
h.append("Accept-Ranges: bytes\r\n");
|
||||
h.append("Access-Control-Allow-Origin: *\r\n");
|
||||
h.append("Content-Length: ").append(length).append("\r\n");
|
||||
if (partial) {
|
||||
h.append("Content-Range: bytes ").append(start).append('-').append(end)
|
||||
.append('/').append(size).append("\r\n");
|
||||
}
|
||||
h.append("\r\n");
|
||||
write(out, h.toString());
|
||||
if (!head) {
|
||||
try (RandomAccessFile raf = new RandomAccessFile(f, "r")) {
|
||||
raf.seek(start);
|
||||
byte[] buf = new byte[64 * 1024];
|
||||
long left = length;
|
||||
while (left > 0) {
|
||||
int n = raf.read(buf, 0, (int) Math.min(buf.length, left));
|
||||
if (n < 0) break;
|
||||
out.write(buf, 0, n);
|
||||
left -= n;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.flush();
|
||||
if (!keepAlive) return;
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
// the speaker hung up mid-file: it does that on every seek
|
||||
}
|
||||
}
|
||||
|
||||
private static void write(OutputStream out, String s) throws IOException {
|
||||
out.write(s.getBytes(StandardCharsets.ISO_8859_1));
|
||||
}
|
||||
}
|
||||
@@ -11,29 +11,35 @@ import android.provider.Settings;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ImageView;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.widget.BaseAdapter;
|
||||
import android.widget.ListView;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.TextView;
|
||||
|
||||
/**
|
||||
* The first screen, and the number the project is judged on: six tiles,
|
||||
* visible in well under 400 ms. It <b>loads nothing</b> — it only starts the
|
||||
* library parse in the background, so the data is usually ready by the time a
|
||||
* finger lands on a tile.
|
||||
* The first screen, and the number the project is judged on: visible in well
|
||||
* under 400 ms. It <b>loads nothing</b> — it only starts the library parse in
|
||||
* the background, so the data is usually ready by the time a finger lands.
|
||||
*
|
||||
* <p>A list like every other menu (trav's call, replacing the six picture
|
||||
* tiles): Now Playing on top (Shuffle All when nothing is loaded), the
|
||||
* library's ways in, Settings at the bottom. Six rows fill the screen; the
|
||||
* wheel scrolls to the seventh.
|
||||
*/
|
||||
public class MenuActivity extends BaseActivity {
|
||||
private static final String[] MODES = {
|
||||
ListActivity.PLAYLISTS, ListActivity.ARTISTS, ListActivity.ALBUMS,
|
||||
ListActivity.SONGS, ListActivity.SEARCH};
|
||||
private static final String[] NAMES = {"playlists", "artists", "albums", "songs", "search"};
|
||||
private static final String[] LABELS = {"Playlists", "Artists", "Albums", "Songs", "Search"};
|
||||
private static final int[] ART = {
|
||||
R.drawable.playlists, R.drawable.artists, R.drawable.albums,
|
||||
R.drawable.songs, R.drawable.search};
|
||||
/** Rows: [0] Now Playing / Shuffle All, then LABELS, then Settings. */
|
||||
private static final int ROWS = LABELS.length + 2;
|
||||
private static final int ROW_DP = 84;
|
||||
|
||||
private ImageView sixth;
|
||||
private Boolean builtWithAccess;
|
||||
private boolean sixthShowsNowPlaying;
|
||||
private BaseAdapter adapter;
|
||||
private ListView list;
|
||||
private WheelScroll wheel;
|
||||
|
||||
@Override protected void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
@@ -49,6 +55,16 @@ public class MenuActivity extends BaseActivity {
|
||||
}
|
||||
}
|
||||
|
||||
@Override protected void onDestroy() {
|
||||
if (wheel != null) wheel.stop();
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@Override protected void onWheel(int dir) {
|
||||
if (wheel != null) wheel.push(dir);
|
||||
else super.onWheel(dir);
|
||||
}
|
||||
|
||||
private void build() {
|
||||
builtWithAccess = hasAccess();
|
||||
if (!builtWithAccess) {
|
||||
@@ -62,38 +78,68 @@ public class MenuActivity extends BaseActivity {
|
||||
requestPermissions(new String[] {Manifest.permission.POST_NOTIFICATIONS}, 1);
|
||||
}
|
||||
|
||||
LinearLayout grid = new LinearLayout(this);
|
||||
grid.setOrientation(LinearLayout.VERTICAL);
|
||||
int pad = Ui.dp(this, 4);
|
||||
grid.setPadding(pad, pad, pad, pad);
|
||||
LinearLayout row = null;
|
||||
for (int i = 0; i < 6; i++) {
|
||||
if (i % 2 == 0) {
|
||||
row = new LinearLayout(this);
|
||||
grid.addView(row, new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f));
|
||||
LinearLayout column = new LinearLayout(this);
|
||||
column.setOrientation(LinearLayout.VERTICAL);
|
||||
TextView titleBar = Ui.text(this, 26, true, Ui.WHITE);
|
||||
titleBar.setBackgroundColor(Ui.BLACK);
|
||||
titleBar.setGravity(Gravity.CENTER_VERTICAL);
|
||||
int pad = Ui.dp(this, 20);
|
||||
titleBar.setPadding(pad, 0, pad, 0);
|
||||
titleBar.setText("andTunes");
|
||||
column.addView(titleBar, new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT, Ui.dp(this, 64)));
|
||||
|
||||
list = new ListView(this);
|
||||
list.setDivider(new ColorDrawable(Ui.BLACK));
|
||||
list.setDividerHeight(Ui.dp(this, 1));
|
||||
list.setBackgroundColor(Ui.WHITE);
|
||||
adapter = new BaseAdapter() {
|
||||
@Override public int getCount() { return ROWS; }
|
||||
@Override public Object getItem(int i) { return i; }
|
||||
@Override public long getItemId(int i) { return i; }
|
||||
@Override public View getView(int i, View convert, ViewGroup parent) {
|
||||
TextView row = convert != null ? (TextView) convert
|
||||
: Ui.text(MenuActivity.this, Ui.TITLE_SP, false, Ui.BLACK);
|
||||
row.setGravity(Gravity.CENTER_VERTICAL);
|
||||
row.setPadding(pad, 0, pad, 0);
|
||||
// Six rows fill the list exactly, whatever the bars leave.
|
||||
int fit = parent.getHeight() > 0
|
||||
? (parent.getHeight() - 5 * list.getDividerHeight()) / 6
|
||||
: Ui.dp(MenuActivity.this, ROW_DP);
|
||||
row.setMinHeight(fit);
|
||||
row.setHeight(fit);
|
||||
row.setTypeface(null, i == 0 ? android.graphics.Typeface.BOLD
|
||||
: android.graphics.Typeface.NORMAL);
|
||||
if (i == 0) {
|
||||
row.setText(hasTrack() ? "Now Playing" : "Shuffle All");
|
||||
} else if (i <= LABELS.length) {
|
||||
row.setText(LABELS[i - 1]);
|
||||
} else {
|
||||
row.setText("Settings");
|
||||
}
|
||||
return row;
|
||||
}
|
||||
ImageView tile = new ImageView(this);
|
||||
tile.setScaleType(ImageView.ScaleType.FIT_CENTER);
|
||||
tile.setPadding(pad, pad, pad, pad);
|
||||
if (i < 5) {
|
||||
final int n = i;
|
||||
tile.setImageDrawable(Ui.button(this, NAMES[i], ART[i]));
|
||||
tile.setContentDescription(LABELS[i]);
|
||||
tile.setOnClickListener(v -> startActivity(
|
||||
new Intent(this, ListActivity.class).putExtra(ListActivity.MODE, MODES[n])));
|
||||
} else {
|
||||
sixth = tile;
|
||||
tile.setOnClickListener(v -> onSixth());
|
||||
}
|
||||
row.addView(tile, new LinearLayout.LayoutParams(0,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT, 1f));
|
||||
}
|
||||
sixthShowsNowPlaying = !hasTrack(); // force the first paint
|
||||
setScreen(grid, false);
|
||||
};
|
||||
list.setAdapter(adapter);
|
||||
list.setOnItemClickListener((parent, view, i, rowId) -> onRow(i));
|
||||
wheel = new WheelScroll(list);
|
||||
column.addView(list, new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f));
|
||||
setScreen(column, false);
|
||||
onPlaybackChanged();
|
||||
}
|
||||
|
||||
private void onRow(int i) {
|
||||
if (i == 0) {
|
||||
onFirst();
|
||||
} else if (i <= LABELS.length) {
|
||||
startActivity(new Intent(this, ListActivity.class)
|
||||
.putExtra(ListActivity.MODE, MODES[i - 1]));
|
||||
} else {
|
||||
startActivity(new Intent(this, SettingsActivity.class));
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean hasTrack() {
|
||||
PlaybackService s = PlaybackService.get();
|
||||
return s != null && s.current() != null;
|
||||
@@ -101,17 +147,11 @@ public class MenuActivity extends BaseActivity {
|
||||
|
||||
@Override public void onPlaybackChanged() {
|
||||
super.onPlaybackChanged();
|
||||
if (sixth == null) return;
|
||||
boolean now = hasTrack();
|
||||
if (now == sixthShowsNowPlaying) return;
|
||||
sixthShowsNowPlaying = now;
|
||||
sixth.setImageDrawable(now ? Ui.button(this, "now_playing", R.drawable.now_playing)
|
||||
: Ui.button(this, "shuffle_all", R.drawable.shuffle_all));
|
||||
sixth.setContentDescription(now ? "Now Playing" : "Shuffle All");
|
||||
if (adapter != null) adapter.notifyDataSetChanged(); // Now Playing / Shuffle All
|
||||
}
|
||||
|
||||
/** "Now Playing" when there is something, else shuffle everything we know. */
|
||||
private void onSixth() {
|
||||
private void onFirst() {
|
||||
if (hasTrack()) {
|
||||
openNowPlaying();
|
||||
return;
|
||||
|
||||
@@ -14,15 +14,20 @@ import android.widget.SeekBar;
|
||||
import android.widget.TextView;
|
||||
|
||||
/**
|
||||
* White background, square art, a slim scrubber, ◀ ⏯ ▶, then shuffle and
|
||||
* repeat. <b>No back button</b> — Android's own is always on screen, and the
|
||||
* panel is too small to spend on a second one (trav's call). The wheel stays
|
||||
* volume here: this is the one screen where that's the useful thing.
|
||||
* White background, square art, a slim scrubber, ◀ ⏯ ▶, then shuffle, repeat
|
||||
* and speakers as icon pills. <b>No back button</b> — Android's own is always
|
||||
* on screen, and the panel is too small to spend on a second one (trav's
|
||||
* call). The wheel stays volume here: this is the one screen where that's the
|
||||
* useful thing.
|
||||
*
|
||||
* <p>Tapping the art shows it full screen (tap again to come back); tapping
|
||||
* the title or the artist line opens the song's album.
|
||||
*/
|
||||
public class NowPlayingActivity extends BaseActivity {
|
||||
private final Handler main = new Handler(Looper.getMainLooper());
|
||||
private ImageView art, playPause;
|
||||
private TextView title, detail, elapsed, remaining, shuffleBtn, repeatBtn;
|
||||
private ImageView art, playPause, shuffleBtn, repeatBtn, speakersBtn, bigArt;
|
||||
private TextView title, detail, elapsed, remaining;
|
||||
private Drawable shuffleD, repeatD, repeatOneD, speakersD;
|
||||
private SeekBar scrubber;
|
||||
private boolean dragging;
|
||||
private Library.Track shown;
|
||||
@@ -52,6 +57,7 @@ public class NowPlayingActivity extends BaseActivity {
|
||||
ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f);
|
||||
alp.gravity = Gravity.CENTER_HORIZONTAL;
|
||||
col.addView(art, alp);
|
||||
art.setOnClickListener(v -> showBigArt(true));
|
||||
|
||||
title = Ui.text(this, 26, true, Ui.BLACK);
|
||||
title.setGravity(Gravity.CENTER);
|
||||
@@ -63,6 +69,8 @@ public class NowPlayingActivity extends BaseActivity {
|
||||
LinearLayout.LayoutParams dlp = wrap();
|
||||
dlp.topMargin = Ui.dp(this, 4);
|
||||
col.addView(detail, dlp);
|
||||
title.setOnClickListener(v -> openAlbum());
|
||||
detail.setOnClickListener(v -> openAlbum());
|
||||
|
||||
scrubber = new SeekBar(this);
|
||||
ColorStateList black = ColorStateList.valueOf(Ui.BLACK);
|
||||
@@ -106,17 +114,53 @@ public class NowPlayingActivity extends BaseActivity {
|
||||
col.addView(transport, new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT, Ui.dp(this, 96)));
|
||||
|
||||
shuffleD = Ui.button(this, "shuffle", R.drawable.shuffle);
|
||||
repeatD = Ui.button(this, "repeat", R.drawable.repeat);
|
||||
repeatOneD = Ui.button(this, "repeat_one", R.drawable.repeat_one);
|
||||
speakersD = Ui.button(this, "speakers", R.drawable.speakers);
|
||||
LinearLayout toggles = new LinearLayout(this);
|
||||
shuffleBtn = toggle(toggles, "Shuffle");
|
||||
repeatBtn = toggle(toggles, "Repeat");
|
||||
shuffleBtn = toggle(toggles, shuffleD, "Shuffle");
|
||||
repeatBtn = toggle(toggles, repeatD, "Repeat");
|
||||
speakersBtn = toggle(toggles, speakersD, "Speakers");
|
||||
shuffleBtn.setOnClickListener(v -> withService(s -> s.setShuffle(!s.shuffle())));
|
||||
repeatBtn.setOnClickListener(v -> withService(PlaybackService::cycleRepeat));
|
||||
speakersBtn.setOnClickListener(v -> startActivity(
|
||||
new android.content.Intent(this, SpeakersActivity.class)));
|
||||
LinearLayout.LayoutParams glp = new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT, Ui.dp(this, 64));
|
||||
glp.topMargin = Ui.dp(this, 8);
|
||||
col.addView(toggles, glp);
|
||||
|
||||
setScreen(col, false);
|
||||
// The art, full screen, over everything; a tap anywhere puts it away.
|
||||
android.widget.FrameLayout stack = new android.widget.FrameLayout(this);
|
||||
stack.addView(col);
|
||||
bigArt = new ImageView(this);
|
||||
bigArt.setScaleType(ImageView.ScaleType.FIT_CENTER);
|
||||
bigArt.setBackgroundColor(Ui.WHITE);
|
||||
bigArt.setVisibility(android.view.View.GONE);
|
||||
bigArt.setOnClickListener(v -> showBigArt(false));
|
||||
stack.addView(bigArt);
|
||||
setScreen(stack, false);
|
||||
}
|
||||
|
||||
private void showBigArt(boolean show) {
|
||||
if (show) {
|
||||
if (shown == null || shown.art.isEmpty()) return;
|
||||
bigArt.setImageDrawable(art.getDrawable());
|
||||
}
|
||||
bigArt.setVisibility(show ? android.view.View.VISIBLE : android.view.View.GONE);
|
||||
}
|
||||
|
||||
@Override public void onBackPressed() {
|
||||
if (bigArt.getVisibility() == android.view.View.VISIBLE) showBigArt(false);
|
||||
else super.onBackPressed();
|
||||
}
|
||||
|
||||
private void openAlbum() {
|
||||
if (shown == null || shown.albumRef == null) return;
|
||||
startActivity(new android.content.Intent(this, ListActivity.class)
|
||||
.putExtra(ListActivity.MODE, ListActivity.ALBUM)
|
||||
.putExtra(ListActivity.ID, shown.albumRef.key));
|
||||
}
|
||||
|
||||
private LinearLayout.LayoutParams wrap() {
|
||||
@@ -134,15 +178,20 @@ public class NowPlayingActivity extends BaseActivity {
|
||||
return b;
|
||||
}
|
||||
|
||||
private TextView toggle(LinearLayout row, String label) {
|
||||
TextView t = Ui.text(this, 22, true, Ui.BLACK);
|
||||
t.setText(label);
|
||||
private ImageView toggle(LinearLayout row, Drawable icon, String label) {
|
||||
ImageView b = new ImageView(this);
|
||||
b.setImageDrawable(icon);
|
||||
b.setScaleType(ImageView.ScaleType.FIT_CENTER);
|
||||
int p = Ui.dp(this, 10);
|
||||
b.setPadding(p, p, p, p);
|
||||
b.setContentDescription(label);
|
||||
Ui.toggleStyle(this, b, false);
|
||||
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
|
||||
0, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
|
||||
int m = Ui.dp(this, 6);
|
||||
lp.setMargins(m, 0, m, 0);
|
||||
row.addView(t, lp);
|
||||
return t;
|
||||
row.addView(b, lp);
|
||||
return b;
|
||||
}
|
||||
|
||||
private interface Action { void run(PlaybackService s); }
|
||||
@@ -200,8 +249,10 @@ public class NowPlayingActivity extends BaseActivity {
|
||||
playPause.setContentDescription(s.isPlaying() ? "Pause" : "Play");
|
||||
Ui.toggleStyle(this, shuffleBtn, s.shuffle());
|
||||
int r = s.repeat();
|
||||
repeatBtn.setText(r == PlaybackService.REPEAT_ONE ? "Repeat one"
|
||||
repeatBtn.setImageDrawable(r == PlaybackService.REPEAT_ONE ? repeatOneD : repeatD);
|
||||
repeatBtn.setContentDescription(r == PlaybackService.REPEAT_ONE ? "Repeat one"
|
||||
: r == PlaybackService.REPEAT_ALL ? "Repeat all" : "Repeat");
|
||||
Ui.toggleStyle(this, repeatBtn, r != PlaybackService.REPEAT_OFF);
|
||||
Ui.toggleStyle(this, speakersBtn, s.remoteName() != null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,8 @@ import java.util.Random;
|
||||
*/
|
||||
public class PlaybackService extends Service implements
|
||||
MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener,
|
||||
MediaPlayer.OnErrorListener, AudioManager.OnAudioFocusChangeListener {
|
||||
MediaPlayer.OnErrorListener, AudioManager.OnAudioFocusChangeListener,
|
||||
Remote.Events {
|
||||
|
||||
interface Listener { void onPlaybackChanged(); }
|
||||
|
||||
@@ -79,6 +80,11 @@ public class PlaybackService extends Service implements
|
||||
private int failures;
|
||||
private final History history = new History();
|
||||
|
||||
/** Playing through a speaker instead of the MediaPlayer (null: here). */
|
||||
private Remote remote;
|
||||
private PowerManager.WakeLock remoteWake;
|
||||
private android.net.wifi.WifiManager.WifiLock remoteWifi;
|
||||
|
||||
// ---- the static front door ----
|
||||
|
||||
static PlaybackService get() { return sService; }
|
||||
@@ -173,7 +179,7 @@ public class PlaybackService extends Service implements
|
||||
}
|
||||
|
||||
@Override public void onTaskRemoved(Intent rootIntent) {
|
||||
if (!playing) stopSelf();
|
||||
if (!playing && remote == null) stopSelf();
|
||||
}
|
||||
|
||||
@Override public void onDestroy() {
|
||||
@@ -182,6 +188,8 @@ public class PlaybackService extends Service implements
|
||||
abandonFocus();
|
||||
unregisterNoisy();
|
||||
main.removeCallbacksAndMessages(null);
|
||||
if (remote != null) { remote.close(); remote = null; }
|
||||
holdRemoteLocks(false);
|
||||
session.release();
|
||||
mp.release();
|
||||
notifications.cancel(NOTIFICATION_ID);
|
||||
@@ -204,13 +212,19 @@ public class PlaybackService extends Service implements
|
||||
|
||||
int repeat() { return repeat; }
|
||||
|
||||
/** The speaker being played through, or null for the Rabbit itself. */
|
||||
String remoteName() { return remote != null ? remote.name() : null; }
|
||||
|
||||
Remote remote() { return remote; }
|
||||
|
||||
int position() {
|
||||
if (!prepared) return pendingSeek;
|
||||
if (remote != null) return remote.position();
|
||||
try { return mp.getCurrentPosition(); } catch (IllegalStateException e) { return 0; }
|
||||
}
|
||||
|
||||
int duration() {
|
||||
if (prepared) {
|
||||
if (prepared && remote == null) {
|
||||
try { return mp.getDuration(); } catch (IllegalStateException ignored) { }
|
||||
}
|
||||
Library.Track t = current();
|
||||
@@ -224,14 +238,18 @@ public class PlaybackService extends Service implements
|
||||
void play() {
|
||||
if (current() == null) return;
|
||||
if (!prepared) { playWhenReady = true; return; }
|
||||
if (audio.requestAudioFocus(focusRequest) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
|
||||
return;
|
||||
if (remote != null) {
|
||||
remote.play();
|
||||
} else {
|
||||
if (audio.requestAudioFocus(focusRequest) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
|
||||
return;
|
||||
}
|
||||
mp.setVolume(1f, 1f);
|
||||
mp.start();
|
||||
}
|
||||
mp.setVolume(1f, 1f);
|
||||
mp.start();
|
||||
playing = true;
|
||||
history.playing(current());
|
||||
registerNoisy();
|
||||
if (remote == null) registerNoisy();
|
||||
goForeground();
|
||||
tick();
|
||||
changed();
|
||||
@@ -240,7 +258,8 @@ public class PlaybackService extends Service implements
|
||||
void pause() {
|
||||
playWhenReady = false;
|
||||
if (playing) {
|
||||
try { mp.pause(); } catch (IllegalStateException ignored) { }
|
||||
if (remote != null) remote.pause();
|
||||
else try { mp.pause(); } catch (IllegalStateException ignored) { }
|
||||
}
|
||||
playing = false;
|
||||
history.paused();
|
||||
@@ -256,7 +275,8 @@ public class PlaybackService extends Service implements
|
||||
}
|
||||
|
||||
void seekTo(int ms) {
|
||||
if (prepared) mp.seekTo(ms);
|
||||
if (prepared && remote != null) remote.seekTo(ms);
|
||||
else if (prepared) mp.seekTo(ms);
|
||||
else pendingSeek = ms;
|
||||
changed();
|
||||
}
|
||||
@@ -335,8 +355,9 @@ public class PlaybackService extends Service implements
|
||||
// End of the queue pauses, parked at the top of the last song.
|
||||
playing = false;
|
||||
pendingSeek = 0;
|
||||
if (prepared) mp.seekTo(0);
|
||||
if (prepared && remote == null) mp.seekTo(0);
|
||||
pause();
|
||||
if (remote != null) { prepared = false; pendingSeek = 0; }
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -354,6 +375,16 @@ public class PlaybackService extends Service implements
|
||||
prepared = false;
|
||||
playWhenReady = play;
|
||||
pendingSeek = seekMs;
|
||||
if (remote != null) {
|
||||
if (!t.file().isFile()) {
|
||||
skipBroken(t, "missing");
|
||||
return;
|
||||
}
|
||||
remote.load(t, seekMs, play);
|
||||
saveState();
|
||||
changed();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
mp.reset();
|
||||
if (!t.file().isFile()) throw new java.io.FileNotFoundException(t.path);
|
||||
@@ -408,9 +439,99 @@ public class PlaybackService extends Service implements
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- playing through a speaker ----
|
||||
|
||||
/**
|
||||
* Hand playback to {@code r}, already connected: the song carries on
|
||||
* there from where it is. The MediaPlayer is stopped, not released.
|
||||
*/
|
||||
void connectRemote(Remote r) {
|
||||
boolean wasPlaying = playing;
|
||||
int at = current() != null ? position() : 0;
|
||||
if (playing) {
|
||||
try { mp.pause(); } catch (IllegalStateException ignored) { }
|
||||
playing = false;
|
||||
}
|
||||
abandonFocus();
|
||||
unregisterNoisy();
|
||||
if (remote != null) remote.close();
|
||||
remote = r;
|
||||
r.setEvents(this);
|
||||
holdRemoteLocks(true);
|
||||
if (current() != null) load(pos, wasPlaying, at);
|
||||
else changed();
|
||||
}
|
||||
|
||||
/** Back to the Rabbit, paused where the speaker was (never blaring out). */
|
||||
void disconnectRemote() {
|
||||
if (remote == null) return;
|
||||
int at = current() != null && prepared ? remote.position() : pendingSeek;
|
||||
Remote r = remote;
|
||||
remote = null;
|
||||
r.close();
|
||||
holdRemoteLocks(false);
|
||||
if (playing) history.paused();
|
||||
playing = false;
|
||||
if (current() != null) load(pos, false, at);
|
||||
else changed();
|
||||
}
|
||||
|
||||
/** Streaming runs on our threads, so the CPU and Wi-Fi must stay up. */
|
||||
private void holdRemoteLocks(boolean hold) {
|
||||
if (hold) {
|
||||
if (remoteWake == null) {
|
||||
remoteWake = getSystemService(PowerManager.class).newWakeLock(
|
||||
PowerManager.PARTIAL_WAKE_LOCK, "andTunes:speaker");
|
||||
remoteWifi = getSystemService(android.net.wifi.WifiManager.class)
|
||||
.createWifiLock(android.net.wifi.WifiManager.WIFI_MODE_FULL_HIGH_PERF,
|
||||
"andTunes:speaker");
|
||||
}
|
||||
if (!remoteWake.isHeld()) remoteWake.acquire();
|
||||
if (!remoteWifi.isHeld()) remoteWifi.acquire();
|
||||
} else {
|
||||
if (remoteWake != null && remoteWake.isHeld()) remoteWake.release();
|
||||
if (remoteWifi != null && remoteWifi.isHeld()) remoteWifi.release();
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void remoteReady() {
|
||||
if (remote == null) return;
|
||||
prepared = true;
|
||||
failures = 0;
|
||||
pendingSeek = 0;
|
||||
if (playWhenReady) {
|
||||
playing = true;
|
||||
history.playing(current());
|
||||
goForeground();
|
||||
tick();
|
||||
}
|
||||
changed();
|
||||
}
|
||||
|
||||
@Override public void remoteEnded() {
|
||||
if (remote == null || !prepared) return;
|
||||
Library.Track done = current();
|
||||
if (done != null) Plays.record(this, done.id);
|
||||
history.end(this, "finish");
|
||||
advance(true);
|
||||
}
|
||||
|
||||
@Override public void remoteFailed(String why) {
|
||||
Library.Track t = current();
|
||||
prepared = false;
|
||||
if (t != null) skipBroken(t, why);
|
||||
}
|
||||
|
||||
@Override public void remoteLost(String why) {
|
||||
if (remote == null) return;
|
||||
Ui.toast(this, "Lost " + remote.name() + (why.isEmpty() ? "" : " (" + why + ")"));
|
||||
disconnectRemote();
|
||||
}
|
||||
|
||||
// ---- audio focus, noisy ----
|
||||
|
||||
@Override public void onAudioFocusChange(int change) {
|
||||
if (remote != null) return; // the speaker isn't ours to duck
|
||||
switch (change) {
|
||||
case AudioManager.AUDIOFOCUS_LOSS:
|
||||
resumeOnFocus = false;
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package me.teafry.andtunes;
|
||||
|
||||
/**
|
||||
* A speaker the queue plays through instead of the Rabbit's own output: a
|
||||
* Chromecast ({@link CastRemote}) or an AirPlay speaker ({@link AirPlayRemote}).
|
||||
*
|
||||
* <p>{@link PlaybackService} keeps the queue, shuffle, repeat and play counts
|
||||
* either way; a remote only has to make one song come out of something and
|
||||
* say where it's up to. Calls arrive on the main thread and return at once
|
||||
* (the network happens on the remote's own threads); {@link Events} are
|
||||
* delivered on the main thread too.
|
||||
*/
|
||||
interface Remote {
|
||||
interface Events {
|
||||
/** The song is loaded (and playing, if it was asked to). */
|
||||
void remoteReady();
|
||||
/** The song played to its end. */
|
||||
void remoteEnded();
|
||||
/** This song can't be played there; the queue moves on. */
|
||||
void remoteFailed(String why);
|
||||
/** The speaker went away; playback stops. */
|
||||
void remoteLost(String why);
|
||||
}
|
||||
|
||||
String name();
|
||||
|
||||
void setEvents(Events events);
|
||||
|
||||
void load(Library.Track track, int startMs, boolean play);
|
||||
|
||||
void play();
|
||||
|
||||
void pause();
|
||||
|
||||
void seekTo(int ms);
|
||||
|
||||
/** Where the listener is in the song, in ms. */
|
||||
int position();
|
||||
|
||||
/** 0..1, the speaker's own volume. */
|
||||
void setVolume(float level);
|
||||
|
||||
float volume();
|
||||
|
||||
void close();
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package me.teafry.andtunes;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.text.format.DateFormat;
|
||||
import android.view.Gravity;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* The menu's last row. Nothing to set yet: what the app is, and what the last
|
||||
* sync left on the Rabbit — the place future settings go.
|
||||
*/
|
||||
public class SettingsActivity extends BaseActivity {
|
||||
private LinearLayout column;
|
||||
private TextView library;
|
||||
|
||||
@Override protected void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
column = new LinearLayout(this);
|
||||
column.setOrientation(LinearLayout.VERTICAL);
|
||||
TextView titleBar = Ui.text(this, 26, true, Ui.WHITE);
|
||||
titleBar.setBackgroundColor(Ui.BLACK);
|
||||
titleBar.setGravity(Gravity.CENTER_VERTICAL);
|
||||
int pad = Ui.dp(this, 20);
|
||||
titleBar.setPadding(pad, 0, pad, 0);
|
||||
titleBar.setText("Settings");
|
||||
column.addView(titleBar, new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT, Ui.dp(this, 64)));
|
||||
|
||||
String version = "";
|
||||
try {
|
||||
version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
|
||||
} catch (Exception ignored) { }
|
||||
line("andTunes " + version, true);
|
||||
library = line("Loading the library…", false);
|
||||
File manifest = Library.manifest();
|
||||
if (manifest.isFile()) {
|
||||
line("Last synced " + DateFormat.format("d MMM yyyy, h:mm a",
|
||||
manifest.lastModified()), false);
|
||||
}
|
||||
setScreen(column, true);
|
||||
Library.whenReady((lib, error) -> {
|
||||
if (lib == null) {
|
||||
library.setText(error != null ? error : "No library");
|
||||
} else {
|
||||
library.setText(lib.tracks.size() + " songs, "
|
||||
+ lib.playlists.size() + " playlists");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private TextView line(String text, boolean bold) {
|
||||
TextView t = Ui.text(this, Ui.SUB_SP + 3, bold, Ui.BLACK);
|
||||
t.setSingleLine(false);
|
||||
t.setText(text);
|
||||
int pad = Ui.dp(this, 20);
|
||||
t.setPadding(pad, Ui.dp(this, 16), pad, 0);
|
||||
column.addView(t, new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
|
||||
return t;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package me.teafry.andtunes;
|
||||
|
||||
import android.content.Context;
|
||||
import android.net.nsd.NsdManager;
|
||||
import android.net.nsd.NsdServiceInfo;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Finds AirPlay (RAOP) speakers and Chromecasts on the Wi-Fi with Android's
|
||||
* own mDNS (NsdManager), while the picker is open. Resolving is done one
|
||||
* service at a time: on Android 13 a second resolve while one is running
|
||||
* fails with FAILURE_ALREADY_ACTIVE.
|
||||
*/
|
||||
final class Speakers {
|
||||
static final String AIRPLAY = "_raop._tcp", CAST = "_googlecast._tcp";
|
||||
|
||||
static final class Speaker {
|
||||
final String kind, id, name, host;
|
||||
final int port;
|
||||
final Map<String, String> txt;
|
||||
/** Why it can't be used ("" = it can). */
|
||||
final String note;
|
||||
|
||||
Speaker(String kind, String id, String name, String host, int port,
|
||||
Map<String, String> txt, String note) {
|
||||
this.kind = kind; this.id = id; this.name = name; this.host = host;
|
||||
this.port = port; this.txt = txt; this.note = note;
|
||||
}
|
||||
|
||||
String kindLabel() { return CAST.equals(kind) ? "Chromecast" : "AirPlay"; }
|
||||
}
|
||||
|
||||
interface Listener { void onSpeakers(ArrayList<Speaker> speakers); }
|
||||
|
||||
private final NsdManager nsd;
|
||||
private final Handler main = new Handler(Looper.getMainLooper());
|
||||
private final Listener listener;
|
||||
private final LinkedHashMap<String, Speaker> found = new LinkedHashMap<>();
|
||||
private final ArrayDeque<NsdServiceInfo> toResolve = new ArrayDeque<>();
|
||||
private boolean resolving, running;
|
||||
private final ArrayList<NsdManager.DiscoveryListener> browsers = new ArrayList<>();
|
||||
|
||||
Speakers(Context c, Listener listener) {
|
||||
nsd = c.getSystemService(NsdManager.class);
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
void start() {
|
||||
if (running) return;
|
||||
running = true;
|
||||
for (String type : new String[] {AIRPLAY, CAST}) {
|
||||
NsdManager.DiscoveryListener l = new NsdManager.DiscoveryListener() {
|
||||
@Override public void onDiscoveryStarted(String t) { }
|
||||
@Override public void onDiscoveryStopped(String t) { }
|
||||
@Override public void onStartDiscoveryFailed(String t, int code) { }
|
||||
@Override public void onStopDiscoveryFailed(String t, int code) { }
|
||||
@Override public void onServiceFound(NsdServiceInfo info) {
|
||||
main.post(() -> { toResolve.add(info); resolveNext(); });
|
||||
}
|
||||
@Override public void onServiceLost(NsdServiceInfo info) {
|
||||
main.post(() -> {
|
||||
String key = typeOf(info) + "/" + info.getServiceName();
|
||||
if (found.remove(key) != null) publish();
|
||||
});
|
||||
}
|
||||
};
|
||||
browsers.add(l);
|
||||
nsd.discoverServices(type, NsdManager.PROTOCOL_DNS_SD, l);
|
||||
}
|
||||
}
|
||||
|
||||
void stop() {
|
||||
if (!running) return;
|
||||
running = false;
|
||||
for (NsdManager.DiscoveryListener l : browsers) {
|
||||
try { nsd.stopServiceDiscovery(l); } catch (IllegalArgumentException ignored) { }
|
||||
}
|
||||
browsers.clear();
|
||||
toResolve.clear();
|
||||
}
|
||||
|
||||
private static String typeOf(NsdServiceInfo info) {
|
||||
String t = info.getServiceType();
|
||||
return t != null && t.contains("googlecast") ? CAST : AIRPLAY;
|
||||
}
|
||||
|
||||
private void resolveNext() {
|
||||
if (resolving || !running || toResolve.isEmpty()) return;
|
||||
resolving = true;
|
||||
NsdServiceInfo next = toResolve.poll();
|
||||
nsd.resolveService(next, new NsdManager.ResolveListener() {
|
||||
@Override public void onResolveFailed(NsdServiceInfo info, int code) {
|
||||
main.post(() -> { resolving = false; resolveNext(); });
|
||||
}
|
||||
@Override public void onServiceResolved(NsdServiceInfo info) {
|
||||
main.post(() -> {
|
||||
resolving = false;
|
||||
add(info);
|
||||
resolveNext();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void add(NsdServiceInfo info) {
|
||||
if (info.getHost() == null) return;
|
||||
String kind = typeOf(info);
|
||||
Map<String, String> txt = new HashMap<>();
|
||||
for (Map.Entry<String, byte[]> e : info.getAttributes().entrySet()) {
|
||||
txt.put(e.getKey(), e.getValue() == null ? ""
|
||||
: new String(e.getValue(), StandardCharsets.UTF_8));
|
||||
}
|
||||
String service = info.getServiceName();
|
||||
String name;
|
||||
String note = "";
|
||||
if (CAST.equals(kind)) {
|
||||
name = txt.containsKey("fn") ? txt.get("fn") : service;
|
||||
} else {
|
||||
// "AABBCCDDEEFF@Living Room"
|
||||
int at = service.indexOf('@');
|
||||
name = at >= 0 ? service.substring(at + 1) : service;
|
||||
if ("true".equalsIgnoreCase(txt.get("pw"))) note = "needs a password";
|
||||
}
|
||||
found.put(kind + "/" + service, new Speaker(kind, kind + "/" + service, name,
|
||||
info.getHost().getHostAddress(), info.getPort(), txt, note));
|
||||
publish();
|
||||
}
|
||||
|
||||
private void publish() {
|
||||
ArrayList<Speaker> list = new ArrayList<>(found.values());
|
||||
list.sort((a, b) -> a.name.compareToIgnoreCase(b.name));
|
||||
listener.onSpeakers(list);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package me.teafry.andtunes;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.widget.BaseAdapter;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ListView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* "Play on": this Rabbit, then every AirPlay speaker and Chromecast found on
|
||||
* the Wi-Fi. Tapping one connects in the background and hands the queue to
|
||||
* it; tapping "This Rabbit" (or the speaker already playing) comes back,
|
||||
* paused.
|
||||
*
|
||||
* <p>Speakers mDNS can't find (another subnet, a receiver that doesn't
|
||||
* advertise) can be listed in {@code Music/andTunes/speakers.txt}, one per
|
||||
* line: {@code airplay|cast <host> [port] [name]}. They come first.
|
||||
*/
|
||||
public class SpeakersActivity extends BaseActivity implements Speakers.Listener {
|
||||
private final Handler main = new Handler(Looper.getMainLooper());
|
||||
private final ArrayList<Speakers.Speaker> speakers = new ArrayList<>();
|
||||
private Speakers discovery;
|
||||
private BaseAdapter adapter;
|
||||
private ListView list;
|
||||
private WheelScroll wheel;
|
||||
private String connecting; // speaker id while a connect runs
|
||||
|
||||
@Override protected void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
LinearLayout column = new LinearLayout(this);
|
||||
column.setOrientation(LinearLayout.VERTICAL);
|
||||
TextView titleBar = Ui.text(this, 26, true, Ui.WHITE);
|
||||
titleBar.setBackgroundColor(Ui.BLACK);
|
||||
titleBar.setGravity(Gravity.CENTER_VERTICAL);
|
||||
int pad = Ui.dp(this, 20);
|
||||
titleBar.setPadding(pad, 0, pad, 0);
|
||||
titleBar.setText("Play on");
|
||||
column.addView(titleBar, new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT, Ui.dp(this, 64)));
|
||||
|
||||
list = new ListView(this);
|
||||
list.setDivider(new ColorDrawable(Ui.BLACK));
|
||||
list.setDividerHeight(Ui.dp(this, 1));
|
||||
list.setBackgroundColor(Ui.WHITE);
|
||||
adapter = new Rows();
|
||||
list.setAdapter(adapter);
|
||||
list.setOnItemClickListener((parent, view, i, id) -> onRow(i));
|
||||
wheel = new WheelScroll(list);
|
||||
column.addView(list, new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f));
|
||||
setScreen(column, false);
|
||||
discovery = new Speakers(this, this);
|
||||
|
||||
speakers.addAll(listed());
|
||||
}
|
||||
|
||||
/** {@code speakers.txt}: the speakers named by address. */
|
||||
private static ArrayList<Speakers.Speaker> listed() {
|
||||
ArrayList<Speakers.Speaker> out = new ArrayList<>();
|
||||
java.io.File f = new java.io.File(Library.root(), "speakers.txt");
|
||||
if (!f.isFile()) return out;
|
||||
try (java.io.BufferedReader r = new java.io.BufferedReader(new java.io.FileReader(f))) {
|
||||
String line;
|
||||
while ((line = r.readLine()) != null) {
|
||||
String[] p = line.trim().split("\\s+", 4);
|
||||
if (p.length < 2 || p[0].startsWith("#")) continue;
|
||||
boolean cast = p[0].equalsIgnoreCase("cast");
|
||||
if (!cast && !p[0].equalsIgnoreCase("airplay")) continue;
|
||||
int port = cast ? 8009 : 7000;
|
||||
if (p.length > 2) {
|
||||
try { port = Integer.parseInt(p[2]); } catch (NumberFormatException ignored) { }
|
||||
}
|
||||
String name = p.length > 3 ? p[3] : p[1];
|
||||
out.add(new Speakers.Speaker(cast ? Speakers.CAST : Speakers.AIRPLAY,
|
||||
"direct/" + p[1] + ":" + port, name, p[1], port,
|
||||
new HashMap<>(), ""));
|
||||
}
|
||||
} catch (java.io.IOException ignored) { }
|
||||
return out;
|
||||
}
|
||||
|
||||
@Override protected void onResume() {
|
||||
super.onResume();
|
||||
discovery.start();
|
||||
}
|
||||
|
||||
@Override protected void onPause() {
|
||||
discovery.stop();
|
||||
super.onPause();
|
||||
}
|
||||
|
||||
@Override protected void onDestroy() {
|
||||
wheel.stop();
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@Override protected void onWheel(int dir) { wheel.push(dir); }
|
||||
|
||||
@Override public void onSpeakers(ArrayList<Speakers.Speaker> found) {
|
||||
ArrayList<Speakers.Speaker> direct = new ArrayList<>();
|
||||
for (Speakers.Speaker s : speakers) if (s.id.startsWith("direct/")) direct.add(s);
|
||||
speakers.clear();
|
||||
speakers.addAll(direct);
|
||||
speakers.addAll(found);
|
||||
adapter.notifyDataSetChanged();
|
||||
}
|
||||
|
||||
@Override public void onPlaybackChanged() {
|
||||
super.onPlaybackChanged();
|
||||
if (adapter != null) adapter.notifyDataSetChanged();
|
||||
}
|
||||
|
||||
private static String playingOn() {
|
||||
PlaybackService s = PlaybackService.get();
|
||||
return s != null ? s.remoteName() : null;
|
||||
}
|
||||
|
||||
private void onRow(int i) {
|
||||
PlaybackService service = PlaybackService.get();
|
||||
if (service == null) {
|
||||
Ui.toast(this, "Play something first");
|
||||
return;
|
||||
}
|
||||
if (i == 0) {
|
||||
service.disconnectRemote();
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
Speakers.Speaker sp = speakers.get(i - 1);
|
||||
if (!sp.note.isEmpty() || connecting != null) return;
|
||||
if (sp.name.equals(playingOn())) {
|
||||
service.disconnectRemote();
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
connecting = sp.id;
|
||||
adapter.notifyDataSetChanged();
|
||||
new Thread(() -> {
|
||||
Remote remote;
|
||||
String error = null;
|
||||
if (Speakers.CAST.equals(sp.kind)) {
|
||||
CastRemote r = new CastRemote(sp.name, sp.host, sp.port);
|
||||
try { r.connect(); } catch (Exception e) { error = e.getMessage(); }
|
||||
remote = r;
|
||||
} else {
|
||||
AirPlayRemote r = new AirPlayRemote(sp.name, sp.host, sp.port, sp.txt);
|
||||
try { r.connect(); } catch (Exception e) { error = e.getMessage(); }
|
||||
remote = r;
|
||||
}
|
||||
final String why = error;
|
||||
main.post(() -> {
|
||||
connecting = null;
|
||||
adapter.notifyDataSetChanged();
|
||||
if (why != null) {
|
||||
Ui.toast(this, "Couldn't connect to " + sp.name
|
||||
+ (why.isEmpty() ? "" : ": " + why));
|
||||
return;
|
||||
}
|
||||
PlaybackService s = PlaybackService.get();
|
||||
if (s == null || isFinishing()) { remote.close(); return; }
|
||||
s.connectRemote(remote);
|
||||
finish();
|
||||
});
|
||||
}, "andTunes-connect").start();
|
||||
}
|
||||
|
||||
private final class Rows extends BaseAdapter {
|
||||
@Override public int getCount() { return speakers.size() + 1; }
|
||||
@Override public Object getItem(int i) { return i; }
|
||||
@Override public long getItemId(int i) { return i; }
|
||||
@Override public boolean isEnabled(int i) {
|
||||
return i == 0 || speakers.get(i - 1).note.isEmpty();
|
||||
}
|
||||
@Override public boolean areAllItemsEnabled() { return false; }
|
||||
|
||||
@Override public View getView(int i, View convert, ViewGroup parent) {
|
||||
LinearLayout line;
|
||||
TextView title, sub;
|
||||
if (convert == null) {
|
||||
line = new LinearLayout(SpeakersActivity.this);
|
||||
line.setOrientation(LinearLayout.VERTICAL);
|
||||
line.setGravity(Gravity.CENTER_VERTICAL);
|
||||
int pad = Ui.dp(SpeakersActivity.this, 20);
|
||||
line.setPadding(pad, Ui.dp(SpeakersActivity.this, 8), pad,
|
||||
Ui.dp(SpeakersActivity.this, 8));
|
||||
line.setMinimumHeight(Ui.dp(SpeakersActivity.this, Ui.ROW_DP));
|
||||
title = Ui.text(SpeakersActivity.this, Ui.TITLE_SP, false, Ui.BLACK);
|
||||
sub = Ui.text(SpeakersActivity.this, Ui.SUB_SP, false, Ui.DIM);
|
||||
line.addView(title);
|
||||
LinearLayout.LayoutParams slp = new LinearLayout.LayoutParams(
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
slp.topMargin = Ui.dp(SpeakersActivity.this, 4);
|
||||
line.addView(sub, slp);
|
||||
} else {
|
||||
line = (LinearLayout) convert;
|
||||
title = (TextView) line.getChildAt(0);
|
||||
sub = (TextView) line.getChildAt(1);
|
||||
}
|
||||
String on = playingOn();
|
||||
boolean current;
|
||||
boolean usable = true;
|
||||
if (i == 0) {
|
||||
title.setText("This Rabbit");
|
||||
sub.setText(on == null ? "In use" : "Its own speaker");
|
||||
current = on == null;
|
||||
} else {
|
||||
Speakers.Speaker sp = speakers.get(i - 1);
|
||||
title.setText(sp.name);
|
||||
current = sp.name.equals(on);
|
||||
usable = sp.note.isEmpty();
|
||||
String state = sp.id.equals(connecting) ? "Connecting…"
|
||||
: current ? "In use" : !usable ? sp.note : "";
|
||||
sub.setText(sp.kindLabel() + (state.isEmpty() ? "" : " · " + state));
|
||||
}
|
||||
// The output in use is drawn inverted, as the playing song is.
|
||||
line.setBackgroundColor(current ? Ui.BLACK : Ui.WHITE);
|
||||
title.setTextColor(current ? Ui.WHITE : usable ? Ui.BLACK : Ui.DIM);
|
||||
sub.setTextColor(current ? Ui.WHITE : Ui.DIM);
|
||||
return line;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,16 @@ final class Ui {
|
||||
t.setGravity(Gravity.CENTER);
|
||||
}
|
||||
|
||||
/** The same pill around an icon: the icon turns white when it's on. */
|
||||
static void toggleStyle(Context c, ImageView b, boolean on) {
|
||||
GradientDrawable d = new GradientDrawable();
|
||||
d.setCornerRadius(dp(c, 12));
|
||||
d.setStroke(dp(c, 3), BLACK);
|
||||
d.setColor(on ? BLACK : WHITE);
|
||||
b.setBackground(d);
|
||||
b.setColorFilter(on ? WHITE : BLACK, android.graphics.PorterDuff.Mode.SRC_IN);
|
||||
}
|
||||
|
||||
static void toast(Context c, String msg) {
|
||||
Toast.makeText(c.getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.2 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.3 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.6 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.3 KiB |
Reference in New Issue
Block a user