GStreamer Setup Tutorial on Ubuntu: Complete Guide

# Tutorial Setup GStreamer di Ubuntu: Panduan Lengkap GStreamer adalah framework multimedia open-source yang powerful untuk membangun aplikasi streaming, video processing, dan media handling. Tutoria...

By Ruby Abdullah · · tutorial
GStreamerUbuntuLinuxVideo ProcessingStreamingMultimedia

GStreamer Setup Tutorial on Ubuntu: Complete Guide

GStreamer is a powerful open-source multimedia framework for building streaming applications, video processing, and media handling. This tutorial will cover installation, configuration, and usage of GStreamer on Ubuntu comprehensively.

What is GStreamer?

GStreamer is a pipeline-based multimedia framework that allows you to:

  • Play and record audio/video
  • Stream media over networks
  • Transcode and convert formats
  • Video processing and filtering
  • Build custom multimedia applications

Key Concepts:
  • Pipeline: A chain of connected elements that process media
  • Elements: Individual processing units (source, filter, sink)
  • Pads: Connection points between elements
  • Caps: Capabilities that define data formats

Installing GStreamer on Ubuntu

1. Update System

sudo apt update

sudo apt upgrade -y

2. Install GStreamer Core and Tools

# GStreamer core

sudo apt install -y gstreamer1.0-tools

Good plugins (high quality, open source)

sudo apt install -y gstreamer1.0-plugins-good

Bad plugins (good quality but with licensing issues)

sudo apt install -y gstreamer1.0-plugins-bad

Ugly plugins (good quality but with patent issues)

sudo apt install -y gstreamer1.0-plugins-ugly

Base plugins

sudo apt install -y gstreamer1.0-plugins-base

Libav plugins (for additional codecs)

sudo apt install -y gstreamer1.0-libav

Development libraries

sudo apt install -y libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev

3. Install Additional Plugins

# RTSP server support

sudo apt install -y gstreamer1.0-rtsp

PulseAudio support

sudo apt install -y gstreamer1.0-pulseaudio

ALSA support

sudo apt install -y gstreamer1.0-alsa

Video4Linux support (webcam)

sudo apt install -y gstreamer1.0-v4l2

OpenGL support

sudo apt install -y gstreamer1.0-gl

X11 support

sudo apt install -y gstreamer1.0-x

Qt support

sudo apt install -y gstreamer1.0-qt5

Vulkan support (Ubuntu 20.04+)

sudo apt install -y gstreamer1.0-vulkan

4. Install Python Bindings

# Python GStreamer bindings

sudo apt install -y python3-gst-1.0

PyGObject for GTK integration

sudo apt install -y python3-gi gir1.2-gst-plugins-base-1.0

5. Verify Installation

# Check GStreamer version

gst-launch-1.0 --version

List all plugins

gst-inspect-1.0 | head -50

Check specific plugin

gst-inspect-1.0 v4l2src

Check total plugins

gst-inspect-1.0 | wc -l

Expected output:

gst-launch-1.0 version 1.20.3

GStreamer 1.20.3

GStreamer Command Line Tools

1. gst-launch-1.0

The main tool for building and running pipelines.

Basic syntax:
gst-launch-1.0 element1 ! element2 ! element3

! is the operator to connect elements. Example: Test video pattern
gst-launch-1.0 videotestsrc ! autovideosink

Example: Test audio
gst-launch-1.0 audiotestsrc ! autoaudiosink

2. gst-inspect-1.0

Tool for inspecting elements and plugins.

# List all elements

gst-inspect-1.0

Inspect specific element

gst-inspect-1.0 filesrc

Search element

gst-inspect-1.0 | grep video

3. gst-discoverer-1.0

Tool for analyzing media files.

gst-discoverer-1.0 video.mp4

Basic Pipelines

1. Video File Playback

# Playback video with audio

gst-launch-1.0 filesrc location=video.mp4 ! decodebin ! autovideosink

Playback with audio and video

