Tutorial Setup GStreamer di Ubuntu: Panduan Lengkap

# 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

Tutorial Setup GStreamer di Ubuntu: Panduan Lengkap

GStreamer adalah framework multimedia open-source yang powerful untuk membangun aplikasi streaming, video processing, dan media handling. Tutorial ini akan membahas instalasi, konfigurasi, dan penggunaan GStreamer di Ubuntu secara lengkap.

Apa itu GStreamer?

GStreamer adalah pipeline-based multimedia framework yang memungkinkan Anda untuk:

  • Memutar dan merekam audio/video
  • Streaming media melalui jaringan
  • Transcoding dan konversi format
  • Video processing dan filtering
  • Membangun aplikasi multimedia custom

Konsep Utama:
  • Pipeline: Rangkaian elements yang terhubung untuk memproses media
  • Elements: Unit pemrosesan individual (source, filter, sink)
  • Pads: Titik koneksi antar elements
  • Caps: Capabilities yang mendefinisikan format data

Instalasi GStreamer di Ubuntu

1. Update System

sudo apt update

sudo apt upgrade -y

2. Install GStreamer Core dan Tools

# GStreamer core

sudo apt install -y gstreamer1.0-tools

Good plugins (berkualitas baik, open source)

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

Bad plugins (berkualitas baik tapi dengan licensing issues)

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

Ugly plugins (berkualitas baik tapi dengan patent issues)

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

Base plugins

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

Libav plugins (untuk codecs tambahan)

sudo apt install -y gstreamer1.0-libav

Development libraries

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

3. Install Plugins Tambahan

# 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 untuk GTK integration

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

5. Verifikasi Instalasi

# Check GStreamer version

gst-launch-1.0 --version

List semua plugins

gst-inspect-1.0 | head -50

Check specific plugin

gst-inspect-1.0 v4l2src

Check total plugins

gst-inspect-1.0 | wc -l

Output yang diharapkan:

gst-launch-1.0 version 1.20.3

GStreamer 1.20.3

GStreamer Command Line Tools

1. gst-launch-1.0

Tool utama untuk membangun dan menjalankan pipelines.

Syntax dasar:
gst-launch-1.0 element1 ! element2 ! element3

! adalah operator untuk menghubungkan elements. Contoh: Test video pattern
gst-launch-1.0 videotestsrc ! autovideosink

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

2. gst-inspect-1.0

Tool untuk inspeksi elements dan plugins.

# List semua 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 untuk menganalisis file media.

gst-discoverer-1.0 video.mp4

Pipeline Dasar

1. Playback Video File

# Playback video dengan audio

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

Playback dengan audio dan video

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

2. Playback Audio File

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

3. Capture dari Webcam

# Display webcam

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

Webcam dengan resolusi spesifik

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

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

videoconvert ! autovideosink

4. Record Video dari Webcam

# Record ke file MP4

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

videoconvert ! x264enc ! mp4mux ! \

filesink location=output.mp4

Record dengan 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 ke WebM

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

videoconvert ! vp8enc ! webmmux ! \

filesink location=output.webm

Convert dengan 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

Buat 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 untuk stream

factory = GstRtspServer.RTSPMediaFactory()

# Pipeline untuk 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()

Jalankan server:

python3 rtspserver.py

2. Client RTSP

# Play RTSP stream

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

decodebin ! videoconvert ! autovideosink

Play dengan latency rendah

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 derajat

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 dengan 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 untuk 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 dengan 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 dengan OpenCV

processed = self.frame.copy()

# Contoh: Add rectangle dan 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 untuk 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 dengan NVENC:

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

videoconvert ! nvh264enc ! \

h264parse ! mp4mux ! \

filesink location=output.mp4

Decode dengan 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 dengan verbose

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

2. Missing Plugins

# Install missing plugin

gst-inspect-1.0 x264enc

Jika tidak ada:

sudo apt install gstreamer1.0-plugins-ugly

3. Permission Denied

# Add user ke video group

sudo usermod -aG video $USER

Logout dan login kembali

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

  • Gunakan queue untuk buffering antar elements
  • Gunakan tee untuk split stream
  • Selalu gunakan videoconvert untuk compatibility
  • Set sync=false untuk low latency

2. Performance

  • Gunakan hardware acceleration jika tersedia
  • Reduce resolution untuk processing
  • Gunakan drop=true pada appsink untuk real-time
  • Tune bitrate sesuai bandwidth

3. Error Handling

  • Selalu handle EOS dan ERROR messages
  • Implement proper state transitions
  • Clean up resources dengan set state ke NULL

Kesimpulan

GStreamer adalah framework yang sangat powerful untuk multimedia processing di Linux. Dengan memahami konsep pipeline, elements, dan tools yang tersedia, Anda dapat membangun berbagai aplikasi multimedia dari simple playback hingga complex video processing dengan deep learning integration.

Key takeaways:

  • Install semua plugin groups untuk compatibility maksimal
  • Gunakan gst-inspect untuk explore available elements
  • Build pipelines incrementally untuk debugging
  • Leverage hardware acceleration untuk performance
  • Integrate dengan Python/OpenCV untuk advanced processing
  • Artikel Terkait

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

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

    nvidia docker

    Tutorial Lengkap Install NVIDIA Docker di Ubuntu

    NVIDIA Docker atau NVIDIA Container Toolkit memungkinkan Docker container mengakses GPU NVIDIA secara langsung di Ubuntu...

    AutoGluon: Tutorial Lengkap Library AutoML dari AWS untuk Machine Learning Otomatis

    Tutorial Lengkap AutoGluon: Library AutoML dari AWS untuk Machine Learning Otomatis AutoGluon adalah library open-source...

    Tutorial Lengkap LM Evaluation Harness: Framework Standar untuk Evaluasi Model Bahasa Besar

    Tutorial Lengkap LM Evaluation Harness: Framework Standar untuk Evaluasi Model Bahasa Besar Evaluasi model bahasa besar ...