-
Notifications
You must be signed in to change notification settings - Fork 2
/
rtp.go
333 lines (286 loc) · 6.14 KB
/
rtp.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package main
import (
"bytes"
"fmt"
"io"
"log"
"net"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/pion/rtp"
)
// https://en.wikipedia.org/wiki/RTP_payload_formats
const (
RTP_Payload_MP2T = 33
)
const (
// https://www.w3.org/2013/12/byte-stream-format-registry/mp2t-byte-stream-format.html
ContentType_MP2T = "video/mp2t"
ContentType_DEFAULT = "application/octet-stream"
)
type Event struct {
etype EventType
address string
}
type EventType int
const (
evtStreamClose = EventType(0)
)
type Handler func(evt *Event) error
type Stream struct {
sync.RWMutex
address string
contentType string
conn *net.UDPConn
readers map[string]*Reader
listeners []Handler
}
func NewStream(address string, timeout time.Duration) (stream *Stream, err error) {
var (
addr *net.UDPAddr
conn *net.UDPConn
p *rtp.Packet
n int
buf []byte
contentType string
)
if addr, err = net.ResolveUDPAddr("udp4", address); err != nil {
return nil, err
}
if conn, err = net.ListenMulticastUDP("udp4", inf, addr); err != nil {
return nil, err
}
buf = make([]byte, 1500)
conn.SetReadDeadline(time.Now().Add((timeout)))
if n, err = conn.Read(buf); err != nil {
return nil, err
}
p = &rtp.Packet{}
if err = p.Unmarshal(buf[:n]); err != nil {
return nil, err
}
if p.PayloadType == RTP_Payload_MP2T {
contentType = ContentType_MP2T
} else {
contentType = ContentType_DEFAULT
}
stream = &Stream{
address: address,
conn: conn,
contentType: contentType,
readers: make(map[string]*Reader),
}
go stream.ioLoop()
return stream, nil
}
func (s *Stream) ioLoop() (err error) {
defer func() {
debugLog.Printf("ioLoop exited: %v", err)
for _, reader := range s.readers {
close(reader.buf)
}
s.Close()
for _, h := range s.listeners {
h(&Event{
address: s.address,
etype: evtStreamClose,
})
}
}()
var (
p rtp.Packet
n int
pool bytes.Buffer
data []byte
timer = time.NewTicker(200 * time.Millisecond)
buf = make([]byte, 1500)
)
// reset read deadline
s.conn.SetReadDeadline(time.Time{})
for {
if n, err = s.conn.Read(buf); err != nil {
return err
}
if err = p.Unmarshal(buf[:n]); err != nil {
return err
}
if _, err = pool.Write(p.Payload); err != nil {
return err
}
select {
case <-timer.C:
b := pool.Bytes()
data = make([]byte, len(b))
copy(data, b)
if err = s.Broadcast(data); err != nil {
return err
}
pool.Reset()
default:
// continue to read next packet
}
}
}
func (s *Stream) Broadcast(data []byte) error {
s.Lock()
rl := len(s.readers)
var rs = make([]chan []byte, 0, rl)
for _, reader := range s.readers {
rs = append(rs, reader.buf)
}
s.Unlock()
if len(rs) == 0 {
return fmt.Errorf("no more clients in %s", s.address)
}
for _, r := range rs {
select {
case r <- data:
//debugLog.Printf("Send buf....")
default:
debugLog.Printf("Send buf skippped")
}
}
return nil
}
func (s *Stream) OnEvent(h Handler) {
s.listeners = append(s.listeners, h)
}
func (s *Stream) Join(client string) (reader *Reader, err error) {
debugLog.Printf("%s Join %s", client, s.address)
reader = &Reader{
buf: make(chan []byte, 1),
}
s.Lock()
s.readers[client] = reader
s.Unlock()
atomic.AddInt32(&rtpServer.clientCount, 1)
return
}
func (s *Stream) Leave(client string) {
debugLog.Printf("%s Leave", client)
s.Lock()
delete(s.readers, client)
s.Unlock()
atomic.AddInt32(&rtpServer.clientCount, -1)
}
func (s *Stream) Close() (err error) {
return s.conn.Close()
}
type Reader struct {
buf chan []byte
e []byte
}
func (r *Reader) Read(buf []byte) (n int, err error) {
var (
data []byte
ok bool
)
if len(r.e) == 0 {
data, ok = <-r.buf
if !ok {
err = io.EOF
return
}
} else {
data = r.e
}
n = copy(buf, data)
if len(data) > n {
r.e = data[n:]
} else {
r.e = nil
}
return
}
type RTPServer struct {
sync.RWMutex
streams map[string]*Stream
streamCount int
clientCount int32
}
func NewRTPServer() *RTPServer {
return &RTPServer{
streams: make(map[string]*Stream),
}
}
func (r *RTPServer) Count() (streamCount, clientCount int) {
r.RLock()
streamCount = r.streamCount
r.RUnlock()
clientCount = int(atomic.LoadInt32(&r.clientCount))
return
}
func (r *RTPServer) Find(address string, timeout time.Duration) (*Stream, error) {
debugLog.Printf("Find channel %s", address)
r.RLock()
stream, ok := r.streams[address]
r.RUnlock()
if ok {
return stream, nil
}
stream, err := NewStream(address, timeout)
if err != nil {
return nil, err
}
r.Lock()
stream.OnEvent(r.HandleEvent)
r.streams[address] = stream
r.streamCount = len(r.streams)
r.Unlock()
return stream, nil
}
func (r *RTPServer) HandleEvent(evt *Event) error {
if evt.etype == evtStreamClose {
debugLog.Printf("Handle Stream Close for: %s", evt.address)
r.Lock()
delete(r.streams, evt.address)
r.streamCount = len(r.streams)
r.Unlock()
}
return nil
}
var rtpServer = NewRTPServer()
func handleRTP(w http.ResponseWriter, req *http.Request) {
var (
path = req.URL.Path
start = time.Now()
parts []string
err error
wc int64
stream *Stream
r io.Reader
)
if inf == nil {
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, "no multicast available")
return
}
parts = strings.FieldsFunc(req.URL.Path, func(r rune) bool { return r == '/' })
if len(parts) < 2 {
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, "No address specified")
return
}
if stream, err = rtpServer.Find(parts[1], *timeout); err != nil {
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, err.Error())
return
}
if r, err = stream.Join(req.RemoteAddr); err != nil {
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, err.Error())
return
}
defer stream.Leave(req.RemoteAddr)
w.Header().Set("Content-Type", stream.contentType)
w.WriteHeader(http.StatusOK)
wc, _ = io.Copy(w, r)
client := req.Header.Get("X-Forwarded-For")
if client == "" {
client, _, _ = net.SplitHostPort(req.RemoteAddr)
}
log.Printf("[RTP] %s %s %s %s [%s]", client, path, time.Since(start), ByteCount(wc), req.UserAgent())
}