gst-launch-1.0 playbin uri=file:///path/to/video.mp4

2. Audio File Playback

gst-launch-1.0 filesrc location=audio.mp3 ! decodebin ! autoaudiosink

3. Webcam Capture

# Display webcam

gst-launch-1.0 v4l2src device=/dev/video0 ! videoconvert ! autovideosink

Webcam with specific resolution

gst-launch-1.0 v4l2src device=/dev/video0 ! \

video/x-raw,width=1280,height=720,framerate=30/1 ! \

videoconvert ! autovideosink

4. Record Video from Webcam

# Record to MP4 file

gst-launch-1.0 v4l2src device=/dev/video0 ! \

videoconvert ! x264enc ! mp4mux ! \

filesink location=output.mp4

Record with audio

gst-launch-1.0 -e \

v4l2src device=/dev/video0 ! videoconvert ! x264enc ! queue ! mux. \

pulsesrc ! audioconvert ! voaacenc ! queue ! mux. \

mp4mux name=mux ! filesink location=output.mp4

5. Video Transcoding

# Convert MP4 to WebM

gst-launch-1.0 filesrc location=input.mp4 ! decodebin ! \

videoconvert ! vp8enc ! webmmux ! \

filesink location=output.webm

Convert with resize

gst-launch-1.0 filesrc location=input.mp4 ! decodebin ! \

videoscale ! video/x-raw,width=640,height=480 ! \

videoconvert ! x264enc ! mp4mux ! \

filesink location=output.mp4

RTSP Streaming

1. Setup RTSP Server

Install gst-rtsp-server:

sudo apt install -y libgstrtspserver-1.0-dev gstreamer1.0-rtsp

Create file rtspserver.py:

#!/usr/bin/env python3

import gi

gi.requireversion('Gst', '1.0')

gi.requireversion('GstRtspServer', '1.0')

from gi.repository import Gst, GstRtspServer, GLib

Gst.init(None)

class RTSPServer:

def init(self):

self.server = GstRtspServer.RTSPServer()

self.server.setservice("8554")

# Factory for stream

factory = GstRtspServer.RTSPMediaFactory()

# Pipeline for webcam streaming

pipeline = (

"( v4l2src device=/dev/video0 ! "

"video/x-raw,width=640,height=480,framerate=30/1 ! "

"videoconvert ! x264enc tune=zerolatency bitrate=500 ! "

"rtph264pay name=pay0 pt=96 )"

)

factory.setlaunch(pipeline)

factory.setshared(True)

# Mount point

mountpoints = self.server.getmountpoints()

mountpoints.addfactory("/stream", factory)

# Attach server

self.server.attach(None)

print("RTSP Server started at rtsp://localhost:8554/stream")

def run(self):

loop = GLib.MainLoop()

loop.run()

if name == "main":

server = RTSPServer()

server.run()

Run server:

python3 rtspserver.py

2. RTSP Client

# Play RTSP stream

gst-launch-1.0 rtspsrc location=rtsp://localhost:8554/stream ! \

decodebin ! videoconvert ! autovideosink

Play with low latency

gst-launch-1.0 rtspsrc location=rtsp://localhost:8554/stream latency=0 ! \

rtph264depay ! h264parse ! avdech264 ! \

videoconvert ! autovideosink sync=false

UDP Streaming

1. Sender (Server)

# Stream webcam via UDP

gst-launch-1.0 v4l2src device=/dev/video0 ! \

video/x-raw,width=640,height=480 ! \

videoconvert ! x264enc tune=zerolatency bitrate=500 ! \

rtph264pay ! udpsink host=192.168.1.100 port=5000

2. Receiver (Client)

# Receive UDP stream

gst-launch-1.0 udpsrc port=5000 ! \

application/x-rtp,encoding-name=H264,payload=96 ! \

rtph264depay ! h264parse ! avdech264 ! \

videoconvert ! autovideosink sync=false

TCP Streaming

1. Server

