- Python 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
tsr.py endet nur nach einem Signal mit 0. Mit on-failure bliebe ein von Hand beendeter Recorder still liegen; die Neustart-Schleife bei Aufruffehlern verhindert weiterhin RestartPreventExitStatus=2. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> |
||
| .forgejo/workflows | ||
| .github/workflows | ||
| tests | ||
| .gitignore | ||
| CHANGELOG.md | ||
| LICENSE | ||
| README.md | ||
| tsr.py | ||
Twitch Stream Recorder (tsr.py)
Twitch Stream Recorder is a Python script for recording live streams from Twitch. The script allows you to record the stream in various quality options, including audio-only, and convert the audio to different formats.
Features:
- Record Twitch streams in different qualities (best, high, medium, low, mobile, and audio_only).
- Automatic stream checking to start recording when a streamer goes live.
- Post-processing: recordings are repaired and remuxed to MP4 (
-c copy,faststart) after the stream ends; audio-only recordings are remuxed to.aac. - Convert audio to formats like MP3, OGG, and AAC.
- Unfinished recordings from a previous run are picked up and processed automatically at startup.
- Post-processing runs in the background (max. 2 parallel ffmpeg jobs) and never delays or blocks a recording.
- Configurable via config file (
~/.config/tsr/config) or environment variables — no need to edit the script. - Runs as a systemd service without root; one instance per streamer, guarded by a lock.
- Optional: block a shutdown of the host while a stream is being recorded.
Requirements
- Linux with Python 3.11 or higher (the test suite runs with 3.11, 3.13 and 3.14)
- streamlink — tested with 5.2.1, 7.3.0 and 8.6.3; older versions are untested
- ffmpeg
- twitch-cli (1.1.24 at the time of writing)
How it works
tsr.py checks via the Twitch API whether the streamer is live and starts recording as soon as they are. It is recommended that the streamer makes a "Starting soon" at the beginning: it takes about 15-45 seconds before the Twitch API reports the status Live, and tsr.py only checks every 15 seconds (configurable, 15 seconds is the minimum).
Recordings are written as .ts files to <root_path>/recorded/<streamer>/ and moved to
<root_path>/processed/<streamer>/ after post-processing. While ffmpeg is still writing, the
file in processed/ is hidden and called .part.<filename>; it only gets its final name once
it is complete. If post-processing fails or is interrupted, the .ts stays in recorded/ and
is processed at the next start.
To access the Twitch API it is necessary to install and configure the Twitch CLI.
Usage
python3 tsr.py -u <username> [-q <quality>] [-a <audio format>] [-s <yes|no>]
| Option | Description |
|---|---|
-h, --help |
Display the help message and exit. |
--version |
Display the version and exit. |
-u, --username |
The Twitch streamer's username (required). 1 to 25 characters out of a-z, 0-9 and _; upper case is converted to lower case. Started in a terminal without -u, tsr.py asks for the name; without a terminal (service, cron, pipe) it prints the usage and exits with code 2. |
-q, --quality |
Stream quality: best, high, medium, low, mobile, audio_only. Default: best. See Quality levels. |
-a, --audio |
Additionally convert the audio track: mp3, ogg or aac. |
-s, --savefile |
Only has an effect together with -a. yes (default): keep the regular result (the .mp4, or the .aac of an audio-only recording) next to the converted audio file. no: keep only the converted audio file. |
The recorded .ts file is always removed once post-processing has succeeded; -s only decides
which files end up in processed/:
| Recording | -a |
-s yes |
-s no |
|---|---|---|---|
| Video | – | .mp4 |
.mp4 |
| Video | mp3 / ogg / aac |
.mp4 and the audio file |
audio file only |
audio_only |
– or aac |
.aac |
.aac |
audio_only |
mp3 / ogg |
.aac and .mp3 / .ogg |
.mp3 / .ogg only |
Examples:
# Record with best quality
python3 tsr.py -u diedoni
# Record in low quality and additionally extract the audio as MP3
python3 tsr.py -u diedoni -q low -a mp3
# Audio-only recording, converted to OGG, no additional AAC file
python3 tsr.py -u diedoni -q audio_only -a ogg -s no
Arguments without an option (tsr.py diedoni) and unknown options are rejected with the usage
text and exit code 2.
Optional: (WIP) tsrcontrol can also be used for administration.
Quality levels
Twitch no longer exposes the legacy names high/medium/low/mobile (streams are called
e.g. 1080p60, 720p60, 480p30 today), so these are mapped to the best available stream up to
a limit:
-q |
Records |
|---|---|
best |
the best stream the channel offers |
high |
the best stream up to 720p (including 720p60) |
medium |
the best stream up to 480p |
low |
the best stream up to 360p |
mobile |
the best stream up to 160p |
audio_only |
the audio stream |
If a channel offers nothing up to the chosen limit — a channel without transcodes only has its
source quality — the best available stream is recorded instead of nothing. -q medium on a
channel that only offers 1080p60 therefore records 1080p60.
Exit codes
| Code | Meaning |
|---|---|
0 |
Regular end: stopped by a signal (systemctl stop, kill, Ctrl+C), --help, --version. |
1 |
Runtime error: the streamer does not exist, the streamer is already being recorded by another instance, streamlink, ffmpeg or twitch-cli not found, recording folder or lock file cannot be created. |
2 |
Usage error: invalid or unknown option, invalid streamer name, no streamer given without a terminal, unbalanced quotes in TSR_STREAMLINK_ARG. |
Errors while tsr.py is running (Twitch API not reachable, streamlink fails) do not end it: it waits 15, 30, 60, 120 and then 300 seconds between attempts and starts over after the first success.
Signals and the lock
- Only one instance runs per streamer. The lock file is
~/.local/state/tsr/<streamer>.lock(respectingXDG_STATE_HOME). A second instance for the same streamer exits with code 1. streamlink holds the lock as well, so a streamlink that outlived tsr.py (e.g. afterkill -9) blocks the next start until it has ended, instead of losing the file it is still writing. SIGTERM(systemctl stop,kill) andSIGHUPend tsr.py quickly: streamlink and ffmpeg are stopped, nothing is post-processed. The recording stays inrecorded/and is processed at the next start.- Ctrl+C stops the recording and still finishes post-processing. A second Ctrl+C aborts that as
well; the recording then stays in
recorded/.
Configuration
All settings have sensible defaults and can be overridden without editing the script — either with a config file or with environment variables. The precedence is:
environment variable > config file > built-in default
An empty value (TSR_ROOT_PATH=) counts as not set.
Config file
tsr.py looks for ~/.config/tsr/config (respecting XDG_CONFIG_HOME); an alternative
path can be set with the TSR_CONFIG environment variable. The format is one
KEY=VALUE per line, encoded as UTF-8:
# ~/.config/tsr/config
TSR_ROOT_PATH=/home/username/recording/
TSR_REFRESH=30
TSR_TWITCH_CLI=/usr/local/bin/twitch
- A line starting with
#is a comment. There are no comments behind a value: a#after the value is part of the value, because it may occur in paths and streamlink arguments. - One pair of quotes around the whole value (
TSR_ROOT_PATH="/srv/rec/") and a leadingexportare removed. - Unknown keys, e.g. a mistyped
TSR_ROOTPATH, are reported with their line number and ignored.
Settings
The same keys can be set as environment variables, which take precedence over the config file:
| Key | Default | Description |
|---|---|---|
TSR_ROOT_PATH |
/recording/ |
Folder where recordings are stored. |
TSR_STREAMLINK |
streamlink |
Path to the streamlink binary (e.g. inside a virtualenv). |
TSR_FFMPEG |
ffmpeg |
Path to the ffmpeg binary. |
TSR_STREAMLINK_ARG |
--twitch-api-header Client-ID=ue6666qo983tsx6so1t0vnawi233wa |
Extra arguments passed to streamlink. Quotes are understood (--twitch-api-header "Authorization=OAuth abc"). Setting it replaces the default. |
TSR_TWITCH_CLI |
/home/linuxbrew/.linuxbrew/bin/twitch |
Path to the Twitch CLI binary. |
TSR_REFRESH |
15 |
Check interval in seconds (minimum 15). |
TSR_INHIBIT_SHUTDOWN |
no |
yes blocks a shutdown of the host while a stream is being recorded. Read Shutdown lock before switching it on. |
TSR_CONFIG |
~/.config/tsr/config |
Path to the config file (environment variable only). |
Example:
TSR_ROOT_PATH=/home/username/recording/ python3 tsr.py -u diedoni
Alternatively, the defaults can still be changed directly in the configuration block
at the top of tsr.py.
Ads and streamlink before 7.5
streamlink 7.5 and later always filter Twitch ads. Older versions — Debian 12 ships 5.2.1,
Debian 13 ships 7.3.0 — only filter them with --twitch-disable-ads. The flag is not part of the
default because newer versions warn that it is deprecated. With streamlink older than 7.5 add it
yourself:
TSR_STREAMLINK_ARG=--twitch-api-header Client-ID=ue6666qo983tsx6so1t0vnawi233wa --twitch-disable-ads
OAuth token
Everything in TSR_STREAMLINK_ARG ends up on the command line of streamlink and is visible to
every local user in the process list. Do not put an OAuth token there; use the config file of
streamlink instead and make it readable for its owner only:
mkdir -p ~/.config/streamlink
echo 'twitch-api-header=Authorization=OAuth YOUR_TOKEN' > ~/.config/streamlink/config
chmod 600 ~/.config/streamlink/config
Install Streamlink and Twitch CLI to run tsr.py
Tested under Debian 13 (Trixie) with Python 3.13. Debian 12 (Bookworm) has not been re-tested with this version.
- Install dependencies:
sudo apt install streamlink ffmpeg curl- Debian 12 ships streamlink 5.2.1. A newer one (7.3.0) is available from bookworm-backports:
sudo apt install -t bookworm-backports streamlink sudo pip3 install streamlinkno longer works on Debian 12 and 13 (PEP 668). If you need a newer streamlink than your distribution offers, install it into a virtualenv and pointTSR_STREAMLINKto it.
- Debian 12 ships streamlink 5.2.1. A newer one (7.3.0) is available from bookworm-backports:
- Install Twitch CLI. Either the release binary from
GitHub (
Linux_x86_64orLinux_arm64):
and setcurl -fsSLO https://github.com/twitchdev/twitch-cli/releases/download/v1.1.24/twitch-cli_1.1.24_Linux_x86_64.tar.gz tar -xzf twitch-cli_1.1.24_Linux_x86_64.tar.gz sudo install -m 755 twitch-cli_1.1.24_Linux_x86_64/twitch /usr/local/bin/twitchTSR_TWITCH_CLI=/usr/local/bin/twitch(step 5), or with Homebrew, which matches the default path ofTSR_TWITCH_CLI:/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"echo 'eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)"' >> /home/$USER/.profileandeval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)"brew install twitchdev/twitch/twitch-cli
- With the following command we now configure the Twitch CLI:
twitch configure- You have to create a Twitch App at https://dev.twitch.tv/ to get Client ID and Secret
- Set OAuth URL to http://localhost:3000 and use Application Integration as category
- After
twitch configureruntwitch tokenonce - Download tsr.py:
curl -fsSLO https://github.com/DravenTec/Twitch-Stream-Recorder/releases/latest/download/tsr.pyand set your recording folder and the path of the Twitch CLI, either in the config file (TSR_ROOT_PATH=/your/recorder/folder/andTSR_TWITCH_CLI=/usr/local/bin/twitchin~/.config/tsr/config), via the environment variables of the same name, or by editingtsr.py - Run with
python3 tsr.py -u STREAMERNAME
Steps 3 and 4 have to be done as the user that runs tsr.py: twitch-cli keeps Client ID, Secret
and token in ~/.config/twitch-cli/.twitch-cli.env.
Running as a systemd service
tsr.py does not need root anywhere, so the service runs as a dedicated system user tsr. Its
home /var/lib/tsr holds the configuration, the credentials of twitch-cli and the lock files;
recordings go to /srv/tsr in this example. Steps 1 and 2 of the installation above are
required; the Twitch CLI is expected in /usr/local/bin/twitch.
- Create the user and the recording folder:
sudo useradd --system --create-home --home-dir /var/lib/tsr --shell /usr/sbin/nologin tsr sudo install -d -o tsr -g tsr -m 750 /srv/tsr - Install the script:
sudo curl -fsSLo /usr/local/bin/tsr.py https://github.com/DravenTec/Twitch-Stream-Recorder/releases/latest/download/tsr.py - Create the config file
/var/lib/tsr/.config/tsr/config:
With streamlink older than 7.5 also add thesudo -u tsr mkdir -p /var/lib/tsr/.config/tsr sudo -u tsr tee /var/lib/tsr/.config/tsr/config > /dev/null <<'EOF' TSR_ROOT_PATH=/srv/tsr/ TSR_TWITCH_CLI=/usr/local/bin/twitch EOFTSR_STREAMLINK_ARGline from Ads and streamlink before 7.5. - Configure the Twitch CLI as this user (Client ID and Secret as in step 3 of the installation):
sudo -u tsr twitch configure sudo -u tsr twitch token - Create the unit
/etc/systemd/system/tsr@.service:[Unit] Description=Twitch Stream Recorder (%i) Wants=network-online.target After=network-online.target # Recording to a network share: wait for the mount # RequiresMountsFor=/srv/tsr [Service] User=tsr ExecStart=/usr/bin/python3 /usr/local/bin/tsr.py -u %i Restart=always RestartSec=30 RestartPreventExitStatus=2 StateDirectory=tsr StateDirectoryMode=0700 ReadWritePaths=/srv/tsr ProtectSystem=strict NoNewPrivileges=yes UMask=0027 [Install] WantedBy=multi-user.target - Start one instance per streamer and have it started at boot:
sudo systemctl daemon-reload sudo systemctl enable --now tsr@diedoni - Look at the log:
"offline" is only logged when the state changes, not on every check.journalctl -u tsr@diedoni -f
Notes on the unit:
- The part after
@is the streamer. tsr.py only acceptsa-z,0-9and_there, so an instance name with a path in it ends with exit code 2 instead of touching other folders. Restart=always: tsr.py only ends with exit code 0 after a signal, so a recorder that was stopped withkillcomes back after 30 seconds instead of staying down unnoticed. To stop it for good usesystemctl stop.RestartPreventExitStatus=2: a usage error (invalid streamer name, brokenTSR_STREAMLINK_ARG) will not get better by restarting, the unit stays failed. Exit code 1 is retried every 30 seconds — this includes a streamer that does not exist.ProtectSystem=strictmakes the file system read-only for the service. Writable are only/var/lib/tsr(StateDirectory=) and the recording folder (ReadWritePaths=, it has to exist). If you changeTSR_ROOT_PATH, changeReadWritePaths=andRequiresMountsFor=too.StateDirectoryMode=0700keeps the home of the user closed: twitch-cli stores Client Secret and token there in a file that is readable for everyone.KillModestays at its defaultcontrol-group, sosystemctl stopreaches streamlink and ffmpeg as well.PYTHONUNBUFFEREDis not needed, the log is written line by line.- With
UMask=0027recordings are readable for the grouptsr, not for everyone.
What happens on systemctl stop and when the host shuts down: the running recording ends, the
.ts file stays in recorded/ and is post-processed when the service starts again. What is lost
is the time the service is not running.
Shutdown lock (optional)
With TSR_INHIBIT_SHUTDOWN=yes tsr.py holds a systemd inhibitor lock while streamlink is
recording. shutdown, poweroff and reboot are then refused with a message that names the
streamer:
Operation inhibited by "tsr" (PID 1234 "systemd-inhibit", user tsr), reason is "Recording diedoni".
systemd-inhibit --list shows the lock, systemctl reboot -i (or poweroff -i) overrides it.
The lock is gone as soon as the recording has ended; post-processing does not hold one. It is
switched off by default and switched on in the config file:
TSR_INHIBIT_SHUTDOWN=yes
Read this before switching it on. The lock does not only stop an admin at the terminal.
logind refuses every shutdown request that does not come with -i — according to the systemd
sources this includes ssh host reboot, a shutdown requested by the hypervisor and a shutdown
by a UPS daemon. A host that is expected to go down on its own (UPS on battery, hypervisor
maintenance) will then stay up for as long as the stream runs, or be powered off hard. Make
sure every automatic shutdown on that host uses systemctl poweroff -i before you enable the
lock. Two places that may need it, both untested here: the kernel setting
kernel.poweroff_cmd (default /sbin/poweroff, e.g. sysctl kernel.poweroff_cmd="/usr/bin/systemctl poweroff -i")
and PowerKeyIgnoreInhibited=yes in /etc/systemd/logind.conf for a shutdown that arrives as a
power button event.
State of testing: on Debian 13 (systemd 257) the lock was taken and released as described and
systemctl reboot --dry-run / systemctl poweroff --dry-run in a terminal were refused. A real
shutdown and requests without a terminal have not been tested. Try it on your host before you
rely on it — in either direction.
Requirements:
systemd-inhibit, logind and GNUtail(the lock is held bysystemd-inhibit … tail --pid=<streamlink>).- systemd 257 or newer (Debian 13) to stop root. With older versions (Debian 12: systemd 252) the lock only stops other users; root shuts down regardless.
- root and users with a login session may take the lock without further setup. A service user
without a session — the
tsruser from above — needs polkit (sudo apt install polkitd) and a rule in/etc/polkit-1/rules.d/50-tsr-inhibit.rules:polkit.addRule(function(action, subject) { if (action.id == "org.freedesktop.login1.inhibit-block-shutdown" && subject.user == "tsr") { return polkit.Result.YES; } });
If the lock cannot be taken (no systemd-inhibit, no permission), tsr.py says so once at startup
(TSR_INHIBIT_SHUTDOWN: could not take a shutdown lock (…). Recording without it.) and records
without it. A missing lock never prevents a recording.
Automatic token renewal
To ensure that the Twitch token is always renewed, I use crontab and have the token updated once a week.
If you want to update it manually you can do that at any time with twitch token.
Set up a cronjob under the user running tsr.py and twitch with crontab -e
(for the service user from above: sudo crontab -u tsr -e).
In my case, I have the token renewed every Monday at 2am.
0 2 * * MON /usr/local/bin/twitch token > /dev/null 2>&1
With Homebrew the path is /home/linuxbrew/.linuxbrew/bin/twitch.
The output of twitch token contains the token itself, so it is discarded here. If you want a
log to have a clue in case of problems, make sure that nobody else can read it:
0 2 * * MON umask 077; /usr/local/bin/twitch token > "$HOME/twitch-token.log" 2>&1
An existing log file keeps its permissions; fix one that was created earlier with
chmod 600.