forked from nareix/joy4
-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
104 lines (85 loc) · 2.02 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
package main
import (
"sync"
"io"
"net/http"
"github.com/kerberos-io/joy4/format"
"github.com/kerberos-io/joy4/av/avutil"
"github.com/kerberos-io/joy4/av/pubsub"
"github.com/kerberos-io/joy4/format/rtmp"
"github.com/kerberos-io/joy4/format/flv"
)
func init() {
format.RegisterAll()
}
type writeFlusher struct {
httpflusher http.Flusher
io.Writer
}
func (self writeFlusher) Flush() error {
self.httpflusher.Flush()
return nil
}
func main() {
server := &rtmp.Server{}
l := &sync.RWMutex{}
type Channel struct {
que *pubsub.Queue
}
channels := map[string]*Channel{}
server.HandlePlay = func(conn *rtmp.Conn) {
l.RLock()
ch := channels[conn.URL.Path]
l.RUnlock()
if ch != nil {
cursor := ch.que.Latest()
avutil.CopyFile(conn, cursor)
}
}
server.HandlePublish = func(conn *rtmp.Conn) {
streams, _ := conn.Streams()
l.Lock()
ch := channels[conn.URL.Path]
if ch == nil {
ch = &Channel{}
ch.que = pubsub.NewQueue()
ch.que.WriteHeader(streams)
channels[conn.URL.Path] = ch
} else {
ch = nil
}
l.Unlock()
if ch == nil {
return
}
avutil.CopyPackets(ch.que, conn)
l.Lock()
delete(channels, conn.URL.Path)
l.Unlock()
ch.que.Close()
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
l.RLock()
ch := channels[r.URL.Path]
l.RUnlock()
if ch != nil {
w.Header().Set("Content-Type", "video/x-flv")
w.Header().Set("Transfer-Encoding", "chunked")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.WriteHeader(200)
flusher := w.(http.Flusher)
flusher.Flush()
muxer := flv.NewMuxerWriteFlusher(writeFlusher{httpflusher: flusher, Writer: w})
cursor := ch.que.Latest()
avutil.CopyFile(muxer, cursor)
} else {
http.NotFound(w, r)
}
})
go http.ListenAndServe(":8089", nil)
server.ListenAndServe()
// ffmpeg -re -i movie.flv -c copy -f flv rtmp://localhost/movie
// ffmpeg -f avfoundation -i "0:0" .... -f flv rtmp://localhost/screen
// ffplay http://localhost:8089/movie
// ffplay http://localhost:8089/screen
}