Capture screen as a video device using FFmpeg
Posted: | Tags: til ffmpegOn my Linux machine I have sometimes shared by screen as a virtual device so it can be used in other programs as a webcam. A similar FFmpeg can also just be used to capture video to the file as well.
Capture as a video device
The v4l2loopback module allows you to create a virtual video devices under /dev/
.
Load the module, with the command below. After doing so you will see a new video device under /dev/
, since I have no video devices currently attached v4l2loopback creates device /dev/video0
.
modprobe v4l2loopback
Next, find your X Server display number to use as the input to FFmpeg. My value was 1.
echo $DISPLAY
The following FFmpeg command captures 1920x1080 pixels and outputs the same resolution at 25 frames per second (fps) to our virtual video device. Note I have also set the X Server display number, 1, after the colon, the offset is denoted for x and y-axis after the +.
ffmpeg -video_size 1920x1080 -framerate 25 -f x11grab -i :1+0,0 -f v4l2 /dev/video0
If you have a second display you can set the input offset to capture it. In my instance both my displays are side-by-side and have a resolution of 1920x1080. Within the following FFmpeg command I still capture 1920x1080 pixels at 25fps but set the input to be offset by 1920 along the x-axis.
ffmpeg -video_size 1920x1080 -framerate 25 -f x11grab -i :1+1920,0 -f v4l2 /dev/video0
After running the FFmpeg commanmd you can now test the video stream within any application that accepts a webcam such as OBS or Discord. To end capturing video you can exit out of FFmpeg.
Capture to file
If you would like to record video from your screen instead of sending it to a virtual device replace -f v4l2 /dev/video0
with a file name like output.mp4
to write to the file.
ffmpeg -video_size 1920x1080 -framerate 25 -f x11grab -i :1+0,0 output.mp4
More information can be found in the FFmpeg documentation such as capturing audio.