-
Notifications
You must be signed in to change notification settings - Fork 50
/
demuxer.go
217 lines (188 loc) · 5.79 KB
/
demuxer.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
package astits
import (
"context"
"errors"
"fmt"
"io"
"github.com/asticode/go-astikit"
)
// Sync byte
const syncByte = '\x47'
// Errors
var (
ErrNoMorePackets = errors.New("astits: no more packets")
ErrPacketMustStartWithASyncByte = errors.New("astits: packet must start with a sync byte")
)
// Demuxer represents a demuxer
// https://en.wikipedia.org/wiki/MPEG_transport_stream
// http://seidl.cs.vsb.cz/download/dvb/DVB_Poster.pdf
// http://www.etsi.org/deliver/etsi_en/300400_300499/300468/01.13.01_40/en_300468v011301o.pdf
type Demuxer struct {
ctx context.Context
dataBuffer []*DemuxerData
l astikit.CompleteLogger
optPacketSize int
optPacketsParser PacketsParser
optPacketSkipper PacketSkipper
packetBuffer *packetBuffer
packetPool *packetPool
programMap *programMap
r io.Reader
}
// PacketsParser represents an object capable of parsing a set of packets containing a unique payload spanning over those packets
// Use the skip returned argument to indicate whether the default process should still be executed on the set of packets
type PacketsParser func(ps []*Packet) (ds []*DemuxerData, skip bool, err error)
// PacketSkipper represents an object capable of skipping a packet before parsing its payload. Its header and adaptation field is parsed and provided to the object.
// Use this option if you need to filter out unwanted packets from your pipeline. NextPacket() will return the next unskipped packet if any.
type PacketSkipper func(p *Packet) (skip bool)
// NewDemuxer creates a new transport stream based on a reader
func NewDemuxer(ctx context.Context, r io.Reader, opts ...func(*Demuxer)) (d *Demuxer) {
// Init
d = &Demuxer{
ctx: ctx,
l: astikit.AdaptStdLogger(nil),
programMap: newProgramMap(),
r: r,
}
d.packetPool = newPacketPool(d.programMap)
// Apply options
for _, opt := range opts {
opt(d)
}
return
}
// DemuxerOptLogger returns the option to set the logger
func DemuxerOptLogger(l astikit.StdLogger) func(*Demuxer) {
return func(d *Demuxer) {
d.l = astikit.AdaptStdLogger(l)
}
}
// DemuxerOptPacketSize returns the option to set the packet size
func DemuxerOptPacketSize(packetSize int) func(*Demuxer) {
return func(d *Demuxer) {
d.optPacketSize = packetSize
}
}
// DemuxerOptPacketsParser returns the option to set the packets parser
func DemuxerOptPacketsParser(p PacketsParser) func(*Demuxer) {
return func(d *Demuxer) {
d.optPacketsParser = p
}
}
// DemuxerOptPacketSkipper returns the option to set the packet skipper
func DemuxerOptPacketSkipper(s PacketSkipper) func(*Demuxer) {
return func(d *Demuxer) {
d.optPacketSkipper = s
}
}
// NextPacket retrieves the next packet
func (dmx *Demuxer) NextPacket() (p *Packet, err error) {
// Check ctx error
// TODO Handle ctx error another way since if the read blocks, everything blocks
// Maybe execute everything in a goroutine and listen the ctx channel in the same for loop
if err = dmx.ctx.Err(); err != nil {
return
}
// Create packet buffer if not exists
if dmx.packetBuffer == nil {
if dmx.packetBuffer, err = newPacketBuffer(dmx.r, dmx.optPacketSize, dmx.optPacketSkipper); err != nil {
err = fmt.Errorf("astits: creating packet buffer failed: %w", err)
return
}
}
// Fetch next packet from buffer
if p, err = dmx.packetBuffer.next(); err != nil {
if err != ErrNoMorePackets {
err = fmt.Errorf("astits: fetching next packet from buffer failed: %w", err)
}
return
}
return
}
// NextData retrieves the next data
func (dmx *Demuxer) NextData() (d *DemuxerData, err error) {
// Check data buffer
if len(dmx.dataBuffer) > 0 {
d = dmx.dataBuffer[0]
dmx.dataBuffer = dmx.dataBuffer[1:]
return
}
// Loop through packets
var p *Packet
var ps []*Packet
var ds []*DemuxerData
for {
// Get next packet
if p, err = dmx.NextPacket(); err != nil {
// If the end of the stream has been reached, we dump the packet pool
if err == ErrNoMorePackets {
for {
// Dump packet pool
if ps = dmx.packetPool.dumpUnlocked(); len(ps) == 0 {
break
}
// Parse data
var errParseData error
if ds, errParseData = parseData(ps, dmx.optPacketsParser, dmx.programMap); errParseData != nil {
// Log error as there may be some incomplete data here
// We still want to try to parse all packets, in case final data is complete
dmx.l.Error(fmt.Errorf("astits: parsing data failed: %w", errParseData))
continue
}
// Update data
if d = dmx.updateData(ds); d != nil {
err = nil
return
}
}
return
}
err = fmt.Errorf("astits: fetching next packet failed: %w", err)
return
}
// Add packet to the pool
if ps = dmx.packetPool.addUnlocked(p); len(ps) == 0 {
continue
}
// Parse data
if ds, err = parseData(ps, dmx.optPacketsParser, dmx.programMap); err != nil {
err = fmt.Errorf("astits: building new data failed: %w", err)
return
}
// Update data
if d = dmx.updateData(ds); d != nil {
return
}
}
}
func (dmx *Demuxer) updateData(ds []*DemuxerData) (d *DemuxerData) {
// Check whether there is data to be processed
if len(ds) > 0 {
// Process data
d = ds[0]
dmx.dataBuffer = append(dmx.dataBuffer, ds[1:]...)
// Update program map
for _, v := range ds {
if v.PAT != nil {
for _, pgm := range v.PAT.Programs {
// Program number 0 is reserved to NIT
if pgm.ProgramNumber > 0 {
dmx.programMap.setUnlocked(pgm.ProgramMapID, pgm.ProgramNumber)
}
}
}
}
}
return
}
// Rewind rewinds the demuxer reader
func (dmx *Demuxer) Rewind() (n int64, err error) {
dmx.dataBuffer = []*DemuxerData{}
dmx.packetBuffer = nil
dmx.packetPool = newPacketPool(dmx.programMap)
if n, err = rewind(dmx.r); err != nil {
err = fmt.Errorf("astits: rewinding reader failed: %w", err)
return
}
return
}