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).
@@ -671,6 +671,15 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
|
|||||||
`lintunes/android/andTunes.apk` with its version in `andTunes.json`;
|
`lintunes/android/andTunes.apk` with its version in `andTunes.json`;
|
||||||
**re-run `--ship` whenever the app changes**, since the committed APK is
|
**re-run `--ship` whenever the app changes**, since the committed APK is
|
||||||
what the self-updater carries and what `install.py` installs.
|
what the self-updater carries and what `install.py` installs.
|
||||||
|
**App v0.4.0** (Round 92): the menu is a list, Now Playing has icon
|
||||||
|
pills and a full-screen art / album link, and a speakers pill plays the
|
||||||
|
queue on AirPlay (`AirPlayRemote`, raop.py in Java) or Chromecast
|
||||||
|
(`CastRemote`, the Cast protocol by hand) — see andtunes/README.md.
|
||||||
|
Test speakers only against shairport-sync in Docker published on this
|
||||||
|
machine's LAN address (its avahi stays on the Docker bridge, so it is
|
||||||
|
never advertised), listed in the device's `Music/andTunes/speakers.txt`
|
||||||
|
— **never** connect the Rabbit to a speaker that isn't trav's, and read
|
||||||
|
a screencap before every `input tap`: the picker lists the neighbours'.
|
||||||
`andtunes/andtunes.keystore` is committed on purpose (both machines must
|
`andtunes/andtunes.keystore` is committed on purpose (both machines must
|
||||||
sign identically or `adb install -r` refuses the update). `install.py` is
|
sign identically or `adb install -r` refuses the update). `install.py` is
|
||||||
Connections → Install andTunes on Rabbit…: adb as a runtime tool, then the
|
Connections → Install andTunes on Rabbit…: adb as a runtime tool, then the
|
||||||
|
|||||||
@@ -46,9 +46,9 @@ Density is overridden to 160, so an app sees a 480 × 640 **dp** canvas — but
|
|||||||
the panel is 2.88", about 278 real ppi. **One dp is roughly half its usual
|
the panel is 2.88", about 278 real ppi. **One dp is roughly half its usual
|
||||||
physical size here.** A stock 48 dp list row is 4.4 mm tall and unusable.
|
physical size here.** A stock 48 dp list row is 4.4 mm tall and unusable.
|
||||||
|
|
||||||
> **Rule: double every stock dp value.** Body text 28–32 sp, list rows ≥ 88 dp,
|
> **Rule: double every stock dp value.** Body text 28–32 sp, list rows ≥ 88 dp.
|
||||||
> menu tiles ~213 dp. A 2 × 3 grid gives six 240 × 213 dp buttons, ≈ 22 × 19 mm
|
> The main menu (a list since v0.4.0) sizes its rows so exactly six fill the
|
||||||
> each.
|
> space the status and navigation bars leave, ≈ 84 dp each.
|
||||||
|
|
||||||
Do **not** "fix" this by changing the device's density. trav has it where he
|
Do **not** "fix" this by changing the device's density. trav has it where he
|
||||||
wants it and asked for it to be left alone.
|
wants it and asked for it to be left alone.
|
||||||
@@ -160,9 +160,34 @@ Target: menu visible in **under 400 ms**.
|
|||||||
`library.json`, which isn't media — that's the whole reason. Fallback if it
|
`library.json`, which isn't media — that's the whole reason. Fallback if it
|
||||||
turns out to be blocked: a one-time SAF folder pick.
|
turns out to be blocked: a one-time SAF folder pick.
|
||||||
- **Screens are activities**, so "the last screen we were at" is Android's own
|
- **Screens are activities**, so "the last screen we were at" is Android's own
|
||||||
back stack with no bookkeeping. `MenuActivity` (six tiles, loads nothing),
|
back stack with no bookkeeping. `MenuActivity` (a list, loads nothing:
|
||||||
one generic `ListActivity` parameterised for every list in the spec,
|
Now Playing / Shuffle All on top, Settings at the bottom), one generic
|
||||||
`NowPlayingActivity`, and a foreground `PlaybackService`.
|
`ListActivity` parameterised for every list in the spec,
|
||||||
|
`NowPlayingActivity` (tap the art for it full screen, the title for its
|
||||||
|
album; shuffle · repeat · speakers as icon pills), `SettingsActivity`
|
||||||
|
(version and library so far), and a foreground `PlaybackService`.
|
||||||
|
- **Speakers** (v0.4.0, `SpeakersActivity`): the speakers pill lists this
|
||||||
|
Rabbit and every AirPlay speaker (`_raop._tcp`) and Chromecast
|
||||||
|
(`_googlecast._tcp`) NsdManager finds, resolved one at a time (Android 13
|
||||||
|
refuses a second concurrent resolve). Picking one hands the queue to a
|
||||||
|
`Remote`; `PlaybackService` keeps queue, shuffle, repeat and play counts
|
||||||
|
either way, holds a wake + Wi-Fi lock while one is connected, and going
|
||||||
|
back to the Rabbit leaves it *paused*. The wheel drives the speaker's
|
||||||
|
volume. No SDKs, by the same rule as everything else:
|
||||||
|
- `CastRemote` speaks the Cast protocol itself (TLS :8009, length-prefixed
|
||||||
|
protobuf `CastMessage` frames — encoded by hand, checked byte-identical
|
||||||
|
to pychromecast's — with JSON payloads), launches the Default Media
|
||||||
|
Receiver and hands it a URL on `MediaServer`, a token-only HTTP server
|
||||||
|
with Range, so the speaker fetches the original file (the desktop's
|
||||||
|
media-receiver model). **Untested on a real Chromecast so far.**
|
||||||
|
- `AirPlayRemote` is the desktop's `airplay/raop.py` in Java (libraop's
|
||||||
|
RAOP behaviour: auth-setup, AppleLossless, RECORD with RTP-Info, a 2 s
|
||||||
|
buffer, NTP-locked timestamps, timing responder, resends), decoding with
|
||||||
|
MediaExtractor + MediaCodec to 44.1 kHz stereo and sending uncompressed
|
||||||
|
ALAC (byte-identical to `support.alac_verbatim`). Verified from the R1
|
||||||
|
against shairport-sync: the receiver's output matched the song.
|
||||||
|
- `Music/andTunes/speakers.txt` lists speakers by address for when mDNS
|
||||||
|
can't see them: `airplay|cast <host> [port] [name]` per line.
|
||||||
- **No back button on the now-playing screen** — Android's own is always on
|
- **No back button on the now-playing screen** — Android's own is always on
|
||||||
screen and the panel is tiny (trav's call).
|
screen and the panel is tiny (trav's call).
|
||||||
- **End of a queue pauses.** It does not roll into shuffle-all. Repeat is
|
- **End of a queue pauses.** It does not roll into shuffle-all. Repeat is
|
||||||
@@ -183,7 +208,8 @@ authority and `manifest.py` for the exact rows.
|
|||||||
Media/<Artist>/<Album>/04 Song.mp3
|
Media/<Artist>/<Album>/04 Song.mp3
|
||||||
Art/<8-hex album key>.jpg 480 px, one per album
|
Art/<8-hex album key>.jpg 480 px, one per album
|
||||||
Playlists/<Name>.m3u entries are ../Media/… relative paths
|
Playlists/<Name>.m3u entries are ../Media/… relative paths
|
||||||
Buttons/*.png the user's own menu artwork — app reads only
|
Buttons/*.png the user's own button artwork — app reads only
|
||||||
|
speakers.txt optional: speakers by address (see Speakers)
|
||||||
plays/andtunes-<installid>.json the app writes counts back here (phase 3)
|
plays/andtunes-<installid>.json the app writes counts back here (phase 3)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,12 @@
|
|||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<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
|
<application
|
||||||
android:label="andTunes"
|
android:label="andTunes"
|
||||||
@@ -34,6 +40,10 @@
|
|||||||
<activity android:name=".NowPlayingActivity" android:exported="false"
|
<activity android:name=".NowPlayingActivity" android:exported="false"
|
||||||
android:launchMode="singleTop" />
|
android:launchMode="singleTop" />
|
||||||
|
|
||||||
|
<activity android:name=".SettingsActivity" android:exported="false" />
|
||||||
|
|
||||||
|
<activity android:name=".SpeakersActivity" android:exported="false" />
|
||||||
|
|
||||||
<service android:name=".PlaybackService" android:exported="false"
|
<service android:name=".PlaybackService" android:exported="false"
|
||||||
android:foregroundServiceType="mediaPlayback" />
|
android:foregroundServiceType="mediaPlayback" />
|
||||||
</application>
|
</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 {
|
abstract class BaseActivity extends Activity implements PlaybackService.Listener {
|
||||||
protected AudioManager audio;
|
protected AudioManager audio;
|
||||||
private TextView nowBar;
|
private TextView nowBar;
|
||||||
|
private static android.widget.Toast volumeToast;
|
||||||
|
|
||||||
@Override protected void onCreate(Bundle state) {
|
@Override protected void onCreate(Bundle state) {
|
||||||
super.onCreate(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) {
|
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,
|
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
|
||||||
dir > 0 ? AudioManager.ADJUST_RAISE : AudioManager.ADJUST_LOWER,
|
dir > 0 ? AudioManager.ADJUST_RAISE : AudioManager.ADJUST_LOWER,
|
||||||
AudioManager.FLAG_SHOW_UI);
|
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.Gravity;
|
||||||
import android.view.View;
|
import android.view.View;
|
||||||
import android.view.ViewGroup;
|
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.LinearLayout;
|
||||||
import android.widget.TextView;
|
import android.widget.TextView;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The first screen, and the number the project is judged on: six tiles,
|
* The first screen, and the number the project is judged on: visible in well
|
||||||
* visible in well under 400 ms. It <b>loads nothing</b> — it only starts the
|
* under 400 ms. It <b>loads nothing</b> — it only starts the library parse in
|
||||||
* library parse in the background, so the data is usually ready by the time a
|
* the background, so the data is usually ready by the time a finger lands.
|
||||||
* finger lands on a tile.
|
*
|
||||||
|
* <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 {
|
public class MenuActivity extends BaseActivity {
|
||||||
private static final String[] MODES = {
|
private static final String[] MODES = {
|
||||||
ListActivity.PLAYLISTS, ListActivity.ARTISTS, ListActivity.ALBUMS,
|
ListActivity.PLAYLISTS, ListActivity.ARTISTS, ListActivity.ALBUMS,
|
||||||
ListActivity.SONGS, ListActivity.SEARCH};
|
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 String[] LABELS = {"Playlists", "Artists", "Albums", "Songs", "Search"};
|
||||||
private static final int[] ART = {
|
/** Rows: [0] Now Playing / Shuffle All, then LABELS, then Settings. */
|
||||||
R.drawable.playlists, R.drawable.artists, R.drawable.albums,
|
private static final int ROWS = LABELS.length + 2;
|
||||||
R.drawable.songs, R.drawable.search};
|
private static final int ROW_DP = 84;
|
||||||
|
|
||||||
private ImageView sixth;
|
|
||||||
private Boolean builtWithAccess;
|
private Boolean builtWithAccess;
|
||||||
private boolean sixthShowsNowPlaying;
|
private BaseAdapter adapter;
|
||||||
|
private ListView list;
|
||||||
|
private WheelScroll wheel;
|
||||||
|
|
||||||
@Override protected void onCreate(Bundle state) {
|
@Override protected void onCreate(Bundle state) {
|
||||||
super.onCreate(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() {
|
private void build() {
|
||||||
builtWithAccess = hasAccess();
|
builtWithAccess = hasAccess();
|
||||||
if (!builtWithAccess) {
|
if (!builtWithAccess) {
|
||||||
@@ -62,38 +78,68 @@ public class MenuActivity extends BaseActivity {
|
|||||||
requestPermissions(new String[] {Manifest.permission.POST_NOTIFICATIONS}, 1);
|
requestPermissions(new String[] {Manifest.permission.POST_NOTIFICATIONS}, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
LinearLayout grid = new LinearLayout(this);
|
LinearLayout column = new LinearLayout(this);
|
||||||
grid.setOrientation(LinearLayout.VERTICAL);
|
column.setOrientation(LinearLayout.VERTICAL);
|
||||||
int pad = Ui.dp(this, 4);
|
TextView titleBar = Ui.text(this, 26, true, Ui.WHITE);
|
||||||
grid.setPadding(pad, pad, pad, pad);
|
titleBar.setBackgroundColor(Ui.BLACK);
|
||||||
LinearLayout row = null;
|
titleBar.setGravity(Gravity.CENTER_VERTICAL);
|
||||||
for (int i = 0; i < 6; i++) {
|
int pad = Ui.dp(this, 20);
|
||||||
if (i % 2 == 0) {
|
titleBar.setPadding(pad, 0, pad, 0);
|
||||||
row = new LinearLayout(this);
|
titleBar.setText("andTunes");
|
||||||
grid.addView(row, new LinearLayout.LayoutParams(
|
column.addView(titleBar, new LinearLayout.LayoutParams(
|
||||||
ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f));
|
ViewGroup.LayoutParams.MATCH_PARENT, Ui.dp(this, 64)));
|
||||||
}
|
|
||||||
ImageView tile = new ImageView(this);
|
list = new ListView(this);
|
||||||
tile.setScaleType(ImageView.ScaleType.FIT_CENTER);
|
list.setDivider(new ColorDrawable(Ui.BLACK));
|
||||||
tile.setPadding(pad, pad, pad, pad);
|
list.setDividerHeight(Ui.dp(this, 1));
|
||||||
if (i < 5) {
|
list.setBackgroundColor(Ui.WHITE);
|
||||||
final int n = i;
|
adapter = new BaseAdapter() {
|
||||||
tile.setImageDrawable(Ui.button(this, NAMES[i], ART[i]));
|
@Override public int getCount() { return ROWS; }
|
||||||
tile.setContentDescription(LABELS[i]);
|
@Override public Object getItem(int i) { return i; }
|
||||||
tile.setOnClickListener(v -> startActivity(
|
@Override public long getItemId(int i) { return i; }
|
||||||
new Intent(this, ListActivity.class).putExtra(ListActivity.MODE, MODES[n])));
|
@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 {
|
} else {
|
||||||
sixth = tile;
|
row.setText("Settings");
|
||||||
tile.setOnClickListener(v -> onSixth());
|
|
||||||
}
|
}
|
||||||
row.addView(tile, new LinearLayout.LayoutParams(0,
|
return row;
|
||||||
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();
|
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() {
|
private static boolean hasTrack() {
|
||||||
PlaybackService s = PlaybackService.get();
|
PlaybackService s = PlaybackService.get();
|
||||||
return s != null && s.current() != null;
|
return s != null && s.current() != null;
|
||||||
@@ -101,17 +147,11 @@ public class MenuActivity extends BaseActivity {
|
|||||||
|
|
||||||
@Override public void onPlaybackChanged() {
|
@Override public void onPlaybackChanged() {
|
||||||
super.onPlaybackChanged();
|
super.onPlaybackChanged();
|
||||||
if (sixth == null) return;
|
if (adapter != null) adapter.notifyDataSetChanged(); // Now Playing / Shuffle All
|
||||||
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");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** "Now Playing" when there is something, else shuffle everything we know. */
|
/** "Now Playing" when there is something, else shuffle everything we know. */
|
||||||
private void onSixth() {
|
private void onFirst() {
|
||||||
if (hasTrack()) {
|
if (hasTrack()) {
|
||||||
openNowPlaying();
|
openNowPlaying();
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -14,15 +14,20 @@ import android.widget.SeekBar;
|
|||||||
import android.widget.TextView;
|
import android.widget.TextView;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* White background, square art, a slim scrubber, ◀ ⏯ ▶, then shuffle and
|
* White background, square art, a slim scrubber, ◀ ⏯ ▶, then shuffle, repeat
|
||||||
* repeat. <b>No back button</b> — Android's own is always on screen, and the
|
* and speakers as icon pills. <b>No back button</b> — Android's own is always
|
||||||
* panel is too small to spend on a second one (trav's call). The wheel stays
|
* on screen, and the panel is too small to spend on a second one (trav's
|
||||||
* volume here: this is the one screen where that's the useful thing.
|
* 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 {
|
public class NowPlayingActivity extends BaseActivity {
|
||||||
private final Handler main = new Handler(Looper.getMainLooper());
|
private final Handler main = new Handler(Looper.getMainLooper());
|
||||||
private ImageView art, playPause;
|
private ImageView art, playPause, shuffleBtn, repeatBtn, speakersBtn, bigArt;
|
||||||
private TextView title, detail, elapsed, remaining, shuffleBtn, repeatBtn;
|
private TextView title, detail, elapsed, remaining;
|
||||||
|
private Drawable shuffleD, repeatD, repeatOneD, speakersD;
|
||||||
private SeekBar scrubber;
|
private SeekBar scrubber;
|
||||||
private boolean dragging;
|
private boolean dragging;
|
||||||
private Library.Track shown;
|
private Library.Track shown;
|
||||||
@@ -52,6 +57,7 @@ public class NowPlayingActivity extends BaseActivity {
|
|||||||
ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f);
|
ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f);
|
||||||
alp.gravity = Gravity.CENTER_HORIZONTAL;
|
alp.gravity = Gravity.CENTER_HORIZONTAL;
|
||||||
col.addView(art, alp);
|
col.addView(art, alp);
|
||||||
|
art.setOnClickListener(v -> showBigArt(true));
|
||||||
|
|
||||||
title = Ui.text(this, 26, true, Ui.BLACK);
|
title = Ui.text(this, 26, true, Ui.BLACK);
|
||||||
title.setGravity(Gravity.CENTER);
|
title.setGravity(Gravity.CENTER);
|
||||||
@@ -63,6 +69,8 @@ public class NowPlayingActivity extends BaseActivity {
|
|||||||
LinearLayout.LayoutParams dlp = wrap();
|
LinearLayout.LayoutParams dlp = wrap();
|
||||||
dlp.topMargin = Ui.dp(this, 4);
|
dlp.topMargin = Ui.dp(this, 4);
|
||||||
col.addView(detail, dlp);
|
col.addView(detail, dlp);
|
||||||
|
title.setOnClickListener(v -> openAlbum());
|
||||||
|
detail.setOnClickListener(v -> openAlbum());
|
||||||
|
|
||||||
scrubber = new SeekBar(this);
|
scrubber = new SeekBar(this);
|
||||||
ColorStateList black = ColorStateList.valueOf(Ui.BLACK);
|
ColorStateList black = ColorStateList.valueOf(Ui.BLACK);
|
||||||
@@ -106,17 +114,53 @@ public class NowPlayingActivity extends BaseActivity {
|
|||||||
col.addView(transport, new LinearLayout.LayoutParams(
|
col.addView(transport, new LinearLayout.LayoutParams(
|
||||||
ViewGroup.LayoutParams.MATCH_PARENT, Ui.dp(this, 96)));
|
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);
|
LinearLayout toggles = new LinearLayout(this);
|
||||||
shuffleBtn = toggle(toggles, "Shuffle");
|
shuffleBtn = toggle(toggles, shuffleD, "Shuffle");
|
||||||
repeatBtn = toggle(toggles, "Repeat");
|
repeatBtn = toggle(toggles, repeatD, "Repeat");
|
||||||
|
speakersBtn = toggle(toggles, speakersD, "Speakers");
|
||||||
shuffleBtn.setOnClickListener(v -> withService(s -> s.setShuffle(!s.shuffle())));
|
shuffleBtn.setOnClickListener(v -> withService(s -> s.setShuffle(!s.shuffle())));
|
||||||
repeatBtn.setOnClickListener(v -> withService(PlaybackService::cycleRepeat));
|
repeatBtn.setOnClickListener(v -> withService(PlaybackService::cycleRepeat));
|
||||||
|
speakersBtn.setOnClickListener(v -> startActivity(
|
||||||
|
new android.content.Intent(this, SpeakersActivity.class)));
|
||||||
LinearLayout.LayoutParams glp = new LinearLayout.LayoutParams(
|
LinearLayout.LayoutParams glp = new LinearLayout.LayoutParams(
|
||||||
ViewGroup.LayoutParams.MATCH_PARENT, Ui.dp(this, 64));
|
ViewGroup.LayoutParams.MATCH_PARENT, Ui.dp(this, 64));
|
||||||
glp.topMargin = Ui.dp(this, 8);
|
glp.topMargin = Ui.dp(this, 8);
|
||||||
col.addView(toggles, glp);
|
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() {
|
private LinearLayout.LayoutParams wrap() {
|
||||||
@@ -134,15 +178,20 @@ public class NowPlayingActivity extends BaseActivity {
|
|||||||
return b;
|
return b;
|
||||||
}
|
}
|
||||||
|
|
||||||
private TextView toggle(LinearLayout row, String label) {
|
private ImageView toggle(LinearLayout row, Drawable icon, String label) {
|
||||||
TextView t = Ui.text(this, 22, true, Ui.BLACK);
|
ImageView b = new ImageView(this);
|
||||||
t.setText(label);
|
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(
|
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
|
||||||
0, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
|
0, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
|
||||||
int m = Ui.dp(this, 6);
|
int m = Ui.dp(this, 6);
|
||||||
lp.setMargins(m, 0, m, 0);
|
lp.setMargins(m, 0, m, 0);
|
||||||
row.addView(t, lp);
|
row.addView(b, lp);
|
||||||
return t;
|
return b;
|
||||||
}
|
}
|
||||||
|
|
||||||
private interface Action { void run(PlaybackService s); }
|
private interface Action { void run(PlaybackService s); }
|
||||||
@@ -200,8 +249,10 @@ public class NowPlayingActivity extends BaseActivity {
|
|||||||
playPause.setContentDescription(s.isPlaying() ? "Pause" : "Play");
|
playPause.setContentDescription(s.isPlaying() ? "Pause" : "Play");
|
||||||
Ui.toggleStyle(this, shuffleBtn, s.shuffle());
|
Ui.toggleStyle(this, shuffleBtn, s.shuffle());
|
||||||
int r = s.repeat();
|
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");
|
: r == PlaybackService.REPEAT_ALL ? "Repeat all" : "Repeat");
|
||||||
Ui.toggleStyle(this, repeatBtn, r != PlaybackService.REPEAT_OFF);
|
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
|
public class PlaybackService extends Service implements
|
||||||
MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener,
|
MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener,
|
||||||
MediaPlayer.OnErrorListener, AudioManager.OnAudioFocusChangeListener {
|
MediaPlayer.OnErrorListener, AudioManager.OnAudioFocusChangeListener,
|
||||||
|
Remote.Events {
|
||||||
|
|
||||||
interface Listener { void onPlaybackChanged(); }
|
interface Listener { void onPlaybackChanged(); }
|
||||||
|
|
||||||
@@ -79,6 +80,11 @@ public class PlaybackService extends Service implements
|
|||||||
private int failures;
|
private int failures;
|
||||||
private final History history = new History();
|
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 ----
|
// ---- the static front door ----
|
||||||
|
|
||||||
static PlaybackService get() { return sService; }
|
static PlaybackService get() { return sService; }
|
||||||
@@ -173,7 +179,7 @@ public class PlaybackService extends Service implements
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override public void onTaskRemoved(Intent rootIntent) {
|
@Override public void onTaskRemoved(Intent rootIntent) {
|
||||||
if (!playing) stopSelf();
|
if (!playing && remote == null) stopSelf();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override public void onDestroy() {
|
@Override public void onDestroy() {
|
||||||
@@ -182,6 +188,8 @@ public class PlaybackService extends Service implements
|
|||||||
abandonFocus();
|
abandonFocus();
|
||||||
unregisterNoisy();
|
unregisterNoisy();
|
||||||
main.removeCallbacksAndMessages(null);
|
main.removeCallbacksAndMessages(null);
|
||||||
|
if (remote != null) { remote.close(); remote = null; }
|
||||||
|
holdRemoteLocks(false);
|
||||||
session.release();
|
session.release();
|
||||||
mp.release();
|
mp.release();
|
||||||
notifications.cancel(NOTIFICATION_ID);
|
notifications.cancel(NOTIFICATION_ID);
|
||||||
@@ -204,13 +212,19 @@ public class PlaybackService extends Service implements
|
|||||||
|
|
||||||
int repeat() { return repeat; }
|
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() {
|
int position() {
|
||||||
if (!prepared) return pendingSeek;
|
if (!prepared) return pendingSeek;
|
||||||
|
if (remote != null) return remote.position();
|
||||||
try { return mp.getCurrentPosition(); } catch (IllegalStateException e) { return 0; }
|
try { return mp.getCurrentPosition(); } catch (IllegalStateException e) { return 0; }
|
||||||
}
|
}
|
||||||
|
|
||||||
int duration() {
|
int duration() {
|
||||||
if (prepared) {
|
if (prepared && remote == null) {
|
||||||
try { return mp.getDuration(); } catch (IllegalStateException ignored) { }
|
try { return mp.getDuration(); } catch (IllegalStateException ignored) { }
|
||||||
}
|
}
|
||||||
Library.Track t = current();
|
Library.Track t = current();
|
||||||
@@ -224,14 +238,18 @@ public class PlaybackService extends Service implements
|
|||||||
void play() {
|
void play() {
|
||||||
if (current() == null) return;
|
if (current() == null) return;
|
||||||
if (!prepared) { playWhenReady = true; return; }
|
if (!prepared) { playWhenReady = true; return; }
|
||||||
|
if (remote != null) {
|
||||||
|
remote.play();
|
||||||
|
} else {
|
||||||
if (audio.requestAudioFocus(focusRequest) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
|
if (audio.requestAudioFocus(focusRequest) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
mp.setVolume(1f, 1f);
|
mp.setVolume(1f, 1f);
|
||||||
mp.start();
|
mp.start();
|
||||||
|
}
|
||||||
playing = true;
|
playing = true;
|
||||||
history.playing(current());
|
history.playing(current());
|
||||||
registerNoisy();
|
if (remote == null) registerNoisy();
|
||||||
goForeground();
|
goForeground();
|
||||||
tick();
|
tick();
|
||||||
changed();
|
changed();
|
||||||
@@ -240,7 +258,8 @@ public class PlaybackService extends Service implements
|
|||||||
void pause() {
|
void pause() {
|
||||||
playWhenReady = false;
|
playWhenReady = false;
|
||||||
if (playing) {
|
if (playing) {
|
||||||
try { mp.pause(); } catch (IllegalStateException ignored) { }
|
if (remote != null) remote.pause();
|
||||||
|
else try { mp.pause(); } catch (IllegalStateException ignored) { }
|
||||||
}
|
}
|
||||||
playing = false;
|
playing = false;
|
||||||
history.paused();
|
history.paused();
|
||||||
@@ -256,7 +275,8 @@ public class PlaybackService extends Service implements
|
|||||||
}
|
}
|
||||||
|
|
||||||
void seekTo(int ms) {
|
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;
|
else pendingSeek = ms;
|
||||||
changed();
|
changed();
|
||||||
}
|
}
|
||||||
@@ -335,8 +355,9 @@ public class PlaybackService extends Service implements
|
|||||||
// End of the queue pauses, parked at the top of the last song.
|
// End of the queue pauses, parked at the top of the last song.
|
||||||
playing = false;
|
playing = false;
|
||||||
pendingSeek = 0;
|
pendingSeek = 0;
|
||||||
if (prepared) mp.seekTo(0);
|
if (prepared && remote == null) mp.seekTo(0);
|
||||||
pause();
|
pause();
|
||||||
|
if (remote != null) { prepared = false; pendingSeek = 0; }
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -354,6 +375,16 @@ public class PlaybackService extends Service implements
|
|||||||
prepared = false;
|
prepared = false;
|
||||||
playWhenReady = play;
|
playWhenReady = play;
|
||||||
pendingSeek = seekMs;
|
pendingSeek = seekMs;
|
||||||
|
if (remote != null) {
|
||||||
|
if (!t.file().isFile()) {
|
||||||
|
skipBroken(t, "missing");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
remote.load(t, seekMs, play);
|
||||||
|
saveState();
|
||||||
|
changed();
|
||||||
|
return;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
mp.reset();
|
mp.reset();
|
||||||
if (!t.file().isFile()) throw new java.io.FileNotFoundException(t.path);
|
if (!t.file().isFile()) throw new java.io.FileNotFoundException(t.path);
|
||||||
@@ -408,9 +439,99 @@ public class PlaybackService extends Service implements
|
|||||||
return true;
|
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 ----
|
// ---- audio focus, noisy ----
|
||||||
|
|
||||||
@Override public void onAudioFocusChange(int change) {
|
@Override public void onAudioFocusChange(int change) {
|
||||||
|
if (remote != null) return; // the speaker isn't ours to duck
|
||||||
switch (change) {
|
switch (change) {
|
||||||
case AudioManager.AUDIOFOCUS_LOSS:
|
case AudioManager.AUDIOFOCUS_LOSS:
|
||||||
resumeOnFocus = false;
|
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);
|
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) {
|
static void toast(Context c, String msg) {
|
||||||
Toast.makeText(c.getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
|
Toast.makeText(c.getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
|
||||||
}
|
}
|
||||||
|
|||||||
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 2.3 KiB |
@@ -26,8 +26,8 @@ import sys
|
|||||||
import zipfile
|
import zipfile
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
VERSION_NAME = "0.3.0"
|
VERSION_NAME = "0.4.0"
|
||||||
VERSION_CODE = 6
|
VERSION_CODE = 7
|
||||||
|
|
||||||
PACKAGE = "me.teafry.andtunes"
|
PACKAGE = "me.teafry.andtunes"
|
||||||
MIN_SDK = 26
|
MIN_SDK = 26
|
||||||
|
|||||||
@@ -42,6 +42,9 @@ MENU = {
|
|||||||
}
|
}
|
||||||
ICON = 128
|
ICON = 128
|
||||||
TRANSPORT = ("prev", "play", "pause", "next")
|
TRANSPORT = ("prev", "play", "pause", "next")
|
||||||
|
# Now Playing's bottom row: icons inside the toggle pills (drawn black; the
|
||||||
|
# app tints them white when the pill is on).
|
||||||
|
TOGGLES = ("shuffle", "repeat", "repeat_one", "speakers")
|
||||||
|
|
||||||
|
|
||||||
def _canvas(w, h):
|
def _canvas(w, h):
|
||||||
@@ -97,6 +100,77 @@ def transport(name: str, color="black", size=ICON) -> QImage:
|
|||||||
return image
|
return image
|
||||||
|
|
||||||
|
|
||||||
|
def toggle_icon(name: str, color="black", size=ICON) -> QImage:
|
||||||
|
from PyQt6.QtGui import QPen
|
||||||
|
image, p = _canvas(size, size)
|
||||||
|
s = size / 128
|
||||||
|
pen = QPen(QColor(color), 10 * s)
|
||||||
|
pen.setCapStyle(Qt.PenCapStyle.FlatCap)
|
||||||
|
pen.setJoinStyle(Qt.PenJoinStyle.MiterJoin)
|
||||||
|
p.setPen(pen)
|
||||||
|
p.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
|
||||||
|
def head(x, y, right=True):
|
||||||
|
# a solid arrowhead whose point is at (x, y)
|
||||||
|
d = 1 if right else -1
|
||||||
|
p.save()
|
||||||
|
p.setPen(Qt.PenStyle.NoPen)
|
||||||
|
p.setBrush(QColor(color))
|
||||||
|
p.drawPolygon(QPolygonF([QPointF(x, y), QPointF(x - d * 22 * s, y - 16 * s),
|
||||||
|
QPointF(x - d * 22 * s, y + 16 * s)]))
|
||||||
|
p.restore()
|
||||||
|
|
||||||
|
if name == "shuffle":
|
||||||
|
# two strands that cross, each ending in an arrow on the right
|
||||||
|
a = QPainterPath(QPointF(14 * s, 38 * s))
|
||||||
|
a.cubicTo(QPointF(60 * s, 38 * s), QPointF(60 * s, 90 * s),
|
||||||
|
QPointF(96 * s, 90 * s))
|
||||||
|
b = QPainterPath(QPointF(14 * s, 90 * s))
|
||||||
|
b.cubicTo(QPointF(60 * s, 90 * s), QPointF(60 * s, 38 * s),
|
||||||
|
QPointF(96 * s, 38 * s))
|
||||||
|
p.drawPath(a)
|
||||||
|
p.drawPath(b)
|
||||||
|
head(116 * s, 38 * s)
|
||||||
|
head(116 * s, 90 * s)
|
||||||
|
elif name in ("repeat", "repeat_one"):
|
||||||
|
# a loop: top run left to right, bottom run back, rounded ends
|
||||||
|
loop = QPainterPath(QPointF(30 * s, 64 * s))
|
||||||
|
loop.lineTo(30 * s, 52 * s)
|
||||||
|
loop.arcTo(QRectF(30 * s, 32 * s, 40 * s, 40 * s), 180, -90)
|
||||||
|
loop.lineTo(92 * s, 32 * s)
|
||||||
|
p.drawPath(loop)
|
||||||
|
head(114 * s, 32 * s)
|
||||||
|
back = QPainterPath(QPointF(98 * s, 64 * s))
|
||||||
|
back.lineTo(98 * s, 76 * s)
|
||||||
|
back.arcTo(QRectF(58 * s, 56 * s, 40 * s, 40 * s), 0, -90)
|
||||||
|
back.lineTo(36 * s, 96 * s)
|
||||||
|
p.drawPath(back)
|
||||||
|
head(14 * s, 96 * s, right=False)
|
||||||
|
if name == "repeat_one":
|
||||||
|
font = QFont("DejaVu Sans")
|
||||||
|
font.setPixelSize(int(34 * s))
|
||||||
|
font.setBold(True)
|
||||||
|
p.setFont(font)
|
||||||
|
p.setPen(QColor(color))
|
||||||
|
p.drawText(QRectF(44 * s, 40 * s, 40 * s, 48 * s),
|
||||||
|
int(Qt.AlignmentFlag.AlignCenter), "1")
|
||||||
|
elif name == "speakers":
|
||||||
|
# broadcast: a dot with two arcs either side, (( • ))
|
||||||
|
p.save()
|
||||||
|
p.setPen(Qt.PenStyle.NoPen)
|
||||||
|
p.setBrush(QColor(color))
|
||||||
|
p.drawEllipse(QPointF(64 * s, 64 * s), 11 * s, 11 * s)
|
||||||
|
p.restore()
|
||||||
|
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||||
|
p.setPen(pen)
|
||||||
|
for r in (30, 52):
|
||||||
|
box = QRectF((64 - r) * s, (64 - r) * s, 2 * r * s, 2 * r * s)
|
||||||
|
p.drawArc(box, -45 * 16, 90 * 16)
|
||||||
|
p.drawArc(box, 135 * 16, 90 * 16)
|
||||||
|
p.end()
|
||||||
|
return image
|
||||||
|
|
||||||
|
|
||||||
def launcher() -> QImage:
|
def launcher() -> QImage:
|
||||||
size = 192
|
size = 192
|
||||||
image, p = _canvas(size, size)
|
image, p = _canvas(size, size)
|
||||||
@@ -125,10 +199,12 @@ def main():
|
|||||||
save(tile(label), name, RES, SHIP)
|
save(tile(label), name, RES, SHIP)
|
||||||
for name in TRANSPORT:
|
for name in TRANSPORT:
|
||||||
save(transport(name), name, RES, SHIP)
|
save(transport(name), name, RES, SHIP)
|
||||||
|
for name in TOGGLES:
|
||||||
|
save(toggle_icon(name), name, RES, SHIP)
|
||||||
save(launcher(), "ic_launcher", RES)
|
save(launcher(), "ic_launcher", RES)
|
||||||
# Status-bar icons must be white-on-transparent; Android tints by alpha.
|
# Status-bar icons must be white-on-transparent; Android tints by alpha.
|
||||||
save(transport("play", "white", 96), "ic_notify", RES)
|
save(transport("play", "white", 96), "ic_notify", RES)
|
||||||
print(f"wrote {len(MENU) + len(TRANSPORT)} buttons to {RES} and {SHIP}")
|
print(f"wrote {len(MENU) + len(TRANSPORT) + len(TOGGLES)} buttons to {RES} and {SHIP}")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
"""LinTunes — iTunes-style music library manager and player for Linux."""
|
"""LinTunes — iTunes-style music library manager and player for Linux."""
|
||||||
|
|
||||||
__version__ = "0.61.1"
|
__version__ = "0.62.0"
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
{"version_name": "0.3.0", "version_code": 6}
|
{"version_name": "0.4.0", "version_code": 7}
|
||||||
|
|||||||
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 2.3 KiB |