gst-launch-1.0 v4l2src device=/dev/video0 ! \

videoconvert ! x264enc tune=zerolatency ! \

mpegtsmux ! tcpserversink host=0.0.0.0 port=5000

2. Client

gst-launch-1.0 tcpclientsrc host=192.168.1.100 port=5000 ! \

tsdemux ! h264parse ! avdech264 ! \

videoconvert ! autovideosink

Video Processing

1. Resize Video

gst-launch-1.0 videotestsrc ! \

videoscale ! video/x-raw,width=320,height=240 ! \

autovideosink

2. Rotate Video

# Rotate 90 degrees

gst-launch-1.0 videotestsrc ! \

videoflip method=clockwise ! \

autovideosink

Methods: clockwise, counterclockwise, rotate-180, horizontal-flip, vertical-flip

3. Add Text Overlay

gst-launch-1.0 videotestsrc ! \

textoverlay text="Hello GStreamer" font-desc="Sans 24" ! \

autovideosink

4. Add Timestamp

gst-launch-1.0 v4l2src device=/dev/video0 ! \

videoconvert ! \

clockoverlay time-format="%Y-%m-%d %H:%M:%S" ! \

autovideosink

5. Picture-in-Picture

gst-launch-1.0 \

videotestsrc pattern=ball ! video/x-raw,width=320,height=240 ! comp.sink0 \

videotestsrc pattern=snow ! video/x-raw,width=160,height=120 ! comp.sink1 \

compositor name=comp sink1::xpos=10 sink1::ypos=10 ! autovideosink

Python GStreamer Integration

1. Basic Pipeline

#!/usr/bin/env python3

import gi

gi.requireversion('Gst', '1.0')

from gi.repository import Gst, GLib

Initialize GStreamer

Gst.init(None)

Create pipeline

pipeline = Gst.parselaunch("videotestsrc ! autovideosink")

Start playing

pipeline.setstate(Gst.State.PLAYING)

Wait for EOS or error

bus = pipeline.getbus()

msg = bus.timedpopfiltered(

Gst.CLOCKTIMENONE,

Gst.MessageType.ERROR | Gst.MessageType.EOS

)

Stop pipeline

pipeline.setstate(Gst.State.NULL)

2. Pipeline with Event Handling

#!/usr/bin/env python3

import gi

gi.requireversion('Gst', '1.0')

from gi.repository import Gst, GLib

Gst.init(None)

class VideoPlayer:

def init(self, uri):

self.pipeline = Gst.ElementFactory.make("playbin", "player")

self.pipeline.setproperty("uri", uri)

# Setup bus for messages

bus = self.pipeline.getbus()

bus.addsignalwatch()

bus.connect("message", self.onmessage)

self.loop = GLib.MainLoop()

def onmessage(self, bus, message):

t = message.type

if t == Gst.MessageType.EOS:

print("End of stream")

self.stop()

elif t == Gst.MessageType.ERROR:

err, debug = message.parseerror()

print(f"Error: {err}, {debug}")

self.stop()

elif t == Gst.MessageType.STATECHANGED:

if message.src == self.pipeline:

old, new, pending = message.parsestatechanged()

print(f"State changed: {old.valuenick} -> {new.valuenick}")

def play(self):

self.pipeline.setstate(Gst.State.PLAYING)

self.loop.run()

def stop(self):

self.pipeline.setstate(Gst.State.NULL)

self.loop.quit()

Usage

player = VideoPlayer("file:///path/to/video.mp4")

player.play()

3. Custom Pipeline with OpenCV Integration

#!/usr/bin/env python3

import gi

gi.requireversion('Gst', '1.0')

from gi.repository import Gst, GLib

import numpy as np

import cv2

Gst.init(None)

class GStreamerOpenCV:

def init(self):

# Pipeline: webcam -> appsink

pipelinestr = (

"v4l2src device=/dev/video0 ! "

"video/x-raw,width=640,height=480,framerate=30/1 ! "

"videoconvert ! "

"video/x-raw,format=BGR ! "

"appsink name=sink emit-signals=true sync=false max-buffers=1 drop=true"

)

