forked from webver/RstpToWs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hls.go
200 lines (179 loc) · 5.08 KB
/
hls.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
package main
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/grafov/m3u8"
"github.com/webver/vdk/av"
"github.com/webver/vdk/format/ts"
)
func ensureDir(dirName string) error {
err := os.MkdirAll(dirName, 0777)
if err == nil || os.IsExist(err) {
return nil
} else {
return err
}
}
func startHls(suuid string, ch chan av.Packet, stopCast chan bool) {
err := ensureDir(Config.HlsDirectory)
if err != nil {
panic("Wrong hls dir path")
}
// create hls playlist
playlistFileName := filepath.Join(Config.HlsDirectory, fmt.Sprintf("%s.m3u8", suuid))
playlist, err := m3u8.NewMediaPlaylist(Config.HlsWindowSize, Config.HlsCapacity)
if err != nil {
fmt.Println(err)
}
isConnected := true
//segmentNumber := Config.getLastHlsSegmentNumber(suuid)
segmentNumber := 0
var lastPacketTime time.Duration = 0
var lastKeyFrame av.Packet
for isConnected {
// create new segment file
segmentName := fmt.Sprintf("%s%04d.ts", suuid, segmentNumber)
segmentPath := filepath.Join(Config.HlsDirectory, segmentName)
outFile, err := os.Create(segmentPath)
if err != nil {
fmt.Println(err)
}
tsMuxer := ts.NewMuxer(outFile)
// write header
if err := tsMuxer.WriteHeader(Config.codecGet(suuid)); err != nil {
fmt.Println(err)
}
var videoStreamIdx int8 = 0
for idx, codec := range Config.codecGet(suuid) {
if codec.Type().IsVideo() == true {
videoStreamIdx = int8(idx)
break
}
}
// write packets
var segmentLength time.Duration = 0
var packetLength time.Duration = 0
var segmentCount int = 0
var start = false
//write lastKeyFrame if exist
if lastKeyFrame.IsKeyFrame == true {
start = true
if err = tsMuxer.WritePacket(lastKeyFrame); err != nil {
fmt.Println("Ts muxer write error")
}
// calculate segment length
packetLength = lastKeyFrame.Time - lastPacketTime
lastPacketTime = lastKeyFrame.Time
segmentLength += packetLength
segmentCount++
}
segmentLoop:
for {
select {
case <-stopCast:
isConnected = false
break segmentLoop
case pck := <-ch:
if pck.Idx == videoStreamIdx && pck.IsKeyFrame {
start = true
if segmentLength.Milliseconds() >= Config.HlsMsPerSegment {
lastKeyFrame = pck
break segmentLoop
}
}
if !start {
continue
}
if (pck.Idx == videoStreamIdx && pck.Time > lastPacketTime) || pck.Idx != videoStreamIdx {
//write packet to destination
if err = tsMuxer.WritePacket(pck); err != nil {
fmt.Println("Ts muxer write error", err)
}
if pck.Idx == videoStreamIdx {
// calculate segment length
packetLength = pck.Time - lastPacketTime
lastPacketTime = pck.Time
segmentLength += packetLength
}
segmentCount++
} else {
fmt.Println("Current packet time < previous ")
}
}
}
// write trailer
if err := tsMuxer.WriteTrailer(); err != nil {
fmt.Println(err)
}
// close segment file
if err := outFile.Close(); err != nil {
fmt.Println(err)
}
fmt.Printf("Wrote segment %s %f %d\n", segmentName, segmentLength.Seconds(), segmentCount)
// update playlist
playlist.Slide(segmentName, segmentLength.Seconds(), "")
playlistFile, err := os.Create(playlistFileName)
if err != nil {
fmt.Println(err)
}
playlistFile.Write(playlist.Encode().Bytes())
playlistFile.Close()
// cleanup segments
if err := removeOutdatedSegments(suuid, playlist); err != nil {
fmt.Println(err)
}
// increase segment index
segmentNumber++
}
filesToRemove := make([]string, len(playlist.Segments)+1)
// collect obsolete files
for _, segment := range playlist.Segments {
if segment != nil {
filesToRemove = append(filesToRemove, segment.URI)
}
}
_, fileName := filepath.Split(playlistFileName)
filesToRemove = append(filesToRemove, fileName)
// delete them later
go func(delay time.Duration, filesToRemove []string) {
fmt.Printf("Files to be deleted after %v: %v\n", delay, filesToRemove)
time.Sleep(delay)
for _, file := range filesToRemove {
if file != "" {
if err := os.Remove(filepath.Join(Config.HlsDirectory, file)); err != nil {
fmt.Println(err)
} else {
fmt.Printf("Successfully removed %s\n", file)
}
}
}
}(time.Duration(Config.HlsMsPerSegment*int64(playlist.Count()))*time.Millisecond, filesToRemove)
}
func removeOutdatedSegments(suuid string, playlist *m3u8.MediaPlaylist) error {
// write all playlist segment URIs into map
currentSegments := make(map[string]struct{}, len(playlist.Segments))
for _, segment := range playlist.Segments {
if segment != nil {
currentSegments[segment.URI] = struct{}{}
}
}
// find (probably) segment files in current directory
segmentFiles, err := filepath.Glob(filepath.Join(Config.HlsDirectory, fmt.Sprintf("%s*.ts", suuid)))
if err != nil {
return err
}
for _, segmentFile := range segmentFiles {
_, fileName := filepath.Split(segmentFile)
// check if file belongs to a playlist segment
if _, ok := currentSegments[fileName]; !ok {
if err := os.Remove(segmentFile); err != nil {
fmt.Println(err)
} else {
fmt.Printf("Removed segment %s\n", segmentFile)
}
}
}
return nil
}