-
Notifications
You must be signed in to change notification settings - Fork 0
/
vstream.go
96 lines (82 loc) · 2.02 KB
/
vstream.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
package vstreamer
import (
"bytes"
"encoding/binary"
"fmt"
"github.com/gorilla/websocket"
"io"
"log"
"net/http"
)
const (
socketBufferSize = 1024
)
type VServer struct {
clients map[*client]bool
width uint16
height uint16
in *string
videoSource *VideoStream
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
ReadBufferSize: socketBufferSize,
WriteBufferSize: socketBufferSize,
}
var magicBytes = []byte("jsmp")
func (s *VServer) Echo(w http.ResponseWriter, r *http.Request) {
socket, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
buf := new(bytes.Buffer)
binary.Write(buf, binary.BigEndian, magicBytes)
binary.Write(buf, binary.BigEndian, s.width)
binary.Write(buf, binary.BigEndian, s.height)
err = socket.WriteMessage(websocket.BinaryMessage, buf.Bytes())
client := NewClient(socket)
s.clients[client] = true
log.Println("Websocket clients:", len(s.clients))
if len(s.clients) == 1 {
s.videoSource.Start(s)
}
}
func (s *VServer) FrameSize(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, "{\"width\":%d, \"height\":%d}", s.width, s.height)
}
func (s *VServer) Broadcast(reader *bytes.Reader) {
var writers []io.Writer
for client := range s.clients {
writer, err := client.socket.NextWriter(websocket.BinaryMessage)
if err != nil {
delete(s.clients, client)
log.Println("Websocket clients:", len(s.clients))
if len(s.clients) == 0 {
s.videoSource.Stop()
}
continue
}
writers = append(writers, writer)
defer writer.Close()
}
if len(writers) > 0 {
wrtr := io.MultiWriter(writers...)
if _, err := io.Copy(wrtr, reader); err != nil {
log.Println(err)
}
}
}
func NewServer(width uint16, height uint16, videoIn *string) *VServer {
vs := VServer{
clients: make(map[*client]bool),
width: width,
height: height,
in: videoIn,
videoSource: NewVideoSource(),
}
return &vs
}