2021-01-31 15:58:57 +00:00
|
|
|
package serverrtmp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"strconv"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/notedit/rtmp/format/rtmp"
|
|
|
|
|
|
|
|
"github.com/aler9/rtsp-simple-server/internal/logger"
|
2021-01-31 20:42:27 +00:00
|
|
|
"github.com/aler9/rtsp-simple-server/internal/rtmputils"
|
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 {
|
|
|
|
l net.Listener
|
|
|
|
srv *rtmp.Server
|
|
|
|
wg sync.WaitGroup
|
2021-01-31 20:42:27 +00:00
|
|
|
|
2021-03-10 14:06:45 +00:00
|
|
|
accept chan *rtmputils.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{
|
2021-01-31 20:42:27 +00:00
|
|
|
l: l,
|
2021-03-10 14:06:45 +00:00
|
|
|
accept: make(chan *rtmputils.Conn),
|
2021-01-31 15:58:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
s.srv = rtmp.NewServer()
|
|
|
|
s.srv.HandleConn = s.innerHandleConn
|
|
|
|
|
|
|
|
parent.Log(logger.Info, "[RTMP listener] opened on %s", address)
|
|
|
|
|
|
|
|
s.wg.Add(1)
|
|
|
|
go s.run()
|
|
|
|
|
|
|
|
return s, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close closes a Server.
|
|
|
|
func (s *Server) Close() {
|
2021-01-31 20:42:27 +00:00
|
|
|
go func() {
|
|
|
|
for co := range s.accept {
|
2021-03-10 14:06:45 +00:00
|
|
|
co.NetConn().Close()
|
2021-01-31 20:42:27 +00:00
|
|
|
}
|
|
|
|
}()
|
2021-01-31 15:58:57 +00:00
|
|
|
s.l.Close()
|
|
|
|
s.wg.Wait()
|
2021-01-31 20:42:27 +00:00
|
|
|
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 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
s.wg.Add(1)
|
|
|
|
go func() {
|
|
|
|
defer s.wg.Done()
|
|
|
|
s.srv.HandleNetConn(nconn)
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) innerHandleConn(rconn *rtmp.Conn, nconn net.Conn) {
|
2021-03-10 14:06:45 +00:00
|
|
|
s.accept <- rtmputils.NewConn(rconn, nconn)
|
2021-01-31 20:42:27 +00:00
|
|
|
}
|
2021-01-31 15:58:57 +00:00
|
|
|
|
2021-01-31 20:42:27 +00:00
|
|
|
// Accept returns a channel to accept incoming connections.
|
2021-03-10 14:06:45 +00:00
|
|
|
func (s *Server) Accept() chan *rtmputils.Conn {
|
2021-01-31 20:42:27 +00:00
|
|
|
return s.accept
|
2021-01-31 15:58:57 +00:00
|
|
|
}
|