self.pipeline = Gst.parselaunch(pipelinestr)

# Get appsink

self.sink = self.pipeline.getbyname("sink")

self.sink.connect("new-sample", self.onnewsample)

self.frame = None

self.running = True

def onnewsample(self, sink):

sample = sink.emit("pull-sample")

if sample:

buffer = sample.getbuffer()

caps = sample.getcaps()

# Get dimensions

struct = caps.getstructure(0)

width = struct.getvalue("width")

height = struct.getvalue("height")

# Extract frame data

success, mapinfo = buffer.map(Gst.MapFlags.READ)

if success:

# Convert to numpy array

self.frame = np.ndarray(

shape=(height, width, 3),

dtype=np.uint8,

buffer=mapinfo.data

).copy()

buffer.unmap(mapinfo)

return Gst.FlowReturn.OK

def run(self):

self.pipeline.setstate(Gst.State.PLAYING)

while self.running:

if self.frame is not None:

# Process frame with OpenCV

processed = self.frame.copy()

# Example: Add rectangle and text

cv2.rectangle(processed, (50, 50), (200, 200), (0, 255, 0), 2)

cv2.putText(processed, "GStreamer + OpenCV",

(10, 30), cv2.FONTHERSHEYSIMPLEX,

0.7, (0, 255, 0), 2)

# Display

cv2.imshow("GStreamer OpenCV", processed)

key = cv2.waitKey(1) & 0xFF

if key == ord('q'):

self.running = False

self.pipeline.setstate(Gst.State.NULL)

cv2.destroyAllWindows()

Run

app = GStreamerOpenCV()

app.run()

4. Pipeline for Deep Learning Inference

#!/usr/bin/env python3

import gi

gi.requireversion('Gst', '1.0')

from gi.repository import Gst, GLib

import numpy as np

import cv2

from ultralytics import YOLO

Gst.init(None)

class GStreamerYOLO:

def init(self):

# Load YOLO model

self.model = YOLO('yolov8n.pt')

# GStreamer pipeline

pipelinestr = (

"v4l2src device=/dev/video0 ! "

"video/x-raw,width=640,height=480,framerate=30/1 ! "

"videoconvert ! "

"video/x-raw,format=BGR ! "

"appsink name=sink emit-signals=true sync=false max-buffers=1 drop=true"

)

self.pipeline = Gst.parselaunch(pipelinestr)

self.sink = self.pipeline.getbyname("sink")

self.sink.connect("new-sample", self.onnewsample)

self.frame = None

self.running = True

def onnewsample(self, sink):

sample = sink.emit("pull-sample")

if sample:

buffer = sample.getbuffer()

caps = sample.getcaps()

struct = caps.getstructure(0)

width = struct.getvalue("width")

height = struct.getvalue("height")

success, mapinfo = buffer.map(Gst.MapFlags.READ)

if success:

self.frame = np.ndarray(

shape=(height, width, 3),

dtype=np.uint8,

buffer=mapinfo.data

).copy()

buffer.unmap(mapinfo)

return Gst.FlowReturn.OK

def run(self):

self.pipeline.setstate(Gst.State.PLAYING)

while self.running:

if self.frame is not None:

# Run YOLO inference

results = self.model(self.frame, verbose=False)

# Draw results

annotated = results[0].plot()

# Display

cv2.imshow("GStreamer + YOLO", annotated)

key = cv2.waitKey(1) & 0xFF

if key == ord('q'):

self.running = False

self.pipeline.setstate(Gst.State.NULL)

cv2.destroyAllWindows()

Run

app = GStreamerYOLO()

app.run()

Hardware Acceleration

1. NVIDIA GPU (NVENC/NVDEC)

Install plugin:

sudo apt install -y gstreamer1.0-plugins-bad

Encode with NVENC:

