initial commit
This commit is contained in:
64
http/hw/hid/hid.go
Normal file
64
http/hw/hid/hid.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package hid
|
||||
|
||||
import (
|
||||
"os"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const (
|
||||
MouseUp = iota
|
||||
MouseDown
|
||||
MouseMoveAbsolute
|
||||
MouseMoveRelative
|
||||
MouseScroll
|
||||
)
|
||||
|
||||
const (
|
||||
MouseLeft = 1
|
||||
MouseRight = 2
|
||||
MouseWheel = 3
|
||||
)
|
||||
|
||||
const (
|
||||
HidMouseLeft byte = 0x01
|
||||
HidMouseRight byte = 0x02
|
||||
HidMouseWheel byte = 0x04
|
||||
)
|
||||
|
||||
const (
|
||||
ModifierLCtrl byte = 0x01
|
||||
ModifierLShift byte = 0x02
|
||||
ModifierLAlt byte = 0x04
|
||||
ModifierLGUI byte = 0x08
|
||||
ModifierRAlt byte = 0x40
|
||||
)
|
||||
|
||||
var (
|
||||
hid *Hid
|
||||
hidOnce sync.Once
|
||||
)
|
||||
|
||||
type Hid struct {
|
||||
g0 *os.File
|
||||
g1 *os.File
|
||||
g2 *os.File
|
||||
kbMutex sync.Mutex
|
||||
mouseMutex sync.Mutex
|
||||
}
|
||||
|
||||
func (h *Hid) Lock() {
|
||||
h.kbMutex.Lock()
|
||||
h.mouseMutex.Lock()
|
||||
}
|
||||
|
||||
func (h *Hid) Unlock() {
|
||||
h.kbMutex.Unlock()
|
||||
h.mouseMutex.Unlock()
|
||||
}
|
||||
|
||||
func GetHid() *Hid {
|
||||
hidOnce.Do(func() {
|
||||
hid = &Hid{}
|
||||
})
|
||||
return hid
|
||||
}
|
||||
47
http/hw/hid/keyboard.go
Normal file
47
http/hw/hid/keyboard.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package hid
|
||||
|
||||
func (h *Hid) Keyboard(queue <-chan []int) {
|
||||
for event := range queue {
|
||||
h.kbMutex.Lock()
|
||||
h.writeKeyboard(event)
|
||||
h.kbMutex.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hid) writeKeyboard(event []int) {
|
||||
var data []byte
|
||||
|
||||
if event[0] > 0 {
|
||||
code := byte(event[0])
|
||||
modifier := getModifier(event)
|
||||
data = []byte{modifier, 0x00, code, 0x00, 0x00, 0x00, 0x00, 0x00}
|
||||
} else {
|
||||
data = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
|
||||
}
|
||||
|
||||
h.Write(h.g0, data)
|
||||
}
|
||||
|
||||
func getModifier(event []int) byte {
|
||||
var modifier byte = 0x00
|
||||
|
||||
if event[1] == 1 {
|
||||
modifier |= ModifierLCtrl
|
||||
}
|
||||
|
||||
if event[2] == 1 {
|
||||
modifier |= ModifierLShift
|
||||
}
|
||||
|
||||
if event[3] == 1 {
|
||||
modifier |= ModifierLAlt
|
||||
} else if event[3] == 2 {
|
||||
modifier |= ModifierRAlt
|
||||
}
|
||||
|
||||
if event[4] == 1 {
|
||||
modifier |= ModifierLGUI
|
||||
}
|
||||
|
||||
return modifier
|
||||
}
|
||||
102
http/hw/hid/mouse.go
Normal file
102
http/hw/hid/mouse.go
Normal file
@@ -0,0 +1,102 @@
|
||||
package hid
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func (h *Hid) Mouse(queue <-chan []int) {
|
||||
for event := range queue {
|
||||
h.mouseMutex.Lock()
|
||||
switch event[0] {
|
||||
case MouseDown:
|
||||
h.mouseDown(event)
|
||||
case MouseUp:
|
||||
h.mouseUp()
|
||||
case MouseMoveAbsolute:
|
||||
h.mouseMoveAbsolute(event)
|
||||
case MouseMoveRelative:
|
||||
h.mouseMoveRelative(event)
|
||||
case MouseScroll:
|
||||
h.scroll(event)
|
||||
default:
|
||||
log.Debugf("invalid mouse event: %+v", event)
|
||||
}
|
||||
h.mouseMutex.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hid) mouseDown(event []int) {
|
||||
var button byte
|
||||
|
||||
switch event[1] {
|
||||
case MouseLeft:
|
||||
button = HidMouseLeft
|
||||
case MouseRight:
|
||||
button = HidMouseRight
|
||||
case MouseWheel:
|
||||
button = HidMouseWheel
|
||||
default:
|
||||
log.Debugf("invalid mouse button: %+v", event)
|
||||
return
|
||||
}
|
||||
|
||||
data := []byte{button, 0, 0, 0}
|
||||
h.writeWithTimeout(h.g1, data)
|
||||
}
|
||||
|
||||
func (h *Hid) mouseUp() {
|
||||
data := []byte{0, 0, 0, 0}
|
||||
h.writeWithTimeout(h.g1, data)
|
||||
}
|
||||
|
||||
func (h *Hid) scroll(event []int) {
|
||||
direction := 0x01
|
||||
if event[3] > 0 {
|
||||
direction = -0x1
|
||||
}
|
||||
|
||||
data := []byte{0, 0, 0, byte(direction)}
|
||||
h.writeWithTimeout(h.g1, data)
|
||||
}
|
||||
|
||||
func (h *Hid) mouseMoveAbsolute(event []int) {
|
||||
x := make([]byte, 2)
|
||||
y := make([]byte, 2)
|
||||
binary.LittleEndian.PutUint16(x, uint16(event[2]))
|
||||
binary.LittleEndian.PutUint16(y, uint16(event[3]))
|
||||
|
||||
data := []byte{0, x[0], x[1], y[0], y[1], 0}
|
||||
h.writeWithTimeout(h.g2, data)
|
||||
}
|
||||
|
||||
func (h *Hid) mouseMoveRelative(event []int) {
|
||||
data := []byte{byte(event[1]), byte(event[2]), byte(event[3]), 0}
|
||||
h.writeWithTimeout(h.g1, data)
|
||||
}
|
||||
|
||||
func (h *Hid) writeWithTimeout(file *os.File, data []byte) {
|
||||
deadline := time.Now().Add(8 * time.Millisecond)
|
||||
_ = file.SetWriteDeadline(deadline)
|
||||
|
||||
_, err := file.Write(data)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, os.ErrClosed):
|
||||
log.Debugf("hid already closed, reopen it...")
|
||||
h.OpenNoLock()
|
||||
case errors.Is(err, os.ErrDeadlineExceeded):
|
||||
log.Debugf("write to hid timeout")
|
||||
default:
|
||||
log.Errorf("write to hid failed: %s", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Tracef("write to hid: %+v", data)
|
||||
}
|
||||
73
http/hw/hid/op.go
Normal file
73
http/hw/hid/op.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package hid
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func (h *Hid) OpenNoLock() {
|
||||
var err error
|
||||
h.CloseNoLock()
|
||||
|
||||
h.g0, err = os.OpenFile("/dev/hidg0", os.O_WRONLY, 0o666)
|
||||
if err != nil {
|
||||
log.Errorf("open /dev/hidg0 failed: %s", err)
|
||||
}
|
||||
|
||||
h.g1, err = os.OpenFile("/dev/hidg1", os.O_WRONLY, 0o666)
|
||||
if err != nil {
|
||||
log.Errorf("open /dev/hidg1 failed: %s", err)
|
||||
}
|
||||
|
||||
h.g2, err = os.OpenFile("/dev/hidg2", os.O_WRONLY, 0o666)
|
||||
if err != nil {
|
||||
log.Errorf("open /dev/hidg2 failed: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hid) Open() {
|
||||
h.kbMutex.Lock()
|
||||
defer h.kbMutex.Unlock()
|
||||
h.mouseMutex.Lock()
|
||||
defer h.mouseMutex.Unlock()
|
||||
|
||||
h.CloseNoLock()
|
||||
|
||||
h.OpenNoLock()
|
||||
}
|
||||
|
||||
func (h *Hid) CloseNoLock() {
|
||||
for _, file := range []*os.File{h.g0, h.g1, h.g2} {
|
||||
if file != nil {
|
||||
_ = file.Sync()
|
||||
_ = file.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hid) Close() {
|
||||
h.kbMutex.Lock()
|
||||
defer h.kbMutex.Unlock()
|
||||
h.mouseMutex.Lock()
|
||||
defer h.mouseMutex.Unlock()
|
||||
|
||||
h.CloseNoLock()
|
||||
}
|
||||
|
||||
func (h *Hid) Write(file *os.File, data []byte) {
|
||||
_, err := file.Write(data)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrClosed) {
|
||||
log.Debugf("hid already closed, reopen it...")
|
||||
h.OpenNoLock()
|
||||
} else {
|
||||
log.Errorf("write to hid failed: %s", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Tracef("write to hid: %+v", data)
|
||||
}
|
||||
184
http/hw/rtc/webrtc.go
Normal file
184
http/hw/rtc/webrtc.go
Normal file
@@ -0,0 +1,184 @@
|
||||
package rtc
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/pion/webrtc/v4"
|
||||
)
|
||||
|
||||
// https://github.com/pion/example-webrtc-applications/blob/master/sfu-ws/main.go
|
||||
|
||||
var rtc *RTC
|
||||
|
||||
func Get() *RTC {
|
||||
return rtc
|
||||
}
|
||||
|
||||
var ErrPeerClosedConn = errors.New("webrtc: peer closed conn")
|
||||
|
||||
type RTC struct {
|
||||
l *net.UDPConn
|
||||
peer *webrtc.PeerConnection
|
||||
track *webrtc.TrackLocalStaticRTP
|
||||
sender *webrtc.RTPSender
|
||||
localSession string
|
||||
}
|
||||
|
||||
func (r *RTC) Close() error {
|
||||
return r.l.Close()
|
||||
}
|
||||
|
||||
// Read incoming RTCP packets
|
||||
// Before these packets are returned they are processed by interceptors. For things
|
||||
// like NACK this needs to be called.
|
||||
func (r *RTC) Read() {
|
||||
rtcpBuf := make([]byte, 1500)
|
||||
for {
|
||||
if _, _, rtcpErr := r.sender.Read(rtcpBuf); rtcpErr != nil {
|
||||
log.Errorf("failed to read RTCP packet: %v", rtcpErr)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func Init(host string, port int) (*RTC, error) {
|
||||
peerConnection, err := webrtc.NewPeerConnection(webrtc.Configuration{
|
||||
ICEServers: []webrtc.ICEServer{
|
||||
{
|
||||
URLs: []string{"stun:stun.l.google.com:19302"},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create peer connection: %v", err)
|
||||
}
|
||||
|
||||
// Open a UDP Listener for RTP Packets on port 5004
|
||||
l, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.ParseIP(host), Port: port})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to init webrtc listener: %v", err)
|
||||
}
|
||||
|
||||
// Increase the UDP receive buffer size
|
||||
// Default UDP buffer sizes vary on different operating systems
|
||||
bufferSize := 300000 // 300KB
|
||||
err = l.SetReadBuffer(bufferSize)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to set read buffer: %v", err)
|
||||
}
|
||||
|
||||
track, err := webrtc.NewTrackLocalStaticRTP(webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeH264}, "video", "pion")
|
||||
if err != nil { // it should never happens
|
||||
panic(fmt.Sprintf("failed to create video track: %v", err))
|
||||
}
|
||||
|
||||
rtpSender, err := peerConnection.AddTrack(track)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to add track to peer connection: %v", err)
|
||||
}
|
||||
|
||||
r := &RTC{
|
||||
peer: peerConnection,
|
||||
sender: rtpSender,
|
||||
track: track,
|
||||
l: l,
|
||||
}
|
||||
rtc = r
|
||||
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (r *RTC) Handshake(clientSession string) (string, error) {
|
||||
// Set the handler for ICE connection state
|
||||
// This will notify you when the peer has connected/disconnected
|
||||
r.peer.OnICEConnectionStateChange(func(connState webrtc.ICEConnectionState) {
|
||||
log.Infof("Connection State has changed %s", connState.String())
|
||||
|
||||
if connState == webrtc.ICEConnectionStateFailed {
|
||||
if closeErr := r.peer.Close(); closeErr != nil {
|
||||
panic(closeErr)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Wait for the offer to be pasted
|
||||
offer := webrtc.SessionDescription{}
|
||||
decode(clientSession, &offer)
|
||||
fmt.Printf("Offer: %+v\n", offer)
|
||||
|
||||
// Set the remote SessionDescription
|
||||
if err := r.peer.SetRemoteDescription(offer); err != nil {
|
||||
return "", fmt.Errorf("failed to set remote session description: %v", err)
|
||||
}
|
||||
|
||||
// Create answer
|
||||
answer, err := r.peer.CreateAnswer(nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create answer: %v", err)
|
||||
}
|
||||
|
||||
// Create channel that is blocked until ICE Gathering is complete
|
||||
gatherComplete := webrtc.GatheringCompletePromise(r.peer)
|
||||
|
||||
// Sets the LocalDescription, and starts our UDP listeners
|
||||
if err = r.peer.SetLocalDescription(answer); err != nil {
|
||||
return "", fmt.Errorf("failed to set local description: %v", err)
|
||||
}
|
||||
|
||||
// Block until ICE Gathering is complete, disabling trickle ICE
|
||||
// we do this because we only can exchange one signaling message
|
||||
// in a production application you should exchange ICE Candidates via OnICECandidate
|
||||
<-gatherComplete
|
||||
|
||||
r.localSession = encode(r.peer.LocalDescription())
|
||||
return r.localSession, nil
|
||||
}
|
||||
|
||||
func (r *RTC) Listen() error {
|
||||
// Read RTP packets forever and send them to the WebRTC Client
|
||||
inboundRTPPacket := make([]byte, 1600) // UDP MTU
|
||||
for {
|
||||
n, _, err := r.l.ReadFrom(inboundRTPPacket)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error during read: %v", err)
|
||||
}
|
||||
|
||||
if _, err = r.track.Write(inboundRTPPacket[:n]); err != nil {
|
||||
if errors.Is(err, io.ErrClosedPipe) {
|
||||
// The peerConnection has been closed.
|
||||
return ErrPeerClosedConn
|
||||
}
|
||||
|
||||
return fmt.Errorf("failed to send RTP packet to client: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// JSON encode + base64 a SessionDescription
|
||||
func encode(obj *webrtc.SessionDescription) string {
|
||||
b, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return base64.StdEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
// Decode a base64 and unmarshal JSON into a SessionDescription
|
||||
func decode(in string, obj *webrtc.SessionDescription) {
|
||||
b, err := base64.StdEncoding.DecodeString(in)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(b, obj); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
33
http/hw/stream/audio.go
Normal file
33
http/hw/stream/audio.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package stream
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"io"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
func AudioHandler(c *gin.Context) {
|
||||
cmd := exec.Command("ffmpeg",
|
||||
"-f", "alsa",
|
||||
"-i", "hw:0,0",
|
||||
"-acodec", "aac",
|
||||
"-f", "mp4", "-")
|
||||
// ffmpeg -f alsa -i hw:0,0 -acodec aac -f mp4 -
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
c.String(http.StatusInternalServerError, "Failed to capture audio: %v", err)
|
||||
return
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
c.String(http.StatusInternalServerError, "Failed to start ffmpeg: %v", err)
|
||||
return
|
||||
}
|
||||
defer cmd.Wait()
|
||||
|
||||
c.Header("Content-Type", "audio/mp4")
|
||||
if _, err := io.Copy(c.Writer, stdout); err != nil {
|
||||
c.String(http.StatusInternalServerError, "Failed to stream audio: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
135
http/hw/stream/extprocess.go
Normal file
135
http/hw/stream/extprocess.go
Normal file
@@ -0,0 +1,135 @@
|
||||
package stream
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sync"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type ExtProcess struct {
|
||||
path string
|
||||
cmd *exec.Cmd
|
||||
mu sync.Mutex
|
||||
args []string
|
||||
running bool
|
||||
stopChan chan struct{}
|
||||
finished chan struct{}
|
||||
state State
|
||||
|
||||
stdin io.WriteCloser
|
||||
}
|
||||
|
||||
func Init(path string, args []string) *ExtProcess {
|
||||
return &ExtProcess{
|
||||
args: args,
|
||||
path: path,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *ExtProcess) Start() {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
|
||||
if u.running {
|
||||
log.Debug("process is already running.")
|
||||
return
|
||||
}
|
||||
|
||||
u.stopChan = make(chan struct{})
|
||||
u.finished = make(chan struct{})
|
||||
|
||||
log.Debug("Starting external process...")
|
||||
u.cmd = exec.Command(u.path, u.args...)
|
||||
u.cmd.Stdout = os.Stdout
|
||||
u.cmd.Stderr = os.Stderr
|
||||
stdin, err := u.cmd.StdinPipe()
|
||||
if err != nil {
|
||||
log.Errorf("Couldn't handle stdin pipe: %v", err)
|
||||
return
|
||||
}
|
||||
u.stdin = stdin
|
||||
|
||||
err = u.cmd.Start()
|
||||
if err != nil {
|
||||
log.Errorf("Failed to start process: %v", err)
|
||||
}
|
||||
u.running = true
|
||||
|
||||
go func() {
|
||||
err = u.cmd.Wait()
|
||||
u.running = false
|
||||
log.Errorf("process exited with error: %v", err)
|
||||
|
||||
// planned stop
|
||||
if err == nil {
|
||||
u.finished <- struct{}{}
|
||||
close(u.stopChan)
|
||||
return
|
||||
}
|
||||
|
||||
u.stopChan <- struct{}{}
|
||||
close(u.finished)
|
||||
}()
|
||||
}
|
||||
|
||||
// Stop the ustreamer application
|
||||
func (u *ExtProcess) Stop() {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
|
||||
if !u.running {
|
||||
log.Debug("process is not running.")
|
||||
return
|
||||
}
|
||||
|
||||
log.Warn("Stopping process...")
|
||||
_, err := u.stdin.Write([]byte("q")) // TODO: works for ffmpeg, should be general or move into FFmpeg struct
|
||||
if err != nil {
|
||||
log.Errorf("Failed to stop process: %v", err)
|
||||
|
||||
if err := u.cmd.Process.Kill(); err != nil {
|
||||
log.Errorf("Failed to kill process: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := u.stdin.Close(); err != nil {
|
||||
log.Errorf("Failed to close stdin: %v", err)
|
||||
}
|
||||
|
||||
log.Info("waiting for finish")
|
||||
|
||||
select {
|
||||
case <-u.finished:
|
||||
log.Info("stopped as expected")
|
||||
case <-u.stopChan:
|
||||
log.Info("was killed")
|
||||
}
|
||||
|
||||
u.running = false
|
||||
}
|
||||
|
||||
func (u *ExtProcess) ChangeArgs(newArgs []string) {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
|
||||
u.args = newArgs
|
||||
log.Printf("Updated process arguments: %v", u.args)
|
||||
}
|
||||
|
||||
func (u *ExtProcess) Watch() {
|
||||
for {
|
||||
select {
|
||||
case <-u.stopChan:
|
||||
log.Errorf("process stopped unexpectedly. Restarting...")
|
||||
u.Start()
|
||||
/*case <-time.After(1 * time.Second): // Adjust the monitoring interval as needed
|
||||
if !u.running {
|
||||
log.Errorf("process is not running. Restarting...")
|
||||
u.Start()
|
||||
}*/
|
||||
}
|
||||
}
|
||||
}
|
||||
53
http/hw/stream/ffmpeg.go
Normal file
53
http/hw/stream/ffmpeg.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package stream
|
||||
|
||||
import (
|
||||
"rkkvm/config"
|
||||
)
|
||||
|
||||
//h264
|
||||
//ffmpeg -re -i /dev/video0 -c:v h264_rkmpp -b:v 2000000 -bsf:v h264_mp4toannexb -g 10 -f rtp rtp://127.0.0.1:5004?pkt_size=1200
|
||||
|
||||
//h265
|
||||
//ffmpeg -re -i /dev/video0 -c:v hevc_rkmpp -b:v 2000000 -g 10 -f rtp rtp://127.0.0.1:5004?pkt_size=1200
|
||||
|
||||
// vp8
|
||||
//ffmpeg -re -i /dev/video0 -c:v libvpx -crf 10 -b:v 3M -deadline 1 -g 10 -error-resilient 1 -auto-alt-ref 1 -an -f rtp rtp://127.0.0.1:5004?pkt_size=1200
|
||||
|
||||
// https://jsfiddle.net/z7ms3u5r/
|
||||
|
||||
var ffmpeg *FFmpeg
|
||||
|
||||
type FFmpeg struct {
|
||||
*ExtProcess
|
||||
config.FFmpeg
|
||||
}
|
||||
|
||||
func (f *FFmpeg) SetBitrate(b int) {
|
||||
f.Bitrate = b
|
||||
if f.Bitrate < 0 {
|
||||
f.Bitrate = 6000
|
||||
}
|
||||
|
||||
f.ChangeArgs(f.FormatArgs())
|
||||
}
|
||||
|
||||
func (f *FFmpeg) SetFPS(fps int) {
|
||||
f.FPS = fps
|
||||
if f.FPS < 0 {
|
||||
f.FPS = 30
|
||||
}
|
||||
|
||||
f.ChangeArgs(f.FormatArgs())
|
||||
}
|
||||
|
||||
func InitFFmpeg(path string, args []string) *FFmpeg {
|
||||
ffmpeg = &FFmpeg{
|
||||
ExtProcess: Init(path, args),
|
||||
FFmpeg: config.Get().FFmpeg,
|
||||
}
|
||||
return ffmpeg
|
||||
}
|
||||
|
||||
func GetFFmpeg() *FFmpeg {
|
||||
return ffmpeg
|
||||
}
|
||||
52
http/hw/stream/ustreamer.go
Normal file
52
http/hw/stream/ustreamer.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package stream
|
||||
|
||||
import (
|
||||
"rkkvm/config"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var ustreamer *UStreamer
|
||||
|
||||
type UStreamer struct {
|
||||
*ExtProcess
|
||||
config.UStreamer
|
||||
}
|
||||
|
||||
func InitUStreamer(path string, args []string) *UStreamer {
|
||||
ustreamer = &UStreamer{
|
||||
ExtProcess: Init(path, args),
|
||||
UStreamer: config.Get().UStreamer,
|
||||
}
|
||||
return ustreamer
|
||||
}
|
||||
|
||||
func GetUStreamer() *UStreamer {
|
||||
return ustreamer
|
||||
}
|
||||
|
||||
func (u *UStreamer) MonitorState() {
|
||||
ticker := time.NewTicker(1 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
{
|
||||
state, err := GetState()
|
||||
if err != nil {
|
||||
u.state = State{}
|
||||
log.Errorf("Failed to get process state: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
u.state = state
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UStreamer) GetState() State {
|
||||
return u.state
|
||||
}
|
||||
189
http/hw/stream/video.go
Normal file
189
http/hw/stream/video.go
Normal file
@@ -0,0 +1,189 @@
|
||||
package stream
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"rkkvm/config"
|
||||
"rkkvm/http/hw/rtc"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
/*
|
||||
{
|
||||
"ok": true,
|
||||
"result": {
|
||||
"instance_id": "",
|
||||
"encoder": {
|
||||
"type": "CPU",
|
||||
"quality": 80
|
||||
},
|
||||
"source": {
|
||||
"resolution": {
|
||||
"width": 1920,
|
||||
"height": 1080
|
||||
},
|
||||
"online": true,
|
||||
"desired_fps": 30,
|
||||
"captured_fps": 50
|
||||
},
|
||||
"stream": {
|
||||
"queued_fps": 26,
|
||||
"clients": 1,
|
||||
"clients_stat": {
|
||||
"2d90d210e837a19c": {
|
||||
"fps": 26,
|
||||
"extra_headers": false,
|
||||
"advance_headers": false,
|
||||
"dual_final_frames": false,
|
||||
"zero_data": false,
|
||||
"key": "0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
type State struct {
|
||||
Ok bool `json:"ok"`
|
||||
Result struct {
|
||||
InstanceID string `json:"instance_id"`
|
||||
Encoder struct {
|
||||
Type string `json:"type"`
|
||||
Quality int `json:"quality"`
|
||||
} `json:"encoder"`
|
||||
Source struct {
|
||||
Resolution struct {
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
} `json:"resolution"`
|
||||
Online bool `json:"online"`
|
||||
DesiredFPS int `json:"desired_fps"`
|
||||
CapturedFPS int `json:"captured_fps"`
|
||||
} `json:"source"`
|
||||
Stream struct {
|
||||
QueuedFPS int `json:"queued_fps"`
|
||||
Clients int `json:"clients"`
|
||||
ClientsStat map[string]struct {
|
||||
FPS int `json:"fps"`
|
||||
ExtraHeaders bool `json:"extra_headers"`
|
||||
AdvanceHeaders bool `json:"advance_headers"`
|
||||
DualFinalFrames bool `json:"dual_final_frames"`
|
||||
ZeroData bool `json:"zero_data"`
|
||||
Key string `json:"key"`
|
||||
}
|
||||
} `json:"stream"`
|
||||
} `json:"result"`
|
||||
}
|
||||
|
||||
func FormatHttpUrl() string {
|
||||
cfg := config.Get()
|
||||
return fmt.Sprintf("http://%s:%d", cfg.UStreamer.Host, cfg.UStreamer.Port)
|
||||
}
|
||||
|
||||
func GetState() (State, error) {
|
||||
url := FormatHttpUrl() + "/state"
|
||||
|
||||
rsp, err := http.Get(url)
|
||||
if err != nil {
|
||||
log.Errorf("Failed to get state: %v", err)
|
||||
return State{}, err
|
||||
}
|
||||
defer rsp.Body.Close()
|
||||
|
||||
if rsp.StatusCode != http.StatusOK {
|
||||
log.Errorf("Invalid status code: %d", rsp.StatusCode)
|
||||
return State{}, err
|
||||
}
|
||||
|
||||
var state State
|
||||
if err := json.NewDecoder(rsp.Body).Decode(&state); err != nil {
|
||||
log.Errorf("Failed to decode state: %v", err)
|
||||
return State{}, err
|
||||
}
|
||||
|
||||
return state, nil
|
||||
}
|
||||
|
||||
func MjpegHandler(c *gin.Context) {
|
||||
url := FormatHttpUrl() + "/stream"
|
||||
|
||||
rsp, err := http.Get(url)
|
||||
if err != nil {
|
||||
c.String(http.StatusInternalServerError, "Failed to get stream")
|
||||
log.Errorf("Failed to get stream: %v", err)
|
||||
return
|
||||
}
|
||||
defer rsp.Body.Close()
|
||||
|
||||
if rsp.StatusCode != http.StatusOK {
|
||||
c.String(rsp.StatusCode, "Invalid status code")
|
||||
return
|
||||
}
|
||||
|
||||
c.Header("Content-Type", rsp.Header.Get("Content-Type"))
|
||||
buf := make([]byte, 1024*1024)
|
||||
_, err = io.CopyBuffer(c.Writer, rsp.Body, buf)
|
||||
if err != nil {
|
||||
c.String(http.StatusInternalServerError, "Failed to passthrough stream")
|
||||
log.Errorf("Failed to passthrough stream: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func WebRTCHandshake(c *gin.Context) {
|
||||
str, err := c.GetRawData()
|
||||
if err != nil {
|
||||
c.String(http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
log.Debugf("Client session description: %s", string(str))
|
||||
|
||||
r := rtc.Get()
|
||||
localSession, err := r.Handshake(string(str))
|
||||
if err != nil {
|
||||
c.String(http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
c.String(http.StatusOK, localSession)
|
||||
}
|
||||
|
||||
func WebRTCSettings(c *gin.Context) {
|
||||
bitrateStr := c.Query("bitrate")
|
||||
fpsStr := c.Query("fps")
|
||||
|
||||
if fpsStr == "" && bitrateStr == "" {
|
||||
c.String(http.StatusBadGateway, "please specify bitrate or fps parameters")
|
||||
return
|
||||
}
|
||||
|
||||
ffmpeg := GetFFmpeg()
|
||||
|
||||
if len(bitrateStr) > 0 {
|
||||
bitrate, err := strconv.Atoi(bitrateStr)
|
||||
if err != nil {
|
||||
c.String(http.StatusBadRequest, "wrong bitrate value")
|
||||
return
|
||||
}
|
||||
ffmpeg.SetBitrate(bitrate)
|
||||
}
|
||||
|
||||
if len(fpsStr) > 0 {
|
||||
fps, err := strconv.Atoi(fpsStr)
|
||||
if err != nil {
|
||||
c.String(http.StatusBadRequest, "wrong fps value")
|
||||
return
|
||||
}
|
||||
ffmpeg.SetFPS(fps)
|
||||
}
|
||||
|
||||
ffmpeg.Stop()
|
||||
ffmpeg.Start()
|
||||
}
|
||||
Reference in New Issue
Block a user