- Build:
go build -o karl - Run:
go run . - Test:
go test ./... - Test with race detector:
go test -race ./... - Test specific package:
go test ./internal/ng_protocol/commands/ - Test with coverage:
go test -cover ./... - Static analysis:
go vet ./... - Format:
go fmt ./...
- Imports: Group stdlib first, third-party next, project imports last; alphabetize within groups
- Formatting: Use tabs for indentation; run
go fmtbefore commits - Types: Use defined structs with clear purpose; implement interfaces when appropriate
- Naming: CamelCase for exported (public) items; camelCase for unexported (private) items
- Error Handling: Return errors with context using
fmt.Errorf("msg: %w", err); log errors before returning - Concurrency: Use
sync.Mutexfor shared state on CallLeg fields (IP, Port, LastActivity, blocking flags). Useatomicfor counters (PacketsSent, PacketsRecv, etc.). Usesession.mufor session-level fields. Never holdsession.muwhile callingRelay.Stop()(deadlock risk). - Resource cleanup: Use
deferfor socket cleanup in offer/answer error paths. Always stop relay before closing sockets.
Karl is an RTP media proxy that acts as a drop-in replacement for rtpengine, handling SIP proxy NG protocol commands and forwarding RTP between call legs.
SIP Proxy (OpenSIPS/Kamailio)
│
▼ NG Protocol (bencode over UDP/Unix socket)
ng_socket_listener.go
│
▼ dispatches by command name
commands/offer.go ─── creates session + caller leg with UDP sockets
commands/answer.go ── creates callee leg, starts MediaRelay
commands/delete.go ── stops relay, closes sockets, frees session
Caller ──RTP──▶ [CallerLeg.Conn] ──readLoop──▶ [CalleeLeg.Conn] ──WriteToUDP──▶ Callee
Callee ──RTP──▶ [CalleeLeg.Conn] ──readLoop──▶ [CallerLeg.Conn] ──WriteToUDP──▶ Caller
Each session has one MediaRelay with two readLoop goroutines (one per direction). The relay handles:
- Port latching: Learn remote address from first packet (symmetric RTP / NAT traversal)
- Media handover: Allow source address change mid-call (phone roaming)
- Strict source: Reject packets from unexpected addresses
- Media blocking / silencing: Drop or zero-fill packets per flag
- Recording hook:
OnPacketcallback sends RTP payload to recording manager - Media timeout: Auto-delete session when both legs are idle
MediaSession(session_manager.go): Holds CallID, tags, CallerLeg, CalleeLeg, Relay, flags, statsCallLeg(session_manager.go): IP/Port (remote), LocalIP/LocalPort, Conn (UDP socket), NAT flags, stats countersMediaRelay(media_relay.go): Two readLoop goroutines, stopCh, WaitGroup, OnPacket/OnTimeout hooksSessionRegistry(session_manager.go): Map of sessions indexed by ID, CallID, FromTag, SSRC; TTL cleanup
CallLeg.muprotects:IP,Port,LastActivity,MediaBlocked,SilencedCallLegstats (PacketsSent,PacketsRecv, etc.) useatomicoperations — read withLoadStats()MediaSession.muprotects session-level fields. Never hold it while callingRelay.Stop().SessionRegistry.muprotects the session maps.removeSessionLockedstops relay before acquiringsession.mu.
karl/
├── main.go, server.go, services.go, config.go # Server lifecycle, wiring
├── internal/
│ ├── media_relay.go # Per-session RTP forwarding (core data path)
│ ├── session_manager.go # Session/CallLeg/Registry
│ ├── ng_socket_listener.go # NG protocol UDP/Unix listener
│ ├── ng_protocol/
│ │ ├── message.go # Bencode parsing
│ │ ├── handler.go # Command registry
│ │ ├── types.go # Flag parsing (100+ rtpengine flags)
│ │ └── commands/ # offer, answer, delete, query, etc.
│ ├── recording/ # WAV recording, audio mixing
│ ├── dtls_cert.go # Self-signed DTLS certificate
│ ├── codec_converter.go # G.711 transcoding (others are stubs)
│ ├── rtcp_handler.go # RTCP quality monitoring
│ ├── fec_handler.go # Forward error correction
│ ├── jitter_buffer.go # Adaptive jitter buffer
│ ├── rate_limiter.go # Per-IP/per-call rate limiting
│ └── ... # Health, metrics, config, etc.