gst-launch-1.0 v4l2src device=/dev/video0 ! \

videoconvert ! nvh264enc ! \

h264parse ! mp4mux ! \

filesink location=output.mp4

Decode with NVDEC:

gst-launch-1.0 filesrc location=video.mp4 ! \

qtdemux ! h264parse ! nvh264dec ! \

videoconvert ! autovideosink

2. Intel Quick Sync (VAAPI)

Install plugin:

sudo apt install -y gstreamer1.0-vaapi

Encode:

gst-launch-1.0 v4l2src device=/dev/video0 ! \

videoconvert ! vaapih264enc ! \

h264parse ! mp4mux ! \

filesink location=output.mp4

Decode:

gst-launch-1.0 filesrc location=video.mp4 ! \

qtdemux ! h264parse ! vaapih264dec ! \

videoconvert ! autovideosink

3. Check Hardware Acceleration

# List VAAPI elements

gst-inspect-1.0 | grep vaapi

List NVIDIA elements

gst-inspect-1.0 | grep nv

Test VAAPI

vainfo

Troubleshooting

1. No Video Output

# Check video device

ls -la /dev/video

Check video capabilities

v4l2-ctl --device=/dev/video0 --list-formats-ext

Test with verbose

GSTDEBUG=3 gst-launch-1.0 v4l2src device=/dev/video0 ! autovideosink

2. Missing Plugins

# Install missing plugin

gst-inspect-1.0 x264enc

If not found:

sudo apt install gstreamer1.0-plugins-ugly

3. Permission Denied

# Add user to video group

sudo usermod -aG video $USER

Logout and login again

4. Debug Pipeline

# Enable debug output

GSTDEBUG=3 gst-launch-1.0 pipeline...

Debug specific element

GSTDEBUG=v4l2src:5 gst-launch-1.0 pipeline...

Generate DOT graph

GSTDEBUGDUMPDOTDIR=/tmp gst-launch-1.0 pipeline...

dot -Tpng /tmp/.dot -o pipeline.png

Best Practices

1. Pipeline Design

  • Use queue for buffering between elements
  • Use tee to split streams
  • Always use videoconvert for compatibility
  • Set sync=false for low latency

2. Performance

  • Use hardware acceleration when available
  • Reduce resolution for processing
  • Use drop=true on appsink for real-time
  • Tune bitrate according to bandwidth

3. Error Handling

  • Always handle EOS and ERROR messages
  • Implement proper state transitions
  • Clean up resources by setting state to NULL

Conclusion

GStreamer is a very powerful framework for multimedia processing on Linux. By understanding pipeline concepts, elements, and available tools, you can build various multimedia applications from simple playback to complex video processing with deep learning integration.

Key takeaways:

  • Install all plugin groups for maximum compatibility
  • Use gst-inspect to explore available elements
  • Build pipelines incrementally for debugging
  • Leverage hardware acceleration for performance
  • Integrate with Python/OpenCV for advanced processing
  • Related Articles

    Apache Kafka for Real-Time ML Tutorial: Streaming Data Pipeline

    Tutorial 13: Apache Kafka untuk Pipeline ML Real-Time Daftar Isi Pendahuluan Prasyarat Memahami Apache Kafka [Menyiapkan...

    nvidia docker

    Complete Guide: Installing NVIDIA Docker on Ubuntu

    NVIDIA Docker, officially known as NVIDIA Container Toolkit, enables Docker containers to access NVIDIA GPUs natively on...

    LocalAI: Run AI Models Locally with an OpenAI-Compatible API

    LocalAI: Menjalankan Model AI Secara Lokal dengan API Kompatibel OpenAI Penulis: Ruby Abdullah, PT RUBYTHALIB DATA KONSU...

    Complete LlamaFile Tutorial: Running LLMs as Single Executable Files

    LlamaFile: Menjalankan LLM sebagai File Eksekutabel Tunggal Penulis: Ruby Abdullah Kategori: Tutorial Tags: LlamaFile, L...