Skip to content

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

addons: photo screensaver, your own pictures and MP4 clips (TCL 43P69K)

JorickGUbf17377211a4
diff --git a/addons/README.md b/addons/README.md
index 4669c0347..e68a7e631 100644
--- a/addons/README.md
+++ b/addons/README.md
@@ -13,6 +13,7 @@ the core bigger or change how it behaves. You install an add-on only if you want
| [Capacity Stats](capacity-stats/) | Available/total and used/total RAM; available/total storage | [lionlev21](https://github.com/lionlev21) | Android TV 12 (model private) | None |
| [Weather](weather/) | The weather for one city: now, US air quality and the next three days, from Open-Meteo (no key) | [@Sumyabazar1](https://github.com/Sumyabazar1) | Hisense SmartTV 4K FFM (lushan), Google TV 12 | `INTERNET` |
| [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, slowly zooming and crossfading (20 s each by default); no module card, it is a system screensaver | [JorickGU](https://github.com/JorickGU) | TCL 43P69K (Google TV 12) | None |
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/photo-screensaver/.gitignore b/addons/photo-screensaver/.gitignore
new file mode 100644
index 000000000..c33becf92
--- /dev/null
+++ b/addons/photo-screensaver/.gitignore
@@ -0,0 +1,5 @@
+# Local build output and your own pictures stay out of git.
+.gradle/
+build/
+local.properties
+/pictures/
diff --git a/addons/photo-screensaver/README.md b/addons/photo-screensaver/README.md
new file mode 100644
index 000000000..2d55e2dd0
--- /dev/null
+++ b/addons/photo-screensaver/README.md
@@ -0,0 +1,70 @@
+# Photo screensaver
+
+A system screensaver (Android's "Daydream") for any Android TV or Google TV that shows your own pictures
+and MP4 clips, separate from the launcher. Pictures go in filename order, each slowly zooming and drifting
+and crossfading into the next after 20 seconds (or what you set). A clip plays once, muted and cropped to
+fill the screen, then the loop moves on; a lone clip loops. Any key wakes the TV back to where it was.
+
+Package `com.gathin.photodream`, about 15 KB. It has no launcher icon: you see it as **Photos** (Dutch:
+**Foto's**) in the TV's screensaver settings.
+
+## Install
+
+JDK 17 and Android SDK 34, as for the launcher, and the `tools/venv` from the main README.
+
+```sh
+TV_HOST=192.168.1.50 addons/photo-screensaver/build-and-install.sh
+```
+
+```powershell
+powershell -ExecutionPolicy Bypass -File addons\photo-screensaver\build-and-install.ps1 -TvHost 192.168.1.50
+```
+
+## Your pictures
+
+Create a `pictures/` folder here (it is gitignored, so your pictures stay yours), put pictures (JPG, PNG,
+WebP, up to 10 MB, 4K at most) and MP4 clips (H.264 or HEVC, up to 1 GB) in it, named with letters, digits,
+`-`, `_` and `.` only, at most 100 files, and run:
+
+```sh
+TV_HOST=192.168.1.50 addons/photo-screensaver/sync.sh # or pass another folder
+TV_HOST=192.168.1.50 SECONDS_PER_PICTURE=30 IDLE_MINUTES=5 START=1 addons/photo-screensaver/sync.sh
+TV_HOST=192.168.1.50 addons/photo-screensaver/sync.sh --off # previous screensaver back
+```
+
+```powershell
+addons\photo-screensaver\sync.ps1 -TvHost 192.168.1.50 [-Seconds 30] [-IdleMinutes 5] [-Start]
+addons\photo-screensaver\sync.ps1 -TvHost 192.168.1.50 -Off
+```
+
+It makes Photos the TV's screensaver and syncs the folder by md5: only new or changed files are sent, and
+files you removed are removed from the TV. A sync that broke off (standby, Wi-Fi drop) is finished by
+running it again. Files go through the shell as base64, about 200 KB/s, so keep clips short: a minute of
+1080p at 8 Mbit/s is about 60 MB, roughly five minutes to send. The screensaver the TV had before the
+first run is remembered for `--off`; `build-and-install.sh --uninstall` does `--off` and removes the app.
+
+`IDLE_MINUTES` sets `screen_off_timeout`, after which the TV starts its screensaver. You can also pick
+Photos yourself in the TV's screensaver settings.
+
+## Memory
+
+At most two screen-sized pictures are held, as GPU bitmaps, and one hardware video player. A 4K picture
+is decoded at screen size. On a TCL 43P69K (1.5 GB) a 1080p clip played with the screensaver at about
+42 MB and 705 MB RAM still free.
+
+## Permissions
+
+None. No network, no storage permission, no background service: the pictures stay on the TV in the app's
+own folder (`Android/data/com.gathin.photodream/files/pictures`), removed with the app.
+
+- **`FilesProvider`** (exported) is how `sync.sh` writes the pictures, so the app owns them: on TCL G10 a
+ file the adb shell copies into `Android/data` is unreadable for the app. Only callers holding
+ `WRITE_SECURE_SETTINGS` may use it, which the adb shell has and ordinary apps cannot get, and only
+ picture and clip names and `seconds.txt` are accepted.
+- **`PhotoDream`** is the screensaver service, bound by the system only (`BIND_DREAM_SERVICE`).
+- **TCL only:** `build-and-install.sh` allows `APP_AUTO_START` with `appops`, because TCL's TclAppBoot
+ blocks the provider without it. Elsewhere that op doesn't exist and the line does nothing.
+
+## Tested on
+
+TCL 43P69K (G10, Google TV 12, Realtek), Netherlands.
diff --git a/addons/photo-screensaver/app/build.gradle b/addons/photo-screensaver/app/build.gradle
new file mode 100644
index 000000000..349af1c2b
--- /dev/null
+++ b/addons/photo-screensaver/app/build.gradle
@@ -0,0 +1,36 @@
+plugins {
+ id 'com.android.application'
+}
+
+android {
+ namespace 'com.gathin.photodream'
+ compileSdk 34
+
+ defaultConfig {
+ applicationId 'com.gathin.photodream'
+ // DreamService with a hardware bitmap and TextureView: Android 8 and up, as the launcher.
+ minSdk 26
+ targetSdk 34
+ versionCode 1
+ versionName '1.0'
+ }
+
+ buildTypes {
+ release {
+ minifyEnabled true
+ shrinkResources true
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
+ // Sideloaded over ADB, never published: sign with the debug key so it installs over a debug build.
+ signingConfig signingConfigs.debug
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_17
+ targetCompatibility JavaVersion.VERSION_17
+ }
+}
+
+dependencies {
+ testImplementation 'junit:junit:4.13.2'
+}
diff --git a/addons/photo-screensaver/app/proguard-rules.pro b/addons/photo-screensaver/app/proguard-rules.pro
new file mode 100644
index 000000000..7bb3d36ed
--- /dev/null
+++ b/addons/photo-screensaver/app/proguard-rules.pro
@@ -0,0 +1,4 @@
+# Shrink and optimise, but keep class and method names: the size win comes from dropping unused
+# AndroidX code, not from renaming, and readable stack traces matter more in a sideloaded app
+# where crash reports arrive as screenshots.
+-dontobfuscate
diff --git a/addons/photo-screensaver/app/src/main/AndroidManifest.xml b/addons/photo-screensaver/app/src/main/AndroidManifest.xml
new file mode 100644
index 000000000..7637d4ad1
--- /dev/null
+++ b/addons/photo-screensaver/app/src/main/AndroidManifest.xml
@@ -0,0 +1,34 @@
+<?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" />
+
+ <!-- No permissions: the pictures come in over ADB through FilesProvider and stay on the TV. -->
+ <application
+ android:allowBackup="false"
+ android:label="@string/app_name"
+ android:supportsRtl="true">
+
+ <!-- `settings put secure screensaver_components com.gathin.photodream/.PhotoDream` (sync.sh does it). -->
+ <service
+ android:name=".PhotoDream"
+ android:label="@string/dream_name"
+ android:exported="true"
+ android:permission="android.permission.BIND_DREAM_SERVICE">
+ <intent-filter>
+ <action android:name="android.service.dreams.DreamService" />
+ <category android:name="android.intent.category.DEFAULT" />
+ </intent-filter>
+ </service>
+
+ <!-- sync.sh writes the pictures through this: on TCL G10 a file the shell copies into Android/data
+ belongs to the shell and the app gets EACCES reading it. WRITE_SECURE_SETTINGS: the adb shell has
+ it, ordinary apps don't. -->
+ <provider
+ android:name=".FilesProvider"
+ android:authorities="com.gathin.photodream.files"
+ android:exported="true"
+ android:permission="android.permission.WRITE_SECURE_SETTINGS" />
+ </application>
+</manifest>
diff --git a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/FilesProvider.java b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/FilesProvider.java
new file mode 100644
index 000000000..44496373b
--- /dev/null
+++ b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/FilesProvider.java
@@ -0,0 +1,68 @@
+package com.gathin.photodream;
+
+import android.content.ContentProvider;
+import android.content.ContentValues;
+import android.database.Cursor;
+import android.net.Uri;
+import android.os.ParcelFileDescriptor;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+
+/**
+ * Lets sync.sh write the pictures into the app's own files dir, so the app owns them. Only the names
+ * {@link Media} allows, and only for callers holding WRITE_SECURE_SETTINGS (the adb shell).
+ *
+ * content write --uri content://com.gathin.photodream.files/pictures/sea.jpg < /data/local/tmp/sea.jpg
+ * content write --uri content://com.gathin.photodream.files/seconds.txt < /data/local/tmp/seconds.txt
+ * content delete --uri content://com.gathin.photodream.files/pictures/sea.jpg
+ * content delete --uri content://com.gathin.photodream.files/pictures (every picture and clip)
+ */
+public class FilesProvider extends ContentProvider {
+
+ private File dir() {
+ return getContext() == null ? null : getContext().getExternalFilesDir(null);
+ }
+
+ private File file(Uri uri) throws FileNotFoundException {
+ String path = Media.path(uri.getPathSegments());
+ File dir = dir();
+ if (dir == null || path == null) throw new FileNotFoundException(String.valueOf(uri));
+ File f = new File(dir, path);
+ File parent = f.getParentFile();
+ if (parent != null && !parent.isDirectory() && !parent.mkdirs()) throw new FileNotFoundException(String.valueOf(uri));
+ return f;
+ }
+
+ @Override
+ public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
+ File f = file(uri);
+ if (mode.contains("w")) {
+ return ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_WRITE_ONLY
+ | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE);
+ }
+ return ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
+ }
+
+ @Override
+ public int delete(Uri uri, String selection, String[] selectionArgs) {
+ File dir = dir();
+ if (dir != null && Media.isFolder(uri.getPathSegments())) {
+ File[] files = new File(dir, Media.PICTURES).listFiles((d, name) -> Media.file(name));
+ int n = 0;
+ if (files != null) for (File f : files) if (f.delete()) n++;
+ return n;
+ }
+ try {
+ return file(uri).delete() ? 1 : 0;
+ } catch (FileNotFoundException e) {
+ return 0;
+ }
+ }
+
+ @Override public boolean onCreate() { return true; }
+ @Override public String getType(Uri uri) { return null; }
+ @Override public Cursor query(Uri uri, String[] p, String s, String[] a, String o) { return null; }
+ @Override public Uri insert(Uri uri, ContentValues values) { return null; }
+ @Override public int update(Uri uri, ContentValues v, String s, String[] a) { return 0; }
+}
diff --git a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Media.java b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Media.java
new file mode 100644
index 000000000..4e5fab0f5
--- /dev/null
+++ b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/Media.java
@@ -0,0 +1,108 @@
+package com.gathin.photodream;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.regex.Pattern;
+
+/** Which files the screensaver shows and FilesProvider accepts, and how big a picture is decoded. */
+final class Media {
+ static final String PICTURES = "pictures";
+ static final String SECONDS = "seconds.txt";
+ static final int DEFAULT_SECONDS = 20;
+ static final int MAX_FILES = 100;
+ static final long IMAGE_MAX = 10L * 1024 * 1024;
+ static final long VIDEO_MAX = 1024L * 1024 * 1024;
+ /** 4K UHD and a little more; a bigger picture is skipped rather than decoded on a 1 GB TV. */
+ static final long MAX_PIXELS = 8_400_000L;
+
+ private static final Pattern IMAGE = Pattern.compile("[A-Za-z0-9_.-]+\\.(jpg|jpeg|png|webp)",
+ Pattern.CASE_INSENSITIVE);
+ private static final Pattern VIDEO = Pattern.compile("[A-Za-z0-9_.-]+\\.mp4", Pattern.CASE_INSENSITIVE);
+
+ private Media() {}
+
+ static boolean image(String name) {
+ return name != null && !name.startsWith(".") && IMAGE.matcher(name).matches();
+ }
+
+ static boolean video(String name) {
+ return name != null && !name.startsWith(".") && VIDEO.matcher(name).matches();
+ }
+
+ static boolean file(String name) {
+ return image(name) || video(name);
+ }
+
+ /** The path under the files dir that a provider URI may write or delete, or null. */
+ static String path(List<String> segments) {
+ if (segments == null) return null;
+ if (segments.size() == 1 && SECONDS.equals(segments.get(0))) return SECONDS;
+ if (segments.size() == 2 && PICTURES.equals(segments.get(0)) && file(segments.get(1))) {
+ return PICTURES + "/" + segments.get(1);
+ }
+ return null;
+ }
+
+ /** True for "pictures" alone: a delete of it clears every picture and clip. */
+ static boolean isFolder(List<String> segments) {
+ return segments != null && segments.size() == 1 && PICTURES.equals(segments.get(0));
+ }
+
+ /** The folder's pictures and clips by name, at most 100; empty and oversized files are left out. */
+ static List<File> list(File folder) {
+ List<File> result = new ArrayList<>();
+ File[] entries = folder == null ? null : folder.listFiles();
+ if (entries == null) return result;
+ Arrays.sort(entries, Comparator.comparing(File::getName));
+ for (File entry : entries) {
+ if (!entry.isFile() || entry.length() <= 0) continue;
+ String name = entry.getName();
+ boolean ok = video(name) ? entry.length() <= VIDEO_MAX : image(name) && entry.length() <= IMAGE_MAX;
+ if (ok) result.add(entry);
+ if (result.size() == MAX_FILES) break;
+ }
+ return result;
+ }
+
+ /** The file after {@code previous} by name, wrapping around; the first one when previous is gone. */
+ static File next(List<File> files, String previous) {
+ if (files.isEmpty()) return null;
+ for (int i = 0; i < files.size(); i++) {
+ if (files.get(i).getName().equals(previous)) return files.get((i + 1) % files.size());
+ }
+ return files.get(0);
+ }
+
+ /** seconds.txt's number, 5 to 3600; 20 when it is missing or not a number. */
+ static int seconds(String text) {
+ if (text == null) return DEFAULT_SECONDS;
+ try {
+ int s = Integer.parseInt(text.trim());
+ return s < 5 || s > 3600 ? DEFAULT_SECONDS : s;
+ } catch (NumberFormatException e) {
+ return DEFAULT_SECONDS;
+ }
+ }
+
+ static boolean accepted(int width, int height) {
+ return width > 0 && height > 0 && (long) width * height <= MAX_PIXELS;
+ }
+
+ /** The largest power-of-two sample size that still covers the screen in both directions. */
+ static int sampleSize(int width, int height, int screenW, int screenH) {
+ int sample = 1;
+ while (width / (sample * 2) >= screenW && height / (sample * 2) >= screenH) sample *= 2;
+ return sample;
+ }
+
+ /** {inDensity, inTargetDensity} that scale a sampled picture down to what CENTER_CROP shows, or null. */
+ static int[] coverScale(int width, int height, int screenW, int screenH) {
+ if ((long) screenW * height >= (long) screenH * width) {
+ return width > screenW ? new int[]{width, screenW} : null;
+ }
+ return height > screenH ? new int[]{height, screenH} : null;
+ }
+}
diff --git a/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/PhotoDream.java b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/PhotoDream.java
new file mode 100644
index 000000000..db12a2819
--- /dev/null
+++ b/addons/photo-screensaver/app/src/main/java/com/gathin/photodream/PhotoDream.java
@@ -0,0 +1,343 @@
+package com.gathin.photodream;
+
+import android.animation.AnimatorSet;
+import android.animation.ObjectAnimator;
+import android.animation.PropertyValuesHolder;
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.Color;
+import android.graphics.Matrix;
+import android.graphics.SurfaceTexture;
+import android.media.MediaPlayer;
+import android.os.Handler;
+import android.os.Looper;
+import android.service.dreams.DreamService;
+import android.util.DisplayMetrics;
+import android.view.Surface;
+import android.view.TextureView;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.animation.LinearInterpolator;
+import android.widget.FrameLayout;
+import android.widget.ImageView;
+
+import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Random;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+/**
+ * Photo screensaver: loops through the pictures sync.sh put in the app's pictures/ folder, in filename order,
+ * each slowly zooming and drifting (Ken Burns) and crossfading into the next after seconds.txt (20 s by
+ * default). Two screen-sized pictures at most, held as GPU bitmaps; no network. MP4 clips play once, muted
+ * and cropped to fill the screen, on the hardware decoder (one player at a time), then the loop moves on.
+ */
+public class PhotoDream extends DreamService {
+
+ private static final long FADE_MS = 1500L;
+ /** How far a picture zooms in over its time on screen; it drifts at most half the extra width. */
+ private static final float ZOOM = 1.12f;
+
+ private final Handler handler = new Handler(Looper.getMainLooper());
+ private final Random random = new Random();
+ private ExecutorService decoder;
+ private ImageView front;
+ private ImageView back;
+ private TextureView video;
+ private MediaPlayer player;
+ private Surface surface;
+ /** A clip waiting for the TextureView's surface. */
+ private File pendingClip;
+ /** Bumped for every clip so callbacks of a released player are ignored. */
+ private int clipGeneration;
+ private List<File> images = new ArrayList<>();
+ private SharedPreferences preferences;
+ private long interval;
+ private int width;
+ private int height;
+ private boolean running;
+
+ private final Runnable advance = this::showNext;
+
+ @Override
+ public void onAttachedToWindow() {
+ super.onAttachedToWindow();
+ setInteractive(false); // any key wakes the TV back to where it was
+ setFullscreen(true);
+ FrameLayout root = new FrameLayout(this);
+ root.setBackgroundColor(Color.BLACK);
+ video = new TextureView(this);
+ video.setAlpha(0f);
+ video.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
+ @Override public void onSurfaceTextureAvailable(SurfaceTexture texture, int w, int h) {
+ surface = new Surface(texture);
+ File clip = pendingClip;
+ pendingClip = null;
+ if (clip != null && running) playVideo(clip);
+ }
+ @Override public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int w, int h) {}
+ @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {
+ stopVideo();
+ if (surface != null) surface.release();
+ surface = null;
+ return true;
+ }
+ @Override public void onSurfaceTextureUpdated(SurfaceTexture texture) {}
+ });
+ root.addView(video, new FrameLayout.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
+ back = image(root);
+ front = image(root);
+ setContentView(root);
+ DisplayMetrics metrics = getResources().getDisplayMetrics();
+ width = metrics.widthPixels;
+ height = metrics.heightPixels;
+ preferences = getSharedPreferences("photo_dream", Context.MODE_PRIVATE);
+ File dir = getExternalFilesDir(null);
+ interval = Media.seconds(read(dir == null ? null : new File(dir, Media.SECONDS))) * 1000L;
+ images = Media.list(dir == null ? null : new File(dir, Media.PICTURES));
+ }
+
+ private ImageView image(FrameLayout root) {
+ ImageView view = new ImageView(this);
+ view.setScaleType(ImageView.ScaleType.CENTER_CROP);
+ view.setAlpha(0f);
+ root.addView(view, new FrameLayout.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
+ return view;
+ }
+
+ private static String read(File file) {
+ try {
+ return file != null && file.isFile() && file.length() < 64
+ ? new String(Files.readAllBytes(file.toPath()), StandardCharsets.US_ASCII) : null;
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ static boolean isVideo(File file) {
+ return file != null && Media.video(file.getName());
+ }
+
+ @Override
+ public void onDreamingStarted() {
+ super.onDreamingStarted();
+ running = true;
+ decoder = Executors.newSingleThreadExecutor();
+ showNext();
+ }
+
+ @Override
+ public void onDreamingStopped() {
+ stopSlides();
+ super.onDreamingStopped();
+ }
+
+ @Override
+ public void onDetachedFromWindow() {
+ stopSlides();
+ super.onDetachedFromWindow();
+ }
+
+ private void stopSlides() {
+ running = false;
+ handler.removeCallbacksAndMessages(null);
+ if (decoder != null) decoder.shutdownNow();
+ decoder = null;
+ if (front != null) { cancel(front); release(front); }
+ if (back != null) { cancel(back); release(back); }
+ pendingClip = null;
+ stopVideo();
+ }
+
+ /** Decodes the next picture off the main thread, then fades it in over the current one. */
+ private void showNext() {
+ if (!running || images.isEmpty() || decoder == null) return;
+ decoder.execute(() -> {
+ Bitmap bitmap = null;
+ File clip = null;
+ // Skip unreadable pictures, but stop after one round so a folder of broken files doesn't spin.
+ for (int tries = 0; tries < images.size() && bitmap == null && clip == null; tries++) {
+ File file = Media.next(images, preferences.getString("image", ""));
+ preferences.edit().putString("image", file.getName()).apply();
+ if (isVideo(file)) clip = file;
+ else bitmap = decode(file);
+ }
+ Bitmap shown = bitmap;
+ File playing = clip;
+ handler.post(() -> {
+ if (!running) {
+ if (shown != null) shown.recycle();
+ return;
+ }
+ if (playing != null) {
+ playVideo(playing); // moves on when the clip ends
+ return;
+ }
+ if (shown != null) crossfade(shown);
+ // A single picture still drifts on: it fades into itself with a new zoom.
+ handler.postDelayed(advance, interval);
+ });
+ });
+ }
+
+ private void crossfade(Bitmap bitmap) {
+ ImageView incoming = back;
+ ImageView outgoing = front;
+ back = outgoing;
+ front = incoming;
+ cancel(incoming);
+ release(incoming);
+ incoming.setImageBitmap(bitmap);
+ incoming.setTag(bitmap);
+ incoming.bringToFront();
+ // Start zoomed in or out at random and drift toward a random spot, over the whole slide.
+ boolean zoomIn = random.nextBoolean();
+ float from = zoomIn ? 1f : ZOOM;
+ float to = zoomIn ? ZOOM : 1f;
+ float dx = (random.nextFloat() - 0.5f) * width * (ZOOM - 1f);
+ float dy = (random.nextFloat() - 0.5f) * height * (ZOOM - 1f);
+ incoming.setAlpha(0f);
+ ObjectAnimator fade = ObjectAnimator.ofFloat(incoming, View.ALPHA, 0f, 1f).setDuration(FADE_MS);
+ ObjectAnimator drift = ObjectAnimator.ofPropertyValuesHolder(incoming,
+ PropertyValuesHolder.ofFloat(View.SCALE_X, from, to),
+ PropertyValuesHolder.ofFloat(View.SCALE_Y, from, to),
+ PropertyValuesHolder.ofFloat(View.TRANSLATION_X, zoomIn ? 0f : dx, zoomIn ? dx : 0f),
+ PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, zoomIn ? 0f : dy, zoomIn ? dy : 0f))
+ .setDuration(interval + 2 * FADE_MS);
+ drift.setInterpolator(new LinearInterpolator());
+ AnimatorSet set = new AnimatorSet();
+ set.playTogether(fade, drift);
+ incoming.setTag(R.id.animation, set);
+ set.start();
+ boolean afterClip = player != null;
+ handler.postDelayed(() -> {
+ cancel(outgoing);
+ outgoing.setAlpha(0f);
+ release(outgoing);
+ if (afterClip) stopVideo();
+ }, FADE_MS + 100);
+ }
+
+ /** Fades the clip in over whatever shows now and plays it to the end (or loops a lone clip). */
+ private void playVideo(File clip) {
+ if (surface == null) {
+ pendingClip = clip;
+ return;
+ }
+ boolean clipShowing = player != null;
+ stopVideo();
+ int generation = ++clipGeneration;
+ MediaPlayer mp = new MediaPlayer();
+ player = mp;
+ try {
+ mp.setDataSource(clip.getPath());
+ mp.setSurface(surface);
+ mp.setVolume(0f, 0f);
+ mp.setLooping(images.size() == 1);
+ mp.setOnVideoSizeChangedListener((p, w, h) -> cover(w, h));
+ mp.setOnPreparedListener(p -> {
+ if (generation != clipGeneration || !running) return;
+ p.start();
+ video.bringToFront();
+ if (clipShowing) video.setAlpha(1f);
+ else video.animate().alpha(1f).setDuration(FADE_MS).start();
+ handler.postDelayed(() -> {
+ if (generation != clipGeneration) return;
+ for (ImageView view : new ImageView[] {front, back}) {
+ cancel(view);
+ view.setAlpha(0f);
+ release(view);
+ }
+ }, FADE_MS + 100);
+ });
+ mp.setOnCompletionListener(p -> {
+ if (generation == clipGeneration && running) showNext();
+ });
+ mp.setOnErrorListener((p, what, extra) -> {
+ if (generation == clipGeneration && running) {
+ stopVideo();
+ handler.postDelayed(advance, 1000);
+ }
+ return true;
+ });
+ mp.prepareAsync();
+ } catch (Exception failure) {
+ stopVideo();
+ handler.postDelayed(advance, 1000);
+ }
+ }
+
+ /** Scales the clip to fill the screen, cropping the overflow evenly (like CENTER_CROP). */
+ private void cover(int videoWidth, int videoHeight) {
+ int w = video.getWidth(), h = video.getHeight();
+ if (videoWidth <= 0 || videoHeight <= 0 || w <= 0 || h <= 0) return;
+ float scale = Math.max((float) w / videoWidth, (float) h / videoHeight);
+ Matrix matrix = new Matrix();
+ matrix.setScale(videoWidth * scale / w, videoHeight * scale / h, w / 2f, h / 2f);
+ video.setTransform(matrix);
+ }
+
+ private void stopVideo() {
+ clipGeneration++;
+ if (video != null) {
+ video.animate().cancel();
+ video.setAlpha(0f);
+ }
+ if (player != null) {
+ try { player.stop(); } catch (IllegalStateException ignored) { }
+ player.release();
+ player = null;
+ }
+ }
+
+ private static void cancel(ImageView view) {
+ Object set = view.getTag(R.id.animation);
+ if (set instanceof AnimatorSet) ((AnimatorSet) set).cancel();
+ view.setTag(R.id.animation, null);
+ }
+
+ /** Frees the view's picture now instead of waiting for the garbage collector. */
+ private static void release(ImageView view) {
+ Object old = view.getTag();
+ view.setImageDrawable(null);
+ view.setTag(null);
+ if (old instanceof Bitmap) ((Bitmap) old).recycle();
+ }
+
+ private Bitmap decode(File file) {
+ try {
+ BitmapFactory.Options options = new BitmapFactory.Options();
+ options.inJustDecodeBounds = true;
+ BitmapFactory.decodeFile(file.getPath(), options);
+ int w = options.outWidth, h = options.outHeight;
+ if (w <= 0 || h <= 0) return null;
+ int sample = Media.sampleSize(w, h, width, height);
+ if (!Media.accepted(w / sample, h / sample)) return null;
+ options.inJustDecodeBounds = false;
+ options.inSampleSize = sample;
+ int[] scale = Media.coverScale(w / sample, h / sample, width, height);
+ if (scale != null) {
+ options.inScaled = true;
+ options.inDensity = scale[0];
+ options.inTargetDensity = scale[1];
+ }
+ options.inPreferredConfig = Bitmap.Config.RGB_565;
+ Bitmap decoded = BitmapFactory.decodeFile(file.getPath(), options);
+ if (decoded == null) return null;
+ Bitmap gpu = decoded.copy(Bitmap.Config.HARDWARE, false);
+ if (gpu == null) return decoded;
+ decoded.recycle();
+ return gpu;
+ } catch (Exception | OutOfMemoryError failure) {
+ return null;
+ }
+ }
+}
diff --git a/addons/photo-screensaver/app/src/main/res/values-nl/strings.xml b/addons/photo-screensaver/app/src/main/res/values-nl/strings.xml
new file mode 100644
index 000000000..7c144d4fe
--- /dev/null
+++ b/addons/photo-screensaver/app/src/main/res/values-nl/strings.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Foto-screensaver</string>
+ <string name="dream_name">Foto\'s</string>
+</resources>
diff --git a/addons/photo-screensaver/app/src/main/res/values/ids.xml b/addons/photo-screensaver/app/src/main/res/values/ids.xml
new file mode 100644
index 000000000..fe2b77e19
--- /dev/null
+++ b/addons/photo-screensaver/app/src/main/res/values/ids.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <item name="animation" type="id" />
+</resources>
diff --git a/addons/photo-screensaver/app/src/main/res/values/strings.xml b/addons/photo-screensaver/app/src/main/res/values/strings.xml
new file mode 100644
index 000000000..1fcbaa5e2
--- /dev/null
+++ b/addons/photo-screensaver/app/src/main/res/values/strings.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Photo screensaver</string>
+ <string name="dream_name">Photos</string>
+</resources>
diff --git a/addons/photo-screensaver/app/src/test/java/com/gathin/photodream/MediaTest.java b/addons/photo-screensaver/app/src/test/java/com/gathin/photodream/MediaTest.java
new file mode 100644
index 000000000..392d4d6a4
--- /dev/null
+++ b/addons/photo-screensaver/app/src/test/java/com/gathin/photodream/MediaTest.java
@@ -0,0 +1,75 @@
+package com.gathin.photodream;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+public class MediaTest {
+ @Rule public TemporaryFolder tmp = new TemporaryFolder();
+
+ @Test public void providerWritesOnlyPicturesClipsAndSeconds() {
+ assertEquals("pictures/sea.jpg", Media.path(Arrays.asList("pictures", "sea.jpg")));
+ assertEquals("pictures/Sea_2.MP4", Media.path(Arrays.asList("pictures", "Sea_2.MP4")));
+ assertEquals("seconds.txt", Media.path(Collections.singletonList("seconds.txt")));
+ assertNull(Media.path(Arrays.asList("pictures", "..")));
+ assertNull(Media.path(Arrays.asList("pictures", ".jpg")));
+ assertNull(Media.path(Arrays.asList("pictures", "sea.mkv")));
+ assertNull(Media.path(Arrays.asList("pictures", "sub", "a.jpg")));
+ assertNull(Media.path(Collections.singletonList("sea.jpg")));
+ assertNull(Media.path(Collections.singletonList("pictures")));
+ assertNull(Media.path(null));
+ assertTrue(Media.isFolder(Collections.singletonList("pictures")));
+ assertFalse(Media.isFolder(Arrays.asList("pictures", "sea.jpg")));
+ }
+
+ @Test public void secondsDefaultToTwenty() {
+ assertEquals(20, Media.seconds(null));
+ assertEquals(20, Media.seconds("abc"));
+ assertEquals(20, Media.seconds("4"));
+ assertEquals(20, Media.seconds("3601"));
+ assertEquals(45, Media.seconds(" 45\n"));
+ }
+
+ @Test public void listsByNameSkippingEmptyAndOtherFiles() throws Exception {
+ File dir = tmp.newFolder();
+ write(new File(dir, "b.mp4"), 3);
+ write(new File(dir, "a.jpg"), 3);
+ write(new File(dir, "empty.png"), 0);
+ write(new File(dir, "notes.txt"), 3);
+ List<File> files = Media.list(dir);
+ assertEquals(2, files.size());
+ assertEquals("a.jpg", files.get(0).getName());
+ assertEquals("b.mp4", files.get(1).getName());
+ assertEquals("b.mp4", Media.next(files, "a.jpg").getName());
+ assertEquals("a.jpg", Media.next(files, "b.mp4").getName());
+ assertEquals("a.jpg", Media.next(files, "gone.jpg").getName());
+ assertTrue(Media.list(new File(dir, "missing")).isEmpty());
+ }
+
+ @Test public void decodesNoBiggerThanTheScreen() {
+ assertTrue(Media.accepted(3840, 2160));
+ assertFalse(Media.accepted(65535, 2159));
+ assertEquals(2, Media.sampleSize(3840, 2160, 1920, 1080));
+ assertEquals(1, Media.sampleSize(1920, 1080, 1920, 1080));
+ assertArrayEquals(new int[]{2400, 1920}, Media.coverScale(2400, 1800, 1920, 1080));
+ assertNull(Media.coverScale(1920, 1080, 1920, 1080));
+ }
+
+ private static void write(File file, int bytes) throws Exception {
+ try (FileOutputStream out = new FileOutputStream(file)) {
+ out.write(new byte[bytes]);
+ }
+ }
+}
diff --git a/addons/photo-screensaver/build-and-install.ps1 b/addons/photo-screensaver/build-and-install.ps1
new file mode 100644
index 000000000..e56efa2f2
--- /dev/null
+++ b/addons/photo-screensaver/build-and-install.ps1
@@ -0,0 +1,38 @@
+# Windows version of build-and-install.sh: build the photo screensaver and install it on the TV.
+# Then run sync.ps1 to send your pictures and make it the TV's screensaver.
+#
+# Usage: addons\photo-screensaver\build-and-install.ps1 -TvHost 192.168.1.50
+# addons\photo-screensaver\build-and-install.ps1 -TvHost 192.168.1.50 -Uninstall
+param(
+ [string]$TvHost = $env:TV_HOST,
+ [switch]$Uninstall
+)
+$ErrorActionPreference = 'Stop'
+if (-not $TvHost) { throw 'pass -TvHost <tv ip> or set $env:TV_HOST' }
+$env:TV_HOST = $TvHost
+$here = $PSScriptRoot
+$tools = Join-Path (Split-Path (Split-Path $here -Parent) -Parent) 'tools'
+$py = Join-Path $tools 'venv\Scripts\python.exe'
+if (-not (Test-Path $py)) { throw 'run: python -m venv tools\venv; tools\venv\Scripts\python.exe -m pip install -r tools\requirements.txt' }
+$pkg = 'com.gathin.photodream'
+function Tv([string]$cmd) { & $py -I (Join-Path $tools 'tv.py') $cmd; if ($LASTEXITCODE) { throw "tv.py failed: $cmd" } }
+
+if ($Uninstall) {
+ # Put the screensaver from before sync.ps1 back first, then remove the app and its pictures.
+ & (Join-Path $here 'sync.ps1') -TvHost $TvHost -Off
+ Tv "pm uninstall $pkg"
+ exit 0
+}
+
+Push-Location $here
+try {
+ & .\gradlew.bat assembleRelease -q
+ if ($LASTEXITCODE) { throw 'build failed (JDK 17 and Android SDK 34 needed; see launcher\README)' }
+} finally { Pop-Location }
+$apk = Join-Path $here 'app\build\outputs\apk\release\app-release.apk'
+& $py -I (Join-Path $tools 'b64push.py') $apk /data/local/tmp/photodream.apk | Out-Null
+if ($LASTEXITCODE) { throw 'sending the APK failed' }
+Tv 'pm install -r /data/local/tmp/photodream.apk; rm -f /data/local/tmp/photodream.apk'
+# TCL's TclAppBoot blocks the app's provider until it may auto-start; elsewhere the op doesn't exist.
+Tv "appops set $pkg APP_AUTO_START allow 2>/dev/null; appops write-settings 2>/dev/null; true" | Out-Null
+Write-Host "Installed. Now: addons\photo-screensaver\sync.ps1 -TvHost $TvHost"
diff --git a/addons/photo-screensaver/build-and-install.sh b/addons/photo-screensaver/build-and-install.sh
new file mode 100644
index 000000000..e637cc915
--- /dev/null
+++ b/addons/photo-screensaver/build-and-install.sh
@@ -0,0 +1,30 @@
+#!/usr/bin/env bash
+# Build the photo screensaver and install it on the TV. Then run sync.sh to send your pictures and make it
+# the TV's screensaver.
+#
+# Usage: TV_HOST=192.168.1.50 addons/photo-screensaver/build-and-install.sh
+# TV_HOST=192.168.1.50 addons/photo-screensaver/build-and-install.sh --uninstall
+set -euo pipefail
+HERE="$(cd "$(dirname "$0")" && pwd)"
+TOOLS="$HERE/../../tools"
+: "${TV_HOST:?set TV_HOST to the TV IP address, e.g. TV_HOST=192.168.1.50 $0}"
+PY="$TOOLS/venv/bin/python"
+[ -x "$PY" ] || PY="$TOOLS/venv/Scripts/python.exe"
+[ -x "$PY" ] || { echo "run: python3 -m venv tools/venv && tools/venv/bin/pip install -r tools/requirements.txt" >&2; exit 1; }
+export MSYS_NO_PATHCONV=1
+PKG=com.gathin.photodream
+tv() { "$PY" -I "$TOOLS/tv.py" "$@"; }
+
+if [ "${1:-}" = --uninstall ]; then
+ # Put the screensaver from before sync.sh back first, then remove the app and its pictures.
+ "$HERE/sync.sh" --off
+ tv "pm uninstall $PKG"
+ exit 0
+fi
+
+(cd "$HERE" && ./gradlew assembleRelease -q) || { echo "build failed (JDK 17 and Android SDK 34 needed; see launcher/README)" >&2; exit 1; }
+"$PY" -I "$TOOLS/b64push.py" "$HERE/app/build/outputs/apk/release/app-release.apk" /data/local/tmp/photodream.apk >/dev/null
+tv "pm install -r /data/local/tmp/photodream.apk; rm -f /data/local/tmp/photodream.apk"
+# TCL's TclAppBoot blocks the app's provider until it may auto-start; elsewhere the op doesn't exist.
+tv "appops set $PKG APP_AUTO_START allow 2>/dev/null; appops write-settings 2>/dev/null; true" >/dev/null
+echo "Installed. Now: TV_HOST=$TV_HOST addons/photo-screensaver/sync.sh"
diff --git a/addons/photo-screensaver/build.gradle b/addons/photo-screensaver/build.gradle
new file mode 100644
index 000000000..48978475f
--- /dev/null
+++ b/addons/photo-screensaver/build.gradle
@@ -0,0 +1,3 @@
+plugins {
+ id 'com.android.application' version '8.5.2' apply false
+}
diff --git a/addons/photo-screensaver/gradle.properties b/addons/photo-screensaver/gradle.properties
new file mode 100644
index 000000000..18825f968
--- /dev/null
+++ b/addons/photo-screensaver/gradle.properties
@@ -0,0 +1,3 @@
+org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
+android.useAndroidX=true
+android.nonTransitiveRClass=true
diff --git a/addons/photo-screensaver/gradle/wrapper/gradle-wrapper.jar b/addons/photo-screensaver/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 000000000..2c3521197
Binary files /dev/null and b/addons/photo-screensaver/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/addons/photo-screensaver/gradle/wrapper/gradle-wrapper.properties b/addons/photo-screensaver/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000..77f5d0ba6
--- /dev/null
+++ b/addons/photo-screensaver/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/photo-screensaver/gradlew b/addons/photo-screensaver/gradlew
new file mode 100644
index 000000000..f5feea6d6
--- /dev/null
+++ b/addons/photo-screensaver/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/photo-screensaver/gradlew.bat b/addons/photo-screensaver/gradlew.bat
new file mode 100644
index 000000000..9d21a2183
--- /dev/null
+++ b/addons/photo-screensaver/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/photo-screensaver/settings.gradle b/addons/photo-screensaver/settings.gradle
new file mode 100644
index 000000000..5971b2b47
--- /dev/null
+++ b/addons/photo-screensaver/settings.gradle
@@ -0,0 +1,16 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+rootProject.name = "photodream"
+include ':app'
diff --git a/addons/photo-screensaver/sync.ps1 b/addons/photo-screensaver/sync.ps1
new file mode 100644
index 000000000..f7bff17d1
--- /dev/null
+++ b/addons/photo-screensaver/sync.ps1
@@ -0,0 +1,89 @@
+# Windows version of sync.sh: make the photo screensaver the TV's screensaver and sync a folder of pictures
+# and MP4 clips to it. Only new or changed files are sent and files no longer in the folder are removed from
+# the TV, so a sync that broke off halfway is finished by running it again. Each picture stays up for
+# -Seconds (20 by default). Install the app first with build-and-install.ps1.
+#
+# Usage: addons\photo-screensaver\sync.ps1 -TvHost 192.168.1.50 # this folder's pictures\
+# addons\photo-screensaver\sync.ps1 -TvHost 192.168.1.50 D:\Pictures\tv # any folder
+# addons\photo-screensaver\sync.ps1 -TvHost 192.168.1.50 -Seconds 30 # 30 s per picture
+# addons\photo-screensaver\sync.ps1 -TvHost 192.168.1.50 -IdleMinutes 5 # start it after 5 idle minutes
+# addons\photo-screensaver\sync.ps1 -TvHost 192.168.1.50 -Start # and show it now
+# addons\photo-screensaver\sync.ps1 -TvHost 192.168.1.50 -Off # previous screensaver back, pictures removed
+param(
+ [Parameter(Position = 0)][string]$Folder,
+ [int]$Seconds = 20,
+ [int]$IdleMinutes = 0,
+ [switch]$Start,
+ [switch]$Off,
+ [string]$TvHost = $env:TV_HOST
+)
+$ErrorActionPreference = 'Stop'
+if (-not $TvHost) { throw 'pass -TvHost <tv ip> or set $env:TV_HOST' }
+$env:TV_HOST = $TvHost
+if (-not $Folder) { $Folder = Join-Path $PSScriptRoot 'pictures' }
+if (Test-Path $Folder) { $Folder = (Resolve-Path $Folder).Path }
+Set-Location (Join-Path (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) 'tools')
+$py = 'venv\Scripts\python.exe'
+if (-not (Test-Path $py)) { throw 'run: python -m venv tools\venv; tools\venv\Scripts\python.exe -m pip install -r tools\requirements.txt' }
+$pkg = 'com.gathin.photodream'
+$dream = "$pkg/.PhotoDream"
+$dir = "/sdcard/Android/data/$pkg/files/pictures"
+$uri = "content://$pkg.files/pictures"
+$tmp = '/data/local/tmp/cyt-screensaver'
+# The screensaver the TV had before the first run, so -Off can put it back.
+$before = '/data/local/tmp/cyt-screensaver-before'
+$types = '^\.(jpg|jpeg|png|webp|mp4)$'
+function Tv([string]$cmd) { & $py -I tv.py $cmd; if ($LASTEXITCODE) { throw "tv.py failed: $cmd" } }
+
+if ($IdleMinutes -lt 0 -or $IdleMinutes -gt 1440) { throw '-IdleMinutes takes 1 to 1440' }
+if ($Seconds -lt 5 -or $Seconds -gt 3600) { throw '-Seconds takes 5 to 3600' }
+if (-not ((Tv "pm path $pkg; true") -match 'package:')) { throw "the photo screensaver is not on the TV: run addons\photo-screensaver\build-and-install.ps1 first" }
+
+if ($Off) {
+ Tv "if [ -f $before ]; then { read c; read e; } < $before; if [ `"`$c`" = null ]; then settings delete secure screensaver_components >/dev/null; else settings put secure screensaver_components `"`$c`"; fi; [ `"`$e`" = null ] || settings put secure screensaver_enabled `"`$e`"; rm -f $before; fi; rm -f $dir/* 2>/dev/null; content delete --uri $uri 2>/dev/null; echo screensaver: `$(settings get secure screensaver_components)"
+ exit 0
+}
+
+if (-not (Test-Path $Folder -PathType Container)) {
+ throw "no folder $Folder. Create it and put your pictures (jpg, png, webp) and MP4 clips in it, or pass another folder."
+}
+$files = @(Get-ChildItem $Folder -File | Where-Object { $_.Extension -match $types } | Sort-Object Name)
+foreach ($f in $files) {
+ if ($f.Name -notmatch '^[A-Za-z0-9_.-]+$' -or $f.Name.StartsWith('.')) { throw "rename $($f.Name): use letters, digits, - _ and . only" }
+ if ($f.Extension -ne '.mp4' -and $f.Length -gt 10MB) { throw "$($f.Name) is over 10 MB; the screensaver skips pictures that big" }
+ if ($f.Length -gt 1GB) { throw "$($f.Name) is over 1 GB; the screensaver skips clips that big" }
+}
+if ($files.Count -gt 100) { throw "$($files.Count) files; the screensaver shows at most 100" }
+if ($files.Count -eq 0) { Write-Warning "no pictures in ${Folder}: the screensaver stays black" }
+
+# What the TV has now, by md5, so unchanged files are not sent again.
+$onTv = @{}
+(Tv "cd $dir 2>/dev/null && md5sum * 2>/dev/null; true") -split "`n" | ForEach-Object {
+ if ($_ -match '^([0-9a-f]{32})\s+(\S+)$') { $onTv[$Matches[2]] = $Matches[1] }
+}
+$names = $files | ForEach-Object { $_.Name }
+foreach ($name in @($onTv.Keys)) {
+ if ($names -notcontains $name) {
+ Tv "rm -f $dir/$name 2>/dev/null; content delete --uri $uri/$name 2>/dev/null" | Out-Null
+ Write-Host "removed $name"
+ }
+}
+$sent = 0
+foreach ($f in $files) {
+ $md5 = (Get-FileHash $f.FullName -Algorithm MD5).Hash.ToLower()
+ if ($onTv[$f.Name] -eq $md5) { continue }
+ Write-Host "sending $($f.Name) ($([math]::Round($f.Length / 1MB, 1)) MB)"
+ $stage = "$tmp-$($f.Name)"
+ & $py -I b64push.py $f.FullName $stage | Select-String 'md5'
+ if ($LASTEXITCODE) { throw "sending $($f.Name) failed; run the script again to resume" }
+ # Written through the app's FilesProvider so the app owns the file (on TCL G10 a copied one gives EACCES).
+ Tv "rm -f $dir/$($f.Name) 2>/dev/null; content write --uri $uri/$($f.Name) < $stage 2>/dev/null || { mkdir -p $dir; cp $stage $dir/$($f.Name); }; rm -f $stage" | Out-Null
+ $sent++
+}
+
+Tv "printf '%s' $Seconds > $tmp-seconds.txt; content write --uri content://$pkg.files/seconds.txt < $tmp-seconds.txt; rm -f $tmp-seconds.txt" | Out-Null
+Tv "[ -f $before ] || { settings get secure screensaver_components; settings get secure screensaver_enabled; } > $before; settings put secure screensaver_components $dream; settings put secure screensaver_enabled 1" | Out-Null
+if ($IdleMinutes -gt 0) { Tv "settings put system screen_off_timeout $($IdleMinutes * 60000)" | Out-Null }
+$count = (Tv "ls $dir 2>/dev/null | wc -l").Trim()
+Write-Host "Screensaver: Photos with $count file(s) on the TV, $Seconds s each ($sent sent). Undo with: addons\photo-screensaver\sync.ps1 -TvHost $TvHost -Off"
+if ($Start) { Tv 'am start -n com.android.systemui/.Somnambulator >/dev/null; sleep 3; dumpsys dreams | grep mCurrentDreamName' }
diff --git a/addons/photo-screensaver/sync.sh b/addons/photo-screensaver/sync.sh
new file mode 100644
index 000000000..e703b82b0
--- /dev/null
+++ b/addons/photo-screensaver/sync.sh
@@ -0,0 +1,90 @@
+#!/usr/bin/env bash
+# Make the photo screensaver the TV's screensaver and sync a folder of pictures and MP4 clips to it. Only new
+# or changed files are sent and files no longer in the folder are removed from the TV, so a sync that broke
+# off halfway is finished by running it again. Each picture stays up for SECONDS_PER_PICTURE (20 by default). Install the
+# app first with build-and-install.sh.
+#
+# Usage: TV_HOST=192.168.1.50 addons/photo-screensaver/sync.sh # this folder's pictures/
+# TV_HOST=192.168.1.50 addons/photo-screensaver/sync.sh ~/Pictures/tv # any folder
+# TV_HOST=192.168.1.50 SECONDS_PER_PICTURE=30 addons/photo-screensaver/sync.sh # 30 s per picture
+# TV_HOST=192.168.1.50 IDLE_MINUTES=5 addons/photo-screensaver/sync.sh # start it after 5 idle minutes
+# TV_HOST=192.168.1.50 START=1 addons/photo-screensaver/sync.sh # and show it now
+# TV_HOST=192.168.1.50 addons/photo-screensaver/sync.sh --off # previous screensaver back, pictures removed
+set -euo pipefail
+HERE="$(cd "$(dirname "$0")" && (pwd -W 2>/dev/null || pwd))"
+FOLDER="${1:-$HERE/pictures}"
+case "$FOLDER" in --off|/*|?:*) ;; *) FOLDER="$(pwd -W 2>/dev/null || pwd)/$FOLDER" ;; esac
+cd "$(dirname "$0")/../../tools"
+: "${TV_HOST:?set TV_HOST to the TV IP address, e.g. TV_HOST=192.168.1.50 $0}"
+PY=venv/bin/python
+[ -x "$PY" ] || PY=venv/Scripts/python.exe
+[ -x "$PY" ] || { echo "run: python3 -m venv tools/venv && tools/venv/bin/pip install -r tools/requirements.txt" >&2; exit 1; }
+export MSYS_NO_PATHCONV=1
+PKG=com.gathin.photodream
+DREAM=$PKG/.PhotoDream
+DIR=/sdcard/Android/data/$PKG/files/pictures
+URI=content://$PKG.files/pictures
+TMP=/data/local/tmp/cyt-screensaver
+# The screensaver the TV had before the first run, so --off can put it back.
+BEFORE=/data/local/tmp/cyt-screensaver-before
+IDLE_MINUTES="${IDLE_MINUTES:-0}"
+SECONDS_PER_PICTURE="${SECONDS_PER_PICTURE:-20}"
+tv() { "$PY" -I tv.py "$@"; }
+md5() { "$PY" -I -c 'import hashlib,sys; print(hashlib.md5(open(sys.argv[1],"rb").read()).hexdigest())' "$1"; }
+
+[[ "$IDLE_MINUTES" =~ ^[0-9]+$ ]] && [ "$IDLE_MINUTES" -le 1440 ] || { echo "IDLE_MINUTES takes 1 to 1440" >&2; exit 1; }
+[[ "$SECONDS_PER_PICTURE" =~ ^[0-9]+$ ]] && [ "$SECONDS_PER_PICTURE" -ge 5 ] && [ "$SECONDS_PER_PICTURE" -le 3600 ] \
+ || { echo "SECONDS_PER_PICTURE takes 5 to 3600" >&2; exit 1; }
+tv "pm path $PKG; true" | grep -q package: \
+ || { echo "the photo screensaver is not on the TV: run addons/photo-screensaver/build-and-install.sh first" >&2; exit 1; }
+
+if [ "$FOLDER" = --off ]; then
+ tv "if [ -f $BEFORE ]; then { read c; read e; } < $BEFORE; if [ \"\$c\" = null ]; then settings delete secure screensaver_components >/dev/null; else settings put secure screensaver_components \"\$c\"; fi; [ \"\$e\" = null ] || settings put secure screensaver_enabled \"\$e\"; rm -f $BEFORE; fi; rm -f $DIR/* 2>/dev/null; content delete --uri $URI 2>/dev/null; echo screensaver: \$(settings get secure screensaver_components)"
+ exit 0
+fi
+
+[ -d "$FOLDER" ] || { echo "no folder $FOLDER. Create it and put your pictures (jpg, png, webp) and MP4 clips in it, or pass another folder." >&2; exit 1; }
+FILES=()
+for F in "$FOLDER"/*; do
+ [ -f "$F" ] || continue
+ NAME=$(basename "$F")
+ case "$(printf '%s' "$NAME" | tr 'A-Z' 'a-z')" in *.jpg|*.jpeg|*.png|*.webp|*.mp4) ;; *) continue ;; esac
+ [[ "$NAME" =~ ^[A-Za-z0-9_.-]+$ && "$NAME" != .* ]] || { echo "rename $NAME: use letters, digits, - _ and . only" >&2; exit 1; }
+ SIZE=$(wc -c < "$F")
+ case "$NAME" in
+ *.mp4|*.MP4) [ "$SIZE" -le 1073741824 ] || { echo "$NAME is over 1 GB; the screensaver skips clips that big" >&2; exit 1; } ;;
+ *) [ "$SIZE" -le 10485760 ] || { echo "$NAME is over 10 MB; the screensaver skips pictures that big" >&2; exit 1; } ;;
+ esac
+ FILES+=("$F")
+done
+[ "${#FILES[@]}" -le 100 ] || { echo "${#FILES[@]} files; the screensaver shows at most 100" >&2; exit 1; }
+[ "${#FILES[@]}" -gt 0 ] || echo "warning: no pictures in $FOLDER: the screensaver stays black" >&2
+
+# What the TV has now, by md5, so unchanged files are not sent again.
+ON_TV="$(tv "cd $DIR 2>/dev/null && md5sum * 2>/dev/null; true" | tr -d '\r')"
+while read -r SUM NAME; do
+ [ -n "${NAME:-}" ] || continue
+ KEEP=
+ for F in ${FILES[@]+"${FILES[@]}"}; do [ "$(basename "$F")" = "$NAME" ] && KEEP=1; done
+ if [ -z "$KEEP" ]; then
+ tv "rm -f $DIR/$NAME 2>/dev/null; content delete --uri $URI/$NAME 2>/dev/null" >/dev/null
+ echo "removed $NAME"
+ fi
+done <<< "$ON_TV"
+SENT=0
+for F in ${FILES[@]+"${FILES[@]}"}; do
+ NAME=$(basename "$F")
+ printf '%s\n' "$ON_TV" | grep -qx "$(md5 "$F") $NAME" && continue
+ echo "sending $NAME"
+ "$PY" -I b64push.py "$F" "$TMP-$NAME" | grep md5 || { echo "sending $NAME failed; run the script again to resume" >&2; exit 1; }
+ # Written through the app's FilesProvider so the app owns the file (on TCL G10 a copied one gives EACCES).
+ tv "rm -f $DIR/$NAME 2>/dev/null; content write --uri $URI/$NAME < $TMP-$NAME 2>/dev/null || { mkdir -p $DIR; cp $TMP-$NAME $DIR/$NAME; }; rm -f $TMP-$NAME" >/dev/null
+ SENT=$((SENT + 1))
+done
+
+tv "printf '%s' $SECONDS_PER_PICTURE > $TMP-seconds.txt; content write --uri content://$PKG.files/seconds.txt < $TMP-seconds.txt; rm -f $TMP-seconds.txt" >/dev/null
+tv "[ -f $BEFORE ] || { settings get secure screensaver_components; settings get secure screensaver_enabled; } > $BEFORE; settings put secure screensaver_components $DREAM; settings put secure screensaver_enabled 1" >/dev/null
+[ "$IDLE_MINUTES" -eq 0 ] || tv "settings put system screen_off_timeout $((IDLE_MINUTES * 60000))" >/dev/null
+COUNT=$(tv "ls $DIR 2>/dev/null | wc -l" | tr -d '\r ')
+echo "Screensaver: Photos with $COUNT file(s) on the TV, $SECONDS_PER_PICTURE s each ($SENT sent). Undo with: addons/photo-screensaver/sync.sh --off"
+[ -z "${START:-}" ] || tv "am start -n com.android.systemui/.Somnambulator >/dev/null; sleep 3; dumpsys dreams | grep mCurrentDreamName"