This repository was archived by the owner on Oct 10, 2023. It is now read-only.
forked from AFathi/live-webrtcsignaling
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpipeline.node.udp.go
106 lines (97 loc) · 2.14 KB
/
pipeline.node.udp.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
/*
* PipelineNodeUDP
* convert an UDPConn to a pipeline emitter
*
* IN: nothing
* OUT: packet.UdpPacket
*
*/
import (
"context"
"net"
"sync/atomic"
"time"
plogger "github.com/heytribe/go-plogger"
"github.com/heytribe/live-webrtcsignaling/packet"
)
type PipelineNodeUDP struct {
PipelineNode
// I/O
Out chan *packet.UDP
// privates
udpConn *net.UDPConn
}
func NewPipelineNodeUDP(udpConn *net.UDPConn) *PipelineNodeUDP {
n := new(PipelineNodeUDP)
n.udpConn = udpConn
n.Out = make(chan *packet.UDP, 1000)
return n
}
func (n *PipelineNodeUDP) ReadPacketUDP(ctx context.Context) (*packet.UDP, error) {
packet := packet.NewUDP()
size, rAddr, err := n.udpConn.ReadFromUDP(packet.GetData())
if err != nil {
return nil, err
}
packet.SetCreatedAt(time.Now())
packet.SetRAddr(rAddr)
packet.Slice(0, size)
return packet, nil
}
// IPipelinePipelineNode interface functions
func (n *PipelineNodeUDP) Run(ctx context.Context) {
var totalPacketsReceivedSize uint64
var lastPacketsReceivedSize uint64
n.Running = true
n.emitStart()
//
log := plogger.FromContextSafe(ctx).Prefix("PipelineNodeUDP")
// monitoring inputs
ticker := time.NewTicker(1 * time.Second)
defer func() {
ticker.Stop()
}()
go func() {
for {
select {
case <-ctx.Done():
n.onStop(ctx)
return
case <-ticker.C:
msg := new(PipelineMessageInBps)
msg.Bps = totalPacketsReceivedSize - lastPacketsReceivedSize
lastPacketsReceivedSize = totalPacketsReceivedSize
select {
case n.Bus <- msg:
default:
plogger.Warnf("Bus is full, dropping event PipelineMessageInBps")
}
}
}
}()
//
for n.Running {
packet, err := n.ReadPacketUDP(ctx)
if err != nil {
log.Errorf("packet read error %s", err.Error())
return
}
atomic.AddUint64(&totalPacketsReceivedSize, uint64(packet.GetSize()))
select {
case n.Out <- packet:
default:
log.Warnf("Out is full, dropping udp packet")
}
}
}
func (n *PipelineNodeUDP) onStop(ctx context.Context) {
log := plogger.FromContextSafe(ctx)
if n.udpConn != nil {
log.Infof("CLOSING UDP CONNECTION\n")
n.udpConn.Close()
n.udpConn = nil
}
n.Running = false
n.emitStop()
}