├── go.mod ├── go.sum ├── netutils_unix.go ├── logging_c.go ├── callback.h ├── callback_c.go ├── netutils_windows.go ├── examples ├── file-receiver │ └── main.go └── echo-receiver │ └── main.go ├── read.go ├── write.go ├── netutils_test.go ├── poll_test.go ├── accept.go ├── logging.go ├── README.md ├── netutils.go ├── pollserver.go ├── rw_test.go ├── poll.go ├── srtgo_test.go ├── srtsocketoptions.go ├── srtstats.go ├── errors.go ├── srtgo.go └── LICENSE /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/haivision/srtgo 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/mattn/go-pointer v0.0.1 7 | golang.org/x/sys v0.0.0-20200926100807-9d91bd62050c 8 | ) 9 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/mattn/go-pointer v0.0.1 h1:n+XhsuGeVO6MEAp7xyEukFINEa+Quek5psIR/ylA6o0= 2 | github.com/mattn/go-pointer v0.0.1/go.mod h1:2zXcozF6qYGgmsG+SeTZz3oAbFLdD3OWqnUbNvJZAlc= 3 | golang.org/x/sys v0.0.0-20200926100807-9d91bd62050c h1:38q6VNPWR010vN82/SB121GujZNIfAUb4YttE2rhGuc= 4 | golang.org/x/sys v0.0.0-20200926100807-9d91bd62050c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 5 | -------------------------------------------------------------------------------- /netutils_unix.go: -------------------------------------------------------------------------------- 1 | //go:build !windows 2 | 3 | package srtgo 4 | 5 | import ( 6 | "syscall" 7 | 8 | "golang.org/x/sys/unix" 9 | ) 10 | 11 | const ( 12 | sizeofSockAddrInet4 = syscall.SizeofSockaddrInet4 13 | sizeofSockAddrInet6 = syscall.SizeofSockaddrInet6 14 | sizeofSockaddrAny = syscall.SizeofSockaddrAny 15 | afINET4 = unix.AF_INET 16 | afINET6 = unix.AF_INET6 17 | ) 18 | -------------------------------------------------------------------------------- /logging_c.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | /* 4 | #cgo LDFLAGS: -lsrt 5 | #include 6 | 7 | extern void srtLogCBWrapper (void* opaque, int level, char* file, int line, char* area, char* message); 8 | 9 | void srtLogCB(void* opaque, int level, const char* file, int line, const char* area, const char* message) 10 | { 11 | srtLogCBWrapper(opaque, level, (char*)file, line, (char*)area,(char*) message); 12 | } 13 | */ 14 | import "C" 15 | -------------------------------------------------------------------------------- /callback.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int srtListenCBWrapper(void* opaque, SRTSOCKET ns, int hs_version, struct sockaddr* peeraddr, char* streamid); 4 | void srtConnectCBWrapper(void* opaque, SRTSOCKET ns, int errorcode, struct sockaddr* peeraddr, int token); 5 | 6 | int srtListenCB(void* opaque, SRTSOCKET ns, int hs_version, const struct sockaddr* peeraddr, const char* streamid); 7 | void srtConnectCB(void* opaque, SRTSOCKET ns, int errorcode, const struct sockaddr* peeraddr, int token); -------------------------------------------------------------------------------- /callback_c.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | /* 4 | #cgo LDFLAGS: -lsrt 5 | #include "callback.h" 6 | 7 | int srtListenCB(void* opaque, SRTSOCKET ns, int hs_version, const struct sockaddr* peeraddr, const char* streamid) 8 | { 9 | return srtListenCBWrapper(opaque, ns, hs_version, (struct sockaddr*)peeraddr, (char*)streamid); 10 | } 11 | 12 | void srtConnectCB(void* opaque, SRTSOCKET ns, int errorcode, const struct sockaddr* peeraddr, int token) 13 | { 14 | srtConnectCBWrapper(opaque, ns, errorcode, (struct sockaddr*)peeraddr, token); 15 | } 16 | */ 17 | import "C" 18 | -------------------------------------------------------------------------------- /netutils_windows.go: -------------------------------------------------------------------------------- 1 | //go:build windows 2 | 3 | package srtgo 4 | 5 | import ( 6 | "unsafe" 7 | 8 | "golang.org/x/sys/windows" 9 | ) 10 | 11 | const ( 12 | afINET4 = windows.AF_INET 13 | afINET6 = windows.AF_INET6 14 | ) 15 | 16 | var ( 17 | sizeofSockAddrInet4 uint64 = 0 18 | sizeofSockAddrInet6 uint64 = 0 19 | sizeofSockaddrAny uint64 = 0 20 | ) 21 | 22 | func init() { 23 | inet4 := windows.RawSockaddrInet4{} 24 | inet6 := windows.RawSockaddrInet6{} 25 | any := windows.RawSockaddrAny{} 26 | sizeofSockAddrInet4 = uint64(unsafe.Sizeof(inet4)) 27 | sizeofSockAddrInet6 = uint64(unsafe.Sizeof(inet6)) 28 | sizeofSockaddrAny = uint64(unsafe.Sizeof(any)) 29 | } 30 | -------------------------------------------------------------------------------- /examples/file-receiver/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | 8 | "github.com/haivision/srtgo" 9 | ) 10 | 11 | func main() { 12 | options := make(map[string]string) 13 | options["blocking"] = "0" 14 | options["transtype"] = "file" 15 | hostname := "0.0.0.0" 16 | port := 8090 17 | 18 | fmt.Printf("(srt://%s:%d) Listening", hostname, port) 19 | a := srtgo.NewSrtSocket(hostname, uint16(port), options) 20 | err := a.Listen(2) 21 | defer a.Close() 22 | if err != nil { 23 | panic("Error on Listen") 24 | } 25 | 26 | for { 27 | s, _, err := a.Accept() 28 | if err != nil { 29 | panic("Error on Accept") 30 | } 31 | 32 | buff := make([]byte, 2048) 33 | fo, err := os.Create("sample.ts") 34 | w := bufio.NewWriter(fo) 35 | for { 36 | n, err := s.Read(buff) 37 | 38 | if err != nil { 39 | fmt.Println(err) 40 | break 41 | } 42 | 43 | if n == 0 { 44 | break 45 | } 46 | 47 | w.Write(buff[:n]) 48 | } 49 | w.Flush() 50 | s.Close() 51 | fo.Close() 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /read.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | /* 4 | #cgo LDFLAGS: -lsrt 5 | #include 6 | 7 | int srt_recvmsg2_wrapped(SRTSOCKET u, char* buf, int len, SRT_MSGCTRL *mctrl, int *srterror, int *syserror) 8 | { 9 | int ret = srt_recvmsg2(u, buf, len, mctrl); 10 | if (ret < 0) { 11 | *srterror = srt_getlasterror(syserror); 12 | } 13 | return ret; 14 | } 15 | 16 | */ 17 | import "C" 18 | import ( 19 | "errors" 20 | "syscall" 21 | "unsafe" 22 | ) 23 | 24 | func srtRecvMsg2Impl(u C.SRTSOCKET, buf []byte, msgctrl *C.SRT_MSGCTRL) (n int, err error) { 25 | srterr := C.int(0) 26 | syserr := C.int(0) 27 | n = int(C.srt_recvmsg2_wrapped(u, (*C.char)(unsafe.Pointer(&buf[0])), C.int(len(buf)), msgctrl, &srterr, &syserr)) 28 | if n < 0 { 29 | srterror := SRTErrno(srterr) 30 | if syserr < 0 { 31 | srterror.wrapSysErr(syscall.Errno(syserr)) 32 | } 33 | err = srterror 34 | n = 0 35 | } 36 | return 37 | } 38 | 39 | // Read data from the SRT socket 40 | func (s SrtSocket) Read(b []byte) (n int, err error) { 41 | //Fastpath 42 | if !s.blocking { 43 | s.pd.reset(ModeRead) 44 | } 45 | n, err = srtRecvMsg2Impl(s.socket, b, nil) 46 | 47 | for { 48 | if !errors.Is(err, error(EAsyncRCV)) || s.blocking { 49 | return 50 | } 51 | s.pd.wait(ModeRead) 52 | n, err = srtRecvMsg2Impl(s.socket, b, nil) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /write.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | /* 4 | #cgo LDFLAGS: -lsrt 5 | #include 6 | 7 | int srt_sendmsg2_wrapped(SRTSOCKET u, const char* buf, int len, SRT_MSGCTRL *mctrl, int *srterror, int *syserror) 8 | { 9 | int ret = srt_sendmsg2(u, buf, len, mctrl); 10 | if (ret < 0) { 11 | *srterror = srt_getlasterror(syserror); 12 | } 13 | return ret; 14 | } 15 | 16 | */ 17 | import "C" 18 | import ( 19 | "errors" 20 | "syscall" 21 | "unsafe" 22 | ) 23 | 24 | func srtSendMsg2Impl(u C.SRTSOCKET, buf []byte, msgctrl *C.SRT_MSGCTRL) (n int, err error) { 25 | srterr := C.int(0) 26 | syserr := C.int(0) 27 | n = int(C.srt_sendmsg2_wrapped(u, (*C.char)(unsafe.Pointer(&buf[0])), C.int(len(buf)), msgctrl, &srterr, &syserr)) 28 | if n < 0 { 29 | srterror := SRTErrno(srterr) 30 | if syserr < 0 { 31 | srterror.wrapSysErr(syscall.Errno(syserr)) 32 | } 33 | err = srterror 34 | n = 0 35 | } 36 | return 37 | } 38 | 39 | // Write data to the SRT socket 40 | func (s SrtSocket) Write(b []byte) (n int, err error) { 41 | 42 | //Fastpath: 43 | if !s.blocking { 44 | s.pd.reset(ModeWrite) 45 | } 46 | n, err = srtSendMsg2Impl(s.socket, b, nil) 47 | 48 | for { 49 | if !errors.Is(err, error(EAsyncSND)) || s.blocking { 50 | return 51 | } 52 | s.pd.wait(ModeWrite) 53 | n, err = srtSendMsg2Impl(s.socket, b, nil) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /netutils_test.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | import ( 4 | "testing" 5 | 6 | "golang.org/x/sys/unix" 7 | ) 8 | 9 | func TestCreateAddrInetV4(t *testing.T) { 10 | ip1, size, err := CreateAddrInet("0.0.0.0", 8090) 11 | 12 | if err != nil { 13 | t.Error("Error on CreateAddrInet") 14 | } 15 | 16 | if size != 16 { 17 | t.Error("Ip Address size does not match", size) 18 | } 19 | 20 | if ip1.sa_family != unix.AF_INET { 21 | t.Error("Ip Address family does not match") 22 | } 23 | 24 | data := []int{31, -102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} 25 | if len(data) != len(ip1.sa_data) { 26 | t.Error("Ip Address ip.sa_data length should be equal") 27 | } 28 | 29 | for i := 0; i < len(data); i++ { 30 | if data[i] != int(ip1.sa_data[i]) { 31 | t.Error("Ip Address ip.sa_data does not match") 32 | } 33 | } 34 | 35 | } 36 | 37 | func TestCreateAddrInetV6(t *testing.T) { 38 | ip1, size, err := CreateAddrInet("2001:0db8:85a3:0000:0000:8a2e:0370:7334", 8090) 39 | 40 | if err != nil { 41 | t.Error("Error on CreateAddrInet") 42 | } 43 | 44 | if size != 28 { 45 | t.Error("Ipv6 Address size does not match", size) 46 | } 47 | 48 | if ip1.sa_family != unix.AF_INET6 { 49 | t.Error("Ipv6 Address family does not match") 50 | } 51 | data := []int{31, -102, 0, 0, 0, 0, 32, 1, 13, -72, -123, -93, 0, 0} 52 | if len(data) != len(ip1.sa_data) { 53 | t.Error("Ipv6 Address ip.sa_data length should be equal") 54 | } 55 | 56 | for i := 0; i < len(data); i++ { 57 | if data[i] != int(ip1.sa_data[i]) { 58 | t.Error("Ipv6 Address ip.sa_data does not match") 59 | } 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /poll_test.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func connectLoop(port uint16, semChan chan struct{}) { 8 | for { 9 | //fmt.Printf("Connecting\n") 10 | s := NewSrtSocket("127.0.0.1", port, map[string]string{"blocking": "0", "mode": "caller"}) 11 | err := s.Connect() 12 | if err != nil { 13 | continue 14 | } 15 | s.Close() 16 | _, ok := <-semChan 17 | if !ok { 18 | return 19 | } 20 | } 21 | } 22 | 23 | func benchAccept(blocking string, N int) { 24 | start: 25 | port := randomPort() 26 | s := NewSrtSocket("127.0.0.1", port, map[string]string{"blocking": blocking, "mode": "listener"}) 27 | if s == nil { 28 | goto start 29 | } 30 | if err := s.Listen(5); err != nil { 31 | goto start 32 | } 33 | semChan := make(chan struct{}, 8) 34 | go connectLoop(port, semChan) 35 | semChan <- struct{}{} 36 | semChan <- struct{}{} 37 | for i := 0; i < N; i++ { 38 | semChan <- struct{}{} 39 | _, _, _ = s.Accept() 40 | } 41 | close(semChan) 42 | s.Close() 43 | } 44 | 45 | func BenchmarkAcceptBlocking(b *testing.B) { 46 | benchAccept("1", b.N) 47 | } 48 | 49 | func BenchmarkAcceptNonBlocking(b *testing.B) { 50 | benchAccept("0", b.N) 51 | } 52 | 53 | /* 54 | func BenchmarkAcceptNonBlockingParallel(b *testing.B) { 55 | SrtSetLogLevel(SrtLogLevelCrit) 56 | b.RunParallel(func(pb *testing.PB) { 57 | for pb.Next() { 58 | benchAccept("0", 2) 59 | } 60 | }) 61 | } 62 | 63 | func BenchmarkAcceptBlockingParallel(b *testing.B) { 64 | b.RunParallel(func(pb *testing.PB) { 65 | for pb.Next() { 66 | benchAccept("1", 2) 67 | } 68 | }) 69 | } 70 | */ 71 | -------------------------------------------------------------------------------- /accept.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | /* 4 | #cgo LDFLAGS: -lsrt 5 | #include 6 | 7 | SRTSOCKET srt_accept_wrapped(SRTSOCKET lsn, struct sockaddr* addr, int* addrlen, int *srterror, int *syserror) 8 | { 9 | int ret = srt_accept(lsn, addr, addrlen); 10 | if (ret < 0) { 11 | *srterror = srt_getlasterror(syserror); 12 | } 13 | return ret; 14 | } 15 | 16 | */ 17 | import "C" 18 | import ( 19 | "fmt" 20 | "net" 21 | "syscall" 22 | "unsafe" 23 | ) 24 | 25 | func srtAcceptImpl(lsn C.SRTSOCKET, addr *C.struct_sockaddr, addrlen *C.int) (C.SRTSOCKET, error) { 26 | srterr := C.int(0) 27 | syserr := C.int(0) 28 | socket := C.srt_accept_wrapped(lsn, addr, addrlen, &srterr, &syserr) 29 | if srterr != 0 { 30 | srterror := SRTErrno(srterr) 31 | if syserr < 0 { 32 | srterror.wrapSysErr(syscall.Errno(syserr)) 33 | } 34 | return socket, srterror 35 | } 36 | return socket, nil 37 | } 38 | 39 | // Accept an incoming connection 40 | func (s SrtSocket) Accept() (*SrtSocket, *net.UDPAddr, error) { 41 | var err error 42 | if !s.blocking { 43 | err = s.pd.wait(ModeRead) 44 | if err != nil { 45 | return nil, nil, err 46 | } 47 | } 48 | var addr syscall.RawSockaddrAny 49 | sclen := C.int(syscall.SizeofSockaddrAny) 50 | socket, err := srtAcceptImpl(s.socket, (*C.struct_sockaddr)(unsafe.Pointer(&addr)), &sclen) 51 | if err != nil { 52 | return nil, nil, err 53 | } 54 | if socket == SRT_INVALID_SOCK { 55 | return nil, nil, fmt.Errorf("srt accept, error accepting the connection: %w", srtGetAndClearError()) 56 | } 57 | 58 | newSocket, err := newFromSocket(&s, socket) 59 | if err != nil { 60 | return nil, nil, fmt.Errorf("new socket could not be created: %w", err) 61 | } 62 | 63 | udpAddr, err := udpAddrFromSockaddr(&addr) 64 | if err != nil { 65 | return nil, nil, err 66 | } 67 | 68 | return newSocket, udpAddr, nil 69 | } 70 | -------------------------------------------------------------------------------- /examples/echo-receiver/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // #cgo LDFLAGS: -lsrt 4 | // #include 5 | import "C" 6 | 7 | import ( 8 | "log" 9 | "net" 10 | 11 | "github.com/haivision/srtgo" 12 | ) 13 | 14 | var allowedStreamIDs = map[string]bool{ 15 | "foo": true, 16 | "foobar": true, 17 | } 18 | 19 | func listenCallback(socket *srtgo.SrtSocket, version int, addr *net.UDPAddr, streamid string) bool { 20 | log.Printf("socket will connect, hsVersion: %d, streamid: %s\n", version, streamid) 21 | 22 | // socket not in allowed ids -> reject 23 | if _, found := allowedStreamIDs[streamid]; !found { 24 | // set custom reject reason 25 | socket.SetRejectReason(srtgo.RejectionReasonUnauthorized) 26 | return false 27 | } 28 | 29 | // allow connection 30 | return true 31 | } 32 | 33 | // echo received packets 34 | func handler(socket *srtgo.SrtSocket, addr *net.UDPAddr) { 35 | buf := make([]byte, 1500) 36 | for { 37 | len, err := socket.Read(buf) 38 | if err != nil { 39 | log.Println(err) 40 | return 41 | } 42 | _, err = socket.Write(buf[:len]) 43 | if err != nil { 44 | log.Println(err) 45 | return 46 | } 47 | } 48 | } 49 | 50 | func main() { 51 | // set socket options 52 | options := make(map[string]string) 53 | options["blocking"] = "0" 54 | options["transtype"] = "live" 55 | options["latency"] = "300" 56 | 57 | // create and bind socket 58 | sck := srtgo.NewSrtSocket("127.0.0.1", 6000, options) 59 | 60 | // set listen callback 61 | sck.SetListenCallback(listenCallback) 62 | 63 | // start listenening 64 | err := sck.Listen(1) 65 | log.Println("started listening on port 6000") 66 | if err != nil { 67 | log.Fatalf("Listen failed: %v \n", err.Error()) 68 | } 69 | 70 | for { 71 | // accept client sockets 72 | socket, peeraddr, err := sck.Accept() 73 | if err != nil { 74 | log.Fatal(err) 75 | } 76 | go handler(socket, peeraddr) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /logging.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | /* 4 | #cgo LDFLAGS: -lsrt 5 | #include 6 | extern void srtLogCB(void* opaque, int level, const char* file, int line, const char* area, const char* message); 7 | */ 8 | import "C" 9 | 10 | import ( 11 | "sync" 12 | "unsafe" 13 | 14 | gopointer "github.com/mattn/go-pointer" 15 | ) 16 | 17 | type LogCallBackFunc func(level SrtLogLevel, file string, line int, area, message string) 18 | 19 | type SrtLogLevel int 20 | 21 | const ( 22 | // SrtLogLevelEmerg = int(C.LOG_EMERG) 23 | // SrtLogLevelAlert = int(C.LOG_ALERT) 24 | SrtLogLevelCrit SrtLogLevel = SrtLogLevel(C.LOG_CRIT) 25 | SrtLogLevelErr SrtLogLevel = SrtLogLevel(C.LOG_ERR) 26 | SrtLogLevelWarning SrtLogLevel = SrtLogLevel(C.LOG_WARNING) 27 | SrtLogLevelNotice SrtLogLevel = SrtLogLevel(C.LOG_NOTICE) 28 | SrtLogLevelInfo SrtLogLevel = SrtLogLevel(C.LOG_INFO) 29 | SrtLogLevelDebug SrtLogLevel = SrtLogLevel(C.LOG_DEBUG) 30 | SrtLogLevelTrace SrtLogLevel = SrtLogLevel(8) 31 | ) 32 | 33 | var ( 34 | logCBPtr unsafe.Pointer = nil 35 | logCBPtrLock sync.Mutex 36 | ) 37 | 38 | //export srtLogCBWrapper 39 | func srtLogCBWrapper(arg unsafe.Pointer, level C.int, file *C.char, line C.int, area, message *C.char) { 40 | userCB := gopointer.Restore(arg).(LogCallBackFunc) 41 | go userCB(SrtLogLevel(level), C.GoString(file), int(line), C.GoString(area), C.GoString(message)) 42 | } 43 | 44 | func SrtSetLogLevel(level SrtLogLevel) { 45 | C.srt_setloglevel(C.int(level)) 46 | } 47 | 48 | func SrtSetLogHandler(cb LogCallBackFunc) { 49 | ptr := gopointer.Save(cb) 50 | C.srt_setloghandler(ptr, (*C.SRT_LOG_HANDLER_FN)(C.srtLogCB)) 51 | storeLogCBPtr(ptr) 52 | } 53 | 54 | func SrtUnsetLogHandler() { 55 | C.srt_setloghandler(nil, nil) 56 | storeLogCBPtr(nil) 57 | } 58 | 59 | func storeLogCBPtr(ptr unsafe.Pointer) { 60 | logCBPtrLock.Lock() 61 | defer logCBPtrLock.Unlock() 62 | if logCBPtr != nil { 63 | gopointer.Unref(logCBPtr) 64 | } 65 | logCBPtr = ptr 66 | } 67 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![PkgGoDev](https://pkg.go.dev/badge/github.com/haivision/srtgo)](https://pkg.go.dev/github.com/haivision/srtgo) 2 | 3 | # srtgo 4 | 5 | Go bindings for [SRT](https://github.com/Haivision/srt) (Secure Reliable Transport), the open source transport technology that optimizes streaming performance across unpredictable networks. 6 | 7 | ## Why srtgo? 8 | The purpose of srtgo is easing the adoption of SRT transport technology. Using Go, with just a few lines of code you can implement an application that sends/receives data with all the benefits of SRT technology: security and reliability, while keeping latency low. 9 | 10 | ## Is this a new implementation of SRT? 11 | No! We are just exposing the great work done by the community in the [SRT project](https://github.com/Haivision/srt) as a golang library. All the functionality and implementation still resides in the official SRT project. 12 | 13 | 14 | # Features supported 15 | * Basic API exposed to easy develop SRT sender/receiver apps 16 | * Caller and Listener mode 17 | * Live transport type 18 | * File transport type 19 | * Message/Buffer API 20 | * SRT transport options up to SRT 1.4.1 21 | * SRT Stats retrieval 22 | 23 | # Usage 24 | Example of a SRT receiver application: 25 | ``` go 26 | package main 27 | 28 | import ( 29 | "github.com/haivision/srtgo" 30 | "fmt" 31 | ) 32 | 33 | func main() { 34 | options := make(map[string]string) 35 | options["transtype"] = "file" 36 | 37 | sck := srtgo.NewSrtSocket("0.0.0.0", 8090, options) 38 | defer sck.Close() 39 | sck.Listen(1) 40 | s, _ := sck.Accept() 41 | defer s.Close() 42 | 43 | buf := make([]byte, 2048) 44 | for { 45 | n, _ := s.Read(buf) 46 | if n == 0 { 47 | break 48 | } 49 | fmt.Println("Received %d bytes", n) 50 | } 51 | //.... 52 | } 53 | 54 | ``` 55 | 56 | 57 | # Dependencies 58 | 59 | * srtlib 60 | 61 | You can find detailed instructions about how to install srtlib in its [README file](https://github.com/Haivision/srt#requirements) 62 | 63 | gosrt has been developed with srt 1.4.1 as its main target and has been successfully tested in srt 1.3.4 and above. 64 | -------------------------------------------------------------------------------- /netutils.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | //#include 4 | import "C" 5 | 6 | import ( 7 | "encoding/binary" 8 | "fmt" 9 | "net" 10 | "syscall" 11 | "unsafe" 12 | ) 13 | 14 | func ntohs(val uint16) uint16 { 15 | tmp := ((*[unsafe.Sizeof(val)]byte)(unsafe.Pointer(&val))) 16 | return binary.BigEndian.Uint16((*tmp)[:]) 17 | } 18 | 19 | func udpAddrFromSockaddr(addr *syscall.RawSockaddrAny) (*net.UDPAddr, error) { 20 | var udpAddr net.UDPAddr 21 | 22 | switch addr.Addr.Family { 23 | case afINET6: 24 | ptr := (*syscall.RawSockaddrInet6)(unsafe.Pointer(addr)) 25 | udpAddr.Port = int(ntohs(ptr.Port)) 26 | udpAddr.IP = ptr.Addr[:] 27 | 28 | case afINET4: 29 | ptr := (*syscall.RawSockaddrInet4)(unsafe.Pointer(addr)) 30 | udpAddr.Port = int(ntohs(ptr.Port)) 31 | udpAddr.IP = net.IPv4( 32 | ptr.Addr[0], 33 | ptr.Addr[1], 34 | ptr.Addr[2], 35 | ptr.Addr[3], 36 | ) 37 | default: 38 | return nil, fmt.Errorf("unknown address family: %v", addr.Addr.Family) 39 | } 40 | 41 | return &udpAddr, nil 42 | } 43 | 44 | func sockAddrFromIp4(ip net.IP, port uint16) (*C.struct_sockaddr, int, error) { 45 | var raw syscall.RawSockaddrInet4 46 | raw.Family = afINET4 47 | 48 | p := (*[2]byte)(unsafe.Pointer(&raw.Port)) 49 | p[0] = byte(port >> 8) 50 | p[1] = byte(port) 51 | 52 | copy(raw.Addr[:], ip.To4()) 53 | 54 | return (*C.struct_sockaddr)(unsafe.Pointer(&raw)), int(sizeofSockAddrInet4), nil 55 | } 56 | 57 | func sockAddrFromIp6(ip net.IP, port uint16) (*C.struct_sockaddr, int, error) { 58 | var raw syscall.RawSockaddrInet6 59 | raw.Family = afINET6 60 | 61 | p := (*[2]byte)(unsafe.Pointer(&raw.Port)) 62 | p[0] = byte(port >> 8) 63 | p[1] = byte(port) 64 | 65 | copy(raw.Addr[:], ip.To16()) 66 | 67 | return (*C.struct_sockaddr)(unsafe.Pointer(&raw)), int(sizeofSockAddrInet6), nil 68 | } 69 | 70 | func CreateAddrInet(name string, port uint16) (*C.struct_sockaddr, int, error) { 71 | ip := net.ParseIP(name) 72 | if ip == nil { 73 | ips, err := net.LookupIP(name) 74 | if err != nil { 75 | return nil, 0, fmt.Errorf("Error in CreateAddrInet, LookupIP") 76 | } 77 | ip = ips[0] 78 | } 79 | 80 | if ip.To4() != nil { 81 | return sockAddrFromIp4(ip, port) 82 | } else if ip.To16() != nil { 83 | return sockAddrFromIp6(ip, port) 84 | } 85 | 86 | return nil, 0, fmt.Errorf("Error in CreateAddrInet, LookupIP") 87 | } 88 | -------------------------------------------------------------------------------- /pollserver.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | /* 4 | #cgo LDFLAGS: -lsrt 5 | #include 6 | */ 7 | import "C" 8 | 9 | import ( 10 | "sync" 11 | "unsafe" 12 | ) 13 | 14 | var ( 15 | phctx *pollServer 16 | once sync.Once 17 | ) 18 | 19 | func pollServerCtx() *pollServer { 20 | once.Do(pollServerCtxInit) 21 | return phctx 22 | } 23 | 24 | func pollServerCtxInit() { 25 | eid := C.srt_epoll_create() 26 | C.srt_epoll_set(eid, C.SRT_EPOLL_ENABLE_EMPTY) 27 | phctx = &pollServer{ 28 | srtEpollDescr: eid, 29 | pollDescs: make(map[C.SRTSOCKET]*pollDesc), 30 | } 31 | go phctx.run() 32 | } 33 | 34 | type pollServer struct { 35 | srtEpollDescr C.int 36 | pollDescLock sync.Mutex 37 | pollDescs map[C.SRTSOCKET]*pollDesc 38 | } 39 | 40 | func (p *pollServer) pollOpen(pd *pollDesc) { 41 | //use uint because otherwise with ET it would overflow :/ (srt should accept an uint instead, or fix it's SRT_EPOLL_ET definition) 42 | events := C.uint(C.SRT_EPOLL_IN | C.SRT_EPOLL_OUT | C.SRT_EPOLL_ERR | C.SRT_EPOLL_ET) 43 | //via unsafe.Pointer because we cannot cast *C.uint to *C.int directly 44 | //block poller 45 | p.pollDescLock.Lock() 46 | ret := C.srt_epoll_add_usock(p.srtEpollDescr, pd.fd, (*C.int)(unsafe.Pointer(&events))) 47 | if ret == -1 { 48 | panic("ERROR ADDING FD TO EPOLL") 49 | } 50 | p.pollDescs[pd.fd] = pd 51 | p.pollDescLock.Unlock() 52 | } 53 | 54 | func (p *pollServer) pollClose(pd *pollDesc) { 55 | sockstate := C.srt_getsockstate(pd.fd) 56 | //Broken/closed sockets get removed internally by SRT lib 57 | if sockstate == C.SRTS_BROKEN || sockstate == C.SRTS_CLOSING || sockstate == C.SRTS_CLOSED || sockstate == C.SRTS_NONEXIST { 58 | return 59 | } 60 | ret := C.srt_epoll_remove_usock(p.srtEpollDescr, pd.fd) 61 | if ret == -1 { 62 | panic("ERROR REMOVING FD FROM EPOLL") 63 | } 64 | p.pollDescLock.Lock() 65 | delete(p.pollDescs, pd.fd) 66 | p.pollDescLock.Unlock() 67 | } 68 | 69 | func init() { 70 | 71 | } 72 | 73 | func (p *pollServer) run() { 74 | timeoutMs := C.int64_t(-1) 75 | fds := [128]C.SRT_EPOLL_EVENT{} 76 | fdlen := C.int(128) 77 | for { 78 | res := C.srt_epoll_uwait(p.srtEpollDescr, &fds[0], fdlen, timeoutMs) 79 | if res == 0 { 80 | continue //Shouldn't happen with -1 81 | } else if res == -1 { 82 | panic("srt_epoll_error") 83 | } else if res > 0 { 84 | max := int(res) 85 | if fdlen < res { 86 | max = int(fdlen) 87 | } 88 | p.pollDescLock.Lock() 89 | for i := 0; i < max; i++ { 90 | s := fds[i].fd 91 | events := fds[i].events 92 | 93 | pd := p.pollDescs[s] 94 | if events&C.SRT_EPOLL_ERR != 0 { 95 | pd.unblock(ModeRead, true, false) 96 | pd.unblock(ModeWrite, true, false) 97 | continue 98 | } 99 | if events&C.SRT_EPOLL_IN != 0 { 100 | pd.unblock(ModeRead, false, true) 101 | } 102 | if events&C.SRT_EPOLL_OUT != 0 { 103 | pd.unblock(ModeWrite, false, true) 104 | } 105 | } 106 | p.pollDescLock.Unlock() 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /rw_test.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "sync" 7 | "testing" 8 | "time" 9 | ) 10 | 11 | type tester struct { 12 | blocking string // blocking state 13 | ctx context.Context // done notification for senders 14 | cancel func() // cancel tester 15 | err chan error // error output for senders/receivers 16 | started sync.WaitGroup // sync goroutines on start 17 | } 18 | 19 | // Creates a connector socket and keeps writing to it 20 | func (t *tester) send(port uint16) { 21 | buf := make([]byte, 1316) 22 | sock := NewSrtSocket("127.0.0.1", port, map[string]string{"blocking": t.blocking, "mode": "caller", "transtype": "file", "latency": "300"}) 23 | if sock == nil { 24 | t.err <- fmt.Errorf("failed to create caller socket") 25 | return 26 | } 27 | defer sock.Close() 28 | 29 | // Wait until all sockets are ready 30 | t.started.Done() 31 | t.started.Wait() 32 | 33 | err := sock.Connect() 34 | if err != nil { 35 | t.err <- fmt.Errorf("connect: %v", err) 36 | return 37 | } 38 | for { 39 | select { 40 | case <-t.ctx.Done(): 41 | return 42 | default: 43 | } 44 | _, err := sock.Write(buf) 45 | if err != nil { 46 | t.err <- fmt.Errorf("write: %v", err) 47 | return 48 | } 49 | time.Sleep(1 * time.Millisecond) // 1316 bytes every 1 ms = 1310 KB/s 50 | } 51 | } 52 | 53 | // Creates a listener socket and keeps reading from it 54 | func (t *tester) receive(port uint16, iterations int) { 55 | sock := NewSrtSocket("127.0.0.1", port, map[string]string{"blocking": t.blocking, "mode": "listener", "rcvbuf": "22937600", "transtype": "file", "latency": "300"}) 56 | if sock == nil { 57 | t.err <- fmt.Errorf("failed to create listener socket") 58 | return 59 | } 60 | buf := make([]byte, 1316) 61 | defer sock.Close() 62 | defer t.cancel() 63 | 64 | // Wait until all sockets are ready 65 | t.started.Done() 66 | t.started.Wait() 67 | 68 | err := sock.Listen(1) 69 | if err != nil { 70 | t.err <- fmt.Errorf("listen: %v", err) 71 | return 72 | } 73 | remote, _, err := sock.Accept() 74 | if err != nil { 75 | t.err <- fmt.Errorf("accept: %v", err) 76 | return 77 | } 78 | for i := 0; i < iterations; i++ { 79 | _, err := remote.Read(buf) 80 | if err != nil { 81 | t.err <- fmt.Errorf("read: %v", err) 82 | return 83 | } 84 | } 85 | } 86 | 87 | func runTransmitBench(b *testing.B, blocking bool) { 88 | blockStr := "0" 89 | if blocking { 90 | blockStr = "1" 91 | } 92 | 93 | ctx, cancel := context.WithCancel(context.Background()) 94 | defer cancel() 95 | t := &tester{ 96 | ctx: ctx, 97 | blocking: blockStr, 98 | cancel: cancel, 99 | err: make(chan error, 1), 100 | } 101 | t.started.Add(2) 102 | port := randomPort() 103 | go t.receive(port, b.N) 104 | go t.send(port) 105 | 106 | t.started.Wait() 107 | b.ResetTimer() 108 | select { 109 | case <-ctx.Done(): 110 | return 111 | case err := <-t.err: 112 | b.Error(err) 113 | } 114 | } 115 | 116 | func BenchmarkRWBlocking(b *testing.B) { 117 | runTransmitBench(b, true) 118 | } 119 | 120 | func BenchmarkRWNonBlocking(b *testing.B) { 121 | runTransmitBench(b, false) 122 | } 123 | -------------------------------------------------------------------------------- /poll.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | /* 4 | #cgo LDFLAGS: -lsrt 5 | #include 6 | */ 7 | import "C" 8 | import ( 9 | "sync" 10 | "sync/atomic" 11 | "time" 12 | ) 13 | 14 | const ( 15 | pollDefault = int32(iota) 16 | pollReady = int32(iota) 17 | pollWait = int32(iota) 18 | ) 19 | 20 | type PollMode int 21 | 22 | const ( 23 | ModeRead = PollMode(iota) 24 | ModeWrite 25 | ) 26 | 27 | /* 28 | pollDesc contains the polling state for the associated SrtSocket 29 | closing: socket is closing, reject all poll operations 30 | pollErr: an error occured on the socket, indicates it's not useable anymore. 31 | unblockRd: is used to unblock the poller when the socket becomes ready for io 32 | rdState: polling state for read operations 33 | rdDeadline: deadline in NS before poll operation times out, -1 means timedout (needs to be cleared), 0 is without timeout 34 | rdSeq: sequence number protects against spurious signalling of timeouts when timer is reset. 35 | rdTimer: timer used to enforce deadline. 36 | */ 37 | type pollDesc struct { 38 | lock sync.Mutex 39 | closing bool 40 | fd C.SRTSOCKET 41 | pollErr bool 42 | unblockRd chan interface{} 43 | rdState int32 44 | rdLock sync.Mutex 45 | rdDeadline int64 46 | rdSeq int64 47 | rdTimer *time.Timer 48 | rtSeq int64 49 | unblockWr chan interface{} 50 | wrState int32 51 | wrLock sync.Mutex 52 | wdDeadline int64 53 | wdSeq int64 54 | wdTimer *time.Timer 55 | wtSeq int64 56 | pollS *pollServer 57 | } 58 | 59 | var pdPool = sync.Pool{ 60 | New: func() interface{} { 61 | return &pollDesc{ 62 | unblockRd: make(chan interface{}, 1), 63 | unblockWr: make(chan interface{}, 1), 64 | rdTimer: time.NewTimer(0), 65 | wdTimer: time.NewTimer(0), 66 | } 67 | }, 68 | } 69 | 70 | func pollDescInit(s C.SRTSOCKET) *pollDesc { 71 | pd := pdPool.Get().(*pollDesc) 72 | pd.lock.Lock() 73 | defer pd.lock.Unlock() 74 | pd.fd = s 75 | pd.rdState = pollDefault 76 | pd.wrState = pollDefault 77 | pd.pollS = pollServerCtx() 78 | pd.closing = false 79 | pd.pollErr = false 80 | pd.rdSeq++ 81 | pd.wdSeq++ 82 | pd.pollS.pollOpen(pd) 83 | return pd 84 | } 85 | 86 | func (pd *pollDesc) release() { 87 | pd.lock.Lock() 88 | defer pd.lock.Unlock() 89 | if !pd.closing || pd.rdState == pollWait || pd.wrState == pollWait { 90 | panic("returning open or blocked upon pollDesc") 91 | } 92 | pd.fd = 0 93 | pdPool.Put(pd) 94 | } 95 | 96 | func (pd *pollDesc) wait(mode PollMode) error { 97 | defer pd.reset(mode) 98 | if err := pd.checkPollErr(mode); err != nil { 99 | return err 100 | } 101 | state := &pd.rdState 102 | unblockChan := pd.unblockRd 103 | expiryChan := pd.rdTimer.C 104 | timerSeq := int64(0) 105 | pd.lock.Lock() 106 | if mode == ModeRead { 107 | timerSeq = pd.rtSeq 108 | pd.rdLock.Lock() 109 | defer pd.rdLock.Unlock() 110 | } else if mode == ModeWrite { 111 | timerSeq = pd.wtSeq 112 | state = &pd.wrState 113 | unblockChan = pd.unblockWr 114 | expiryChan = pd.wdTimer.C 115 | pd.wrLock.Lock() 116 | defer pd.wrLock.Unlock() 117 | } 118 | 119 | for { 120 | old := *state 121 | if old == pollReady { 122 | *state = pollDefault 123 | pd.lock.Unlock() 124 | return nil 125 | } 126 | if atomic.CompareAndSwapInt32(state, pollDefault, pollWait) { 127 | break 128 | } 129 | } 130 | pd.lock.Unlock() 131 | 132 | wait: 133 | for { 134 | select { 135 | case <-unblockChan: 136 | break wait 137 | case <-expiryChan: 138 | pd.lock.Lock() 139 | if mode == ModeRead { 140 | if timerSeq == pd.rdSeq { 141 | pd.rdDeadline = -1 142 | pd.lock.Unlock() 143 | break wait 144 | } 145 | timerSeq = pd.rtSeq 146 | } 147 | if mode == ModeWrite { 148 | if timerSeq == pd.wdSeq { 149 | pd.wdDeadline = -1 150 | pd.lock.Unlock() 151 | break wait 152 | } 153 | timerSeq = pd.wtSeq 154 | } 155 | pd.lock.Unlock() 156 | } 157 | } 158 | err := pd.checkPollErr(mode) 159 | return err 160 | } 161 | 162 | func (pd *pollDesc) close() { 163 | pd.lock.Lock() 164 | defer pd.lock.Unlock() 165 | if pd.closing { 166 | return 167 | } 168 | pd.closing = true 169 | pd.pollS.pollClose(pd) 170 | } 171 | 172 | func (pd *pollDesc) checkPollErr(mode PollMode) error { 173 | pd.lock.Lock() 174 | defer pd.lock.Unlock() 175 | if pd.closing { 176 | return &SrtSocketClosed{} 177 | } 178 | 179 | if mode == ModeRead && pd.rdDeadline < 0 || mode == ModeWrite && pd.wdDeadline < 0 { 180 | return &SrtEpollTimeout{} 181 | } 182 | 183 | if pd.pollErr { 184 | return &SrtSocketClosed{} 185 | } 186 | 187 | return nil 188 | } 189 | 190 | func (pd *pollDesc) setDeadline(t time.Time, mode PollMode) { 191 | pd.lock.Lock() 192 | defer pd.lock.Unlock() 193 | var d int64 194 | if !t.IsZero() { 195 | d = int64(time.Until(t)) 196 | if d == 0 { 197 | d = -1 198 | } 199 | } 200 | if mode == ModeRead || mode == ModeRead+ModeWrite { 201 | pd.rdSeq++ 202 | pd.rtSeq = pd.rdSeq 203 | if pd.rdDeadline > 0 { 204 | pd.rdTimer.Stop() 205 | } 206 | pd.rdDeadline = d 207 | if d > 0 { 208 | pd.rdTimer.Reset(time.Duration(d)) 209 | } 210 | if d < 0 { 211 | pd.unblock(ModeRead, false, false) 212 | } 213 | } 214 | if mode == ModeWrite || mode == ModeRead+ModeWrite { 215 | pd.wdSeq++ 216 | pd.wtSeq = pd.wdSeq 217 | if pd.wdDeadline > 0 { 218 | pd.wdTimer.Stop() 219 | } 220 | pd.wdDeadline = d 221 | if d > 0 { 222 | pd.wdTimer.Reset(time.Duration(d)) 223 | } 224 | if d < 0 { 225 | pd.unblock(ModeWrite, false, false) 226 | } 227 | } 228 | } 229 | 230 | func (pd *pollDesc) unblock(mode PollMode, pollerr, ioready bool) { 231 | if pollerr { 232 | pd.lock.Lock() 233 | pd.pollErr = pollerr 234 | pd.lock.Unlock() 235 | } 236 | state := &pd.rdState 237 | unblockChan := pd.unblockRd 238 | if mode == ModeWrite { 239 | state = &pd.wrState 240 | unblockChan = pd.unblockWr 241 | } 242 | pd.lock.Lock() 243 | old := atomic.LoadInt32(state) 244 | if ioready { 245 | atomic.StoreInt32(state, pollReady) 246 | } 247 | pd.lock.Unlock() 248 | if old == pollWait { 249 | //make sure we never block here 250 | select { 251 | case unblockChan <- struct{}{}: 252 | // 253 | default: 254 | // 255 | } 256 | } 257 | } 258 | 259 | func (pd *pollDesc) reset(mode PollMode) { 260 | if mode == ModeRead { 261 | pd.rdLock.Lock() 262 | pd.rdState = pollDefault 263 | pd.rdLock.Unlock() 264 | } else if mode == ModeWrite { 265 | pd.wrLock.Lock() 266 | pd.wrState = pollDefault 267 | pd.wrLock.Unlock() 268 | } 269 | } 270 | -------------------------------------------------------------------------------- /srtgo_test.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | import ( 4 | "math/rand" 5 | "sync" 6 | "testing" 7 | "time" 8 | ) 9 | 10 | func init() { 11 | rand.Seed(time.Now().UnixNano()) 12 | } 13 | 14 | func randomPort() uint16 { 15 | return uint16(rand.Intn(32768-1024) + 1024) 16 | } 17 | 18 | func TestNewSocket(t *testing.T) { 19 | options := make(map[string]string) 20 | a := NewSrtSocket("localhost", 8090, options) 21 | 22 | if a == nil { 23 | t.Error("Could not create a srt socket") 24 | } 25 | } 26 | 27 | func TestNewSocketBlocking(t *testing.T) { 28 | options := make(map[string]string) 29 | options["blocking"] = "true" 30 | a := NewSrtSocket("localhost", 8090, options) 31 | 32 | if a == nil { 33 | t.Error("Could not create a srt socket") 34 | } 35 | } 36 | 37 | func TestNewSocketLinger(t *testing.T) { 38 | options := make(map[string]string) 39 | options["linger"] = "1000" 40 | a := NewSrtSocket("localhost", 8090, options) 41 | 42 | if a == nil { 43 | t.Error("Could not create a srt socket with linger") 44 | } 45 | 46 | // read back value to make sure 47 | res, err := getSocketLingerOption(a) 48 | if err != nil { 49 | t.Error(err) 50 | } 51 | if res != 1000 { 52 | t.Error("Failed to set linger option") 53 | } 54 | } 55 | 56 | func TestNewSocketWithTransType(t *testing.T) { 57 | options := make(map[string]string) 58 | options["transtype"] = "3" 59 | a := NewSrtSocket("localhost", 8090, options) 60 | 61 | if a == nil { 62 | t.Error("Could not create a srt socket") 63 | } 64 | } 65 | 66 | func TestNewSocketWithParameters(t *testing.T) { 67 | options := make(map[string]string) 68 | options["pbkeylen"] = "32" 69 | a := NewSrtSocket("localhost", 8090, options) 70 | 71 | if a == nil { 72 | t.Error("Could not create a srt socket") 73 | } 74 | } 75 | 76 | func TestNewSocketWithInt64Param(t *testing.T) { 77 | options := make(map[string]string) 78 | options["maxbw"] = "300000" 79 | a := NewSrtSocket("localhost", 8090, options) 80 | 81 | if a == nil { 82 | t.Error("Could not create a srt socket") 83 | } 84 | } 85 | 86 | func TestNewSocketWithBoolParam(t *testing.T) { 87 | options := make(map[string]string) 88 | options["enforcedencryption"] = "0" 89 | a := NewSrtSocket("localhost", 8090, options) 90 | 91 | if a == nil { 92 | t.Error("Could not create a srt socket") 93 | } 94 | } 95 | 96 | func TestNewSocketWithStringParam(t *testing.T) { 97 | options := make(map[string]string) 98 | options["passphrase"] = "11111111111" 99 | a := NewSrtSocket("localhost", 8090, options) 100 | 101 | if a == nil { 102 | t.Error("Could not create a srt socket") 103 | } 104 | } 105 | 106 | func TestListen(t *testing.T) { 107 | InitSRT() 108 | 109 | options := make(map[string]string) 110 | options["blocking"] = "0" 111 | options["transtype"] = "file" 112 | 113 | a := NewSrtSocket("0.0.0.0", 8090, options) 114 | err := a.Listen(2) 115 | if err != nil { 116 | t.Error("Error on testListen") 117 | } 118 | } 119 | 120 | func AcceptHelper(numSockets int, port uint16, options map[string]string, t *testing.T) { 121 | listening := make(chan struct{}) 122 | listener := NewSrtSocket("localhost", port, options) 123 | var connectors []*SrtSocket 124 | for i := 0; i < numSockets; i++ { 125 | connectors = append(connectors, NewSrtSocket("localhost", port, options)) 126 | } 127 | wg := sync.WaitGroup{} 128 | timer := time.AfterFunc(time.Second, func() { 129 | t.Log("Accept timed out") 130 | listener.Close() 131 | for _, s := range connectors { 132 | s.Close() 133 | } 134 | }) 135 | wg.Add(1) 136 | go func() { 137 | defer wg.Done() 138 | <-listening 139 | for _, s := range connectors { 140 | err := s.Connect() 141 | if err != nil { 142 | t.Error(err) 143 | } 144 | } 145 | }() 146 | 147 | err := listener.Listen(numSockets) 148 | if err != nil { 149 | t.Error(err) 150 | } 151 | listening <- struct{}{} 152 | for i := 0; i < numSockets; i++ { 153 | sock, addr, err := listener.Accept() 154 | if err != nil { 155 | t.Error(err) 156 | } 157 | if sock == nil || addr == nil { 158 | t.Error("Expected non-nil addr and sock") 159 | } 160 | } 161 | 162 | wg.Wait() 163 | if timer.Stop() { 164 | listener.Close() 165 | for _, s := range connectors { 166 | s.Close() 167 | } 168 | } 169 | } 170 | 171 | func TestAcceptNonBlocking(t *testing.T) { 172 | InitSRT() 173 | 174 | options := make(map[string]string) 175 | options["transtype"] = "file" 176 | AcceptHelper(1, 8091, options, t) 177 | } 178 | 179 | func TestAcceptBlocking(t *testing.T) { 180 | InitSRT() 181 | 182 | options := make(map[string]string) 183 | options["blocking"] = "1" 184 | options["transtype"] = "file" 185 | AcceptHelper(1, 8092, options, t) 186 | } 187 | 188 | func TestMultipleAcceptNonBlocking(t *testing.T) { 189 | InitSRT() 190 | 191 | options := make(map[string]string) 192 | options["transtype"] = "file" 193 | AcceptHelper(3, 8093, options, t) 194 | } 195 | 196 | func TestMultipleAcceptBlocking(t *testing.T) { 197 | InitSRT() 198 | 199 | options := make(map[string]string) 200 | options["blocking"] = "1" 201 | options["transtype"] = "file" 202 | AcceptHelper(3, 8094, options, t) 203 | } 204 | 205 | func TestSetSockOptInt(t *testing.T) { 206 | InitSRT() 207 | options := make(map[string]string) 208 | a := NewSrtSocket("localhost", 8090, options) 209 | 210 | expected := 200 211 | err := a.SetSockOptInt(SRTO_LATENCY, expected) 212 | if err != nil { 213 | t.Error(err) 214 | } 215 | 216 | v, err := a.GetSockOptInt(SRTO_LATENCY) 217 | if err != nil { 218 | t.Error(err) 219 | } 220 | if v != expected { 221 | t.Errorf("Failed to set SRTO_LATENCY expected %d, got %d\n", expected, v) 222 | } 223 | } 224 | 225 | func TestSetSockOptString(t *testing.T) { 226 | InitSRT() 227 | options := make(map[string]string) 228 | a := NewSrtSocket("localhost", 8090, options) 229 | 230 | expected := "123" 231 | err := a.SetSockOptString(SRTO_STREAMID, expected) 232 | if err != nil { 233 | t.Error(err) 234 | } 235 | 236 | v, err := a.GetSockOptString(SRTO_STREAMID) 237 | if err != nil { 238 | t.Error(err) 239 | } 240 | if v != expected { 241 | t.Errorf("Failed to set SRTO_STREAMID expected %s, got %s\n", expected, v) 242 | } 243 | } 244 | 245 | func TestSetSockOptBool(t *testing.T) { 246 | InitSRT() 247 | options := make(map[string]string) 248 | a := NewSrtSocket("localhost", 8090, options) 249 | 250 | expected := true 251 | err := a.SetSockOptBool(SRTO_MESSAGEAPI, expected) 252 | if err != nil { 253 | t.Error(err) 254 | } 255 | 256 | v, err := a.GetSockOptBool(SRTO_MESSAGEAPI) 257 | if err != nil { 258 | t.Error(err) 259 | } 260 | if v != expected { 261 | t.Errorf("Failed to set SRTO_MESSAGEAPI expected %t, got %t\n", expected, v) 262 | } 263 | } 264 | -------------------------------------------------------------------------------- /srtsocketoptions.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | // #cgo LDFLAGS: -lsrt 4 | // #include 5 | import "C" 6 | 7 | import ( 8 | "errors" 9 | "fmt" 10 | "strconv" 11 | "syscall" 12 | "unsafe" 13 | ) 14 | 15 | const ( 16 | transTypeLive = 0 17 | transTypeFile = 1 18 | ) 19 | 20 | const ( 21 | tInteger32 = 0 22 | tInteger64 = 1 23 | tString = 2 24 | tBoolean = 3 25 | tTransType = 4 26 | 27 | SRTO_TRANSTYPE = C.SRTO_TRANSTYPE 28 | SRTO_MAXBW = C.SRTO_MAXBW 29 | SRTO_PBKEYLEN = C.SRTO_PBKEYLEN 30 | SRTO_PASSPHRASE = C.SRTO_PASSPHRASE 31 | SRTO_MSS = C.SRTO_MSS 32 | SRTO_FC = C.SRTO_FC 33 | SRTO_SNDBUF = C.SRTO_SNDBUF 34 | SRTO_RCVBUF = C.SRTO_RCVBUF 35 | SRTO_IPTTL = C.SRTO_IPTTL 36 | SRTO_IPTOS = C.SRTO_IPTOS 37 | SRTO_INPUTBW = C.SRTO_INPUTBW 38 | SRTO_OHEADBW = C.SRTO_OHEADBW 39 | SRTO_LATENCY = C.SRTO_LATENCY 40 | SRTO_TSBPDMODE = C.SRTO_TSBPDMODE 41 | SRTO_TLPKTDROP = C.SRTO_TLPKTDROP 42 | SRTO_SNDDROPDELAY = C.SRTO_SNDDROPDELAY 43 | SRTO_NAKREPORT = C.SRTO_NAKREPORT 44 | SRTO_CONNTIMEO = C.SRTO_CONNTIMEO 45 | SRTO_LOSSMAXTTL = C.SRTO_LOSSMAXTTL 46 | SRTO_RCVLATENCY = C.SRTO_RCVLATENCY 47 | SRTO_PEERLATENCY = C.SRTO_PEERLATENCY 48 | SRTO_MINVERSION = C.SRTO_MINVERSION 49 | SRTO_STREAMID = C.SRTO_STREAMID 50 | SRTO_CONGESTION = C.SRTO_CONGESTION 51 | SRTO_MESSAGEAPI = C.SRTO_MESSAGEAPI 52 | SRTO_PAYLOADSIZE = C.SRTO_PAYLOADSIZE 53 | SRTO_KMREFRESHRATE = C.SRTO_KMREFRESHRATE 54 | SRTO_KMPREANNOUNCE = C.SRTO_KMPREANNOUNCE 55 | SRTO_ENFORCEDENCRYPTION = C.SRTO_ENFORCEDENCRYPTION 56 | SRTO_PEERIDLETIMEO = C.SRTO_PEERIDLETIMEO 57 | SRTO_PACKETFILTER = C.SRTO_PACKETFILTER 58 | SRTO_STATE = C.SRTO_STATE 59 | ) 60 | 61 | type socketOption struct { 62 | name string 63 | level int 64 | option int 65 | binding int 66 | dataType int 67 | } 68 | 69 | // List of possible srt socket options 70 | var SocketOptions = []socketOption{ 71 | {"transtype", 0, SRTO_TRANSTYPE, bindingPre, tTransType}, 72 | {"maxbw", 0, SRTO_MAXBW, bindingPre, tInteger64}, 73 | {"pbkeylen", 0, SRTO_PBKEYLEN, bindingPre, tInteger32}, 74 | {"passphrase", 0, SRTO_PASSPHRASE, bindingPre, tString}, 75 | {"mss", 0, SRTO_MSS, bindingPre, tInteger32}, 76 | {"fc", 0, SRTO_FC, bindingPre, tInteger32}, 77 | {"sndbuf", 0, SRTO_SNDBUF, bindingPre, tInteger32}, 78 | {"rcvbuf", 0, SRTO_RCVBUF, bindingPre, tInteger32}, 79 | {"ipttl", 0, SRTO_IPTTL, bindingPre, tInteger32}, 80 | {"iptos", 0, SRTO_IPTOS, bindingPre, tInteger32}, 81 | {"inputbw", 0, SRTO_INPUTBW, bindingPost, tInteger64}, 82 | {"oheadbw", 0, SRTO_OHEADBW, bindingPost, tInteger32}, 83 | {"latency", 0, SRTO_LATENCY, bindingPre, tInteger32}, 84 | {"tsbpdmode", 0, SRTO_TSBPDMODE, bindingPre, tBoolean}, 85 | {"tlpktdrop", 0, SRTO_TLPKTDROP, bindingPre, tBoolean}, 86 | {"snddropdelay", 0, SRTO_SNDDROPDELAY, bindingPost, tInteger32}, 87 | {"nakreport", 0, SRTO_NAKREPORT, bindingPre, tBoolean}, 88 | {"conntimeo", 0, SRTO_CONNTIMEO, bindingPre, tInteger32}, 89 | {"lossmaxttl", 0, SRTO_LOSSMAXTTL, bindingPre, tInteger32}, 90 | {"rcvlatency", 0, SRTO_RCVLATENCY, bindingPre, tInteger32}, 91 | {"peerlatency", 0, SRTO_PEERLATENCY, bindingPre, tInteger32}, 92 | {"minversion", 0, SRTO_MINVERSION, bindingPre, tInteger32}, 93 | {"streamid", 0, SRTO_STREAMID, bindingPre, tString}, 94 | {"congestion", 0, SRTO_CONGESTION, bindingPre, tString}, 95 | {"messageapi", 0, SRTO_MESSAGEAPI, bindingPre, tBoolean}, 96 | {"payloadsize", 0, SRTO_PAYLOADSIZE, bindingPre, tInteger32}, 97 | {"kmrefreshrate", 0, SRTO_KMREFRESHRATE, bindingPre, tInteger32}, 98 | {"kmpreannounce", 0, SRTO_KMPREANNOUNCE, bindingPre, tInteger32}, 99 | {"enforcedencryption", 0, SRTO_ENFORCEDENCRYPTION, bindingPre, tBoolean}, 100 | {"peeridletimeo", 0, SRTO_PEERIDLETIMEO, bindingPre, tInteger32}, 101 | {"packetfilter", 0, SRTO_PACKETFILTER, bindingPre, tString}, 102 | } 103 | 104 | func setSocketLingerOption(s C.int, li int32) error { 105 | var lin syscall.Linger 106 | lin.Linger = li 107 | if lin.Linger > 0 { 108 | lin.Onoff = 1 109 | } else { 110 | lin.Onoff = 0 111 | } 112 | res := C.srt_setsockopt(s, bindingPre, C.SRTO_LINGER, unsafe.Pointer(&lin), C.int(unsafe.Sizeof(lin))) 113 | if res == SRT_ERROR { 114 | return errors.New("failed to set linger") 115 | } 116 | return nil 117 | } 118 | 119 | func getSocketLingerOption(s *SrtSocket) (int32, error) { 120 | var lin syscall.Linger 121 | size := int(unsafe.Sizeof(lin)) 122 | err := s.getSockOpt(C.SRTO_LINGER, unsafe.Pointer(&lin), &size) 123 | if err != nil { 124 | return 0, err 125 | } 126 | if lin.Onoff == 0 { 127 | return 0, nil 128 | } 129 | return lin.Linger, nil 130 | } 131 | 132 | // Set socket options for SRT 133 | func setSocketOptions(s C.int, binding int, options map[string]string) error { 134 | for _, so := range SocketOptions { 135 | if val, ok := options[so.name]; ok { 136 | if so.binding == binding { 137 | if so.dataType == tInteger32 { 138 | v, err := strconv.Atoi(val) 139 | v32 := int32(v) 140 | if err == nil { 141 | result := C.srt_setsockflag(s, C.SRT_SOCKOPT(so.option), unsafe.Pointer(&v32), C.int32_t(unsafe.Sizeof(v32))) 142 | if result == -1 { 143 | return fmt.Errorf("warning - error setting option %s to %s, %w", so.name, val, srtGetAndClearError()) 144 | } 145 | } 146 | } else if so.dataType == tInteger64 { 147 | v, err := strconv.ParseInt(val, 10, 64) 148 | if err == nil { 149 | result := C.srt_setsockflag(s, C.SRT_SOCKOPT(so.option), unsafe.Pointer(&v), C.int32_t(unsafe.Sizeof(v))) 150 | if result == -1 { 151 | return fmt.Errorf("warning - error setting option %s to %s, %w", so.name, val, srtGetAndClearError()) 152 | } 153 | } 154 | } else if so.dataType == tString { 155 | sval := C.CString(val) 156 | defer C.free(unsafe.Pointer(sval)) 157 | result := C.srt_setsockflag(s, C.SRT_SOCKOPT(so.option), unsafe.Pointer(sval), C.int32_t(len(val))) 158 | if result == -1 { 159 | return fmt.Errorf("warning - error setting option %s to %s, %w", so.name, val, srtGetAndClearError()) 160 | } 161 | 162 | } else if so.dataType == tBoolean { 163 | var result C.int 164 | if val == "1" { 165 | v := C.char(1) 166 | result = C.srt_setsockflag(s, C.SRT_SOCKOPT(so.option), unsafe.Pointer(&v), C.int32_t(unsafe.Sizeof(v))) 167 | } else if val == "0" { 168 | v := C.char(0) 169 | result = C.srt_setsockflag(s, C.SRT_SOCKOPT(so.option), unsafe.Pointer(&v), C.int32_t(unsafe.Sizeof(v))) 170 | } 171 | if result == -1 { 172 | return fmt.Errorf("warning - error setting option %s to %s, %w", so.name, val, srtGetAndClearError()) 173 | } 174 | } else if so.dataType == tTransType { 175 | var result C.int 176 | if val == "live" { 177 | var v int32 = C.SRTT_LIVE 178 | result = C.srt_setsockflag(s, C.SRT_SOCKOPT(so.option), unsafe.Pointer(&v), C.int32_t(unsafe.Sizeof(v))) 179 | } else if val == "file" { 180 | var v int32 = C.SRTT_FILE 181 | result = C.srt_setsockflag(s, C.SRT_SOCKOPT(so.option), unsafe.Pointer(&v), C.int32_t(unsafe.Sizeof(v))) 182 | } 183 | if result == -1 { 184 | return fmt.Errorf("warning - error setting option %s to %s: %w", so.name, val, srtGetAndClearError()) 185 | } 186 | } 187 | } 188 | } 189 | } 190 | return nil 191 | } 192 | -------------------------------------------------------------------------------- /srtstats.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | // #cgo LDFLAGS: -lsrt 4 | // #include 5 | import "C" 6 | 7 | type SrtStats struct { 8 | // Global measurements 9 | MsTimeStamp int64 // time since the UDT entity is started, in milliseconds 10 | PktSentTotal int64 // total number of sent data packets, including retransmissions 11 | PktRecvTotal int64 // total number of received packets 12 | PktSndLossTotal int // total number of lost packets (sender side) 13 | PktRcvLossTotal int // total number of lost packets (receiver side) 14 | PktRetransTotal int // total number of retransmitted packets 15 | PktSentACKTotal int // total number of sent ACK packets 16 | PktRecvACKTotal int // total number of received ACK packets 17 | PktSentNAKTotal int // total number of sent NAK packets 18 | PktRecvNAKTotal int // total number of received NAK packets 19 | UsSndDurationTotal int64 // total time duration when UDT is sending data (idle time exclusive) 20 | 21 | PktSndDropTotal int // number of too-late-to-send dropped packets 22 | PktRcvDropTotal int // number of too-late-to play missing packets 23 | PktRcvUndecryptTotal int // number of undecrypted packets 24 | ByteSentTotal int64 // total number of sent data bytes, including retransmissions 25 | ByteRecvTotal int64 // total number of received bytes 26 | ByteRcvLossTotal int64 // total number of lost bytes 27 | 28 | ByteRetransTotal int64 // total number of retransmitted bytes 29 | ByteSndDropTotal int64 // number of too-late-to-send dropped bytes 30 | ByteRcvDropTotal int64 // number of too-late-to play missing bytes (estimate based on average packet size) 31 | ByteRcvUndecryptTotal int64 // number of undecrypted bytes 32 | 33 | // Local measurements 34 | PktSent int64 // number of sent data packets, including retransmissions 35 | PktRecv int64 // number of received packets 36 | PktSndLoss int // number of lost packets (sender side) 37 | PktRcvLoss int // number of lost packets (receiver side) 38 | PktRetrans int // number of retransmitted packets 39 | PktRcvRetrans int // number of retransmitted packets received 40 | PktSentACK int // number of sent ACK packets 41 | PktRecvACK int // number of received ACK packets 42 | PktSentNAK int // number of sent NAK packets 43 | PktRecvNAK int // number of received NAK packets 44 | MbpsSendRate float64 // sending rate in Mb/s 45 | MbpsRecvRate float64 // receiving rate in Mb/s 46 | UsSndDuration int64 // busy sending time (i.e., idle time exclusive) 47 | PktReorderDistance int // size of order discrepancy in received sequences 48 | PktRcvAvgBelatedTime float64 // average time of packet delay for belated packets (packets with sequence past the ACK) 49 | PktRcvBelated int64 // number of received AND IGNORED packets due to having come too late 50 | 51 | PktSndDrop int // number of too-late-to-send dropped packets 52 | PktRcvDrop int // number of too-late-to play missing packets 53 | PktRcvUndecrypt int // number of undecrypted packets 54 | ByteSent int64 // number of sent data bytes, including retransmissions 55 | ByteRecv int64 // number of received bytes 56 | 57 | ByteRcvLoss int64 // number of retransmitted Bytes 58 | ByteRetrans int64 // number of retransmitted Bytes 59 | ByteSndDrop int64 // number of too-late-to-send dropped Bytes 60 | ByteRcvDrop int64 // number of too-late-to play missing Bytes (estimate based on average packet size) 61 | ByteRcvUndecrypt int64 // number of undecrypted bytes 62 | 63 | // Instant measurements 64 | UsPktSndPeriod float64 // packet sending period, in microseconds 65 | PktFlowWindow int // flow window size, in number of packets 66 | PktCongestionWindow int // congestion window size, in number of packets 67 | PktFlightSize int // number of packets on flight 68 | MsRTT float64 // RTT, in milliseconds 69 | MbpsBandwidth float64 // estimated bandwidth, in Mb/s 70 | ByteAvailSndBuf int // available UDT sender buffer size 71 | ByteAvailRcvBuf int // available UDT receiver buffer size 72 | 73 | MbpsMaxBW float64 // Transmit Bandwidth ceiling (Mbps) 74 | ByteMSS int // MTU 75 | 76 | PktSndBuf int // UnACKed packets in UDT sender 77 | ByteSndBuf int // UnACKed bytes in UDT sender 78 | MsSndBuf int // UnACKed timespan (msec) of UDT sender 79 | MsSndTsbPdDelay int // Timestamp-based Packet Delivery Delay 80 | 81 | PktRcvBuf int // Undelivered packets in UDT receiver 82 | ByteRcvBuf int // Undelivered bytes of UDT receiver 83 | MsRcvBuf int // Undelivered timespan (msec) of UDT receiver 84 | MsRcvTsbPdDelay int // Timestamp-based Packet Delivery Delay 85 | 86 | PktSndFilterExtraTotal int // number of control packets supplied by packet filter 87 | PktRcvFilterExtraTotal int // number of control packets received and not supplied back 88 | PktRcvFilterSupplyTotal int // number of packets that the filter supplied extra (e.g. FEC rebuilt) 89 | PktRcvFilterLossTotal int // number of packet loss not coverable by filter 90 | 91 | PktSndFilterExtra int // number of control packets supplied by packet filter 92 | PktRcvFilterExtra int // number of control packets received and not supplied back 93 | PktRcvFilterSupply int // number of packets that the filter supplied extra (e.g. FEC rebuilt) 94 | PktRcvFilterLoss int // number of packet loss not coverable by filter 95 | PktReorderTolerance int // packet reorder tolerance value 96 | } 97 | 98 | func newSrtStats(stats *C.SRT_TRACEBSTATS) *SrtStats { 99 | s := new(SrtStats) 100 | 101 | s.MsTimeStamp = int64(stats.msTimeStamp) 102 | s.PktSentTotal = int64(stats.pktSentTotal) 103 | s.PktRecvTotal = int64(stats.pktRecvTotal) 104 | s.PktSndLossTotal = int(stats.pktSndLossTotal) 105 | s.PktRcvLossTotal = int(stats.pktRcvLossTotal) 106 | s.PktRetransTotal = int(stats.pktRetransTotal) 107 | s.PktSentACKTotal = int(stats.pktSentACKTotal) 108 | s.PktRecvACKTotal = int(stats.pktRecvACKTotal) 109 | s.PktSentNAKTotal = int(stats.pktSentNAKTotal) 110 | s.PktRecvNAKTotal = int(stats.pktRecvNAKTotal) 111 | s.UsSndDurationTotal = int64(stats.usSndDurationTotal) 112 | 113 | s.PktSndDropTotal = int(stats.pktSndDropTotal) 114 | s.PktRcvDropTotal = int(stats.pktRcvDropTotal) 115 | s.PktRcvUndecryptTotal = int(stats.pktRcvUndecryptTotal) 116 | s.ByteSentTotal = int64(stats.byteSentTotal) 117 | s.ByteRecvTotal = int64(stats.byteRecvTotal) 118 | s.ByteRcvLossTotal = int64(stats.byteRcvLossTotal) 119 | 120 | s.ByteRetransTotal = int64(stats.byteRetransTotal) 121 | s.ByteSndDropTotal = int64(stats.byteSndDropTotal) 122 | s.ByteRcvDropTotal = int64(stats.byteRcvDropTotal) 123 | s.ByteRcvUndecryptTotal = int64(stats.byteRcvUndecryptTotal) 124 | 125 | s.PktSent = int64(stats.pktSent) 126 | s.PktRecv = int64(stats.pktRecv) 127 | s.PktSndLoss = int(stats.pktSndLoss) 128 | s.PktRcvLoss = int(stats.pktRcvLoss) 129 | s.PktRetrans = int(stats.pktRetrans) 130 | s.PktRcvRetrans = int(stats.pktRcvRetrans) 131 | s.PktSentACK = int(stats.pktSentACK) 132 | s.PktRecvACK = int(stats.pktRecvACK) 133 | s.PktSentNAK = int(stats.pktSentNAK) 134 | s.PktRecvNAK = int(stats.pktRecvNAK) 135 | s.MbpsSendRate = float64(stats.mbpsSendRate) 136 | s.MbpsRecvRate = float64(stats.mbpsRecvRate) 137 | s.UsSndDuration = int64(stats.usSndDuration) 138 | s.PktReorderDistance = int(stats.pktReorderDistance) 139 | s.PktRcvAvgBelatedTime = float64(stats.pktRcvAvgBelatedTime) 140 | s.PktRcvBelated = int64(stats.pktRcvBelated) 141 | 142 | s.PktSndDrop = int(stats.pktSndDrop) 143 | s.PktRcvDrop = int(stats.pktRcvDrop) 144 | s.PktRcvUndecrypt = int(stats.pktRcvUndecrypt) 145 | s.ByteSent = int64(stats.byteSent) 146 | s.ByteRecv = int64(stats.byteRecv) 147 | 148 | s.ByteRcvLoss = int64(stats.byteRcvLoss) 149 | s.ByteRetrans = int64(stats.byteRetrans) 150 | s.ByteSndDrop = int64(stats.byteSndDrop) 151 | s.ByteRcvDrop = int64(stats.byteRcvDrop) 152 | s.ByteRcvUndecrypt = int64(stats.byteRcvUndecrypt) 153 | 154 | s.UsPktSndPeriod = float64(stats.usPktSndPeriod) 155 | s.PktFlowWindow = int(stats.pktFlowWindow) 156 | s.PktCongestionWindow = int(stats.pktCongestionWindow) 157 | s.PktFlightSize = int(stats.pktFlightSize) 158 | s.MsRTT = float64(stats.msRTT) 159 | s.MbpsBandwidth = float64(stats.mbpsBandwidth) 160 | s.ByteAvailSndBuf = int(stats.byteAvailSndBuf) 161 | s.ByteAvailRcvBuf = int(stats.byteAvailRcvBuf) 162 | 163 | s.MbpsMaxBW = float64(stats.mbpsMaxBW) 164 | s.ByteMSS = int(stats.byteMSS) 165 | 166 | s.PktSndBuf = int(stats.pktSndBuf) 167 | s.ByteSndBuf = int(stats.byteSndBuf) 168 | s.MsSndBuf = int(stats.msSndBuf) 169 | s.MsSndTsbPdDelay = int(stats.msSndTsbPdDelay) 170 | 171 | s.PktRcvBuf = int(stats.pktRcvBuf) 172 | s.ByteRcvBuf = int(stats.byteRcvBuf) 173 | s.MsRcvBuf = int(stats.msRcvBuf) 174 | s.MsRcvTsbPdDelay = int(stats.msRcvTsbPdDelay) 175 | 176 | s.PktSndFilterExtraTotal = int(stats.pktSndFilterExtraTotal) 177 | s.PktRcvFilterExtraTotal = int(stats.pktRcvFilterExtraTotal) 178 | s.PktRcvFilterSupplyTotal = int(stats.pktRcvFilterSupplyTotal) 179 | s.PktRcvFilterLossTotal = int(stats.pktRcvFilterLossTotal) 180 | 181 | s.PktSndFilterExtra = int(stats.pktSndFilterExtra) 182 | s.PktRcvFilterExtra = int(stats.pktRcvFilterExtra) 183 | s.PktRcvFilterSupply = int(stats.pktRcvFilterSupply) 184 | s.PktRcvFilterLoss = int(stats.pktRcvFilterLoss) 185 | s.PktReorderTolerance = int(stats.pktReorderTolerance) 186 | 187 | return s 188 | } 189 | -------------------------------------------------------------------------------- /errors.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | /* 4 | #cgo LDFLAGS: -lsrt 5 | #include 6 | */ 7 | import "C" 8 | import ( 9 | "strconv" 10 | "syscall" 11 | ) 12 | 13 | type SrtInvalidSock struct{} 14 | type SrtRendezvousUnbound struct{} 15 | type SrtSockConnected struct{} 16 | type SrtConnectionRejected struct{} 17 | type SrtConnectTimeout struct{} 18 | type SrtSocketClosed struct{} 19 | type SrtEpollTimeout struct{} 20 | 21 | func (m *SrtInvalidSock) Error() string { 22 | return "Socket u indicates no valid socket ID" 23 | } 24 | 25 | func (m *SrtRendezvousUnbound) Error() string { 26 | return "Socket u is in rendezvous mode, but it wasn't bound" 27 | } 28 | 29 | func (m *SrtSockConnected) Error() string { 30 | return "Socket u is already connected" 31 | } 32 | 33 | func (m *SrtConnectionRejected) Error() string { 34 | return "Connection has been rejected" 35 | } 36 | 37 | func (m *SrtConnectTimeout) Error() string { 38 | return "Connection has been timed out" 39 | } 40 | 41 | func (m *SrtSocketClosed) Error() string { 42 | return "The socket has been closed" 43 | } 44 | 45 | func (m *SrtEpollTimeout) Error() string { 46 | return "Operation has timed out" 47 | } 48 | 49 | func (m *SrtEpollTimeout) Timeout() bool { 50 | return true 51 | } 52 | 53 | func (m *SrtEpollTimeout) Temporary() bool { 54 | return true 55 | } 56 | 57 | //MUST be called from same OS thread that generated the error (i.e.: use runtime.LockOSThread()) 58 | func srtGetAndClearError() error { 59 | defer C.srt_clearlasterror() 60 | eSysErrno := C.int(0) 61 | errno := C.srt_getlasterror(&eSysErrno) 62 | srterr := SRTErrno(errno) 63 | if eSysErrno != 0 { 64 | return srterr.wrapSysErr(syscall.Errno(eSysErrno)) 65 | } 66 | return srterr 67 | } 68 | 69 | //Based of off golang errno handling: https://cs.opensource.google/go/go/+/refs/tags/go1.16.6:src/syscall/syscall_unix.go;l=114 70 | type SRTErrno int 71 | 72 | func (e SRTErrno) Error() string { 73 | //Workaround for unknown being -1 74 | if e == Unknown { 75 | return "Internal error when setting the right error code" 76 | } 77 | if 0 <= int(e) && int(e) < len(srterrors) { 78 | s := srterrors[e] 79 | if s != "" { 80 | return s 81 | } 82 | } 83 | return "srterrno: " + strconv.Itoa(int(e)) 84 | } 85 | 86 | func (e SRTErrno) Is(target error) bool { 87 | //for backwards compat 88 | switch target.(type) { 89 | case *SrtInvalidSock: 90 | return e == EInvSock 91 | case *SrtRendezvousUnbound: 92 | return e == ERdvUnbound 93 | case *SrtSockConnected: 94 | return e == EConnSock 95 | case *SrtConnectionRejected: 96 | return e == EConnRej 97 | case *SrtConnectTimeout: 98 | return e == ETimeout 99 | case *SrtSocketClosed: 100 | return e == ESClosed 101 | } 102 | return false 103 | } 104 | 105 | func (e SRTErrno) Temporary() bool { 106 | return e == EAsyncFAIL || e == EAsyncRCV || e == EAsyncSND || e == ECongest || e == ETimeout 107 | } 108 | 109 | func (e SRTErrno) Timeout() bool { 110 | return e == ETimeout 111 | } 112 | 113 | func (e SRTErrno) wrapSysErr(errno syscall.Errno) error { 114 | return &srtErrnoSysErrnoWrapped{ 115 | e: e, 116 | eSys: errno, 117 | } 118 | } 119 | 120 | type srtErrnoSysErrnoWrapped struct { 121 | e SRTErrno 122 | eSys syscall.Errno 123 | } 124 | 125 | func (e *srtErrnoSysErrnoWrapped) Error() string { 126 | return e.e.Error() 127 | } 128 | 129 | func (e *srtErrnoSysErrnoWrapped) Is(target error) bool { 130 | return e.e.Is(target) 131 | } 132 | 133 | func (e *srtErrnoSysErrnoWrapped) Temporary() bool { 134 | return e.e.Temporary() 135 | } 136 | 137 | func (e *srtErrnoSysErrnoWrapped) Timeout() bool { 138 | return e.e.Timeout() 139 | } 140 | 141 | func (e *srtErrnoSysErrnoWrapped) Unwrap() error { 142 | return error(e.eSys) 143 | } 144 | 145 | //Shadows SRT_ERRNO srtcore/srt.h line 490+ 146 | const ( 147 | Unknown = SRTErrno(C.SRT_EUNKNOWN) 148 | Success = SRTErrno(C.SRT_SUCCESS) 149 | //Major: SETUP 150 | EConnSetup = SRTErrno(C.SRT_ECONNSETUP) 151 | ENoServer = SRTErrno(C.SRT_ENOSERVER) 152 | EConnRej = SRTErrno(C.SRT_ECONNREJ) 153 | ESockFail = SRTErrno(C.SRT_ESOCKFAIL) 154 | ESecFail = SRTErrno(C.SRT_ESECFAIL) 155 | ESClosed = SRTErrno(C.SRT_ESCLOSED) 156 | //Major: CONNECTION 157 | EConnFail = SRTErrno(C.SRT_ECONNFAIL) 158 | EConnLost = SRTErrno(C.SRT_ECONNLOST) 159 | ENoConn = SRTErrno(C.SRT_ENOCONN) 160 | //Major: SYSTEMRES 161 | EResource = SRTErrno(C.SRT_ERESOURCE) 162 | EThread = SRTErrno(C.SRT_ETHREAD) 163 | EnoBuf = SRTErrno(C.SRT_ENOBUF) 164 | ESysObj = SRTErrno(C.SRT_ESYSOBJ) 165 | //Major: FILESYSTEM 166 | EFile = SRTErrno(C.SRT_EFILE) 167 | EInvRdOff = SRTErrno(C.SRT_EINVRDOFF) 168 | ERdPerm = SRTErrno(C.SRT_ERDPERM) 169 | EInvWrOff = SRTErrno(C.SRT_EINVWROFF) 170 | EWrPerm = SRTErrno(C.SRT_EWRPERM) 171 | //Major: NOTSUP 172 | EInvOp = SRTErrno(C.SRT_EINVOP) 173 | EBoundSock = SRTErrno(C.SRT_EBOUNDSOCK) 174 | EConnSock = SRTErrno(C.SRT_ECONNSOCK) 175 | EInvParam = SRTErrno(C.SRT_EINVPARAM) 176 | EInvSock = SRTErrno(C.SRT_EINVSOCK) 177 | EUnboundSock = SRTErrno(C.SRT_EUNBOUNDSOCK) 178 | ENoListen = SRTErrno(C.SRT_ENOLISTEN) 179 | ERdvNoServ = SRTErrno(C.SRT_ERDVNOSERV) 180 | ERdvUnbound = SRTErrno(C.SRT_ERDVUNBOUND) 181 | EInvalMsgAPI = SRTErrno(C.SRT_EINVALMSGAPI) 182 | EInvalBufferAPI = SRTErrno(C.SRT_EINVALBUFFERAPI) 183 | EDupListen = SRTErrno(C.SRT_EDUPLISTEN) 184 | ELargeMsg = SRTErrno(C.SRT_ELARGEMSG) 185 | EInvPollID = SRTErrno(C.SRT_EINVPOLLID) 186 | EPollEmpty = SRTErrno(C.SRT_EPOLLEMPTY) 187 | //EBindConflict = SRTErrno(C.SRT_EBINDCONFLICT) 188 | //Major: AGAIN 189 | EAsyncFAIL = SRTErrno(C.SRT_EASYNCFAIL) 190 | EAsyncSND = SRTErrno(C.SRT_EASYNCSND) 191 | EAsyncRCV = SRTErrno(C.SRT_EASYNCRCV) 192 | ETimeout = SRTErrno(C.SRT_ETIMEOUT) 193 | ECongest = SRTErrno(C.SRT_ECONGEST) 194 | //Major: PEERERROR 195 | EPeer = SRTErrno(C.SRT_EPEERERR) 196 | ) 197 | 198 | //Unknown cannot be here since it would have a negative index! 199 | //Error strings taken from: https://github.com/Haivision/srt/blob/master/docs/API/API-functions.md 200 | var srterrors = [...]string{ 201 | Success: "The value set when the last error was cleared and no error has occurred since then", 202 | EConnSetup: "General setup error resulting from internal system state", 203 | ENoServer: "Connection timed out while attempting to connect to the remote address", 204 | EConnRej: "Connection has been rejected", 205 | ESockFail: "An error occurred when trying to call a system function on an internally used UDP socket", 206 | ESecFail: "A possible tampering with the handshake packets was detected, or encryption request wasn't properly fulfilled.", 207 | ESClosed: "A socket that was vital for an operation called in blocking mode has been closed during the operation", 208 | EConnFail: "General connection failure of unknown details", 209 | EConnLost: "The socket was properly connected, but the connection has been broken", 210 | ENoConn: "The socket is not connected", 211 | EResource: "System or standard library error reported unexpectedly for unknown purpose", 212 | EThread: "System was unable to spawn a new thread when requried", 213 | EnoBuf: "System was unable to allocate memory for buffers", 214 | ESysObj: "System was unable to allocate system specific objects", 215 | EFile: "General filesystem error (for functions operating with file transmission)", 216 | EInvRdOff: "Failure when trying to read from a given position in the file", 217 | ERdPerm: "Read permission was denied when trying to read from file", 218 | EInvWrOff: "Failed to set position in the written file", 219 | EWrPerm: "Write permission was denied when trying to write to a file", 220 | EInvOp: "Invalid operation performed for the current state of a socket", 221 | EBoundSock: "The socket is currently bound and the required operation cannot be performed in this state", 222 | EConnSock: "The socket is currently connected and therefore performing the required operation is not possible", 223 | EInvParam: "Call parameters for API functions have some requirements that were not satisfied", 224 | EInvSock: "The API function required an ID of an entity (socket or group) and it was invalid", 225 | EUnboundSock: "The operation to be performed on a socket requires that it first be explicitly bound", 226 | ENoListen: "The socket passed for the operation is required to be in the listen state", 227 | ERdvNoServ: "The required operation cannot be performed when the socket is set to rendezvous mode", 228 | ERdvUnbound: "An attempt was made to connect to a socket set to rendezvous mode that was not first bound", 229 | EInvalMsgAPI: "The function was used incorrectly in the message API", 230 | EInvalBufferAPI: "The function was used incorrectly in the stream (buffer) API", 231 | EDupListen: "The port tried to be bound for listening is already busy", 232 | ELargeMsg: "Size exceeded", 233 | EInvPollID: "The epoll ID passed to an epoll function is invalid", 234 | EPollEmpty: "The epoll container currently has no subscribed sockets", 235 | //EBindConflict: "SRT_EBINDCONFLICT", 236 | EAsyncFAIL: "General asynchronous failure (not in use currently)", 237 | EAsyncSND: "Sending operation is not ready to perform", 238 | EAsyncRCV: "Receiving operation is not ready to perform", 239 | ETimeout: "The operation timed out", 240 | ECongest: "With SRTO_TSBPDMODE and SRTO_TLPKTDROP set to true, some packets were dropped by sender", 241 | EPeer: "Receiver peer is writing to a file that the agent is sending", 242 | } 243 | -------------------------------------------------------------------------------- /srtgo.go: -------------------------------------------------------------------------------- 1 | package srtgo 2 | 3 | /* 4 | #cgo LDFLAGS: -lsrt 5 | #include 6 | #include 7 | #include "callback.h" 8 | static const SRTSOCKET get_srt_invalid_sock() { return SRT_INVALID_SOCK; }; 9 | static const int get_srt_error() { return SRT_ERROR; }; 10 | static const int get_srt_error_reject_predefined() { return SRT_REJC_PREDEFINED; }; 11 | static const int get_srt_error_reject_userdefined() { return SRT_REJC_USERDEFINED; }; 12 | */ 13 | import "C" 14 | 15 | import ( 16 | "errors" 17 | "fmt" 18 | "net" 19 | "runtime" 20 | "strconv" 21 | "sync" 22 | "syscall" 23 | "time" 24 | "unsafe" 25 | 26 | gopointer "github.com/mattn/go-pointer" 27 | ) 28 | 29 | // SRT Socket mode 30 | const ( 31 | ModeFailure = iota 32 | ModeListener 33 | ModeCaller 34 | ModeRendezvouz 35 | ) 36 | 37 | // Binding ops 38 | const ( 39 | bindingPre = 0 40 | bindingPost = 1 41 | ) 42 | 43 | // SrtSocket - SRT socket 44 | type SrtSocket struct { 45 | socket C.int 46 | blocking bool 47 | pd *pollDesc 48 | host string 49 | port uint16 50 | options map[string]string 51 | mode int 52 | pktSize int 53 | pollTimeout int64 54 | } 55 | 56 | var ( 57 | callbackMutex sync.Mutex 58 | listenCallbackMap map[C.int]unsafe.Pointer = make(map[C.int]unsafe.Pointer) 59 | connectCallbackMap map[C.int]unsafe.Pointer = make(map[C.int]unsafe.Pointer) 60 | ) 61 | 62 | // Static consts from library 63 | var ( 64 | SRT_INVALID_SOCK = C.get_srt_invalid_sock() 65 | SRT_ERROR = C.get_srt_error() 66 | SRTS_CONNECTED = C.SRTS_CONNECTED 67 | ) 68 | 69 | const defaultPacketSize = 1456 70 | 71 | // InitSRT - Initialize srt library 72 | func InitSRT() { 73 | C.srt_startup() 74 | } 75 | 76 | // CleanupSRT - Cleanup SRT lib 77 | func CleanupSRT() { 78 | C.srt_cleanup() 79 | } 80 | 81 | // NewSrtSocket - Create a new SRT Socket 82 | func NewSrtSocket(host string, port uint16, options map[string]string) *SrtSocket { 83 | s := new(SrtSocket) 84 | 85 | s.socket = C.srt_create_socket() 86 | if s.socket == SRT_INVALID_SOCK { 87 | return nil 88 | } 89 | 90 | s.host = host 91 | s.port = port 92 | s.options = options 93 | s.pollTimeout = -1 94 | 95 | val, exists := options["pktsize"] 96 | if exists { 97 | pktSize, err := strconv.Atoi(val) 98 | if err != nil { 99 | s.pktSize = pktSize 100 | } 101 | } 102 | if s.pktSize <= 0 { 103 | s.pktSize = defaultPacketSize 104 | } 105 | 106 | val, exists = options["blocking"] 107 | if exists && val != "0" { 108 | s.blocking = true 109 | } 110 | 111 | if !s.blocking { 112 | s.pd = pollDescInit(s.socket) 113 | } 114 | 115 | finalizer := func(obj interface{}) { 116 | sf := obj.(*SrtSocket) 117 | sf.Close() 118 | if sf.pd != nil { 119 | sf.pd.release() 120 | } 121 | } 122 | 123 | //Cleanup SrtSocket if no references exist anymore 124 | runtime.SetFinalizer(s, finalizer) 125 | 126 | var err error 127 | s.mode, err = s.preconfiguration() 128 | if err != nil { 129 | return nil 130 | } 131 | 132 | return s 133 | } 134 | 135 | func newFromSocket(acceptSocket *SrtSocket, socket C.SRTSOCKET) (*SrtSocket, error) { 136 | s := new(SrtSocket) 137 | s.socket = socket 138 | s.pktSize = acceptSocket.pktSize 139 | s.blocking = acceptSocket.blocking 140 | s.pollTimeout = acceptSocket.pollTimeout 141 | 142 | err := acceptSocket.postconfiguration(s) 143 | if err != nil { 144 | return nil, err 145 | } 146 | 147 | if !s.blocking { 148 | s.pd = pollDescInit(s.socket) 149 | } 150 | 151 | finalizer := func(obj interface{}) { 152 | sf := obj.(*SrtSocket) 153 | sf.Close() 154 | if sf.pd != nil { 155 | sf.pd.release() 156 | } 157 | } 158 | 159 | //Cleanup SrtSocket if no references exist anymore 160 | runtime.SetFinalizer(s, finalizer) 161 | 162 | return s, nil 163 | } 164 | 165 | func (s SrtSocket) GetSocket() C.int { 166 | return s.socket 167 | } 168 | 169 | // Listen for incoming connections. The backlog setting defines how many sockets 170 | // may be allowed to wait until they are accepted (excessive connection requests 171 | // are rejected in advance) 172 | func (s *SrtSocket) Listen(backlog int) error { 173 | runtime.LockOSThread() 174 | defer runtime.UnlockOSThread() 175 | nbacklog := C.int(backlog) 176 | 177 | sa, salen, err := CreateAddrInet(s.host, s.port) 178 | if err != nil { 179 | return err 180 | } 181 | 182 | res := C.srt_bind(s.socket, sa, C.int(salen)) 183 | if res == SRT_ERROR { 184 | C.srt_close(s.socket) 185 | return fmt.Errorf("Error in srt_bind: %w", srtGetAndClearError()) 186 | } 187 | 188 | res = C.srt_listen(s.socket, nbacklog) 189 | if res == SRT_ERROR { 190 | C.srt_close(s.socket) 191 | return fmt.Errorf("Error in srt_listen: %w", srtGetAndClearError()) 192 | } 193 | 194 | err = s.postconfiguration(s) 195 | if err != nil { 196 | return fmt.Errorf("Error setting post socket options") 197 | } 198 | 199 | return nil 200 | } 201 | 202 | // Connect to a remote endpoint 203 | func (s *SrtSocket) Connect() error { 204 | runtime.LockOSThread() 205 | defer runtime.UnlockOSThread() 206 | sa, salen, err := CreateAddrInet(s.host, s.port) 207 | if err != nil { 208 | return err 209 | } 210 | 211 | res := C.srt_connect(s.socket, sa, C.int(salen)) 212 | if res == SRT_ERROR { 213 | C.srt_close(s.socket) 214 | return srtGetAndClearError() 215 | } 216 | 217 | if !s.blocking { 218 | if err := s.pd.wait(ModeWrite); err != nil { 219 | return err 220 | } 221 | } 222 | 223 | err = s.postconfiguration(s) 224 | if err != nil { 225 | return fmt.Errorf("Error setting post socket options in connect") 226 | } 227 | 228 | return nil 229 | } 230 | 231 | // Stats - Retrieve stats from the SRT socket 232 | func (s SrtSocket) Stats() (*SrtStats, error) { 233 | runtime.LockOSThread() 234 | defer runtime.UnlockOSThread() 235 | var stats C.SRT_TRACEBSTATS = C.SRT_TRACEBSTATS{} 236 | var b C.int = 1 237 | if C.srt_bstats(s.socket, &stats, b) == SRT_ERROR { 238 | return nil, fmt.Errorf("Error getting stats, %w", srtGetAndClearError()) 239 | } 240 | 241 | return newSrtStats(&stats), nil 242 | } 243 | 244 | // Mode - Return working mode of the SRT socket 245 | func (s SrtSocket) Mode() int { 246 | return s.mode 247 | } 248 | 249 | // PacketSize - Return packet size of the SRT socket 250 | func (s SrtSocket) PacketSize() int { 251 | return s.pktSize 252 | } 253 | 254 | // PollTimeout - Return polling max time, for connect/read/write operations. 255 | // Only applied when socket is in non-blocking mode. 256 | func (s SrtSocket) PollTimeout() time.Duration { 257 | return time.Duration(s.pollTimeout) * time.Millisecond 258 | } 259 | 260 | // SetPollTimeout - Sets polling max time, for connect/read/write operations. 261 | // Only applied when socket is in non-blocking mode. 262 | func (s *SrtSocket) SetPollTimeout(pollTimeout time.Duration) { 263 | s.pollTimeout = pollTimeout.Milliseconds() 264 | } 265 | 266 | func (s *SrtSocket) SetDeadline(deadline time.Time) { 267 | s.pd.setDeadline(deadline, ModeRead+ModeWrite) 268 | } 269 | 270 | func (s *SrtSocket) SetReadDeadline(deadline time.Time) { 271 | s.pd.setDeadline(deadline, ModeRead) 272 | } 273 | 274 | func (s *SrtSocket) SetWriteDeadline(deadline time.Time) { 275 | s.pd.setDeadline(deadline, ModeWrite) 276 | } 277 | 278 | // Close the SRT socket 279 | func (s *SrtSocket) Close() { 280 | 281 | C.srt_close(s.socket) 282 | s.socket = SRT_INVALID_SOCK 283 | if !s.blocking { 284 | s.pd.close() 285 | } 286 | callbackMutex.Lock() 287 | if ptr, exists := listenCallbackMap[s.socket]; exists { 288 | gopointer.Unref(ptr) 289 | } 290 | if ptr, exists := connectCallbackMap[s.socket]; exists { 291 | gopointer.Unref(ptr) 292 | } 293 | callbackMutex.Unlock() 294 | } 295 | 296 | // ListenCallbackFunc specifies a function to be called before a connecting socket is passed to accept 297 | type ListenCallbackFunc func(socket *SrtSocket, version int, addr *net.UDPAddr, streamid string) bool 298 | 299 | //export srtListenCBWrapper 300 | func srtListenCBWrapper(arg unsafe.Pointer, socket C.SRTSOCKET, hsVersion C.int, peeraddr *C.struct_sockaddr, streamid *C.char) C.int { 301 | userCB := gopointer.Restore(arg).(ListenCallbackFunc) 302 | 303 | s := new(SrtSocket) 304 | s.socket = socket 305 | udpAddr, _ := udpAddrFromSockaddr((*syscall.RawSockaddrAny)(unsafe.Pointer(peeraddr))) 306 | 307 | if userCB(s, int(hsVersion), udpAddr, C.GoString(streamid)) { 308 | return 0 309 | } 310 | return SRT_ERROR 311 | } 312 | 313 | // SetListenCallback - set a function to be called early in the handshake before a client 314 | // is handed to accept on a listening socket. 315 | // The connection can be rejected by returning false from the callback. 316 | // See examples/echo-receiver for more details. 317 | func (s SrtSocket) SetListenCallback(cb ListenCallbackFunc) { 318 | ptr := gopointer.Save(cb) 319 | C.srt_listen_callback(s.socket, (*C.srt_listen_callback_fn)(C.srtListenCB), ptr) 320 | 321 | callbackMutex.Lock() 322 | defer callbackMutex.Unlock() 323 | if listenCallbackMap[s.socket] != nil { 324 | gopointer.Unref(listenCallbackMap[s.socket]) 325 | } 326 | listenCallbackMap[s.socket] = ptr 327 | } 328 | 329 | // ConnectCallbackFunc specifies a function to be called after a socket or connection in a group has failed. 330 | type ConnectCallbackFunc func(socket *SrtSocket, err error, addr *net.UDPAddr, token int) 331 | 332 | //export srtConnectCBWrapper 333 | func srtConnectCBWrapper(arg unsafe.Pointer, socket C.SRTSOCKET, errcode C.int, peeraddr *C.struct_sockaddr, token C.int) { 334 | userCB := gopointer.Restore(arg).(ConnectCallbackFunc) 335 | 336 | s := new(SrtSocket) 337 | s.socket = socket 338 | udpAddr, _ := udpAddrFromSockaddr((*syscall.RawSockaddrAny)(unsafe.Pointer(peeraddr))) 339 | 340 | userCB(s, SRTErrno(errcode), udpAddr, int(token)) 341 | } 342 | 343 | // SetConnectCallback - set a function to be called after a socket or connection in a group has failed 344 | // Note that the function is not guaranteed to be called if the socket is set to blocking mode. 345 | func (s SrtSocket) SetConnectCallback(cb ConnectCallbackFunc) { 346 | ptr := gopointer.Save(cb) 347 | C.srt_connect_callback(s.socket, (*C.srt_connect_callback_fn)(C.srtConnectCB), ptr) 348 | 349 | callbackMutex.Lock() 350 | defer callbackMutex.Unlock() 351 | if connectCallbackMap[s.socket] != nil { 352 | gopointer.Unref(connectCallbackMap[s.socket]) 353 | } 354 | connectCallbackMap[s.socket] = ptr 355 | } 356 | 357 | // Rejection reasons 358 | var ( 359 | // Start of range for predefined rejection reasons 360 | RejectionReasonPredefined = int(C.get_srt_error_reject_predefined()) 361 | 362 | // General syntax error in the SocketID specification (also a fallback code for undefined cases) 363 | RejectionReasonBadRequest = RejectionReasonPredefined + 400 364 | 365 | // Authentication failed, provided that the user was correctly identified and access to the required resource would be granted 366 | RejectionReasonUnauthorized = RejectionReasonPredefined + 401 367 | 368 | // The server is too heavily loaded, or you have exceeded credits for accessing the service and the resource. 369 | RejectionReasonOverload = RejectionReasonPredefined + 402 370 | 371 | // Access denied to the resource by any kind of reason 372 | RejectionReasonForbidden = RejectionReasonPredefined + 403 373 | 374 | // Resource not found at this time. 375 | RejectionReasonNotFound = RejectionReasonPredefined + 404 376 | 377 | // The mode specified in `m` key in StreamID is not supported for this request. 378 | RejectionReasonBadMode = RejectionReasonPredefined + 405 379 | 380 | // The requested parameters specified in SocketID cannot be satisfied for the requested resource. Also when m=publish and the data format is not acceptable. 381 | RejectionReasonUnacceptable = RejectionReasonPredefined + 406 382 | 383 | // Start of range for application defined rejection reasons 384 | RejectionReasonUserDefined = int(C.get_srt_error_reject_predefined()) 385 | ) 386 | 387 | // SetRejectReason - set custom reason for connection reject 388 | func (s SrtSocket) SetRejectReason(value int) error { 389 | res := C.srt_setrejectreason(s.socket, C.int(value)) 390 | if res == SRT_ERROR { 391 | return errors.New(C.GoString(C.srt_getlasterror_str())) 392 | } 393 | return nil 394 | } 395 | 396 | // GetSockOptByte - return byte value obtained with srt_getsockopt 397 | func (s SrtSocket) GetSockOptByte(opt int) (byte, error) { 398 | var v byte 399 | l := 1 400 | 401 | err := s.getSockOpt(opt, unsafe.Pointer(&v), &l) 402 | return v, err 403 | } 404 | 405 | // GetSockOptBool - return bool value obtained with srt_getsockopt 406 | func (s SrtSocket) GetSockOptBool(opt int) (bool, error) { 407 | var v int32 408 | l := 4 409 | 410 | err := s.getSockOpt(opt, unsafe.Pointer(&v), &l) 411 | if v == 1 { 412 | return true, err 413 | } 414 | 415 | return false, err 416 | } 417 | 418 | // GetSockOptInt - return int value obtained with srt_getsockopt 419 | func (s SrtSocket) GetSockOptInt(opt int) (int, error) { 420 | var v int32 421 | l := 4 422 | 423 | err := s.getSockOpt(opt, unsafe.Pointer(&v), &l) 424 | return int(v), err 425 | } 426 | 427 | // GetSockOptInt64 - return int64 value obtained with srt_getsockopt 428 | func (s SrtSocket) GetSockOptInt64(opt int) (int64, error) { 429 | var v int64 430 | l := 8 431 | 432 | err := s.getSockOpt(opt, unsafe.Pointer(&v), &l) 433 | return v, err 434 | } 435 | 436 | // GetSockOptString - return string value obtained with srt_getsockopt 437 | func (s SrtSocket) GetSockOptString(opt int) (string, error) { 438 | buf := make([]byte, 256) 439 | l := len(buf) 440 | 441 | err := s.getSockOpt(opt, unsafe.Pointer(&buf[0]), &l) 442 | if err != nil { 443 | return "", err 444 | } 445 | return string(buf[:l]), nil 446 | } 447 | 448 | // SetSockOptByte - set byte value using srt_setsockopt 449 | func (s SrtSocket) SetSockOptByte(opt int, value byte) error { 450 | return s.setSockOpt(opt, unsafe.Pointer(&value), 1) 451 | } 452 | 453 | // SetSockOptBool - set bool value using srt_setsockopt 454 | func (s SrtSocket) SetSockOptBool(opt int, value bool) error { 455 | val := int(0) 456 | if value { 457 | val = 1 458 | } 459 | return s.setSockOpt(opt, unsafe.Pointer(&val), 4) 460 | } 461 | 462 | // SetSockOptInt - set int value using srt_setsockopt 463 | func (s SrtSocket) SetSockOptInt(opt int, value int) error { 464 | return s.setSockOpt(opt, unsafe.Pointer(&value), 4) 465 | } 466 | 467 | // SetSockOptInt64 - set int64 value using srt_setsockopt 468 | func (s SrtSocket) SetSockOptInt64(opt int, value int64) error { 469 | return s.setSockOpt(opt, unsafe.Pointer(&value), 8) 470 | } 471 | 472 | // SetSockOptString - set string value using srt_setsockopt 473 | func (s SrtSocket) SetSockOptString(opt int, value string) error { 474 | return s.setSockOpt(opt, unsafe.Pointer(&[]byte(value)[0]), len(value)) 475 | } 476 | 477 | func (s SrtSocket) setSockOpt(opt int, data unsafe.Pointer, size int) error { 478 | runtime.LockOSThread() 479 | defer runtime.UnlockOSThread() 480 | res := C.srt_setsockopt(s.socket, 0, C.SRT_SOCKOPT(opt), data, C.int(size)) 481 | if res == -1 { 482 | return fmt.Errorf("Error calling srt_setsockopt %w", srtGetAndClearError()) 483 | } 484 | return nil 485 | } 486 | 487 | func (s SrtSocket) getSockOpt(opt int, data unsafe.Pointer, size *int) error { 488 | runtime.LockOSThread() 489 | defer runtime.UnlockOSThread() 490 | res := C.srt_getsockopt(s.socket, 0, C.SRT_SOCKOPT(opt), data, (*C.int)(unsafe.Pointer(size))) 491 | if res == -1 { 492 | return fmt.Errorf("Error calling srt_getsockopt %w", srtGetAndClearError()) 493 | } 494 | 495 | return nil 496 | } 497 | 498 | func (s SrtSocket) preconfiguration() (int, error) { 499 | runtime.LockOSThread() 500 | defer runtime.UnlockOSThread() 501 | var blocking C.int 502 | if s.blocking { 503 | blocking = C.int(1) 504 | } else { 505 | blocking = C.int(0) 506 | } 507 | result := C.srt_setsockopt(s.socket, 0, C.SRTO_RCVSYN, unsafe.Pointer(&blocking), C.int(unsafe.Sizeof(blocking))) 508 | if result == -1 { 509 | return ModeFailure, fmt.Errorf("could not set SRTO_RCVSYN flag: %w", srtGetAndClearError()) 510 | } 511 | 512 | var mode int 513 | modeVal, ok := s.options["mode"] 514 | if !ok { 515 | modeVal = "default" 516 | } 517 | 518 | if modeVal == "client" || modeVal == "caller" { 519 | mode = ModeCaller 520 | } else if modeVal == "server" || modeVal == "listener" { 521 | mode = ModeListener 522 | } else if modeVal == "default" { 523 | if s.host == "" { 524 | mode = ModeListener 525 | } else { 526 | // Host is given, so check also "adapter" 527 | if _, ok := s.options["adapter"]; ok { 528 | mode = ModeRendezvouz 529 | } else { 530 | mode = ModeCaller 531 | } 532 | } 533 | } else { 534 | mode = ModeFailure 535 | } 536 | 537 | if linger, ok := s.options["linger"]; ok { 538 | li, err := strconv.Atoi(linger) 539 | if err == nil { 540 | if err := setSocketLingerOption(s.socket, int32(li)); err != nil { 541 | return ModeFailure, fmt.Errorf("could not set LINGER option %w", err) 542 | } 543 | } else { 544 | return ModeFailure, fmt.Errorf("could not set LINGER option %w", err) 545 | } 546 | } 547 | 548 | err := setSocketOptions(s.socket, bindingPre, s.options) 549 | if err != nil { 550 | return ModeFailure, fmt.Errorf("Error setting socket options: %w", err) 551 | } 552 | 553 | return mode, nil 554 | } 555 | 556 | func (s SrtSocket) postconfiguration(sck *SrtSocket) error { 557 | runtime.LockOSThread() 558 | defer runtime.UnlockOSThread() 559 | var blocking C.int 560 | if s.blocking { 561 | blocking = 1 562 | } else { 563 | blocking = 0 564 | } 565 | 566 | res := C.srt_setsockopt(sck.socket, 0, C.SRTO_SNDSYN, unsafe.Pointer(&blocking), C.int(unsafe.Sizeof(blocking))) 567 | if res == -1 { 568 | return fmt.Errorf("Error in postconfiguration setting SRTO_SNDSYN: %w", srtGetAndClearError()) 569 | } 570 | 571 | res = C.srt_setsockopt(sck.socket, 0, C.SRTO_RCVSYN, unsafe.Pointer(&blocking), C.int(unsafe.Sizeof(blocking))) 572 | if res == -1 { 573 | return fmt.Errorf("Error in postconfiguration setting SRTO_RCVSYN: %w", srtGetAndClearError()) 574 | } 575 | 576 | err := setSocketOptions(sck.socket, bindingPost, s.options) 577 | return err 578 | } 579 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. --------------------------------------------------------------------------------