-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
197 lines (182 loc) · 4.94 KB
/
main.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
package hdl // import "m7s.live/plugin/hdl/v4"
import (
"net"
"net/http"
"strings"
"time"
m7sdb "github.com/zzs89117920/m7s-db"
"go.uber.org/zap"
. "m7s.live/engine/v4"
"m7s.live/engine/v4/codec"
"m7s.live/engine/v4/config"
"m7s.live/engine/v4/util"
)
type HDLConfig struct {
config.HTTP
config.Publish
config.Subscribe
config.Pull
}
func pull(streamPath, url string) {
if err := HDLPlugin.Pull(streamPath, url, NewHDLPuller(), 0); err != nil {
HDLPlugin.Error("pull", zap.String("streamPath", streamPath), zap.String("url", url), zap.Error(err))
}
}
func (c *HDLConfig) OnEvent(event any) {
switch v := event.(type) {
case FirstConfig:
var pullDevices []PullDevice
db := m7sdb.MysqlDB()
result := db.Where("type = ? and save = ?", 2, 1).Find(&pullDevices)
if(result.RowsAffected>0){
for _, item := range pullDevices {
pull(item.StreamPath, item.Target)
}
}
// for streamPath, url := range c.PullOnStart {
// pull(streamPath, url)
// }
case *Stream: //按需拉流
if url, ok := c.PullOnSub[v.Path]; ok {
pull(v.Path, url)
}
case SEclose://关闭流
streamPath := v.StreamEvent.Target.Path
db := m7sdb.MysqlDB()
var count int64
db.Model(&PullDevice{}).Where("stream_path = ?", streamPath).Count(&count)
if(count > 0){
db.Model(&PullDevice{}).Where("stream_path = ?", streamPath).Update("status", "2")
}
}
}
func str2number(s string) int {
switch s {
case "1":
return 1
case "2":
return 2
default:
return 0
}
}
type PullDevice struct {
Type int
StreamPath string
Target string
IsRecord bool
CreateTime time.Time
UserId int
Status int
Save int
}
func (c *HDLConfig) API_Pull(rw http.ResponseWriter, r *http.Request) {
streamPath := r.URL.Query().Get("streamPath")
target := r.URL.Query().Get("target")
save := str2number(r.URL.Query().Get("save"))
err := HDLPlugin.Pull(streamPath, target, NewHDLPuller(), str2number(r.URL.Query().Get("save")))
if err != nil {
http.Error(rw, err.Error(), http.StatusBadRequest)
} else {
if(save>0){
db := m7sdb.MysqlDB()
var count int64
db.Model(&PullDevice{}).Where("stream_path = ?", streamPath).Count(&count)
if(count==0){
device := PullDevice{ Type:2, CreateTime: time.Now(), UserId: 0, IsRecord:false, StreamPath:streamPath, Target: target, Status:1,Save: save }
db.Create(&device)
}
}
rw.Write([]byte("ok"))
}
}
func (*HDLConfig) API_List(rw http.ResponseWriter, r *http.Request) {
util.ReturnJson(FilterStreams[*HDLPuller], time.Second, rw, r)
}
// 确保HDLConfig实现了PullPlugin接口
var hdlConfig = new(HDLConfig)
var HDLPlugin = InstallPlugin(hdlConfig)
type HDLSubscriber struct {
Subscriber
}
func (sub *HDLSubscriber) OnEvent(event any) {
switch v := event.(type) {
case FLVFrame:
// t := time.Now()
// s := util.SizeOfBuffers(v)
if hdlConfig.WriteTimeout > 0 {
if conn, ok := sub.Writer.(net.Conn); ok {
conn.SetWriteDeadline(time.Now().Add(hdlConfig.WriteTimeout))
}
}
if _, err := v.WriteTo(sub); err != nil {
sub.Stop()
// } else {
// println(time.Since(t)/time.Millisecond, s)
}
default:
sub.Subscriber.OnEvent(event)
}
}
func (sub *HDLSubscriber) WriteFlvHeader() {
at, vt := sub.Audio, sub.Video
hasAudio, hasVideo := at != nil, vt != nil
var amf util.AMF
amf.Marshal("onMetaData")
metaData := util.EcmaArray{
"MetaDataCreator": "m7s" + Engine.Version,
"hasVideo": hasVideo,
"hasAudio": hasAudio,
"hasMatadata": true,
"canSeekToEnd": false,
"duration": 0,
"hasKeyFrames": 0,
"framerate": 0,
"videodatarate": 0,
"filesize": 0,
}
var flags byte
if hasAudio {
flags |= (1 << 2)
metaData["audiocodecid"] = int(at.CodecID)
metaData["audiosamplerate"] = at.SampleRate
metaData["audiosamplesize"] = at.SampleSize
metaData["stereo"] = at.Channels == 2
}
if hasVideo {
flags |= 1
metaData["videocodecid"] = int(vt.CodecID)
metaData["width"] = vt.SPSInfo.Width
metaData["height"] = vt.SPSInfo.Height
}
amf.Marshal(metaData)
// 写入FLV头
sub.Write([]byte{'F', 'L', 'V', 0x01, flags, 0, 0, 0, 9, 0, 0, 0, 0})
codec.WriteFLVTag(sub, codec.FLV_TAG_TYPE_SCRIPT, 0, amf.Buffer)
}
func (c *HDLConfig) ServeHTTP(w http.ResponseWriter, r *http.Request) {
streamPath := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/"), ".flv")
if r.URL.RawQuery != "" {
streamPath += "?" + r.URL.RawQuery
}
sub := &HDLSubscriber{}
sub.ID = r.RemoteAddr
sub.SetParentCtx(r.Context())
sub.SetIO(w)
if err := HDLPlugin.Subscribe(streamPath, sub); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
} else {
w.Header().Set("Content-Type", "video/x-flv")
w.Header().Set("Transfer-Encoding", "identity")
w.WriteHeader(http.StatusOK)
if hijacker, ok := w.(http.Hijacker); ok && c.WriteTimeout > 0 {
conn, _, _ := hijacker.Hijack()
conn.SetWriteDeadline(time.Now().Add(c.WriteTimeout))
sub.SetIO(conn)
} else {
w.(http.Flusher).Flush()
}
sub.WriteFlvHeader()
sub.PlayBlock(SUBTYPE_FLV)
}
}