Skip to content

Latest commit

Β 

History

350 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Forge Media Engine

High-Performance RTP and WebRTC Media Engine for Real-Time Communications

Rust License Security

Part of the Ferrous Communications Platform (FCP)


πŸ”¨ What is Forge?

Forge is a carrier-grade media server built in Rust that handles all media processing for real-time communications. It works alongside the Siphon SIP stack to provide comprehensive VoIP capabilities.

Forge is both:

  • πŸ“š A Library: Use in your Rust projects (FCP, custom applications)
  • πŸš€ A Binary: Run as a standalone media server

Key Features

  • 🎡 Audio Processing: G.711, G.722, G.729, Opus codec support with transcoding
  • πŸ“ž RTP/SRTP: Full RFC-compliant RTP handling with SRTP encryption (AES-128-GCM, AES-256-GCM)
  • 🌐 WebRTC: ICE, DTLS, SRTP for browser-based communications
  • πŸ‘₯ Conferencing: Audio mixing, VAD, AGC, dominant speaker detection, host controls, capacity management
  • πŸŽ™οΈ Conference Features: PIN authentication, wait-for-moderator, audio feedback, per-room configuration
  • πŸ“Ό Recording: Multi-format recording with multiple storage backends
  • πŸ€– AI Integration: Real-time voice AI with OpenAI Realtime API, bidirectional audio, DTMF support
  • πŸ” Security: Rate limiting, SSRF protection, path traversal prevention, randomized port allocation, secure defaults
  • πŸ›‘οΈ Enterprise Grade: SIPREC, CAC, DoS protection, production-ready security hardening
  • ⚑ Performance: Async Rust, zero-copy parsing, optional kernel offload

πŸ—οΈ Project Status

Current Phase: Production Ready πŸš€

Core functionality complete and security-hardened. Ready for production deployment with enterprise-grade security features.

What's Working

  • βœ… Project structure and workspace
  • βœ… Core types and configuration system
  • βœ… RTP/RTCP/SRTP packet handling
  • βœ… Session management with bidirectional audio
  • βœ… WebRTC support (ICE, DTLS, SRTP)
  • βœ… Codec Support: G.711 (Β΅-law/A-law), G.722 (wideband), G.729 (with VAD/PLC), Opus
  • βœ… Audio conferencing with mixing
  • βœ… Conference features (PINs, host controls, capacity management)
  • βœ… Audio feedback system with WAV playback
  • βœ… Recording system (WAV, Opus)
  • βœ… AI integration (OpenAI Realtime API, multiple providers)
  • βœ… DTMF detection and handling
  • βœ… Prometheus metrics and monitoring
  • βœ… Security Hardening: Rate limiting, SSRF protection, path validation, secure defaults

What's Completed

See DEVELOPMENT_PLAN.md for the complete roadmap. Major milestones achieved:

  • Phase 0-4: βœ… Foundation through WebRTC & AI Integration (~95% complete)
  • Security Hardening: βœ… All 5 security issues (SEC-001 through SEC-005) resolved

Coming Soon

  • πŸ”œ Advanced transcoding pipelines
  • πŸ”œ High availability features
  • πŸ”œ Enhanced kernel offload (eBPF/XDP)

πŸš€ Quick Start

Prerequisites

  • Rust 1.75 or later
  • C compiler (for native dependencies)
  • OpenSSL development libraries
# Ubuntu/Debian
sudo apt-get install build-essential libssl-dev pkg-config

# macOS
brew install openssl pkg-config

# Fedora/RHEL
sudo dnf install gcc openssl-devel pkg-config

Build

# Clone the repository
git clone https://github.com/ferrous-comms/forge-media
cd forge-media

# Build all crates
cargo build

# Build with all features
cargo build --features full

# Build release version
cargo build --release

Run as Binary

# Run with default configuration (localhost-only, safe for development)
cargo run

# Run with custom config
cargo run -- --config /path/to/config.toml

# Run with debug logging
RUST_LOG=forge=debug cargo run

Use as Library

Add to your Cargo.toml:

[dependencies]
forge-media = { path = "../forge-media" }
# Or from git:
# forge-media = { git = "https://github.com/ferrous-comms/forge-media" }

# Optional: Choose features
forge-media = { path = "../forge-media", features = ["full"] }

Then in your code:

use forge_media::{ForgeEngine, ForgeConfig, CallId};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create engine with default config
    let config = ForgeConfig::default();
    let engine = ForgeEngine::new(config).await?;

    // Use the engine in your application
    // let session = engine.create_session(...).await?;

    Ok(())
}

