forked from Monibuca/plugin-hls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
write.go
282 lines (265 loc) · 7.31 KB
/
write.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
package hls
import (
"container/ring"
"fmt"
"math"
"strconv"
"strings"
"sync"
"time"
"github.com/zls3434/m7s-engine/v4"
"github.com/zls3434/m7s-engine/v4/codec"
"github.com/zls3434/m7s-engine/v4/codec/mpegts"
"github.com/zls3434/m7s-engine/v4/track"
"github.com/zls3434/m7s-engine/v4/util"
"go.uber.org/zap"
)
var memoryTs util.Map[string, interface {
GetTs(key string) util.Recyclable
}]
var memoryM3u8 sync.Map
var pools sync.Pool
func init() {
pools.New = func() any {
return make(util.BytesPool, 20)
}
}
type TrackReader struct {
sync.RWMutex
M3u8 util.Buffer
pes *mpegts.MpegtsPESFrame
ts *engine.MemoryTs
*track.AVRingReader
write_time time.Duration
m3u8Name string
hls_segment_count uint32 // hls segment count
playlist Playlist
infoRing *ring.Ring
hls_playlist_count uint32
hls_segment_window uint32
}
func (tr *TrackReader) init(hls *HLSWriter, media *track.Media, pid uint16) {
tr.ts = &engine.MemoryTs{
BytesPool: hls.pool,
}
tr.pes = &mpegts.MpegtsPESFrame{
Pid: pid,
}
tr.hls_segment_window = uint32(hlsConfig.Window) + 1
tr.infoRing = ring.New(int(tr.hls_segment_window))
tr.m3u8Name = hls.Stream.Path + "/" + media.Name
tr.AVRingReader = hls.CreateTrackReader(media)
tr.playlist = Playlist{
Writer: &tr.M3u8,
Version: 3,
Sequence: 0,
Targetduration: int(hlsConfig.Fragment / time.Millisecond / 666), // hlsFragment * 1.5 / 1000
}
}
type AudioTrackReader struct {
TrackReader
*track.Audio
}
type VideoTrackReader struct {
TrackReader
*track.Video
}
type HLSWriter struct {
pool util.BytesPool
audio_tracks []*AudioTrackReader
video_tracks []*VideoTrackReader
engine.Subscriber
memoryTs util.Map[string, util.Recyclable]
lastReadTime time.Time
}
func (hls *HLSWriter) GetTs(key string) util.Recyclable {
hls.lastReadTime = time.Now()
return hls.memoryTs.Get(key)
}
func (hls *HLSWriter) Start(streamPath string) {
hls.pool = pools.Get().(util.BytesPool)
if err := HLSPlugin.Subscribe(streamPath, hls); err != nil {
HLSPlugin.Error("HLS Subscribe", zap.Error(err))
return
}
streamPath = strings.Split(streamPath, "?")[0]
memoryTs.Add(streamPath, hls)
hls.ReadTrack()
memoryTs.Delete(streamPath)
hls.memoryTs.Range(func(k string, v util.Recyclable) {
v.Recycle()
})
pools.Put(hls.pool)
memoryM3u8.Delete(streamPath)
for _, t := range hls.video_tracks {
memoryM3u8.Delete(t.m3u8Name)
}
for _, t := range hls.audio_tracks {
memoryM3u8.Delete(t.m3u8Name)
}
if !hlsConfig.Preload {
writingMap.Delete(streamPath)
}
}
func (hls *HLSWriter) ReadTrack() {
var defaultAudio *AudioTrackReader
var defaultVideo *VideoTrackReader
if len(hls.video_tracks) > 0 {
defaultVideo = hls.video_tracks[0]
}
if len(hls.audio_tracks) > 0 {
defaultAudio = hls.audio_tracks[0]
if defaultVideo != nil {
for defaultAudio.IDRing == nil && !hls.IsClosed() {
time.Sleep(time.Millisecond * 10)
}
defaultAudio.Ring = defaultAudio.IDRing
} else {
defaultAudio.Ring = defaultAudio.Track.Ring
}
}
var audioGroup string
m3u8 := `#EXTM3U
#EXT-X-VERSION:3`
if defaultAudio != nil {
audioGroup = `,AUDIO="audio"`
m3u8 += fmt.Sprintf(`
#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="%s",DEFAULT=YES,AUTOSELECT=YES,URI="%s/%s.m3u8?sub=1"`, defaultAudio.Track.Name, hls.Stream.StreamName, defaultAudio.Track.Name)
}
if defaultVideo != nil {
m3u8 += fmt.Sprintf(`
#EXT-X-STREAM-INF:BANDWIDTH=2962000,NAME="%s",RESOLUTION=%dx%d%s
%s/%s.m3u8?sub=1`, defaultVideo.Track.Name, defaultVideo.Width, defaultVideo.Height, audioGroup, hls.Stream.StreamName, defaultVideo.Track.Name)
}
// 存一个默认的m3u8
memoryM3u8.Store(hls.Stream.Path, m3u8)
for hls.IO.Err() == nil {
for _, t := range hls.video_tracks {
for {
frame, err := t.TryRead()
if err != nil {
return
}
if frame == nil {
break
}
if frame.IFrame {
t.TrackReader.frag(hls, frame.Timestamp)
}
t.pes.IsKeyFrame = frame.IFrame
if err = t.ts.WriteVideoFrame(engine.VideoFrame{frame, t.Video, t.AbsTime, uint32(frame.PTS), uint32(frame.DTS)}, t.pes); err != nil {
return
}
}
}
for _, t := range hls.audio_tracks {
for {
frame, err := t.TryRead()
if err != nil {
return
}
if frame == nil {
break
}
t.TrackReader.frag(hls, frame.Timestamp)
t.pes.IsKeyFrame = false
if err = t.ts.WriteAudioFrame(engine.AudioFrame{frame, t.Audio, t.AbsTime, uint32(frame.PTS), uint32(frame.DTS)}, t.pes); err != nil {
return
}
}
}
time.Sleep(time.Millisecond * 10)
if !hlsConfig.Preload && !hls.lastReadTime.IsZero() && time.Since(hls.lastReadTime) > time.Second*15 {
hls.Stop(zap.String("reason", "no reader after 15s"))
}
}
}
func (t *TrackReader) frag(hls *HLSWriter, ts time.Duration) (err error) {
streamPath := hls.Stream.Path
// 当前的时间戳减去上一个ts切片的时间戳
if dur := ts - t.write_time; dur >= hlsConfig.Fragment {
// fmt.Println("time :", video.Timestamp, tsSegmentTimestamp)
if dur == ts && t.write_time == 0 { //时间戳不对的情况,首个默认为2s
dur = time.Duration(2) * time.Second
}
num := uint32(t.hls_segment_count)
tsFilename := t.Track.Name + strconv.FormatInt(time.Now().Unix(), 10) + "_" + strconv.FormatUint(uint64(num), 10) + ".ts"
tsFilePath := streamPath + "/" + tsFilename
// println(hls.currentTs.Length)
t.ts = &engine.MemoryTs{
BytesPool: t.ts.BytesPool,
PMT: t.ts.PMT,
}
HLSPlugin.Debug("write ts", zap.String("tsFilePath", tsFilePath))
hls.memoryTs.Store(tsFilePath, t.ts)
if t.playlist.Targetduration < int(dur.Seconds()) {
t.playlist.Targetduration = int(math.Ceil(dur.Seconds()))
}
if t.M3u8.Len() == 0 {
t.playlist.Init()
}
inf := PlaylistInf{
//浮点计算精度
Duration: dur.Seconds(),
Title: tsFilename,
FilePath: tsFilePath,
}
t.Lock()
defer t.Unlock()
if t.hls_segment_count > 0 {
if t.hls_playlist_count >= uint32(hlsConfig.Window) {
t.M3u8.Reset()
if err = t.playlist.Init(); err != nil {
return
}
//playlist起点是ring.next,长度是len(ring)-1
for p := t.infoRing.Next(); p != t.infoRing; p = p.Next() {
t.playlist.WriteInf(p.Value.(PlaylistInf))
}
} else {
if err = t.playlist.WriteInf(t.infoRing.Prev().Value.(PlaylistInf)); err != nil {
return
}
}
memoryM3u8.LoadOrStore(t.m3u8Name, t)
t.hls_playlist_count++
}
if t.hls_segment_count >= t.hls_segment_window {
if mts, loaded := hls.memoryTs.Delete(t.infoRing.Value.(PlaylistInf).FilePath); loaded {
mts.Recycle()
}
t.infoRing.Value = inf
t.infoRing = t.infoRing.Next()
} else {
t.infoRing.Value = inf
t.infoRing = t.infoRing.Next()
}
t.hls_segment_count++
t.write_time = ts
}
return
}
func (hls *HLSWriter) OnEvent(event any) {
switch v := event.(type) {
case *track.Video:
track := &VideoTrackReader{
Video: v,
}
track.init(hls, &v.Media, mpegts.PID_VIDEO)
track.ts.WritePMTPacket(0, v.CodecID)
track.Ring = track.IDRing
hls.video_tracks = append(hls.video_tracks, track)
case *track.Audio:
if v.CodecID != codec.CodecID_AAC {
return
}
track := &AudioTrackReader{
Audio: v,
}
track.init(hls, &v.Media, mpegts.PID_AUDIO)
track.ts.WritePMTPacket(v.CodecID, 0)
hls.audio_tracks = append(hls.audio_tracks, track)
default:
hls.Subscriber.OnEvent(event)
}
}