Virtual webcam with v4l2

A few weeks ago I discovered Video4Linux (v4l2), which allows you to control video devices like a webcam.

In my case, I simulated/virtualized a webcam. That means that with the help of v4l2 I could send a video stream (or an image) to a virtual/simulated webcam. And every app that can normally address a webcam (e.g. Zoom or Skype) played my video what I sent to the webcam.

Here are some of the commands I found useful.

Setup

With v4l2loopback we can virtualize a webcam.

1
sudo apt install v4l2loopback-dkms

With v4l2-ctl we can control the video4linux drivers. (It is in the v4l-utils package)

1
sudo apt install v4l-utils

With ffmpeg we can stream our video to the webcam

1
sudo apt install ffmpeg

Start

Let’s load the kernel module v4l2loopback, which creates a virtual video device.

1
sudo modprobe v4l2loopback

If you need multiple video devices, you can load them as follow

1
sudo modprobe v4l2loopback devices=2

The video devices will appear under /dev/video[0-9].
You can check with v4l2-ctl, which id your video devices have

1
v4l2-ctl --list-devices

Video to webcam

You can stream a video (input.mov in that case) to your virtualized webcam

1
ffmpeg -re -i input.mov -f v4l2 /dev/video0

Loop

If you would like to send your video in a loop

1
ffmpeg -stream_loop -1 -re -i input.mov -f v4l2 /dev/video0

Picture to webcam

If you would like just send a picture to your virtualized webcam.

1
ffmpeg -loop 1 -re -i input.jpg -f v4l2 -vcodec rawvideo -pix_fmt yuv420p /dev/video0

Desktop to webcam

If you would like to stream your desktop. Very handy if the application you use doesn’t support screen sharing.

1
ffmpeg -f x11grab -framerate 25 -video_size 1920x1080 -i :1 -f v4l2 /dev/video0

In my case the input is “:1”, this could be different e.g :0.
You can identify your display by echo $DISPLAY

You can identify your resolution with resolution: xrandr -q

If you have multiple screens, you can just add the resolution you have to the display e.g. :1+1920

Cloning a webcam

You can clone e.g. your real webcam (/dev/video0) to multiple devices. In that case /dev/video1 and /dev/video2

That is handy if an application is blocking a device (because it will be used), you can bypass it by cloning the webcam and use it in another application the cloned video device.

1
ffmpeg -f v4l2 -i /dev/video0 -f v4l2 /dev/video1 -f v4l2 /dev/video2

video1 and video2 need to be created. E.g. sudo modprobe v4l2loopback devices=2

Useful commands

Playing the webcam stream

ffplay is a simple media player, which use the FFmpeg library

1
ffplay /dev/video0

If the stream you playing is a bit laggy (that was in my case) you can tune it with:

1
ffplay /dev/video0  -fflags nobuffer -flags low_delay -framedrop

mpv is a free (as in freedom) media player for the command line.

1
mpv /dev/video0