πŸ” Security & Configuration

Forge is designed with security-first defaults and comprehensive hardening for production deployments.

Security Features

βœ… Secure by Default

  • Localhost-only binding by default (127.0.0.1:8080)
  • CORS disabled by default
  • Startup guard prevents insecure configurations
  • Empty auth token list requires explicit configuration

βœ… Rate Limiting

  • Per-IP rate limiting with configurable windows
  • X-Forwarded-For validation with trusted proxy list
  • Protection against IP spoofing attacks

βœ… SSRF Protection

  • AI endpoint allowlist with validation
  • Private IP and loopback address blocking
  • HTTPS/WSS enforcement for external connections

βœ… Path Traversal Prevention

  • Jail-root validation for recording directories
  • Symlink rejection and canonicalization
  • PID-scoped writeability testing

βœ… Port Randomization

  • Double-randomized RTP port allocation
  • Prevents predictable port scanning
  • Reduces session hijacking risk

βœ… Secret Management

  • SecureString type with automatic redaction
  • API keys protected in logs, metrics, and JSON output
  • Safe deserialization with placeholder rejection

Configuration

Development (Default):

[api]
http_bind = "127.0.0.1:8080"  # Localhost only
enable_cors = false
auth_tokens = []  # No auth required for localhost

Production Deployment:

[api]
# Bind to public interface (requires auth + HTTPS)
http_bind = "0.0.0.0:8080"
enable_https = true
https_bind = "0.0.0.0:8443"
tls_cert = "/etc/forge/certs/fullchain.pem"
tls_key = "/etc/forge/certs/privkey.pem"
auth_tokens = ["your-secure-token-here"]

# CORS (optional, only if needed)
enable_cors = true
cors_origins = ["https://app.example.com"]

# Rate limiting
rate_limit_requests_per_window = 100
rate_limit_window_secs = 60

# Trusted proxies (for X-Forwarded-For)
trusted_proxies = ["10.0.1.100", "10.0.1.101"]

[recording]
base_dir = "/var/lib/forge/recordings"
root_jail = "/var/lib/forge"  # All recordings must be within this directory

[ai]
allowed_endpoints = [
    "https://api.openai.com",
    "https://api.anthropic.com"
]

Copy the example configuration and customize:

cp config/forge.toml.example /etc/forge/config.toml
# Edit /etc/forge/config.toml

See config/forge.toml.example for complete production deployment template with all security options.

πŸ“– Security Documentation:


🎡 Codec Support

Forge supports a comprehensive range of audio codecs for different use cases:

Codec Comparison Matrix

Codec Bit Rate Sample Rate Frame Size Latency Use Case Quality
G.711 (Β΅-law/A-law) 64 kbps 8 kHz 160 samples (20ms) ~20ms Legacy PSTN, high compatibility Toll quality
G.722 48-64 kbps 16 kHz 320 samples (20ms) ~20ms HD Voice, wideband Wideband
G.729 8 kbps 8 kHz 80 samples (10ms) ~25ms Low bandwidth, mobile Near toll quality
Opus 6-510 kbps 8-48 kHz Variable (2.5-60ms) 2.5-60ms Internet, WebRTC Excellent

Codec Features

G.711 (Β΅-law/A-law)

  • Status: βœ… Fully implemented
  • Format: PCM-based, log-companded
  • Variants: Β΅-law (North America, Japan), A-law (Europe, rest of world)
  • Use: PSTN interoperability, maximum compatibility
  • Pros: No licensing, minimal CPU, universal support
  • Cons: High bandwidth, narrowband only

G.722

  • Status: βœ… Fully implemented with ITU-T compliance
  • Format: Sub-band ADPCM with QMF (Quadrature Mirror Filter)
  • Features:
    • 64/56/48 kbps modes
    • Auxiliary bit support for data embedding
    • ITU threshold-based quantization with Gray coding
  • Use: HD Voice on VoIP, conference systems
  • Pros: Wideband (7 kHz bandwidth), no licensing, excellent quality
  • Cons: Higher CPU than G.711, fixed 64 kbps default

