-
Notifications
You must be signed in to change notification settings - Fork 110
/
stream.go
413 lines (361 loc) · 10.4 KB
/
stream.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
413
// Package gostream implements a simple server for serving video streams over WebRTC.
package gostream
import (
"context"
"errors"
"image"
"sync"
"time"
"github.com/edaniels/golog"
"github.com/google/uuid"
// register screen drivers.
_ "github.com/pion/mediadevices/pkg/driver/microphone"
"github.com/pion/mediadevices/pkg/prop"
"github.com/pion/mediadevices/pkg/wave"
"github.com/pion/webrtc/v3"
"go.viam.com/utils"
"go.viam.com/rdk/gostream/codec"
"go.viam.com/rdk/rimage"
utils2 "go.viam.com/rdk/utils"
)
// A Stream is sink that accepts any image frames for the purpose
// of displaying in a WebRTC video track.
type Stream interface {
internalStream
Name() string
// Start starts processing frames.
Start()
// Ready signals that there is at least one client connected and that
// streams are ready for input. The returned context should be used for
// signaling that streaming is no longer ready.
StreamingReady() (<-chan struct{}, context.Context)
InputVideoFrames(props prop.Video) (chan<- MediaReleasePair[image.Image], error)
InputAudioChunks(props prop.Audio) (chan<- MediaReleasePair[wave.Audio], error)
// Stop stops further processing of frames.
Stop()
}
type internalStream interface {
VideoTrackLocal() (webrtc.TrackLocal, bool)
AudioTrackLocal() (webrtc.TrackLocal, bool)
}
// MediaReleasePair associates a media with a corresponding
// function to release its resources once the receiver of a
// pair is finished with the media.
type MediaReleasePair[T any] struct {
Media T
Release func()
}
// NewStream returns a newly configured stream that can begin to handle
// new connections.
func NewStream(config StreamConfig) (Stream, error) {
logger := config.Logger
if logger == nil {
logger = golog.Global()
}
if config.VideoEncoderFactory == nil && config.AudioEncoderFactory == nil {
return nil, errors.New("at least one audio or video encoder factory must be set")
}
if config.TargetFrameRate == 0 {
config.TargetFrameRate = codec.DefaultKeyFrameInterval
}
name := config.Name
if name == "" {
name = uuid.NewString()
}
var trackLocal *trackLocalStaticSample
if config.VideoEncoderFactory != nil {
trackLocal = newVideoTrackLocalStaticSample(
webrtc.RTPCodecCapability{MimeType: config.VideoEncoderFactory.MIMEType()},
"video",
name,
)
}
var audioTrackLocal *trackLocalStaticSample
if config.AudioEncoderFactory != nil {
audioTrackLocal = newAudioTrackLocalStaticSample(
webrtc.RTPCodecCapability{MimeType: config.AudioEncoderFactory.MIMEType()},
"audio",
name,
)
}
ctx, cancelFunc := context.WithCancel(context.Background())
bs := &basicStream{
name: name,
config: config,
streamingReadyCh: make(chan struct{}),
videoTrackLocal: trackLocal,
inputImageChan: make(chan MediaReleasePair[image.Image]),
outputVideoChan: make(chan []byte),
audioTrackLocal: audioTrackLocal,
inputAudioChan: make(chan MediaReleasePair[wave.Audio]),
outputAudioChan: make(chan []byte),
logger: logger,
shutdownCtx: ctx,
shutdownCtxCancel: cancelFunc,
}
return bs, nil
}
type basicStream struct {
mu sync.RWMutex
name string
config StreamConfig
started bool
streamingReadyCh chan struct{}
videoTrackLocal *trackLocalStaticSample
inputImageChan chan MediaReleasePair[image.Image]
outputVideoChan chan []byte
videoEncoder codec.VideoEncoder
audioTrackLocal *trackLocalStaticSample
inputAudioChan chan MediaReleasePair[wave.Audio]
outputAudioChan chan []byte
audioEncoder codec.AudioEncoder
// audioLatency specifies how long in between audio samples. This must be guaranteed
// by all streamed audio.
audioLatency time.Duration
audioLatencySet bool
shutdownCtx context.Context
shutdownCtxCancel func()
activeBackgroundWorkers sync.WaitGroup
logger golog.Logger
}
func (bs *basicStream) Name() string {
return bs.name
}
func (bs *basicStream) Start() {
bs.mu.Lock()
defer bs.mu.Unlock()
if bs.started {
return
}
bs.started = true
close(bs.streamingReadyCh)
bs.activeBackgroundWorkers.Add(4)
utils.ManagedGo(bs.processInputFrames, bs.activeBackgroundWorkers.Done)
utils.ManagedGo(bs.processOutputFrames, bs.activeBackgroundWorkers.Done)
utils.ManagedGo(bs.processInputAudioChunks, bs.activeBackgroundWorkers.Done)
utils.ManagedGo(bs.processOutputAudioChunks, bs.activeBackgroundWorkers.Done)
}
func (bs *basicStream) Stop() {
bs.mu.Lock()
defer bs.mu.Unlock()
if !bs.started {
close(bs.streamingReadyCh)
}
bs.started = false
bs.shutdownCtxCancel()
bs.activeBackgroundWorkers.Wait()
if bs.audioEncoder != nil {
bs.audioEncoder.Close()
}
if bs.videoEncoder != nil {
if err := bs.videoEncoder.Close(); err != nil {
bs.logger.Error(err)
}
}
// reset
bs.outputVideoChan = make(chan []byte)
bs.outputAudioChan = make(chan []byte)
ctx, cancelFunc := context.WithCancel(context.Background())
bs.shutdownCtx = ctx
bs.shutdownCtxCancel = cancelFunc
bs.streamingReadyCh = make(chan struct{})
}
func (bs *basicStream) StreamingReady() (<-chan struct{}, context.Context) {
bs.mu.RLock()
defer bs.mu.RUnlock()
return bs.streamingReadyCh, bs.shutdownCtx
}
func (bs *basicStream) InputVideoFrames(props prop.Video) (chan<- MediaReleasePair[image.Image], error) {
if bs.config.VideoEncoderFactory == nil {
return nil, errors.New("no video in stream")
}
return bs.inputImageChan, nil
}
func (bs *basicStream) InputAudioChunks(props prop.Audio) (chan<- MediaReleasePair[wave.Audio], error) {
if bs.config.AudioEncoderFactory == nil {
return nil, errors.New("no audio in stream")
}
bs.mu.Lock()
if bs.audioLatencySet && bs.audioLatency != props.Latency {
return nil, errors.New("cannot stream audio source with different latencies")
}
bs.audioLatencySet = true
bs.audioLatency = props.Latency
bs.mu.Unlock()
return bs.inputAudioChan, nil
}
func (bs *basicStream) VideoTrackLocal() (webrtc.TrackLocal, bool) {
return bs.videoTrackLocal, bs.videoTrackLocal != nil
}
func (bs *basicStream) AudioTrackLocal() (webrtc.TrackLocal, bool) {
return bs.audioTrackLocal, bs.audioTrackLocal != nil
}
func (bs *basicStream) processInputFrames() {
frameLimiterDur := time.Second / time.Duration(bs.config.TargetFrameRate)
defer close(bs.outputVideoChan)
var dx, dy int
ticker := time.NewTicker(frameLimiterDur)
defer ticker.Stop()
for {
select {
case <-bs.shutdownCtx.Done():
return
default:
}
select {
case <-bs.shutdownCtx.Done():
return
case <-ticker.C:
}
var framePair MediaReleasePair[image.Image]
select {
case framePair = <-bs.inputImageChan:
case <-bs.shutdownCtx.Done():
return
}
if framePair.Media == nil {
continue
}
var initErr bool
func() {
if framePair.Release != nil {
defer framePair.Release()
}
var encodedFrame []byte
if frame, ok := framePair.Media.(*rimage.LazyEncodedImage); ok && frame.MIMEType() == utils2.MimeTypeH264 {
encodedFrame = frame.RawData() // nothing to do; already encoded
} else {
bounds := framePair.Media.Bounds()
newDx, newDy := bounds.Dx(), bounds.Dy()
if bs.videoEncoder == nil || dx != newDx || dy != newDy {
dx, dy = newDx, newDy
bs.logger.Infow("detected new image bounds", "width", dx, "height", dy)
if err := bs.initVideoCodec(dx, dy); err != nil {
bs.logger.Error(err)
initErr = true
return
}
}
// thread-safe because the size is static
var err error
encodedFrame, err = bs.videoEncoder.Encode(bs.shutdownCtx, framePair.Media)
if err != nil {
bs.logger.Error(err)
return
}
}
if encodedFrame != nil {
select {
case <-bs.shutdownCtx.Done():
return
case bs.outputVideoChan <- encodedFrame:
}
}
}()
if initErr {
return
}
}
}
func (bs *basicStream) processInputAudioChunks() {
defer close(bs.outputAudioChan)
var samplingRate, channels int
for {
select {
case <-bs.shutdownCtx.Done():
return
default:
}
var audioChunkPair MediaReleasePair[wave.Audio]
select {
case audioChunkPair = <-bs.inputAudioChan:
case <-bs.shutdownCtx.Done():
return
}
if audioChunkPair.Media == nil {
continue
}
var initErr bool
func() {
if audioChunkPair.Release != nil {
defer audioChunkPair.Release()
}
info := audioChunkPair.Media.ChunkInfo()
newSamplingRate, newChannels := info.SamplingRate, info.Channels
if samplingRate != newSamplingRate || channels != newChannels {
samplingRate, channels = newSamplingRate, newChannels
bs.logger.Infow("detected new audio info", "sampling_rate", samplingRate, "channels", channels)
bs.audioTrackLocal.setAudioLatency(bs.audioLatency)
if err := bs.initAudioCodec(samplingRate, channels); err != nil {
bs.logger.Error(err)
initErr = true
return
}
}
encodedChunk, ready, err := bs.audioEncoder.Encode(bs.shutdownCtx, audioChunkPair.Media)
if err != nil {
bs.logger.Error(err)
return
}
if ready && encodedChunk != nil {
select {
case <-bs.shutdownCtx.Done():
return
case bs.outputAudioChan <- encodedChunk:
}
}
}()
if initErr {
return
}
}
}
func (bs *basicStream) processOutputFrames() {
framesSent := 0
for outputFrame := range bs.outputVideoChan {
select {
case <-bs.shutdownCtx.Done():
return
default:
}
now := time.Now()
if err := bs.videoTrackLocal.WriteData(outputFrame); err != nil {
bs.logger.Errorw("error writing frame", "error", err)
}
framesSent++
if Debug {
bs.logger.Debugw("wrote sample", "frames_sent", framesSent, "write_time", time.Since(now))
}
}
}
func (bs *basicStream) processOutputAudioChunks() {
chunksSent := 0
for outputChunk := range bs.outputAudioChan {
select {
case <-bs.shutdownCtx.Done():
return
default:
}
now := time.Now()
if err := bs.audioTrackLocal.WriteData(outputChunk); err != nil {
bs.logger.Errorw("error writing audio chunk", "error", err)
}
chunksSent++
if Debug {
bs.logger.Debugw("wrote sample", "chunks_sent", chunksSent, "write_time", time.Since(now))
}
}
}
func (bs *basicStream) initVideoCodec(width, height int) error {
var err error
bs.videoEncoder, err = bs.config.VideoEncoderFactory.New(width, height, bs.config.TargetFrameRate, bs.logger)
return err
}
func (bs *basicStream) initAudioCodec(sampleRate, channelCount int) error {
var err error
if bs.audioEncoder != nil {
bs.audioEncoder.Close()
}
bs.audioEncoder, err = bs.config.AudioEncoderFactory.New(sampleRate, channelCount, bs.audioLatency, bs.logger)
return err
}