How to Use video4linux2 with FFmpeg on Linux
This article provides a straightforward guide on how to capture video
from webcams and capture cards on Linux using FFmpeg’s
video4linux2 (V4L2) input device. You will learn how to
identify your connected video devices, list their supported formats, and
construct FFmpeg commands to record, stream, or configure your video
feed with specific resolutions and frame rates.
Finding Your Video Device
Before using FFmpeg, you need to identify the device path of your
camera (usually /dev/videoX). You can list all connected
video devices by running the following command in your terminal:
ls /dev/video*Alternatively, if you have the v4l-utils package
installed, you can get a cleaner list with:
v4l2-ctl --list-devicesIdentify the path corresponding to your camera, which is typically
/dev/video0.
Basic Video Capture
To test if your webcam is working and capture a basic video stream,
use the -f video4linux2 (or -f v4l2) option to
specify the input format, followed by the device path.
ffmpeg -f video4linux2 -i /dev/video0 output.mp4To stop recording, press q in your terminal.
Listing Supported Resolutions and Formats
Webcams support specific resolutions, frame rates, and pixel formats. To see what your hardware supports, ask FFmpeg to list them:
ffmpeg -f video4linux2 -list_formats all -i /dev/video0This will print a list of supported formats (such as raw
yuyv422 or compressed mjpeg), resolutions, and
framerates to your terminal.
Setting Resolution, Framerate, and Input Format
For optimal performance, you should explicitly set the input
parameters before the input file option (-i).
-video_size: Sets the resolution (e.g.,1280x720).-framerate: Sets the frames per second (e.g.,30).-input_format: Specifies the input codec or pixel format (e.g.,mjpegoryuyv422). Usingmjpegis often required for high resolutions at 30+ FPS on USB 2.0 webcams.
Here is an example command combining these options:
ffmpeg -f video4linux2 -input_format mjpeg -video_size 1920x1080 -framerate 30 -i /dev/video0 output.mp4Capturing Video with Audio
If you want to record audio from your microphone alongside the video,
you must add an audio input device. On modern Linux systems, this is
typically done using pulse or alsa.
Here is an example capturing video via V4L2 and audio via PulseAudio:
ffmpeg -f video4linux2 -video_size 1280x720 -framerate 30 -i /dev/video0 -f pulse -i default output.mkv