G.729

  • Status: βœ… Fully implemented via bcg729 FFI
  • Format: CS-ACELP (Conjugate-Structure Algebraic-Code-Excited Linear-Prediction)
  • Features:
    • G.729 Annex A (standard 8 kbps)
    • G.729 Annex B (VAD/DTX for bandwidth savings)
    • Packet Loss Concealment (PLC)
    • Length-prefixed framing for variable-length VAD frames
  • Use: Mobile networks, satellite links, low-bandwidth scenarios
  • Pros: Very low bandwidth, good quality, patents expired
  • Cons: Higher CPU than G.711/G.722, narrowband only
  • Requirements: libbcg729-dev package, enable with --features g729
  • See: G.729 Integration Guide for detailed usage

Opus

  • Status: βœ… Fully implemented
  • Format: Hybrid SILK + CELT
  • Features:
    • Adaptive bit rate (6-510 kbps)
    • Multiple bandwidth modes (narrowband to fullband)
    • Built-in FEC (Forward Error Correction)
    • Ultra-low latency option
  • Use: WebRTC, VoIP, music streaming
  • Pros: Best quality/bandwidth ratio, flexible, low latency, royalty-free
  • Cons: Higher complexity than legacy codecs

Feature Flags

Enable specific codecs in your Cargo.toml:

[dependencies]
forge-codecs = { version = "0.2", features = ["g729", "opus"] }

# Or enable all codecs
forge-codecs = { version = "0.2", features = ["all-codecs"] }

Transcoding

Forge automatically transcodes between codecs when needed:

  • Conference mixing (multiple codecs β†’ common format β†’ mix β†’ transcode per participant)
  • RTP forwarding (codec negotiation mismatch)
  • Recording (input codec β†’ target codec for storage)

See the Coming Soon section for advanced transcoding pipeline features.


πŸ“š Architecture

Forge follows a modular, layered architecture:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    Control Plane                         β”‚
β”‚  HTTP REST API β”‚ WebSocket Events β”‚ Metrics             β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                       β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    Media Plane                           β”‚
β”‚  Sessions β”‚ Conferencing β”‚ Transcoding β”‚ Recording      β”‚
β”‚  RTP/RTCP β”‚ SRTP β”‚ Jitter Buffer β”‚ DTMF                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                       β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              Kernel Offload (Optional)                   β”‚
β”‚  eBPF/XDP β”‚ Userspace Fallback                          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Crate Structure

forge-media/
β”œβ”€β”€ forge-core                  # Common types, traits, utilities
β”œβ”€β”€ forge-rtp                   # RTP/RTCP/SRTP implementation
β”œβ”€β”€ forge-engine                # Core engine and session management
β”œβ”€β”€ forge-codecs                # Audio codec implementations (G.711, Opus, etc.)
β”œβ”€β”€ forge-resampler             # Audio sample rate conversion
β”œβ”€β”€ forge-transcoder            # Audio transcoding pipeline
β”œβ”€β”€ forge-storage               # Recording storage management
β”œβ”€β”€ forge-recorder              # Audio recording (WAV, Opus)
β”œβ”€β”€ forge-mixer                 # Multi-party audio mixing
β”œβ”€β”€ forge-video                 # Video frames, scaling, layouts + compositor, clock, flavors, codec traits
β”œβ”€β”€ forge-video-codecs          # libvpx / OpenH264 / dav1d / SVT-AV1 bindings behind cargo features
β”œβ”€β”€ forge-conference-processor  # Conference bridge management
β”œβ”€β”€ forge-recording             # Recording system
β”œβ”€β”€ forge-dtmf                  # DTMF detection and generation
β”œβ”€β”€ forge-transcription         # Real-time transcription
β”œβ”€β”€ forge-injection             # Audio injection and TTS
β”œβ”€β”€ forge-webrtc                # WebRTC support (ICE, DTLS)
β”œβ”€β”€ forge-sdp                   # SDP parsing and generation
β”œβ”€β”€ forge-siprec                # SIPREC (RFC 7865/7866)
β”œβ”€β”€ forge-ai-stream             # AI streaming integration
β”œβ”€β”€ forge-ha                    # High availability
β”œβ”€β”€ forge-kernel                # Kernel offload (eBPF/XDP)
└── forge-api                   # HTTP/WebSocket API with security

See FORGE ARCHITECTURE.md for detailed design.


πŸ€– AI Integration

Forge provides seamless integration with real-time AI services like OpenAI's Realtime API for voice agents, IVR systems, and AI-powered call features.

Quick Example

