Capture V4L2 Video on Linux Using FFmpeg

Capturing video from a webcam, capture card, or other video input devices on Linux is highly efficient when combining Video4Linux2 (V4L2) with FFmpeg. This guide provides a direct, step-by-step walkthrough to help you identify your connected V4L2 devices, discover their supported resolutions, and execute the precise FFmpeg commands required to record high-quality video and audio directly from your terminal.

Step 1: Identify Your Video Device

Before capturing, you need to locate the device path assigned to your camera by Linux (usually /dev/video0, /dev/video1, etc.).

You can list all connected video devices by running:

ls /dev/video*

Alternatively, use the v4l2-ctl utility (installed via the v4l-utils package) for a cleaner output:

v4l2-ctl --list-devices

Step 2: Find Supported Resolutions and Formats

To ensure optimal capture quality and prevent FFmpeg errors, check what formats, resolutions, and frame rates your device supports:

v4l2-ctl --list-formats-ext -d /dev/video0

(Replace /dev/video0 with your actual device path if different).

Look for formats like raw (YUYV) or compressed formats like mjpeg (Motion JPEG) and h264, along with their available resolution and fps settings.

Step 3: Basic Video Capture

To start capturing video using the default camera settings and save it to an MP4 container, run the following command:

ffmpeg -f v4l2 -i /dev/video0 output.mp4

To stop the recording at any time, press q or Ctrl+C in your terminal.

Step 4: Advanced Video Capture (Custom Resolution and Framerate)

For high-definition recording, you should explicitly define the input format, resolution, and frame rate matching your device’s capabilities.

For example, to capture at 1080p at 30 FPS using the mjpeg input format:

ffmpeg -f v4l2 -input_format mjpeg -video_size 1920x1080 -framerate 30 -i /dev/video0 -c:v libx264 -preset ultrafast output.mp4

Command breakdown: * -f v4l2: Demuxer to use the Video4Linux2 framework. * -input_format mjpeg: Tells FFmpeg to read the camera’s MJPEG stream (useful for high-resolution USB 2.0 webcams). * -video_size 1920x1080: Sets the video dimensions. * -framerate 30: Sets the frame capture rate. * -i /dev/video0: Specifies the input source. * -c:v libx264: Encodes the output video to H.264. * -preset ultrafast: Reduces CPU usage during live recording.

Step 5: Capture Video with Audio

If your camera has a built-in microphone or you want to capture audio from an external system source, you can pair the V4L2 input with PulseAudio or ALSA.

Using PulseAudio:

ffmpeg -f v4l2 -video_size 1280x720 -framerate 30 -i /dev/video0 -f pulse -i default -c:v libx264 -c:a aac output.mp4

Using ALSA (Direct hardware audio device):

ffmpeg -f v4l2 -video_size 1280x720 -framerate 30 -i /dev/video0 -f alsa -i hw:1 -c:v libx264 -c:a aac output.mp4

(Note: Replace hw:1 with your specific sound card index, which you can find by running arecord -l).