Skip to content

[RFC] Create @ceralive/belacoder TypeScript package for type-safe integration #1

@andrescera

Description

@andrescera

Summary

Create a dedicated @ceralive/belacoder package within the CeraUI monorepo to centralize belacoder-related types, utilities, and configuration. This will improve type safety, enable version tracking, and provide a cleaner separation of concerns.

Motivation

Currently, belacoder integration in CeraUI is spread across multiple backend modules:

  • streamloop.ts - Process spawning, lifecycle management
  • encoder.ts - Bitrate control (including SIGHUP handling)
  • pipelines.ts - Pipeline file management
  • audio.ts - Audio pipeline manipulation
  • revisions.ts - Version tracking

This leads to:

  • Duplicated type definitions
  • No formal belacoder version compatibility tracking
  • Harder to test pure utility functions
  • No shared types between frontend and backend

Proposed Package Structure

packages/
  belacoder/
    package.json
    src/
      index.ts
      types/
        pipeline.ts         # Pipeline types and Zod schemas
        hardware.ts         # Hardware types (jetson, n100, rk3588)
        config.ts           # Belacoder config file types (INI format)
        balancer.ts         # Balancer algorithm types
      cli/
        args-builder.ts     # Type-safe CLI argument construction
        version.ts          # Version parsing utilities
      config/
        generator.ts        # Generate belacoder.conf files
        parser.ts           # Parse existing config files
        defaults.ts         # Default configuration values
      pipelines/
        parser.ts           # Parse pipeline files
        audio-patterns.ts   # Audio pattern matchers (alsaSrc, codec patterns)
        constants.ts        # Pipeline paths, defaults
      compatibility/
        hardware-matrix.ts  # Feature compatibility per hardware type

What Goes in the Package

Component Description
Pipeline types/schemas Zod schemas for pipeline configuration
Hardware types HardwareType = 'jetson' | 'n100' | 'rk3588'
Config types Types for belacoder.conf INI sections
Balancer types BalancerAlgorithm = 'adaptive' | 'fixed' | 'aimd'
CLI argument builder Type-safe belacoder argument construction
Config generator Generate valid belacoder.conf files
Pipeline parser Extract audio props, modify pipeline files
Audio patterns alsaSrcPattern, audioCodecPattern, etc.
Version utilities Parse and compare belacoder versions
Constants Paths, defaults, codec mappings

What Stays in CeraUI Backend

Component Reason
Process spawning Bun-specific, coupled to streaming state
Signal handling (HUP) System-level operations
Audio device probing Real-time OS state
Notification broadcasting UI-layer concern

Belacoder CLI Interface (Current)

belacoder PIPELINE_FILE ADDR PORT [options]

Options:
  -v                  Print the version and exit
  -c <config file>    Configuration file (INI format, recommended)
  -d <delay>          Audio-video delay in milliseconds
  -s <streamid>       SRT stream ID
  -l <latency>        SRT latency in milliseconds (default: 2000)
  -r                  Reduced SRT packet size (6 TS packets instead of 7)
  -b <bitrate file>   Bitrate settings file (legacy, use -c instead)
  -a <algorithm>      Bitrate balancer algorithm (overrides config)

Belacoder Config File Format

[general]
min_bitrate = 500    # Kbps
max_bitrate = 6000   # Kbps
balancer = adaptive  # Algorithm: adaptive, fixed, aimd

[srt]
latency = 2000       # ms

[adaptive]
incr_step = 30       # Bitrate increase step (Kbps)
decr_step = 100      # Bitrate decrease step (Kbps)
incr_interval = 500  # Min interval between increases (ms)
decr_interval = 200  # Min interval between decreases (ms)

[aimd]
incr_step = 50       # Additive increase step (Kbps)
decr_mult = 0.75     # Multiplicative decrease factor

Balancer Algorithms

Algorithm Description Best For
adaptive (default) RTT and buffer-based control with graduated response Most use cases, variable networks
fixed Constant bitrate, no adaptation Stable networks, testing
aimd TCP-style Additive Increase Multiplicative Decrease Fair bandwidth sharing

TypeScript Types (Proposed)

// Balancer algorithm type
type BalancerAlgorithm = 'adaptive' | 'fixed' | 'aimd';

// Config file structure
interface BelacoderConfig {
  general: {
    min_bitrate: number;  // Kbps
    max_bitrate: number;  // Kbps
    balancer: BalancerAlgorithm;
  };
  srt?: {
    latency?: number;     // ms
  };
  adaptive?: {
    incr_step?: number;
    decr_step?: number;
    incr_interval?: number;
    decr_interval?: number;
  };
  aimd?: {
    incr_step?: number;
    decr_mult?: number;
  };
}

// CLI options
interface BelacoderCliOptions {
  pipelineFile: string;
  host: string;
  port: number;
  configFile?: string;
  delay?: number;
  streamId?: string;
  latency?: number;
  reducedPacketSize?: boolean;
  bitrateFile?: string;  // legacy
  algorithm?: BalancerAlgorithm;
}

Version Compatibility Tracking

The package.json could include belacoder version compatibility metadata:

{
  "name": "@ceralive/belacoder",
  "version": "1.0.0",
  "belacoderCompatibility": {
    "minVersion": "1.0.0",
    "features": {
      "configFile": "1.0.0",
      "balancerAlgorithms": "1.0.0",
      "packetLossDetection": "1.0.0"
    }
  }
}

Migration Plan

Phase 1: Foundation

  • Create package scaffolding (in ceracoder/bindings/typescript)
  • Extract type definitions (including new balancer types)
  • Move constants (paths, patterns, codec mappings)

Phase 2: Config Support

  • Create config file generator
  • Create config file parser
  • Add Zod schemas for config validation
  • Support all balancer algorithm options

Phase 3: CLI Builder

  • Create CLI argument builder supporting all options
  • Add version parsing utilities (not yet implemented)
  • Handle legacy -b vs new -c option

Phase 4: Integration

  • Update CeraUI backend imports
  • Document hardware compatibility matrix (jetson, n100, rk3588, generic)

Phase 5: Testing

  • Unit tests for pure functions
  • Integration tests with mock pipelines
  • Config generation tests

Benefits

  1. Type Safety - Shared types between frontend/backend
  2. Versioning - Track belacoder compatibility formally
  3. Testing - Pure functions are easily unit testable
  4. Documentation - Centralized integration docs
  5. Maintainability - Clear separation of concerns
  6. Config Management - Type-safe config file generation

Open Questions

  • Should pipeline file templates be versioned/included in this package?
  • How should we handle belacoder breaking changes in the future?
  • Should the package include GStreamer pipeline validation utilities?
  • Should we support runtime balancer switching via SIGHUP?

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentationenhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions