mediamtx/internal/serverrtmp/server.go

107 lines
1.9 KiB
Go
Raw Normal View History

2021-01-31 15:58:57 +00:00
package serverrtmp
import (
"net"
"strconv"
"sync"
"sync/atomic"
2021-01-31 15:58:57 +00:00
2021-04-03 09:39:19 +00:00
nrtmp "github.com/notedit/rtmp/format/rtmp"
2021-01-31 15:58:57 +00:00
"github.com/aler9/rtsp-simple-server/internal/logger"
2021-04-03 09:39:19 +00:00
"github.com/aler9/rtsp-simple-server/internal/rtmp"
2021-01-31 15:58:57 +00:00
)
// Parent is implemented by program.
type Parent interface {
Log(logger.Level, string, ...interface{})
}
// Server is a RTMP listener.
type Server struct {
parent Parent
l net.Listener
2021-04-03 09:39:19 +00:00
srv *nrtmp.Server
closed uint32
wg sync.WaitGroup
2021-04-03 09:39:19 +00:00
accept chan *rtmp.Conn
2021-01-31 15:58:57 +00:00
}
// New allocates a Server.
func New(
listenIP string,
port int,
parent Parent) (*Server, error) {
address := listenIP + ":" + strconv.FormatInt(int64(port), 10)
l, err := net.Listen("tcp", address)
if err != nil {
return nil, err
}
s := &Server{
parent: parent,
l: l,
2021-04-03 09:39:19 +00:00
accept: make(chan *rtmp.Conn),
2021-01-31 15:58:57 +00:00
}
2021-04-03 09:39:19 +00:00
s.srv = nrtmp.NewServer()
2021-01-31 15:58:57 +00:00
s.srv.HandleConn = s.innerHandleConn
s.log(logger.Info, "opened on %s", address)
2021-01-31 15:58:57 +00:00
s.wg.Add(1)
go s.run()
return s, nil
}
func (s *Server) log(level logger.Level, format string, args ...interface{}) {
s.parent.Log(level, "[RTMP listener] "+format, append([]interface{}{}, args...)...)
}
2021-01-31 15:58:57 +00:00
// Close closes a Server.
func (s *Server) Close() {
go func() {
for co := range s.accept {
2021-03-10 14:06:45 +00:00
co.NetConn().Close()
}
}()
atomic.StoreUint32(&s.closed, 1)
2021-01-31 15:58:57 +00:00
s.l.Close()
s.wg.Wait()
close(s.accept)
2021-01-31 15:58:57 +00:00
}
func (s *Server) run() {
defer s.wg.Done()
for {
nconn, err := s.l.Accept()
if err != nil {
if atomic.LoadUint32(&s.closed) == 1 {
break
}
s.log(logger.Warn, "ERR: %s", err)
continue
2021-01-31 15:58:57 +00:00
}
s.wg.Add(1)
go func() {
defer s.wg.Done()
s.srv.HandleNetConn(nconn)
}()
}
}
2021-04-03 09:39:19 +00:00
func (s *Server) innerHandleConn(rconn *nrtmp.Conn, nconn net.Conn) {
s.accept <- rtmp.NewConn(rconn, nconn)
}
2021-01-31 15:58:57 +00:00
// Accept returns a channel to accept incoming connections.
2021-04-03 09:39:19 +00:00
func (s *Server) Accept() chan *rtmp.Conn {
return s.accept
2021-01-31 15:58:57 +00:00
}