-
Notifications
You must be signed in to change notification settings - Fork 1
/
transport_tcp.go
131 lines (105 loc) · 2.15 KB
/
transport_tcp.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
package rtsp
import (
"bufio"
"encoding/binary"
"errors"
"fmt"
"net"
"sync"
)
const (
interleavedPacketSize = 0x10000
interleavedHeaderSize = 4
)
type TransportTCP struct {
reader *bufio.Reader
onceError sync.Once
err chan error
}
func NewTransportTCP(reader *bufio.Reader) *TransportTCP {
return &TransportTCP{
reader: reader,
err: make(chan error, 1),
}
}
func (t *TransportTCP) loop(wg *sync.WaitGroup, handler MediaHandler, onError func(error)) {
defer wg.Done()
buf := make([]byte, interleavedPacketSize)
var (
size, skip int
transportID int
)
for {
if size == 0 {
n, err := t.reader.Read(buf[skip:interleavedHeaderSize])
if err != nil {
if errors.Is(err, net.ErrClosed) {
return
}
onError(fmt.Errorf("read interleved header: %w", err))
return
}
skip += n
if skip == interleavedHeaderSize {
if buf[0] != '$' {
onError(fmt.Errorf("invalid interleved header"))
return
}
transportID = int(buf[1])
size = int(binary.BigEndian.Uint16(buf[2:4]))
skip = 0
}
continue
}
n, err := t.reader.Read(buf[skip:size])
if err != nil {
if errors.Is(err, net.ErrClosed) {
return
}
onError(fmt.Errorf("read interleaved packet: %w", err))
return
}
skip += n
if skip == size {
id := transportID >> 1
packet := buf[:size]
if (transportID & 1) == 0 {
handler.OnRTP(id, packet)
} else {
handler.OnRTCP(id, packet)
}
size = 0
skip = 0
}
}
}
// Setup prepares the transport and returns the transport parameters.
func (t *TransportTCP) Setup(mediaID int) (string, error) {
rtpId := mediaID * 2
rtcpId := rtpId + 1
transport := fmt.Sprintf(
"RTP/AVP/TCP;unicast;interleaved=%d-%d",
rtpId,
rtcpId,
)
return transport, nil
}
// Play starts receigin RTP/RTCP packets.
func (t *TransportTCP) Play(handler MediaHandler) {
var wg sync.WaitGroup
wg.Add(1)
go t.loop(&wg, handler, t.onError)
go func() {
wg.Wait()
t.onError(nil)
}()
}
func (t *TransportTCP) Close() {}
func (t *TransportTCP) onError(err error) {
t.onceError.Do(func() {
t.err <- err
})
}
func (t *TransportTCP) Err() <-chan error {
return t.err
}