.
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | `rffmpeg` is a remote FFmpeg wrapper used to execute FFmpeg commands on a remote server via SSH. It is most useful in situations involving media servers such as Jellyfin (our reference user), where one might want to perform transcoding actions with FFmpeg on a remote machine or set of machines which can better handle transcoding, take advantage of hardware acceleration, or distribute transcodes across multiple servers for load balancing.
18 |
19 | ## Quick usage
20 |
21 | 1. Install the required Python 3 dependencies: `click`, `yaml` and `subprocess` (`sudo apt install python3-click python3-yaml python3-subprocess` in Debian) and optionally install `psycopg2` with `sudo apt install python3-psycopg2` for Postgresql support.
22 |
23 | 1. Create the directory `/etc/rffmpeg`.
24 |
25 | 1. Optionally, copy the `rffmpeg.yml.sample` file to `/etc/rffmpeg/rffmpeg.yml` and edit it to suit your needs.
26 |
27 | 1. Install `rffmpeg` somewhere useful, for instance at `/usr/local/bin/rffmpeg`.
28 |
29 | 1. Create symlinks for the command names `ffmpeg` and `ffprobe` to `rffmpeg`, for example `sudo ln -s /usr/local/bin/rffmpeg /usr/local/bin/ffmpeg` and `sudo ln -s /usr/local/bin/rffmpeg /usr/local/bin/ffprobe`.
30 |
31 | 1. Initialize the database and add a target host, for example `sudo rffmpeg init && rffmpeg add myhost.domain.tld`.
32 |
33 | 1. Set your media program to use `rffmpeg` via the `ffmpeg` symlink name created above, instead of any other `ffmpeg` binary.
34 |
35 | 1. Profit!
36 |
37 | `rffmpeg` does require a little bit more configuration to work properly however. For a comprehensive installation tutorial based on a reference setup, please see [the SETUP guide](SETUP.md).
38 |
39 | **NOTE** Jellyfin 10.10.x and newer require an additional `TMPDIR` environment variable set to somewhere exported to the remote machine, or these paths will not work properly. Edit your Jellyfin startup/service configuration to set that. See the setup guide for more details.
40 |
41 | ## Setup and Usage
42 |
43 | ### The `rffmpeg` Configuration file
44 |
45 | `rffmpeg` will look at `/etc/rffmpeg/rffmpeg.yml` (or a path specified by the `RFFMPEG_CONFIG` environment variable) for a configuration file. If it doesn't find one, defaults will be used instead. You can use this file to override many configurable default values to better fit your environment. The defaults should be sensible for anyone using [Jellyfin](https://jellyfin.org) and following the [SETUP guide](SETUP.md).
46 |
47 | The example configuration file at `rffmpeg.yml.sample` shows all available options; this file can be copied as-is to the above location and edited to suit your needs; simply uncomment any lines you want to change. Note that if you do specify a file, you *must* ensure that all top-level categories are present or it will error out.
48 |
49 | **NOTE:** If you are running into problems with `rffmpeg`, you must use the config file to adjust `logging` -> `debug` to `true` to obtain more detailed logs before requesting help.
50 |
51 | Each option has an explanatory comment above it detailing its purpose.
52 |
53 | Since the configuration file is YAML, ensure that you do not use "Tab" characters inside of it, only spaces.
54 |
55 | ### CLI interface to `rffmpeg`
56 |
57 | `rffmpeg` is a [Click](https://click.palletsprojects.com)-based application; thus, all commands have a `-h` or `--help` flag to show usage and additional options that may be specified.
58 |
59 | ### Initializing `rffmpeg`
60 |
61 | After first installing `rffmpeg`, you must initialize the database with the `rffmpeg init` command.
62 |
63 | Note that by default, `sudo`/root privilege is required for this command to create the required data paths, but afterwards, `rffmpeg` can be run by anyone in the configured group (by default the `sudo` group). You can bypass the `sudo` requirement with the `--no-root` command, for example when running in a rootless container; this will require the running user to have write permissions to the state and database parent directories, and will not perform any permissions modifications on the resulting files.
64 |
65 | ### Viewing Status
66 |
67 | Once installed and initialized, you can see the status of the `rffmpeg` system with the `rffmpeg status` command. This will show all configured target hosts, their states, and any active commands being run.
68 |
69 | ### Adding or Removing Target Hosts
70 |
71 | To add a target host, use the `rffmpeg add` command. You must add at least one target host for `rffmpeg` to be useful. This command takes the optional `-w`/`--weight` flag to adjust the weight of the target host (see below). A host can also be added more than once for a pseudo-weight, but this is an advanced usage.
72 |
73 | To remove a target host, use the `rffmpeg remove` command. This command takes either a target host name/IP, which affects all instances of that name, or a specific host ID. Removing an in-use target host will not terminate any running processes, though it may result in undefined behaviour within `rffmpeg`. Before removing a host it is best to ensure there is nothing using it.
74 |
75 | ### Viewing the Logfile
76 |
77 | The `rffmpeg` CLI offers a convenient way to view the log file. Use `rffmpeg log` to view the entire logfile in the default pager (usually `less`), or use `rffmpeg log -f` to follow any new log entries after that point (like `tail -0 -f`).
78 |
79 | ## Important Considerations
80 |
81 | ### Localhost and Fallback
82 |
83 | If one of the configured target hosts is called `localhost` or `127.0.0.1`, `rffmpeg` will run the `ffmpeg`/`ffprobe` commands locally without SSH. This can be useful if the local machine is also a powerful transcoding device, but you still want to offload some transcoding jobs to other machines.
84 |
85 | In addition, `rffmpeg` will fall back to `localhost` automatically, even if it is not explicitly configured, should it be unable to find any working remote hosts. This helps prevent situations where `rffmpeg` cannot be run due to none of the remote host(s) being available.
86 |
87 | The exact path to the local `ffmpeg` and `ffprobe` binaries can be overridden in the configuration, should their paths not match those of the remote system(s).
88 |
89 | ### Hardware Acceleration
90 |
91 | Note that if hardware acceleration is configured in the calling application, **the exact same hardware acceleration modes must be available on all configured hosts, and, for fallback to work, the local host as well**, or the `ffmpeg` commands will fail.
92 |
93 | This is an explicit requirement, and there is no easy way around this without rewriting the passed arguments, which is explicitly out-of-scope for `rffmpeg` (see the FAQ entry below about mangling arguments).
94 |
95 | You should always use a lowest-common-denominator approach when deciding what hardware acceleration option(s) to enable, such that any configured host can run any process, or accept that fallback will not work if all remote hosts are unavailable.
96 |
97 | ### Target Host Selection
98 |
99 | When more than one target host is present, `rffmpeg` uses the following rules to select a target host. These rules are evaluated each time a new `rffmpeg` alias process is spawned based on the current state (actively running processes, etc.).
100 |
101 | 1. Any hosts marked `bad` are ignored.
102 |
103 | 1. All remaining hosts are iterated through in an indeterminate order (Python dictionary with root key as the host ID). For each host:
104 |
105 | a. If the host is not `localhost`/`127.0.0.1`, it is tested to ensure it is reachable (responds to `ffmpeg -version` over SSH). If it is not reachable, it is marked `bad` for the duration of this processes' runtime and skipped.
106 |
107 | b. If the host is `idle` (has no running processes), it is immediately chosen and the iteration stops.
108 |
109 | c. If the host is `active` (has at least one running process), it is checked against the host with the current fewest number of processes, adjusted for host weight. If it has the fewest, it takes over this role.
110 |
111 | 1. Once all hosts have been iterated through, at least one host should have been chosen: either the first `idle` host, or the host with the fewest number of active processes. `rffmpeg` will then begin running against this host. If no valid target host was found, `localhost` is used (see section [Localhost and Fallback](#localhost-and-fallback) above).
112 |
113 | ### Target Host Weights and Duplicated Target Hosts
114 |
115 | When adding a host to `rffmpeg`, a weight can be specified. Weights are used during the calculation of the fewest number of processes among hosts. The actual number of processes running on the host is floor divided (rounded down to the nearest divisible integer) by the weight to give a "weighted count", which is then used in the determination. This option allows one host to take on more processes than other nodes, as it will be chosen as the "least busy" host more often.
116 |
117 | For example, consider two hosts: `host1` with weight 1, and `host2` with weight 5. `host2` would have its actual number of processes floor divided by `5`, and thus any number of processes under `5` would count as `0`, any number of processes between `5` and `10` would count as `1`, and so on, resulting in `host2` being chosen over `host1` even if it had several processes. Thus, `host2` would on average handle 5x more `ffmpeg` processes than `host1` would.
118 |
119 | Host weighting is a fairly blunt instrument, and only becomes important when many simultaneous `ffmpeg` processes/transcodes are occurring at once across at least 2 remote hosts, and where the target hosts have significantly different performance profiles. Generally leaving all hosts at weight 1 would be sufficient for most use-cases.
120 |
121 | Furthermore, it is possible to add a host of the same name more than once in the `rffmpeg add` command. This is functionally equivalent to setting the host with a higher weight, but may have some subtle effects on host selection beyond what weight alone can do; this is probably not worthwhile but is left in for the option.
122 |
123 | ### `bad` Hosts
124 |
125 | As mentioned above under [Target Host Selection](#target-host-selection), a host can be marked `bad` if it does not respond to an `ffmpeg -version` command in at least 1 second if it is due to be checked as a target for a new `rffmpeg` alias process. This can happen because a host is offline, unreachable, overloaded, or otherwise unresponsive.
126 |
127 | Once a host is marked `bad`, it will remain so for as long as the `rffmpeg` process that marked it `bad` is running. This can last anywhere from a few seconds (library scan processes, image extraction) to several tens of minutes (a long video transcode). During this time, any new `rffmpeg` processes that start will see that the host is marked as `bad` and thus skip it for target selection. Once the marking `rffmpeg` process completes or is terminated, the `bad` status of that host will be cleared, allowing the next run to try it again. This strikes a balance between always retrying known-unresponsive hosts over and over (and thus delaying process startup), and ensuring that hosts will eventually be retried.
128 |
129 | If for some reason all configured hosts are marked `bad`, fallback will be engaged; see the above section [Localhost and Fallback](#localhost-and-fallback) for details on what occurs in this situation. An explicit `localhost` host entry cannot be marked `bad`.
130 |
131 | ## FAQ
132 |
133 | ### Why did you make `rffmpeg`?
134 |
135 | My virtualization setup (multiple 1U nodes with lots of live migration/failover) didn't lend itself well to passing a GPU into my Jellyfin VM, but I wanted to offload transcoding because doing 4K HEVC transcodes with a CPU performs horribly. I happened to have another machine (my "base" remote headless desktop/gaming server) which had a GPU, so I wanted to find a way to offload the transcoding to it. I came up with `rffmpeg` as a simple wrapper to the `ffmpeg` and `ffprobe` calls that Jellyfin (and Emby, and likely other media servers too) makes which would run them on that host instead. After finding it quite useful myself, I released it publicly as GPLv3 software so that others may benefit as well! It has since received a lot of feedback and feature requests from the community, leading to the tool as it exists today.
136 |
137 | ### What supports `rffmpeg`?
138 |
139 | This depends on what "layer" you're asking at.
140 |
141 | * Media Servers: Jellyfin is officially supported; Emby seems to work fine, with caveats (see [Issue #10](https://github.com/joshuaboniface/rffmpeg/issues/10)); no others have been tested to my knowledge.
142 | * Operating Systems (source): Debian and its derivatives (Ubuntu, Linux Mint, etc.) should all work perfectly; other Linux operating systems should work fine too as the principles are the same; MacOS should work since it has an SSH client built in; Windows will not work as `rffmpeg` depends on some POSIX assumptions internally.
143 | * Operating Systems (target): Any Linux system which [`jellyfin-ffmpeg`](https://github.com/jellyfin/jellyfin-ffmpeg) supports, which is currently just Debian and Ubuntu; Windows *might* work if you can get an SSH server running on it (see [Issue #17](https://github.com/joshuaboniface/rffmpeg/issues/17)).
144 | * Install Methods for Jellyfin: Native packages/installers/archives are recommended; a set of [Jellyfin Docker containers integrating `rffmpeg`](https://github.com/Shadowghost/jellyfin-rffmpeg) has been created by [@Shadowghost](https://github.com/Shadowghost). In addition to this special docker image you can use linuxserver's image with [this mod](https://github.com/linuxserver/docker-mods/tree/jellyfin-rffmpeg).
145 | * Install Methods for `rffmpeg`: Direct installation is recommended; a [Docker container to act as an ffmpeg transcode target](https://github.com/aleksasiriski/rffmpeg-worker) has been created by [@aleksasiriski](https://github.com/aleksasiriski) as well as [another](https://github.com/BasixKOR/rffmpeg-docker) by [@BasixKOR](https://github.com/BasixKOR).
146 | * OUTDATED Cloud: [HCloud Rffmpeg](https://github.com/aleksasiriski/hcloud-rffmpeg) script made to read rffmpeg database and spin up more transcode nodes in Hetzner Cloud.
147 | * Kubernetes: A short guide and example yaml files are available [here](https://github.com/aleksasiriski/rffmpeg-worker/tree/main/Kubernetes).
148 |
149 | ### Can `rffmpeg` mangle/alter FFMPEG arguments?
150 |
151 | Explicitly *no*. `rffmpeg` is not designed to interact with the arguments that the media server passes to `ffmpeg`/`ffprobe` at all, nor will it.
152 |
153 | This is an explicit design decision due to the massive complexity of FFmpeg. FFmpeg has a very large number of possible arguments, many of which are position-dependent or dependent on other arguments elsewhere in the chain. To implement argument mangling, we would need to be aware of every possible FFmpeg argument, exactly how each argument maps to each other argument, and be able to dynamically parse and update arguments based on this. As should hopefully be quite obvious, this is a massive undertaking and not something that I have any desire to implement or manage in such a (relatively) simple utility.
154 |
155 | This has a number of effects:
156 |
157 | * `rffmpeg` cannot adjust any `ffmpeg` options based on the host selected.
158 | * `rffmpeg` does not know whether hardware acceleration is turned on or not (see above caveats under [Hardware Acceleration](#hardware-acceleration)), or what type(s) of hardware acceleration are active.
159 | * `rffmpeg` does not know what media file(s) is is handling or where it's outputting files to, and cannot alter these paths.
160 |
161 | Thus it is imperative that you set up your entire system correctly for `rffmpeg` to work using a "least-common-denominator" approach as required. Please see the [SETUP guide](SETUP.md) for more information.
162 |
163 | ### Can `rffmpeg` do Wake-On-LAN or other similar options to turn on a transcode server?
164 |
165 | Explicitly *no*, though the linuxserver.io [docker mod](https://github.com/linuxserver/docker-mods/tree/jellyfin-rffmpeg) does support this.
166 |
167 | I've thought about implementing this more than once (most recently, in response to [Issue #21](https://github.com/joshuaboniface/rffmpeg/issues/21)) but ultimately I do not believe this is worth the complexity and delays it would introduce when spawning processes. That issue does provide one example of a workaround wrapper script that could accomplish this, but I do not plan for it to be a part of `rffmpeg` itself.
168 |
169 | ### I'm getting an error, help!
170 |
171 | First, run though the setup guide again and make sure that everything is set up correctly.
172 |
173 | If the problem persists, please check the [closed issues](https://github.com/joshuaboniface/rffmpeg/issues?q=is%3Aissue+sort%3Aupdated-desc+is%3Aclosed) and see if it's been reported before (if it's regarding Emby and you get an "error 127", see [Issue #10](https://github.com/joshuaboniface/rffmpeg/issues/10)).
174 |
175 | If it hasn't, you can [ask in our chat](https://matrix.to/#/#rffmpeg:matrix.org) or open a new issue. Ensure you:
176 |
177 | 1. Enable debug logging in `rffmpeg.yml` (`logging` -> `debug` to `true`) and re-run any failing or incorrect command(s) to obtain debug-level logs for analysis.
178 |
179 | 1. For issues, use a descriptive and useful title that quickly explains the problem.
180 |
181 | 1. Clearly explain (in the body of the issue or in your chat message) your setup, what is going wrong, and what you expect should be happening. Don't fret if English isn't your first language or anything like that, as long as you are trying to be clear that's what counts!
182 |
183 | 1. Include your `rffmpeg.log` and Jellyfin/Emby transcode logs as these are absolutely critical in determining what is going on. Use triple-backticks ("```") to enclose logs inline, both in chat and in issues.
184 |
185 | I will probably ask clarifying questions as required; please be prepared to run test commands, etc. as requested and paste the output.
186 |
187 | ### I found a bug/flaw and fixed it, or made a feature improvement; can I share it?
188 |
189 | Absolutely - I'm happy to take pull requests for just about any bugfix or improvement. There is one exception: please refer to the "Can `rffmpeg` mangle/alter FFMPEG arguments?" entry above; unless it's really good work with a very explicitly defined limitation, I probably don't want to go down that route, but I'm more than willing to look at what you've done and consider it on its merits.
190 |
191 | ### Can you help me set up my server?
192 |
193 | I'm always happy to help, though please ensure you try to follow the setup guide first - that's why I wrote it! Support can be found [on Matrix](https://matrix.to/#/#rffmpeg:matrix.org) or via email at `joshua@boniface.me`. Please note though that I may be unresponsive sometimes, though I will get back to you eventually I promise! Please don't open Issues here about setup problems; the Issue tracker is for bugs or feature requests instead.
194 |
195 | ### `rffmpeg-go` - forked project
196 |
197 | There's also a [fork of this script written in Go](https://github.com/aleksasiriski/rffmpeg-go) with semver tags and binaries available, as well as docker images for both the [script](https://github.com/aleksasiriski/rffmpeg-go/pkgs/container/rffmpeg-go) and [Jellyfin](https://github.com/aleksasiriski/jellyfin-rffmpeg).
198 |
--------------------------------------------------------------------------------
/SETUP.md:
--------------------------------------------------------------------------------
1 | # Example Setup Guide
2 |
3 | This example setup is the one I use for `rffmpeg` with Jellyfin. It uses 2 servers: a media server running Jellyfin called `jellyfin1`, and a remote transcode server called `transcode1`. Both systems run Debian GNU/Linux, though the commands below should also work on Ubuntu. Throughout this guide I assume you are running as an unprivileged user with `sudo` privileges (i.e. in the group `sudo`). Basic knowledge of Linux CLI usage is assumed. Whenever a verbatim command is specified, it will be prefixed by the relevant host to run it on (either `jellyfin1` or `transcode1`) and then a `$` prompt indicator. Any command output is usually not shown unless it is relevant.
4 |
5 | This guide is provided as a basic starting point - there are myriad possible combinations of systems, and I try to keep `rffmpeg` quite flexible. Feel free to experiment.
6 |
7 | ## Set up the media server (`jellyfin1`)
8 |
9 | ### Basic Setup
10 |
11 | 1. Install Jellyfin (or similar FFMPEG-using media server) on your machine. This guide assumes you're using native `.deb` packages.
12 |
13 | 1. Make note of the Jellyfin service user's details, specifically the UID and any groups (and GIDs) it is a member of; this will be needed later on.
14 |
15 | ```
16 | jellyfin1 $ id jellyfin
17 | uid=110(jellyfin) gid=117(jellyfin) groups=117(jellyfin)
18 | ```
19 |
20 | 1. Make note of the Jellyfin data path; this will be needed later on. By default when using native OS packages, this is `/var/lib/jellyfin`. If you choose to move this directory, do so now (I personally use `/srv/jellyfin` but this guide will assume the default).
21 |
22 | To make life easier below, you can store this in a variable that I will reference frequently later:
23 |
24 | ```
25 | jellyfin1 $ export jellyfin_data_path="/var/lib/jellyfin"
26 | jellyfin1 $ export jellyfin_cache_path="/var/lib/jellyfin"
27 | transcode1 $ export jellyfin_data_path="/var/lib/jellyfin"
28 | transcode1 $ export jellyfin_cache_path="/var/lib/jellyfin"
29 | ```
30 |
31 | The important subdirectories for `rffmpeg`'s operation are:
32 |
33 | * `$jellyfin_cache_path/`: Used to store cached extracted data.
34 | * `$jellyfin_cache_path/transcodes/`: Used to store on-the-fly transcoding files, and configurable separately in Jellyfin but with `rffmpeg` I recommend leaving it at the default location under the cache path.
35 | * `$jellyfin_data_path/data/subtitles/`: Used to store on-the-fly extracted subtitles so that they can be reused later.
36 | * `$jellyfin_data_path/.ssh/`: This doesn't exist yet but will after the next step.
37 |
38 | **NOTE:** On Docker, these directories are different. The main data directory (our `jellyfin_data_path`) is `/config`, and the cache directory is separate at `/cache`. Both must be exported and mounted on targets for proper operation.
39 |
40 | **NOTE:** On Jellyfin 10.10.x and newer, temporary transient files were moved into the system temporary storage path (on Linux, usually `/tmp`). This will break rffmpeg for certain tasks that use these files, for instance trickplay generation. To restore the previous behaviour, ensure you set the `TMPDIR` environment variable for your Jellyfin service to a path under the data path above, for example `/var/lib/jellyfin/temp`, and create this directory with correct ownership and permissions.
41 |
42 | 1. Create an SSH keypair to use for `rffmpeg`'s login to the remote server. For ease of use with the following steps, use the Jellyfin service user (`jellyfin`) to create the keypair and store it under its home directory (the Jellyfin data path above). I use `rsa` here but you can substitute `ed25519` instead (avoid `dsa` and `ecdsa` for reasons I won't get into here). Once done, copy the public key to `authorized_keys` which will be used to authenticate the key later.
43 |
44 | ```
45 | jellyfin1 $ sudo -u jellyfin mkdir ${jellyfin_data_path}/.ssh
46 | jellyfin1 $ sudo chmod 700 ${jellyfin_data_path}/.ssh
47 | jellyfin1 $ export keytype="rsa"
48 | jellyfin1 $ sudo -u jellyfin ssh-keygen -t ${keytype} -f ${jellyfin_data_path}/.ssh/id_${keytype}
49 | jellyfin1 $ sudo -u jellyfin cp -a ${jellyfin_data_path}/.ssh/id_${keytype}.pub ${jellyfin_data_path}/.ssh/authorized_keys
50 | ```
51 |
52 | It is important that you do not alter the permissions under this `.ssh` directory or this can cause SSH to fail later. The SSH *must* occur as the `jellyfin` user for this to work.
53 |
54 | 1. Scan and save the SSH host key of the transcode server(s), to avoid a prompt later:
55 |
56 | ```
57 | jellyfin1 $ ssh-keyscan transcode1 | sudo -u jellyfin tee -a ${jellyfin_data_path}/.ssh/known_hosts
58 | ```
59 |
60 | * **NOTE:** Ensure you use the exact name here that you will use in `rffmpeg`. If this is an FQDN (e.g. `jellyfin1.mydomain.tld`) or an IP (e.g. `192.168.0.101`) instead of a short name, use that instead in this command, or repeat it for every possible option (it doesn't hurt).
61 |
62 | ### `rffmpeg` Setup
63 |
64 | 1. Install the required Python3 dependencies of `rffmpeg`:
65 |
66 | ```
67 | jellyfin1 $ sudo apt -y install python3-yaml
68 | jellyfin1 $ sudo apt -y install python3-click
69 | jellyfin1 $ sudo apt -y install python3-subprocess
70 | ```
71 |
72 | * **NOTE:** On some Ubuntu versions, `python3-subprocess` does not exist, and should instead be part of the Python standard library. Skip installing this package if it can't be found.
73 |
74 | 1. Clone the `rffmpeg` repository somewhere onto the system, then install the `rffmpeg` binary, make it executable, and prepare symlinks for the command names `ffmpeg` and `ffprobe` to it. I recommend storing these in `/usr/local/bin` for simplicity and so that they are present on the default `$PATH` for most users.
75 |
76 | ```
77 | jellyfin1 $ git clone https://github.com/joshuaboniface/rffmpeg # or download the files manually
78 | jellyfin1 $ sudo cp rffmpeg/rffmpeg /usr/local/bin/rffmpeg
79 | jellyfin1 $ sudo chmod +x /usr/local/bin/rffmpeg
80 | jellyfin1 $ sudo ln -s /usr/local/bin/rffmpeg /usr/local/bin/ffmpeg
81 | jellyfin1 $ sudo ln -s /usr/local/bin/rffmpeg /usr/local/bin/ffprobe
82 | ```
83 |
84 | 1. Optional: Create a directory for the `rffmpeg` configuration at `/etc/rffmpeg`, then copy `rffmpeg.yml.sample` to `/etc/rffmpeg/rffmpeg.yml` and edit it to suit your needs if required. Generally, if you're following this guide exactly, you will not need to install this file or adjust anything in in it. If you do require help though, I require debug logging to be enabled via the configuration file, so it's probably best to get this out of the way when installing `rffmpeg`:
85 |
86 | ```
87 | jellyfin1 $ sudo mkdir -p /etc/rffmpeg
88 | jellyfin1 $ sudo cp rffmpeg/rffmpeg.yml.sample /etc/rffmpeg/rffmpeg.yml
89 | jellyfin1 $ sudo $EDITOR /etc/rffmpeg/rffmpeg.yml # if required
90 | ```
91 |
92 | 1. Initialize `rffmpeg` (note the `sudo` command) and add at the target host to it. You can add other hosts now or later, and set weights of hosts, if required; for full details see the [main README](README.md) or run `rffmpeg --help` to view the CLI help menu.
93 |
94 | ```
95 | jellyfin1 $ sudo rffmpeg init --yes
96 | jellyfin1 $ rffmpeg add --weight 1 transcode1
97 | ```
98 |
99 | ### NFS Setup
100 |
101 | * **WARNING:** This guide assumes your hosts are on the same private local network. It is not recommended to run NFS over the Internet as it is unencrypted, and any rffmpeg connection will be very bandwidth-intensive. If you must have both systems in separate networks, consider other remote filesystems like SSHFS in such cases as these will offer greater privacy and robustness.
102 |
103 | 1. Install the NFS kernel server. We will use NFS to export the various required directories so the transcode machine can read from and write to them.
104 |
105 | ```
106 | jellyfin1 $ sudo apt -y install nfs-kernel-server
107 | ```
108 |
109 | 1. Create an `/etc/exports` configuration. What to put here can vary a lot, but here are some important points:
110 |
111 | * Always export the `${jellyfin_data_path}` in full. Advanced users might be able to export the required subdirectories individually, but I find this to be not worth the hassle.
112 | * Note the security options of NFS. It will limit mounts to the IP addresses specified. If your home network is secure, you can use the entire network, e.g. `192.168.0.0/24`, but I would recommend determining the exact IP of your transcode server(s) and use them explicitly, e.g. for this example `192.168.0.101` and `192.168.0.102`.
113 | * If your `transcodes` directory is not on a **native Linux filesystem** (i.e. external to Jellyfin, such as on a NAS exported by NFS, SMB, etc.), then you may experience delays of ~15-60s when playback starts. This is because NFS uses a file attribute cache that in most applications greatly increases performance, however for this usecase it causes a delay in Jellyfin seeing the `.ts` files. The solution for this is to reduce the NFS cache time by adding `sync` and `actimeo=1` to your NFS mount(s) (command or fstab), which will set the NFS file attribute cache to 1 second (reducing the NFS delay to ~1-2 seconds). This time can be further reduced to 0 by setting the `noac` option, but this is not normally recommended because it will negatively impact the performance other NFS applications. Verify that your mount added the `actimeo=1` parameter correctly by checking `mount` or `cat /proc/mounts`, which will show `sync,acregmin=1,acregmax=1,acdirmin=1,acdirmax=1` as parameters for your `transcodes` mount.
114 | * If your media is local to the Jellyfin server (and not already mountable on the transcode host(s) via a remote filesystems like NFS, Samba, CephFS, etc.), also add an export for it as well.
115 |
116 | An example `/etc/exports` file would look like this:
117 |
118 | ```
119 | # /etc/exports: the access control list for filesystems which may be exported
120 | # to NFS clients. See exports(5).
121 | #
122 | # Other examples removed
123 |
124 | # jellyfin_data_path first host second host, etc.
125 | /var/lib/jellyfin 192.168.0.101/32(rw,sync,no_subtree_check,no_root_squash) 192.168.0.102/32(rw,sync,no_subtree_check,no_root_squash)
126 | # jellyfin_cache_path first host second host, etc.
127 | /var/cache/jellyfin 192.168.0.101/32(rw,sync,no_subtree_check,no_root_squash) 192.168.0.102/32(rw,sync,no_subtree_check,no_root_squash)
128 | # Local media path if required
129 | /srv/mymedia 192.168.0.101/32(rw,sync,no_subtree_check,no_root_squash) 192.168.0.102/32(rw,sync,no_subtree_check,no_root_squash)
130 | ```
131 |
132 | 1. Reload the exports file and ensure the NFS server is properly exporting it now:
133 |
134 | ```
135 | jellyfin1 $ sudo exportfs -arfv
136 | jellyfin1 $ sudo exportfs
137 | /var/lib/jellyfin 192.168.0.101/32
138 | /var/lib/jellyfin 192.168.0.102/32
139 | /var/cache/jellyfin 192.168.0.101/32
140 | /var/cache/jellyfin 192.168.0.102/32
141 | ```
142 |
143 | ## Set up the transcode server (`transcode1`)
144 |
145 | 1. Install and configure anything you need for hardware transcoding, if applicable. For example GPU drivers if using a GPU for transcoding.
146 |
147 | * **NOTE:** Make sure you understand the caveats of using hardware transcoding with `rffmpeg` from [the main README](README.md#hardware-acceleration).
148 |
149 | 1. Install the correct `jellyfin-ffmpeg` package for your version of Jellyfin; check which version is installed on your `jellyfin1` system with `dpkg -l | grep jellyfin-ffmpeg`, then install that version on this host too; follow the same steps as you would to install Jellyfin on the media server, only don't install `jellyfin` (and `jellyfin-server`/`jellyfin-web`) itself, just the `jellyfin-ffmpeg` of the required version.
150 |
151 | ```
152 | jellyfin1 $ dpkg -l | grep jellyfin-ffmpeg
153 | ii jellyfin-ffmpeg6 6.0.1-8-bookworm amd64 Tools for transcoding, streaming and playing of multimedia files
154 | transcode1 $ sudo apt -y install curl gnupg
155 | transcode1 $ curl -fsSL https://repo.jellyfin.org/ubuntu/jellyfin_team.gpg.key | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/jellyfin.gpg
156 | transcode1 $ echo "deb [arch=$( dpkg --print-architecture )] https://repo.jellyfin.org/$( awk -F'=' '/^ID=/{ print $NF }' /etc/os-release ) $( awk -F'=' '/^VERSION_CODENAME=/{ print $NF }' /etc/os-release ) main" | sudo tee /etc/apt/sources.list.d/jellyfin.list
157 | transcode1 $ sudo apt update
158 | transcode1 $ sudo apt install jellyfin-ffmpeg6
159 | ```
160 |
161 | 1. Install the NFS client utilities:
162 |
163 | ```
164 | transcode1 $ sudo apt install -y nfs-common
165 | ```
166 |
167 | 1. Create the Jellyfin service user and its default group; ensure you use the exact same UID and GID values you found in the beginning of the last section and adjust the example here to match yours:
168 |
169 | ```
170 | transcode1 $ sudo groupadd --gid 117 jellyfin
171 | transcode1 $ sudo useradd --uid 110 --gid jellyfin --shell /bin/bash --no-create-home --home-dir ${jellyfin_data_path} jellyfin
172 | ```
173 |
174 | * **NOTE:** For some hardware acceleration, you might need to add this user to additional groups. For example `--groups video,render`.
175 |
176 | * **NOTE:** The UID and GIDs here are dynamic; on the `jellyfin1` machine, they would have been selected automatically at install time with the next available ID in the range 100-199 (at least in Debian/Ubuntu). However, this means that the exact UID of your Jellyfin service user might not be available on your transcode server, depending on what packages are installed and in what order. If there is a conflict, you must adjust user IDs on one side or the other so that they match on both machines. You can use `sudo usermod` to change a user's ID if required.
177 |
178 | 1. Create the Jellyfin data directory at the same location as on the media server, and set it immutable so that it won't be written to if the NFS mount goes down:
179 |
180 | ```
181 | transcode1 $ sudo mkdir ${jellyfin_data_path}
182 | transcode1 $ sudo chattr +i ${jellyfin_data_path}
183 | ```
184 |
185 | * **NOTE:** Don't worry about permissions here; the mount will set those.
186 |
187 | 1. Create the NFS client mount. There are two main ways to do this:
188 |
189 | * Use the traditional `/etc/fstab` by adding a new entry like so, replacing the paths and hostname as required, and then mounting it:
190 |
191 | ```
192 | transcode1 $ echo "jellyfin1:${jellyfin_data_path} ${jellyfin_data_path} nfs defaults,vers=3,sync" | sudo tee -a /etc/fstab
193 | transcode1 $ echo "jellyfin1:${jellyfin_cache_path} ${jellyfin_cache_path} nfs defaults,vers=3,sync" | sudo tee -a /etc/fstab
194 | transcode1 $ sudo mount ${jellyfin_data_path}
195 | transcode1 $ sudo mount ${jellyfin_cache_path}
196 | ```
197 |
198 | * Use a SystemD `mount` unit, which is a newer way of doing mounts with SystemD. I personally prefer this method as I find it easier to set up automatically, but this is up to preference. An example based on mine would be:
199 |
200 | ```
201 | transcode1 $ cat /etc/systemd/system/var-lib-jellyfin.mount
202 | [Unit]
203 | Description = NFS volume for Jellyfin data directory
204 | Requires = network-online.target
205 | After = network-online.target
206 |
207 | [Mount]
208 | type = nfs
209 | What = jellyfin1:/var/lib/jellyfin
210 | Where = /var/lib/jellyfin
211 | Options = _netdev,sync,vers=3
212 |
213 | [Install]
214 | WantedBy = remote-fs.target
215 | ```
216 |
217 | ```
218 | transcode1 $ cat /etc/systemd/system/var-cache-jellyfin.mount
219 | [Unit]
220 | Description = NFS volume for Jellyfin cache directory
221 | Requires = network-online.target
222 | After = network-online.target
223 |
224 | [Mount]
225 | type = nfs
226 | What = jellyfin1:/var/cache/jellyfin
227 | Where = /var/cache/jellyfin
228 | Options = _netdev,sync,vers=3
229 |
230 | [Install]
231 | WantedBy = remote-fs.target
232 | ```
233 |
234 | Once the unit file is created, you can then reload the unit list and mount it:
235 |
236 | ```
237 | transcode1 $ sudo systemctl daemon-reload
238 | transcode1 $ sudo systemctl enable --now var-lib-jellyfin.mount
239 | transcode1 $ sudo systemctl enable --now var-cache-jellyfin.mount
240 | ```
241 |
242 | Note that mount units are fairly "new" and can be a bit finicky, be sure to read the SystemD documentation if you get stuck! Generally for new users, I'd recommend the `/etc/fstab` method instead.
243 |
244 | **NOTE:** Don't forget about `actimeo=1` here if you need it!
245 |
246 | 1. Mount your media directories in the **same location(s)** as on the media server. If you exported them via NFS from your media server, use the process above only for those directories instead.
247 |
248 | ## Test the setup
249 |
250 | 1. On the media server, verify that SSH as the Jellyfin service user is working as expected to each transcoding server:
251 |
252 | ```
253 | jellyfin1 $ sudo -u jellyfin ssh -i ${jellyfin_data_path}/.ssh/id_rsa jellyfin@transcode1 uname -a
254 | Linux transcode1 [...]
255 | ```
256 |
257 | 1. Validate that `rffmpeg` itself is working by calling its `ffmpeg` and `ffprobe` aliases with the `-version` option:
258 |
259 | ```
260 | jellyfin1 $ sudo -u jellyfin /usr/local/bin/ffmpeg -version
261 | ffmpeg version 5.0.1-Jellyfin Copyright (c) 2000-2022 the FFmpeg developers
262 | built with gcc 10 (Debian 10.2.1-6)
263 | [...]
264 | jellyfin1 $ sudo -u jellyfin /usr/local/bin/ffprobe -version
265 | ffprobe version 5.0.1-Jellyfin Copyright (c) 2007-2022 the FFmpeg developers
266 | built with gcc 10 (Debian 10.2.1-6)
267 | [...]
268 | ```
269 |
270 | As long as these steps work, all further steps should as well. If one of these *doesn't* work, double-check all previous steps and confirm that everything is set up right.
271 |
272 | ## Configure Jellyfin to use `rffmpeg`
273 |
274 | **NOTE**: With Jellyfin 10.8.13 and newer, the ability to configure the `ffmpeg` path has been removed from the WebUI due to major security concerns. You must follow this method to change it.
275 |
276 | 1. On the `jellyfin1` system, edit `/etc/default/jellyfin`:
277 |
278 | ```
279 | jellyfin1 $ sudo $EDITOR /etc/default/jellyfin
280 | ```
281 |
282 | 1. Change the value of `JELLYFIN_FFMPEG_OPT` to be `--ffmpeg=/usr/local/bin/ffmpeg` (the `rffmpeg` alias name `ffmpeg` in whatever path you installed `rffmpeg` to).
283 |
284 | 1. On Jellyfin 10.10.x or newer, add `TMPDIR=$jellyfin_cache_path/temp`, for instance `TMPDIR=/var/cache/jellyfin/temp`, to ensure this is properly synchronized over the network.
285 |
286 | 1. Save the file and restart Jellyfin:
287 |
288 | ```
289 | jellyfin1 $ sudo systemctl restart jellyfin
290 | ```
291 |
292 | If you wish to use hardware transcoding, you must also enable it in Jellyfin's WebUI:
293 |
294 | 1. Navigate to Hamburger Menu -> Administration -> Dashboard, navigate to Playback.
295 |
296 | 1. Configure any hardware acceleration you require and have set up on the remote server(s).
297 |
298 | 1. Save the settings.
299 |
300 | Now, run `rffmpeg log -f` on the `jellyfin1` machine and try to play a video that requires transcoding. You should see `rffmpeg` spawn a process on the `jellyfin1` machine, which then begins running the `ffmpeg` process on the `transcode1` machine, writing data to the configured paths, and playback should begin normally. If anything doesn't work, double-check all previous steps and confirm that everything is set up right.
301 |
302 | ## NOTE for NVEnv/NVDec Hardware Acceleration
303 |
304 | If you are using NVEnv/NVDec, you will need to symlink the `.nv` folder inside the Jellyfin user's homedir (i.e. `/var/lib/jellyfin/.nv`) to somewhere outside of the NFS volume on both the Jellyfin and transcoding hosts. For example:
305 |
306 | ```
307 | jellyfin1 $ sudo mv /var/lib/jellyfin/.nv /var/lib/nvidia-cache # or "sudo mkdir /var/lib/nvidia-cache" and "sudo chown jellyfin /var/lib/nvidia-cache" if it does not yet exist
308 | jellyfin1 $ sudo ln -s /var/lib/nvidia-cache /var/lib/jellyfin/.nv
309 | transcode1 $ sudo mkdir /var/lib/nvidia-cache
310 | transcode1 $ sudo chown jellyfin /var/lib/nvidia-cache
311 | transcode1 $ ls -alh /var/lib/jellyfin
312 | [...]
313 | lrwxrwxrwx 1 root root 17 Jun 11 15:51 .nv -> /var/lib/nvidia-cache
314 | [...]
315 | ```
316 |
317 | Be sure to adjust these paths to match your Jellyfin setup. The name of the target doesn't matter too much, as long as `.nv` inside the homedir is symlinked to it and it is owned by the `jellyfin` service user.
318 |
319 | This is because some functions of FFMpeg's NVEnc/NVDec stack - specifically the `scale_cuda` and `tonemap_cuda` filters - leverage this directory to cache their JIT codes, and this can result in very slow startup times and very poor transcoding performance due to NFS locking issues. See https://developer.nvidia.com/blog/cuda-pro-tip-understand-fat-binaries-jit-caching/ for further information.
320 |
321 | Alternatively, based on that link, you might also be able to experiment with the environment variables that control the JIT caching to move it somewhere else, but this has not been tested by the author. Feel free to experiment and find the best solution for your setup.
322 |
--------------------------------------------------------------------------------
/rffmpeg:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | # rffmpeg.py - Remote FFMPEG transcoding wrapper
4 | #
5 | # Copyright (C) 2019-2022 Joshua M. Boniface
6 | # and Contributors.
7 | #
8 | # This program is free software: you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation, either version 3 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 | #
21 | ###############################################################################
22 |
23 | import click
24 | import logging
25 | import os
26 | import signal
27 | import sys
28 | import shlex
29 | import yaml
30 |
31 | from contextlib import contextmanager
32 | from grp import getgrnam
33 | from pathlib import Path
34 | from pwd import getpwnam
35 | from re import search
36 | from sqlite3 import connect as sqlite_connect
37 | from subprocess import run, PIPE
38 | from time import sleep
39 | from datetime import datetime
40 |
41 |
42 | # Set up the logger
43 | log = logging.getLogger("rffmpeg")
44 |
45 |
46 | # Use Postgresql if specified, otherwise use SQLite
47 | DB_TYPE = "SQLITE"
48 | SQL_VAR_SIGN = "?"
49 | SQL_PRIMARY_KEY="INTEGER"
50 | SQL_DATE_TIME="DATETIME"
51 | POSTGRES_DB = os.environ.get("RFFMPEG_POSTGRES_DB", "rffmpeg")
52 | POSTGRES_USER = os.environ.get("RFFMPEG_POSTGRES_USER")
53 | POSTGRES_PASS = os.environ.get("RFFMPEG_POSTGRES_PASS", "")
54 | POSTGRES_PORT = os.environ.get("RFFMPEG_POSTGRES_PORT", "5432")
55 | POSTGRES_HOST = os.environ.get("RFFMPEG_POSTGRES_HOST", "localhost")
56 |
57 | if POSTGRES_USER != None:
58 | DB_TYPE = "POSTGRES"
59 | SQL_VAR_SIGN = "%s"
60 | SQL_PRIMARY_KEY="SERIAL"
61 | SQL_DATE_TIME="TIMESTAMP"
62 | POSTGRES_CREDENTIALS = {
63 | "dbname": POSTGRES_DB,
64 | "user": POSTGRES_USER,
65 | "password": POSTGRES_PASS,
66 | "port": int(POSTGRES_PORT),
67 | "host": POSTGRES_HOST,
68 | }
69 | from psycopg2 import connect as postgres_connect
70 | from psycopg2 import DatabaseError as postgres_error
71 |
72 |
73 | # Open a database connection (context manager)
74 | @contextmanager
75 | def dbconn(config, init = False):
76 | """
77 | Open a database connection.
78 | """
79 | if DB_TYPE == "SQLITE":
80 | if not init and not Path(config["db_path"]).is_file():
81 | fail(f"Failed to find database '{config['db_path']}' - did you forget to run 'rffmpeg init' or add all env vars for Postgresql?")
82 | log.debug("Using SQLite as database.")
83 | conn = sqlite_connect(config["db_path"])
84 | conn.execute("PRAGMA foreign_keys = 1")
85 | cur = conn.cursor()
86 | yield cur
87 | conn.commit()
88 | conn.close()
89 | log.debug("SQLite connection closed.")
90 | elif DB_TYPE == "POSTGRES":
91 | conn = None
92 | try:
93 | log.debug("Using Postgresql as database. Connecting...")
94 | conn = postgres_connect(**POSTGRES_CREDENTIALS)
95 | cur = conn.cursor()
96 | cur.execute("SELECT version()")
97 | db_version = cur.fetchone()
98 | log.debug(f"Connected to Postgresql version {db_version}")
99 | yield cur
100 | conn.commit()
101 | except (Exception, postgres_error) as error:
102 | print(error)
103 | log.error(error)
104 | finally:
105 | if conn is not None:
106 | conn.close()
107 | log.debug("Postgresql connection closed.")
108 |
109 |
110 | def fail(msg):
111 | """
112 | Output an error message and terminate.
113 | """
114 | log.error(msg)
115 | exit(1)
116 |
117 |
118 | def load_config():
119 | """
120 | Parse the YAML configuration file (either /etc/rffmpeg/rffmpeg.yml or specified by the envvar
121 | RFFMPEG_CONFIG) and return a standard dictionary of configuration values.
122 | """
123 |
124 | default_config_file = "/etc/rffmpeg/rffmpeg.yml"
125 | config_file = os.environ.get("RFFMPEG_CONFIG", default_config_file)
126 |
127 | if not Path(config_file).is_file():
128 | log.info(f"No config found in {config_file}. Using default settings.")
129 | o_config = {
130 | "rffmpeg": {"logging": {}, "directories": {}, "remote": {}, "commands": {}}
131 | }
132 | else:
133 | with open(config_file, "r") as cfgfh:
134 | try:
135 | o_config = yaml.load(cfgfh, Loader=yaml.SafeLoader)
136 | except Exception as e:
137 | fail(f"Failed to parse configuration file: {e}")
138 |
139 | config = dict()
140 |
141 | # Parse the base group ("rffmpeg")
142 | config_base = o_config.get("rffmpeg", dict())
143 | if not config_base:
144 | fail("Failed to parse configuration file top level key 'rffmpeg'.")
145 |
146 | # Parse the logging group ("rffmpeg" -> "logging")
147 | config_logging = config_base.get("logging", dict())
148 | if config_logging is None:
149 | config_logging = dict()
150 |
151 | # Parse the directories group ("rffmpeg" -> "directories")
152 | config_directories = config_base.get("directories", dict())
153 | if config_directories is None:
154 | config_directories = dict()
155 |
156 | # Parse the remote group ("rffmpeg" -> "remote")
157 | config_remote = config_base.get("remote", dict())
158 | if config_remote is None:
159 | config_remote = dict()
160 |
161 | # Parse the commands group ("rffmpeg" -> "commands")
162 | config_commands = config_base.get("commands", dict())
163 | if config_commands is None:
164 | config_commands = dict()
165 |
166 | # Parse the keys from the logging group
167 | config["log_to_file"] = config_logging.get("log_to_file", True)
168 | config["logfile"] = config_logging.get("logfile", "/var/log/jellyfin/rffmpeg.log")
169 | config["datedlogfiles"] = config_logging.get("datedlogfiles", False)
170 | if config["datedlogfiles"] is True:
171 | config["datedlogdir"] = config_logging.get("datedlogdir", "/var/log/jellyfin")
172 | config["logfile"] = (
173 | config["datedlogdir"]
174 | + "/"
175 | + datetime.today().strftime("%Y%m%d")
176 | + "_rffmpeg.log"
177 | )
178 | config["logdebug"] = config_logging.get("debug", False)
179 |
180 | # Parse the keys from the state group
181 | config["state_dir"] = config_directories.get("state", "/var/lib/rffmpeg")
182 | config["persist_dir"] = config_directories.get("persist", "/run/shm")
183 | config["dir_owner"] = config_directories.get("owner", "jellyfin")
184 | config["dir_group"] = config_directories.get("group", "sudo")
185 |
186 | # Parse the keys from the remote group
187 | config["remote_user"] = config_remote.get("user", "")
188 | config["remote_args"] = config_remote.get(
189 | "args", ["-i", "/var/lib/jellyfin/.ssh/id_rsa"]
190 | )
191 | if config["remote_args"] is None:
192 | config["remote_args"] = []
193 | config["persist_time"] = config_remote.get("persist", 300)
194 |
195 | # Parse the keys from the commands group
196 | config["ssh_command"] = config_commands.get("ssh", "/usr/bin/ssh")
197 | config["pre_commands"] = config_commands.get("pre", [])
198 | if config["pre_commands"] is None:
199 | config["pre_commands"] = []
200 | config["ffmpeg_command"] = config_commands.get(
201 | "ffmpeg", "/usr/lib/jellyfin-ffmpeg/ffmpeg"
202 | )
203 | config["ffprobe_command"] = config_commands.get(
204 | "ffprobe", "/usr/lib/jellyfin-ffmpeg/ffprobe"
205 | )
206 | config["fallback_ffmpeg_command"] = config_commands.get(
207 | "fallback_ffmpeg", "/usr/lib/jellyfin-ffmpeg/ffmpeg"
208 | )
209 | config["fallback_ffprobe_command"] = config_commands.get(
210 | "fallback_ffprobe", "/usr/lib/jellyfin-ffmpeg/ffprobe"
211 | )
212 |
213 | # Set the database path
214 | config["db_path"] = config["state_dir"] + "/rffmpeg.db"
215 |
216 |
217 | # Set a list of special flags that cause different behaviour
218 | config["special_flags"] = [
219 | "-version",
220 | "-encoders",
221 | "-decoders",
222 | "-hwaccels",
223 | "-filters",
224 | "-h",
225 | "-muxers",
226 | "-fp_format",
227 | ] + config_commands.get("special_flags", [])
228 |
229 | # Set the current PID of this process
230 | config["current_pid"] = os.getpid()
231 |
232 | return config
233 |
234 |
235 | def cleanup(signum="", frame=""):
236 | """
237 | Clean up this processes stored transient data.
238 | """
239 | global config
240 |
241 | log.debug(f"Cleaning up after signal {signum} PID {config['current_pid']}")
242 |
243 | with dbconn(config) as cur:
244 | cur.execute(
245 | f"DELETE FROM states WHERE process_id = {SQL_VAR_SIGN}",
246 | (config["current_pid"],),
247 | )
248 | cur.execute(
249 | f"DELETE FROM processes WHERE process_id = {SQL_VAR_SIGN}",
250 | (config["current_pid"],),
251 | )
252 |
253 |
254 | def generate_ssh_command(config, target_hostname):
255 | """
256 | Generate an SSH command for use.
257 | """
258 | ssh_command = list()
259 |
260 | # Add SSH component
261 | ssh_command.append(config["ssh_command"])
262 | ssh_command.append("-q")
263 | ssh_command.append("-t")
264 |
265 | # Set our connection details
266 | ssh_command.extend(["-o", "ConnectTimeout=1"])
267 | ssh_command.extend(["-o", "ConnectionAttempts=1"])
268 | ssh_command.extend(["-o", "StrictHostKeyChecking=no"])
269 | ssh_command.extend(["-o", "UserKnownHostsFile=/dev/null"])
270 |
271 | # Use SSH control persistence to keep sessions alive for subsequent commands
272 | if config["persist_time"] > 0:
273 | ssh_command.extend(["-o", "ControlMaster=auto"])
274 | ssh_command.extend(
275 | ["-o", f"ControlPath={config['persist_dir']}/ssh-%r@%h:%p"]
276 | )
277 | ssh_command.extend(["-o", f"ControlPersist={config['persist_time']}"])
278 |
279 | # Add the remote config args
280 | for arg in config["remote_args"]:
281 | if arg:
282 | ssh_command.append(arg)
283 |
284 | # Add user+host string
285 | ssh_command.append(f"{config['remote_user']}@{target_hostname}")
286 |
287 | return ssh_command
288 |
289 |
290 | def run_command(command, stdin, stdout, stderr):
291 | """
292 | Execute the command using subprocess.
293 | """
294 | p = run(
295 | command,
296 | shell=False,
297 | bufsize=0,
298 | universal_newlines=True,
299 | stdin=stdin,
300 | stdout=stdout,
301 | stderr=stderr,
302 | )
303 | return p
304 |
305 |
306 | def get_target_host(config):
307 | """
308 | Determine an optimal target host via data on currently active processes and states.
309 | """
310 | log.debug("Determining optimal target host")
311 | # Select all hosts and active processes from the database
312 | with dbconn(config) as cur:
313 | cur.execute("SELECT * FROM hosts")
314 | hosts = cur.fetchall()
315 | cur.execute("SELECT * FROM processes")
316 | processes = cur.fetchall()
317 |
318 | # Generate a mapping dictionary of hosts and processes
319 | host_mappings = dict()
320 | for host in hosts:
321 | hid, servername, hostname, weight, created = host
322 |
323 | # Get the latest state
324 | with dbconn(config) as cur:
325 | cur.execute(
326 | f"SELECT * FROM states WHERE host_id = {SQL_VAR_SIGN} ORDER BY id DESC",
327 | (hid,),
328 | )
329 | current_state = cur.fetchone()
330 |
331 | if not current_state:
332 | current_state = "idle"
333 | marking_pid = "N/A"
334 | else:
335 | sid, host_id, process_id, state = current_state
336 | current_state = state
337 | marking_pid = process_id
338 |
339 | # Create the mappings entry
340 | host_mappings[hid] = {
341 | "hostname": hostname,
342 | "weight": weight,
343 | "servername": servername,
344 | "current_state": current_state,
345 | "marking_pid": marking_pid,
346 | "commands": [proc[2] for proc in processes if proc[1] == hid],
347 | }
348 |
349 | lowest_count = 9999
350 | target_hid = None
351 | target_hostname = None
352 | target_servername = None
353 | # For each host in the mapping, let's determine if it is suitable
354 | for hid, host in host_mappings.items():
355 | log.debug(f"Trying host ID {hid} '{host['hostname']}'")
356 | # If it's marked as bad, continue
357 | if host["current_state"] == "bad":
358 | log.debug(f"Host previously marked bad by PID {host['marking_pid']}")
359 | continue
360 |
361 | # Try to connect to the host and run a very quick command to determine if it is workable
362 | if host["hostname"] not in ["localhost", "127.0.0.1"]:
363 | log.debug("Running SSH test")
364 | test_ssh_command = generate_ssh_command(config, host["hostname"])
365 | test_ssh_command.remove("-q")
366 | test_ssh_command = [arg.replace('@', '', 1) if arg.startswith('@') else arg for arg in test_ssh_command]
367 | test_ffmpeg_command = [config["ffmpeg_command"], "-version"]
368 | ret = run_command(test_ssh_command + test_ffmpeg_command, PIPE, PIPE, PIPE)
369 | if ret.returncode != 0:
370 | # Mark the host as bad
371 | log.warning(f"Marking host {host['hostname']} ({host['servername']}) as bad due to retcode {ret.returncode}")
372 | log.debug(f"SSH test command was: {' '.join(test_ssh_command + test_ffmpeg_command)}")
373 | log.debug(f"SSH test command stdout: {ret.stdout}")
374 | log.debug(f"SSH test command stderr: {ret.stderr}")
375 | with dbconn(config) as cur:
376 | cur.execute(
377 | f"INSERT INTO states (host_id, process_id, state) VALUES ({SQL_VAR_SIGN}, {SQL_VAR_SIGN}, {SQL_VAR_SIGN})",
378 | (hid, config["current_pid"], "bad"),
379 | )
380 | continue
381 | log.debug(f"SSH test succeeded with retcode {ret.returncode}")
382 |
383 | # If the host state is idle, we can use it immediately
384 | if host["current_state"] == "idle":
385 | target_hid = hid
386 | target_hostname = host["hostname"]
387 | target_servername = host["servername"]
388 | log.debug("Selecting host as idle")
389 | break
390 |
391 | # Get the modified count of the host
392 | raw_proc_count = len(host["commands"])
393 | weighted_proc_count = raw_proc_count // host["weight"]
394 |
395 | # If this host is currently the least used, provisionally set it as the target
396 | if weighted_proc_count < lowest_count:
397 | lowest_count = weighted_proc_count
398 | target_hid = hid
399 | target_hostname = host["hostname"]
400 | target_servername = host["servername"]
401 | log.debug(f"Selecting host as current lowest proc count (raw count: {raw_proc_count}, weighted count: {weighted_proc_count})")
402 |
403 | log.debug(f"Found optimal host ID {target_hid} '{target_hostname}' ({target_servername})")
404 | return target_hid, target_hostname, target_servername
405 |
406 |
407 | def run_local_command(config, target_hid, command, command_args, stderr_as_stdout = False, mapped_cmd = None):
408 | """
409 | Run command locally, either because "localhost" is the target host, or because no good target
410 | host was found by get_target_host().
411 | """
412 | rffmpeg_command = [mapped_cmd or command]
413 |
414 | # Prepare our default stdin/stdout/stderr
415 | stdin = sys.stdin
416 | stderr = sys.stderr
417 |
418 | if stderr_as_stdout:
419 | stdout = sys.stderr
420 | else:
421 | stdout = sys.stdout
422 |
423 | # Append all the passed arguments directly
424 | for arg in command_args:
425 | rffmpeg_command.append(f"{arg}")
426 |
427 | log.info("Running command on host 'localhost'")
428 | log.debug(f"Local command: {' '.join(rffmpeg_command)}")
429 |
430 | if target_hid is None:
431 | target_hid = 0
432 | log.debug(f"Could not find any host, using fallback 'localhost'")
433 |
434 | with dbconn(config) as cur:
435 | cur.execute(
436 | f"INSERT INTO processes (host_id, process_id, cmd) VALUES ({SQL_VAR_SIGN}, {SQL_VAR_SIGN}, {SQL_VAR_SIGN})",
437 | (target_hid, config["current_pid"], command + ' ' + ' '.join(command_args)),
438 | )
439 | cur.execute(
440 | f"INSERT INTO states (host_id, process_id, state) VALUES ({SQL_VAR_SIGN}, {SQL_VAR_SIGN}, {SQL_VAR_SIGN})",
441 | (target_hid, config["current_pid"], "active"),
442 | )
443 |
444 | return run_command(rffmpeg_command, stdin, stdout, stderr)
445 |
446 |
447 | def run_local_ffmpeg(config, target_hid, ffmpeg_args):
448 | """
449 | Run ffmpeg locally, either because "localhost" is the target host, or because no good target
450 | host was found by get_target_host().
451 | """
452 | if "ffprobe" in cmd_name:
453 | return run_local_command(config, target_hid, cmd_name, ffmpeg_args, mapped_cmd=config["fallback_ffprobe_command"])
454 | else:
455 | return run_local_command(config, target_hid, cmd_name, ffmpeg_args, stderr_as_stdout=not any(item in config["special_flags"] for item in ffmpeg_args), mapped_cmd=config["fallback_ffmpeg_command"])
456 |
457 |
458 | def run_remote_command(
459 | config, target_hid, target_hostname, target_servername, command, command_args, stderr_as_stdout = False, mapped_cmd = None, pre_commands = []
460 | ):
461 | """
462 | Run command against the remote target_hostname.
463 | """
464 | rffmpeg_ssh_command = generate_ssh_command(config, target_hostname)
465 | rffmpeg_ssh_command = [arg.replace('@', '', 1) if arg.startswith('@') else arg for arg in rffmpeg_ssh_command]
466 |
467 | rffmpeg_command = list()
468 |
469 | # Add any pre commands
470 | for cmd in pre_commands:
471 | if cmd:
472 | rffmpeg_command.append(cmd)
473 |
474 | rffmpeg_command.append(mapped_cmd or command)
475 |
476 | # Prepare our default stdin/stderr
477 | stdin = sys.stdin
478 | stderr = sys.stderr
479 |
480 | if stderr_as_stdout:
481 | stdout = sys.stderr
482 | else:
483 | stdout = sys.stdout
484 |
485 | rffmpeg_command.extend(map(shlex.quote, command_args))
486 |
487 | log.info(f"Running command on host '{target_hostname}' ({target_servername})")
488 | log.debug(f"Remote command: {' '.join(rffmpeg_ssh_command + rffmpeg_command)}")
489 |
490 | with dbconn(config) as cur:
491 | cur.execute(
492 | f"INSERT INTO processes (host_id, process_id, cmd) VALUES ({SQL_VAR_SIGN}, {SQL_VAR_SIGN}, {SQL_VAR_SIGN})",
493 | (target_hid, config["current_pid"], command + ' ' + ' '.join(command_args)),
494 | )
495 | cur.execute(
496 | f"INSERT INTO states (host_id, process_id, state) VALUES ({SQL_VAR_SIGN}, {SQL_VAR_SIGN}, {SQL_VAR_SIGN})",
497 | (target_hid, config["current_pid"], "active"),
498 | )
499 |
500 | return run_command(
501 | rffmpeg_ssh_command + rffmpeg_command, stdin, stdout, stderr
502 | )
503 |
504 |
505 | def run_remote_ffmpeg(
506 | config, target_hid, target_hostname, target_servername, ffmpeg_args
507 | ):
508 | """
509 | Run ffmpeg against the remote target_hostname.
510 | """
511 | if "ffprobe" in cmd_name:
512 | # If we're in ffprobe mode use that command and sys.stdout as stdout
513 | return run_remote_command(config, target_hid, target_hostname, target_servername, cmd_name, ffmpeg_args, mapped_cmd=config["ffprobe_command"], pre_commands=config["pre_commands"])
514 | else:
515 | # Otherwise, we use stderr as stdout
516 | return run_remote_command(config, target_hid, target_hostname, target_servername, cmd_name, ffmpeg_args, stderr_as_stdout=not any(item in config["special_flags"] for item in ffmpeg_args), mapped_cmd=config["ffmpeg_command"], pre_commands=config["pre_commands"])
517 |
518 |
519 | def setup_logging(config):
520 | """
521 | Set up logging.
522 | """
523 | if config["logdebug"] is True:
524 | logging_level = logging.DEBUG
525 | else:
526 | logging_level = logging.INFO
527 |
528 | if config["log_to_file"]:
529 | logging.basicConfig(
530 | filename=config["logfile"],
531 | level=logging_level,
532 | format="%(asctime)s - %(name)s[%(process)s] - %(levelname)s - %(message)s",
533 | )
534 | else:
535 | logging.basicConfig(
536 | level=logging_level,
537 | format="%(asctime)s - %(name)s[%(process)s] - %(levelname)s - %(message)s",
538 | )
539 |
540 |
541 | def hook_signals():
542 | signal.signal(signal.SIGTERM, cleanup)
543 | signal.signal(signal.SIGINT, cleanup)
544 | signal.signal(signal.SIGQUIT, cleanup)
545 | signal.signal(signal.SIGHUP, cleanup)
546 |
547 |
548 | def run_ffmpeg(config, ffmpeg_args):
549 | """
550 | Entrypoint for an ffmpeg/ffprobe aliased process.
551 | """
552 | hook_signals()
553 |
554 | setup_logging(config)
555 |
556 | log.info(f"Starting rffmpeg as {cmd_name} with args: {' '.join(ffmpeg_args)}")
557 |
558 | target_hid, target_hostname, target_servername = get_target_host(config)
559 |
560 | try:
561 | returncode = 200
562 | if not target_hostname or target_hostname == "localhost":
563 | ret = run_local_ffmpeg(config, None, ffmpeg_args)
564 | returncode = ret.returncode
565 | else:
566 | ret = run_remote_ffmpeg(
567 | config, target_hid, target_hostname, target_servername, ffmpeg_args
568 | )
569 | returncode = ret.returncode
570 | finally:
571 | cleanup()
572 | if returncode == 0:
573 | log.info(f"Finished rffmpeg with return code {ret.returncode}")
574 | else:
575 | log.error(f"Finished rffmpeg with return code {ret.returncode}")
576 | exit(returncode)
577 |
578 |
579 | def run_control(config):
580 | """
581 | Entrypoint for the Click CLI for managing the rffmpeg system.
582 | """
583 | CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"], max_content_width=120)
584 |
585 | @click.group(context_settings=CONTEXT_SETTINGS)
586 | def rffmpeg_click():
587 | """
588 | rffmpeg CLI interface
589 | """
590 | if (
591 | not Path(config["state_dir"]).is_dir()
592 | or not Path(config["db_path"]).is_file()
593 | ):
594 | return
595 |
596 | # List all DB migrations here
597 | did_alter_0001AddServername = False
598 | # Check conditions for migrations
599 | with dbconn(config) as cur:
600 | # Migration for new servername (PR #36)
601 | cur.execute(
602 | "SELECT COUNT(*) AS CNTREC FROM pragma_table_info('hosts') WHERE name='servername'"
603 | )
604 | if cur.fetchone()[0] == 0:
605 | cur.execute(
606 | "ALTER TABLE hosts ADD servername TEXT NOT NULL DEFAULT 'invalid'"
607 | )
608 | did_alter_0001AddServername = True
609 | # Migration for new servername (PR #36)
610 | if did_alter_0001AddServername:
611 | with dbconn(config) as cur:
612 | cur.execute("SELECT * FROM hosts")
613 | for host in cur.fetchall():
614 | hid, servername, hostname, weight, created = host
615 | if servername == "invalid":
616 | cur.execute(
617 | f"UPDATE hosts SET servername = {SQL_VAR_SIGN} WHERE hostname = {SQL_VAR_SIGN}",
618 | (hostname, hostname),
619 | )
620 |
621 | @click.command(name="init", short_help="Initialize the system.")
622 | @click.option(
623 | "--no-root",
624 | "no_root_flag",
625 | is_flag=True,
626 | default=False,
627 | help="Bypass root check and permission adjustments; if destinations aren't writable, init will fail.",
628 | )
629 | @click.option(
630 | "-y",
631 | "--yes",
632 | "confirm_flag",
633 | is_flag=True,
634 | default=False,
635 | help="Confirm initialization.",
636 | )
637 | def rffmpeg_click_init(no_root_flag, confirm_flag):
638 | """
639 | Initialize the rffmpeg system and database; this will erase all hosts and current state.
640 |
641 | By default this command should be run as "sudo" before any attempts to use rffmpeg. If you
642 | do not require root permissions to write to your configured state and database paths, you
643 | may pass the "--no-root" option.
644 | """
645 | if not no_root_flag and os.getuid() != 0:
646 | click.echo("Error: This command requires root privileges.")
647 | exit(1)
648 |
649 | if not confirm_flag:
650 | try:
651 | click.confirm(
652 | "Are you sure you want to (re)initialize the database",
653 | prompt_suffix="? ",
654 | abort=True,
655 | )
656 | except Exception:
657 | fail("Aborting due to failed confirmation.")
658 |
659 | click.echo("Initializing database")
660 |
661 | if not Path(config["state_dir"]).is_dir():
662 | try:
663 | os.makedirs(config["state_dir"])
664 | except OSError as e:
665 | fail(f"Failed to create state directory '{config['state_dir']}': {e}")
666 |
667 | try:
668 | with dbconn(config, True) as cur:
669 | cur.execute("DROP TABLE IF EXISTS hosts")
670 | cur.execute("DROP TABLE IF EXISTS processes")
671 | cur.execute("DROP TABLE IF EXISTS states")
672 | cur.execute(f"CREATE TABLE hosts (id {SQL_PRIMARY_KEY} PRIMARY KEY, servername TEXT NOT NULL UNIQUE, hostname TEXT NOT NULL, weight INTEGER DEFAULT 1, created {SQL_DATE_TIME} NOT NULL)")
673 | cur.execute(f"CREATE TABLE processes (id {SQL_PRIMARY_KEY} PRIMARY KEY, host_id INTEGER, process_id INTEGER, cmd TEXT)")
674 | cur.execute(f"CREATE TABLE states (id {SQL_PRIMARY_KEY} PRIMARY KEY, host_id INTEGER, process_id INTEGER, state TEXT)")
675 | except Exception as e:
676 | fail(f"Failed to create database: {e}")
677 |
678 | if not no_root_flag:
679 | os.chown(
680 | config["state_dir"],
681 | getpwnam(config["dir_owner"]).pw_uid,
682 | getgrnam(config["dir_group"]).gr_gid,
683 | )
684 | os.chmod(config["state_dir"], 0o770)
685 |
686 | if DB_TYPE == "SQLITE":
687 | os.chown(
688 | config["db_path"],
689 | getpwnam(config["dir_owner"]).pw_uid,
690 | getgrnam(config["dir_group"]).gr_gid,
691 | )
692 | os.chmod(config["db_path"], 0o660)
693 |
694 | rffmpeg_click.add_command(rffmpeg_click_init)
695 |
696 | @click.command(name="status", short_help="Show hosts and status.")
697 | def rffmpeg_click_status():
698 | """
699 | Show the current status of all rffmpeg target hosts and active processes.
700 | """
701 | with dbconn(config) as cur:
702 | cur.execute("SELECT * FROM hosts")
703 | hosts = cur.fetchall()
704 | cur.execute("SELECT * FROM processes")
705 | processes = cur.fetchall()
706 | cur.execute("SELECT * FROM states")
707 | states = cur.fetchall()
708 |
709 | # Determine if there are any fallback processes running
710 | fallback_processes = list()
711 | for process in processes:
712 | pid, host_id, process_id, cmd = process
713 | if host_id == 0:
714 | fallback_processes.append(process)
715 |
716 | # Generate a mapping dictionary of hosts and processes
717 | host_mappings = dict()
718 |
719 | if len(fallback_processes) > 0:
720 | host_mappings[0] = {
721 | "hostname": "localhost (fallback)",
722 | "servername": "localhost (fallback)",
723 | "weight": 0,
724 | "current_state": "fallback",
725 | "commands": fallback_processes,
726 | }
727 |
728 | for host in hosts:
729 | hid, servername, hostname, weight, created = host
730 |
731 | # Get the latest state
732 | with dbconn(config) as cur:
733 | cur.execute(
734 | f"SELECT * FROM states WHERE host_id = {SQL_VAR_SIGN} ORDER BY id DESC",
735 | (hid,),
736 | )
737 | current_state = cur.fetchone()
738 |
739 | if not current_state:
740 | current_state = "idle"
741 | else:
742 | sid, host_id, process_id, state = current_state
743 | current_state = state
744 |
745 | # Create the mappings entry
746 | host_mappings[hid] = {
747 | "hostname": hostname,
748 | "servername": servername,
749 | "weight": weight,
750 | "current_state": current_state,
751 | "commands": [proc for proc in processes if proc[1] == hid],
752 | }
753 |
754 | hostname_length = 9
755 | servername_length = 11
756 | hid_length = 3
757 | weight_length = 7
758 | state_length = 6
759 | for hid, host in host_mappings.items():
760 | if len(host["hostname"]) + 1 > hostname_length:
761 | hostname_length = len(host["hostname"]) + 1
762 | if len(host["servername"]) + 1 > servername_length:
763 | servername_length = len(host["servername"]) + 1
764 | if len(str(hid)) + 1 > hid_length:
765 | hid_length = len(str(hid)) + 1
766 | if len(str(host["weight"])) + 1 > weight_length:
767 | weight_length = len(str(host["weight"])) + 1
768 | if len(host["current_state"]) + 1 > state_length:
769 | state_length = len(host["current_state"]) + 1
770 |
771 | output = list()
772 | output.append(
773 | "{bold}{hostname: <{hostname_length}} {servername: <{servername_length}} {hid: <{hid_length}} {weight: <{weight_length}} {state: <{state_length}} {commands}{end_bold}".format(
774 | bold="\033[1m",
775 | end_bold="\033[0m",
776 | hostname="Hostname",
777 | hostname_length=hostname_length,
778 | servername="Servername",
779 | servername_length=servername_length,
780 | hid="ID",
781 | hid_length=hid_length,
782 | weight="Weight",
783 | weight_length=weight_length,
784 | state="State",
785 | state_length=state_length,
786 | commands="Active Commands",
787 | )
788 | )
789 |
790 | for hid, host in host_mappings.items():
791 | if len(host["commands"]) < 1:
792 | first_command = "N/A"
793 | else:
794 | first_command = f"PID {host['commands'][0][2]}: {host['commands'][0][3]}"
795 |
796 | host_entry = list()
797 | host_entry.append(
798 | "{hostname: <{hostname_length}} {servername: <{servername_length}} {hid: <{hid_length}} {weight: <{weight_length}} {state: <{state_length}} {commands}".format(
799 | hostname=host["hostname"],
800 | hostname_length=hostname_length,
801 | servername=host["servername"],
802 | servername_length=servername_length,
803 | hid=hid,
804 | hid_length=hid_length,
805 | weight=host["weight"],
806 | weight_length=weight_length,
807 | state=host["current_state"],
808 | state_length=state_length,
809 | commands=first_command,
810 | )
811 | )
812 |
813 | for idx, command in enumerate(host["commands"]):
814 | if idx == 0:
815 | continue
816 | host_entry.append(
817 | "{hostname: <{hostname_length}} {servername: <{servername_length}} {hid: <{hid_length}} {weight: <{weight_length}} {state: <{state_length}} {commands}".format(
818 | hostname="",
819 | hostname_length=hostname_length,
820 | servername="",
821 | servername_length=servername_length,
822 | hid="",
823 | hid_length=hid_length,
824 | weight="",
825 | weight_length=weight_length,
826 | state="",
827 | state_length=state_length,
828 | commands=f"PID {command[2]}: {command[3]}",
829 | )
830 | )
831 |
832 | output.append("\n".join(host_entry))
833 |
834 | click.echo("\n".join(output))
835 |
836 | rffmpeg_click.add_command(rffmpeg_click_status)
837 |
838 | @click.command(name="add", short_help="Add a host.")
839 | @click.option(
840 | "-w",
841 | "--weight",
842 | "weight",
843 | required=False,
844 | default=1,
845 | help="The weight of the host.",
846 | )
847 | @click.option(
848 | "-n",
849 | "--name",
850 | "name",
851 | required=False,
852 | default=None,
853 | help="The name of the host (if different from the HOST).",
854 | )
855 | @click.argument("host")
856 | def rffmpeg_click_add(weight, name, host):
857 | """
858 | Add a new host with IP or hostname HOST to the database.
859 | """
860 | created = datetime.now()
861 | if name is None:
862 | name = host
863 | click.echo(f"Adding new host '{host}' ({name})")
864 | with dbconn(config) as cur:
865 | cur.execute(
866 | f"INSERT INTO hosts (servername, hostname, weight, created) VALUES ({SQL_VAR_SIGN}, {SQL_VAR_SIGN}, {SQL_VAR_SIGN}, {SQL_VAR_SIGN})",
867 | (name, host, weight, created),
868 | )
869 |
870 | rffmpeg_click.add_command(rffmpeg_click_add)
871 |
872 | @click.command(name="remove", short_help="Remove a host.")
873 | @click.argument("host")
874 | def rffmpeg_click_remove(host):
875 | """
876 | Remove a host with internal ID/IP/hostname/servername HOST from the database.
877 | """
878 | try:
879 | host = int(host)
880 | field = "id"
881 | except ValueError:
882 | field = "servername"
883 | fieldAlt = "hostname"
884 |
885 | with dbconn(config) as cur:
886 | cur.execute(f"SELECT * FROM hosts WHERE {field} = {SQL_VAR_SIGN}", (host,))
887 | entry = cur.fetchall()
888 | if len(entry) < 1:
889 | cur.execute(
890 | f"SELECT * FROM hosts WHERE {fieldAlt} = {SQL_VAR_SIGN}", (host,)
891 | )
892 | entry = cur.fetchall()
893 | if len(entry) < 1:
894 | fail("No hosts found to delete!")
895 |
896 | if len(entry) == 1:
897 | click.echo(f"Removing {len(entry)} host:")
898 | else:
899 | click.echo(f"Removing {len(entry)} hosts:")
900 | for host in entry:
901 | hid, servername, hostname, weight, created = host
902 | click.echo(f"\tID: {hid}\tHostname: {hostname}\tServername: {servername}")
903 | cur.execute(f"DELETE FROM hosts WHERE id = {SQL_VAR_SIGN}", (hid,))
904 |
905 | rffmpeg_click.add_command(rffmpeg_click_remove)
906 |
907 | @click.command(name="run", short_help="Run a command.", context_settings={
908 | "ignore_unknown_options": True
909 | })
910 | @click.option("--stderr-as-stdout", "stderr_as_stdout", is_flag=True, default=False, help="Use stderr as stdout for the command.")
911 | @click.argument('full_command', nargs=-1, type=click.UNPROCESSED)
912 | def rffmpeg_click_run(stderr_as_stdout, full_command):
913 | """
914 | Run a command on the optimal host.
915 | """
916 | hook_signals()
917 |
918 | setup_logging(config)
919 |
920 | command = full_command[0]
921 | command_args = full_command[1:]
922 |
923 | log.info(f"Starting rffmpeg as {command} with args: {' '.join(command_args)}")
924 |
925 | target_hid, target_hostname, target_servername = get_target_host(config)
926 |
927 | if not target_hostname or target_hostname == "localhost":
928 | ret = run_local_command(config, target_hid, command, command_args)
929 | else:
930 | ret = run_remote_command(
931 | config,
932 | target_hid,
933 | target_hostname,
934 | target_servername,
935 | command,
936 | command_args,
937 | stderr_as_stdout=stderr_as_stdout
938 | )
939 |
940 | cleanup()
941 | if ret.returncode == 0:
942 | log.info(f"Finished rffmpeg with return code {ret.returncode}")
943 | else:
944 | log.error(f"Finished rffmpeg with return code {ret.returncode}")
945 | exit(ret.returncode)
946 |
947 | rffmpeg_click.add_command(rffmpeg_click_run)
948 |
949 | @click.command(name="log", short_help="View the rffmpeg log.")
950 | @click.option(
951 | "-f",
952 | "--follow",
953 | "follow_flag",
954 | is_flag=True,
955 | default=False,
956 | help="Follow new log entries instead of seeing current log entries.",
957 | )
958 | def rffmpeg_click_log(follow_flag):
959 | """
960 | View the rffmpeg log file.
961 | """
962 | if follow_flag:
963 | if not os.path.exists(config["logfile"]):
964 | click.echo("Failed to find log file; have you initialized rffmpeg?")
965 | exit(1)
966 |
967 | with open(config["logfile"]) as file_:
968 | # Go to the end of file
969 | file_.seek(0, 2)
970 | while True:
971 | curr_position = file_.tell()
972 | line = file_.readline()
973 | if not line:
974 | file_.seek(curr_position)
975 | sleep(0.1)
976 | else:
977 | click.echo(line, nl=False)
978 | else:
979 | with open(config["logfile"], "r") as logfh:
980 | click.echo_via_pager(logfh.readlines())
981 |
982 | rffmpeg_click.add_command(rffmpeg_click_log)
983 |
984 | @click.command(name="clear", short_help="Clear processes and states.")
985 | @click.argument("host", required=False, default=None)
986 | def rffmpeg_click_log(host):
987 | """
988 | Clear all active process and states from the database, optionally limited to a host with internal ID/IP/hostname/servername HOST.
989 |
990 | This command is designed to assist in rare error cases whereby stuck process states are present in the database, and should be used sparingly. This will not affect running processes negatively, though rffmpeg will no longer see them as active. It is recommended to run this command only when you are sure that no processes are actually running.
991 | """
992 | with dbconn(config) as cur:
993 | if host is not None:
994 | try:
995 | host = int(host)
996 | field = "id"
997 | except ValueError:
998 | field = "servername"
999 | fieldAlt = "hostname"
1000 |
1001 | cur.execute(f"SELECT id FROM hosts WHERE {field} = {SQL_VAR_SIGN}", (host,))
1002 | entry = cur.fetchall()
1003 | if len(entry) < 1:
1004 | cur.execute(f"SELECT id FROM hosts WHERE {fieldAlt} = {SQL_VAR_SIGN}", (host,))
1005 | entry = cur.fetchall()
1006 | if len(entry) < 1:
1007 | fail("Host not found!")
1008 | if len(entry) > 1:
1009 | fail("Multiple hosts found, please be more specific!")
1010 | host_id = entry[0][0]
1011 |
1012 | click.echo(f"Clearing all active processes and states for host ID '{host_id}'")
1013 | cur.execute(f"SELECT id FROM processes WHERE host_id = {SQL_VAR_SIGN}", (host_id,))
1014 | processes = cur.fetchall()
1015 | cur.execute(f"SELECT id FROM states WHERE host_id = {SQL_VAR_SIGN}", (host_id,))
1016 | states = cur.fetchall()
1017 |
1018 | for process in processes:
1019 | cur.execute(f"DELETE FROM processes WHERE id = {SQL_VAR_SIGN}", process)
1020 | for state in states:
1021 | cur.execute(f"DELETE FROM states WHERE id = {SQL_VAR_SIGN}", state)
1022 | else:
1023 | click.echo("Clearing all active processes and states")
1024 | cur.execute("DELETE FROM processes")
1025 | cur.execute("DELETE FROM states")
1026 |
1027 | rffmpeg_click.add_command(rffmpeg_click_log)
1028 |
1029 | return rffmpeg_click(obj={})
1030 |
1031 |
1032 | # Entrypoint
1033 | if __name__ == "__main__":
1034 | all_args = sys.argv
1035 | cmd_name = all_args[0]
1036 |
1037 | # Load the config
1038 | config = load_config()
1039 |
1040 | if "rffmpeg" in cmd_name:
1041 | run_control(config)
1042 |
1043 | else:
1044 | ffmpeg_args = all_args[1:]
1045 | run_ffmpeg(config, ffmpeg_args)
1046 |
--------------------------------------------------------------------------------
/rffmpeg.yml.sample:
--------------------------------------------------------------------------------
1 | ---
2 | # Configuration file for rffmpeg
3 | #
4 | # Copy this sample to /etc/rffmpeg/rffmpeg.yml and replace the various attributes
5 | # with the values for your environment. For more details please see the README.
6 | #
7 | # Any commented value represents the default. Uncomment and alter as required.
8 |
9 | rffmpeg:
10 | # Logging configuration
11 | logging:
12 | # Enable or disable file logging.
13 | #log_to_file: true
14 |
15 | # Log messages to this file.
16 | # Ensure the user running rffmpeg can write to this directory.
17 | #logfile: "/var/log/jellyfin/rffmpeg.log"
18 |
19 | # Use a Jellyfin-logging compatible dated log format, e.g. "20221223_rffmpeg.log"
20 | # Supersedes the "logfile" directive above
21 | #datedlogfiles: false
22 |
23 | # Use this base directory for Jellyfin-logging compatible dated log files if you enable "datedlogfiles"
24 | # Set this to your Jellyfin logging directory if it differs from the default
25 | #datedlogdir: "/var/log/jellyfin/"
26 |
27 | # Show debugging messages
28 | #debug: false
29 |
30 | # Directory configuration
31 | directories:
32 | # Persistent directory to store state database.
33 | #state: "/var/lib/rffmpeg"
34 |
35 | # Temporary directory to store SSH persistence sockets.
36 | #persist: "/run/shm"
37 |
38 | # The user who should own the state directory and database.
39 | # This should normally be the user who normally runs rffmpeg commands (i.e. the media
40 | # server service user).
41 | #owner: jellyfin
42 |
43 | # The group who should own the state directory and database (an administrative group).
44 | # Use this group to control who is able to run "rffmpeg" management commands; users in
45 | # this group will have unlimited access to the tool to add/remove hosts, view status, etc.
46 | #group: sudo
47 |
48 | # Remote (SSH) configuration
49 | remote:
50 | # The remote SSH user to connect as.
51 | #user: jellyfin
52 |
53 | # How long to persist SSH sessions; 0 to disable SSH persistence.
54 | #persist: 300
55 |
56 | # A YAML list of additional SSH arguments (e.g. private keys).
57 | # One entry line per space-separated argument element.
58 | #args:
59 | # - "-i"
60 | # - "/var/lib/jellyfin/id_rsa"
61 |
62 | # Remote command configuration
63 | commands:
64 | # The path (either full or in $PATH) to the default SSH binary.
65 | #ssh: "/usr/bin/ssh"
66 |
67 | # A YAML list of prefixes to the ffmpeg command (e.g. sudo, nice, etc.).
68 | # One entry line per space-separated command element.
69 | #pre:
70 | # - ""
71 |
72 | # The (remote) ffmpeg and ffprobe command binary paths.
73 | #ffmpeg: "/usr/lib/jellyfin-ffmpeg/ffmpeg"
74 | #ffprobe: "/usr/lib/jellyfin-ffmpeg/ffprobe"
75 |
76 | # Optional local fallback ffmpeg and ffprobe binary paths, if different from the above.
77 | #fallback_ffmpeg: "/usr/lib/jellyfin-ffmpeg/ffmpeg"
78 | #fallback_ffprobe: "/usr/lib/jellyfin-ffmpeg/ffprobe"
79 |
80 | # Optional additions to special flags that output to stdout instead of stderr. This isn't an override.
81 | #special_flags:
82 | # - "-muxers"
83 | # - "-fp_format"
84 |
--------------------------------------------------------------------------------