This repository has been archived by the owner on Nov 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathstream.go
635 lines (533 loc) · 12.6 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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
package main
import (
"bufio"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
type Chunk struct {
id int
done bool
notifs []chan bool
}
func NewChunk(id int) *Chunk {
return &Chunk{
id: id,
done: false,
notifs: make([]chan bool, 0),
}
}
type Stream struct {
c *Config
m *Manager
quality string
order int
height int
width int
bitrate int
goal int
mutex sync.Mutex
chunks map[int]*Chunk
seenChunks map[int]bool // only for stdout reader
coder *exec.Cmd
inactive int
stop chan bool
}
func (s *Stream) Run() {
// run every 5s
t := time.NewTicker(5 * time.Second)
defer t.Stop()
s.stop = make(chan bool)
for {
select {
case <-t.C:
s.mutex.Lock()
// Prune chunks
for id := range s.chunks {
if id < s.goal-s.c.goalBufferMax {
s.pruneChunk(id)
}
}
s.inactive++
// Nothing done for 2 minutes
if s.inactive >= s.c.streamIdleTime/5 && s.coder != nil {
t.Stop()
s.clear()
}
s.mutex.Unlock()
case <-s.stop:
t.Stop()
s.mutex.Lock()
s.clear()
s.mutex.Unlock()
return
}
}
}
func (s *Stream) clear() {
log.Printf("%s-%s: stopping stream", s.m.id, s.quality)
for _, chunk := range s.chunks {
// Delete files
s.pruneChunk(chunk.id)
}
s.chunks = make(map[int]*Chunk)
s.seenChunks = make(map[int]bool)
s.goal = 0
if s.coder != nil {
s.coder.Process.Kill()
s.coder.Wait()
s.coder = nil
}
}
func (s *Stream) Stop() {
select {
case s.stop <- true:
default:
}
}
func (s *Stream) ServeList(w http.ResponseWriter, r *http.Request) error {
WriteM3U8ContentType(w)
w.Write([]byte("#EXTM3U\n"))
w.Write([]byte("#EXT-X-VERSION:4\n"))
w.Write([]byte("#EXT-X-MEDIA-SEQUENCE:0\n"))
w.Write([]byte("#EXT-X-PLAYLIST-TYPE:VOD\n"))
w.Write([]byte(fmt.Sprintf("#EXT-X-TARGETDURATION:%d\n", s.c.chunkSize)))
query := GetQueryString(r)
duration := s.m.probe.Duration.Seconds()
i := 0
for duration > 0 {
size := float64(s.c.chunkSize)
if duration < size {
size = duration
}
w.Write([]byte(fmt.Sprintf("#EXTINF:%.3f, nodesc\n", size)))
w.Write([]byte(fmt.Sprintf("%s-%06d.ts%s\n", s.quality, i, query)))
duration -= float64(s.c.chunkSize)
i++
}
w.Write([]byte("#EXT-X-ENDLIST\n"))
return nil
}
func (s *Stream) ServeChunk(w http.ResponseWriter, id int) error {
s.mutex.Lock()
defer s.mutex.Unlock()
s.inactive = 0
s.checkGoal(id)
// Already have this chunk
if chunk, ok := s.chunks[id]; ok {
// Chunk is finished, just return it
if chunk.done {
s.returnChunk(w, chunk)
return nil
}
// Still waiting on transcoder
s.waitForChunk(w, chunk)
return nil
}
// Will have this soon enough
foundBehind := false
for i := id - 1; i > id-s.c.lookBehind && i >= 0; i-- {
if _, ok := s.chunks[i]; ok {
foundBehind = true
}
}
if foundBehind {
// Make sure the chunk exists
chunk := s.createChunk(id)
// Wait for it
s.waitForChunk(w, chunk)
return nil
}
// Let's start over
s.restartAtChunk(w, id)
return nil
}
func (s *Stream) ServeFullVideo(w http.ResponseWriter, r *http.Request) error {
args := s.transcodeArgs(0)
if s.m.probe.CodecName == "h264" && s.quality == "max" {
// no need to transcode, just copy
// args = []string{"-loglevel", "warning", "-i", s.m.path, "-c", "copy"}
// try to just send the original file
http.ServeFile(w, r, s.m.path)
return nil
}
// Output mov
args = append(args, []string{
"-movflags", "frag_keyframe+empty_moov+faststart", "-f", "mov", "pipe:1",
}...)
coder := exec.Command(s.c.ffmpeg, args...)
log.Printf("%s-%s: %s", s.m.id, s.quality, strings.Join(coder.Args[:], " "))
cmdStdOut, err := coder.StdoutPipe()
if err != nil {
fmt.Printf("FATAL: ffmpeg command stdout failed with %s\n", err)
}
cmdStdErr, err := coder.StderrPipe()
if err != nil {
fmt.Printf("FATAL: ffmpeg command stdout failed with %s\n", err)
}
err = coder.Start()
if err != nil {
log.Printf("FATAL: ffmpeg command failed with %s\n", err)
}
go s.monitorStderr(cmdStdErr)
// Write to response
defer cmdStdOut.Close()
stdoutReader := bufio.NewReader(cmdStdOut)
// Write mov headers
w.Header().Set("Content-Type", "video/quicktime")
w.WriteHeader(http.StatusOK)
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Server does not support Flusher!",
http.StatusInternalServerError)
return nil
}
// Write data, flusing every 1MB
buf := make([]byte, 1024*1024)
for {
n, err := stdoutReader.Read(buf)
if err != nil {
if err == io.EOF {
break
}
log.Printf("FATAL: ffmpeg command failed with %s\n", err)
break
}
_, err = w.Write(buf[:n])
if err != nil {
log.Printf("%s-%s: client closed connection", s.m.id, s.quality)
log.Println(err)
break
}
flusher.Flush()
}
// Terminate ffmpeg process
coder.Process.Kill()
coder.Wait()
return nil
}
func (s *Stream) createChunk(id int) *Chunk {
if c, ok := s.chunks[id]; ok {
return c
} else {
s.chunks[id] = NewChunk(id)
return s.chunks[id]
}
}
func (s *Stream) pruneChunk(id int) {
delete(s.chunks, id)
// Remove file
filename := s.getTsPath(id)
os.Remove(filename)
}
func (s *Stream) returnChunk(w http.ResponseWriter, chunk *Chunk) {
// This function is called with lock, but we don't need it
s.mutex.Unlock()
defer s.mutex.Lock()
// Read file and write to response
filename := s.getTsPath(chunk.id)
f, err := os.Open(filename)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer f.Close()
w.Header().Set("Content-Type", "video/MP2T")
io.Copy(w, f)
}
func (s *Stream) waitForChunk(w http.ResponseWriter, chunk *Chunk) {
if chunk.done {
s.returnChunk(w, chunk)
return
}
// Add our channel
notif := make(chan bool)
chunk.notifs = append(chunk.notifs, notif)
t := time.NewTimer(10 * time.Second)
coder := s.coder
s.mutex.Unlock()
select {
case <-notif:
t.Stop()
case <-t.C:
}
s.mutex.Lock()
// remove channel
for i, c := range chunk.notifs {
if c == notif {
chunk.notifs = append(chunk.notifs[:i], chunk.notifs[i+1:]...)
break
}
}
// check for success
if chunk.done {
s.returnChunk(w, chunk)
return
}
// Check if coder was changed
if coder != s.coder {
w.WriteHeader(http.StatusConflict)
return
}
// Return timeout error
w.WriteHeader(http.StatusRequestTimeout)
}
func (s *Stream) restartAtChunk(w http.ResponseWriter, id int) {
// Stop current transcoder
s.clear()
chunk := s.createChunk(id) // create first chunk
// Start the transcoder
s.goal = id + s.c.goalBufferMax
s.transcode(id)
s.waitForChunk(w, chunk) // this is also a request
}
// Get arguments to ffmpeg
func (s *Stream) transcodeArgs(startAt float64) []string {
args := []string{
"-loglevel", "warning",
}
if startAt > 0 {
args = append(args, []string{
"-ss", fmt.Sprintf("%.6f", startAt),
}...)
}
// encoder selection
CV := "libx264"
// Check whether hwaccel should be used
if os.Getenv("VAAPI") == "1" {
CV = "h264_vaapi"
extra := "-hwaccel vaapi -hwaccel_device /dev/dri/renderD128 -hwaccel_output_format vaapi"
args = append(args, strings.Split(extra, " ")...)
} else if os.Getenv("NVENC") == "1" {
CV = "h264_nvenc"
extra := "-hwaccel cuda -hwaccel_output_format cuda"
args = append(args, strings.Split(extra, " ")...)
}
// Input specs
args = append(args, []string{
"-autorotate", "0", // consistent behavior
"-i", s.m.path, // Input file
"-copyts", // So the "-to" refers to the original TS
}...)
// Scaling for output
var scale string
var format string
if CV == "h264_vaapi" {
// VAAPI
format = "format=nv12|vaapi,hwupload"
scale = fmt.Sprintf("scale_vaapi=w=%d:h=%d:force_original_aspect_ratio=decrease", s.width, s.height)
} else if CV == "h264_nvenc" {
// NVENC
format = "format=nv12|cuda,hwupload"
scale = fmt.Sprintf("scale_cuda=w=%d:h=%d:force_original_aspect_ratio=decrease:passthrough=0", s.width, s.height)
} else {
// x264
format = "format=nv12"
if s.width >= s.height {
scale = fmt.Sprintf("scale=-2:%d", s.height)
} else {
scale = fmt.Sprintf("scale=%d:-2", s.width)
}
}
// do not scale or set bitrate for full quality
if s.quality == "max" {
if CV == "h264_nvenc" {
// Due to a bug(?) in NVENC, passthrough=0 must be set
args = append(args, []string{
"-vf", fmt.Sprintf("%s,%s", format, "scale_cuda=passthrough=0"),
}...)
} else {
args = append(args, []string{
"-vf", format,
}...)
}
} else {
args = append(args, []string{
"-vf", fmt.Sprintf("%s,%s", format, scale),
"-maxrate", fmt.Sprintf("%d", s.bitrate),
"-bufsize", fmt.Sprintf("%d", s.bitrate*2),
}...)
}
// Output specs
args = append(args, []string{
"-c:v", CV,
"-profile:v", "high",
}...)
// Device specific output args
if CV == "h264_vaapi" {
args = append(args, []string{
"-low_power", "1",
"-global_quality", "25",
}...)
} else if CV == "h264_nvenc" {
args = append(args, []string{
"-preset", "p6",
"-tune", "ll",
"-temporal-aq", "1",
"-rc", "vbr",
"-rc-lookahead", "30",
"-cq", "24",
}...)
} else if CV == "libx264" {
args = append(args, []string{
"-preset", "faster",
"-level:v", "4.0",
"-crf", "24",
}...)
}
// Audio
ab := "192k"
if s.bitrate < 1000000 {
ab = "64k"
} else if s.bitrate < 3000000 {
ab = "128k"
}
args = append(args, []string{
"-c:a", "aac",
"-ac", "1",
"-b:a", ab,
}...)
return args
}
func (s *Stream) transcode(startId int) {
if startId > 0 {
// Start one frame before
// This ensures that the keyframes are aligned
startId--
}
startAt := float64(startId * s.c.chunkSize)
args := s.transcodeArgs(startAt)
// Segmenting specs
args = append(args, []string{
"-avoid_negative_ts", "disabled",
"-f", "hls",
"-hls_time", fmt.Sprintf("%d", s.c.chunkSize),
"-force_key_frames", fmt.Sprintf("expr:gte(t,n_forced*%d)", s.c.chunkSize),
"-hls_segment_type", "mpegts",
"-start_number", fmt.Sprintf("%d", startId),
"-hls_segment_filename", s.getTsPath(-1),
"-",
}...)
s.coder = exec.Command(s.c.ffmpeg, args...)
log.Printf("%s-%s: %s", s.m.id, s.quality, strings.Join(s.coder.Args[:], " "))
cmdStdOut, err := s.coder.StdoutPipe()
if err != nil {
fmt.Printf("FATAL: ffmpeg command stdout failed with %s\n", err)
}
cmdStdErr, err := s.coder.StderrPipe()
if err != nil {
fmt.Printf("FATAL: ffmpeg command stdout failed with %s\n", err)
}
err = s.coder.Start()
if err != nil {
log.Printf("FATAL: ffmpeg command failed with %s\n", err)
}
go s.monitorTranscodeOutput(cmdStdOut, startAt)
go s.monitorStderr(cmdStdErr)
}
func (s *Stream) checkGoal(id int) {
goal := id + s.c.goalBufferMin
if goal > s.goal {
s.goal = id + s.c.goalBufferMax
// resume encoding
if s.coder != nil {
log.Printf("%s-%s: resuming transcoding", s.m.id, s.quality)
s.coder.Process.Signal(syscall.SIGCONT)
}
}
}
func (s *Stream) getTsPath(id int) string {
if id == -1 {
return fmt.Sprintf("%s/%s-%%06d.ts", s.m.tempDir, s.quality)
}
return fmt.Sprintf("%s/%s-%06d.ts", s.m.tempDir, s.quality, id)
}
// Separate goroutine
func (s *Stream) monitorTranscodeOutput(cmdStdOut io.ReadCloser, startAt float64) {
s.mutex.Lock()
coder := s.coder
s.mutex.Unlock()
defer cmdStdOut.Close()
stdoutReader := bufio.NewReader(cmdStdOut)
for {
if s.coder != coder {
break
}
line, err := stdoutReader.ReadBytes('\n')
if err == io.EOF {
if len(line) == 0 {
break
}
} else {
if err != nil {
log.Fatal(err)
}
line = line[:(len(line) - 1)]
}
l := string(line)
if strings.Contains(l, ".ts") {
// 1080p-000003.ts
idx := strings.Split(strings.Split(l, "-")[1], ".")[0]
id, err := strconv.Atoi(idx)
if err != nil {
log.Println("Error parsing chunk id")
}
if s.seenChunks[id] {
continue
}
s.seenChunks[id] = true
// Debug
log.Printf("%s-%s: recv %s", s.m.id, s.quality, l)
func() {
s.mutex.Lock()
defer s.mutex.Unlock()
// The coder has changed; do nothing
if s.coder != coder {
return
}
// Notify everyone
chunk := s.createChunk(id)
if chunk.done {
return
}
chunk.done = true
for _, n := range chunk.notifs {
n <- true
}
// Check goal satisfied
if id >= s.goal {
log.Printf("%s-%s: goal satisfied: %d", s.m.id, s.quality, s.goal)
s.coder.Process.Signal(syscall.SIGSTOP)
}
}()
}
}
// Join the process
coder.Wait()
}
func (s *Stream) monitorStderr(cmdStdErr io.ReadCloser) {
stderrReader := bufio.NewReader(cmdStdErr)
for {
line, err := stderrReader.ReadBytes('\n')
if err == io.EOF {
if len(line) == 0 {
break
}
} else {
if err != nil {
log.Fatal(err)
}
line = line[:(len(line) - 1)]
}
log.Println("ffmpeg-error:", string(line))
}
}