-
-
Notifications
You must be signed in to change notification settings - Fork 346
Expand file tree
/
Copy pathpublisher.go
More file actions
819 lines (764 loc) · 20.7 KB
/
Copy pathpublisher.go
File metadata and controls
819 lines (764 loc) · 20.7 KB
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
package m7s
import (
"context"
"errors"
"fmt"
"reflect"
"sync"
"time"
"github.com/langhuihui/gomem"
"m7s.live/v5/pkg/codec"
. "m7s.live/v5/pkg"
"m7s.live/v5/pkg/config"
"m7s.live/v5/pkg/util"
)
type PublisherState int
const (
PublisherStateInit PublisherState = iota
PublisherStateTrackAdded
PublisherStateSubscribed
PublisherStateWaitSubscriber
PublisherStateDisposed
)
const (
PublishTypePull = "pull"
PublishTypeServer = "server"
PublishTypeVod = "vod"
PublishTypeTransform = "transform"
PublishTypeReplay = "replay"
)
type AVTracks struct {
*AVTrack
util.Collection[reflect.Type, *AVTrack]
sync.RWMutex
baseTs time.Duration //from old publisher's lastTs
}
func (t *AVTracks) Set(track *AVTrack) {
t.Lock()
defer t.Unlock()
t.AVTrack = track
track.BaseTs = t.baseTs
t.Add(track)
}
func (t *AVTracks) SetMinBuffer(start time.Duration) {
if t.AVTrack == nil {
return
}
t.AVTrack.BufferRange[0] = start
}
func (t *AVTracks) GetOrCreate(dataType reflect.Type) *AVTrack {
t.Lock()
defer t.Unlock()
if track, ok := t.Get(dataType); ok {
return track
}
if t.AVTrack == nil {
return nil
}
return t.CreateSubTrack(dataType)
}
func (t *AVTracks) CheckTimeout(timeout time.Duration) bool {
if t.AVTrack == nil {
return false
}
return time.Since(t.AVTrack.LastValue.WriteTime) > timeout
}
func (t *AVTracks) CreateSubTrack(dataType reflect.Type) (track *AVTrack) {
track = NewAVTrack(dataType, t.AVTrack)
track.WrapIndex = t.Length
t.Add(track)
return
}
func (t *AVTracks) Dispose() {
t.Lock()
defer t.Unlock()
for track := range t.Range {
track.Ready(ErrDisposed)
if track == t.AVTrack || track.RingWriter != t.AVTrack.RingWriter {
track.Dispose()
}
}
t.AVTrack = nil
t.Clear()
}
type Publisher struct {
PubSubBase
config.Publish
State PublisherState
Paused *util.Promise
pauseTime time.Time
AudioTrack, VideoTrack AVTracks
audioReady, videoReady *util.Promise
TimeoutTimer *time.Timer
DataTrack *DataTrack
Subscribers SubscriberCollection
GOP int
OnSeek func(time.Time)
OnGetPosition func() time.Time
PullProxyConfig *PullProxyConfig
dropAfterTs time.Duration
bufferTimeCounts map[time.Duration]int
serverSubCount int
vodSubCount int
}
type PublishParam struct {
Context context.Context
Audio, Video IAVFrame
StreamPath string
Config *config.Publish
}
func (p *Publisher) SubscriberRange(yield func(sub *Subscriber) bool) {
p.Subscribers.Range(yield)
}
func (p *Publisher) GetKey() string {
return p.StreamPath
}
func (p *Publisher) Start() (err error) {
s := p.Plugin.Server
if p.MaxCount > 0 && s.Streams.Length >= p.MaxCount {
return ErrPublishMaxCount
}
p.bufferTimeCounts = make(map[time.Duration]int)
p.Info("publish")
p.processPullProxyOnStart()
p.audioReady = util.NewPromise(p)
if !p.PubAudio {
p.audioReady.Reject(ErrMuted)
}
p.videoReady = util.NewPromise(p)
if !p.PubVideo {
p.videoReady.Reject(ErrMuted)
}
s.Waiting.WakeUp(p.StreamPath, p)
p.processAliasOnStart()
p.Plugin.Server.OnPublish(p)
return
}
func (p *Publisher) Go() error {
noDataCheck := time.NewTicker(time.Second * 5)
defer noDataCheck.Stop()
for {
select {
case <-p.TimeoutTimer.C:
if p.Paused != nil {
continue
}
switch p.State {
case PublisherStateInit:
if p.HasAudioTrack() || p.HasVideoTrack() {
} else {
return ErrPublishTimeout
}
case PublisherStateSubscribed:
case PublisherStateWaitSubscriber:
if p.Publish.DelayCloseTimeout > 0 {
return ErrPublishDelayCloseTimeout
}
}
case <-noDataCheck.C:
if p.Paused != nil {
continue
}
if p.State == PublisherStateInit && p.Publish.IdleTimeout > 0 && time.Since(p.StartTime) > p.Publish.IdleTimeout {
return ErrPublishIdleTimeout
}
if p.PubVideo && p.VideoTrack.CheckTimeout(p.PublishTimeout) {
p.Error("video timeout", "writeTime", p.VideoTrack.LastValue.WriteTime)
if p.VideoTrack.LastValue.Sequence > 0 {
return ErrPublishTimeout
}
if !p.HasAudioTrack() {
return ErrPublishTimeout
}
p.NoVideo()
}
if p.PubAudio && p.AudioTrack.CheckTimeout(p.PublishTimeout) {
p.Error("audio timeout", "writeTime", p.AudioTrack.LastValue.WriteTime)
if p.AudioTrack.LastValue.Sequence > 0 {
return ErrPublishTimeout
}
if !p.HasVideoTrack() {
return ErrPublishTimeout
}
p.NoAudio()
}
// 有订阅者但从未收到任何音视频数据(AVTrack 为 nil),超过 PublishTimeout 则终止
if p.State == PublisherStateSubscribed &&
p.PublishTimeout > 0 &&
time.Since(p.StartTime) > p.PublishTimeout &&
!p.HasAudioTrack() && !p.HasVideoTrack() {
p.Error("publish timeout: subscribed but no audio/video data received")
return ErrPublishTimeout
}
case <-p.Done():
return p.Err()
}
}
}
func (p *Publisher) RemoveSubscriber(subscriber *Subscriber) {
p.Subscribers.Remove(subscriber)
p.bufferTimeCounts[subscriber.BufferTime]--
if p.bufferTimeCounts[subscriber.BufferTime] == 0 {
delete(p.bufferTimeCounts, subscriber.BufferTime)
}
p.Info("subscriber -1", "count", p.Subscribers.Length)
if p.Plugin == nil {
return
}
if p.Subscribers.Length > 0 {
var maxBuf time.Duration
for k := range p.bufferTimeCounts {
if k > maxBuf {
maxBuf = k
}
}
if defaultBuf := p.Plugin.GetCommonConf().Publish.BufferTime; maxBuf < defaultBuf {
maxBuf = defaultBuf
}
p.BufferTime = maxBuf
} else {
p.BufferTime = p.Plugin.GetCommonConf().Publish.BufferTime
}
p.AudioTrack.SetMinBuffer(p.BufferTime)
p.VideoTrack.SetMinBuffer(p.BufferTime)
if subscriber.Type == SubscribeTypeServer {
p.serverSubCount--
}
if subscriber.Type == SubscribeTypeVod {
p.vodSubCount--
}
if p.State == PublisherStateSubscribed && p.serverSubCount == 0 && p.vodSubCount == 0 {
p.State = PublisherStateWaitSubscriber
if p.DelayCloseTimeout > 0 {
p.TimeoutTimer.Reset(p.DelayCloseTimeout)
}
}
}
func (p *Publisher) AddSubscriber(subscriber *Subscriber) {
oldPublisher := subscriber.Publisher
subscriber.Publisher = p
if oldPublisher == nil {
close(subscriber.waitPublishDone)
} else {
if subscriber.waitingPublish() {
subscriber.Info("publisher recover", "pid", p.ID)
} else {
subscriber.Info("publisher changed", "prePid", oldPublisher.ID, "pid", p.ID)
}
}
subscriber.waitStartTime = time.Time{}
if p.Subscribers.AddUnique(subscriber) {
if subscriber.Type == SubscribeTypeServer {
p.serverSubCount++
}
if subscriber.Type == SubscribeTypeVod {
p.vodSubCount++
}
p.bufferTimeCounts[subscriber.BufferTime]++
p.Info("subscriber +1", "count", p.Subscribers.Length)
if subscriber.BufferTime > p.BufferTime {
p.BufferTime = subscriber.BufferTime
p.AudioTrack.SetMinBuffer(p.BufferTime)
p.VideoTrack.SetMinBuffer(p.BufferTime)
}
p.State = PublisherStateSubscribed
if p.PublishTimeout > 0 {
p.TimeoutTimer.Reset(p.PublishTimeout)
}
}
}
func (p *Publisher) writeAV(t *AVTrack, avFrame *AVFrame, codecCtxChanged bool, tracks *AVTracks) (err error) {
t.AcceptFrame()
if p.TraceEnabled() {
frame := &t.Value
codec := t.FourCC().String()
p.Trace("write", "seq", frame.Sequence, "baseTs", int32(t.BaseTs/time.Millisecond), "ts0", uint32(avFrame.TS0/time.Millisecond), "ts", uint32(frame.Timestamp/time.Millisecond), "codec", codec, "size", frame.Size, "data", frame.Wraps[0].String())
}
// 处理子轨道
if tracks.Length > 1 && tracks.IsReady() {
for i, track := range tracks.Items[1:] {
if track.ICodecCtx == nil {
// 为新的子轨道初始化历史帧
if tracks == &p.VideoTrack {
// 视频轨道使用 IDRingList
if t.IDRingList.Len() > 0 {
for rf := t.IDRingList.Front().Value; rf != t.Ring; rf = rf.Next() {
toFrame := track.NewFrame(&rf.Value)
toSample := toFrame.GetSample()
if track.ICodecCtx != nil {
toSample.ICodecCtx = track.ICodecCtx
}
err = ConvertFrameType(rf.Value.Wraps[0], toFrame)
if err != nil {
track.ICodecCtx = nil
return
}
track.ICodecCtx = toSample.ICodecCtx
if track.ICodecCtx == nil {
return ErrUnsupportCodec
}
rf.Value.Wraps = append(rf.Value.Wraps, toFrame)
}
}
} else {
// 音频轨道使用 GetOldestIDR
if idr := tracks.GetOldestIDR(); idr != nil {
for rf := idr; rf != t.Ring; rf = rf.Next() {
toFrame := track.NewFrame(&rf.Value)
toSample := toFrame.GetSample()
if track.ICodecCtx != nil {
toSample.ICodecCtx = track.ICodecCtx
}
err = ConvertFrameType(rf.Value.Wraps[0], toFrame)
if err != nil {
track.ICodecCtx = nil
return
}
track.ICodecCtx = toSample.ICodecCtx
if track.ICodecCtx == nil {
return ErrUnsupportCodec
}
rf.Value.Wraps = append(rf.Value.Wraps, toFrame)
}
}
}
}
// 处理当前帧的转换
var toFrame IAVFrame
if len(avFrame.Wraps) > i+1 {
toFrame = avFrame.Wraps[i+1]
} else {
toFrame = track.NewFrame(avFrame)
avFrame.Wraps = append(avFrame.Wraps, toFrame)
}
toSample := toFrame.GetSample()
if codecCtxChanged {
track.ICodecCtx = nil
} else {
toSample.ICodecCtx = track.ICodecCtx
}
err = ConvertFrameType(avFrame.Wraps[0], toFrame)
track.ICodecCtx = toSample.ICodecCtx
if track.ICodecCtx != nil {
track.Ready(err)
}
}
}
if !t.Step() {
err = ErrDisposed
}
return
}
func (p *Publisher) checkCodecChange(t *AVTrack) (codecCtxChanged bool, err error) {
avFrame := &t.Value
if t.Allocator == nil {
t.Allocator = avFrame.GetAllocator()
}
err = avFrame.Wraps[0].CheckCodecChange()
if err != nil {
return
}
if avFrame.ICodecCtx == nil {
err = ErrUnsupportCodec
return
}
oldCodecCtx := t.ICodecCtx
t.ICodecCtx = avFrame.ICodecCtx
avFrame.TS0 = avFrame.Timestamp
t.FixTimestamp(avFrame.Sample, p.Scale)
codecCtxChanged = oldCodecCtx != t.ICodecCtx
return
}
func (p *Publisher) nextVideo() (err error) {
t := p.VideoTrack.AVTrack
defer func() {
if err == nil {
t.SpeedControl(p.Speed)
} else if t != nil {
t.Value.Reset()
}
}()
if err = p.Err(); err != nil {
return
}
avFrame := &t.Value
oldCodecCtx := t.ICodecCtx
var codecCtxChanged bool
codecCtxChanged, err = p.checkCodecChange(t)
if err != nil {
return err
}
if codecCtxChanged && oldCodecCtx != nil {
oldWidth, oldHeight := oldCodecCtx.(IVideoCodecCtx).Width(), oldCodecCtx.(IVideoCodecCtx).Height()
newWidth, newHeight := t.ICodecCtx.(IVideoCodecCtx).Width(), t.ICodecCtx.(IVideoCodecCtx).Height()
if oldWidth != newWidth || oldHeight != newHeight {
p.Info("video resolution changed", "oldWidth", oldWidth, "oldHeight", oldHeight, "newWidth", newWidth, "newHeight", newHeight)
}
}
var idr *util.Ring[AVFrame]
if t.IDRingList.Len() > 0 {
idr = t.IDRingList.Back().Value
if p.Speed != 1 && t.CheckIfNeedDropFrame(p.MaxFPS, p.Speed) {
p.dropAfterTs = t.LastTs
t.Trace("FRAME_DROP", "speed", p.Speed, "max_fps", p.MaxFPS,
"drop_level", t.DropFrameLevel, "stream_path", p.StreamPath)
return ErrSkip
} else {
p.dropAfterTs = 0
}
}
if avFrame.IDR {
if !t.IsReady() {
t.Ready(nil)
} else if idr != nil {
p.GOP = int(t.Value.Sequence - idr.Value.Sequence)
} else {
p.GOP = 0
}
if p.AudioTrack.Length > 0 {
p.AudioTrack.PushIDR()
}
}
return p.writeAV(t, avFrame, codecCtxChanged, &p.VideoTrack)
}
func (p *Publisher) nextAudio() (err error) {
t := p.AudioTrack.AVTrack
defer func() {
if err == nil {
t.SpeedControl(p.Speed)
} else if t != nil {
t.Value.Recycle()
}
}()
if err = p.Err(); err != nil {
return
}
avFrame := &t.Value
var codecCtxChanged bool
codecCtxChanged, err = p.checkCodecChange(t)
if err != nil {
return err
}
// 根据丢帧率进行音频帧丢弃
if p.dropAfterTs > 0 {
if t.LastTs > p.dropAfterTs {
return ErrSkip
}
}
if !t.IsReady() {
t.Ready(nil)
}
return p.writeAV(t, avFrame, codecCtxChanged, &p.AudioTrack)
}
func (p *Publisher) WriteData(data IDataFrame) (err error) {
for subscriber := range p.SubscriberRange {
if subscriber.DataChannel == nil {
continue
}
select {
case subscriber.DataChannel <- data:
default:
p.Warn("subscriber channel full", "subscriber", subscriber.ID)
}
}
return nil
}
func (p *Publisher) GetAudioCodecCtx() (ctx codec.ICodecCtx) {
if p.HasAudioTrack() {
return p.AudioTrack.ICodecCtx
}
return nil
}
func (p *Publisher) GetVideoCodecCtx() (ctx codec.ICodecCtx) {
if p.HasVideoTrack() {
return p.VideoTrack.ICodecCtx
}
return nil
}
func (p *Publisher) GetAudioTrack(dataType reflect.Type) (t *AVTrack) {
return p.AudioTrack.GetOrCreate(dataType)
}
func (p *Publisher) GetVideoTrack(dataType reflect.Type) (t *AVTrack) {
return p.VideoTrack.GetOrCreate(dataType)
}
func (p *Publisher) HasAudioTrack() bool {
return p.PubAudio && p.AudioTrack.Length > 0
}
func (p *Publisher) HasVideoTrack() bool {
return p.PubVideo && p.VideoTrack.Length > 0
}
// PreDispose is called by the gotask framework before waiting for subscriber
// child tasks to stop. Disposing the ring buffers here releases the write lock
// that subscriber goroutines may be blocked on in RingReader.StartRead(),
// preventing the following deadlock:
//
// waitChildrenDispose() blocks waiting for subscriber tasks to stop
// ↓ subscriber goroutines stuck on RLock() waiting for write lock
// ↓ write lock released only in RingWriter.Dispose()
// ↓ RingWriter.Dispose() called only after waitChildrenDispose()
//
// AVTracks.Dispose() is idempotent, so the subsequent call from Dispose() is safe.
func (p *Publisher) PreDispose() {
p.AudioTrack.Dispose()
p.VideoTrack.Dispose()
}
func (p *Publisher) Dispose() {
s := p.Plugin.Server
if p.Paused != nil {
p.Paused.Reject(p.StopReason())
}
p.processAliasOnDispose()
// Set disposed state BEFORE track disposal. processAliasOnDispose may
// have moved subscribers to Waiting or another publisher, and clears
// p.Subscribers. Setting the state here ensures subscriber goroutines
// detect disposal via checkPublishChanged even if track disposal panics
// (gotask silently catches panics via recover in the event loop).
p.State = PublisherStateDisposed
p.AudioTrack.Dispose()
p.VideoTrack.Dispose()
p.Info("unpublish", "remain", s.Streams.Length, "reason", p.StopReason())
DetachLogger(p.Logger)
// Stop any remaining subscribers (typically empty after processAliasOnDispose).
for subscriber := range p.SubscriberRange {
subscriber.Stop(ErrLost)
}
p.State = PublisherStateDisposed
p.processPullProxyOnDispose()
}
func (p *Publisher) TransferSubscribers(newPublisher *Publisher) {
p.Info("transfer subscribers", "newPublisher", newPublisher.ID, "newStreamPath", newPublisher.StreamPath)
var remain SubscriberCollection
for subscriber := range p.SubscriberRange {
if subscriber.Type != SubscribeTypeServer {
remain.Add(subscriber)
} else {
newPublisher.AddSubscriber(subscriber)
}
}
p.Subscribers = remain
p.serverSubCount = 0
p.BufferTime = p.Plugin.GetCommonConf().Publish.BufferTime
p.AudioTrack.SetMinBuffer(p.BufferTime)
p.VideoTrack.SetMinBuffer(p.BufferTime)
if p.State == PublisherStateSubscribed {
p.State = PublisherStateWaitSubscriber
if p.DelayCloseTimeout > 0 {
p.TimeoutTimer.Reset(p.DelayCloseTimeout)
}
}
}
func (p *Publisher) takeOver(old *Publisher) {
if old.HasAudioTrack() {
p.AudioTrack.baseTs = old.AudioTrack.LastTs
}
if old.HasVideoTrack() {
p.VideoTrack.baseTs = old.VideoTrack.LastTs
}
old.Stop(ErrKick)
p.Info("takeOver", "old", old.ID)
if old.Subscribers.Length > 0 {
p.Info(fmt.Sprintf("subscriber +%d", old.Subscribers.Length))
for subscriber := range old.SubscriberRange {
subscriber.Publisher = p
if subscriber.BufferTime > p.BufferTime {
p.BufferTime = subscriber.BufferTime
}
}
}
old.AudioTrack.Dispose()
old.VideoTrack.Dispose()
old.Subscribers = SubscriberCollection{}
}
func (p *Publisher) WaitTrack(audio, video bool) error {
var v, a = ErrNoTrack, ErrNoTrack
// wait any track
if p.PubAudio && p.PubVideo && !audio && !video {
select {
case <-p.videoReady.Done():
v = context.Cause(p.videoReady.Context)
if errors.Is(v, util.ErrResolve) {
v = nil
}
case <-p.audioReady.Done():
v = context.Cause(p.audioReady.Context)
if errors.Is(v, util.ErrResolve) {
v = nil
}
}
} else {
// need wait video
if p.PubVideo && video {
v = p.videoReady.Await()
}
// need wait audio
if p.PubAudio && audio {
a = p.audioReady.Await()
}
}
if v != nil && a != nil {
return ErrNoTrack
}
return nil
}
func (p *Publisher) NoVideo() {
p.PubVideo = false
if p.videoReady != nil {
p.videoReady.Reject(ErrMuted)
}
}
func (p *Publisher) NoAudio() {
p.PubAudio = false
if p.audioReady != nil {
p.audioReady.Reject(ErrMuted)
}
}
func (p *Publisher) Pause() {
if p.Paused != nil {
return
}
p.Paused = util.NewPromise(p)
p.pauseTime = time.Now()
}
func (p *Publisher) Resume() {
if p.Paused == nil {
return
}
p.Paused.Resolve()
p.Paused = nil
if p.HasVideoTrack() {
p.VideoTrack.AddPausedTime(time.Since(p.pauseTime))
}
if p.HasAudioTrack() {
p.AudioTrack.AddPausedTime(time.Since(p.pauseTime))
}
}
func (p *Publisher) Seek(ts time.Time) {
p.Info("seek", "time", ts)
if p.OnSeek != nil {
p.OnSeek(ts)
}
}
func (p *Publisher) GetPosition() (t time.Time) {
if p.OnGetPosition != nil {
return p.OnGetPosition()
}
return
}
type PublishAudioWriter[A IAVFrame] struct {
AudioFrame A
*Publisher
*gomem.ScalableMemoryAllocator
audioTrack *AVTrack
}
func NewPublishAudioWriter[A IAVFrame](puber *Publisher, allocator *gomem.ScalableMemoryAllocator) *PublishAudioWriter[A] {
if !puber.PubAudio {
return nil
}
if puber.AudioTrack.AVTrack != nil {
panic("audio track already exists")
}
pw := &PublishAudioWriter[A]{
Publisher: puber,
ScalableMemoryAllocator: allocator,
}
var tmp A
t := NewAVTrack(reflect.TypeOf(tmp), pw.Logger.With("track", "audio"), &pw.Publish, pw.audioReady)
pw.AudioTrack.Set(t)
pw.audioTrack = t
pw.AudioFrame = pw.getAudioFrameToWrite()
return pw
}
func (pw *PublishAudioWriter[A]) getAudioFrameToWrite() (frame A) {
if !pw.PubAudio {
return
}
t := pw.audioTrack
avFrame := &t.Value
if avFrame.Sample == nil {
avFrame.Wraps = append(avFrame.Wraps, t.NewFrame(avFrame))
}
avFrame.ICodecCtx = t.ICodecCtx
frame = avFrame.Wraps[0].(A)
frame.GetSample().SetAllocator(pw.ScalableMemoryAllocator)
return
}
func (pw *PublishAudioWriter[A]) NextAudio() (err error) {
if err = pw.nextAudio(); err != nil {
if err == ErrSkip {
return nil
}
return
}
pw.AudioFrame = pw.getAudioFrameToWrite()
return
}
type PublishVideoWriter[V IAVFrame] struct {
VideoFrame V
*Publisher
*gomem.ScalableMemoryAllocator
videoTrack *AVTrack
}
func NewPublishVideoWriter[V IAVFrame](puber *Publisher, allocator *gomem.ScalableMemoryAllocator) *PublishVideoWriter[V] {
if !puber.PubVideo {
return nil
}
if puber.VideoTrack.AVTrack != nil {
// Video track already exists, create a wrapper for the existing track
puber.Warn("video track already exists, creating wrapper")
pw := &PublishVideoWriter[V]{
Publisher: puber,
ScalableMemoryAllocator: allocator,
videoTrack: puber.VideoTrack.AVTrack,
}
// Reset SpeedController state for the reused track to prevent state conflicts
pw.videoTrack.ResetSpeedController()
// Also reset Publisher speed to normal for video loop playback
puber.Speed = 1.0
pw.VideoFrame = pw.getVideoFrameToWrite()
return pw
}
pw := &PublishVideoWriter[V]{
Publisher: puber,
ScalableMemoryAllocator: allocator,
}
var tmp V
t := NewAVTrack(reflect.TypeOf(tmp), pw.Logger.With("track", "video"), &pw.Publish, pw.videoReady)
pw.VideoTrack.Set(t)
pw.videoTrack = t
pw.VideoFrame = pw.getVideoFrameToWrite()
return pw
}
func (pw *PublishVideoWriter[V]) getVideoFrameToWrite() (frame V) {
if !pw.PubVideo {
return
}
t := pw.videoTrack
avFrame := &t.Value
if avFrame.Sample == nil {
avFrame.Wraps = append(avFrame.Wraps, t.NewFrame(avFrame))
}
avFrame.ICodecCtx = t.ICodecCtx
frame = avFrame.Wraps[0].(V)
frame.GetSample().SetAllocator(pw.ScalableMemoryAllocator)
return
}
func (pw *PublishVideoWriter[V]) NextVideo() (err error) {
if err = pw.nextVideo(); err != nil {
if err == ErrSkip {
return nil
}
return
}
pw.VideoFrame = pw.getVideoFrameToWrite()
return
}
type PublishWriter[A IAVFrame, V IAVFrame] struct {
*PublishAudioWriter[A]
*PublishVideoWriter[V]
}
func NewPublisherWriter[A IAVFrame, V IAVFrame](puber *Publisher, allocator *gomem.ScalableMemoryAllocator) *PublishWriter[A, V] {
return &PublishWriter[A, V]{
PublishAudioWriter: NewPublishAudioWriter[A](puber, allocator),
PublishVideoWriter: NewPublishVideoWriter[V](puber, allocator),
}
}