How to Capture V4L2 Video with FFmpeg on Linux
Capturing video from a Video4Linux2 (V4L2) device, such as a webcam or capture card, is a highly efficient process when using the FFmpeg command-line tool on Linux. This guide provides a straightforward, step-by-step tutorial on how to identify your connected video devices, query their supported resolutions, and run FFmpeg commands to record high-quality video and audio directly from the terminal.
Step 1: Identify Your V4L2 Device
Before recording, you need to find the device path (usually
/dev/video*) assigned to your capture card or webcam. You
can list all connected video devices by running:
ls /dev/video*Alternatively, use the v4l2-ctl tool (part of the
v4l-utils package) for a more detailed list:
v4l2-ctl --list-devicesThis will output the name of your device and its corresponding path,
for example, /dev/video0.
Step 2: List Supported Formats and Resolutions
To ensure you capture at the correct settings, query your device to see what resolutions, frame rates, and pixel formats it supports:
ffmpeg -f v4l2 -list_formats all -i /dev/video0Look at the output to find your desired resolution (e.g.,
1920x1080) and frame rate (e.g., 30 fps).
Step 3: Capture Video (Basic Command)
To quickly start capturing video using the default settings of the device and save it to an MP4 file, run:
ffmpeg -f v4l2 -i /dev/video0 output.mp4To stop the recording at any time, press q or
Ctrl+C in your terminal.
Step 4: Configure Resolution, Frame Rate, and Codecs
For professional or high-quality capturing, you should explicitly set the input parameters and encode the video using the H.264 codec.
ffmpeg -f v4l2 -video_size 1920x1080 -framerate 30 -i /dev/video0 -c:v libx264 -preset ultrafast output.mp4Command breakdown: * -f v4l2: Specifies
the input format as Video4Linux2. * -video_size 1920x1080:
Sets the capture resolution. * -framerate 30: Sets the
capture frame rate to 30 frames per second. *
-i /dev/video0: Defines the input source device. *
-c:v libx264: Encodes the output video using the H.264
video codec. * -preset ultrafast: Reduces CPU usage during
real-time encoding.
Step 5: Capture Video with Audio
If your capture device or a separate microphone provides audio, you can capture both signals simultaneously. To record video from V4L2 alongside audio from an ALSA or PulseAudio source, use the following command:
Using PulseAudio:
ffmpeg -f v4l2 -video_size 1280x720 -framerate 30 -i /dev/video0 -f pulse -i default -c:v libx264 -c:a aac output.mp4Using ALSA:
ffmpeg -f v4l2 -video_size 1280x720 -framerate 30 -i /dev/video0 -f alsa -i hw:1 -c:v libx264 -c:a aac output.mp4Make sure to replace default or hw:1 with
the correct audio identifier for your system.