-
Notifications
You must be signed in to change notification settings - Fork 0
/
dashcat.go
351 lines (280 loc) · 7.08 KB
/
dashcat.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
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
package main
import (
"context"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"sync"
"syscall"
"time"
"github.com/puellanivis/breton/lib/files"
"github.com/puellanivis/breton/lib/files/httpfiles"
_ "github.com/puellanivis/breton/lib/files/plugins"
"github.com/puellanivis/breton/lib/glog"
flag "github.com/puellanivis/breton/lib/gnuflag"
"github.com/puellanivis/breton/lib/io/bufpipe"
_ "github.com/puellanivis/breton/lib/metrics/http"
"github.com/puellanivis/breton/lib/net/dash"
"github.com/puellanivis/breton/lib/os/process"
"github.com/pkg/errors"
)
// Version information ready for build-time injection.
var (
Version = "v0.1.0"
Buildstamp = "dev"
)
// Flags contains all of the flags defined for the application.
var Flags struct {
MimeTypes []string `flag:"mime-type,short=t" desc:"which mime-type(s) to stream (default \"video/mp4\")"`
Play bool ` desc:"start a subprocess to pipe the output to (currently only mpv)"`
Quiet bool `flag:",short=q" desc:"suppress unnecessary output from subprocesses"`
Metrics bool ` desc:"listens on a given port to report metrics"`
Port int `flag:",short=p" desc:"which port to listen to, if set, implies --metrics (default random available port)"`
UserAgent string `flag:",default=dashcat/1.0" desc:"which User-Agent string to use"`
}
func init() {
flag.Struct("", &Flags)
}
var stderr = os.Stderr
func main() {
ctx, finish := process.Init("dash-cat", Version, Buildstamp)
defer finish()
args := flag.Args()
if len(args) < 1 {
flag.Usage()
process.Exit(1)
}
ctx = httpfiles.WithUserAgent(ctx, Flags.UserAgent)
ctx, cancel := context.WithCancel(ctx)
done := make(chan struct{})
defer func() {
cancel()
<-done
}()
if Flags.Quiet {
stderr = nil
}
if glog.V(2) {
if err := flag.Set("stderrthreshold", "INFO"); err != nil {
glog.Error(err)
}
}
if Flags.Port != 0 {
Flags.Metrics = true
}
if Flags.Metrics {
go func() {
l, err := net.Listen("tcp", fmt.Sprintf(":%d", Flags.Port))
if err != nil {
glog.Error("failed to establish listener: ", err)
return
}
_, lport, err := net.SplitHostPort(l.Addr().String())
if err != nil {
glog.Error("failed to get port from listener: ", err)
return
}
msg := fmt.Sprintf("metrics available at: http://localhost:%s/metrics/prometheus", lport)
fmt.Fprintln(os.Stderr, msg)
glog.Info(msg)
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, "/metrics/prometheus", http.StatusMovedPermanently)
})
srv := &http.Server{}
go func() {
if err := srv.Serve(l); err != nil {
if err != http.ErrServerClosed {
glog.Error("http.Server.Serve: ", err)
}
}
}()
<-ctx.Done()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
glog.Error("http.Server.Shutdown: ", err)
}
l.Close()
}()
}
if !Flags.Play {
// close done, because there will be no subprocess
close(done)
}
if len(Flags.MimeTypes) < 1 {
Flags.MimeTypes = append(Flags.MimeTypes, "video/mp4")
}
var out io.Writer = os.Stdout
if Flags.Play {
mpv, err := exec.LookPath("mpv")
if err != nil {
glog.Fatal(err)
}
cmd := exec.CommandContext(ctx, mpv, "-")
pipe, err := cmd.StdinPipe()
if err != nil {
glog.Fatal(err)
}
defer pipe.Close()
out = pipe
cmd.Stdout = os.Stdout
cmd.Stderr = stderr
if err := cmd.Start(); err != nil {
glog.Error(err)
}
go func() {
defer close(done)
defer cancel()
if err := cmd.Wait(); err != nil {
glog.Error(err)
}
if !Flags.Quiet {
glog.Info("subprocess quit")
}
}()
}
for _, arg := range args {
for err := range maybeMUX(ctx, out, arg) {
if err != nil {
glog.Errorf("%+v", err)
}
}
}
}
func maybeMUX(ctx context.Context, out io.Writer, arg string) <-chan error {
errch := make(chan error)
go func() {
defer close(errch)
var wg sync.WaitGroup
defer wg.Wait()
mpd, err := dash.New(ctx, arg)
if err != nil {
errch <- err
return
}
if len(Flags.MimeTypes) == 1 {
errch <- stream(ctx, out, mpd, Flags.MimeTypes[0])
return
}
ffmpegArgs := []string{
"-nostdin",
}
for i := range Flags.MimeTypes {
if mpd.IsDynamic() {
ffmpegArgs = append(ffmpegArgs,
"-thread_queue_size", "1024",
)
}
ffmpegArgs = append(ffmpegArgs, "-i", fmt.Sprintf("/dev/fd/%d", 3+i))
}
ffmpegArgs = append(ffmpegArgs,
"-c", "copy",
"-copyts",
"-movflags", "frag_keyframe+empty_moov",
)
ffmpegArgs = append(ffmpegArgs,
"-f", "mp4",
"-",
)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if glog.V(5) {
glog.Info("ffmpeg", ffmpegArgs)
}
cmd := exec.CommandContext(process.Context(), "ffmpeg", ffmpegArgs...)
cmd.Stdout = out
cmd.Stderr = stderr
for _, mimeType := range Flags.MimeTypes {
rd, wr, err := os.Pipe()
if err != nil {
errch <- errors.WithStack(err)
return
}
cmd.ExtraFiles = append(cmd.ExtraFiles, rd)
// make a loop-only shadow copy for closures.
mimeType := mimeType
pipe := bufpipe.New(ctx)
wg.Add(1)
go func() {
defer wg.Done()
defer func() {
errch <- errors.WithStack(wr.Close())
}()
// simple enough, bufpipe.Pipe will block on Reads until written to.
if _, err := files.Copy(ctx, wr, pipe); err != nil {
if err != ctx.Err() {
errch <- errors.WithStack(err)
}
}
}()
wg.Add(1)
go func() {
defer wg.Done()
defer func() {
errch <- errors.WithStack(pipe.Close())
}()
if err := stream(ctx, pipe, mpd, mimeType); err != nil {
if err != ctx.Err() {
errch <- err
}
cancel()
}
}()
}
if err := cmd.Run(); err != nil {
state := cmd.ProcessState.Sys().(syscall.WaitStatus)
if sig := state.Signal(); sig != -1 {
if sig == syscall.SIGPIPE {
// ignore “pipe closed”,
// which means that what we were catting to a process
// and that process closed.
return
}
}
errch <- errors.WithStack(err)
}
}()
return errch
}
func stream(ctx context.Context, out io.Writer, mpd *dash.Manifest, mimeType string) error {
s, err := mpd.Stream(out, mimeType, dash.PickHighestBandwidth())
if err != nil {
return err
}
if err := s.Init(ctx); err != nil {
return err
}
var totalDuration time.Duration
// we will later divide this duration by 2 below, to keep it the right
// value to ensure we don’t update too often.
minDuration := mpd.MinimumUpdatePeriod() * 2
readLoop:
for {
duration, err := s.Read(ctx)
totalDuration += duration
if err != nil {
if err != io.EOF {
glog.Error(err)
}
break
}
if duration > 0 {
if glog.V(1) {
fmt.Fprintln(os.Stderr, "segments had a duration of:", duration)
}
}
if duration < minDuration {
duration = minDuration
}
select {
case <-time.After(duration / 2):
case <-ctx.Done():
break readLoop
}
}
fmt.Fprintf(os.Stderr, "%s: total duration: %v\n", mimeType, totalDuration)
return nil
}