forked from bluenviron/mediamtx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
source.go
382 lines (305 loc) · 6.95 KB
/
source.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package main
import (
"math/rand"
"net"
"os"
"sync"
"time"
"github.com/aler9/gortsplib"
)
const (
sourceRetryInterval = 5 * time.Second
sourceUdpReadBufferSize = 2048
sourceTcpReadBufferSize = 128 * 1024
)
type sourceState int
const (
sourceStateStopped sourceState = iota
sourceStateRunning
)
type sourceEvent interface {
isSourceEvent()
}
type sourceEventApplyState struct {
state sourceState
}
func (sourceEventApplyState) isSourceEvent() {}
type sourceEventTerminate struct{}
func (sourceEventTerminate) isSourceEvent() {}
type source struct {
p *program
pathName string
confp *confPath
state sourceState
tracks []*gortsplib.Track
events chan sourceEvent
done chan struct{}
}
func newSource(p *program, pathName string, confp *confPath) *source {
s := &source{
p: p,
pathName: pathName,
confp: confp,
events: make(chan sourceEvent),
done: make(chan struct{}),
}
if confp.SourceOnDemand {
s.state = sourceStateStopped
} else {
s.state = sourceStateRunning
}
return s
}
func (s *source) log(format string, args ...interface{}) {
s.p.log("[source "+s.pathName+"] "+format, args...)
}
func (s *source) isPublisher() {}
func (s *source) run() {
running := false
var doTerminate chan struct{}
var doDone chan struct{}
applyState := func(state sourceState) {
if state == sourceStateRunning {
if !running {
s.log("started")
running = true
doTerminate = make(chan struct{})
doDone = make(chan struct{})
go s.do(doTerminate, doDone)
}
} else {
if running {
close(doTerminate)
<-doDone
running = false
s.log("stopped")
}
}
}
applyState(s.state)
outer:
for rawEvt := range s.events {
switch evt := rawEvt.(type) {
case sourceEventApplyState:
applyState(evt.state)
case sourceEventTerminate:
break outer
}
}
if running {
close(doTerminate)
<-doDone
}
close(s.done)
}
func (s *source) do(terminate chan struct{}, done chan struct{}) {
defer close(done)
for {
ok := func() bool {
ok := s.doInner(terminate)
if !ok {
return false
}
t := time.NewTimer(sourceRetryInterval)
defer t.Stop()
select {
case <-terminate:
return false
case <-t.C:
}
return true
}()
if !ok {
break
}
}
}
func (s *source) doInner(terminate chan struct{}) bool {
s.log("connecting")
var conn *gortsplib.ConnClient
var err error
dialDone := make(chan struct{})
go func() {
conn, err = gortsplib.NewConnClient(gortsplib.ConnClientConf{
Host: s.confp.sourceUrl.Host,
ReadTimeout: s.p.conf.ReadTimeout,
WriteTimeout: s.p.conf.WriteTimeout,
})
close(dialDone)
}()
select {
case <-terminate:
return false
case <-dialDone:
}
if err != nil {
s.log("ERR: %s", err)
return true
}
defer conn.Close()
_, err = conn.Options(s.confp.sourceUrl)
if err != nil {
s.log("ERR: %s", err)
return true
}
tracks, _, err := conn.Describe(s.confp.sourceUrl)
if err != nil {
s.log("ERR: %s", err)
return true
}
// create a filtered SDP that is used by the server (not by the client)
serverSdpParsed, serverSdpText := sdpForServer(tracks)
s.tracks = tracks
s.p.paths[s.pathName].publisherSdpText = serverSdpText
s.p.paths[s.pathName].publisherSdpParsed = serverSdpParsed
if s.confp.sourceProtocolParsed == gortsplib.StreamProtocolUdp {
return s.runUdp(terminate, conn)
} else {
return s.runTcp(terminate, conn)
}
}
func (s *source) runUdp(terminate chan struct{}, conn *gortsplib.ConnClient) bool {
type trackListenerPair struct {
serverRtp *gortsplib.ConnClientUdpListener
serverRtcp *gortsplib.ConnClientUdpListener
}
var listeners []*trackListenerPair
for _, track := range s.tracks {
var serverRtp *gortsplib.ConnClientUdpListener
var serverRtcp *gortsplib.ConnClientUdpListener
var err error
for {
// choose two consecutive ports in range 65536-10000
// rtp must be pair and rtcp odd
rtpPort := (rand.Intn((65535-10000)/2) * 2) + 10000
rtcpPort := rtpPort + 1
serverRtp, serverRtcp, _, err = conn.SetupUdp(s.confp.sourceUrl, track, rtpPort, rtcpPort)
if err != nil {
// retry if it's a bind error
if nerr, ok := err.(*net.OpError); ok {
if serr, ok := nerr.Err.(*os.SyscallError); ok {
if serr.Syscall == "bind" {
continue
}
}
}
s.log("ERR: %s", err)
return true
}
break
}
listeners = append(listeners, &trackListenerPair{
serverRtp: serverRtp,
serverRtcp: serverRtcp,
})
}
_, err := conn.Play(s.confp.sourceUrl)
if err != nil {
s.log("ERR: %s", err)
return true
}
s.p.events <- programEventSourceReady{s}
var wg sync.WaitGroup
for trackId, lp := range listeners {
wg.Add(2)
// receive RTP packets
go func(trackId int, l *gortsplib.ConnClientUdpListener) {
defer wg.Done()
doubleBuf := newDoubleBuffer(sourceUdpReadBufferSize)
for {
buf := doubleBuf.swap()
n, err := l.Read(buf)
if err != nil {
break
}
s.p.events <- programEventSourceFrame{s, trackId, gortsplib.StreamTypeRtp, buf[:n]}
}
}(trackId, lp.serverRtp)
// receive RTCP packets
go func(trackId int, l *gortsplib.ConnClientUdpListener) {
defer wg.Done()
doubleBuf := newDoubleBuffer(sourceUdpReadBufferSize)
for {
buf := doubleBuf.swap()
n, err := l.Read(buf)
if err != nil {
break
}
s.p.events <- programEventSourceFrame{s, trackId, gortsplib.StreamTypeRtcp, buf[:n]}
}
}(trackId, lp.serverRtcp)
}
tcpConnDone := make(chan error)
go func() {
tcpConnDone <- conn.LoopUDP(s.confp.sourceUrl)
}()
var ret bool
outer:
for {
select {
case <-terminate:
conn.NetConn().Close()
<-tcpConnDone
ret = false
break outer
case err := <-tcpConnDone:
s.log("ERR: %s", err)
ret = true
break outer
}
}
s.p.events <- programEventSourceNotReady{s}
for _, lp := range listeners {
lp.serverRtp.Close()
lp.serverRtcp.Close()
}
wg.Wait()
return ret
}
func (s *source) runTcp(terminate chan struct{}, conn *gortsplib.ConnClient) bool {
for _, track := range s.tracks {
_, err := conn.SetupTcp(s.confp.sourceUrl, track)
if err != nil {
s.log("ERR: %s", err)
return true
}
}
_, err := conn.Play(s.confp.sourceUrl)
if err != nil {
s.log("ERR: %s", err)
return true
}
s.p.events <- programEventSourceReady{s}
frame := &gortsplib.InterleavedFrame{}
doubleBuf := newDoubleBuffer(sourceTcpReadBufferSize)
tcpConnDone := make(chan error)
go func() {
for {
frame.Content = doubleBuf.swap()
frame.Content = frame.Content[:cap(frame.Content)]
err := conn.ReadFrame(frame)
if err != nil {
tcpConnDone <- err
return
}
s.p.events <- programEventSourceFrame{s, frame.TrackId, frame.StreamType, frame.Content}
}
}()
var ret bool
outer:
for {
select {
case <-terminate:
conn.NetConn().Close()
<-tcpConnDone
ret = false
break outer
case err := <-tcpConnDone:
s.log("ERR: %s", err)
ret = true
break outer
}
}
s.p.events <- programEventSourceNotReady{s}
return ret
}