# Attach AI to an active call
curl -X POST http://localhost:8080/v1/sessions/call-001/ai \
  -H "Content-Type: application/json" \
  -d '{
    "api_key": "sk-your-key-here",
    "model": "gpt-4o-realtime-preview-2024-12-17",
    "voice": "alloy",
    "instructions": "You are a helpful customer service agent."
  }'

Features

  • Bidirectional Audio: Automatic RTP ↔ AI audio routing with codec conversion
  • DTMF Integration: Forward DTMF events to AI for IVR scenarios
  • Function Calling: Let AI trigger actions (transfers, lookups, etc.)
  • Recording: SIPREC support with AI metadata for compliance
  • Multi-Codec: G.711, Opus with automatic sample rate conversion
  • Secure: API keys redacted in all logs/metrics, SSRF protection with endpoint allowlist

See AI Integration Guide for complete documentation.


πŸ”Œ API Reference

REST API

Sessions

# Create session
POST /v1/sessions
{
  "call_id": "call-123",
  "sdp": "v=0\r\no=- ..."
}

# Get session
GET /v1/sessions/:call_id

# Delete session
DELETE /v1/sessions/:call_id

Conferences

# Create conference
POST /v1/conferences
{
  "room_id": "room-456"
}

# Configure room
POST /v1/conferences/:room_id/configure
{
  "guest_pin": "1234",
  "host_pin": "9999",
  "max_channels": 100,
  "wait_for_moderator": true,
  "require_guest_pin": true
}

# Get room configuration
GET /v1/conferences/:room_id/config

# Add participant
POST /v1/conferences/:room_id/participants
{
  "participant_id": "user-123",
  "is_host": false
}

# List participants with host status
GET /v1/conferences/:room_id/participants

# List waiting participants
GET /v1/conferences/:room_id/waiting

# Promote participant to host
POST /v1/conferences/:room_id/participants/:id/promote
{
  "host_pin": "9999"
}

# Start recording
POST /v1/conferences/:room_id/recording
{
  "output_path": "conference-123.wav"
}

Recording

# Start recording
POST /v1/recordings
{
  "target": "session_leg",
  "call_id": "call-123",
  "format": "opus"
}

AI Integration

# Attach AI to session
POST /v1/sessions/:call_id/ai
{
  "api_key": "sk-your-key",
  "model": "gpt-4o-realtime-preview-2024-12-17",
  "voice": "alloy",
  "instructions": "You are a helpful assistant."
}

# Get AI status
GET /v1/sessions/:call_id/ai

# Detach AI
DELETE /v1/sessions/:call_id/ai

# Send function response
POST /v1/sessions/:call_id/ai/function-response

Metrics

# JSON metrics
GET /v1/metrics

# Prometheus metrics
GET /metrics

See API Documentation for complete reference.


πŸ§ͺ Testing

# Run all tests
cargo test

# Run with logging
RUST_LOG=debug cargo test -- --nocapture

# Run integration tests only
cargo test --test '*'

# Run benchmarks
cargo bench

# Security tests
cargo test --package forge-api validate
cargo test --package forge-rtp port_pool

πŸ“ˆ Performance

Forge is designed for carrier-grade performance:

  • 1,000+ concurrent sessions per instance
  • <1ms packet forwarding latency (p99)
  • <20ms conference mixing latency
  • 100,000+ packets per second
  • <10Β΅s RTP forwarding with kernel offload (XDP)

Benchmarks

# RTP packet processing
cargo bench --package forge-rtp

# SRTP encryption/decryption
cargo bench --package forge-rtp srtp

# Codec transcoding
cargo bench --package forge-codecs

# Conference mixing
cargo bench --package forge-mixer

See DEVELOPMENT_PLAN.md for detailed targets.


🀝 Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

Development Setup

# Install development tools
cargo install cargo-watch cargo-edit cargo-nextest

# Run tests on file change
cargo watch -x test

# Format code
cargo fmt

# Lint code
cargo clippy -- -D warnings

πŸ“„ Documentation

Architecture & Design

Integration Guides

Security & Operations


πŸ”— Related Projects

  • Siphon - SIP stack for signaling
  • Ferrous Communications Platform - Complete UC platform

πŸ“ License

Licensed under either of:

at your option.


πŸ™ Acknowledgments

Forge is built with these excellent Rust crates:


πŸ”¨ Forging Connections, One Stream at a Time

Report Bug Β· Request Feature Β· Documentation

About

Forge is a high-performance RTP and WebRTC media engine for real-time communications. It handles all media processing for the Ferrous Communications Platform, working alongside the Siphon SIP stack.

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages