Skip to content

Zig server library for converting RTSP streams to HLS format. easily set up a streaming server that can receive RTSP streams and serve them as HLS for browser-based playback

License

Notifications You must be signed in to change notification settings

bkataru-workshop/zonic

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Zonic: RTSP to HLS Streaming in Zig

Zonic is a Zig-based library for converting RTSP streams to HLS format. It allows you to easily set up a streaming server that can receive RTSP streams and serve them as HLS for browser-based playback.

Features

  • Receive RTSP streams from IP cameras, stream servers, and other RTSP sources
  • Convert the streams to HLS format on-the-fly
  • Serve the HLS streams via HTTP/HTTPS for browser playback
  • Support for multiple concurrent streams
  • Low latency streaming with IDR frame alignment
  • Configurable segment duration and retention policy
  • Simple and efficient pure Zig implementation
  • CORS support for cross-domain requests
  • Authentication support for RTSP sources
  • Zero-copy processing for optimal performance
  • Robust reconnection handling
  • RESTful API for stream management
  • Interactive UI with HTMX for managing streams

Requirements

  • Zig 0.13.0 or later
  • zvdk library (included as dependency)

Installation

Using Zig Package Manager

Add Zonic as a dependency in your build.zig.zon file:

.{
    .name = "your_project",
    .version = "0.1.0",
    .dependencies = .{
        .zonic = .{
            .url = "https://github.com/yourusername/zonic/archive/refs/tags/v0.1.0.tar.gz",
            .hash = "...", // Replace with actual hash after first resolution
        },
    },
}

Then, in your build.zig file:

const zonic_dep = b.dependency("zonic", .{
    .target = target,
    .optimize = optimize,
});
exe.addModule("zonic", zonic_dep.module("zonic"));

Manual Installation

  1. Clone the repository:

    git clone https://github.com/yourusername/zonic.git
    
  2. Build the project:

    cd zonic
    zig build
    

Usage

Basic Example

const std = @import("std");
const zonic = @import("zonic");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    // Initialize the service
    var service = try zonic.service.Service.init(allocator, "config.json");
    defer service.deinit();

    // Start the service with API on port 8888
    try service.start(8888);

    // Keep the program running
    while (true) {
        std.time.sleep(1 * std.time.ns_per_s);
    }
}

Configuration File Example

{
  "hls_server": {
    "port": 8080,
    "segment_base_dir": "segments",
    "cors": {
      "enabled": true,
      "allow_origin": "*"
    },
    "ssl": {
      "enabled": false,
      "cert_file": "/path/to/cert.pem",
      "key_file": "/path/to/key.pem"
    },
    "cache_control": "no-cache"
  },
  "streams": [
    {
      "id": "camera1",
      "name": "Front Door Camera",
      "rtsp_url": "rtsp://192.168.1.100:554/stream",
      "segment_duration_ms": 3000,
      "max_segments": 6,
      "auth": {
        "username": "admin",
        "password": "password"
      },
      "enabled": true,
      "reconnect_attempts": 5,
      "reconnect_delay_ms": 5000
    }
  ]
}

HTTP Server Example with HTMX

Zonic includes a complete HTTP server example that serves HLS streams and provides a web interface for viewing and managing streams:

cd zonic
zig build run-http-example

This will start the server with the default config. To specify a custom config:

zig build run-http-example -- --config my-config.json --api-port 9000 --log-level debug

API Documentation

Zonic provides a RESTful API for managing streams and configurations:

Stream Management

  • GET /api/streams - List all configured streams
  • POST /api/streams - Add a new stream
  • GET /api/streams/:id - Get stream details
  • PUT /api/streams/:id - Update stream configuration
  • DELETE /api/streams/:id - Remove a stream

Configuration Management

  • GET /api/config - Get current configuration
  • PUT /api/config - Update configuration

Status Information

  • GET /api/status - Get server status and statistics

Advanced Features

Zero-Copy Processing

Zonic uses zero-copy processing for optimal performance when handling video frames, reducing memory usage and CPU overhead.

IDR Frame Alignment

HLS segments are aligned with IDR frames to ensure smooth playback and proper seeking.

Authentication

Zonic supports authentication for RTSP sources, with support for both basic and token-based authentication.

HTTPS Support

HLS streams can be served over HTTPS by providing SSL certificate and key files in the configuration.

CORS Support

Cross-origin resource sharing (CORS) is supported for allowing HLS playback from different domains.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Built on the zvdk library for RTSP and TS handling
  • Inspired by the need for efficient RTSP to HLS conversion in Zig

Testing

Zonic includes a comprehensive test suite with unit tests, integration tests, and performance tests. The test infrastructure is designed to ensure code quality and maintain performance standards.

Running Tests

You can run different types of tests using the following commands:

# Run all tests
zig build test

# Run only unit tests
zig build test-runner -- --type unit

# Run only integration tests
zig build test-runner -- --type integration

# Run only performance tests
zig build test-perf

# Run all tests and generate a report
zig build test-with-report

Test Structure

The test suite is organized into three main categories:

  1. Unit Tests (test/unit/)

    • Tests individual components in isolation
    • Fast execution, suitable for CI/CD
    • Covers core functionality:
      • RTSP client
      • HLS server
      • Stream management
      • Configuration handling
  2. Integration Tests (test/integration/)

    • Tests component interactions
    • Verifies end-to-end functionality
    • Includes:
      • Complete streaming pipeline
      • Stream reconnection
      • Error handling scenarios
  3. Performance Tests (test/performance/)

    • Measures system performance
    • Monitors resource usage
    • Tests include:
      • High load scenarios
      • Memory usage
      • CPU utilization
      • Concurrent stream handling

Test Reports

When running tests with the test-with-report option, a detailed report is generated in Markdown format at test_results/report.md. The report includes:

  • Test execution timestamps
  • Results for each test category
  • Performance metrics
  • Error logs (if any)

Writing Tests

When contributing new features, please ensure proper test coverage:

  1. Unit Tests:

    test "Feature Name - Specific Aspect" {
        // Test setup
        const result = try featureFunction();
        try testing.expect(result == expected);
    }
  2. Integration Tests:

    test "Feature Integration" {
        // Setup components
        var component1 = try Component1.init();
        var component2 = try Component2.init();
        
        // Test interaction
        try component1.interactWith(component2);
        
        // Verify results
        try testing.expect(component1.state == expected);
    }
  3. Performance Tests:

    test "Feature Performance" {
        // Setup test scenario
        var system = try System.init();
        
        // Run performance test
        const metrics = try system.runLoadTest();
        
        // Verify performance requirements
        try testing.expect(metrics.responseTime < maxAllowed);
    }

Continuous Integration

The test suite is integrated with our CI/CD pipeline:

  • Unit and integration tests run on every pull request
  • Performance tests run on release branches
  • Test reports are automatically generated and attached to CI artifacts

For more detailed information about testing, see TESTING.md.

About

Zig server library for converting RTSP streams to HLS format. easily set up a streaming server that can receive RTSP streams and serve them as HLS for browser-based playback

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors