mirror of
https://github.com/nestriness/nestri.git
synced 2025-12-13 01:05:37 +02:00
## Description Whew, some stuff is still not re-implemented, but it's working! Rabbit's gonna explode with the amount of changes I reckon 😅 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Introduced a peer-to-peer relay system using libp2p with enhanced stream forwarding, room state synchronization, and mDNS peer discovery. - Added decentralized room and participant management, metrics publishing, and safe, size-limited, concurrent message streaming with robust framing and callback dispatching. - Implemented asynchronous, callback-driven message handling over custom libp2p streams replacing WebSocket signaling. - **Improvements** - Migrated signaling and stream protocols from WebSocket to libp2p, improving reliability and scalability. - Simplified configuration and environment variables, removing deprecated flags and adding persistent data support. - Enhanced logging, error handling, and connection management for better observability and robustness. - Refined RTP header extension registration and NAT IP handling for improved WebRTC performance. - **Bug Fixes** - Improved ICE candidate buffering and SDP negotiation in WebRTC connections. - Fixed NAT IP and UDP port range configuration issues. - **Refactor** - Modularized codebase, reorganized relay and server logic, and removed deprecated WebSocket-based components. - Streamlined message structures, removed obsolete enums and message types, and simplified SafeMap concurrency. - Replaced WebSocket signaling with libp2p stream protocols in server and relay components. - **Chores** - Updated and cleaned dependencies across Go, Rust, and JavaScript packages. - Added `.gitignore` for persistent data directory in relay package. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: DatCaptainHorse <DatCaptainHorse@users.noreply.github.com> Co-authored-by: Philipp Neumann <3daquawolf@gmail.com>
132 lines
3.9 KiB
Go
132 lines
3.9 KiB
Go
package common
|
|
|
|
import (
|
|
"fmt"
|
|
"log/slog"
|
|
"strconv"
|
|
|
|
"github.com/libp2p/go-reuseport"
|
|
"github.com/pion/ice/v4"
|
|
"github.com/pion/interceptor"
|
|
"github.com/pion/webrtc/v4"
|
|
)
|
|
|
|
var globalWebRTCAPI *webrtc.API
|
|
var globalWebRTCConfig = webrtc.Configuration{
|
|
ICETransportPolicy: webrtc.ICETransportPolicyAll,
|
|
BundlePolicy: webrtc.BundlePolicyBalanced,
|
|
SDPSemantics: webrtc.SDPSemanticsUnifiedPlan,
|
|
}
|
|
|
|
func InitWebRTCAPI() error {
|
|
var err error
|
|
flags := GetFlags()
|
|
|
|
// Media engine
|
|
mediaEngine := &webrtc.MediaEngine{}
|
|
|
|
// Register our extensions
|
|
if err := RegisterExtensions(mediaEngine); err != nil {
|
|
return fmt.Errorf("failed to register extensions: %w", err)
|
|
}
|
|
|
|
// Default codecs cover most of our needs
|
|
err = mediaEngine.RegisterDefaultCodecs()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Add H.265 for special cases
|
|
videoRTCPFeedback := []webrtc.RTCPFeedback{{"goog-remb", ""}, {"ccm", "fir"}, {"nack", ""}, {"nack", "pli"}}
|
|
for _, codec := range []webrtc.RTPCodecParameters{
|
|
{
|
|
RTPCodecCapability: webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeH265, ClockRate: 90000, RTCPFeedback: videoRTCPFeedback},
|
|
PayloadType: 48,
|
|
},
|
|
{
|
|
RTPCodecCapability: webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeRTX, ClockRate: 90000, SDPFmtpLine: "apt=48"},
|
|
PayloadType: 49,
|
|
},
|
|
} {
|
|
if err = mediaEngine.RegisterCodec(codec, webrtc.RTPCodecTypeVideo); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
// Interceptor registry
|
|
interceptorRegistry := &interceptor.Registry{}
|
|
|
|
// Use default set
|
|
err = webrtc.RegisterDefaultInterceptors(mediaEngine, interceptorRegistry)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Setting engine
|
|
settingEngine := webrtc.SettingEngine{}
|
|
|
|
// New in v4, reduces CPU usage and latency when enabled
|
|
settingEngine.EnableSCTPZeroChecksum(true)
|
|
|
|
nat11IP := GetFlags().NAT11IP
|
|
if len(nat11IP) > 0 {
|
|
settingEngine.SetNAT1To1IPs([]string{nat11IP}, webrtc.ICECandidateTypeSrflx)
|
|
slog.Info("Using NAT 1:1 IP for WebRTC", "nat11_ip", nat11IP)
|
|
}
|
|
|
|
muxPort := GetFlags().UDPMuxPort
|
|
if muxPort > 0 {
|
|
// Use reuseport to allow multiple listeners on the same port
|
|
pktListener, err := reuseport.ListenPacket("udp", ":"+strconv.Itoa(muxPort))
|
|
if err != nil {
|
|
return fmt.Errorf("failed to create WebRTC muxed UDP listener: %w", err)
|
|
}
|
|
|
|
mux := ice.NewMultiUDPMuxDefault(ice.NewUDPMuxDefault(ice.UDPMuxParams{
|
|
UDPConn: pktListener,
|
|
}))
|
|
slog.Info("Using UDP Mux for WebRTC", "port", muxPort)
|
|
settingEngine.SetICEUDPMux(mux)
|
|
}
|
|
|
|
if flags.WebRTCUDPStart > 0 && flags.WebRTCUDPEnd > 0 && flags.WebRTCUDPStart < flags.WebRTCUDPEnd {
|
|
// Set the UDP port range used by WebRTC
|
|
err = settingEngine.SetEphemeralUDPPortRange(uint16(flags.WebRTCUDPStart), uint16(flags.WebRTCUDPEnd))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
slog.Info("Using WebRTC UDP Port Range", "start", flags.WebRTCUDPStart, "end", flags.WebRTCUDPEnd)
|
|
}
|
|
|
|
settingEngine.SetIncludeLoopbackCandidate(true) // Just in case
|
|
|
|
// Create a new API object with our customized settings
|
|
globalWebRTCAPI = webrtc.NewAPI(webrtc.WithMediaEngine(mediaEngine), webrtc.WithSettingEngine(settingEngine), webrtc.WithInterceptorRegistry(interceptorRegistry))
|
|
|
|
return nil
|
|
}
|
|
|
|
// CreatePeerConnection sets up a new peer connection
|
|
func CreatePeerConnection(onClose func()) (*webrtc.PeerConnection, error) {
|
|
pc, err := globalWebRTCAPI.NewPeerConnection(globalWebRTCConfig)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Log connection state changes and handle failed/disconnected connections
|
|
pc.OnConnectionStateChange(func(connectionState webrtc.PeerConnectionState) {
|
|
// Close PeerConnection in cases
|
|
if connectionState == webrtc.PeerConnectionStateFailed ||
|
|
connectionState == webrtc.PeerConnectionStateDisconnected ||
|
|
connectionState == webrtc.PeerConnectionStateClosed {
|
|
err = pc.Close()
|
|
if err != nil {
|
|
slog.Error("Failed to close PeerConnection", "err", err)
|
|
}
|
|
onClose()
|
|
}
|
|
})
|
|
|
|
return pc, nil
|
|
}
|