Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

Add-on: Headphones, Bluetooth audio with a quiet guard

מקס חיים165302eb74c1
diff --git a/addons/README.md b/addons/README.md
index 7136a318a..acd2f4893 100644
--- a/addons/README.md
+++ b/addons/README.md
@@ -15,6 +15,7 @@ the core bigger or change how it behaves. You install an add-on only if you want
| [Photo Prints](photo-prints/) | Your own photos as a screensaver: dated prints dealt in on a time-of-day sky, and a card that starts the slideshow | [@shivamsingh262](https://github.com/shivamsingh262) | Sony BRAVIA KD-65X82L (Google TV 12) | None |
| [Photo screensaver](photo-screensaver/) | Your own pictures and MP4 clips as the TV's screensaver and as a card, slowly zooming and crossfading (20 s each by default); optional time, photo dates, prints on a sky and weather | [JorickGU](https://github.com/JorickGU) | TCL 43P69K (Google TV 12) | `INTERNET` and coarse location, only with the weather option on |
| [Prayer Times](prayer-times/) | Today's prayer times for one city from Aladhan (no key), the next prayer with a countdown, Gregorian and Hijri dates | [@majnioui](https://github.com/majnioui) | Xiaomi TV (MiTV-MOOR2), Google TV 11 | `INTERNET` |
+| [Headphones](headphones/) | Bluetooth headphones made easy: where the sound goes, paired pairs with battery, a pairing shortcut, and a quiet guard that pauses and mutes the speakers when headphones drop | [@maxhayim](https://github.com/maxhayim) | Not yet on a TV | Bluetooth (paired devices only) |
A widget, an info tile, a storage or smart-home card: if it can live as its own small app, it can live
here. See the rules below.
diff --git a/addons/brightness/local.properties b/addons/brightness/local.properties
new file mode 100644
index 000000000..bf729038f
--- /dev/null
+++ b/addons/brightness/local.properties
@@ -0,0 +1 @@
+sdk.dir=/opt/homebrew/share/android-commandlinetools
diff --git a/addons/headphones/.gitignore b/addons/headphones/.gitignore
new file mode 100644
index 000000000..a7e04a21b
--- /dev/null
+++ b/addons/headphones/.gitignore
@@ -0,0 +1,4 @@
+.gradle/
+build/
+app/build/
+local.properties
diff --git a/addons/headphones/README.md b/addons/headphones/README.md
new file mode 100644
index 000000000..b71147a1d
--- /dev/null
+++ b/addons/headphones/README.md
@@ -0,0 +1,91 @@
+# Headphones
+
+Bluetooth headphones on the TV, made easy to keep quiet: one screen that shows where the sound goes now, your
+paired headphones with their battery, a shortcut to pairing, and a **quiet guard** that pauses and mutes the
+speakers when headphones drop, so a flat battery doesn't send a film's sound into a room where someone is
+asleep. For the [Clean Your TV](../../README.md) launcher it declares a [module card](../../docs/modules.md):
+once you answer **Show card** its tile reads "Headphones" with a blue glow. On any other Android TV home it is an
+ordinary app.
+
+Opening it shows:
+
+| Row | What it does |
+|---|---|
+| **Sound now plays through** | At the top: the headphones' own name, the TV speakers, or the TV's audio output (ARC or optical). |
+| **Pair or connect headphones** | Opens the TV's Bluetooth settings. Apps can't pair or connect headphones themselves on Android; the TV's settings do that. |
+| **Quiet when they drop** | On by default. When headphones or a Bluetooth speaker disconnect, it sends a pause to whatever is playing and mutes the TV speakers. When they connect again it lifts its own mute (never one you set yourself). |
+| **Unmute the speakers** | Shown only while the guard's mute is on, to lift it by hand. |
+| **Paired headphones and speakers** | Each pair, connected or not, with its battery where the headphones report it. OK opens the Bluetooth settings to connect it. |
+| **Several headphones at once** | What this TV can do for two listeners or more; see below. |
+
+## Several headphones at once
+
+Android TV sends sound to one pair of classic Bluetooth headphones at a time; an app can't change that. The
+screen says what the TV in front of you supports:
+
+- **LE Audio broadcast (Auracast)**, on Android 13+ TVs whose Bluetooth chip has it: any number of Auracast
+ headphones can listen at once, started from the TV's Bluetooth settings.
+- Otherwise, a **dual-link Bluetooth transmitter** on the TV's headphone or optical output feeds two pairs, and
+ some headphones can share their sound with a second pair of the same brand.
+
+## Permissions
+
+| Permission | Why |
+|---|---|
+| Nearby devices (`BLUETOOTH_CONNECT`, Android 12+) | To list paired headphones and whether they're connected, and to receive the connect and disconnect broadcasts the quiet guard acts on. Granted by `install.sh`; otherwise the app asks once. |
+| Bluetooth (`BLUETOOTH`, Android 8 to 11 only) | The same on older versions, granted at install. |
+
+No scanning and no location: it reads only devices already paired in the TV's settings. No internet permission:
+nothing leaves the TV. No accounts, telemetry, ads or libraries. No background service: Android starts the
+quiet guard only for a connect or disconnect broadcast. Muting and the pause key need no permission.
+
+## Build and install
+
+JDK 17 and Android SDK platform 34 with build-tools 34.0.0, as for the launcher. From the repo root, with ADB on:
+
+```bash
+TV_HOST=<tv ip> addons/headphones/install.sh
+```
+
+It builds the add-on, installs it, grants Bluetooth access (and TCL's auto-start), and opens it. Press Home: the
+launcher asks once whether to show the card. Change the answer later by holding OK on Settings, then Module
+cards. To build only: `cd addons/headphones && ./gradlew assembleRelease`; the JVM tests run with
+`./gradlew testReleaseUnitTest`.
+
+The release build is signed with the debug key so it installs over ADB like the launcher. Sign your own builds
+with your own key if you hand them out; the launcher pins its Show answer to the signing key.
+
+## Limits
+
+- **A moment of sound can still escape.** Android reroutes to the speakers as headphones drop, and players
+ that follow Android's rules pause on their own at that moment. The guard's pause and mute follow the
+ disconnect broadcast, a fraction of a second later. Keep the TV's own volume low while headphones are in use
+ for the surest quiet.
+- **Fixed volume.** When the TV's sound goes through HDMI ARC or an amplifier, Android reports a fixed volume
+ and an app can't mute it; the guard then only pauses, and the screen says so.
+- **The pause goes to the app playing media.** Apps without a media session (some live TV and HDMI inputs)
+ ignore it; the mute still applies.
+- **Battery** comes from a call that isn't public Android API. Many TVs answer it; where one doesn't, the
+ battery isn't shown.
+- **Pairing screens differ.** On TVs with no Bluetooth settings screen of their own, the shortcut opens the main
+ Settings instead.
+- **TCL** blocks broadcasts to apps it hasn't allowed to auto-start; `install.sh` allows it.
+
+## Tested on
+
+Not yet on a TV. The JVM tests cover the guard's decisions (audio devices only, pause only on fixed volume,
+unmute only its own mute), the battery and sharing wording, and name cleaning. These checks need a TV and a
+pair of Bluetooth headphones:
+
+1. The card prompt and **Show card**; the card opens the app.
+2. Pairing through the shortcut, then the pair listed as Connected, with its battery where reported.
+3. "Sound now plays through" names the headphones, then the speakers after disconnecting.
+4. With a video playing, switch the headphones off: it pauses and the speakers are muted. Switch them on: the
+ mute is lifted. With the guard off, neither happens.
+5. A remote or keyboard disconnecting never pauses anything.
+6. On a TV with ARC or fixed volume, the screen says so and the guard only pauses.
+7. The sharing line on an Android 13+ TV, with and without LE Audio broadcast.
+
+## Maintainer
+
+[@maxhayim](https://github.com/maxhayim)
diff --git a/addons/headphones/app/build.gradle b/addons/headphones/app/build.gradle
new file mode 100644
index 000000000..2c13151d9
--- /dev/null
+++ b/addons/headphones/app/build.gradle
@@ -0,0 +1,36 @@
+plugins {
+ id 'com.android.application'
+}
+
+android {
+ namespace 'io.github.maxhayim.headphones'
+ compileSdk 34
+
+ defaultConfig {
+ applicationId 'io.github.maxhayim.headphones'
+ minSdk 26
+ targetSdk 34
+ versionCode 1
+ versionName '0.1'
+ }
+
+ buildTypes {
+ release {
+ minifyEnabled true
+ shrinkResources true
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
+ // Sideloaded over ADB, never published: signed with the debug key, like the launcher.
+ signingConfig signingConfigs.debug
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_17
+ targetCompatibility JavaVersion.VERSION_17
+ }
+}
+
+dependencies {
+ // No libraries in the APK. Test only: plain JVM tests in src/test.
+ testImplementation 'junit:junit:4.13.2'
+}
diff --git a/addons/headphones/app/proguard-rules.pro b/addons/headphones/app/proguard-rules.pro
new file mode 100644
index 000000000..a4435d69a
--- /dev/null
+++ b/addons/headphones/app/proguard-rules.pro
@@ -0,0 +1,2 @@
+# Keep class and method names: readable stack traces matter more than the last few KB in a sideloaded app.
+-dontobfuscate
diff --git a/addons/headphones/app/src/main/AndroidManifest.xml b/addons/headphones/app/src/main/AndroidManifest.xml
new file mode 100644
index 000000000..da60f86a7
--- /dev/null
+++ b/addons/headphones/app/src/main/AndroidManifest.xml
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <uses-feature android:name="android.software.leanback" android:required="false" />
+ <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
+ <uses-feature android:name="android.hardware.bluetooth" android:required="false" />
+
+ <!-- Paired headphones, whether they are connected, and the connect/disconnect broadcasts. Android 12+. -->
+ <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
+ <!-- The same on Android 8 to 11. -->
+ <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
+
+ <application
+ android:allowBackup="false"
+ android:banner="@drawable/banner"
+ android:icon="@mipmap/ic_launcher"
+ android:label="@string/app_name"
+ android:theme="@android:style/Theme.DeviceDefault.NoActionBar">
+
+ <activity
+ android:name=".MainActivity"
+ android:exported="true"
+ android:launchMode="singleTask">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
+ </intent-filter>
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="com.gathin.tvhome.category.DOCK_CARD" />
+ </intent-filter>
+ <meta-data android:name="com.gathin.tvhome.card" android:resource="@xml/module_card" />
+ </activity>
+
+ <!-- Quiet guard. Android still delivers these two to manifest receivers; no service runs. -->
+ <receiver
+ android:name=".QuietReceiver"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
+ <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
+ </intent-filter>
+ </receiver>
+ </application>
+</manifest>
diff --git a/addons/headphones/app/src/main/java/io/github/maxhayim/headphones/MainActivity.java b/addons/headphones/app/src/main/java/io/github/maxhayim/headphones/MainActivity.java
new file mode 100644
index 000000000..cb8d9f577
--- /dev/null
+++ b/addons/headphones/app/src/main/java/io/github/maxhayim/headphones/MainActivity.java
@@ -0,0 +1,295 @@
+package io.github.maxhayim.headphones;
+
+import android.Manifest;
+import android.app.Activity;
+import android.bluetooth.BluetoothA2dp;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothClass;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothManager;
+import android.bluetooth.BluetoothProfile;
+import android.content.ActivityNotFoundException;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.SharedPreferences;
+import android.content.pm.PackageManager;
+import android.media.AudioDeviceInfo;
+import android.media.AudioManager;
+import android.os.Build;
+import android.os.Bundle;
+import android.provider.Settings;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.LinearLayout;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * The tile and module card open this: where the sound goes now, the quiet guard, the paired headphones with their
+ * state and battery, and what the TV can do for several listeners. Connecting and pairing happen in the TV's own
+ * Bluetooth settings, which apps can't do for it; OK on a pair opens them.
+ */
+public class MainActivity extends Activity {
+ private static final int ASK_BLUETOOTH = 1;
+
+ private SharedPreferences prefs;
+ private AudioManager audio;
+ private BluetoothAdapter adapter;
+ private BluetoothA2dp a2dp;
+ private LinearLayout rows;
+ private TextView status;
+ /** Redraws when headphones connect or drop while the screen is open. */
+ private final BroadcastReceiver changes = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ build();
+ }
+ };
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ prefs = getSharedPreferences(QuietReceiver.PREFS, MODE_PRIVATE);
+ audio = getSystemService(AudioManager.class);
+ BluetoothManager bm = getSystemService(BluetoothManager.class);
+ adapter = bm == null ? null : bm.getAdapter();
+
+ LinearLayout page = new LinearLayout(this);
+ page.setOrientation(LinearLayout.VERTICAL);
+ page.setBackgroundColor(0xFF0D1117);
+ page.setPadding(px(48), px(32), px(48), px(24));
+ TextView title = new TextView(this);
+ title.setText(R.string.app_name);
+ title.setTextSize(28);
+ title.setTextColor(0xFFFFFFFF);
+ status = new TextView(this);
+ status.setTextSize(15);
+ status.setTextColor(0xFF8B949E);
+ status.setPadding(0, 0, 0, px(16));
+ page.addView(title);
+ page.addView(status);
+ ScrollView scroll = new ScrollView(this);
+ rows = new LinearLayout(this);
+ rows.setOrientation(LinearLayout.VERTICAL);
+ scroll.addView(rows);
+ page.addView(scroll, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f));
+ setContentView(page);
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ IntentFilter f = new IntentFilter();
+ f.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
+ f.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
+ f.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
+ f.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
+ f.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
+ registerReceiver(changes, f);
+ if (allowed() && adapter != null && a2dp == null) {
+ adapter.getProfileProxy(this, new BluetoothProfile.ServiceListener() {
+ @Override
+ public void onServiceConnected(int profile, BluetoothProfile proxy) {
+ a2dp = (BluetoothA2dp) proxy;
+ build();
+ }
+
+ @Override
+ public void onServiceDisconnected(int profile) {
+ a2dp = null;
+ }
+ }, BluetoothProfile.A2DP);
+ }
+ build();
+ }
+
+ @Override
+ protected void onPause() {
+ unregisterReceiver(changes);
+ super.onPause();
+ }
+
+ @Override
+ protected void onDestroy() {
+ if (a2dp != null && adapter != null) adapter.closeProfileProxy(BluetoothProfile.A2DP, a2dp);
+ super.onDestroy();
+ }
+
+ @Override
+ public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] results) {
+ super.onRequestPermissionsResult(requestCode, permissions, results);
+ if (requestCode == ASK_BLUETOOTH) recreate();
+ }
+
+ /** Rebuilds the list; focus stays on the row it was on. */
+ private void build() {
+ int focused = rows.indexOfChild(rows.getFocusedChild());
+ rows.removeAllViews();
+ status.setText("Sound now plays through: " + output());
+ Row first;
+
+ if (!allowed()) {
+ first = add(new Row(this, "Allow Bluetooth access",
+ "To list your headphones and to notice when they drop. OK asks.", this::askBluetooth));
+ first.setValue("Not allowed");
+ } else {
+ first = null;
+ }
+
+ Row pair = add(new Row(this, "Pair or connect headphones",
+ "Opens the TV's Bluetooth settings. Put the headphones in pairing mode first.", this::openBluetooth));
+ if (first == null) first = pair;
+
+ boolean fixed = audio.isVolumeFixed();
+ Row guard = add(new Row(this, "Quiet when they drop", fixed
+ ? "Pauses what plays when headphones disconnect. This TV's volume is fixed (ARC or an amplifier), so it can't also mute the speakers."
+ : "Pauses what plays and mutes the TV speakers when headphones disconnect, so the sound doesn't jump to the room. Unmutes when they're back.",
+ () -> {
+ prefs.edit().putBoolean(QuietReceiver.GUARD, !prefs.getBoolean(QuietReceiver.GUARD, true)).apply();
+ build();
+ }));
+ guard.setValue(prefs.getBoolean(QuietReceiver.GUARD, true) ? "On" : "Off");
+ if (prefs.getBoolean(QuietReceiver.MUTED_BY_US, false)) {
+ Row unmute = add(new Row(this, "Unmute the speakers", "Muted when headphones dropped.", () -> {
+ audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_SHOW_UI);
+ prefs.edit().putBoolean(QuietReceiver.MUTED_BY_US, false).apply();
+ build();
+ }));
+ unmute.setValue("Muted");
+ }
+
+ heading("Paired headphones and speakers");
+ if (adapter == null) {
+ add(new Row(this, "No Bluetooth on this TV", null, null));
+ } else if (!adapter.isEnabled()) {
+ add(new Row(this, "Bluetooth is off", "Switch it on in the TV's settings.", this::openBluetooth));
+ } else if (allowed()) {
+ List<BluetoothDevice> paired = pairedAudio();
+ if (paired.isEmpty()) add(new Row(this, "None yet", "Use the row above to pair some.", null));
+ Set<String> connected = connected();
+ for (BluetoothDevice d : paired) {
+ boolean on = connected.contains(d.getAddress());
+ String battery = on ? Quiet.battery(batteryLevel(d)) : "";
+ Row r = add(new Row(this, name(d),
+ on ? (battery.isEmpty() ? "Connected" : "Connected, battery " + battery) : "Not connected. OK opens Bluetooth settings to connect.",
+ this::openBluetooth));
+ r.setValue(on ? "Connected" : "");
+ }
+ }
+
+ heading("Several headphones at once");
+ add(new Row(this, Quiet.sharing(Build.VERSION.SDK_INT, broadcastSupport()), null, null));
+
+ View keep = focused >= 0 && focused < rows.getChildCount() ? rows.getChildAt(focused) : null;
+ (keep != null && keep.isFocusable() ? keep : first).requestFocus();
+ }
+
+ private Row add(Row r) {
+ rows.addView(r, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
+ return r;
+ }
+
+ private void heading(String text) {
+ TextView h = new TextView(this);
+ h.setText(text);
+ h.setTextSize(13);
+ h.setTextColor(0xFF7C9CFF);
+ h.setPadding(px(16), px(20), 0, px(4));
+ rows.addView(h);
+ }
+
+ private boolean allowed() {
+ if (Build.VERSION.SDK_INT < 31) return true;
+ return checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED;
+ }
+
+ private void askBluetooth() {
+ if (Build.VERSION.SDK_INT >= 31) requestPermissions(new String[]{Manifest.permission.BLUETOOTH_CONNECT}, ASK_BLUETOOTH);
+ }
+
+ private void openBluetooth() {
+ for (String action : new String[]{Settings.ACTION_BLUETOOTH_SETTINGS, Settings.ACTION_SETTINGS}) {
+ try {
+ startActivity(new Intent(action));
+ return;
+ } catch (ActivityNotFoundException | SecurityException ignored) {
+ // Try the next; TV firmware differs in which settings screens it has.
+ }
+ }
+ }
+
+ /** The output Android routes media to now, by the name the headphones give themselves. */
+ private String output() {
+ for (AudioDeviceInfo d : audio.getDevices(AudioManager.GET_DEVICES_OUTPUTS)) {
+ int t = d.getType();
+ boolean bt = t == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP
+ || (Build.VERSION.SDK_INT >= 31 && (t == AudioDeviceInfo.TYPE_BLE_HEADSET || t == AudioDeviceInfo.TYPE_BLE_SPEAKER));
+ if (bt) return Quiet.clean(String.valueOf(d.getProductName()));
+ }
+ return audio.isVolumeFixed() ? "the TV's audio output (HDMI ARC or optical)" : "the TV speakers";
+ }
+
+ private List<BluetoothDevice> pairedAudio() {
+ List<BluetoothDevice> out = new ArrayList<>();
+ try {
+ for (BluetoothDevice d : adapter.getBondedDevices()) {
+ BluetoothClass c = d.getBluetoothClass();
+ if (c != null && Quiet.isAudio(c.getMajorDeviceClass())) out.add(d);
+ }
+ Collections.sort(out, (a, b) -> name(a).compareToIgnoreCase(name(b)));
+ } catch (SecurityException ignored) {
+ // Access taken back while open: the permission row shows next time.
+ }
+ return out;
+ }
+
+ private Set<String> connected() {
+ Set<String> out = new HashSet<>();
+ if (a2dp == null) return out;
+ try {
+ for (BluetoothDevice d : a2dp.getConnectedDevices()) out.add(d.getAddress());
+ } catch (SecurityException ignored) {
+ // As above.
+ }
+ return out;
+ }
+
+ private static String name(BluetoothDevice d) {
+ try {
+ return Quiet.clean(d.getName());
+ } catch (SecurityException e) {
+ return Quiet.clean(null);
+ }
+ }
+
+ /** Not public API: many TVs report it, some refuse the call. -1 hides it. */
+ private static int batteryLevel(BluetoothDevice d) {
+ try {
+ Object v = BluetoothDevice.class.getMethod("getBatteryLevel").invoke(d);
+ return v instanceof Integer ? (Integer) v : -1;
+ } catch (ReflectiveOperationException | RuntimeException e) {
+ return -1;
+ }
+ }
+
+ private int broadcastSupport() {
+ if (Build.VERSION.SDK_INT < 33 || adapter == null) return -1;
+ try {
+ return adapter.isLeAudioBroadcastSourceSupported();
+ } catch (RuntimeException e) {
+ return -1;
+ }
+ }
+
+ private int px(int dp) {
+ return Math.round(dp * getResources().getDisplayMetrics().density);
+ }
+}
diff --git a/addons/headphones/app/src/main/java/io/github/maxhayim/headphones/Quiet.java b/addons/headphones/app/src/main/java/io/github/maxhayim/headphones/Quiet.java
new file mode 100644
index 000000000..034c5138b
--- /dev/null
+++ b/addons/headphones/app/src/main/java/io/github/maxhayim/headphones/Quiet.java
@@ -0,0 +1,62 @@
+package io.github.maxhayim.headphones;
+
+/**
+ * The decisions and the wording, with no Android types, so the JVM tests cover them: what the quiet guard does
+ * when headphones come and go, and what the screen says about batteries and sharing to several headphones.
+ */
+final class Quiet {
+ /** BluetoothClass.Device.Major.AUDIO_VIDEO: headphones, headsets, speakers, hi-fi. */
+ static final int MAJOR_AUDIO_VIDEO = 0x0400;
+ /** BluetoothStatusCodes.FEATURE_SUPPORTED, from BluetoothAdapter's feature checks. */
+ static final int FEATURE_SUPPORTED = 10;
+
+ enum Action { NOTHING, PAUSE, PAUSE_AND_MUTE }
+
+ private Quiet() {
+ }
+
+ static boolean isAudio(int majorDeviceClass) {
+ return majorDeviceClass == MAJOR_AUDIO_VIDEO;
+ }
+
+ /**
+ * Headphones dropped (battery, out of range, switched off): pause what plays, and mute the speakers it would
+ * fall back to. A TV with fixed volume (sound through HDMI ARC or an amplifier) can't be muted from an app,
+ * so there it only pauses.
+ */
+ static Action onDisconnect(boolean guardOn, boolean audio, boolean volumeFixed) {
+ if (!guardOn || !audio) return Action.NOTHING;
+ return volumeFixed ? Action.PAUSE : Action.PAUSE_AND_MUTE;
+ }
+
+ /** Headphones back: undo only a mute this app made, never one the owner set. */
+ static boolean unmuteOnConnect(boolean audio, boolean mutedByUs) {
+ return audio && mutedByUs;
+ }
+
+ /** -1 or anything out of range means the headphones don't report it. */
+ static String battery(int level) {
+ return level >= 0 && level <= 100 ? level + " %" : "";
+ }
+
+ /** What the TV can do for several listeners, from its LE Audio broadcast check (Android 13+). */
+ static String sharing(int sdk, int broadcastSource) {
+ if (sdk < 33) {
+ return "This TV sends sound to one pair of Bluetooth headphones at a time. For two pairs, use a"
+ + " dual-link Bluetooth transmitter on the TV's headphone or optical output.";
+ }
+ if (broadcastSource == FEATURE_SUPPORTED) {
+ return "This TV can broadcast to many LE Audio (Auracast) headphones at once: start sharing from the"
+ + " TV's Bluetooth settings.";
+ }
+ return "This TV sends sound to one pair of Bluetooth headphones at a time; it has no LE Audio broadcast."
+ + " For two pairs, use a dual-link Bluetooth transmitter on the TV's headphone or optical output.";
+ }
+
+ static String clean(String name) {
+ if (name == null) return "Unnamed device";
+ String n = name.replaceAll("\\p{C}", "").trim();
+ if (n.isEmpty()) return "Unnamed device";
+ return n.length() > 40 ? n.substring(0, 40).trim() + "…" : n;
+ }
+}
diff --git a/addons/headphones/app/src/main/java/io/github/maxhayim/headphones/QuietReceiver.java b/addons/headphones/app/src/main/java/io/github/maxhayim/headphones/QuietReceiver.java
new file mode 100644
index 000000000..9285db788
--- /dev/null
+++ b/addons/headphones/app/src/main/java/io/github/maxhayim/headphones/QuietReceiver.java
@@ -0,0 +1,64 @@
+package io.github.maxhayim.headphones;
+
+import android.bluetooth.BluetoothClass;
+import android.bluetooth.BluetoothDevice;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.media.AudioManager;
+import android.os.Build;
+import android.os.SystemClock;
+import android.util.Log;
+import android.view.KeyEvent;
+
+/**
+ * The quiet guard: when headphones drop it pauses what plays and mutes the speakers, so the sound doesn't jump to
+ * the room; when they come back it lifts its own mute. Android wakes it for these broadcasts; nothing runs between.
+ */
+public class QuietReceiver extends BroadcastReceiver {
+ static final String PREFS = "headphones";
+ static final String GUARD = "guard";
+ static final String MUTED_BY_US = "muted_by_us";
+ static final String TAG = "Headphones";
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ String action = intent.getAction();
+ boolean disconnected = BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action);
+ if (!disconnected && !BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) return;
+ BluetoothDevice device = Build.VERSION.SDK_INT >= 33
+ ? intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE, BluetoothDevice.class)
+ : intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+ boolean audio;
+ try {
+ BluetoothClass c = device == null ? null : device.getBluetoothClass();
+ audio = c != null && Quiet.isAudio(c.getMajorDeviceClass());
+ } catch (SecurityException e) {
+ return; // Bluetooth access was taken back; nothing to judge by.
+ }
+ SharedPreferences p = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
+ AudioManager am = context.getSystemService(AudioManager.class);
+ if (disconnected) {
+ Quiet.Action a = Quiet.onDisconnect(p.getBoolean(GUARD, true), audio, am.isVolumeFixed());
+ if (a == Quiet.Action.NOTHING) return;
+ pause(am);
+ if (a == Quiet.Action.PAUSE_AND_MUTE) {
+ am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE, 0);
+ p.edit().putBoolean(MUTED_BY_US, true).apply();
+ }
+ Log.i(TAG, "headphones dropped: " + a);
+ } else if (Quiet.unmuteOnConnect(audio, p.getBoolean(MUTED_BY_US, false))) {
+ am.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE, 0);
+ p.edit().putBoolean(MUTED_BY_US, false).apply();
+ Log.i(TAG, "headphones back: unmuted");
+ }
+ }
+
+ /** A pause key to whatever media session is playing, as the remote's own pause button would send. */
+ private static void pause(AudioManager am) {
+ long t = SystemClock.uptimeMillis();
+ am.dispatchMediaKeyEvent(new KeyEvent(t, t, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PAUSE, 0));
+ am.dispatchMediaKeyEvent(new KeyEvent(t, t, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PAUSE, 0));
+ }
+}
diff --git a/addons/headphones/app/src/main/java/io/github/maxhayim/headphones/Row.java b/addons/headphones/app/src/main/java/io/github/maxhayim/headphones/Row.java
new file mode 100644
index 000000000..95185fe2a
--- /dev/null
+++ b/addons/headphones/app/src/main/java/io/github/maxhayim/headphones/Row.java
@@ -0,0 +1,58 @@
+package io.github.maxhayim.headphones;
+
+import android.content.Context;
+import android.view.Gravity;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+/**
+ * One settings row: a name with a line saying what it does on the left, its value on the right; OK runs it.
+ */
+final class Row extends LinearLayout {
+ private final TextView value;
+ private final TextView desc;
+
+ Row(Context context, String name, String description, Runnable onClick) {
+ super(context);
+ float dp = context.getResources().getDisplayMetrics().density;
+ setOrientation(HORIZONTAL);
+ setGravity(Gravity.CENTER_VERTICAL);
+ int ph = Math.round(16 * dp), pv = Math.round(10 * dp);
+ setPadding(ph, pv, ph, pv);
+ setBackgroundResource(R.drawable.row_background);
+ setFocusable(onClick != null);
+ setClickable(onClick != null);
+ if (onClick != null) setOnClickListener(v -> onClick.run());
+
+ LinearLayout text = new LinearLayout(context);
+ text.setOrientation(VERTICAL);
+ TextView label = new TextView(context);
+ label.setText(name);
+ label.setTextSize(17);
+ label.setTextColor(0xFFFFFFFF);
+ text.addView(label);
+ desc = new TextView(context);
+ desc.setTextSize(12);
+ desc.setTextColor(0xFF8B949E);
+ desc.setPadding(0, Math.round(2 * dp), Math.round(16 * dp), 0);
+ text.addView(desc);
+ setDetail(description);
+ addView(text, new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f));
+
+ value = new TextView(context);
+ value.setTextSize(17);
+ value.setTextColor(0xFFC9D1D9);
+ value.setGravity(Gravity.END);
+ value.setMinWidth(Math.round(90 * dp));
+ addView(value, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
+ }
+
+ void setDetail(String d) {
+ desc.setText(d == null ? "" : d);
+ desc.setVisibility(d == null || d.isEmpty() ? GONE : VISIBLE);
+ }
+
+ void setValue(String v) {
+ value.setText(v);
+ }
+}
diff --git a/addons/headphones/app/src/main/res/drawable/banner.xml b/addons/headphones/app/src/main/res/drawable/banner.xml
new file mode 100644
index 000000000..5f5f1d230
--- /dev/null
+++ b/addons/headphones/app/src/main/res/drawable/banner.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 16:9 banner: a pair of headphones over a dark screen. Own art. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="320dp" android:height="180dp"
+ android:viewportWidth="320" android:viewportHeight="180">
+ <path android:fillColor="#101418" android:pathData="M0,0h320v180h-320z" />
+ <path android:fillColor="#1E2630" android:pathData="M24,24h272v132h-272z" />
+ <path android:strokeColor="#7C9CFF" android:strokeWidth="10" android:fillColor="#00000000"
+ android:pathData="M122,112v-22a38,38 0 0 1 76,0v22" />
+ <path android:fillColor="#7C9CFF" android:pathData="M110,100h22v40h-22z" />
+ <path android:fillColor="#7C9CFF" android:pathData="M188,100h22v40h-22z" />
+</vector>
diff --git a/addons/headphones/app/src/main/res/drawable/ic_foreground.xml b/addons/headphones/app/src/main/res/drawable/ic_foreground.xml
new file mode 100644
index 000000000..e4f9faee7
--- /dev/null
+++ b/addons/headphones/app/src/main/res/drawable/ic_foreground.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Headphones inside the adaptive icon's safe zone. Own art. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp" android:height="108dp"
+ android:viewportWidth="108" android:viewportHeight="108">
+ <path android:strokeColor="#7C9CFF" android:strokeWidth="5" android:fillColor="#00000000"
+ android:pathData="M38,62v-10a16,16 0 0 1 32,0v10" />
+ <path android:fillColor="#7C9CFF" android:pathData="M33,56h10v18h-10z" />
+ <path android:fillColor="#7C9CFF" android:pathData="M65,56h10v18h-10z" />
+</vector>
diff --git a/addons/headphones/app/src/main/res/drawable/row_background.xml b/addons/headphones/app/src/main/res/drawable/row_background.xml
new file mode 100644
index 000000000..03ccab9f5
--- /dev/null
+++ b/addons/headphones/app/src/main/res/drawable/row_background.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- A settings row: transparent until focused, then a glass highlight like the launcher's. -->
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+ <item android:state_focused="true">
+ <shape android:shape="rectangle">
+ <solid android:color="#33FFFFFF" />
+ <stroke android:width="1dp" android:color="#55FFFFFF" />
+ <corners android:radius="12dp" />
+ </shape>
+ </item>
+ <item>
+ <shape android:shape="rectangle">
+ <solid android:color="#00000000" />
+ <corners android:radius="12dp" />
+ </shape>
+ </item>
+</selector>
diff --git a/addons/headphones/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/addons/headphones/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 000000000..0a99b20b1
--- /dev/null
+++ b/addons/headphones/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@android:color/black" />
+ <foreground android:drawable="@drawable/ic_foreground" />
+</adaptive-icon>
diff --git a/addons/headphones/app/src/main/res/values/strings.xml b/addons/headphones/app/src/main/res/values/strings.xml
new file mode 100644
index 000000000..827ee06f2
--- /dev/null
+++ b/addons/headphones/app/src/main/res/values/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Headphones</string>
+</resources>
diff --git a/addons/headphones/app/src/main/res/xml/module_card.xml b/addons/headphones/app/src/main/res/xml/module_card.xml
new file mode 100644
index 000000000..0e52ebaa0
--- /dev/null
+++ b/addons/headphones/app/src/main/res/xml/module_card.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="utf-8"?>
+<card spec="1" label="Headphones" caption="Bluetooth audio" accent="#7C9CFF" />
diff --git a/addons/headphones/app/src/test/java/io/github/maxhayim/headphones/QuietTest.java b/addons/headphones/app/src/test/java/io/github/maxhayim/headphones/QuietTest.java
new file mode 100644
index 000000000..1a8e70556
--- /dev/null
+++ b/addons/headphones/app/src/test/java/io/github/maxhayim/headphones/QuietTest.java
@@ -0,0 +1,63 @@
+package io.github.maxhayim.headphones;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class QuietTest {
+ @Test
+ public void onlyAudioDevicesCount() {
+ assertTrue(Quiet.isAudio(0x0400));
+ assertFalse("the remote and keyboards are peripherals", Quiet.isAudio(0x0500));
+ assertFalse("phones", Quiet.isAudio(0x0200));
+ }
+
+ @Test
+ public void droppedHeadphonesPauseAndMute() {
+ assertEquals(Quiet.Action.PAUSE_AND_MUTE, Quiet.onDisconnect(true, true, false));
+ }
+
+ @Test
+ public void fixedVolumeOnlyPauses() {
+ assertEquals(Quiet.Action.PAUSE, Quiet.onDisconnect(true, true, true));
+ }
+
+ @Test
+ public void guardOffOrNotAudioDoesNothing() {
+ assertEquals(Quiet.Action.NOTHING, Quiet.onDisconnect(false, true, false));
+ assertEquals("a remote dropping never pauses the film", Quiet.Action.NOTHING, Quiet.onDisconnect(true, false, false));
+ }
+
+ @Test
+ public void unmutesOnlyItsOwnMute() {
+ assertTrue(Quiet.unmuteOnConnect(true, true));
+ assertFalse("the owner's own mute stays", Quiet.unmuteOnConnect(true, false));
+ assertFalse(Quiet.unmuteOnConnect(false, true));
+ }
+
+ @Test
+ public void batteryShownOnlyWhenReported() {
+ assertEquals("80 %", Quiet.battery(80));
+ assertEquals("0 %", Quiet.battery(0));
+ assertEquals("", Quiet.battery(-1));
+ assertEquals("", Quiet.battery(101));
+ }
+
+ @Test
+ public void sharingWording() {
+ assertTrue(Quiet.sharing(30, -1).contains("one pair"));
+ assertTrue(Quiet.sharing(34, Quiet.FEATURE_SUPPORTED).contains("Auracast"));
+ assertTrue(Quiet.sharing(34, 11).contains("no LE Audio broadcast"));
+ }
+
+ @Test
+ public void namesAreCleaned() {
+ assertEquals("Unnamed device", Quiet.clean(null));
+ assertEquals("Unnamed device", Quiet.clean(" \u0007 "));
+ assertEquals("WH-1000XM4", Quiet.clean(" WH-1000XM4\n"));
+ String longName = "A".repeat(50);
+ assertEquals("A".repeat(40) + "…", Quiet.clean(longName));
+ }
+}
diff --git a/addons/headphones/build.gradle b/addons/headphones/build.gradle
new file mode 100644
index 000000000..48978475f
--- /dev/null
+++ b/addons/headphones/build.gradle
@@ -0,0 +1,3 @@
+plugins {
+ id 'com.android.application' version '8.5.2' apply false
+}
diff --git a/addons/headphones/gradle.properties b/addons/headphones/gradle.properties
new file mode 100644
index 000000000..18825f968
--- /dev/null
+++ b/addons/headphones/gradle.properties
@@ -0,0 +1,3 @@
+org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
+android.useAndroidX=true
+android.nonTransitiveRClass=true
diff --git a/addons/headphones/gradle/wrapper/gradle-wrapper.jar b/addons/headphones/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 000000000..2c3521197
Binary files /dev/null and b/addons/headphones/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/addons/headphones/gradle/wrapper/gradle-wrapper.properties b/addons/headphones/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000..77f5d0ba6
--- /dev/null
+++ b/addons/headphones/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,8 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
+distributionSha256Sum=d725d707bfabd4dfdc958c624003b3c80accc03f7037b5122c4b1d0ef15cecab
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/addons/headphones/gradlew b/addons/headphones/gradlew
new file mode 100755
index 000000000..f5feea6d6
--- /dev/null
+++ b/addons/headphones/gradlew
@@ -0,0 +1,252 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
+' "$PWD" ) || exit
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ if ! command -v java >/dev/null 2>&1
+ then
+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/addons/headphones/gradlew.bat b/addons/headphones/gradlew.bat
new file mode 100644
index 000000000..9d21a2183
--- /dev/null
+++ b/addons/headphones/gradlew.bat
@@ -0,0 +1,94 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/addons/headphones/install.sh b/addons/headphones/install.sh
new file mode 100755
index 000000000..f7f403beb
--- /dev/null
+++ b/addons/headphones/install.sh
@@ -0,0 +1,28 @@
+#!/usr/bin/env bash
+# Build Headphones, install it on the TV and allow its Bluetooth access, so the TV never has to ask.
+# TV_HOST=<tv ip> addons/headphones/install.sh
+set -euo pipefail
+: "${TV_HOST:?set TV_HOST to the TV IP address}"
+cd "$(dirname "$0")"
+TOOLS="$(cd ../../tools && pwd)"
+PY=$TOOLS/venv/bin/python
+[ -x "$PY" ] || PY=$TOOLS/venv/Scripts/python.exe
+export MSYS_NO_PATHCONV=1
+PKG=io.github.maxhayim.headphones
+# Script paths stay relative: with MSYS_NO_PATHCONV, Git Bash would hand Windows Python a /c/... path.
+tv() { "$PY" -I ../../tools/tv.py "$@"; }
+
+[ -f local.properties ] || { [ -n "${ANDROID_HOME:-}" ] && echo "sdk.dir=$ANDROID_HOME" > local.properties; } || true
+if [ -n "${JAVA_HOME:-}" ]; then export PATH="$JAVA_HOME/bin:$PATH"; fi
+./gradlew assembleRelease -q --console=plain
+
+"$PY" -I ../../tools/b64push.py app/build/outputs/apk/release/app-release.apk /data/local/tmp/headphones.apk
+OUT=$(tv 'pm install -r /data/local/tmp/headphones.apk; rm -f /data/local/tmp/headphones.apk')
+echo "$OUT"
+case "$OUT" in *Success*) ;; *) echo "ERROR: pm install failed" >&2; exit 1 ;; esac
+
+# Bluetooth access on Android 12+ (older versions grant it at install), and TCL's auto-start, which
+# otherwise keeps the quiet guard from waking when headphones drop.
+tv "pm grant $PKG android.permission.BLUETOOTH_CONNECT 2>/dev/null; cmd appops set $PKG APP_AUTO_START allow 2>/dev/null; echo permissions granted"
+tv "am start -n $PKG/.MainActivity >/dev/null; echo opened"
+echo "Installed. Headphones is open on the TV; press Home and answer Show card for the card."
diff --git a/addons/headphones/settings.gradle b/addons/headphones/settings.gradle
new file mode 100644
index 000000000..4c76036b1
--- /dev/null
+++ b/addons/headphones/settings.gradle
@@ -0,0 +1,16 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+rootProject.name = "headphones"
+include ':app'