Run any app in "Kiosk" mode on Ubuntu Server

I have a spare monitor on my aux desk which I use for testing purposes, I wanted to make better use of this screen so I decided to hook up a nearby Raspberry PI 4 running Ubuntu Server, and display one of my IP cameras on it, here is how I done it.

On Ubuntu Server there is no GUI so the first step is to install xserver, to do this just run the command: sudo apt install xorg.

In my case I will use mpv which is a video player to display the stream from the camera. To install this you run sudo apt install mpv

To get hardware accelerated graphics you also need to setup a "Device Tree Overlay" to load the appropriate kernel modules. This is easy enough, you can add the following to /boot/firmware/usercfg.txt


The last step is to reboot and then run the command to start your app in "kiosk" mode, for me it looks like this:
xinit $(which mpv) --fs --no-audio rtmp://local-cam:1935/live/front -- :0

This works great but there is one more step you can do to make it run all the time.

I use a program called flock this allows you to run a process with an external lock file, what this means is that you can run a program only once and ensure that its always running by trying to start this process every minute.

To install flock you can install it with the command sudo apt install flock

To run the flock command every minute you can use cron, to add an entry to cron you run the command cron -e this will bring up your editor.

The entry you want to add to cron is this:

* * * * * /usr/bin/flock -xn /var/lock/.my_kiosk bash -c "run your command here"

You should paste the xinit command inside the quotes, for me it looks like this:

* * * * * /usr/bin/flock -xn /var/lock/.ip_cam bash -c "xinit $(which mpv) --fs --no-audio rtmp://local-cam:1935/live/front -- :0"

Now your "Kiosk" app will restart if it crashes or if you reboot your machine, this saves a lot of headache later when trying to manage a bunch of random things running.