View/record a webcam with VLC

There's a wide, wide variety of ways to record webcams in unices but I've come to rely on just one, VLC. Yes, it's a video viewer more than a recorder but it does both quite well. Let's detail how to view a live webcam stream first, just keep in mind that the drivers for your webcam need to be v4l compatible (most are, of course).

vlc -vvv v4l2:///dev/video0:chroma=mjpg:width=1920:height=1080:fps=30 :input-slave=pulse://alsa_input.usb-Blue_Microphones_Yeti_Stereo_Microphone-00-Microphone.analog-stereo

-vvv = Verbosity
v4l2:///dev/video0 = Video input device
:chroma=mjpg = MJPEG Codec
:width=1920:height=1080 = Resolution
:fps=30 = Frames per second

The :input-slave simply loops my external microphone into the stream, this is something I want but it's naturally up to your preference. That command line looked complex at first but really it's quite straight forward. Let's move on to recording said stream to a file and also previewing it at the same time.

vlc -vvv v4l2:///dev/video0:chroma=mjpg:width=1920:height=1080:fps=30 :input-slave=pulse://alsa_input.usb-Blue_Microphones_Yeti_Stereo_Microphone-00-Microphone.analog-stereo --sout="#duplicate{dst=std{access=file,fps=30,mux=avi,dst=/mnt/misc/test.avi},dst=display}"

First part is exactly the same so let's move straight to the output bit.

--sout="#duplicate{ = Define a duplicate stream, both preview and file output.
dst=std{access=file, = First stream destination is a std-file.
fps=30,mux=avi, = 30 FPS, avi muxing.
dst=/mnt/misc/test.avi}, = Output file path and name.
dst=display}" = Second stream destination is the display/preview.

This has worked reliably with all devices and distributions I've tried it on. Every single other application has had its own set of quirks that required elaborate workarounds, this did not.

There's one final thing to keep in mind. If your camera supports multiple output streams, like my Logitech C920 has both YUV, MJPEG and H.264, then you might be required to set it before entering either of these commands. It can be set as simply as this.

v4l2-ctl --set-fmt-video=width=1920,height=1080,pixelformat=2

Everything should be clear there, pixelformat refers to the stream. You will need to either simply try each format to figure out what your camera outputs there or refer to its driver documentation. pixelformat=2 for the C920 is MJPEG, which I found to have a consistently higher quality than its built in H.264 encoder.