Add enrichment video player for Raspberry Pi and x86
Plays folders of videos on a loop from boot, with a controller menu, per-video on/off, play settings, a logo boot splash and a nightly YouTube sync. Tested on a Raspberry Pi 4; x86 paths are untested. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
10d8139e81
16 files changed
+2897
No files matched your search
@@ -0,0 +1,2 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
@@ -0,0 +1,126 @@
|
||||
# Enrichment video player
|
||||
|
||||
Plays the videos in one folder of `~/enrichment_videos` on an endless loop, full
|
||||
screen, starting automatically when the Raspberry Pi boots. No desktop needed.
|
||||
|
||||
~/enrichment_videos/
|
||||
birds/ clip1.mp4 clip2.mp4
|
||||
fish/ reef.mkv
|
||||
|
||||
## Using it
|
||||
|
||||
Press any button, or up or down, to open the menu over the video. Left and right do
|
||||
nothing until the menu is open, so a stray press can't change the video.
|
||||
|
||||
In the list of folders:
|
||||
|
||||
| Control | Action |
|
||||
| ------------------- | --------------------------- |
|
||||
| D-pad or left stick | Move up and down |
|
||||
| Right | Open the folder |
|
||||
| A | Play the highlighted folder |
|
||||
| B or Back | Close the menu |
|
||||
|
||||
Inside a folder:
|
||||
|
||||
| Control | Action |
|
||||
| ---------- | ------------------------------------------------------- |
|
||||
| A | Play that exact video, then carry on through the folder |
|
||||
| X | Turn the video on or off |
|
||||
| Left or B | Back to the folders |
|
||||
|
||||
Anywhere in the menu, **RB** goes to the next video and **LB** jumps to a random spot.
|
||||
The menu stays open so you can press them again. Next wraps back to the first video
|
||||
after the last, and does nothing if only one video is on.
|
||||
|
||||
Videos that are off stay on the Pi but are skipped, and this is remembered after a
|
||||
reboot. Turning off the video that is playing moves on to the next one. The last
|
||||
video left on in a folder can't be turned off.
|
||||
|
||||
## Play settings
|
||||
|
||||
Press **Start**, or choose **Settings** at the bottom of the list of folders. Up and
|
||||
down choose a setting, left and right change it, and B closes the window. Changes apply straight away and are remembered
|
||||
after a reboot.
|
||||
|
||||
| Setting | What it does |
|
||||
| ----------------------------- | ---------------------------------------------------- |
|
||||
| Shuffle play order | Plays the videos that are on in a random order. All |
|
||||
| | of them play once before any repeats, with a new |
|
||||
| | order each time round. |
|
||||
| Max time per video | Moves to the next video after this long. A longer |
|
||||
| | video starts at a random spot that leaves the full |
|
||||
| | time to play: 1 hour of a 9 hour video starts 0 to 8 |
|
||||
| | hours in. A folder with one video jumps to a new |
|
||||
| | spot instead of moving on. |
|
||||
| Start videos at a random spot | Begins each video somewhere new instead of the start |
|
||||
| Volume | Sets the sound level, or mutes it |
|
||||
|
||||
## Controller notes
|
||||
|
||||
Menus close themselves after 30 seconds. The X/D switch on a Logitech pad can be in
|
||||
either position. A USB keyboard also works: arrows, Enter, Esc, Space for on/off, N for
|
||||
next, R for a random spot and S for settings.
|
||||
|
||||
## Behaviour
|
||||
|
||||
- On boot it plays the last picked folder, starting from a random video other than
|
||||
the one last on screen. If that folder is gone or has no videos, it picks another
|
||||
folder at random and remembers it.
|
||||
- Videos play in name order; `clip2` comes before `clip10`.
|
||||
- Folders with no videos are left out of the menu. Sub-folders are not searched.
|
||||
- Add or remove videos at any time: changes take effect when the folder next
|
||||
loops back to its first video, and new folders appear next time the menu opens.
|
||||
- Damaged videos are skipped. If mpv crashes or freezes, it is restarted.
|
||||
- Sound goes to whichever HDMI port has the screen attached.
|
||||
|
||||
Videos play smoothest as H.264 or H.265 at up to 1080p. 1080p at 60fps H.264 has been
|
||||
measured with no dropped frames; much above that (such as 4K H.264) is too much for
|
||||
the Pi.
|
||||
|
||||
## YouTube
|
||||
|
||||
List videos or playlists in `~/enrichment_videos/youtube.txt`, one per line, with the
|
||||
folder to put them in:
|
||||
|
||||
# Folder name | link
|
||||
Birds and Squirrels | https://www.youtube.com/watch?v=MrSYP-cotdg
|
||||
Fish | https://www.youtube.com/playlist?list=...
|
||||
|
||||
Every night around 3am the Pi downloads anything new, at low priority so playback is
|
||||
not disturbed. To start straight away:
|
||||
|
||||
sudo systemctl start --no-block enrichment-youtube-sync
|
||||
sudo journalctl -u enrichment-youtube-sync -f # watch progress
|
||||
|
||||
Videos appear only once fully downloaded, an interrupted download resumes next time,
|
||||
and it stops rather than filling the disk (5 GB is kept free). A video is downloaded
|
||||
only once, so deleting one from its folder removes it for good. To get it back, delete
|
||||
its line from `~/.local/state/enrichment_player/youtube_archive.txt`. Removing a line
|
||||
from `youtube.txt` stops future downloads but keeps the videos already on the Pi.
|
||||
|
||||
An 8-hour 1080p video is about 16 GB. Check that you have permission to download and
|
||||
show the videos you list.
|
||||
|
||||
## Starting up
|
||||
|
||||
The Pi starts as soon as it has power and goes straight to the player. It shows the
|
||||
logo with its progress, and any problem in red. Both HDMI ports are forced on at
|
||||
1080p, so playback starts even if the TV is off or slow to wake. The picture goes to
|
||||
whichever port a screen answers on, or the last one that did.
|
||||
|
||||
On a Raspberry Pi, undo this by restoring `cmdline.txt.before-enrichment` and
|
||||
`config.txt.before-enrichment` in `/boot/firmware`. The SD card or drive can be read
|
||||
on any computer if the Pi will not start.
|
||||
|
||||
## Maintenance
|
||||
|
||||
./install.sh # install and enable at boot
|
||||
sudo systemctl restart enrichment-player # restart
|
||||
sudo systemctl stop enrichment-player # stop until next boot
|
||||
journalctl -u enrichment-player -f # watch the log (needs sudo)
|
||||
python3 -m unittest # run the tests
|
||||
|
||||
The chosen folder is stored in `~/.local/state/enrichment_player/last_folder`, and
|
||||
the videos that are off in `disabled.json` and the play settings in `settings.json`
|
||||
beside it.
|
||||
@@ -0,0 +1,107 @@
|
||||
# Recreating this setup
|
||||
|
||||
How to build the enrichment player on a new machine, what is different on x86, and
|
||||
what was learned on the original Raspberry Pi. `README.md` covers daily use.
|
||||
|
||||
**Status:** built and tested on a Raspberry Pi 4. The x86 paths in the code and
|
||||
installers have **not been run on x86 yet**. Expect to tune them there.
|
||||
|
||||
## What the repo does not contain
|
||||
|
||||
- **Videos.** Copy them to `~/enrichment_videos/<folder>/`. Files directly inside a
|
||||
folder are played; sub-folders are not searched. The Pi's `Kya` folder came from
|
||||
`thebears@tree:/home/thebears/Downloads/enrichment-videos/Kya`. Run `scp` from
|
||||
`~/enrichment_videos`, not from inside the folder, or it nests as `Kya/Kya`.
|
||||
- **State.** Recreated automatically in `~/.local/state/enrichment_player/`:
|
||||
`last_folder`, `last_video`, `display`, `settings.json`, `disabled.json`,
|
||||
`youtube_archive.txt`. Copy `disabled.json` and `settings.json` to keep those choices.
|
||||
- **`~/enrichment_videos/youtube.txt`.** Optional. Lines of `Folder name | link`.
|
||||
A link already in `youtube_archive.txt` is skipped, even if its file was deleted.
|
||||
|
||||
## Install
|
||||
|
||||
git clone ssh://gitea@winslowthehedgehog.com/thebears/enrichment-shower.git
|
||||
cd enrichment-shower
|
||||
./install.sh # as the user that will own the player, with sudo rights
|
||||
sudo reboot
|
||||
|
||||
`install.sh` installs packages, adds the user to `video render audio input`, allows
|
||||
that user to run `plymouth` and `plymouthd` through sudo without a password, installs
|
||||
`yt-dlp` and `deno` to `~/.local/bin` for this CPU, sets up the boot splash, fits the
|
||||
unit files to this user and folder, and enables the player and the nightly sync.
|
||||
|
||||
Log files: `sudo journalctl -u enrichment-player -f`. Each button press is logged as
|
||||
`control: ...`, and each time limit as `max time reached`.
|
||||
|
||||
## What is different on x86
|
||||
|
||||
| Area | Raspberry Pi 4 | x86 |
|
||||
| ---- | -------------- | --- |
|
||||
| Detection | `/proc/device-tree/model` | Anything else counts as x86 |
|
||||
| Video | `--hwdec=v4l2m2m,drm`, frames sent to a display plane | `--hwdec=auto-safe`, through the GPU |
|
||||
| Boot options | `/boot/firmware/cmdline.txt`, `config.txt` | `/etc/default/grub`, then `update-grub` |
|
||||
| Forced display | Both HDMI ports, always | Only with `FORCE_DISPLAY=<name>` |
|
||||
| Audio | HDMI card matching the picture port | mpv's automatic choice |
|
||||
| Display driver at boot | `vc4` added to the initramfs | Whatever Debian includes |
|
||||
|
||||
To set up on x86:
|
||||
|
||||
1. **Force the display.** List ports with `ls /sys/class/drm`, then run
|
||||
`FORCE_DISPLAY=HDMI-A-1 boot/install_boot.sh` with the right name.
|
||||
2. **Video decoding.** Install the driver: `intel-media-va-driver` or
|
||||
`i965-va-driver` for Intel, `mesa-va-drivers` for AMD. mpv needs a working DRM
|
||||
driver; NVIDIA's proprietary driver is the likeliest to need extra work.
|
||||
3. **Audio.** If sound goes to the wrong output, list devices with
|
||||
`mpv --audio-device=help`, then have `hdmi_audio_device()` return that device.
|
||||
4. **BIOS.** Set "restore on AC power loss" to **Power On**, or it won't start when
|
||||
plugged in. Secure Boot and fast-boot settings may also matter.
|
||||
5. **Check smoothness.** With the player running, read `frame-drop-count` from mpv's
|
||||
socket in `/tmp/enrichment-player-*/mpv.sock`. Watch the speed too: dropped frames
|
||||
can look like zero if playback is running slow.
|
||||
|
||||
## Boot settings on the Pi
|
||||
|
||||
Added to `/boot/firmware/cmdline.txt`, which must stay a single line:
|
||||
|
||||
quiet splash loglevel=3 logo.nologo vt.global_cursor_default=0
|
||||
plymouth.ignore-serial-consoles
|
||||
video=HDMI-A-1:1920x1080@60D video=HDMI-A-2:1920x1080@60D
|
||||
|
||||
Added to `config.txt`: `disable_splash=1`. Added to
|
||||
`/etc/initramfs-tools/modules`: `vc4`. Added to
|
||||
`/etc/initramfs-tools/conf.d/splash`: `FRAMEBUFFER=y`.
|
||||
|
||||
Versions in use: Debian 13 (trixie), kernel 6.18.50+rpt-rpi-v8, mpv 0.40.0,
|
||||
ffmpeg 7.1.5, plymouth 24.004.60, python3-evdev 1.9.1, yt-dlp 2026.10.26, deno 2.9.8.
|
||||
|
||||
## Why it is built this way
|
||||
|
||||
Each of these came from a measurement on the Pi, and is easy to undo by accident.
|
||||
|
||||
- **Display planes, not GPU compositing.** At 1080p60, H.264 through the GPU dropped
|
||||
10 or more frames a second. Direct to a plane: no drops at about 40% of one core.
|
||||
Software decoding used about 200% and dropped frames, especially alongside a download.
|
||||
- **The OSD plane must be above the video.** `--drm-draw-plane=overlay` with
|
||||
`--drm-drmprime-video-plane=primary`. The other way round hides the menu.
|
||||
- **Forcing both ports means both report connected.** A real screen is the one with
|
||||
EDID data, so `choose_connector()` trusts that and remembers the last answer.
|
||||
- **Card numbers change between boots** (`card0` or `card1`), so never hard-code them.
|
||||
- **Splash hand-over.** `plymouth quit --retain-splash` brought the text console back
|
||||
for over a second. `plymouth deactivate` keeps the image on screen; quit only after
|
||||
the first video frame.
|
||||
- **`time-pos` appears about 2 seconds before any picture.** Wait until it moves.
|
||||
- **Cold starts are slow** because nothing is in memory, so mpv runs once behind the logo.
|
||||
- **The splash needs root**, hence the sudo rule. It needs `plymouth-label` for text,
|
||||
and `splash` on the kernel command line or it falls back to plain text.
|
||||
- **Limit-aware start.** A video longer than the time limit starts where the whole
|
||||
limit can play: 1 hour of a 9 hour video starts 0 to 8 hours in.
|
||||
|
||||
## Unfinished
|
||||
|
||||
- A real power pull, and power-on with the HDMI cable unplugged, are untested.
|
||||
- Sound has never been confirmed by ear.
|
||||
- The real F310 buttons need checking, X in particular.
|
||||
- Max time failed once on the real player for an unknown reason, then passed twice.
|
||||
- The Pi looks for an SD card before USB. `BOOT_ORDER=0xf14` should shorten the black
|
||||
screen before Linux starts; not done.
|
||||
- The Pi boots from a USB flash drive, which is the weakest part for power cuts.
|
||||
Executable
+47
@@ -0,0 +1,47 @@
|
||||
#!/bin/sh
|
||||
# Boot straight to the player with a logo splash. Safe to run twice.
|
||||
# Raspberry Pi: forces both HDMI ports on at 1080p, so a TV that is off, asleep
|
||||
# or slow to answer can't stop playback starting. Originals are kept as
|
||||
# *.before-enrichment in /boot/firmware.
|
||||
# x86 with GRUB: set FORCE_DISPLAY to force a port, for example
|
||||
# FORCE_DISPLAY=HDMI-A-1 boot/install_boot.sh
|
||||
# The names are in /sys/class/drm. Original kept as /etc/default/grub.before-enrichment
|
||||
set -e
|
||||
cd "$(dirname "$0")"
|
||||
FW=/boot/firmware
|
||||
SPLASH_ARGS="quiet splash loglevel=3 logo.nologo vt.global_cursor_default=0 plymouth.ignore-serial-consoles"
|
||||
|
||||
sudo apt-get install -y --no-install-recommends plymouth plymouth-label plymouth-themes
|
||||
|
||||
sudo install -d /usr/share/plymouth/themes/enrichment
|
||||
sudo install -m 644 plymouth/logo.png plymouth/enrichment.plymouth plymouth/enrichment.script \
|
||||
/usr/share/plymouth/themes/enrichment/
|
||||
sudo plymouth-set-default-theme enrichment
|
||||
echo 'FRAMEBUFFER=y' | sudo tee /etc/initramfs-tools/conf.d/splash >/dev/null
|
||||
|
||||
if [ -f "$FW/cmdline.txt" ]; then
|
||||
sudo cp -n "$FW/cmdline.txt" "$FW/cmdline.txt.before-enrichment"
|
||||
sudo cp -n "$FW/config.txt" "$FW/config.txt.before-enrichment"
|
||||
sudo cp -n "$FW/initramfs8" "$FW/initramfs8.before-enrichment"
|
||||
# cmdline.txt must stay a single line
|
||||
for arg in $SPLASH_ARGS video=HDMI-A-1:1920x1080@60D video=HDMI-A-2:1920x1080@60D; do
|
||||
grep -qE "(^| )$arg( |\$)" "$FW/cmdline.txt" || sudo sed -i "1 s|\$| $arg|" "$FW/cmdline.txt"
|
||||
done
|
||||
grep -q '^disable_splash=1' "$FW/config.txt" || echo 'disable_splash=1' | sudo tee -a "$FW/config.txt" >/dev/null
|
||||
# The display driver must be available early for the logo to show during startup
|
||||
grep -qx vc4 /etc/initramfs-tools/modules || echo vc4 | sudo tee -a /etc/initramfs-tools/modules >/dev/null
|
||||
elif [ -f /etc/default/grub ]; then
|
||||
sudo cp -n /etc/default/grub /etc/default/grub.before-enrichment
|
||||
ARGS="$SPLASH_ARGS"
|
||||
[ -n "$FORCE_DISPLAY" ] && ARGS="$ARGS video=$FORCE_DISPLAY:1920x1080@60D"
|
||||
for arg in $ARGS; do
|
||||
grep -qE "^GRUB_CMDLINE_LINUX_DEFAULT=.*[\" ]$arg[\" ]" /etc/default/grub ||
|
||||
sudo sed -i "s|^\(GRUB_CMDLINE_LINUX_DEFAULT=\"[^\"]*\)\"|\1 $arg\"|" /etc/default/grub
|
||||
done
|
||||
grep -q '^GRUB_TIMEOUT=0' /etc/default/grub || sudo sed -i 's/^GRUB_TIMEOUT=.*/GRUB_TIMEOUT=0/' /etc/default/grub
|
||||
sudo update-grub
|
||||
else
|
||||
echo "No Raspberry Pi boot folder or GRUB found: splash theme installed, boot options not set."
|
||||
fi
|
||||
|
||||
sudo update-initramfs -u -k all
|
||||
Binary file not shown.
@@ -0,0 +1,8 @@
|
||||
[Plymouth Theme]
|
||||
Name=Enrichment
|
||||
Description=Logo with startup status and errors
|
||||
ModuleName=script
|
||||
|
||||
[script]
|
||||
ImageDir=/usr/share/plymouth/themes/enrichment
|
||||
ScriptFile=/usr/share/plymouth/themes/enrichment/enrichment.script
|
||||
@@ -0,0 +1,54 @@
|
||||
# Boot splash: the logo, a status line, and any error in red.
|
||||
# Messages come from `plymouth display-message`; "ERROR: ..." shows as an error.
|
||||
|
||||
Window.SetBackgroundTopColor(0, 0, 0);
|
||||
Window.SetBackgroundBottomColor(0, 0, 0);
|
||||
|
||||
screen_width = Window.GetWidth();
|
||||
screen_height = Window.GetHeight();
|
||||
|
||||
logo = Image("logo.png");
|
||||
logo_width = screen_width * 0.55;
|
||||
logo_height = logo.GetHeight() * logo_width / logo.GetWidth();
|
||||
logo_sprite = Sprite(logo.Scale(logo_width, logo_height));
|
||||
logo_y = screen_height * 0.5 - logo_height * 0.6;
|
||||
logo_sprite.SetPosition((screen_width - logo_width) / 2, logo_y, 1);
|
||||
|
||||
status_y = logo_y + logo_height + screen_height * 0.07;
|
||||
status_sprite = Sprite();
|
||||
error_sprite = Sprite();
|
||||
|
||||
fun show_line(sprite, text, y, red, green, blue, font) {
|
||||
image = Image.Text(text, red, green, blue, 1, font);
|
||||
sprite.SetImage(image);
|
||||
sprite.SetPosition((screen_width - image.GetWidth()) / 2, y, 2);
|
||||
}
|
||||
|
||||
fun show_status(text) {
|
||||
show_line(status_sprite, text, status_y, 1, 1, 1, "DejaVu Sans 30");
|
||||
}
|
||||
|
||||
fun show_error(text) {
|
||||
show_line(error_sprite, text, status_y + 70, 1, 0.3, 0.3, "DejaVu Sans Bold 30");
|
||||
}
|
||||
|
||||
fun message_callback(text) {
|
||||
if (text.SubString(0, 7) == "ERROR: ")
|
||||
show_error(text.SubString(7, text.Length()));
|
||||
else
|
||||
show_status(text);
|
||||
}
|
||||
Plymouth.SetMessageFunction(message_callback);
|
||||
|
||||
fun root_mounted_callback() {
|
||||
show_status("Starting: loading system");
|
||||
}
|
||||
Plymouth.SetRootMountedFunction(root_mounted_callback);
|
||||
|
||||
fun status_callback(status) {
|
||||
if (status.SubString(0, 4) == "fsck")
|
||||
show_status("Starting: checking disk");
|
||||
}
|
||||
Plymouth.SetUpdateStatusFunction(status_callback);
|
||||
|
||||
show_status("Starting");
|
||||
Executable
BIN
Binary file not shown.
|
After Width: | Height: | Size: 35 KiB |
@@ -0,0 +1,17 @@
|
||||
[Unit]
|
||||
Description=Enrichment video player
|
||||
# Start as soon as the system is up, without waiting for the network.
|
||||
After=basic.target sound.target plymouth-start.service
|
||||
Before=plymouth-quit.service
|
||||
# Keep retrying forever rather than letting systemd give up on the unit.
|
||||
StartLimitIntervalSec=0
|
||||
|
||||
[Service]
|
||||
User=infra
|
||||
SupplementaryGroups=video render audio input
|
||||
ExecStart=/usr/bin/python3 /home/infra/source/killer_kitties/enrichment_player.py
|
||||
Restart=always
|
||||
RestartSec=2
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,17 @@
|
||||
[Unit]
|
||||
Description=Download enrichment videos from YouTube
|
||||
Wants=network-online.target
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=infra
|
||||
Environment=PATH=/home/infra/.local/bin:/usr/bin:/bin
|
||||
# YouTube changes often, so update first; a failed update must not stop the sync.
|
||||
ExecStartPre=-/home/infra/.local/bin/yt-dlp --update
|
||||
ExecStartPre=-/home/infra/.local/bin/deno upgrade
|
||||
ExecStart=/usr/bin/python3 /home/infra/source/killer_kitties/sync_youtube.py
|
||||
# Playback comes first.
|
||||
Nice=15
|
||||
CPUWeight=20
|
||||
IOSchedulingClass=idle
|
||||
@@ -0,0 +1,10 @@
|
||||
[Unit]
|
||||
Description=Nightly YouTube sync for enrichment videos
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 03:00
|
||||
RandomizedDelaySec=30min
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
Executable
+1538
File diff suppressed because it is too large.
Load diff
Executable
+53
@@ -0,0 +1,53 @@
|
||||
#!/bin/sh
|
||||
# Installs everything on a Raspberry Pi or an x86 PC running Debian-style Linux, and
|
||||
# starts the player now and at every boot. Run it as the user that will own the
|
||||
# player, from anywhere. See SETUP.md first on a new machine.
|
||||
set -e
|
||||
cd "$(dirname "$0")"
|
||||
DIR=$(pwd)
|
||||
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends mpv ffmpeg python3-evdev fonts-dejavu-core \
|
||||
alsa-utils curl unzip
|
||||
sudo usermod -aG video,render,audio,input "$USER"
|
||||
|
||||
# The splash only takes orders from root; the player runs as this user.
|
||||
echo "$USER ALL=(root) NOPASSWD: /usr/bin/plymouth, /usr/sbin/plymouthd" \
|
||||
| sudo tee /etc/sudoers.d/enrichment-player >/dev/null
|
||||
sudo chmod 440 /etc/sudoers.d/enrichment-player
|
||||
sudo visudo -cf /etc/sudoers.d/enrichment-player
|
||||
|
||||
case "$(uname -m)" in
|
||||
aarch64) YT_DLP=yt-dlp_linux_aarch64; DENO=deno-aarch64-unknown-linux-gnu.zip ;;
|
||||
x86_64) YT_DLP=yt-dlp_linux; DENO=deno-x86_64-unknown-linux-gnu.zip ;;
|
||||
*) echo "Unsupported machine: $(uname -m)"; exit 1 ;;
|
||||
esac
|
||||
|
||||
# yt-dlp and deno are kept up to date by the nightly sync, so they live here
|
||||
# rather than in apt, whose copies fall behind YouTube.
|
||||
mkdir -p ~/.local/bin ~/enrichment_videos
|
||||
[ -x ~/.local/bin/yt-dlp ] || {
|
||||
curl -fsSL -o ~/.local/bin/yt-dlp \
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/$YT_DLP"
|
||||
chmod +x ~/.local/bin/yt-dlp
|
||||
}
|
||||
[ -x ~/.local/bin/deno ] || {
|
||||
curl -fsSL -o /tmp/deno.zip \
|
||||
"https://github.com/denoland/deno/releases/latest/download/$DENO"
|
||||
unzip -q -o /tmp/deno.zip -d ~/.local/bin
|
||||
rm /tmp/deno.zip
|
||||
}
|
||||
|
||||
boot/install_boot.sh
|
||||
|
||||
# The unit files name this Pi's user and folder; fit them to this machine.
|
||||
for unit in enrichment-player.service enrichment-youtube-sync.service \
|
||||
enrichment-youtube-sync.timer; do
|
||||
sed -e "s#/home/infra/source/killer_kitties#$DIR#g" \
|
||||
-e "s#/home/infra#$HOME#g" -e "s#User=infra#User=$USER#" "$unit" \
|
||||
| sudo tee "/etc/systemd/system/$unit" >/dev/null
|
||||
done
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable enrichment-player enrichment-youtube-sync.timer
|
||||
|
||||
echo "Installed. Reboot to start the player: sudo reboot"
|
||||
Executable
+91
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Download the videos listed in ~/enrichment_videos/youtube.txt.
|
||||
|
||||
Each line is 'Folder name | link'. Files reach the video folder only once
|
||||
complete, so the player never picks up a partial download.
|
||||
"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
HOME = Path.home()
|
||||
VIDEOS = HOME / "enrichment_videos"
|
||||
SOURCES = VIDEOS / "youtube.txt"
|
||||
ARCHIVE = HOME / ".local/state/enrichment_player/youtube_archive.txt"
|
||||
TEMP = HOME / ".cache/enrichment_player/downloads" # same disk: the final move is atomic
|
||||
YT_DLP = HOME / ".local/bin/yt-dlp"
|
||||
|
||||
RESERVE_BYTES = 5 * 1024**3 # always leave this much disk free
|
||||
|
||||
# H.264 up to 1080p first: the Pi plays it reliably and YouTube's 4K versions
|
||||
# are far too heavy. The later choices only apply if a video has no H.264.
|
||||
FORMAT = ("bv*[vcodec^=avc1][height<=1080]+ba[ext=m4a]"
|
||||
"/b[vcodec^=avc1][height<=1080]/bv*[height<=1080]+ba/b[height<=1080]")
|
||||
|
||||
|
||||
def parse_sources(text):
|
||||
"""Return [(folder, url)], reporting and skipping lines that make no sense."""
|
||||
sources = []
|
||||
for number, raw in enumerate(text.splitlines(), start=1):
|
||||
line = raw.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
folder, separator, url = (part.strip() for part in line.partition("|"))
|
||||
safe = folder and folder not in (".", "..") and "/" not in folder
|
||||
if not (separator and safe and url.startswith("http")):
|
||||
print(f"youtube.txt line {number} ignored: {raw!r}", flush=True)
|
||||
continue
|
||||
sources.append((folder, url))
|
||||
return sources
|
||||
|
||||
|
||||
def download(folder, url):
|
||||
"""Run yt-dlp for one source. Returns True if it finished cleanly."""
|
||||
target = VIDEOS / folder
|
||||
budget = shutil.disk_usage(HOME).free - RESERVE_BYTES
|
||||
if budget <= 0:
|
||||
print(f"skipping {folder!r}: disk is nearly full", flush=True)
|
||||
return False
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
print(f"syncing {folder!r}: {url}", flush=True)
|
||||
result = subprocess.run([
|
||||
str(YT_DLP), url,
|
||||
"--format", FORMAT,
|
||||
"--format-sort", "proto:https", # far smaller than the HLS copies
|
||||
"--merge-output-format", "mp4",
|
||||
"--paths", str(target),
|
||||
"--paths", f"temp:{TEMP}",
|
||||
"--output", "%(title).120B [%(id)s].%(ext)s",
|
||||
"--download-archive", str(ARCHIVE),
|
||||
"--no-playlist", # a video link stays one video; playlist links still work
|
||||
"--match-filters", "!is_live",
|
||||
"--max-filesize", str(budget),
|
||||
"--ignore-errors",
|
||||
"--retries", "20",
|
||||
"--newline",
|
||||
"--progress-delta", "60",
|
||||
], stdin=subprocess.DEVNULL, check=False)
|
||||
return result.returncode == 0
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
sources = parse_sources(SOURCES.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
print(f"nothing to do: {SOURCES} does not exist", flush=True)
|
||||
return 0
|
||||
ARCHIVE.parent.mkdir(parents=True, exist_ok=True)
|
||||
TEMP.mkdir(parents=True, exist_ok=True)
|
||||
results = [download(folder, url) for folder, url in sources]
|
||||
if all(results):
|
||||
# Partial files are kept after a failure so the next run can resume.
|
||||
shutil.rmtree(TEMP, ignore_errors=True)
|
||||
return 0
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,807 @@
|
||||
"""Run with: python3 -m unittest"""
|
||||
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from evdev import ecodes as e
|
||||
|
||||
import enrichment_player as ep
|
||||
|
||||
|
||||
def key(code, value=1):
|
||||
return SimpleNamespace(type=e.EV_KEY, code=code, value=value)
|
||||
|
||||
|
||||
def axis(code, value):
|
||||
return SimpleNamespace(type=e.EV_ABS, code=code, value=value)
|
||||
|
||||
|
||||
class LibraryTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.root = Path(tmp.name) / "videos"
|
||||
self.state = Path(tmp.name) / "state" / "last_folder"
|
||||
for name in ("birds/clip10.mp4", "birds/clip2.MKV", "birds/._clip.mp4",
|
||||
"birds/notes.txt", "fish/a.mov", "empty/readme.txt"):
|
||||
path = self.root / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.touch()
|
||||
|
||||
def test_videos_are_filtered_and_naturally_sorted(self):
|
||||
names = [Path(p).name for p in ep.list_videos(self.root / "birds")]
|
||||
self.assertEqual(names, ["clip2.MKV", "clip10.mp4"])
|
||||
|
||||
def test_folders_without_videos_are_hidden(self):
|
||||
self.assertEqual(ep.list_folders(self.root), {"birds": 2, "fish": 1})
|
||||
|
||||
def test_last_folder_wins(self):
|
||||
ep.save_last_folder(self.state, "fish")
|
||||
for _ in range(20):
|
||||
self.assertEqual(ep.choose_folder(self.root, self.state), "fish")
|
||||
|
||||
def test_random_pick_is_remembered(self):
|
||||
pick = ep.choose_folder(self.root, self.state)
|
||||
self.assertIn(pick, ("birds", "fish"))
|
||||
self.assertEqual(ep.load_last_folder(self.state), pick)
|
||||
|
||||
def test_missing_or_empty_last_folder_falls_back(self):
|
||||
for gone in ("deleted", "empty"):
|
||||
ep.save_last_folder(self.state, gone)
|
||||
self.assertIn(ep.choose_folder(self.root, self.state), ("birds", "fish"))
|
||||
|
||||
def test_no_library(self):
|
||||
self.assertIsNone(ep.choose_folder(self.root / "nope", self.state))
|
||||
|
||||
|
||||
class TranslatorTest(unittest.TestCase):
|
||||
def test_xinput_buttons(self):
|
||||
t = ep.Translator()
|
||||
self.assertEqual(t.feed(key(e.BTN_SOUTH), 0), ["confirm"])
|
||||
self.assertEqual(t.feed(key(e.BTN_SOUTH, 0), 0), [])
|
||||
self.assertEqual(t.feed(key(e.BTN_EAST), 0), ["cancel"])
|
||||
self.assertEqual(t.feed(key(e.BTN_THUMBL), 0), ["any"])
|
||||
|
||||
def test_directinput_buttons(self):
|
||||
t = ep.Translator()
|
||||
self.assertEqual(t.feed(key(e.BTN_THUMB), 0), ["confirm"])
|
||||
self.assertEqual(t.feed(key(e.BTN_THUMB2), 0), ["cancel"])
|
||||
|
||||
def test_hat_moves_once_then_repeats_while_held(self):
|
||||
t = ep.Translator()
|
||||
t.ranges[e.ABS_HAT0Y] = (-1, 1)
|
||||
self.assertEqual(t.feed(axis(e.ABS_HAT0Y, 1), 0), ["down"])
|
||||
self.assertEqual(t.tick(0.1), [])
|
||||
self.assertEqual(t.tick(ep.REPEAT_DELAY), ["down"])
|
||||
self.assertEqual(t.feed(axis(e.ABS_HAT0Y, 0), 1), [])
|
||||
self.assertEqual(t.tick(5), [])
|
||||
|
||||
def test_unsigned_stick_rests_at_centre(self):
|
||||
t = ep.Translator()
|
||||
t.ranges[e.ABS_Y] = (0, 255)
|
||||
self.assertEqual(t.feed(axis(e.ABS_Y, 128), 0), [])
|
||||
self.assertEqual(t.feed(axis(e.ABS_Y, 0), 0), ["up"])
|
||||
|
||||
def test_stick_noise_near_threshold_does_not_repeat_presses(self):
|
||||
t = ep.Translator()
|
||||
t.ranges[e.ABS_Y] = (-100, 100)
|
||||
self.assertEqual(t.feed(axis(e.ABS_Y, 70), 0), ["down"])
|
||||
self.assertEqual(t.feed(axis(e.ABS_Y, 50), 0), [])
|
||||
self.assertEqual(t.feed(axis(e.ABS_Y, 70), 0), [])
|
||||
|
||||
|
||||
class ButtonTest(unittest.TestCase):
|
||||
def test_start_opens_settings_in_both_modes(self):
|
||||
for code in (e.BTN_START, e.BTN_BASE4, e.KEY_S):
|
||||
self.assertEqual(ep.Translator().feed(key(code), 0), ["settings"])
|
||||
|
||||
def test_bumpers_in_both_controller_modes(self):
|
||||
for code, action in ((e.BTN_TR, "next"), (e.BTN_PINKIE, "next"),
|
||||
(e.BTN_TL, "jump"), (e.BTN_TOP2, "jump")):
|
||||
self.assertEqual(ep.Translator().feed(key(code), 0), [action])
|
||||
|
||||
def test_only_x_toggles_in_both_modes(self):
|
||||
for code in (e.BTN_X, e.BTN_TRIGGER):
|
||||
self.assertEqual(ep.Translator().feed(key(code), 0), ["toggle"])
|
||||
for code in (e.BTN_Y, e.BTN_TOP):
|
||||
self.assertEqual(ep.Translator().feed(key(code), 0), ["any"])
|
||||
|
||||
def test_keyboard(self):
|
||||
for code, action in ((e.KEY_RIGHT, "right"), (e.KEY_LEFT, "left"),
|
||||
(e.KEY_SPACE, "toggle"), (e.KEY_N, "next"), (e.KEY_R, "jump")):
|
||||
self.assertEqual(ep.Translator().feed(key(code), 0), [action])
|
||||
|
||||
def test_holding_a_key_acts_only_once(self):
|
||||
self.assertEqual(ep.Translator().feed(key(e.KEY_RIGHT, 2), 0), [])
|
||||
|
||||
def test_hat_acts_once_until_released(self):
|
||||
t = ep.Translator()
|
||||
t.ranges[e.ABS_HAT0X] = (-1, 1)
|
||||
self.assertEqual(t.feed(axis(e.ABS_HAT0X, 1), 0), ["right"])
|
||||
self.assertEqual(t.tick(10), [])
|
||||
self.assertEqual(t.feed(axis(e.ABS_HAT0X, 0), 0), [])
|
||||
self.assertEqual(t.feed(axis(e.ABS_HAT0X, -1), 0), ["left"])
|
||||
|
||||
def test_unsigned_stick_at_rest_does_nothing(self):
|
||||
t = ep.Translator()
|
||||
t.ranges[e.ABS_X] = (0, 255)
|
||||
self.assertEqual(t.feed(axis(e.ABS_X, 128), 0), [])
|
||||
self.assertEqual(t.feed(axis(e.ABS_X, 255), 0), ["right"])
|
||||
self.assertEqual(t.feed(axis(e.ABS_X, 128), 0), [])
|
||||
self.assertEqual(t.feed(axis(e.ABS_X, 0), 0), ["left"])
|
||||
|
||||
def test_stick_noise_does_not_act_again(self):
|
||||
t = ep.Translator()
|
||||
t.ranges[e.ABS_X] = (-100, 100)
|
||||
self.assertEqual(t.feed(axis(e.ABS_X, 70), 0), ["right"])
|
||||
self.assertEqual(t.feed(axis(e.ABS_X, 50), 0), [])
|
||||
self.assertEqual(t.feed(axis(e.ABS_X, 70), 0), [])
|
||||
|
||||
|
||||
class FakeMpv:
|
||||
"""Just enough of mpv: a playlist and a record of commands."""
|
||||
|
||||
def __init__(self):
|
||||
self.list = []
|
||||
self.path = None
|
||||
self.commands = []
|
||||
self.time = 100.0
|
||||
|
||||
def get(self, name):
|
||||
if name == "time-pos":
|
||||
self.time += 1 # always moving, or the freeze detector trips
|
||||
return self.time
|
||||
if name == "path":
|
||||
return self.path
|
||||
if name == "playlist":
|
||||
return [{"filename": f} for f in self.list]
|
||||
if name == "playlist-pos":
|
||||
return self.list.index(self.path) if self.path in self.list else None
|
||||
return None
|
||||
|
||||
def play(self, order):
|
||||
self.list = list(order)
|
||||
self.path = self.list[0]
|
||||
|
||||
def overlay(self, ass):
|
||||
pass
|
||||
|
||||
def logo(self, show):
|
||||
pass
|
||||
|
||||
def command(self, *args):
|
||||
self.commands.append(args)
|
||||
if args[0] == "playlist-remove":
|
||||
del self.list[args[1]]
|
||||
elif args[0] == "playlist-move":
|
||||
self.list.insert(args[2], self.list.pop(args[1]))
|
||||
elif args[:1] == ("loadfile",):
|
||||
self.list.insert(args[3], args[1])
|
||||
|
||||
|
||||
class PlayerCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.lengths = {}
|
||||
original = ep.video_duration
|
||||
ep.video_duration = lambda path: self.lengths.get(Path(path).name)
|
||||
self.addCleanup(setattr, ep, "video_duration", original)
|
||||
real_choose = ep.choose_connector
|
||||
ep.choose_connector = lambda *_: None
|
||||
self.addCleanup(setattr, ep, "choose_connector", real_choose)
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.root = Path(tmp.name) / "videos"
|
||||
self.state = Path(tmp.name) / "state" / "last_folder"
|
||||
for name in ("birds/a.mp4", "birds/b.mp4", "birds/c.mp4", "fish/f.mp4"):
|
||||
path = self.root / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.touch()
|
||||
self.player = self.new_player()
|
||||
|
||||
def new_player(self):
|
||||
player = ep.Player(self.root, self.state)
|
||||
player.mpv = FakeMpv()
|
||||
player._load("birds")
|
||||
return player
|
||||
|
||||
def press(self, *actions):
|
||||
self.player._handle(list(actions), 0)
|
||||
|
||||
def path(self, name):
|
||||
return str(self.root / "birds" / name)
|
||||
|
||||
def names(self):
|
||||
return [Path(f).name for f in self.player.mpv.list]
|
||||
|
||||
def toasts(self):
|
||||
return [c[1] for c in self.player.mpv.commands if c[0] == "show-text"]
|
||||
|
||||
|
||||
class PlayerMenuTest(PlayerCase):
|
||||
def test_left_and_right_do_nothing_while_closed(self):
|
||||
self.press("right", "left")
|
||||
self.assertFalse(self.player.menu.open)
|
||||
|
||||
def test_next_and_jump_only_open_the_menu_while_closed(self):
|
||||
self.press("next")
|
||||
self.assertTrue(self.player.menu.open)
|
||||
self.assertNotIn(("playlist-next",), self.player.mpv.commands)
|
||||
|
||||
def test_next_works_with_menu_open_and_keeps_it_open(self):
|
||||
self.press("any", "next")
|
||||
self.assertIn(("playlist-next",), self.player.mpv.commands)
|
||||
self.assertTrue(self.player.menu.open)
|
||||
|
||||
def test_right_opens_folder_and_left_goes_back(self):
|
||||
self.press("any", "right")
|
||||
self.assertEqual(self.player.menu.folder, "birds")
|
||||
self.assertEqual(self.player.menu.items, [self.path(n) for n in "a.mp4 b.mp4 c.mp4".split()])
|
||||
self.press("left")
|
||||
self.assertIsNone(self.player.menu.folder)
|
||||
self.assertTrue(self.player.menu.open)
|
||||
|
||||
def test_a_plays_the_exact_video_and_keeps_the_loop_order(self):
|
||||
self.press("any", "right", "down", "down", "confirm")
|
||||
self.assertEqual(self.names(), ["c.mp4", "a.mp4", "b.mp4"])
|
||||
self.assertFalse(self.player.menu.open)
|
||||
|
||||
def test_a_in_another_folder_remembers_that_folder(self):
|
||||
self.press("any", "down", "right", "confirm")
|
||||
self.assertEqual(self.names(), ["f.mp4"])
|
||||
self.assertEqual(ep.load_last_folder(self.state), "fish")
|
||||
|
||||
def test_turning_off_removes_it_and_is_remembered(self):
|
||||
self.press("any", "right", "down", "toggle")
|
||||
self.assertEqual(self.names(), ["a.mp4", "c.mp4"])
|
||||
self.assertTrue(self.player.menu.open)
|
||||
self.player = self.new_player()
|
||||
self.assertEqual(self.names(), ["a.mp4", "c.mp4"])
|
||||
|
||||
def test_turning_back_on_restores_its_place(self):
|
||||
self.press("any", "right", "down", "toggle", "toggle")
|
||||
self.assertEqual(self.names(), ["a.mp4", "b.mp4", "c.mp4"])
|
||||
self.assertEqual(ep.load_disabled(self.state.with_name("disabled.json")), {})
|
||||
|
||||
def test_last_video_on_cannot_be_turned_off(self):
|
||||
self.press("any", "right", "toggle", "down", "toggle", "down", "toggle")
|
||||
self.assertEqual(self.names(), ["c.mp4"])
|
||||
self.assertIn("At least one video must stay on", self.toasts())
|
||||
|
||||
def test_a_on_a_video_that_is_off_explains_and_stays_open(self):
|
||||
self.press("any", "right", "toggle", "confirm")
|
||||
self.assertTrue(self.player.menu.open)
|
||||
self.assertEqual(self.names(), ["b.mp4", "c.mp4"])
|
||||
|
||||
def test_toggling_in_another_folder_leaves_the_playlist_alone(self):
|
||||
(self.root / "fish/g.mp4").touch()
|
||||
self.press("any", "down", "right", "toggle")
|
||||
self.assertEqual(self.names(), ["a.mp4", "b.mp4", "c.mp4"])
|
||||
self.assertEqual(self.player.disabled, {"fish": {"f.mp4"}})
|
||||
|
||||
def test_settings_row_is_last_and_opens_with_a_or_right(self):
|
||||
for action in ("confirm", "right"):
|
||||
self.press("any", "up")
|
||||
self.assertEqual(self.player.menu.items[-1], ep.SETTINGS_ITEM)
|
||||
self.press(action)
|
||||
self.assertTrue(self.player.window.open)
|
||||
self.assertFalse(self.player.menu.open)
|
||||
self.press("cancel", "cancel")
|
||||
|
||||
def test_settings_row_does_not_play_anything(self):
|
||||
before = list(self.player.mpv.list)
|
||||
self.press("any", "up", "confirm")
|
||||
self.assertEqual(self.player.mpv.list, before)
|
||||
self.assertEqual(ep.load_last_folder(self.state), None)
|
||||
|
||||
def test_b_in_settings_returns_to_the_settings_row(self):
|
||||
self.press("any", "up", "confirm", "cancel")
|
||||
self.assertFalse(self.player.window.open)
|
||||
self.assertTrue(self.player.menu.open)
|
||||
self.assertEqual(self.player.menu.items[self.player.menu.index], ep.SETTINGS_ITEM)
|
||||
|
||||
def test_b_in_settings_opened_directly_closes_everything(self):
|
||||
self.press("settings", "cancel")
|
||||
self.assertFalse(self.player.window.open or self.player.menu.open)
|
||||
|
||||
def test_settings_row_labels_its_buttons(self):
|
||||
self.press("any", "up")
|
||||
self.assertIn("Open settings", ep.render_menu(self.player.menu, "birds"))
|
||||
|
||||
def test_y_does_nothing_in_a_folder(self):
|
||||
self.press("any", "right", "any")
|
||||
self.assertEqual(self.names(), ["a.mp4", "b.mp4", "c.mp4"])
|
||||
self.assertTrue(self.player.menu.open)
|
||||
|
||||
def test_folder_shows_how_many_are_on(self):
|
||||
self.press("any", "right", "toggle", "left", "cancel", "any")
|
||||
self.assertEqual(self.player.menu.folders["birds"], "2 of 3 on")
|
||||
|
||||
|
||||
class SettingsTest(PlayerCase):
|
||||
def advance(self, seconds):
|
||||
self.clock += seconds
|
||||
self.player._check_health(self.clock)
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
for name in ("d.mp4", "e.mp4"):
|
||||
(self.root / "birds" / name).touch()
|
||||
self.player = self.new_player()
|
||||
self.clock = 1000.0
|
||||
self.player._check_health(self.clock)
|
||||
|
||||
def set(self, **values):
|
||||
self.player.settings.update(values)
|
||||
for key in values:
|
||||
self.player._apply_setting(key)
|
||||
|
||||
def finish_video(self):
|
||||
"""What mpv does when a video ends."""
|
||||
mpv = self.player.mpv
|
||||
mpv.path = mpv.list[(mpv.list.index(mpv.path) + 1) % len(mpv.list)]
|
||||
self.advance(1)
|
||||
|
||||
def test_shuffle_never_repeats_until_all_have_played(self):
|
||||
self.set(shuffle=True)
|
||||
seen = []
|
||||
for _ in range(250):
|
||||
seen.append(self.player.mpv.path)
|
||||
self.finish_video()
|
||||
for start in range(0, 250, 5):
|
||||
self.assertEqual(len(set(seen[start:start + 5])), 5, "repeated within a pass")
|
||||
for one, two in zip(seen, seen[1:]):
|
||||
self.assertNotEqual(one, two)
|
||||
|
||||
def test_shuffle_changes_the_order_each_pass(self):
|
||||
self.set(shuffle=True)
|
||||
passes = set()
|
||||
for _ in range(30):
|
||||
order = []
|
||||
for _ in range(5):
|
||||
order.append(self.player.mpv.path)
|
||||
self.finish_video()
|
||||
passes.add(tuple(order))
|
||||
self.assertGreater(len(passes), 5)
|
||||
|
||||
def test_turning_shuffle_on_and_off_keeps_the_current_video(self):
|
||||
playing = self.player.mpv.path
|
||||
self.set(shuffle=True)
|
||||
self.assertEqual(self.player.mpv.path, playing)
|
||||
self.assertEqual(self.player.mpv.list[0], playing)
|
||||
self.assertEqual(sorted(self.player.mpv.list), self.player.files)
|
||||
self.set(shuffle=False)
|
||||
self.assertEqual(self.player.mpv.list, self.player.files)
|
||||
|
||||
def test_shuffle_skips_videos_that_are_off(self):
|
||||
self.press("any", "right", "toggle", "cancel", "cancel")
|
||||
self.set(shuffle=True)
|
||||
self.assertNotIn(self.path("a.mp4"), self.player.mpv.list)
|
||||
|
||||
def test_video_turned_back_on_plays_later_in_this_pass(self):
|
||||
self.set(shuffle=True)
|
||||
mpv = self.player.mpv
|
||||
target = mpv.list[-1]
|
||||
self.press("any", "right")
|
||||
self.player.menu.index = self.player.menu.items.index(target)
|
||||
self.press("toggle", "toggle")
|
||||
self.assertGreater(mpv.list.index(target), mpv.list.index(mpv.path))
|
||||
|
||||
def test_max_time_moves_on(self):
|
||||
self.set(max_minutes=5)
|
||||
self.advance(299)
|
||||
self.assertNotIn(("playlist-next",), self.player.mpv.commands)
|
||||
self.advance(1)
|
||||
self.assertIn(("playlist-next",), self.player.mpv.commands)
|
||||
|
||||
def test_no_limit_never_moves_on(self):
|
||||
self.advance(100000)
|
||||
self.assertNotIn(("playlist-next",), self.player.mpv.commands)
|
||||
|
||||
def test_max_time_counts_from_each_new_video(self):
|
||||
self.set(max_minutes=5)
|
||||
self.advance(200)
|
||||
self.finish_video()
|
||||
self.advance(200)
|
||||
self.assertNotIn(("playlist-next",), self.player.mpv.commands)
|
||||
|
||||
def test_max_time_with_one_video_keeps_playing(self):
|
||||
self.press("any", "down", "confirm")
|
||||
self.set(max_minutes=5)
|
||||
self.player.mpv.commands.clear()
|
||||
self.advance(1000)
|
||||
self.assertEqual([c for c in self.player.mpv.commands if c[0] != "set_property"], [])
|
||||
|
||||
def spots(self):
|
||||
return [c[2] for c in self.player.mpv.commands if c[1:2] == ("start",)]
|
||||
|
||||
def test_limit_shorter_than_video_leaves_the_full_limit_to_play(self):
|
||||
self.lengths.update({f"{n}.mp4": 9 * 3600 for n in "abcde"})
|
||||
self.set(max_minutes=60)
|
||||
for _ in range(200):
|
||||
self.finish_video()
|
||||
percents = [float(spot[:-1]) for spot in self.spots() if spot != "none"]
|
||||
self.assertGreater(len(percents), 150)
|
||||
self.assertTrue(all(0 <= p <= 100 * 8 / 9 for p in percents), max(percents))
|
||||
self.assertGreater(max(percents), 80) # really does use the whole range
|
||||
self.assertLess(min(percents), 8)
|
||||
|
||||
def test_limit_longer_than_video_starts_at_the_beginning(self):
|
||||
self.lengths.update({f"{n}.mp4": 1800 for n in "abcde"})
|
||||
self.set(max_minutes=60)
|
||||
self.finish_video()
|
||||
self.assertEqual(self.spots()[-1], "none")
|
||||
|
||||
def test_limit_with_unreadable_length_starts_at_the_beginning(self):
|
||||
self.set(max_minutes=60)
|
||||
self.finish_video()
|
||||
self.assertEqual(self.spots()[-1], "none")
|
||||
|
||||
def test_exact_pick_also_starts_where_the_limit_fits(self):
|
||||
self.lengths["c.mp4"] = 9 * 3600
|
||||
self.set(max_minutes=60)
|
||||
self.press("any", "right", "down", "down", "confirm")
|
||||
self.assertTrue(self.spots()[-1].endswith("%") or self.spots()[-2].endswith("%"))
|
||||
|
||||
def test_one_long_video_jumps_within_the_limit_when_time_runs_out(self):
|
||||
self.lengths["f.mp4"] = 9 * 3600
|
||||
self.press("any", "down", "confirm")
|
||||
self.set(max_minutes=60)
|
||||
self.advance(1) # the video has begun
|
||||
self.player.mpv.commands.clear()
|
||||
self.advance(3600)
|
||||
seeks = [c for c in self.player.mpv.commands if c[0] == "seek"]
|
||||
self.assertEqual(len(seeks), 1)
|
||||
self.assertLessEqual(seeks[0][1], 100 * 8 / 9)
|
||||
|
||||
def test_durations_are_only_read_once(self):
|
||||
calls = []
|
||||
ep.video_duration = lambda path: calls.append(path) or 7200
|
||||
for _ in range(3):
|
||||
self.player._random_spot(self.path("a.mp4"))
|
||||
self.player.settings["max_minutes"] = 60
|
||||
self.assertEqual(len(calls), 1)
|
||||
|
||||
def test_random_start_sets_a_new_spot_for_each_video(self):
|
||||
self.set(random_start=True)
|
||||
self.finish_video()
|
||||
self.finish_video()
|
||||
spots = self.spots()
|
||||
self.assertTrue(all(s.endswith("%") for s in spots[-2:]))
|
||||
self.assertNotEqual(spots[-1], spots[-2])
|
||||
self.set(random_start=False)
|
||||
self.assertEqual(self.player.mpv.commands[-1], ("set_property", "start", "none"))
|
||||
|
||||
def test_volume(self):
|
||||
self.set(volume=0)
|
||||
self.assertEqual(self.player.mpv.commands[-1], ("set_property", "volume", 0))
|
||||
|
||||
def test_settings_window_changes_and_saves(self):
|
||||
self.press("settings", "right")
|
||||
self.assertTrue(self.player.settings["shuffle"])
|
||||
self.assertTrue(ep.load_settings(self.player.settings_file)["shuffle"])
|
||||
self.press("down", "left")
|
||||
self.assertEqual(self.player.settings["max_minutes"], 120)
|
||||
|
||||
def test_start_switches_from_menu_and_closes(self):
|
||||
self.press("any", "settings")
|
||||
self.assertTrue(self.player.window.open)
|
||||
self.assertFalse(self.player.menu.open)
|
||||
self.press("settings")
|
||||
self.assertFalse(self.player.window.open)
|
||||
self.assertTrue(self.player.menu.open) # back where it came from
|
||||
|
||||
def test_left_and_right_stay_dead_when_everything_is_closed(self):
|
||||
self.press("right", "left")
|
||||
self.assertFalse(self.player.window.open or self.player.menu.open)
|
||||
|
||||
def test_bad_settings_file_gives_defaults(self):
|
||||
self.player.settings_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.player.settings_file.write_text('{"max_minutes": 7, "volume": 50, "shuffle": []}')
|
||||
self.assertEqual(ep.load_settings(self.player.settings_file),
|
||||
{"shuffle": False, "max_minutes": 0, "random_start": False, "volume": 50})
|
||||
self.player.settings_file.write_text("not json")
|
||||
self.assertEqual(ep.load_settings(self.player.settings_file)["volume"], 100)
|
||||
|
||||
|
||||
class GuideTest(unittest.TestCase):
|
||||
def test_each_screen_labels_its_buttons(self):
|
||||
for screen, words in (("folders", ("Open folder", "Play folder", "Settings")),
|
||||
("videos", ("Play video", "Turn on/off", "Back")),
|
||||
("settings", ("Move up", "Change", "Close"))):
|
||||
text = "\n".join(ep.render_guide(screen))
|
||||
for word in words:
|
||||
self.assertIn(word, text)
|
||||
|
||||
def test_lit_buttons_are_brighter(self):
|
||||
lit = "\n".join(ep.render_controller(0, 0, {"a"}))
|
||||
dim = "\n".join(ep.render_controller(0, 0, set()))
|
||||
self.assertGreater(lit.count("&H00&"), dim.count("&H00&"))
|
||||
|
||||
def test_every_label_has_a_place_on_the_drawing(self):
|
||||
for guide in ep.GUIDES.values():
|
||||
self.assertLessEqual(set(guide), set(ep.CALLOUTS))
|
||||
|
||||
|
||||
class PlayingHighlightTest(unittest.TestCase):
|
||||
def videos_menu(self, videos, index):
|
||||
menu = ep.Menu()
|
||||
menu.show({"Kya": "2 videos"}, "Kya", 0)
|
||||
menu.enter("Kya", videos, set(), None)
|
||||
menu.index = index
|
||||
return menu
|
||||
|
||||
def test_playing_video_gets_a_green_bar_and_a_tag(self):
|
||||
ass = ep.render_menu(self.videos_menu(["/v/a.mp4", "/v/b.mp4"], 0), "/v/b.mp4")
|
||||
self.assertIn(ep.PLAYING_GREEN, ass)
|
||||
self.assertIn("PLAYING", ass)
|
||||
|
||||
def test_stripe_still_shows_when_selected(self):
|
||||
ass = ep.render_menu(self.videos_menu(["/v/a.mp4"], 0), "/v/a.mp4")
|
||||
self.assertIn(ep.PLAYING_GREEN, ass)
|
||||
|
||||
def test_no_highlight_for_other_folders_videos(self):
|
||||
ass = ep.render_menu(self.videos_menu(["/v/a.mp4"], 0), "/other/c.mp4")
|
||||
self.assertNotIn(ep.PLAYING_GREEN, ass)
|
||||
self.assertNotIn("PLAYING", ass)
|
||||
|
||||
def test_current_folder_is_highlighted(self):
|
||||
menu = ep.Menu()
|
||||
menu.show({"Birds": "2 videos", "Kya": "13 videos"}, "Kya", 0)
|
||||
menu.index = 0
|
||||
self.assertIn(ep.PLAYING_GREEN, ep.render_menu(menu, "Kya"))
|
||||
|
||||
|
||||
class FolderHintTest(unittest.TestCase):
|
||||
def menu(self, index=0):
|
||||
menu = ep.Menu()
|
||||
menu.show({"Birds": "2 videos", "Fish": "1 video"}, "Birds", 0)
|
||||
menu.index = index
|
||||
return menu
|
||||
|
||||
def test_selected_folder_shows_play_and_open(self):
|
||||
ass = ep.render_menu(self.menu(), "Birds")
|
||||
self.assertIn("Play", ass)
|
||||
self.assertIn("Open", ass)
|
||||
|
||||
def test_other_folders_show_they_can_be_opened(self):
|
||||
self.assertIn("1 video ▶", ep.render_menu(self.menu(), "Birds"))
|
||||
|
||||
def test_settings_row_does_not_offer_to_play(self):
|
||||
ass = ep.render_menu(self.menu(index=2), "Birds")
|
||||
self.assertNotIn("Play folder", ass)
|
||||
self.assertNotIn(ep.render_folder_buttons(960, 500)[2], ass)
|
||||
|
||||
def test_folder_actions_stand_out(self):
|
||||
ass = "\n".join(ep.render_guide("folders"))
|
||||
self.assertRegex(ass, r"\\b1}Open folder")
|
||||
self.assertRegex(ass, r"\\b1}Play folder")
|
||||
self.assertNotRegex(ass, r"\\b1}Next video")
|
||||
|
||||
|
||||
class VideoHintTest(unittest.TestCase):
|
||||
def menu(self, off=()):
|
||||
menu = ep.Menu()
|
||||
menu.show({"Birds": "2 videos"}, "Birds", 0)
|
||||
menu.enter("Birds", ["/v/a.mp4", "/v/b.mp4"], set(off), None)
|
||||
menu.index = 0
|
||||
return menu
|
||||
|
||||
def test_selected_video_shows_its_buttons(self):
|
||||
ass = ep.render_menu(self.menu(), "/v/b.mp4")
|
||||
self.assertIn("Turn off", ass)
|
||||
self.assertIn("}Play\n", ass)
|
||||
|
||||
def test_selected_video_that_is_off_offers_turn_on_and_not_play(self):
|
||||
ass = ep.render_menu(self.menu(off={"/v/a.mp4"}), "/v/b.mp4")
|
||||
self.assertIn("Turn on", ass)
|
||||
self.assertNotIn("}Play\n", ass)
|
||||
|
||||
def test_on_off_and_play_stand_out_on_the_controller(self):
|
||||
ass = "\n".join(ep.render_guide("videos"))
|
||||
self.assertRegex(ass, r"\\b1}Turn on/off")
|
||||
self.assertRegex(ass, r"\\b1}Play video")
|
||||
|
||||
|
||||
class BootStartTest(PlayerCase):
|
||||
def boot(self):
|
||||
player = ep.Player(self.root, self.state)
|
||||
player.mpv = FakeMpv()
|
||||
player._pick_and_load()
|
||||
return player
|
||||
|
||||
def test_starts_on_a_random_video_but_never_the_last_one(self):
|
||||
ep.save_last_folder(self.state, "birds")
|
||||
ep.save_last_folder(self.state.with_name("last_video"), "a.mp4")
|
||||
firsts = {Path(self.boot().mpv.list[0]).name for _ in range(60)}
|
||||
self.assertEqual(firsts, {"b.mp4", "c.mp4"})
|
||||
|
||||
def test_whole_folder_still_queued(self):
|
||||
ep.save_last_folder(self.state, "birds")
|
||||
self.assertEqual(len(self.boot().mpv.list), 3)
|
||||
|
||||
def test_keeps_the_last_folder(self):
|
||||
ep.save_last_folder(self.state, "fish")
|
||||
self.assertEqual(self.boot().folder, "fish")
|
||||
|
||||
def test_one_video_folder_plays_that_video(self):
|
||||
ep.save_last_folder(self.state, "fish")
|
||||
ep.save_last_folder(self.state.with_name("last_video"), "f.mp4")
|
||||
self.assertEqual(Path(self.boot().mpv.list[0]).name, "f.mp4")
|
||||
|
||||
def test_videos_that_are_off_are_not_chosen(self):
|
||||
ep.save_last_folder(self.state, "birds")
|
||||
ep.save_disabled(self.state.with_name("disabled.json"), {"birds": {"b.mp4"}})
|
||||
ep.save_last_folder(self.state.with_name("last_video"), "a.mp4")
|
||||
firsts = {Path(self.boot().mpv.list[0]).name for _ in range(30)}
|
||||
self.assertEqual(firsts, {"c.mp4"})
|
||||
|
||||
def test_playing_video_is_remembered(self):
|
||||
player = self.boot()
|
||||
player._check_health(1000.0)
|
||||
self.assertEqual(ep.load_last_folder(self.state.with_name("last_video")),
|
||||
Path(player.mpv.path).name)
|
||||
|
||||
|
||||
class VideoOptionsTest(unittest.TestCase):
|
||||
def test_pi_uses_display_planes(self):
|
||||
original = ep.is_raspberry_pi
|
||||
self.addCleanup(setattr, ep, "is_raspberry_pi", original)
|
||||
ep.is_raspberry_pi = lambda: True
|
||||
self.assertIn("--gpu-hwdec-interop=drmprime-overlay", ep.video_options())
|
||||
|
||||
def test_other_machines_do_not(self):
|
||||
original = ep.is_raspberry_pi
|
||||
self.addCleanup(setattr, ep, "is_raspberry_pi", original)
|
||||
ep.is_raspberry_pi = lambda: False
|
||||
self.assertEqual(ep.video_options(), ["--hwdec=auto-safe"])
|
||||
|
||||
|
||||
class FirstFrameTest(PlayerCase):
|
||||
def test_stops_waiting_when_a_frame_arrives(self):
|
||||
positions = iter([None, 5.0, 5.0, 5.2])
|
||||
self.player.mpv.get = lambda name: next(positions)
|
||||
self.player._wait_for_first_frame()
|
||||
self.assertEqual(next(positions, "used"), "used")
|
||||
|
||||
def test_does_not_wait_with_nothing_to_play(self):
|
||||
self.player.folder = None
|
||||
self.player._wait_for_first_frame()
|
||||
|
||||
def test_starting_text_matches_the_splash(self):
|
||||
self.assertIn("Starting", ep.render_starting())
|
||||
|
||||
|
||||
class ConnectorTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.sysfs = Path(tmp.name)
|
||||
self.saved = self.sysfs / "display"
|
||||
|
||||
def port(self, name, edid=b""):
|
||||
folder = self.sysfs / f"card0-{name}"
|
||||
folder.mkdir(exist_ok=True)
|
||||
(folder / "edid").write_bytes(edid)
|
||||
|
||||
def choose(self):
|
||||
return ep.choose_connector(self.saved, str(self.sysfs))
|
||||
|
||||
def test_prefers_the_port_with_a_real_screen(self):
|
||||
self.port("HDMI-A-1")
|
||||
self.port("HDMI-A-2", b"edid")
|
||||
self.assertEqual(self.choose(), "HDMI-A-2")
|
||||
self.port("HDMI-A-1", b"edid")
|
||||
self.port("HDMI-A-2")
|
||||
self.assertEqual(self.choose(), "HDMI-A-1")
|
||||
|
||||
def test_remembers_the_port_while_the_tv_is_off(self):
|
||||
self.port("HDMI-A-1", b"edid")
|
||||
self.port("HDMI-A-2")
|
||||
self.choose()
|
||||
self.port("HDMI-A-1")
|
||||
self.assertEqual(self.choose(), "HDMI-A-1")
|
||||
|
||||
def test_defaults_to_the_second_port_on_first_boot_with_no_screen(self):
|
||||
self.port("HDMI-A-1")
|
||||
self.port("HDMI-A-2")
|
||||
self.assertEqual(self.choose(), "HDMI-A-2")
|
||||
|
||||
def test_other_connector_types_work_and_writeback_is_ignored(self):
|
||||
self.port("DP-1", b"edid")
|
||||
self.port("Writeback-1", b"edid")
|
||||
self.assertEqual(self.choose(), "DP-1")
|
||||
|
||||
def test_no_ports(self):
|
||||
self.assertIsNone(self.choose())
|
||||
|
||||
def test_audio_follows_the_picture(self):
|
||||
self.assertEqual(ep.hdmi_audio_device(None), "auto")
|
||||
|
||||
|
||||
class FullNameTest(unittest.TestCase):
|
||||
LONG = "A Wildlife Odyssey - Southeast Asia's Island Paradise | Part 1 | Free Documentary"
|
||||
|
||||
def render(self, title, index=0):
|
||||
menu = ep.Menu()
|
||||
menu.show({"Kya": "2 videos"}, "Kya", 0)
|
||||
menu.enter("Kya", [f"/v/{title}.mp4", "/v/Fish.mp4"], set(), None)
|
||||
menu.index = index
|
||||
return ep.render_menu(menu, None)
|
||||
|
||||
def test_shortened_title_shows_the_full_name_beneath(self):
|
||||
self.assertIn(self.LONG, self.render(self.LONG, index=1))
|
||||
|
||||
def test_selected_title_shows_the_full_name_beneath(self):
|
||||
self.assertIn(self.LONG, self.render(self.LONG, index=0))
|
||||
|
||||
def test_short_title_is_not_repeated(self):
|
||||
self.assertEqual(self.render("Fish tank", index=1).count("Fish tank"), 1)
|
||||
|
||||
def test_longer_names_use_smaller_print(self):
|
||||
self.assertEqual(ep.full_name_size("x" * 40), 20)
|
||||
self.assertLess(ep.full_name_size("x" * 110), 20)
|
||||
self.assertEqual(ep.full_name_size("x" * 500), 14)
|
||||
|
||||
|
||||
class TitleTest(unittest.TestCase):
|
||||
def test_tidies_youtube_file_names(self):
|
||||
self.assertEqual(ep.video_title("/x/10 Hours 😻 Cat TV | Birds [t36lxBkp-Mc].mp4"),
|
||||
"10 Hours Cat TV | Birds")
|
||||
|
||||
def test_long_titles_stay_different(self):
|
||||
base = "A Wildlife Odyssey - Southeast Asia's Island Paradise | Part {} | Full Documentary"
|
||||
titles = ep.short_titles([base.format(n) for n in (1, 2, 3)], 42)
|
||||
self.assertEqual(len(set(titles)), 3)
|
||||
self.assertTrue(all(len(t) <= 42 for t in titles))
|
||||
self.assertTrue(all(f"{n}" in t for n, t in zip((1, 2, 3), titles)))
|
||||
|
||||
def test_short_titles_are_left_alone(self):
|
||||
self.assertEqual(ep.short_titles(["Fish", "Birds"], 42), ["Fish", "Birds"])
|
||||
|
||||
def test_leaves_short_brackets_alone(self):
|
||||
self.assertEqual(ep.video_title("/x/clip [1].mp4"), "clip [1]")
|
||||
|
||||
|
||||
class FormatTimeTest(unittest.TestCase):
|
||||
def test_formats(self):
|
||||
self.assertEqual(ep.format_time(59), "0:59")
|
||||
self.assertEqual(ep.format_time(3725), "1:02:05")
|
||||
|
||||
|
||||
class MenuTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.menu = ep.Menu()
|
||||
self.menu.show({"a": "1 video", "b": "2 videos", "c": "3 videos"}, "b", 0)
|
||||
|
||||
def test_starts_on_current_folder_and_wraps(self):
|
||||
self.assertEqual(self.menu.index, 1)
|
||||
self.menu.handle("down", 0)
|
||||
self.menu.handle("down", 0)
|
||||
self.menu.handle("down", 0) # c, Settings, then round to a
|
||||
self.assertEqual(self.menu.index, 0)
|
||||
self.menu.handle("up", 0)
|
||||
self.assertEqual(self.menu.items[self.menu.index], ep.SETTINGS_ITEM)
|
||||
|
||||
def test_confirm_returns_folder_and_closes(self):
|
||||
self.menu.handle("down", 0)
|
||||
self.assertEqual(self.menu.handle("confirm", 0), ("play_folder", "c"))
|
||||
self.assertFalse(self.menu.open)
|
||||
|
||||
def test_cancel_picks_nothing(self):
|
||||
self.assertIsNone(self.menu.handle("cancel", 0))
|
||||
self.assertFalse(self.menu.open)
|
||||
|
||||
def test_b_inside_a_folder_goes_back_to_the_same_folder(self):
|
||||
self.menu.enter("b", ["/v/1.mp4"], set(), None)
|
||||
self.menu.handle("cancel", 0)
|
||||
self.assertTrue(self.menu.open)
|
||||
self.assertEqual(self.menu.items[self.menu.index], "b")
|
||||
|
||||
def test_names_cannot_inject_ass_tags(self):
|
||||
self.assertEqual(ep.ass_escape(r"a{\b1}"), r"a\{\\b1\}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,20 @@
|
||||
import unittest
|
||||
|
||||
from sync_youtube import parse_sources
|
||||
|
||||
|
||||
class ParseSourcesTest(unittest.TestCase):
|
||||
def test_reads_folders_and_links(self):
|
||||
text = "# comment\n\nBirds and Squirrels | https://y.be/a\nFish|https://y.be/b?x=1\n"
|
||||
self.assertEqual(parse_sources(text), [("Birds and Squirrels", "https://y.be/a"),
|
||||
("Fish", "https://y.be/b?x=1")])
|
||||
|
||||
def test_rejects_bad_lines(self):
|
||||
for line in ("https://y.be/a", "| https://y.be/a", "Fish | not-a-link",
|
||||
"../escape | https://y.be/a", ".. | https://y.be/a",
|
||||
"a/b | https://y.be/a"):
|
||||
self.assertEqual(parse_sources(line), [], line)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user