github.com/pion/webrtc/v4@v4.0.1/api.go (about) 1 // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly> 2 // SPDX-License-Identifier: MIT 3 4 //go:build !js 5 // +build !js 6 7 package webrtc 8 9 import ( 10 "github.com/pion/interceptor" 11 "github.com/pion/logging" 12 ) 13 14 // API allows configuration of a PeerConnection 15 // with APIs that are available in the standard. This 16 // lets you set custom behavior via the SettingEngine, configure 17 // codecs via the MediaEngine and define custom media behaviors via 18 // Interceptors. 19 type API struct { 20 settingEngine *SettingEngine 21 mediaEngine *MediaEngine 22 interceptorRegistry *interceptor.Registry 23 24 interceptor interceptor.Interceptor // Generated per PeerConnection 25 } 26 27 // NewAPI Creates a new API object for keeping semi-global settings to WebRTC objects 28 // 29 // It uses the default Codecs and Interceptors unless you customize them 30 // using WithMediaEngine and WithInterceptorRegistry respectively. 31 func NewAPI(options ...func(*API)) *API { 32 a := &API{ 33 interceptor: &interceptor.NoOp{}, 34 settingEngine: &SettingEngine{}, 35 } 36 37 for _, o := range options { 38 o(a) 39 } 40 41 if a.settingEngine.LoggerFactory == nil { 42 a.settingEngine.LoggerFactory = logging.NewDefaultLoggerFactory() 43 } 44 45 logger := a.settingEngine.LoggerFactory.NewLogger("api") 46 47 if a.mediaEngine == nil { 48 a.mediaEngine = &MediaEngine{} 49 err := a.mediaEngine.RegisterDefaultCodecs() 50 if err != nil { 51 logger.Errorf("Failed to register default codecs %s", err) 52 } 53 } 54 55 if a.interceptorRegistry == nil { 56 a.interceptorRegistry = &interceptor.Registry{} 57 err := RegisterDefaultInterceptors(a.mediaEngine, a.interceptorRegistry) 58 if err != nil { 59 logger.Errorf("Failed to register default interceptors %s", err) 60 } 61 } 62 63 return a 64 } 65 66 // WithMediaEngine allows providing a MediaEngine to the API. 67 // Settings can be changed after passing the engine to an API. 68 // When a PeerConnection is created the MediaEngine is copied 69 // and no more changes can be made. 70 func WithMediaEngine(m *MediaEngine) func(a *API) { 71 return func(a *API) { 72 a.mediaEngine = m 73 if a.mediaEngine == nil { 74 a.mediaEngine = &MediaEngine{} 75 } 76 } 77 } 78 79 // WithSettingEngine allows providing a SettingEngine to the API. 80 // Settings should not be changed after passing the engine to an API. 81 func WithSettingEngine(s SettingEngine) func(a *API) { 82 return func(a *API) { 83 a.settingEngine = &s 84 } 85 } 86 87 // WithInterceptorRegistry allows providing Interceptors to the API. 88 // Settings should not be changed after passing the registry to an API. 89 func WithInterceptorRegistry(ir *interceptor.Registry) func(a *API) { 90 return func(a *API) { 91 a.interceptorRegistry = ir 92 if a.interceptorRegistry == nil { 93 a.interceptorRegistry = &interceptor.Registry{} 94 } 95 } 96 }