This repository has been archived by the owner on Jul 2, 2021. It is now read-only.
/
webm.go
412 lines (351 loc) · 9.74 KB
/
webm.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package elements
import (
"sync"
"sync/atomic"
"time"
"github.com/at-wat/ebml-go/mkvcore"
"github.com/at-wat/ebml-go/webm"
avp "github.com/pion/ion-avp/pkg"
log "github.com/pion/ion-log"
)
const (
defaultWidth = 640
defaultHeight = 480
maxBufferedSamples = 60 * 15 // 60 FPS for 15 seconds
maxAudioVideoSyncDelay = time.Duration(15) * time.Second
)
// webmSaverStats keep track of statistics for the sake of logging
type webmSaverStats struct {
audio int
videoKey, videoInter int
droppedAudio, droppedVideo int
unknown int
}
// WebmSaver Module for saving rtp streams to webm
type WebmSaver struct {
sync.Mutex
firstWrite bool
dateUTC time.Time
closed bool
writeInProgress int32
audioWriter, videoWriter webm.BlockWriteCloser
vttAudioWriter, vttVideoWriter webm.BlockWriteCloser
audioTimestamp, videoTimestamp uint32
sampleWriter *SampleWriter
preBuffering []*avp.Sample
statsContext string
preBufferingStats webmSaverStats
liveStats webmSaverStats
}
// NewWebmSaver Initialize a new webm saver
func NewWebmSaver() *WebmSaver {
return &WebmSaver{
firstWrite: true,
sampleWriter: NewSampleWriter(),
preBuffering: make([]*avp.Sample, 0, maxBufferedSamples),
}
}
// SetStatsContext sets the logging information to display when writing
// stats to the log.
func (s *WebmSaver) SetStatsContext(context string) {
s.statsContext = context
}
// Write sample to webmsaver
func (s *WebmSaver) Write(sample *avp.Sample) error {
s.Lock()
if s.firstWrite {
s.dateUTC = time.Now()
s.firstWrite = false
}
if s.closed {
// already closed, ignore samples that are pending
s.Unlock()
return nil
}
atomic.StoreInt32(&(s.writeInProgress), 1)
s.Unlock()
if s.handlePrebuffer(sample) {
atomic.StoreInt32(&(s.writeInProgress), 0)
return nil
}
s.handleStats(sample, &s.liveStats)
if sample.Type == avp.TypeVP8 {
if sample.PrevDroppedPackets > 0 {
s.pushVideoDropped(sample)
}
s.pushVP8(sample)
} else if sample.Type == avp.TypeOpus {
if sample.PrevDroppedPackets > 0 {
s.pushAudioDropped(sample)
}
s.pushOpus(sample)
}
atomic.StoreInt32(&(s.writeInProgress), 0)
return nil
}
func (s *WebmSaver) handlePrebuffer(sample *avp.Sample) bool {
if s.preBuffering == nil {
return false
}
s.handleStats(sample, &s.preBufferingStats)
if sample != nil {
s.preBuffering = append(s.preBuffering, sample)
}
initVideoNow := func(useWidth, useHeight int) {
// Initialize WebM saver using received frame size.
s.initWriter(useWidth, useHeight)
preBuffering := s.preBuffering
s.preBuffering = nil
for _, bufferedSample := range preBuffering {
_ = s.Write(bufferedSample)
}
}
if sample == nil || len(s.preBuffering) == cap(s.preBuffering) {
initVideoNow(defaultWidth, defaultHeight)
return true
}
if sample.Type != avp.TypeVP8 {
return true
}
payload := sample.Payload.([]byte)
if len(payload) < 10 {
return true
}
// Read VP8 header.
if payload[0]&0x1 != 0 {
return true
}
// Keyframe has frame information.
raw := uint(payload[6]) | uint(payload[7])<<8 | uint(payload[8])<<16 | uint(payload[9])<<24
width := int(raw & 0x3FFF)
height := int((raw >> 16) & 0x3FFF)
initVideoNow(width, height)
return true
}
func (s *WebmSaver) handleStats(sample *avp.Sample, useStats *webmSaverStats) {
if len(s.statsContext) < 1 {
return
}
report := func(value *int, total, mask int, message string) {
wasZero := (*value) == 0
(*value) += total
if wasZero || (*value)&mask == 0x00 {
log.Debugf("WebM saver stat: %d for %s, context=%s\n", (*value), message, s.statsContext)
}
}
if nil == sample {
report(&useStats.unknown, 1, 0xFF, "unknown nil samples")
return
}
switch sample.Type {
case avp.TypeOpus:
if sample.PrevDroppedPackets > 0 {
report(&useStats.droppedAudio, int(sample.PrevDroppedPackets), 0xFF, "audio dropped")
}
report(&useStats.audio, 1, 0xFF, "audio")
case avp.TypeVP8:
if sample.PrevDroppedPackets > 0 {
report(&useStats.droppedVideo, int(sample.PrevDroppedPackets), 0xFF, "video dropped")
}
payload := sample.Payload.([]byte)
videoKeyframe := (payload[0]&0x1 == 0)
if videoKeyframe {
report(&useStats.videoKey, 1, 0x3, "video key")
} else {
report(&useStats.videoInter, 1, 0x3F, "video")
}
default:
report(&useStats.unknown, 1, 0xFF, "unknown samples")
}
}
// Attach attach a child element
func (s *WebmSaver) Attach(e avp.Element) {
s.sampleWriter.Attach(e)
}
// Close Close the WebmSaver
func (s *WebmSaver) Close() {
// wait for any pending writes to complete
for {
var alreadyClosed bool
var closed bool
s.Lock()
if s.closed {
alreadyClosed = true
}
if atomic.LoadInt32(&(s.writeInProgress)) == 0 {
s.closed = true
closed = true
}
s.Unlock()
if alreadyClosed {
return
}
if closed {
break
}
time.Sleep(time.Millisecond * 20)
}
s.handlePrebuffer(nil)
s.closed = true
if s.vttAudioWriter != nil {
if err := s.vttAudioWriter.Close(); err != nil {
log.Errorf("vtt audio close err: %s", err)
}
}
if s.vttVideoWriter != nil {
if err := s.vttVideoWriter.Close(); err != nil {
log.Errorf("vtt video close err: %s", err)
}
}
if s.audioWriter != nil {
if err := s.audioWriter.Close(); err != nil {
log.Errorf("audio close err: %s", err)
}
}
if s.videoWriter != nil {
if err := s.videoWriter.Close(); err != nil {
log.Errorf("video close err: %s", err)
}
}
}
func (s *WebmSaver) pushAudioDropped(sample *avp.Sample) {
if s.vttAudioWriter != nil {
var metaPayload [2]byte
// big endian encoded value as two bytes
metaPayload[0] = uint8(sample.PrevDroppedPackets >> 8)
metaPayload[1] = uint8(sample.PrevDroppedPackets & 0xFF)
referenceTimestamp := s.audioTimestamp
if referenceTimestamp == 0 {
referenceTimestamp = sample.Timestamp
}
t := (sample.Timestamp - referenceTimestamp) / 48
if _, err := s.vttAudioWriter.Write(true, int64(t), metaPayload[:]); err != nil {
log.Errorf("vtt audio writer err: %s", err)
}
}
}
func (s *WebmSaver) pushVideoDropped(sample *avp.Sample) {
if s.vttAudioWriter != nil {
var metaPayload [2]byte
// big endian encoded value as two bytes
metaPayload[0] = uint8(sample.PrevDroppedPackets >> 8)
metaPayload[1] = uint8(sample.PrevDroppedPackets & 0xFF)
referenceTimestamp := s.videoTimestamp
if referenceTimestamp == 0 {
referenceTimestamp = sample.Timestamp
}
t := (sample.Timestamp - referenceTimestamp) / 90
if _, err := s.vttVideoWriter.Write(true, int64(t), metaPayload[:]); err != nil {
log.Errorf("vtt video writer err: %s", err)
}
}
}
func (s *WebmSaver) pushOpus(sample *avp.Sample) {
if s.audioWriter != nil {
if s.audioTimestamp == 0 {
s.audioTimestamp = sample.Timestamp
}
t := (sample.Timestamp - s.audioTimestamp) / 48
if _, err := s.audioWriter.Write(true, int64(t), sample.Payload.([]byte)); err != nil {
log.Errorf("audio writer err: %s", err)
}
}
}
func (s *WebmSaver) pushVP8(sample *avp.Sample) {
payload := sample.Payload.([]byte)
// Read VP8 header.
videoKeyframe := (payload[0]&0x1 == 0)
if s.videoWriter != nil {
if s.videoTimestamp == 0 {
s.videoTimestamp = sample.Timestamp
}
t := (sample.Timestamp - s.videoTimestamp) / 90
if _, err := s.videoWriter.Write(videoKeyframe, int64(t), payload); err != nil {
log.Errorf("video write err: %s", err)
}
}
}
func (s *WebmSaver) initWriter(width, height int) {
useInterceptor := mkvcore.MustBlockInterceptor(mkvcore.NewMultiTrackBlockSorter(mkvcore.WithMaxTimescaleDelay(maxAudioVideoSyncDelay.Milliseconds()), mkvcore.WithSortRule(mkvcore.BlockSorterDropOutdated)))
options := []mkvcore.BlockWriterOption{
mkvcore.WithSegmentInfo(&webm.Info{
TimecodeScale: webm.DefaultSegmentInfo.TimecodeScale,
MuxingApp: webm.DefaultSegmentInfo.MuxingApp,
WritingApp: webm.DefaultSegmentInfo.WritingApp,
DateUTC: s.dateUTC,
}),
mkvcore.WithSeekHead(true),
mkvcore.WithBlockInterceptor(useInterceptor),
}
ws, err := webm.NewSimpleBlockWriter(s.sampleWriter,
[]webm.TrackEntry{
{
Name: "VttAudioDroppedPacketMeta",
TrackNumber: 1,
TrackUID: 98765,
CodecID: "D_WEBVTT/METADATA",
TrackType: 0x21,
DefaultDuration: 20000000,
}, {
Name: "Audio",
TrackNumber: 2,
TrackUID: 12345,
CodecID: "A_OPUS",
TrackType: 2,
DefaultDuration: 20000000,
Audio: &webm.Audio{
SamplingFrequency: 48000.0,
Channels: 2,
},
}, {
Name: "VttVideoDroppedPacketMeta",
TrackNumber: 3,
TrackUID: 54321,
CodecID: "D_WEBVTT/METADATA",
TrackType: 0x21,
DefaultDuration: 20000000,
}, {
Name: "Video",
TrackNumber: 4,
TrackUID: 67890,
CodecID: "V_VP8",
TrackType: 1,
DefaultDuration: 20000000,
Video: &webm.Video{
PixelWidth: uint64(width),
PixelHeight: uint64(height),
},
},
}, options...)
if err != nil {
log.Errorf("init writer err: %s", err)
}
log.Infof("WebM saver has started with video width=%d, height=%d\n", width, height)
s.audioWriter = ws[1]
s.videoWriter = ws[3]
s.vttAudioWriter = ws[0]
s.vttVideoWriter = ws[2]
}
// SampleWriter for writing samples
type SampleWriter struct {
Node
}
// NewSampleWriter creates a new sample writer
func NewSampleWriter() *SampleWriter {
return &SampleWriter{}
}
// Write sample
func (w *SampleWriter) Write(p []byte) (n int, err error) {
err = w.Node.Write(&avp.Sample{
Type: TypeBinary,
Payload: p,
})
if err != nil {
return 0, err
}
return len(p), nil
}
func (w *SampleWriter) Close() error {
w.Node.Close()
return nil
}