This repository has been archived by the owner on Nov 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathstream-udpl.go
91 lines (75 loc) · 1.59 KB
/
stream-udpl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"net"
"sync"
"time"
)
type streamUdpListenerState int
const (
_UDPL_STATE_STARTING streamUdpListenerState = iota
_UDPL_STATE_RUNNING
)
type streamUdpListener struct {
p *program
nconn *net.UDPConn
state streamUdpListenerState
done chan struct{}
publisherIp net.IP
publisherPort int
trackId int
flow trackFlow
path string
mutex sync.Mutex
lastFrameTime time.Time
}
func newStreamUdpListener(p *program, port int) (*streamUdpListener, error) {
nconn, err := net.ListenUDP("udp", &net.UDPAddr{
Port: port,
})
if err != nil {
return nil, err
}
l := &streamUdpListener{
p: p,
nconn: nconn,
state: _UDPL_STATE_STARTING,
done: make(chan struct{}),
}
return l, nil
}
func (l *streamUdpListener) close() {
l.nconn.Close()
if l.state == _UDPL_STATE_RUNNING {
<-l.done
}
}
func (l *streamUdpListener) start() {
l.state = _UDPL_STATE_RUNNING
go l.run()
}
func (l *streamUdpListener) run() {
for {
// create a buffer for each read.
// this is necessary since the buffer is propagated with channels
// so it must be unique.
buf := make([]byte, 2048) // UDP MTU is 1400
n, addr, err := l.nconn.ReadFromUDP(buf)
if err != nil {
break
}
if !l.publisherIp.Equal(addr.IP) || addr.Port != l.publisherPort {
continue
}
func() {
l.p.tcpl.mutex.RLock()
defer l.p.tcpl.mutex.RUnlock()
l.p.tcpl.forwardTrack(l.path, l.trackId, l.flow, buf[:n])
}()
func() {
l.mutex.Lock()
defer l.mutex.Unlock()
l.lastFrameTime = time.Now()
}()
}
close(l.done)
}