-
Notifications
You must be signed in to change notification settings - Fork 21
/
stream.go
90 lines (84 loc) · 2.24 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
package main
import (
"errors"
"log"
"time"
"github.com/deepch/vdk/av"
"github.com/deepch/vdk/format/rtspv2"
)
var (
ErrorStreamExitNoVideoOnStream = errors.New("Stream Exit No Video On Stream")
ErrorStreamExitRtspDisconnect = errors.New("Stream Exit Rtsp Disconnect")
ErrorStreamExitNoViewer = errors.New("Stream Exit On Demand No Viewer")
)
func serveStreams() {
for k, v := range Config.Streams {
if v.OnDemand {
log.Println("OnDemand not supported")
v.OnDemand = false
}
if !v.OnDemand {
go RTSPWorkerLoop(k, v.URL, v.OnDemand)
}
}
}
func RTSPWorkerLoop(name, url string, OnDemand bool) {
defer Config.RunUnlock(name)
for {
log.Println(name, "Stream Try Connect")
err := RTSPWorker(name, url, OnDemand)
if err != nil {
log.Println(err)
}
if OnDemand && !Config.HasViewer(name) {
log.Println(name, ErrorStreamExitNoViewer)
return
}
time.Sleep(1 * time.Second)
}
}
func RTSPWorker(name, url string, OnDemand bool) error {
keyTest := time.NewTimer(20 * time.Second)
clientTest := time.NewTimer(20 * time.Second)
var preKeyTS = time.Duration(0)
var Seq []*av.Packet
RTSPClient, err := rtspv2.Dial(rtspv2.RTSPClientOptions{URL: url, DisableAudio: false, DialTimeout: 3 * time.Second, ReadWriteTimeout: 3 * time.Second, Debug: false})
if err != nil {
return err
}
defer RTSPClient.Close()
if RTSPClient.CodecData != nil {
Config.coAd(name, RTSPClient.CodecData)
}
var AudioOnly bool
if len(RTSPClient.CodecData) == 1 && RTSPClient.CodecData[0].Type().IsAudio() {
AudioOnly = true
}
for {
select {
case <-clientTest.C:
if OnDemand && !Config.HasViewer(name) {
return ErrorStreamExitNoViewer
}
case <-keyTest.C:
return ErrorStreamExitNoVideoOnStream
case signals := <-RTSPClient.Signals:
switch signals {
case rtspv2.SignalCodecUpdate:
Config.coAd(name, RTSPClient.CodecData)
case rtspv2.SignalStreamRTPStop:
return ErrorStreamExitRtspDisconnect
}
case packetAV := <-RTSPClient.OutgoingPacketQueue:
if AudioOnly || packetAV.IsKeyFrame {
keyTest.Reset(20 * time.Second)
if preKeyTS > 0 {
Config.StreamHLSAdd(name, Seq, packetAV.Time-preKeyTS)
Seq = []*av.Packet{}
}
preKeyTS = packetAV.Time
}
Seq = append(Seq, packetAV)
}
}
}