
Recall first from GStreamer pipelines and tools
- A pipeline is a top-level bin that manages a graph of linked elements.
- Negotiated caps describe the media format on a link, and buffers carry the media data.
- The pipeline bus delivers messages such as errors and end of stream to the controlling program.
Record camera video to a file
3 min readCommand-line pipelines become real programs; this lesson assembles capture, encode, display, and audio pipelines and builds them with the C API.
A camera can give you a working preview and still fail to record. The Linux kernel's V4L2 capture documentation describes how capture devices expose their supported formats. Those formats determine what v4l2src can deliver. A display pipeline can accept a format that a particular encoder cannot consume. Before combining the two jobs, identify the format at the camera output and the format at the encoder input.
The examples use /dev/video0 for a camera that can supply raw frames. Substitute your capture node if it differs. A VM needs access to a camera passed through from the host. If Ubuntu has no accessible capture device, use videotestsrc is-live=true in place of v4l2src device=/dev/video0 to verify the GStreamer stages. That run verifies recording and transport with test frames. For a camera that supplies JPEG frames, select image/jpeg immediately after v4l2src and insert jpegdec before videoconvert. Choose a mode the camera actually advertises.
gst-launch-1.0 -e \
v4l2src device=/dev/video0 ! videoconvert ! \
x264enc ! h264parse ! mp4mux ! filesink location=capture.mp4
videoconvert converts raw pixel formats so the source and encoder can agree on one. It leaves frame size and rate to other stages. If you add a caps filter to choose a capture size or rate, put it next to the source and use a supported mode. x264enc compresses raw frames into H.264 on the CPU. h264parse parses the bitstream and can negotiate its framing with mp4mux, which packages the encoded pictures and their timing into an MP4 container. filesink writes the resulting bytes to the named path. Shell quoting matters when a path or a caps expression contains spaces.
On a target with a compatible V4L2 H.264 encoding device and a registered v4l2h264enc factory, you can place that element where x264enc sits. Check with gst-inspect-1.0 v4l2h264enc and read the encoder's sink caps before choosing a raw format. Camera capture support and hardware encoding support are separate capabilities. The capture node can work even when the encoding factory is unavailable. Use x264enc for the Ubuntu baseline when its plugin is installed, and keep the parser and muxer downstream when changing encoders.
Press Ctrl+C once after a few seconds. The -e option makes gst-launch-1.0 send an end-of-stream (EOS) event during shutdown so mp4mux can finish the container. Wait for the command to exit before opening the file. A growing file shows that bytes are being written. Playing it back verifies that a reader can open the container and decode the pictures. For this video-only file, you can test both in a graphical session with:
gst-launch-1.0 \
filesrc location=capture.mp4 ! qtdemux ! h264parse ! \
avdec_h264 ! videoconvert ! autovideosink
Choose display and audio endpoints
3 min readFor a local preview, take raw frames from the camera and send them to a video sink. This lets you verify the camera, raw conversion, and display environment before involving an encoder. Run the preview after closing the recorder so the two processes do not compete for the same camera stream.
gst-launch-1.0 \
v4l2src device=/dev/video0 ! videoconvert ! autovideosink
autovideosink searches for an installed video sink it can use. It is convenient on a desktop where the application can reach the display session. An explicit element makes the display dependency visible in the pipeline. Use waylandsink when the application runs in a Wayland session and can connect to its compositor. Use glimagesink when the target provides a working OpenGL display context. It can render to its own window and can also take a supported application-provided window handle through GstVideoOverlay. Window integration depends on the window system in use.
kmssink displays through DRM/KMS using a display plane. It fits a target with an attached display where the application has access to the required DRM device and display resources. The kernel's KMS documentation describes the plane, CRTC, and connector used to present a frame. A desktop compositor may already control the relevant resources. Access to a desktop window in a VM or WSL2 does not by itself give the guest application control of a physical display pipeline.
Audio has its own source and sink. alsasrc records from an ALSA capture PCM and alsasink plays through an ALSA playback PCM. You can select a PCM with the element's device property. pulsesink sends audio to a PulseAudio server or a compatible server such as PipeWire's PulseAudio service. The session must expose that server to the process. For a playback check with an audible test signal, start with the output volume low:
gst-launch-1.0 \
audiotestsrc ! audioconvert ! audioresample ! pulsesink
Replace pulsesink with alsasink to check ALSA playback on a target with a usable playback PCM. Once playback works, alsasrc can replace audiotestsrc to check capture and playback together. Use headphones for microphone monitoring to avoid acoustic feedback. audioconvert adapts sample formats or channel layouts, and audioresample adapts the sample rate when needed. If only the test tone works, you have verified playback and can focus on the capture PCM. If playback fails with either source, check which audio endpoint the process can reach before changing the capture settings.
A product that records and previews from one camera can use a single v4l2src feeding a tee, with a queue at the start of each branch. One branch converts frames for display and the other converts and encodes them for storage. The queues let the branches run in separate streaming threads. Each queue has a finite capacity, so a persistently slow branch can still stall other branches when its queue fills. Preview and recording can have different requirements for dropping frames. Decide those requirements before configuring queue limits.
Send video to a client and control the pipeline in C
5 min readThe network example keeps the capture and H.264 encoding stages and sends the encoded video through rtph264pay. A an element that packages encoded media into packets for a transport format prepares the H.264 for RTP, and udpsink sends the packets. Start the receiver in a graphical Ubuntu session first. The caps beside udpsrc tell the receiver how to interpret the packets arriving on the chosen port.
gst-launch-1.0 \
udpsrc port=5000 \
caps='application/x-rtp,media=video,clock-rate=90000,encoding-name=H264,payload=96' ! \
rtph264depay ! h264parse ! avdec_h264 ! videoconvert ! autovideosink
Run the sender in a second terminal in the same Ubuntu instance. Here 127.0.0.1 makes the client local. For a client on a separate machine, use that client's reachable address as the host and allow incoming UDP on the chosen port there.
gst-launch-1.0 \
v4l2src device=/dev/video0 ! videoconvert ! \
x264enc tune=zerolatency key-int-max=30 ! h264parse ! \
rtph264pay pt=96 config-interval=-1 ! udpsink host=127.0.0.1 port=5000
The receiver's port and payload type match the sender. The payloader repeats the H.264 parameter sets with each IDR picture when config-interval=-1. Repeating them helps a receiver that starts after the sender, since decoding can begin once the receiver gets the parameter sets and a suitable picture. key-int-max=30 sets a maximum keyframe distance in frames. tune=zerolatency reduces buffering in the encoder for this preview. When the client shows moving video, you have verified packet reception and decoding as well as capture. The two commands use a direct RTP stream over UDP.
With RTSP, a client opens a URL and negotiates a media session. An application using gst-rtsp-server can mount a media factory at /camera and give the factory a launch description with a source, encoder, parser, and rtph264pay name=pay0 pt=96. The server uses pay0 as the first media stream. With a server listening on port 8554, an RTSP client can open rtsp://127.0.0.1:8554/camera on the same machine. A GStreamer RTSP client can use rtspsrc with that URL and connect the H.264 RTP output to the depayloader. tcpserversink is another option when both endpoints agree on a TCP byte stream. For example, send h264parse ! mpegtsmux ! tcpserversink after the encoder, and receive with tcpclientsrc ! tsdemux followed by the H.264 parser and decoder. The TCP sink accepts connections and writes bytes. Session negotiation requires an RTSP server.
The same launch syntax can define a pipeline inside a C program. A GstPipeline is a top-level container for GstElement objects, and it provides a bus for messages about execution. gst_parse_launch creates and links elements from a description. To build a graph explicitly, create the container with gst_pipeline_new, create elements with gst_element_factory_make, set properties with g_object_set, add elements with gst_bin_add, and link them with gst_element_link. Check each creation, add, and link result. The bin takes ownership of an element when adding it succeeds.
This program records a finite test pattern, so it can exercise the full MP4 shutdown path on Ubuntu without a camera. Save it as record.c.
#include <gst/gst.h>
int main(void)
{
GError *error = NULL;
gst_init(NULL, NULL);
GstElement *pipeline = gst_parse_launch(
"videotestsrc num-buffers=60 ! videoconvert ! x264enc ! "
"h264parse ! mp4mux ! filesink location=app.mp4", &error);
if (error || !pipeline) {
g_printerr("%s\n", error ? error->message : "No pipeline");
g_clear_error(&error);
if (pipeline)
gst_object_unref(pipeline);
return 1;
}
int status = 1;
GstBus *bus = gst_element_get_bus(pipeline);
if (gst_element_set_state(pipeline, GST_STATE_PLAYING) != GST_STATE_CHANGE_FAILURE) {
GstMessage *message = gst_bus_timed_pop_filtered(
bus, GST_CLOCK_TIME_NONE, GST_MESSAGE_ERROR | GST_MESSAGE_EOS);
if (message && GST_MESSAGE_TYPE(message) == GST_MESSAGE_EOS) {
status = 0;
} else if (message) {
gst_message_parse_error(message, &error, NULL);
g_printerr("%s\n", error->message);
g_clear_error(&error);
}
if (message)
gst_message_unref(message);
} else {
g_printerr("Could not start the pipeline\n");
}
if (gst_element_set_state(pipeline, GST_STATE_NULL) == GST_STATE_CHANGE_FAILURE)
status = 1;
gst_object_unref(bus);
gst_object_unref(pipeline);
return status;
}
On Ubuntu, libgstreamer1.0-dev supplies the headers and pkg-config metadata. The examples use the GStreamer tools and elements from the base, good, bad, ugly, and libav plugin packages, with the ALSA and GL elements available in gstreamer1.0-alsa and gstreamer1.0-gl.
gcc -Wall -Wextra -std=c17 record.c -o record \
$(pkg-config --cflags --libs gstreamer-1.0)
./record
The link flags include -lgstreamer-1.0 and its GLib dependencies. The encoder and muxer are loaded as runtime plugins. gst_element_set_state requests PLAYING, and a successful request can complete asynchronously. The bus reports failures that appear later and EOS when the pipeline finishes. This finite program can wait in its main thread. A GUI or service using a GLib main loop can attach a bus watch with gst_bus_add_watch and handle messages without blocking its event loop. For a live recorder, have the application's stop action send EOS with gst_element_send_event(pipeline, gst_event_new_eos()), check whether the event was accepted, and wait for EOS or an error before teardown. EOS travels downstream as an event. The bus message tells the application that processing has finished.
Going deeperApplication dataflow and buffer lifetime
Use appsink when application code consumes samples, for example to inspect camera frames. A sample carries a buffer and its negotiated caps. Release each sample once processing finishes, and bound the sink's queue according to how much latency and memory the application can tolerate. A slow consumer can accumulate buffers or apply backpressure depending on the configuration. Keep work triggered from a streaming callback short so the pipeline can continue processing.
Use appsrc when the application produces buffers. Set caps that describe the actual bytes, and supply timestamps and durations appropriate to the stream. For timestamped live input, configure the source for live operation and use time format. Check the push result and respect the source's demand for data. Signal EOS when the producer is finished. For an operation reused across pipelines, a custom element can expose pads, caps, and properties. GstBaseTransform is a starting point for processing buffers between an input pad and an output pad.
A buffer pool reuses allocations as buffers are released. An application that keeps references to captured buffers can delay their return to the pool. If the available buffers are all held, upstream may stall or use another allocation path, depending on the elements. Set a limit on outstanding samples when handing frames to an application worker. Check the buffer layout before interpreting pixels, since row stride can differ from the number of visible bytes per row.
In Hardware codecs, streaming, and debugging, you will examine how target codec support changes these pipeline choices and how to diagnose failures in a running media path.
Key takeaways
- The encoder produces H.264, the muxer builds the MP4 container, and filesink writes it.
- The display sink must match the session and the target's display access.
- RTP carries packetized media, while RTSP controls a streaming session.
- A recorder waits for EOS before setting the pipeline to NULL so the muxer can finish the file.
Reflect
- Explain to a colleague, in two sentences: record a V4L2 capture stream to a playable MP4 file.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Kernel documentationVideo Capture Interface: V4L2 device capabilities and formats
- Kernel documentationBuffers: V4L2 streaming buffer exchange
- Kernel documentationKernel Mode Setting: DRM display resources
- GStreamer documentationGStreamer command line tools
- GStreamer documentationGStreamer: pads
Official documentation first. Links checked when the lesson was published.