Compare commits
1 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
73bd516c40 | 3 years ago |
232 changed files with 6366 additions and 12347 deletions
@ -1,139 +0,0 @@
@@ -1,139 +0,0 @@
|
||||
package api |
||||
|
||||
import ( |
||||
"errors" |
||||
"io/fs" |
||||
"path/filepath" |
||||
"sort" |
||||
"strings" |
||||
|
||||
"github.com/bluenviron/mediamtx/internal/conf" |
||||
"github.com/bluenviron/mediamtx/internal/defs" |
||||
"github.com/bluenviron/mediamtx/internal/playback" |
||||
"github.com/bluenviron/mediamtx/internal/record" |
||||
) |
||||
|
||||
var errFound = errors.New("found") |
||||
|
||||
func fixedPathHasRecordings(pathConf *conf.Path) bool { |
||||
recordPath := record.PathAddExtension( |
||||
strings.ReplaceAll(pathConf.RecordPath, "%path", pathConf.Name), |
||||
pathConf.RecordFormat, |
||||
) |
||||
|
||||
// we have to convert to absolute paths
|
||||
// otherwise, recordPath and fpath inside Walk() won't have common elements
|
||||
recordPath, _ = filepath.Abs(recordPath) |
||||
|
||||
commonPath := record.CommonPath(recordPath) |
||||
|
||||
err := filepath.Walk(commonPath, func(fpath string, info fs.FileInfo, err error) error { |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
if !info.IsDir() { |
||||
var pa record.Path |
||||
ok := pa.Decode(recordPath, fpath) |
||||
if ok { |
||||
return errFound |
||||
} |
||||
} |
||||
|
||||
return nil |
||||
}) |
||||
if err != nil && !errors.Is(err, errFound) { |
||||
return false |
||||
} |
||||
|
||||
return errors.Is(err, errFound) |
||||
} |
||||
|
||||
func regexpPathGetRecordings(pathConf *conf.Path) []string { |
||||
recordPath := record.PathAddExtension( |
||||
pathConf.RecordPath, |
||||
pathConf.RecordFormat, |
||||
) |
||||
|
||||
// we have to convert to absolute paths
|
||||
// otherwise, recordPath and fpath inside Walk() won't have common elements
|
||||
recordPath, _ = filepath.Abs(recordPath) |
||||
|
||||
commonPath := record.CommonPath(recordPath) |
||||
|
||||
var ret []string |
||||
|
||||
filepath.Walk(commonPath, func(fpath string, info fs.FileInfo, err error) error { //nolint:errcheck
|
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
if !info.IsDir() { |
||||
var pa record.Path |
||||
ok := pa.Decode(recordPath, fpath) |
||||
if ok && pathConf.Regexp.FindStringSubmatch(pa.Path) != nil { |
||||
ret = append(ret, pa.Path) |
||||
} |
||||
} |
||||
|
||||
return nil |
||||
}) |
||||
|
||||
return ret |
||||
} |
||||
|
||||
func removeDuplicatesAndSort(in []string) []string { |
||||
ma := make(map[string]struct{}, len(in)) |
||||
for _, i := range in { |
||||
ma[i] = struct{}{} |
||||
} |
||||
|
||||
out := []string{} |
||||
|
||||
for k := range ma { |
||||
out = append(out, k) |
||||
} |
||||
|
||||
sort.Strings(out) |
||||
|
||||
return out |
||||
} |
||||
|
||||
func getAllPathsWithRecordings(paths map[string]*conf.Path) []string { |
||||
pathNames := []string{} |
||||
|
||||
for _, pathConf := range paths { |
||||
if pathConf.Playback { |
||||
if pathConf.Regexp == nil { |
||||
if fixedPathHasRecordings(pathConf) { |
||||
pathNames = append(pathNames, pathConf.Name) |
||||
} |
||||
} else { |
||||
pathNames = append(pathNames, regexpPathGetRecordings(pathConf)...) |
||||
} |
||||
} |
||||
} |
||||
|
||||
return removeDuplicatesAndSort(pathNames) |
||||
} |
||||
|
||||
func recordingEntry( |
||||
pathConf *conf.Path, |
||||
pathName string, |
||||
) *defs.APIRecording { |
||||
ret := &defs.APIRecording{ |
||||
Name: pathName, |
||||
} |
||||
|
||||
segments, _ := playback.FindSegments(pathConf, pathName) |
||||
|
||||
ret.Segments = make([]*defs.APIRecordingSegment, len(segments)) |
||||
|
||||
for i, seg := range segments { |
||||
ret.Segments[i] = &defs.APIRecordingSegment{ |
||||
Start: seg.Start, |
||||
} |
||||
} |
||||
|
||||
return ret |
||||
} |
||||
@ -1,22 +0,0 @@
@@ -1,22 +0,0 @@
|
||||
package asyncwriter |
||||
|
||||
import ( |
||||
"fmt" |
||||
"testing" |
||||
|
||||
"github.com/stretchr/testify/require" |
||||
) |
||||
|
||||
func TestAsyncWriter(t *testing.T) { |
||||
w := New(512, nil) |
||||
|
||||
w.Start() |
||||
defer w.Stop() |
||||
|
||||
w.Push(func() error { |
||||
return fmt.Errorf("testerror") |
||||
}) |
||||
|
||||
err := <-w.Error() |
||||
require.EqualError(t, err, "testerror") |
||||
} |
||||
@ -1,327 +0,0 @@
@@ -1,327 +0,0 @@
|
||||
// Package auth contains the authentication system.
|
||||
package auth |
||||
|
||||
import ( |
||||
"bytes" |
||||
"encoding/json" |
||||
"fmt" |
||||
"io" |
||||
"net" |
||||
"net/http" |
||||
"net/url" |
||||
"regexp" |
||||
"strings" |
||||
"sync" |
||||
"time" |
||||
|
||||
"github.com/MicahParks/keyfunc/v3" |
||||
"github.com/bluenviron/gortsplib/v4/pkg/auth" |
||||
"github.com/bluenviron/gortsplib/v4/pkg/base" |
||||
"github.com/bluenviron/gortsplib/v4/pkg/headers" |
||||
"github.com/bluenviron/mediamtx/internal/conf" |
||||
"github.com/golang-jwt/jwt/v5" |
||||
"github.com/google/uuid" |
||||
) |
||||
|
||||
const ( |
||||
// PauseAfterError is the pause to apply after an authentication failure.
|
||||
PauseAfterError = 2 * time.Second |
||||
|
||||
rtspAuthRealm = "IPCAM" |
||||
jwtRefreshPeriod = 60 * 60 * time.Second |
||||
) |
||||
|
||||
// Protocol is a protocol.
|
||||
type Protocol string |
||||
|
||||
// protocols.
|
||||
const ( |
||||
ProtocolRTSP Protocol = "rtsp" |
||||
ProtocolRTMP Protocol = "rtmp" |
||||
ProtocolHLS Protocol = "hls" |
||||
ProtocolWebRTC Protocol = "webrtc" |
||||
ProtocolSRT Protocol = "srt" |
||||
) |
||||
|
||||
// Request is an authentication request.
|
||||
type Request struct { |
||||
User string |
||||
Pass string |
||||
IP net.IP |
||||
Action conf.AuthAction |
||||
|
||||
// only for ActionPublish, ActionRead, ActionPlayback
|
||||
Path string |
||||
Protocol Protocol |
||||
ID *uuid.UUID |
||||
Query string |
||||
RTSPRequest *base.Request |
||||
RTSPBaseURL *base.URL |
||||
RTSPNonce string |
||||
} |
||||
|
||||
// Error is a authentication error.
|
||||
type Error struct { |
||||
Message string |
||||
} |
||||
|
||||
// Error implements the error interface.
|
||||
func (e Error) Error() string { |
||||
return "authentication failed: " + e.Message |
||||
} |
||||
|
||||
func matchesPermission(perms []conf.AuthInternalUserPermission, req *Request) bool { |
||||
for _, perm := range perms { |
||||
if perm.Action == req.Action { |
||||
if perm.Action == conf.AuthActionPublish || |
||||
perm.Action == conf.AuthActionRead || |
||||
perm.Action == conf.AuthActionPlayback { |
||||
switch { |
||||
case perm.Path == "": |
||||
return true |
||||
|
||||
case strings.HasPrefix(perm.Path, "~"): |
||||
regexp, err := regexp.Compile(perm.Path[1:]) |
||||
if err == nil && regexp.MatchString(req.Path) { |
||||
return true |
||||
} |
||||
|
||||
case perm.Path == req.Path: |
||||
return true |
||||
} |
||||
} else { |
||||
return true |
||||
} |
||||
} |
||||
} |
||||
|
||||
return false |
||||
} |
||||
|
||||
type customClaims struct { |
||||
jwt.RegisteredClaims |
||||
MediaMTXPermissions []conf.AuthInternalUserPermission `json:"mediamtx_permissions"` |
||||
} |
||||
|
||||
// Manager is the authentication manager.
|
||||
type Manager struct { |
||||
Method conf.AuthMethod |
||||
InternalUsers []conf.AuthInternalUser |
||||
HTTPAddress string |
||||
HTTPExclude []conf.AuthInternalUserPermission |
||||
JWTJWKS string |
||||
ReadTimeout time.Duration |
||||
RTSPAuthMethods []headers.AuthMethod |
||||
|
||||
mutex sync.RWMutex |
||||
jwtHTTPClient *http.Client |
||||
jwtLastRefresh time.Time |
||||
jwtKeyFunc keyfunc.Keyfunc |
||||
} |
||||
|
||||
// ReloadInternalUsers reloads InternalUsers.
|
||||
func (m *Manager) ReloadInternalUsers(u []conf.AuthInternalUser) { |
||||
m.mutex.Lock() |
||||
defer m.mutex.Unlock() |
||||
m.InternalUsers = u |
||||
} |
||||
|
||||
// Authenticate authenticates a request.
|
||||
func (m *Manager) Authenticate(req *Request) error { |
||||
err := m.authenticateInner(req) |
||||
if err != nil { |
||||
return Error{Message: err.Error()} |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
func (m *Manager) authenticateInner(req *Request) error { |
||||
// if this is a RTSP request, fill username and password
|
||||
var rtspAuthHeader headers.Authorization |
||||
if req.RTSPRequest != nil { |
||||
err := rtspAuthHeader.Unmarshal(req.RTSPRequest.Header["Authorization"]) |
||||
if err == nil { |
||||
switch rtspAuthHeader.Method { |
||||
case headers.AuthBasic: |
||||
req.User = rtspAuthHeader.BasicUser |
||||
req.Pass = rtspAuthHeader.BasicPass |
||||
|
||||
case headers.AuthDigestMD5: |
||||
req.User = rtspAuthHeader.Username |
||||
|
||||
default: |
||||
return fmt.Errorf("unsupported RTSP authentication method") |
||||
} |
||||
} |
||||
} |
||||
|
||||
switch m.Method { |
||||
case conf.AuthMethodInternal: |
||||
return m.authenticateInternal(req, &rtspAuthHeader) |
||||
|
||||
case conf.AuthMethodHTTP: |
||||
return m.authenticateHTTP(req) |
||||
|
||||
default: |
||||
return m.authenticateJWT(req) |
||||
} |
||||
} |
||||
|
||||
func (m *Manager) authenticateInternal(req *Request, rtspAuthHeader *headers.Authorization) error { |
||||
m.mutex.RLock() |
||||
defer m.mutex.RUnlock() |
||||
|
||||
for _, u := range m.InternalUsers { |
||||
if err := m.authenticateWithUser(req, rtspAuthHeader, &u); err == nil { |
||||
return nil |
||||
} |
||||
} |
||||
|
||||
return fmt.Errorf("authentication failed") |
||||
} |
||||
|
||||
func (m *Manager) authenticateWithUser( |
||||
req *Request, |
||||
rtspAuthHeader *headers.Authorization, |
||||
u *conf.AuthInternalUser, |
||||
) error { |
||||
if u.User != "any" && !u.User.Check(req.User) { |
||||
return fmt.Errorf("wrong user") |
||||
} |
||||
|
||||
if len(u.IPs) != 0 && !u.IPs.Contains(req.IP) { |
||||
return fmt.Errorf("IP not allowed") |
||||
} |
||||
|
||||
if !matchesPermission(u.Permissions, req) { |
||||
return fmt.Errorf("user doesn't have permission to perform action") |
||||
} |
||||
|
||||
if u.User != "any" { |
||||
if req.RTSPRequest != nil && rtspAuthHeader.Method == headers.AuthDigestMD5 { |
||||
err := auth.Validate( |
||||
req.RTSPRequest, |
||||
string(u.User), |
||||
string(u.Pass), |
||||
req.RTSPBaseURL, |
||||
m.RTSPAuthMethods, |
||||
rtspAuthRealm, |
||||
req.RTSPNonce) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
} else if !u.Pass.Check(req.Pass) { |
||||
return fmt.Errorf("invalid credentials") |
||||
} |
||||
} |
||||
|
||||
return nil |
||||
} |
||||
|
||||
func (m *Manager) authenticateHTTP(req *Request) error { |
||||
if matchesPermission(m.HTTPExclude, req) { |
||||
return nil |
||||
} |
||||
|
||||
enc, _ := json.Marshal(struct { |
||||
IP string `json:"ip"` |
||||
User string `json:"user"` |
||||
Password string `json:"password"` |
||||
Action string `json:"action"` |
||||
Path string `json:"path"` |
||||
Protocol string `json:"protocol"` |
||||
ID *uuid.UUID `json:"id"` |
||||
Query string `json:"query"` |
||||
}{ |
||||
IP: req.IP.String(), |
||||
User: req.User, |
||||
Password: req.Pass, |
||||
Action: string(req.Action), |
||||
Path: req.Path, |
||||
Protocol: string(req.Protocol), |
||||
ID: req.ID, |
||||
Query: req.Query, |
||||
}) |
||||
|
||||
res, err := http.Post(m.HTTPAddress, "application/json", bytes.NewReader(enc)) |
||||
if err != nil { |
||||
return fmt.Errorf("HTTP request failed: %w", err) |
||||
} |
||||
defer res.Body.Close() |
||||
|
||||
if res.StatusCode < 200 || res.StatusCode > 299 { |
||||
if resBody, err := io.ReadAll(res.Body); err == nil && len(resBody) != 0 { |
||||
return fmt.Errorf("server replied with code %d: %s", res.StatusCode, string(resBody)) |
||||
} |
||||
|
||||
return fmt.Errorf("server replied with code %d", res.StatusCode) |
||||
} |
||||
|
||||
return nil |
||||
} |
||||
|
||||
func (m *Manager) authenticateJWT(req *Request) error { |
||||
keyfunc, err := m.pullJWTJWKS() |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
v, err := url.ParseQuery(req.Query) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
if len(v["jwt"]) != 1 { |
||||
return fmt.Errorf("JWT not provided") |
||||
} |
||||
|
||||
var customClaims customClaims |
||||
_, err = jwt.ParseWithClaims(v["jwt"][0], &customClaims, keyfunc) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
if !matchesPermission(customClaims.MediaMTXPermissions, req) { |
||||
return fmt.Errorf("user doesn't have permission to perform action") |
||||
} |
||||
|
||||
return nil |
||||
} |
||||
|
||||
func (m *Manager) pullJWTJWKS() (jwt.Keyfunc, error) { |
||||
now := time.Now() |
||||
|
||||
m.mutex.Lock() |
||||
defer m.mutex.Unlock() |
||||
|
||||
if now.Sub(m.jwtLastRefresh) >= jwtRefreshPeriod { |
||||
if m.jwtHTTPClient == nil { |
||||
m.jwtHTTPClient = &http.Client{ |
||||
Timeout: (m.ReadTimeout), |
||||
Transport: &http.Transport{}, |
||||
} |
||||
} |
||||
|
||||
res, err := m.jwtHTTPClient.Get(m.JWTJWKS) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
defer res.Body.Close() |
||||
|
||||
var raw json.RawMessage |
||||
err = json.NewDecoder(res.Body).Decode(&raw) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
tmp, err := keyfunc.NewJWKSetJSON(raw) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
m.jwtKeyFunc = tmp |
||||
m.jwtLastRefresh = now |
||||
} |
||||
|
||||
return m.jwtKeyFunc.Keyfunc, nil |
||||
} |
||||
@ -1,309 +0,0 @@
@@ -1,309 +0,0 @@
|
||||
package auth |
||||
|
||||
import ( |
||||
"context" |
||||
"encoding/json" |
||||
"net" |
||||
"net/http" |
||||
"testing" |
||||
|
||||
"github.com/bluenviron/gortsplib/v4/pkg/auth" |
||||
"github.com/bluenviron/gortsplib/v4/pkg/base" |
||||
"github.com/bluenviron/gortsplib/v4/pkg/headers" |
||||
"github.com/bluenviron/mediamtx/internal/conf" |
||||
"github.com/stretchr/testify/require" |
||||
) |
||||
|
||||
func mustParseCIDR(v string) net.IPNet { |
||||
_, ne, err := net.ParseCIDR(v) |
||||
if err != nil { |
||||
panic(err) |
||||
} |
||||
if ipv4 := ne.IP.To4(); ipv4 != nil { |
||||
return net.IPNet{IP: ipv4, Mask: ne.Mask[len(ne.Mask)-4 : len(ne.Mask)]} |
||||
} |
||||
return *ne |
||||
} |
||||
|
||||
type testHTTPAuthenticator struct { |
||||
*http.Server |
||||
} |
||||
|
||||
func (ts *testHTTPAuthenticator) initialize(t *testing.T, protocol string, action string) { |
||||
firstReceived := false |
||||
|
||||
ts.Server = &http.Server{ |
||||
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
||||
require.Equal(t, http.MethodPost, r.Method) |
||||
require.Equal(t, "/auth", r.URL.Path) |
||||
|
||||
var in struct { |
||||
IP string `json:"ip"` |
||||
User string `json:"user"` |
||||
Password string `json:"password"` |
||||
Path string `json:"path"` |
||||
Protocol string `json:"protocol"` |
||||
ID string `json:"id"` |
||||
Action string `json:"action"` |
||||
Query string `json:"query"` |
||||
} |
||||
err := json.NewDecoder(r.Body).Decode(&in) |
||||
require.NoError(t, err) |
||||
|
||||
var user string |
||||
if action == "publish" { |
||||
user = "testpublisher" |
||||
} else { |
||||
user = "testreader" |
||||
} |
||||
|
||||
if in.IP != "127.0.0.1" || |
||||
in.User != user || |
||||
in.Password != "testpass" || |
||||
in.Path != "teststream" || |
||||
in.Protocol != protocol || |
||||
(firstReceived && in.ID == "") || |
||||
in.Action != action || |
||||
(in.Query != "user=testreader&pass=testpass¶m=value" && |
||||
in.Query != "user=testpublisher&pass=testpass¶m=value" && |
||||
in.Query != "param=value") { |
||||
w.WriteHeader(http.StatusBadRequest) |
||||
return |
||||
} |
||||
|
||||
firstReceived = true |
||||
}), |
||||
} |
||||
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:9120") |
||||
require.NoError(t, err) |
||||
|
||||
go ts.Server.Serve(ln) |
||||
} |
||||
|
||||
func (ts *testHTTPAuthenticator) close() { |
||||
ts.Server.Shutdown(context.Background()) |
||||
} |
||||
|
||||
func TestAuthInternal(t *testing.T) { |
||||
for _, outcome := range []string{ |
||||
"ok", |
||||
"wrong user", |
||||
"wrong pass", |
||||
"wrong ip", |
||||
"wrong action", |
||||
"wrong path", |
||||
} { |
||||
for _, encryption := range []string{ |
||||
"plain", |
||||
"sha256", |
||||
"argon2", |
||||
} { |
||||
t.Run(outcome+" "+encryption, func(t *testing.T) { |
||||
m := Manager{ |
||||
Method: conf.AuthMethodInternal, |
||||
InternalUsers: []conf.AuthInternalUser{ |
||||
{ |
||||
IPs: conf.IPNetworks{mustParseCIDR("127.1.1.1/32")}, |
||||
Permissions: []conf.AuthInternalUserPermission{ |
||||
{ |
||||
Action: conf.AuthActionPublish, |
||||
Path: "mypath", |
||||
}, |
||||
}, |
||||
}, |
||||
}, |
||||
HTTPAddress: "", |
||||
RTSPAuthMethods: nil, |
||||
} |
||||
|
||||
switch encryption { |
||||
case "plain": |
||||
m.InternalUsers[0].User = conf.Credential("testuser") |
||||
m.InternalUsers[0].Pass = conf.Credential("testpass") |
||||
|
||||
case "sha256": |
||||
m.InternalUsers[0].User = conf.Credential("sha256:rl3rgi4NcZkpAEcacZnQ2VuOfJ0FxAqCRaKB/SwdZoQ=") |
||||
m.InternalUsers[0].Pass = conf.Credential("sha256:E9JJ8stBJ7QM+nV4ZoUCeHk/gU3tPFh/5YieiJp6n2w=") |
||||
|
||||
case "argon2": |
||||
m.InternalUsers[0].User = conf.Credential( |
||||
"argon2:$argon2id$v=19$m=4096,t=3,p=1$MTIzNDU2Nzg$Ux/LWeTgJQPyfMMJo1myR64+o8rALHoPmlE1i/TR+58") |
||||
m.InternalUsers[0].Pass = conf.Credential( |
||||
"argon2:$argon2i$v=19$m=4096,t=3,p=1$MTIzNDU2Nzg$/mrZ42TiTv1mcPnpMUera5oi0SFYbbyueAbdx5sUvWo") |
||||
} |
||||
|
||||
switch outcome { |
||||
case "ok": |
||||
err := m.Authenticate(&Request{ |
||||
User: "testuser", |
||||
Pass: "testpass", |
||||
IP: net.ParseIP("127.1.1.1"), |
||||
Action: conf.AuthActionPublish, |
||||
Path: "mypath", |
||||
}) |
||||
require.NoError(t, err) |
||||
|
||||
case "wrong user": |
||||
err := m.Authenticate(&Request{ |
||||
User: "wrong", |
||||
Pass: "testpass", |
||||
IP: net.ParseIP("127.1.1.1"), |
||||
Action: conf.AuthActionPublish, |
||||
Path: "mypath", |
||||
}) |
||||
require.Error(t, err) |
||||
|
||||
case "wrong pass": |
||||
err := m.Authenticate(&Request{ |
||||
User: "testuser", |
||||
Pass: "wrong", |
||||
IP: net.ParseIP("127.1.1.1"), |
||||
Action: conf.AuthActionPublish, |
||||
Path: "mypath", |
||||
}) |
||||
require.Error(t, err) |
||||
|
||||
case "wrong ip": |
||||
err := m.Authenticate(&Request{ |
||||
User: "testuser", |
||||
Pass: "testpass", |
||||
IP: net.ParseIP("127.1.1.2"), |
||||
Action: conf.AuthActionPublish, |
||||
Path: "mypath", |
||||
}) |
||||
require.Error(t, err) |
||||
|
||||
case "wrong action": |
||||
err := m.Authenticate(&Request{ |
||||
User: "testuser", |
||||
Pass: "testpass", |
||||
IP: net.ParseIP("127.1.1.1"), |
||||
Action: conf.AuthActionRead, |
||||
Path: "mypath", |
||||
}) |
||||
require.Error(t, err) |
||||
|
||||
case "wrong path": |
||||
err := m.Authenticate(&Request{ |
||||
User: "testuser", |
||||
Pass: "testpass", |
||||
IP: net.ParseIP("127.1.1.1"), |
||||
Action: conf.AuthActionPublish, |
||||
Path: "wrong", |
||||
}) |
||||
require.Error(t, err) |
||||
} |
||||
}) |
||||
} |
||||
} |
||||
} |
||||
|
||||
func TestAuthInternalRTSPDigest(t *testing.T) { |
||||
m := Manager{ |
||||
Method: conf.AuthMethodInternal, |
||||
InternalUsers: []conf.AuthInternalUser{ |
||||
{ |
||||
User: "myuser", |
||||
Pass: "mypass", |
||||
IPs: conf.IPNetworks{mustParseCIDR("127.1.1.1/32")}, |
||||
Permissions: []conf.AuthInternalUserPermission{ |
||||
{ |
||||
Action: conf.AuthActionPublish, |
||||
Path: "mypath", |
||||
}, |
||||
}, |
||||
}, |
||||
}, |
||||
HTTPAddress: "", |
||||
RTSPAuthMethods: []headers.AuthMethod{headers.AuthDigestMD5}, |
||||
} |
||||
|
||||
u, err := base.ParseURL("rtsp://127.0.0.1:8554/mypath") |
||||
require.NoError(t, err) |
||||
|
||||
s, err := auth.NewSender( |
||||
auth.GenerateWWWAuthenticate([]headers.AuthMethod{headers.AuthDigestMD5}, "IPCAM", "mynonce"), |
||||
"myuser", |
||||
"mypass", |
||||
) |
||||
require.NoError(t, err) |
||||
|
||||
req := &base.Request{ |
||||
Method: "ANNOUNCE", |
||||
URL: u, |
||||
} |
||||
|
||||
s.AddAuthorization(req) |
||||
|
||||
err = m.Authenticate(&Request{ |
||||
IP: net.ParseIP("127.1.1.1"), |
||||
Action: conf.AuthActionPublish, |
||||
Path: "mypath", |
||||
RTSPRequest: req, |
||||
RTSPNonce: "mynonce", |
||||
}) |
||||
require.NoError(t, err) |
||||
} |
||||
|
||||
func TestAuthHTTP(t *testing.T) { |
||||
for _, outcome := range []string{"ok", "fail"} { |
||||
t.Run(outcome, func(t *testing.T) { |
||||
m := Manager{ |
||||
Method: conf.AuthMethodHTTP, |
||||
HTTPAddress: "http://127.0.0.1:9120/auth", |
||||
RTSPAuthMethods: nil, |
||||
} |
||||
|
||||
au := &testHTTPAuthenticator{} |
||||
au.initialize(t, "rtsp", "publish") |
||||
defer au.close() |
||||
|
||||
if outcome == "ok" { |
||||
err := m.Authenticate(&Request{ |
||||
User: "testpublisher", |
||||
Pass: "testpass", |
||||
IP: net.ParseIP("127.0.0.1"), |
||||
Action: conf.AuthActionPublish, |
||||
Path: "teststream", |
||||
Protocol: ProtocolRTSP, |
||||
Query: "param=value", |
||||
}) |
||||
require.NoError(t, err) |
||||
} else { |
||||
err := m.Authenticate(&Request{ |
||||
User: "invalid", |
||||
Pass: "testpass", |
||||
IP: net.ParseIP("127.0.0.1"), |
||||
Action: conf.AuthActionPublish, |
||||
Path: "teststream", |
||||
Protocol: ProtocolRTSP, |
||||
Query: "param=value", |
||||
}) |
||||
require.Error(t, err) |
||||
} |
||||
}) |
||||
} |
||||
} |
||||
|
||||
func TestAuthHTTPExclude(t *testing.T) { |
||||
m := Manager{ |
||||
Method: conf.AuthMethodHTTP, |
||||
HTTPAddress: "http://not-to-be-used:9120/auth", |
||||
HTTPExclude: []conf.AuthInternalUserPermission{{ |
||||
Action: conf.AuthActionPublish, |
||||
}}, |
||||
RTSPAuthMethods: nil, |
||||
} |
||||
|
||||
err := m.Authenticate(&Request{ |
||||
User: "", |
||||
Pass: "", |
||||
IP: net.ParseIP("127.0.0.1"), |
||||
Action: conf.AuthActionPublish, |
||||
Path: "teststream", |
||||
Protocol: ProtocolRTSP, |
||||
Query: "param=value", |
||||
}) |
||||
require.NoError(t, err) |
||||
} |
||||
@ -1,52 +0,0 @@
@@ -1,52 +0,0 @@
|
||||
package conf |
||||
|
||||
import ( |
||||
"encoding/json" |
||||
"fmt" |
||||
) |
||||
|
||||
// AuthAction is an authentication action.
|
||||
type AuthAction string |
||||
|
||||
// auth actions
|
||||
const ( |
||||
AuthActionPublish AuthAction = "publish" |
||||
AuthActionRead AuthAction = "read" |
||||
AuthActionPlayback AuthAction = "playback" |
||||
AuthActionAPI AuthAction = "api" |
||||
AuthActionMetrics AuthAction = "metrics" |
||||
AuthActionPprof AuthAction = "pprof" |
||||
) |
||||
|
||||
// MarshalJSON implements json.Marshaler.
|
||||
func (d AuthAction) MarshalJSON() ([]byte, error) { |
||||
return json.Marshal(string(d)) |
||||
} |
||||
|
||||
// UnmarshalJSON implements json.Unmarshaler.
|
||||
func (d *AuthAction) UnmarshalJSON(b []byte) error { |
||||
var in string |
||||
if err := json.Unmarshal(b, &in); err != nil { |
||||
return err |
||||
} |
||||
|
||||
switch in { |
||||
case string(AuthActionPublish), |
||||
string(AuthActionRead), |
||||
string(AuthActionPlayback), |
||||
string(AuthActionAPI), |
||||
string(AuthActionMetrics), |
||||
string(AuthActionPprof): |
||||
*d = AuthAction(in) |
||||
|
||||
default: |
||||
return fmt.Errorf("invalid auth action: '%s'", in) |
||||
} |
||||
|
||||
return nil |
||||
} |
||||
|
||||
// UnmarshalEnv implements env.Unmarshaler.
|
||||
func (d *AuthAction) UnmarshalEnv(_ string, v string) error { |
||||
return d.UnmarshalJSON([]byte(`"` + v + `"`)) |
||||
} |
||||
@ -1,15 +0,0 @@
@@ -1,15 +0,0 @@
|
||||
package conf |
||||
|
||||
// AuthInternalUserPermission is a permission of a user.
|
||||
type AuthInternalUserPermission struct { |
||||
Action AuthAction `json:"action"` |
||||
Path string `json:"path"` |
||||
} |
||||
|
||||
// AuthInternalUser is an user.
|
||||
type AuthInternalUser struct { |
||||
User Credential `json:"user"` |
||||
Pass Credential `json:"pass"` |
||||
IPs IPNetworks `json:"ips"` |
||||
Permissions []AuthInternalUserPermission `json:"permissions"` |
||||
} |
||||
@ -1,84 +0,0 @@
@@ -1,84 +0,0 @@
|
||||
package conf |
||||
|
||||
import ( |
||||
"encoding/json" |
||||
"fmt" |
||||
"net" |
||||
"sort" |
||||
"strings" |
||||
) |
||||
|
||||
// IPNetworks is a parameter that contains a list of IP networks.
|
||||
type IPNetworks []net.IPNet |
||||
|
||||
// MarshalJSON implements json.Marshaler.
|
||||
func (d IPNetworks) MarshalJSON() ([]byte, error) { |
||||
out := make([]string, len(d)) |
||||
|
||||
for i, v := range d { |
||||
out[i] = v.String() |
||||
} |
||||
|
||||
sort.Strings(out) |
||||
|
||||
return json.Marshal(out) |
||||
} |
||||
|
||||
// UnmarshalJSON implements json.Unmarshaler.
|
||||
func (d *IPNetworks) UnmarshalJSON(b []byte) error { |
||||
var in []string |
||||
if err := json.Unmarshal(b, &in); err != nil { |
||||
return err |
||||
} |
||||
|
||||
*d = nil |
||||
|
||||
if len(in) == 0 { |
||||
return nil |
||||
} |
||||
|
||||
for _, t := range in { |
||||
if _, ipnet, err := net.ParseCIDR(t); err == nil { |
||||
if ipv4 := ipnet.IP.To4(); ipv4 != nil { |
||||
*d = append(*d, net.IPNet{IP: ipv4, Mask: ipnet.Mask[len(ipnet.Mask)-4 : len(ipnet.Mask)]}) |
||||
} else { |
||||
*d = append(*d, *ipnet) |
||||
} |
||||
} else if ip := net.ParseIP(t); ip != nil { |
||||
if ipv4 := ip.To4(); ipv4 != nil { |
||||
*d = append(*d, net.IPNet{IP: ipv4, Mask: net.CIDRMask(32, 32)}) |
||||
} else { |
||||
*d = append(*d, net.IPNet{IP: ip, Mask: net.CIDRMask(128, 128)}) |
||||
} |
||||
} else { |
||||
return fmt.Errorf("unable to parse IP/CIDR '%s'", t) |
||||
} |
||||
} |
||||
|
||||
return nil |
||||
} |
||||
|
||||
// UnmarshalEnv implements env.Unmarshaler.
|
||||
func (d *IPNetworks) UnmarshalEnv(_ string, v string) error { |
||||
byts, _ := json.Marshal(strings.Split(v, ",")) |
||||
return d.UnmarshalJSON(byts) |
||||
} |
||||
|
||||
// ToTrustedProxies converts IPNetworks into a string slice for SetTrustedProxies.
|
||||
func (d *IPNetworks) ToTrustedProxies() []string { |
||||
ret := make([]string, len(*d)) |
||||
for i, entry := range *d { |
||||
ret[i] = entry.String() |
||||
} |
||||
return ret |
||||
} |
||||
|
||||
// Contains checks whether the IP is part of one of the networks.
|
||||
func (d IPNetworks) Contains(ip net.IP) bool { |
||||
for _, network := range d { |
||||
if network.Contains(ip) { |
||||
return true |
||||
} |
||||
} |
||||
return false |
||||
} |
||||
@ -0,0 +1,66 @@
@@ -0,0 +1,66 @@
|
||||
package conf |
||||
|
||||
import ( |
||||
"encoding/json" |
||||
"fmt" |
||||
"net" |
||||
"sort" |
||||
"strings" |
||||
) |
||||
|
||||
// IPsOrCIDRs is a parameter that contains a list of IPs or CIDRs.
|
||||
type IPsOrCIDRs []fmt.Stringer |
||||
|
||||
// MarshalJSON implements json.Marshaler.
|
||||
func (d IPsOrCIDRs) MarshalJSON() ([]byte, error) { |
||||
out := make([]string, len(d)) |
||||
|
||||
for i, v := range d { |
||||
out[i] = v.String() |
||||
} |
||||
|
||||
sort.Strings(out) |
||||
|
||||
return json.Marshal(out) |
||||
} |
||||
|
||||
// UnmarshalJSON implements json.Unmarshaler.
|
||||
func (d *IPsOrCIDRs) UnmarshalJSON(b []byte) error { |
||||
var in []string |
||||
if err := json.Unmarshal(b, &in); err != nil { |
||||
return err |
||||
} |
||||
|
||||
*d = nil |
||||
|
||||
if len(in) == 0 { |
||||
return nil |
||||
} |
||||
|
||||
for _, t := range in { |
||||
if _, ipnet, err := net.ParseCIDR(t); err == nil { |
||||
*d = append(*d, ipnet) |
||||
} else if ip := net.ParseIP(t); ip != nil { |
||||
*d = append(*d, ip) |
||||
} else { |
||||
return fmt.Errorf("unable to parse IP/CIDR '%s'", t) |
||||
} |
||||
} |
||||
|
||||
return nil |
||||
} |
||||
|
||||
// UnmarshalEnv implements env.Unmarshaler.
|
||||
func (d *IPsOrCIDRs) UnmarshalEnv(_ string, v string) error { |
||||
byts, _ := json.Marshal(strings.Split(v, ",")) |
||||
return d.UnmarshalJSON(byts) |
||||
} |
||||
|
||||
// ToTrustedProxies converts IPsOrCIDRs into a string slice for SetTrustedProxies.
|
||||
func (d *IPsOrCIDRs) ToTrustedProxies() []string { |
||||
ret := make([]string, len(*d)) |
||||
for i, entry := range *d { |
||||
ret[i] = entry.String() |
||||
} |
||||
return ret |
||||
} |
||||
@ -1,63 +0,0 @@
@@ -1,63 +0,0 @@
|
||||
package conf |
||||
|
||||
import ( |
||||
"encoding/json" |
||||
"fmt" |
||||
"sort" |
||||
"strings" |
||||
|
||||
"github.com/bluenviron/gortsplib/v4/pkg/headers" |
||||
) |
||||
|
||||
// RTSPAuthMethods is the rtspAuthMethods parameter.
|
||||
type RTSPAuthMethods []headers.AuthMethod |
||||
|
||||
// MarshalJSON implements json.Marshaler.
|
||||
func (d RTSPAuthMethods) MarshalJSON() ([]byte, error) { |
||||
out := make([]string, len(d)) |
||||
|
||||
for i, v := range d { |
||||
switch v { |
||||
case headers.AuthBasic: |
||||
out[i] = "basic" |
||||
|
||||
default: |
||||
out[i] = "digest" |
||||
} |
||||
} |
||||
|
||||
sort.Strings(out) |
||||
|
||||
return json.Marshal(out) |
||||
} |
||||
|
||||
// UnmarshalJSON implements json.Unmarshaler.
|
||||
func (d *RTSPAuthMethods) UnmarshalJSON(b []byte) error { |
||||
var in []string |
||||
if err := json.Unmarshal(b, &in); err != nil { |
||||
return err |
||||
} |
||||
|
||||
*d = nil |
||||
|
||||
for _, v := range in { |
||||
switch v { |
||||
case "basic": |
||||
*d = append(*d, headers.AuthBasic) |
||||
|
||||
case "digest": |
||||
*d = append(*d, headers.AuthDigestMD5) |
||||
|
||||
default: |
||||
return fmt.Errorf("invalid authentication method: '%s'", v) |
||||
} |
||||
} |
||||
|
||||
return nil |
||||
} |
||||
|
||||
// UnmarshalEnv implements env.Unmarshaler.
|
||||
func (d *RTSPAuthMethods) UnmarshalEnv(_ string, v string) error { |
||||
byts, _ := json.Marshal(strings.Split(v, ",")) |
||||
return d.UnmarshalJSON(byts) |
||||
} |
||||
@ -0,0 +1,126 @@
@@ -0,0 +1,126 @@
|
||||
package core |
||||
|
||||
import ( |
||||
"bytes" |
||||
"encoding/json" |
||||
"fmt" |
||||
"io" |
||||
"net/http" |
||||
|
||||
"github.com/bluenviron/gortsplib/v4/pkg/auth" |
||||
"github.com/bluenviron/gortsplib/v4/pkg/headers" |
||||
"github.com/google/uuid" |
||||
|
||||
"github.com/bluenviron/mediamtx/internal/conf" |
||||
"github.com/bluenviron/mediamtx/internal/defs" |
||||
) |
||||
|
||||
func doExternalAuthentication( |
||||
ur string, |
||||
accessRequest defs.PathAccessRequest, |
||||
) error { |
||||
enc, _ := json.Marshal(struct { |
||||
IP string `json:"ip"` |
||||
User string `json:"user"` |
||||
Password string `json:"password"` |
||||
Path string `json:"path"` |
||||
Protocol string `json:"protocol"` |
||||
ID *uuid.UUID `json:"id"` |
||||
Action string `json:"action"` |
||||
Query string `json:"query"` |
||||
}{ |
||||
IP: accessRequest.IP.String(), |
||||
User: accessRequest.User, |
||||
Password: accessRequest.Pass, |
||||
Path: accessRequest.Name, |
||||
Protocol: string(accessRequest.Proto), |
||||
ID: accessRequest.ID, |
||||
Action: func() string { |
||||
if accessRequest.Publish { |
||||
return "publish" |
||||
} |
||||
return "read" |
||||
}(), |
||||
Query: accessRequest.Query, |
||||
}) |
||||
res, err := http.Post(ur, "application/json", bytes.NewReader(enc)) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
defer res.Body.Close() |
||||
|
||||
if res.StatusCode < 200 || res.StatusCode > 299 { |
||||
if resBody, err := io.ReadAll(res.Body); err == nil && len(resBody) != 0 { |
||||
return fmt.Errorf("server replied with code %d: %s", res.StatusCode, string(resBody)) |
||||
} |
||||
return fmt.Errorf("server replied with code %d", res.StatusCode) |
||||
} |
||||
|
||||
return nil |
||||
} |
||||
|
||||
func doAuthentication( |
||||
externalAuthenticationURL string, |
||||
rtspAuthMethods conf.AuthMethods, |
||||
pathConf *conf.Path, |
||||
accessRequest defs.PathAccessRequest, |
||||
) error { |
||||
var rtspAuth headers.Authorization |
||||
if accessRequest.RTSPRequest != nil { |
||||
err := rtspAuth.Unmarshal(accessRequest.RTSPRequest.Header["Authorization"]) |
||||
if err == nil && rtspAuth.Method == headers.AuthBasic { |
||||
accessRequest.User = rtspAuth.BasicUser |
||||
accessRequest.Pass = rtspAuth.BasicPass |
||||
} |
||||
} |
||||
|
||||
if externalAuthenticationURL != "" { |
||||
err := doExternalAuthentication( |
||||
externalAuthenticationURL, |
||||
accessRequest, |
||||
) |
||||
if err != nil { |
||||
return defs.AuthenticationError{Message: fmt.Sprintf("external authentication failed: %s", err)} |
||||
} |
||||
} |
||||
|
||||
var pathIPs conf.IPsOrCIDRs |
||||
var pathUser conf.Credential |
||||
var pathPass conf.Credential |
||||
|
||||
if accessRequest.Publish { |
||||
pathIPs = pathConf.PublishIPs |
||||
pathUser = pathConf.PublishUser |
||||
pathPass = pathConf.PublishPass |
||||
} else { |
||||
pathIPs = pathConf.ReadIPs |
||||
pathUser = pathConf.ReadUser |
||||
pathPass = pathConf.ReadPass |
||||
} |
||||
|
||||
if pathIPs != nil { |
||||
if !ipEqualOrInRange(accessRequest.IP, pathIPs) { |
||||
return defs.AuthenticationError{Message: fmt.Sprintf("IP %s not allowed", accessRequest.IP)} |
||||
} |
||||
} |
||||
|
||||
if !pathUser.IsEmpty() { |
||||
if accessRequest.RTSPRequest != nil && rtspAuth.Method == headers.AuthDigest { |
||||
err := auth.Validate( |
||||
accessRequest.RTSPRequest, |
||||
pathUser.GetValue(), |
||||
pathPass.GetValue(), |
||||
accessRequest.RTSPBaseURL, |
||||
rtspAuthMethods, |
||||
"IPCAM", |
||||
accessRequest.RTSPNonce) |
||||
if err != nil { |
||||
return defs.AuthenticationError{Message: err.Error()} |
||||
} |
||||
} else if !pathUser.Check(accessRequest.User) || !pathPass.Check(accessRequest.Pass) { |
||||
return defs.AuthenticationError{Message: "invalid credentials"} |
||||
} |
||||
} |
||||
|
||||
return nil |
||||
} |
||||
@ -0,0 +1,222 @@
@@ -0,0 +1,222 @@
|
||||
package core |
||||
|
||||
import ( |
||||
"context" |
||||
"encoding/json" |
||||
"io" |
||||
"net" |
||||
"net/http" |
||||
"testing" |
||||
"time" |
||||
|
||||
"github.com/bluenviron/gortsplib/v4" |
||||
"github.com/bluenviron/gortsplib/v4/pkg/description" |
||||
"github.com/bluenviron/gortsplib/v4/pkg/format" |
||||
"github.com/pion/rtp" |
||||
"github.com/stretchr/testify/require" |
||||
) |
||||
|
||||
type testHTTPAuthenticator struct { |
||||
*http.Server |
||||
} |
||||
|
||||
func newTestHTTPAuthenticator(t *testing.T, protocol string, action string) *testHTTPAuthenticator { |
||||
firstReceived := false |
||||
|
||||
ts := &testHTTPAuthenticator{} |
||||
|
||||
ts.Server = &http.Server{ |
||||
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
||||
require.Equal(t, http.MethodPost, r.Method) |
||||
require.Equal(t, "/auth", r.URL.Path) |
||||
|
||||
var in struct { |
||||
IP string `json:"ip"` |
||||
User string `json:"user"` |
||||
Password string `json:"password"` |
||||
Path string `json:"path"` |
||||
Protocol string `json:"protocol"` |
||||
ID string `json:"id"` |
||||
Action string `json:"action"` |
||||
Query string `json:"query"` |
||||
} |
||||
err := json.NewDecoder(r.Body).Decode(&in) |
||||
require.NoError(t, err) |
||||
|
||||
var user string |
||||
if action == "publish" { |
||||
user = "testpublisher" |
||||
} else { |
||||
user = "testreader" |
||||
} |
||||
|
||||
if in.IP != "127.0.0.1" || |
||||
in.User != user || |
||||
in.Password != "testpass" || |
||||
in.Path != "teststream" || |
||||
in.Protocol != protocol || |
||||
(firstReceived && in.ID == "") || |
||||
in.Action != action || |
||||
(in.Query != "user=testreader&pass=testpass¶m=value" && |
||||
in.Query != "user=testpublisher&pass=testpass¶m=value" && |
||||
in.Query != "param=value") { |
||||
w.WriteHeader(http.StatusBadRequest) |
||||
return |
||||
} |
||||
|
||||
firstReceived = true |
||||
}), |
||||
} |
||||
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:9120") |
||||
require.NoError(t, err) |
||||
|
||||
go ts.Server.Serve(ln) |
||||
|
||||
return ts |
||||
} |
||||
|
||||
func (ts *testHTTPAuthenticator) close() { |
||||
ts.Server.Shutdown(context.Background()) |
||||
} |
||||
|
||||
func httpPullFile(t *testing.T, hc *http.Client, u string) []byte { |
||||
res, err := hc.Get(u) |
||||
require.NoError(t, err) |
||||
defer res.Body.Close() |
||||
|
||||
if res.StatusCode != http.StatusOK { |
||||
t.Errorf("bad status code: %v", res.StatusCode) |
||||
} |
||||
|
||||
byts, err := io.ReadAll(res.Body) |
||||
require.NoError(t, err) |
||||
|
||||
return byts |
||||
} |
||||
|
||||
func TestHLSReadNotFound(t *testing.T) { |
||||
p, ok := newInstance("") |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8888/stream/", nil) |
||||
require.NoError(t, err) |
||||
|
||||
hc := &http.Client{Transport: &http.Transport{}} |
||||
|
||||
res, err := hc.Do(req) |
||||
require.NoError(t, err) |
||||
defer res.Body.Close() |
||||
require.Equal(t, http.StatusNotFound, res.StatusCode) |
||||
} |
||||
|
||||
func TestHLSRead(t *testing.T) { |
||||
p, ok := newInstance("hlsAlwaysRemux: yes\n" + |
||||
"paths:\n" + |
||||
" all_others:\n") |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
medi := &description.Media{ |
||||
Type: description.MediaTypeVideo, |
||||
Formats: []format.Format{&format.H264{ |
||||
PayloadTyp: 96, |
||||
PacketizationMode: 1, |
||||
SPS: []byte{ // 1920x1080 baseline
|
||||
0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02, |
||||
0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04, |
||||
0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9, 0x20, |
||||
}, |
||||
PPS: []byte{0x08, 0x06, 0x07, 0x08}, |
||||
}}, |
||||
} |
||||
|
||||
v := gortsplib.TransportTCP |
||||
source := gortsplib.Client{ |
||||
Transport: &v, |
||||
} |
||||
err := source.StartRecording("rtsp://localhost:8554/stream", |
||||
&description.Session{Medias: []*description.Media{medi}}) |
||||
require.NoError(t, err) |
||||
defer source.Close() |
||||
|
||||
time.Sleep(500 * time.Millisecond) |
||||
|
||||
for i := 0; i < 2; i++ { |
||||
err = source.WritePacketRTP(medi, &rtp.Packet{ |
||||
Header: rtp.Header{ |
||||
Version: 2, |
||||
Marker: true, |
||||
PayloadType: 96, |
||||
SequenceNumber: 123 + uint16(i), |
||||
Timestamp: 45343 + uint32(i*90000), |
||||
SSRC: 563423, |
||||
}, |
||||
Payload: []byte{ |
||||
0x05, 0x02, 0x03, 0x04, // IDR
|
||||
}, |
||||
}) |
||||
require.NoError(t, err) |
||||
} |
||||
|
||||
hc := &http.Client{Transport: &http.Transport{}} |
||||
|
||||
cnt := httpPullFile(t, hc, "http://localhost:8888/stream/index.m3u8") |
||||
require.Equal(t, "#EXTM3U\n"+ |
||||
"#EXT-X-VERSION:9\n"+ |
||||
"#EXT-X-INDEPENDENT-SEGMENTS\n"+ |
||||
"\n"+ |
||||
"#EXT-X-STREAM-INF:BANDWIDTH=1192,AVERAGE-BANDWIDTH=1192,"+ |
||||
"CODECS=\"avc1.42c028\",RESOLUTION=1920x1080,FRAME-RATE=30.000\n"+ |
||||
"stream.m3u8\n", string(cnt)) |
||||
|
||||
cnt = httpPullFile(t, hc, "http://localhost:8888/stream/stream.m3u8") |
||||
require.Regexp(t, "#EXTM3U\n"+ |
||||
"#EXT-X-VERSION:9\n"+ |
||||
"#EXT-X-TARGETDURATION:1\n"+ |
||||
"#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=YES,PART-HOLD-BACK=2\\.50000,CAN-SKIP-UNTIL=6\\.00000\n"+ |
||||
"#EXT-X-PART-INF:PART-TARGET=1\\.00000\n"+ |
||||
"#EXT-X-MEDIA-SEQUENCE:1\n"+ |
||||
"#EXT-X-MAP:URI=\".*?_init.mp4\"\n"+ |
||||
"#EXT-X-GAP\n"+ |
||||
"#EXTINF:1\\.00000,\n"+ |
||||
"gap.mp4\n"+ |
||||
"#EXT-X-GAP\n"+ |
||||
"#EXTINF:1\\.00000,\n"+ |
||||
"gap.mp4\n"+ |
||||
"#EXT-X-GAP\n"+ |
||||
"#EXTINF:1\\.00000,\n"+ |
||||
"gap.mp4\n"+ |
||||
"#EXT-X-GAP\n"+ |
||||
"#EXTINF:1\\.00000,\n"+ |
||||
"gap.mp4\n"+ |
||||
"#EXT-X-GAP\n"+ |
||||
"#EXTINF:1\\.00000,\n"+ |
||||
"gap.mp4\n"+ |
||||
"#EXT-X-GAP\n"+ |
||||
"#EXTINF:1\\.00000,\n"+ |
||||
"gap.mp4\n"+ |
||||
"#EXT-X-PROGRAM-DATE-TIME:.+?\n"+ |
||||
"#EXT-X-PART:DURATION=1\\.00000,URI=\".*?_part0.mp4\",INDEPENDENT=YES\n"+ |
||||
"#EXTINF:1\\.00000,\n"+ |
||||
".*?_seg7.mp4\n"+ |
||||
"#EXT-X-PRELOAD-HINT:TYPE=PART,URI=\".*?_part1.mp4\"\n", string(cnt)) |
||||
|
||||
/*trak := <-c.track |
||||
|
||||
pkt, _, err := trak.ReadRTP() |
||||
require.NoError(t, err) |
||||
require.Equal(t, &rtp.Packet{ |
||||
Header: rtp.Header{ |
||||
Version: 2, |
||||
Marker: true, |
||||
PayloadType: 102, |
||||
SequenceNumber: pkt.SequenceNumber, |
||||
Timestamp: pkt.Timestamp, |
||||
SSRC: pkt.SSRC, |
||||
CSRC: []uint32{}, |
||||
}, |
||||
Payload: []byte{0x01, 0x02, 0x03, 0x04}, |
||||
}, pkt)*/ |
||||
} |
||||
@ -0,0 +1,23 @@
@@ -0,0 +1,23 @@
|
||||
package core |
||||
|
||||
import ( |
||||
"fmt" |
||||
"net" |
||||
) |
||||
|
||||
func ipEqualOrInRange(ip net.IP, ips []fmt.Stringer) bool { |
||||
for _, item := range ips { |
||||
switch titem := item.(type) { |
||||
case net.IP: |
||||
if titem.Equal(ip) { |
||||
return true |
||||
} |
||||
|
||||
case *net.IPNet: |
||||
if titem.Contains(ip) { |
||||
return true |
||||
} |
||||
} |
||||
} |
||||
return false |
||||
} |
||||
@ -0,0 +1,348 @@
@@ -0,0 +1,348 @@
|
||||
package core //nolint:dupl
|
||||
|
||||
import ( |
||||
"crypto/tls" |
||||
"net" |
||||
"net/url" |
||||
"os" |
||||
"testing" |
||||
"time" |
||||
|
||||
"github.com/bluenviron/gortsplib/v4/pkg/format" |
||||
"github.com/bluenviron/mediacommon/pkg/codecs/mpeg4audio" |
||||
"github.com/stretchr/testify/require" |
||||
|
||||
"github.com/bluenviron/mediamtx/internal/protocols/rtmp" |
||||
) |
||||
|
||||
func TestRTMPServer(t *testing.T) { |
||||
for _, encrypt := range []string{ |
||||
"plain", |
||||
"tls", |
||||
} { |
||||
for _, auth := range []string{ |
||||
"none", |
||||
"internal", |
||||
"external", |
||||
} { |
||||
t.Run("encrypt_"+encrypt+"_auth_"+auth, func(t *testing.T) { |
||||
var port string |
||||
var conf string |
||||
|
||||
if encrypt == "plain" { |
||||
port = "1935" |
||||
|
||||
conf = "rtsp: no\n" + |
||||
"hls: no\n" |
||||
} else { |
||||
port = "1936" |
||||
|
||||
serverCertFpath, err := writeTempFile(serverCert) |
||||
require.NoError(t, err) |
||||
defer os.Remove(serverCertFpath) |
||||
|
||||
serverKeyFpath, err := writeTempFile(serverKey) |
||||
require.NoError(t, err) |
||||
defer os.Remove(serverKeyFpath) |
||||
|
||||
conf = "rtsp: no\n" + |
||||
"hls: no\n" + |
||||
"webrtc: no\n" + |
||||
"rtmpEncryption: \"yes\"\n" + |
||||
"rtmpServerCert: " + serverCertFpath + "\n" + |
||||
"rtmpServerKey: " + serverKeyFpath + "\n" |
||||
} |
||||
|
||||
switch auth { |
||||
case "none": |
||||
conf += "paths:\n" + |
||||
" all_others:\n" |
||||
|
||||
case "internal": |
||||
conf += "paths:\n" + |
||||
" all_others:\n" + |
||||
" publishUser: testpublisher\n" + |
||||
" publishPass: testpass\n" + |
||||
" publishIPs: [127.0.0.0/16]\n" + |
||||
" readUser: testreader\n" + |
||||
" readPass: testpass\n" + |
||||
" readIPs: [127.0.0.0/16]\n" |
||||
|
||||
case "external": |
||||
conf += "externalAuthenticationURL: http://localhost:9120/auth\n" + |
||||
"paths:\n" + |
||||
" all_others:\n" |
||||
} |
||||
|
||||
p, ok := newInstance(conf) |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
var a *testHTTPAuthenticator |
||||
if auth == "external" { |
||||
a = newTestHTTPAuthenticator(t, "rtmp", "publish") |
||||
} |
||||
|
||||
u1, err := url.Parse("rtmp://127.0.0.1:" + port + "/teststream?user=testpublisher&pass=testpass¶m=value") |
||||
require.NoError(t, err) |
||||
|
||||
nconn1, err := func() (net.Conn, error) { |
||||
if encrypt == "plain" { |
||||
return net.Dial("tcp", u1.Host) |
||||
} |
||||
return tls.Dial("tcp", u1.Host, &tls.Config{InsecureSkipVerify: true}) |
||||
}() |
||||
require.NoError(t, err) |
||||
defer nconn1.Close() |
||||
|
||||
conn1, err := rtmp.NewClientConn(nconn1, u1, true) |
||||
require.NoError(t, err) |
||||
|
||||
videoTrack := &format.H264{ |
||||
PayloadTyp: 96, |
||||
SPS: []byte{ // 1920x1080 baseline
|
||||
0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02, |
||||
0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04, |
||||
0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9, 0x20, |
||||
}, |
||||
PPS: []byte{0x08, 0x06, 0x07, 0x08}, |
||||
PacketizationMode: 1, |
||||
} |
||||
|
||||
audioTrack := &format.MPEG4Audio{ |
||||
PayloadTyp: 96, |
||||
Config: &mpeg4audio.Config{ |
||||
Type: 2, |
||||
SampleRate: 44100, |
||||
ChannelCount: 2, |
||||
}, |
||||
SizeLength: 13, |
||||
IndexLength: 3, |
||||
IndexDeltaLength: 3, |
||||
} |
||||
|
||||
w, err := rtmp.NewWriter(conn1, videoTrack, audioTrack) |
||||
require.NoError(t, err) |
||||
|
||||
time.Sleep(500 * time.Millisecond) |
||||
|
||||
if auth == "external" { |
||||
a.close() |
||||
a = newTestHTTPAuthenticator(t, "rtmp", "read") |
||||
defer a.close() |
||||
} |
||||
|
||||
u2, err := url.Parse("rtmp://127.0.0.1:" + port + "/teststream?user=testreader&pass=testpass¶m=value") |
||||
require.NoError(t, err) |
||||
|
||||
nconn2, err := func() (net.Conn, error) { |
||||
if encrypt == "plain" { |
||||
return net.Dial("tcp", u2.Host) |
||||
} |
||||
return tls.Dial("tcp", u2.Host, &tls.Config{InsecureSkipVerify: true}) |
||||
}() |
||||
require.NoError(t, err) |
||||
defer nconn2.Close() |
||||
|
||||
conn2, err := rtmp.NewClientConn(nconn2, u2, false) |
||||
require.NoError(t, err) |
||||
|
||||
r, err := rtmp.NewReader(conn2) |
||||
require.NoError(t, err) |
||||
|
||||
videoTrack1, audioTrack2 := r.Tracks() |
||||
require.Equal(t, videoTrack, videoTrack1) |
||||
require.Equal(t, audioTrack, audioTrack2) |
||||
|
||||
err = w.WriteH264(0, 0, true, [][]byte{ |
||||
{0x05, 0x02, 0x03, 0x04}, // IDR 1
|
||||
{0x05, 0x02, 0x03, 0x04}, // IDR 2
|
||||
}) |
||||
require.NoError(t, err) |
||||
|
||||
r.OnDataH264(func(pts time.Duration, au [][]byte) { |
||||
require.Equal(t, [][]byte{ |
||||
{ // SPS
|
||||
0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02, |
||||
0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04, |
||||
0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9, |
||||
0x20, |
||||
}, |
||||
{ // PPS
|
||||
0x08, 0x06, 0x07, 0x08, |
||||
}, |
||||
{ // IDR 1
|
||||
0x05, 0x02, 0x03, 0x04, |
||||
}, |
||||
{ // IDR 2
|
||||
0x05, 0x02, 0x03, 0x04, |
||||
}, |
||||
}, au) |
||||
}) |
||||
|
||||
err = r.Read() |
||||
require.NoError(t, err) |
||||
}) |
||||
} |
||||
} |
||||
} |
||||
|
||||
func TestRTMPServerAuthFail(t *testing.T) { |
||||
t.Run("publish", func(t *testing.T) { //nolint:dupl
|
||||
p, ok := newInstance("rtsp: no\n" + |
||||
"hls: no\n" + |
||||
"webrtc: no\n" + |
||||
"paths:\n" + |
||||
" all_others:\n" + |
||||
" publishUser: testuser2\n" + |
||||
" publishPass: testpass\n") |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
u1, err := url.Parse("rtmp://127.0.0.1:1935/teststream?user=testuser&pass=testpass") |
||||
require.NoError(t, err) |
||||
|
||||
nconn1, err := net.Dial("tcp", u1.Host) |
||||
require.NoError(t, err) |
||||
defer nconn1.Close() |
||||
|
||||
conn1, err := rtmp.NewClientConn(nconn1, u1, true) |
||||
require.NoError(t, err) |
||||
|
||||
videoTrack := &format.H264{ |
||||
PayloadTyp: 96, |
||||
SPS: []byte{ |
||||
0x67, 0x64, 0x00, 0x0c, 0xac, 0x3b, 0x50, 0xb0, |
||||
0x4b, 0x42, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, |
||||
0x00, 0x03, 0x00, 0x3d, 0x08, |
||||
}, |
||||
PPS: []byte{ |
||||
0x68, 0xee, 0x3c, 0x80, |
||||
}, |
||||
PacketizationMode: 1, |
||||
} |
||||
|
||||
_, err = rtmp.NewWriter(conn1, videoTrack, nil) |
||||
require.NoError(t, err) |
||||
|
||||
time.Sleep(500 * time.Millisecond) |
||||
|
||||
u2, err := url.Parse("rtmp://127.0.0.1:1935/teststream") |
||||
require.NoError(t, err) |
||||
|
||||
nconn2, err := net.Dial("tcp", u2.Host) |
||||
require.NoError(t, err) |
||||
defer nconn2.Close() |
||||
|
||||
conn2, err := rtmp.NewClientConn(nconn2, u2, false) |
||||
require.NoError(t, err) |
||||
|
||||
_, err = rtmp.NewReader(conn2) |
||||
require.EqualError(t, err, "EOF") |
||||
}) |
||||
|
||||
t.Run("publish_external", func(t *testing.T) { |
||||
p, ok := newInstance("externalAuthenticationURL: http://localhost:9120/auth\n" + |
||||
"paths:\n" + |
||||
" all_others:\n") |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
a := newTestHTTPAuthenticator(t, "rtmp", "publish") |
||||
defer a.close() |
||||
|
||||
u1, err := url.Parse("rtmp://127.0.0.1:1935/teststream?user=testuser1&pass=testpass") |
||||
require.NoError(t, err) |
||||
|
||||
nconn1, err := net.Dial("tcp", u1.Host) |
||||
require.NoError(t, err) |
||||
defer nconn1.Close() |
||||
|
||||
conn1, err := rtmp.NewClientConn(nconn1, u1, true) |
||||
require.NoError(t, err) |
||||
|
||||
videoTrack := &format.H264{ |
||||
PayloadTyp: 96, |
||||
SPS: []byte{ |
||||
0x67, 0x64, 0x00, 0x0c, 0xac, 0x3b, 0x50, 0xb0, |
||||
0x4b, 0x42, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, |
||||
0x00, 0x03, 0x00, 0x3d, 0x08, |
||||
}, |
||||
PPS: []byte{ |
||||
0x68, 0xee, 0x3c, 0x80, |
||||
}, |
||||
PacketizationMode: 1, |
||||
} |
||||
|
||||
_, err = rtmp.NewWriter(conn1, videoTrack, nil) |
||||
require.NoError(t, err) |
||||
|
||||
time.Sleep(500 * time.Millisecond) |
||||
|
||||
u2, err := url.Parse("rtmp://127.0.0.1:1935/teststream") |
||||
require.NoError(t, err) |
||||
|
||||
nconn2, err := net.Dial("tcp", u2.Host) |
||||
require.NoError(t, err) |
||||
defer nconn2.Close() |
||||
|
||||
conn2, err := rtmp.NewClientConn(nconn2, u2, false) |
||||
require.NoError(t, err) |
||||
|
||||
_, err = rtmp.NewReader(conn2) |
||||
require.EqualError(t, err, "EOF") |
||||
}) |
||||
|
||||
t.Run("read", func(t *testing.T) { //nolint:dupl
|
||||
p, ok := newInstance("rtsp: no\n" + |
||||
"hls: no\n" + |
||||
"webrtc: no\n" + |
||||
"paths:\n" + |
||||
" all_others:\n" + |
||||
" readUser: testuser2\n" + |
||||
" readPass: testpass\n") |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
u1, err := url.Parse("rtmp://127.0.0.1:1935/teststream") |
||||
require.NoError(t, err) |
||||
|
||||
nconn1, err := net.Dial("tcp", u1.Host) |
||||
require.NoError(t, err) |
||||
defer nconn1.Close() |
||||
|
||||
conn1, err := rtmp.NewClientConn(nconn1, u1, true) |
||||
require.NoError(t, err) |
||||
|
||||
videoTrack := &format.H264{ |
||||
PayloadTyp: 96, |
||||
SPS: []byte{ |
||||
0x67, 0x64, 0x00, 0x0c, 0xac, 0x3b, 0x50, 0xb0, |
||||
0x4b, 0x42, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, |
||||
0x00, 0x03, 0x00, 0x3d, 0x08, |
||||
}, |
||||
PPS: []byte{ |
||||
0x68, 0xee, 0x3c, 0x80, |
||||
}, |
||||
PacketizationMode: 1, |
||||
} |
||||
|
||||
_, err = rtmp.NewWriter(conn1, videoTrack, nil) |
||||
require.NoError(t, err) |
||||
|
||||
time.Sleep(500 * time.Millisecond) |
||||
|
||||
u2, err := url.Parse("rtmp://127.0.0.1:1935/teststream?user=testuser1&pass=testpass") |
||||
require.NoError(t, err) |
||||
|
||||
nconn2, err := net.Dial("tcp", u2.Host) |
||||
require.NoError(t, err) |
||||
defer nconn2.Close() |
||||
|
||||
conn2, err := rtmp.NewClientConn(nconn2, u2, false) |
||||
require.NoError(t, err) |
||||
|
||||
_, err = rtmp.NewReader(conn2) |
||||
require.EqualError(t, err, "EOF") |
||||
}) |
||||
} |
||||
@ -0,0 +1,373 @@
@@ -0,0 +1,373 @@
|
||||
package core |
||||
|
||||
import ( |
||||
"testing" |
||||
|
||||
"github.com/bluenviron/gortsplib/v4" |
||||
"github.com/bluenviron/gortsplib/v4/pkg/base" |
||||
"github.com/bluenviron/gortsplib/v4/pkg/description" |
||||
"github.com/pion/rtp" |
||||
"github.com/stretchr/testify/require" |
||||
) |
||||
|
||||
func TestRTSPServer(t *testing.T) { |
||||
for _, auth := range []string{ |
||||
"none", |
||||
"internal", |
||||
"external", |
||||
} { |
||||
t.Run("auth_"+auth, func(t *testing.T) { |
||||
var conf string |
||||
|
||||
switch auth { |
||||
case "none": |
||||
conf = "paths:\n" + |
||||
" all_others:\n" |
||||
|
||||
case "internal": |
||||
conf = "rtmp: no\n" + |
||||
"hls: no\n" + |
||||
"webrtc: no\n" + |
||||
"paths:\n" + |
||||
" all_others:\n" + |
||||
" publishUser: testpublisher\n" + |
||||
" publishPass: testpass\n" + |
||||
" publishIPs: [127.0.0.0/16]\n" + |
||||
" readUser: testreader\n" + |
||||
" readPass: testpass\n" + |
||||
" readIPs: [127.0.0.0/16]\n" |
||||
|
||||
case "external": |
||||
conf = "externalAuthenticationURL: http://localhost:9120/auth\n" + |
||||
"paths:\n" + |
||||
" all_others:\n" |
||||
} |
||||
|
||||
p, ok := newInstance(conf) |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
var a *testHTTPAuthenticator |
||||
if auth == "external" { |
||||
a = newTestHTTPAuthenticator(t, "rtsp", "publish") |
||||
} |
||||
|
||||
medi := testMediaH264 |
||||
|
||||
source := gortsplib.Client{} |
||||
|
||||
err := source.StartRecording( |
||||
"rtsp://testpublisher:testpass@127.0.0.1:8554/teststream?param=value", |
||||
&description.Session{Medias: []*description.Media{medi}}) |
||||
require.NoError(t, err) |
||||
defer source.Close() |
||||
|
||||
if auth == "external" { |
||||
a.close() |
||||
a = newTestHTTPAuthenticator(t, "rtsp", "read") |
||||
defer a.close() |
||||
} |
||||
|
||||
reader := gortsplib.Client{} |
||||
|
||||
u, err := base.ParseURL("rtsp://testreader:testpass@127.0.0.1:8554/teststream?param=value") |
||||
require.NoError(t, err) |
||||
|
||||
err = reader.Start(u.Scheme, u.Host) |
||||
require.NoError(t, err) |
||||
defer reader.Close() |
||||
|
||||
desc, _, err := reader.Describe(u) |
||||
require.NoError(t, err) |
||||
|
||||
err = reader.SetupAll(desc.BaseURL, desc.Medias) |
||||
require.NoError(t, err) |
||||
|
||||
_, err = reader.Play(nil) |
||||
require.NoError(t, err) |
||||
}) |
||||
} |
||||
} |
||||
|
||||
func TestRTSPServerAuthHashedSHA256(t *testing.T) { |
||||
p, ok := newInstance( |
||||
"rtmp: no\n" + |
||||
"hls: no\n" + |
||||
"webrtc: no\n" + |
||||
"paths:\n" + |
||||
" all_others:\n" + |
||||
" publishUser: sha256:rl3rgi4NcZkpAEcacZnQ2VuOfJ0FxAqCRaKB/SwdZoQ=\n" + |
||||
" publishPass: sha256:E9JJ8stBJ7QM+nV4ZoUCeHk/gU3tPFh/5YieiJp6n2w=\n") |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
medi := testMediaH264 |
||||
|
||||
source := gortsplib.Client{} |
||||
|
||||
err := source.StartRecording( |
||||
"rtsp://testuser:testpass@127.0.0.1:8554/test/stream", |
||||
&description.Session{Medias: []*description.Media{medi}}) |
||||
require.NoError(t, err) |
||||
defer source.Close() |
||||
} |
||||
|
||||
func TestRTSPServerAuthHashedArgon2(t *testing.T) { |
||||
p, ok := newInstance( |
||||
"rtmp: no\n" + |
||||
"hls: no\n" + |
||||
"webrtc: no\n" + |
||||
"paths:\n" + |
||||
" all_others:\n" + |
||||
" publishUser: argon2:$argon2id$v=19$m=4096,t=3,p=1$MTIzNDU2Nzg$Ux/LWeTgJQPyfMMJo1myR64+o8rALHoPmlE1i/TR+58\n" + |
||||
" publishPass: argon2:$argon2i$v=19$m=4096,t=3,p=1$MTIzNDU2Nzg$/mrZ42TiTv1mcPnpMUera5oi0SFYbbyueAbdx5sUvWo\n") |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
medi := testMediaH264 |
||||
|
||||
source := gortsplib.Client{} |
||||
|
||||
err := source.StartRecording( |
||||
"rtsp://testuser:testpass@127.0.0.1:8554/test/stream", |
||||
&description.Session{Medias: []*description.Media{medi}}) |
||||
require.NoError(t, err) |
||||
defer source.Close() |
||||
} |
||||
|
||||
func TestRTSPServerAuthFail(t *testing.T) { |
||||
for _, ca := range []struct { |
||||
name string |
||||
user string |
||||
pass string |
||||
}{ |
||||
{ |
||||
"wronguser", |
||||
"test1user", |
||||
"testpass", |
||||
}, |
||||
{ |
||||
"wrongpass", |
||||
"testuser", |
||||
"test1pass", |
||||
}, |
||||
{ |
||||
"wrongboth", |
||||
"test1user", |
||||
"test1pass", |
||||
}, |
||||
} { |
||||
t.Run("publish_"+ca.name, func(t *testing.T) { |
||||
p, ok := newInstance("rtmp: no\n" + |
||||
"hls: no\n" + |
||||
"webrtc: no\n" + |
||||
"paths:\n" + |
||||
" all_others:\n" + |
||||
" publishUser: testuser\n" + |
||||
" publishPass: testpass\n") |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
medi := testMediaH264 |
||||
|
||||
c := gortsplib.Client{} |
||||
|
||||
err := c.StartRecording( |
||||
"rtsp://"+ca.user+":"+ca.pass+"@localhost:8554/test/stream", |
||||
&description.Session{Medias: []*description.Media{medi}}, |
||||
) |
||||
require.EqualError(t, err, "bad status code: 401 (Unauthorized)") |
||||
}) |
||||
} |
||||
|
||||
for _, ca := range []struct { |
||||
name string |
||||
user string |
||||
pass string |
||||
}{ |
||||
{ |
||||
"wronguser", |
||||
"test1user", |
||||
"testpass", |
||||
}, |
||||
{ |
||||
"wrongpass", |
||||
"testuser", |
||||
"test1pass", |
||||
}, |
||||
{ |
||||
"wrongboth", |
||||
"test1user", |
||||
"test1pass", |
||||
}, |
||||
} { |
||||
t.Run("read_"+ca.name, func(t *testing.T) { |
||||
p, ok := newInstance("rtmp: no\n" + |
||||
"hls: no\n" + |
||||
"webrtc: no\n" + |
||||
"paths:\n" + |
||||
" all_others:\n" + |
||||
" readUser: testuser\n" + |
||||
" readPass: testpass\n") |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
c := gortsplib.Client{} |
||||
|
||||
u, err := base.ParseURL("rtsp://" + ca.user + ":" + ca.pass + "@localhost:8554/test/stream") |
||||
require.NoError(t, err) |
||||
|
||||
err = c.Start(u.Scheme, u.Host) |
||||
require.NoError(t, err) |
||||
defer c.Close() |
||||
|
||||
_, _, err = c.Describe(u) |
||||
require.EqualError(t, err, "bad status code: 401 (Unauthorized)") |
||||
}) |
||||
} |
||||
|
||||
t.Run("ip", func(t *testing.T) { |
||||
p, ok := newInstance("rtmp: no\n" + |
||||
"hls: no\n" + |
||||
"webrtc: no\n" + |
||||
"paths:\n" + |
||||
" all_others:\n" + |
||||
" publishIPs: [128.0.0.1/32]\n") |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
medi := testMediaH264 |
||||
|
||||
c := gortsplib.Client{} |
||||
|
||||
err := c.StartRecording( |
||||
"rtsp://localhost:8554/test/stream", |
||||
&description.Session{Medias: []*description.Media{medi}}, |
||||
) |
||||
require.EqualError(t, err, "bad status code: 401 (Unauthorized)") |
||||
}) |
||||
|
||||
t.Run("external", func(t *testing.T) { |
||||
p, ok := newInstance("externalAuthenticationURL: http://localhost:9120/auth\n" + |
||||
"paths:\n" + |
||||
" all_others:\n") |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
a := newTestHTTPAuthenticator(t, "rtsp", "publish") |
||||
defer a.close() |
||||
|
||||
medi := testMediaH264 |
||||
|
||||
c := gortsplib.Client{} |
||||
|
||||
err := c.StartRecording( |
||||
"rtsp://testpublisher2:testpass@localhost:8554/teststream?param=value", |
||||
&description.Session{Medias: []*description.Media{medi}}, |
||||
) |
||||
require.EqualError(t, err, "bad status code: 401 (Unauthorized)") |
||||
}) |
||||
} |
||||
|
||||
func TestRTSPServerPublisherOverride(t *testing.T) { |
||||
for _, ca := range []string{ |
||||
"enabled", |
||||
"disabled", |
||||
} { |
||||
t.Run(ca, func(t *testing.T) { |
||||
conf := "rtmp: no\n" + |
||||
"paths:\n" + |
||||
" all_others:\n" |
||||
|
||||
if ca == "disabled" { |
||||
conf += " overridePublisher: no\n" |
||||
} |
||||
|
||||
p, ok := newInstance(conf) |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
medi := testMediaH264 |
||||
|
||||
s1 := gortsplib.Client{} |
||||
|
||||
err := s1.StartRecording("rtsp://localhost:8554/teststream", |
||||
&description.Session{Medias: []*description.Media{medi}}) |
||||
require.NoError(t, err) |
||||
defer s1.Close() |
||||
|
||||
s2 := gortsplib.Client{} |
||||
|
||||
err = s2.StartRecording("rtsp://localhost:8554/teststream", |
||||
&description.Session{Medias: []*description.Media{medi}}) |
||||
if ca == "enabled" { |
||||
require.NoError(t, err) |
||||
defer s2.Close() |
||||
} else { |
||||
require.Error(t, err) |
||||
} |
||||
|
||||
frameRecv := make(chan struct{}) |
||||
|
||||
c := gortsplib.Client{} |
||||
|
||||
u, err := base.ParseURL("rtsp://localhost:8554/teststream") |
||||
require.NoError(t, err) |
||||
|
||||
err = c.Start(u.Scheme, u.Host) |
||||
require.NoError(t, err) |
||||
defer c.Close() |
||||
|
||||
desc, _, err := c.Describe(u) |
||||
require.NoError(t, err) |
||||
|
||||
err = c.SetupAll(desc.BaseURL, desc.Medias) |
||||
require.NoError(t, err) |
||||
|
||||
c.OnPacketRTP(desc.Medias[0], desc.Medias[0].Formats[0], func(pkt *rtp.Packet) { |
||||
if ca == "enabled" { |
||||
require.Equal(t, []byte{5, 15, 16, 17, 18}, pkt.Payload) |
||||
} else { |
||||
require.Equal(t, []byte{5, 11, 12, 13, 14}, pkt.Payload) |
||||
} |
||||
close(frameRecv) |
||||
}) |
||||
|
||||
_, err = c.Play(nil) |
||||
require.NoError(t, err) |
||||
|
||||
if ca == "enabled" { |
||||
err := s1.Wait() |
||||
require.EqualError(t, err, "EOF") |
||||
|
||||
err = s2.WritePacketRTP(medi, &rtp.Packet{ |
||||
Header: rtp.Header{ |
||||
Version: 0x02, |
||||
PayloadType: 96, |
||||
SequenceNumber: 57899, |
||||
Timestamp: 345234345, |
||||
SSRC: 978651231, |
||||
Marker: true, |
||||
}, |
||||
Payload: []byte{5, 15, 16, 17, 18}, |
||||
}) |
||||
require.NoError(t, err) |
||||
} else { |
||||
err = s1.WritePacketRTP(medi, &rtp.Packet{ |
||||
Header: rtp.Header{ |
||||
Version: 0x02, |
||||
PayloadType: 96, |
||||
SequenceNumber: 57899, |
||||
Timestamp: 345234345, |
||||
SSRC: 978651231, |
||||
Marker: true, |
||||
}, |
||||
Payload: []byte{5, 11, 12, 13, 14}, |
||||
}) |
||||
require.NoError(t, err) |
||||
} |
||||
|
||||
<-frameRecv |
||||
}) |
||||
} |
||||
} |
||||
@ -0,0 +1,146 @@
@@ -0,0 +1,146 @@
|
||||
package core |
||||
|
||||
import ( |
||||
"bufio" |
||||
"testing" |
||||
"time" |
||||
|
||||
"github.com/bluenviron/mediacommon/pkg/formats/mpegts" |
||||
"github.com/datarhei/gosrt" |
||||
"github.com/stretchr/testify/require" |
||||
) |
||||
|
||||
func TestSRTServer(t *testing.T) { |
||||
for _, ca := range []string{ |
||||
"no passphrase", |
||||
"publish passphrase", |
||||
"read passphrase", |
||||
} { |
||||
t.Run(ca, func(t *testing.T) { |
||||
conf := "paths:\n" + |
||||
" all_others:\n" |
||||
|
||||
switch ca { |
||||
case "publish passphrase": |
||||
conf += " srtPublishPassphrase: 123456789abcde" |
||||
|
||||
case "read passphrase": |
||||
conf += " srtReadPassphrase: 123456789abcde" |
||||
} |
||||
|
||||
p, ok := newInstance(conf) |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
u := "srt://localhost:8890?streamid=publish:mypath" |
||||
if ca == "publish passphrase" { |
||||
u += "&passphrase=123456789abcde" |
||||
} |
||||
|
||||
srtConf := srt.DefaultConfig() |
||||
address, err := srtConf.UnmarshalURL(u) |
||||
require.NoError(t, err) |
||||
|
||||
err = srtConf.Validate() |
||||
require.NoError(t, err) |
||||
|
||||
publisher, err := srt.Dial("srt", address, srtConf) |
||||
require.NoError(t, err) |
||||
defer publisher.Close() |
||||
|
||||
track := &mpegts.Track{ |
||||
Codec: &mpegts.CodecH264{}, |
||||
} |
||||
|
||||
bw := bufio.NewWriter(publisher) |
||||
w := mpegts.NewWriter(bw, []*mpegts.Track{track}) |
||||
require.NoError(t, err) |
||||
|
||||
err = w.WriteH26x(track, 0, 0, true, [][]byte{ |
||||
{ // SPS
|
||||
0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02, |
||||
0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04, |
||||
0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9, |
||||
0x20, |
||||
}, |
||||
{ // PPS
|
||||
0x08, 0x06, 0x07, 0x08, |
||||
}, |
||||
{ // IDR
|
||||
0x05, 1, |
||||
}, |
||||
}) |
||||
require.NoError(t, err) |
||||
|
||||
err = bw.Flush() |
||||
require.NoError(t, err) |
||||
|
||||
time.Sleep(500 * time.Millisecond) |
||||
|
||||
u = "srt://localhost:8890?streamid=read:mypath" |
||||
if ca == "read passphrase" { |
||||
u += "&passphrase=123456789abcde" |
||||
} |
||||
|
||||
srtConf = srt.DefaultConfig() |
||||
address, err = srtConf.UnmarshalURL(u) |
||||
require.NoError(t, err) |
||||
|
||||
err = srtConf.Validate() |
||||
require.NoError(t, err) |
||||
|
||||
reader, err := srt.Dial("srt", address, srtConf) |
||||
require.NoError(t, err) |
||||
defer reader.Close() |
||||
|
||||
err = w.WriteH26x(track, 2*90000, 1*90000, true, [][]byte{ |
||||
{ // IDR
|
||||
0x05, 2, |
||||
}, |
||||
}) |
||||
require.NoError(t, err) |
||||
|
||||
err = bw.Flush() |
||||
require.NoError(t, err) |
||||
|
||||
r, err := mpegts.NewReader(reader) |
||||
require.NoError(t, err) |
||||
|
||||
require.Equal(t, []*mpegts.Track{{ |
||||
PID: 256, |
||||
Codec: &mpegts.CodecH264{}, |
||||
}}, r.Tracks()) |
||||
|
||||
received := false |
||||
|
||||
r.OnDataH26x(r.Tracks()[0], func(pts int64, dts int64, au [][]byte) error { |
||||
require.Equal(t, int64(0), pts) |
||||
require.Equal(t, int64(0), dts) |
||||
require.Equal(t, [][]byte{ |
||||
{ // SPS
|
||||
0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02, |
||||
0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04, |
||||
0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9, |
||||
0x20, |
||||
}, |
||||
{ // PPS
|
||||
0x08, 0x06, 0x07, 0x08, |
||||
}, |
||||
{ // IDR
|
||||
0x05, 1, |
||||
}, |
||||
}, au) |
||||
received = true |
||||
return nil |
||||
}) |
||||
|
||||
for { |
||||
err = r.Read() |
||||
require.NoError(t, err) |
||||
if received { |
||||
break |
||||
} |
||||
} |
||||
}) |
||||
} |
||||
} |
||||
@ -0,0 +1,362 @@
@@ -0,0 +1,362 @@
|
||||
package core |
||||
|
||||
import ( |
||||
"bytes" |
||||
"context" |
||||
"net/http" |
||||
"net/url" |
||||
"testing" |
||||
"time" |
||||
|
||||
"github.com/bluenviron/gortsplib/v4" |
||||
"github.com/bluenviron/gortsplib/v4/pkg/base" |
||||
"github.com/bluenviron/gortsplib/v4/pkg/description" |
||||
"github.com/bluenviron/gortsplib/v4/pkg/format" |
||||
"github.com/pion/rtp" |
||||
pwebrtc "github.com/pion/webrtc/v3" |
||||
"github.com/stretchr/testify/require" |
||||
|
||||
"github.com/bluenviron/mediamtx/internal/protocols/webrtc" |
||||
) |
||||
|
||||
func TestWebRTCPages(t *testing.T) { |
||||
p, ok := newInstance("paths:\n" + |
||||
" all:\n") |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
hc := &http.Client{Transport: &http.Transport{}} |
||||
|
||||
for _, path := range []string{"/stream", "/stream/publish", "/publish"} { |
||||
func() { |
||||
req, err := http.NewRequest(http.MethodGet, "http://localhost:8889"+path, nil) |
||||
require.NoError(t, err) |
||||
|
||||
res, err := hc.Do(req) |
||||
require.NoError(t, err) |
||||
defer res.Body.Close() |
||||
|
||||
require.Equal(t, http.StatusOK, res.StatusCode) |
||||
}() |
||||
} |
||||
} |
||||
|
||||
func TestWebRTCRead(t *testing.T) { |
||||
for _, auth := range []string{ |
||||
"none", |
||||
"internal", |
||||
"external", |
||||
} { |
||||
t.Run("auth_"+auth, func(t *testing.T) { |
||||
var conf string |
||||
|
||||
switch auth { |
||||
case "none": |
||||
conf = "paths:\n" + |
||||
" all_others:\n" |
||||
|
||||
case "internal": |
||||
conf = "paths:\n" + |
||||
" all_others:\n" + |
||||
" readUser: myuser\n" + |
||||
" readPass: mypass\n" |
||||
|
||||
case "external": |
||||
conf = "externalAuthenticationURL: http://localhost:9120/auth\n" + |
||||
"paths:\n" + |
||||
" all_others:\n" |
||||
} |
||||
|
||||
p, ok := newInstance(conf) |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
var a *testHTTPAuthenticator |
||||
if auth == "external" { |
||||
a = newTestHTTPAuthenticator(t, "rtsp", "publish") |
||||
} |
||||
|
||||
medi := &description.Media{ |
||||
Type: description.MediaTypeVideo, |
||||
Formats: []format.Format{&format.H264{ |
||||
PayloadTyp: 96, |
||||
PacketizationMode: 1, |
||||
}}, |
||||
} |
||||
|
||||
v := gortsplib.TransportTCP |
||||
source := gortsplib.Client{ |
||||
Transport: &v, |
||||
} |
||||
err := source.StartRecording( |
||||
"rtsp://testpublisher:testpass@localhost:8554/teststream?param=value", |
||||
&description.Session{Medias: []*description.Media{medi}}) |
||||
require.NoError(t, err) |
||||
defer source.Close() |
||||
|
||||
if auth == "external" { |
||||
a.close() |
||||
a = newTestHTTPAuthenticator(t, "webrtc", "read") |
||||
defer a.close() |
||||
} |
||||
|
||||
hc := &http.Client{Transport: &http.Transport{}} |
||||
|
||||
user := "" |
||||
pass := "" |
||||
|
||||
switch auth { |
||||
case "internal": |
||||
user = "myuser" |
||||
pass = "mypass" |
||||
|
||||
case "external": |
||||
user = "testreader" |
||||
pass = "testpass" |
||||
} |
||||
|
||||
ur := "http://" |
||||
if user != "" { |
||||
ur += user + ":" + pass + "@" |
||||
} |
||||
ur += "localhost:8889/teststream/whep?param=value" |
||||
|
||||
go func() { |
||||
time.Sleep(500 * time.Millisecond) |
||||
|
||||
err := source.WritePacketRTP(medi, &rtp.Packet{ |
||||
Header: rtp.Header{ |
||||
Version: 2, |
||||
Marker: true, |
||||
PayloadType: 96, |
||||
SequenceNumber: 123, |
||||
Timestamp: 45343, |
||||
SSRC: 563423, |
||||
}, |
||||
Payload: []byte{5, 3}, |
||||
}) |
||||
require.NoError(t, err) |
||||
}() |
||||
|
||||
u, err := url.Parse(ur) |
||||
require.NoError(t, err) |
||||
|
||||
c := &webrtc.WHIPClient{ |
||||
HTTPClient: hc, |
||||
URL: u, |
||||
} |
||||
|
||||
tracks, err := c.Read(context.Background()) |
||||
require.NoError(t, err) |
||||
defer checkClose(t, c.Close) |
||||
|
||||
pkt, err := tracks[0].ReadRTP() |
||||
require.NoError(t, err) |
||||
require.Equal(t, &rtp.Packet{ |
||||
Header: rtp.Header{ |
||||
Version: 2, |
||||
Marker: true, |
||||
PayloadType: 100, |
||||
SequenceNumber: pkt.SequenceNumber, |
||||
Timestamp: pkt.Timestamp, |
||||
SSRC: pkt.SSRC, |
||||
CSRC: []uint32{}, |
||||
}, |
||||
Payload: []byte{5, 3}, |
||||
}, pkt) |
||||
}) |
||||
} |
||||
} |
||||
|
||||
func TestWebRTCReadNotFound(t *testing.T) { |
||||
p, ok := newInstance("paths:\n" + |
||||
" all_others:\n") |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
hc := &http.Client{Transport: &http.Transport{}} |
||||
|
||||
iceServers, err := webrtc.WHIPOptionsICEServers(context.Background(), hc, "http://localhost:8889/stream/whep") |
||||
require.NoError(t, err) |
||||
|
||||
pc, err := pwebrtc.NewPeerConnection(pwebrtc.Configuration{ |
||||
ICEServers: iceServers, |
||||
}) |
||||
require.NoError(t, err) |
||||
defer pc.Close() //nolint:errcheck
|
||||
|
||||
_, err = pc.AddTransceiverFromKind(pwebrtc.RTPCodecTypeVideo) |
||||
require.NoError(t, err) |
||||
|
||||
offer, err := pc.CreateOffer(nil) |
||||
require.NoError(t, err) |
||||
|
||||
req, err := http.NewRequest(http.MethodPost, "http://localhost:8889/stream/whep", bytes.NewReader([]byte(offer.SDP))) |
||||
require.NoError(t, err) |
||||
|
||||
req.Header.Set("Content-Type", "application/sdp") |
||||
|
||||
res, err := hc.Do(req) |
||||
require.NoError(t, err) |
||||
defer res.Body.Close() |
||||
|
||||
require.Equal(t, http.StatusNotFound, res.StatusCode) |
||||
} |
||||
|
||||
func TestWebRTCPublish(t *testing.T) { |
||||
for _, auth := range []string{ |
||||
"none", |
||||
"internal", |
||||
"external", |
||||
} { |
||||
t.Run("auth_"+auth, func(t *testing.T) { |
||||
var conf string |
||||
|
||||
switch auth { |
||||
case "none": |
||||
conf = "paths:\n" + |
||||
" all_others:\n" |
||||
|
||||
case "internal": |
||||
conf = "paths:\n" + |
||||
" all_others:\n" + |
||||
" publishUser: myuser\n" + |
||||
" publishPass: mypass\n" |
||||
|
||||
case "external": |
||||
conf = "externalAuthenticationURL: http://localhost:9120/auth\n" + |
||||
"paths:\n" + |
||||
" all_others:\n" |
||||
} |
||||
|
||||
p, ok := newInstance(conf) |
||||
require.Equal(t, true, ok) |
||||
defer p.Close() |
||||
|
||||
var a *testHTTPAuthenticator |
||||
if auth == "external" { |
||||
a = newTestHTTPAuthenticator(t, "webrtc", "publish") |
||||
} |
||||
|
||||
hc := &http.Client{Transport: &http.Transport{}} |
||||
|
||||
// preflight requests must always work, without authentication
|
||||
func() { |
||||
req, err := http.NewRequest(http.MethodOptions, "http://localhost:8889/teststream/whip", nil) |
||||
require.NoError(t, err) |
||||
|
||||
req.Header.Set("Access-Control-Request-Method", "OPTIONS") |
||||
|
||||
res, err := hc.Do(req) |
||||
require.NoError(t, err) |
||||
defer res.Body.Close() |
||||
|
||||
require.Equal(t, http.StatusNoContent, res.StatusCode) |
||||
|
||||
if auth != "none" { |
||||
_, ok := res.Header["Link"] |
||||
require.Equal(t, false, ok) |
||||
} |
||||
}() |
||||
|
||||
user := "" |
||||
pass := "" |
||||
|
||||
switch auth { |
||||
case "internal": |
||||
user = "myuser" |
||||
pass = "mypass" |
||||
|
||||
case "external": |
||||
user = "testpublisher" |
||||
pass = "testpass" |
||||
} |
||||
|
||||
ur := "http://" |
||||
if user != "" { |
||||
ur += user + ":" + pass + "@" |
||||
} |
||||
ur += "localhost:8889/teststream/whip?param=value" |
||||
|
||||
su, err := url.Parse(ur) |
||||
require.NoError(t, err) |
||||
|
||||
s := &webrtc.WHIPClient{ |
||||
HTTPClient: hc, |
||||
URL: su, |
||||
} |
||||
|
||||
tracks, err := s.Publish(context.Background(), testMediaH264.Formats[0], nil) |
||||
require.NoError(t, err) |
||||
defer checkClose(t, s.Close) |
||||
|
||||
err = tracks[0].WriteRTP(&rtp.Packet{ |
||||
Header: rtp.Header{ |
||||
Version: 2, |
||||
Marker: true, |
||||
PayloadType: 96, |
||||
SequenceNumber: 123, |
||||
Timestamp: 45343, |
||||
SSRC: 563423, |
||||
}, |
||||
Payload: []byte{1}, |
||||
}) |
||||
require.NoError(t, err) |
||||
|
||||
time.Sleep(200 * time.Millisecond) |
||||
|
||||
if auth == "external" { |
||||
a.close() |
||||
a = newTestHTTPAuthenticator(t, "rtsp", "read") |
||||
defer a.close() |
||||
} |
||||
|
||||
c := gortsplib.Client{ |
||||
OnDecodeError: func(err error) { |
||||
panic(err) |
||||
}, |
||||
} |
||||
|
||||
u, err := base.ParseURL("rtsp://testreader:testpass@127.0.0.1:8554/teststream?param=value") |
||||
require.NoError(t, err) |
||||
|
||||
err = c.Start(u.Scheme, u.Host) |
||||
require.NoError(t, err) |
||||
defer c.Close() |
||||
|
||||
desc, _, err := c.Describe(u) |
||||
require.NoError(t, err) |
||||
|
||||
var forma *format.H264 |
||||
medi := desc.FindFormat(&forma) |
||||
|
||||
_, err = c.Setup(desc.BaseURL, medi, 0, 0) |
||||
require.NoError(t, err) |
||||
|
||||
received := make(chan struct{}) |
||||
|
||||
c.OnPacketRTP(medi, forma, func(pkt *rtp.Packet) { |
||||
require.Equal(t, []byte{3}, pkt.Payload) |
||||
close(received) |
||||
}) |
||||
|
||||
_, err = c.Play(nil) |
||||
require.NoError(t, err) |
||||
|
||||
err = tracks[0].WriteRTP(&rtp.Packet{ |
||||
Header: rtp.Header{ |
||||
Version: 2, |
||||
Marker: true, |
||||
PayloadType: 96, |
||||
SequenceNumber: 124, |
||||
Timestamp: 45343, |
||||
SSRC: 563423, |
||||
}, |
||||
Payload: []byte{3}, |
||||
}) |
||||
require.NoError(t, err) |
||||
|
||||
<-received |
||||
}) |
||||
} |
||||
} |
||||
@ -0,0 +1,23 @@
@@ -0,0 +1,23 @@
|
||||
package defs |
||||
|
||||
// AuthProtocol is a authentication protocol.
|
||||
type AuthProtocol string |
||||
|
||||
// authentication protocols.
|
||||
const ( |
||||
AuthProtocolRTSP AuthProtocol = "rtsp" |
||||
AuthProtocolRTMP AuthProtocol = "rtmp" |
||||
AuthProtocolHLS AuthProtocol = "hls" |
||||
AuthProtocolWebRTC AuthProtocol = "webrtc" |
||||
AuthProtocolSRT AuthProtocol = "srt" |
||||
) |
||||
|
||||
// AuthenticationError is a authentication error.
|
||||
type AuthenticationError struct { |
||||
Message string |
||||
} |
||||
|
||||
// Error implements the error interface.
|
||||
func (e AuthenticationError) Error() string { |
||||
return "authentication failed: " + e.Message |
||||
} |
||||
@ -0,0 +1,9 @@
@@ -0,0 +1,9 @@
|
||||
package defs |
||||
|
||||
// PathManager is a path manager.
|
||||
type PathManager interface { |
||||
GetConfForPath(req PathGetConfForPathReq) PathGetConfForPathRes |
||||
Describe(req PathDescribeReq) PathDescribeRes |
||||
AddPublisher(req PathAddPublisherReq) PathAddPublisherRes |
||||
AddReader(req PathAddReaderReq) PathAddReaderRes |
||||
} |
||||
@ -1,594 +0,0 @@
@@ -1,594 +0,0 @@
|
||||
package playback |
||||
|
||||
import ( |
||||
"bytes" |
||||
"errors" |
||||
"fmt" |
||||
"io" |
||||
"time" |
||||
|
||||
"github.com/abema/go-mp4" |
||||
"github.com/bluenviron/mediacommon/pkg/formats/fmp4" |
||||
"github.com/bluenviron/mediacommon/pkg/formats/fmp4/seekablebuffer" |
||||
) |
||||
|
||||
const ( |
||||
sampleFlagIsNonSyncSample = 1 << 16 |
||||
concatenationTolerance = 1 * time.Second |
||||
fmp4Timescale = 90000 |
||||
) |
||||
|
||||
func durationGoToMp4(v time.Duration, timeScale uint32) uint64 { |
||||
timeScale64 := uint64(timeScale) |
||||
secs := v / time.Second |
||||
dec := v % time.Second |
||||
return uint64(secs)*timeScale64 + uint64(dec)*timeScale64/uint64(time.Second) |
||||
} |
||||
|
||||
func durationMp4ToGo(v uint64, timeScale uint32) time.Duration { |
||||
timeScale64 := uint64(timeScale) |
||||
secs := v / timeScale64 |
||||
dec := v % timeScale64 |
||||
return time.Duration(secs)*time.Second + time.Duration(dec)*time.Second/time.Duration(timeScale64) |
||||
} |
||||
|
||||
var errTerminated = errors.New("terminated") |
||||
|
||||
func fmp4CanBeConcatenated( |
||||
prevInit []byte, |
||||
prevEnd time.Time, |
||||
curInit []byte, |
||||
curStart time.Time, |
||||
) bool { |
||||
return bytes.Equal(prevInit, curInit) && |
||||
!curStart.Before(prevEnd.Add(-concatenationTolerance)) && |
||||
!curStart.After(prevEnd.Add(concatenationTolerance)) |
||||
} |
||||
|
||||
func fmp4ReadInit(r io.ReadSeeker) ([]byte, error) { |
||||
buf := make([]byte, 8) |
||||
_, err := io.ReadFull(r, buf) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
// find ftyp
|
||||
|
||||
if !bytes.Equal(buf[4:], []byte{'f', 't', 'y', 'p'}) { |
||||
return nil, fmt.Errorf("ftyp box not found") |
||||
} |
||||
|
||||
ftypSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3]) |
||||
|
||||
_, err = r.Seek(int64(ftypSize), io.SeekStart) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
// find moov
|
||||
|
||||
_, err = io.ReadFull(r, buf) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
if !bytes.Equal(buf[4:], []byte{'m', 'o', 'o', 'v'}) { |
||||
return nil, fmt.Errorf("moov box not found") |
||||
} |
||||
|
||||
moovSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3]) |
||||
|
||||
_, err = r.Seek(0, io.SeekStart) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
// return ftyp and moov
|
||||
|
||||
buf = make([]byte, ftypSize+moovSize) |
||||
|
||||
_, err = io.ReadFull(r, buf) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
return buf, nil |
||||
} |
||||
|
||||
func fmp4ReadDuration(r io.ReadSeeker) (time.Duration, error) { |
||||
// find and skip ftyp
|
||||
|
||||
buf := make([]byte, 8) |
||||
_, err := io.ReadFull(r, buf) |
||||
if err != nil { |
||||
return 0, err |
||||
} |
||||
|
||||
if !bytes.Equal(buf[4:], []byte{'f', 't', 'y', 'p'}) { |
||||
return 0, fmt.Errorf("ftyp box not found") |
||||
} |
||||
|
||||
ftypSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3]) |
||||
|
||||
_, err = r.Seek(int64(ftypSize), io.SeekStart) |
||||
if err != nil { |
||||
return 0, err |
||||
} |
||||
|
||||
// find and skip moov
|
||||
|
||||
_, err = io.ReadFull(r, buf) |
||||
if err != nil { |
||||
return 0, err |
||||
} |
||||
|
||||
if !bytes.Equal(buf[4:], []byte{'m', 'o', 'o', 'v'}) { |
||||
return 0, fmt.Errorf("moov box not found") |
||||
} |
||||
|
||||
moovSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3]) |
||||
|
||||
_, err = r.Seek(int64(moovSize)-8, io.SeekCurrent) |
||||
if err != nil { |
||||
return 0, err |
||||
} |
||||
|
||||
// find last valid moof and mdat
|
||||
|
||||
lastMoofPos := int64(-1) |
||||
|
||||
for { |
||||
moofPos, err := r.Seek(0, io.SeekCurrent) |
||||
if err != nil { |
||||
return 0, err |
||||
} |
||||
|
||||
_, err = io.ReadFull(r, buf) |
||||
if err != nil { |
||||
break |
||||
} |
||||
|
||||
if !bytes.Equal(buf[4:], []byte{'m', 'o', 'o', 'f'}) { |
||||
return 0, fmt.Errorf("moof box not found") |
||||
} |
||||
|
||||
moofSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3]) |
||||
|
||||
_, err = r.Seek(int64(moofSize)-8, io.SeekCurrent) |
||||
if err != nil { |
||||
break |
||||
} |
||||
|
||||
_, err = io.ReadFull(r, buf) |
||||
if err != nil { |
||||
break |
||||
} |
||||
|
||||
if !bytes.Equal(buf[4:], []byte{'m', 'd', 'a', 't'}) { |
||||
return 0, fmt.Errorf("mdat box not found") |
||||
} |
||||
|
||||
mdatSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3]) |
||||
|
||||
_, err = r.Seek(int64(mdatSize)-8, io.SeekCurrent) |
||||
if err != nil { |
||||
break |
||||
} |
||||
|
||||
lastMoofPos = moofPos |
||||
} |
||||
|
||||
if lastMoofPos < 0 { |
||||
return 0, fmt.Errorf("no moof boxes found") |
||||
} |
||||
|
||||
// open last moof
|
||||
|
||||
_, err = r.Seek(lastMoofPos+8, io.SeekStart) |
||||
if err != nil { |
||||
return 0, err |
||||
} |
||||
|
||||
_, err = io.ReadFull(r, buf) |
||||
if err != nil { |
||||
return 0, err |
||||
} |
||||
|
||||
// skip mfhd
|
||||
|
||||
if !bytes.Equal(buf[4:], []byte{'m', 'f', 'h', 'd'}) { |
||||
return 0, fmt.Errorf("mfhd box not found") |
||||
} |
||||
|
||||
_, err = r.Seek(8, io.SeekCurrent) |
||||
if err != nil { |
||||
return 0, err |
||||
} |
||||
|
||||
maxElapsed := uint64(0) |
||||
|
||||
// foreach traf
|
||||
|
||||
for { |
||||
_, err := io.ReadFull(r, buf) |
||||
if err != nil { |
||||
return 0, err |
||||
} |
||||
|
||||
if !bytes.Equal(buf[4:], []byte{'t', 'r', 'a', 'f'}) { |
||||
if bytes.Equal(buf[4:], []byte{'m', 'd', 'a', 't'}) { |
||||
break |
||||
} |
||||
return 0, fmt.Errorf("traf box not found") |
||||
} |
||||
|
||||
// skip tfhd
|
||||
|
||||
_, err = io.ReadFull(r, buf) |
||||
if err != nil { |
||||
return 0, err |
||||
} |
||||
|
||||
if !bytes.Equal(buf[4:], []byte{'t', 'f', 'h', 'd'}) { |
||||
return 0, fmt.Errorf("tfhd box not found") |
||||
} |
||||
|
||||
tfhdSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3]) |
||||
|
||||
_, err = r.Seek(int64(tfhdSize)-8, io.SeekCurrent) |
||||
if err != nil { |
||||
return 0, err |
||||
} |
||||
|
||||
// parse tfdt
|
||||
|
||||
_, err = io.ReadFull(r, buf) |
||||
if err != nil { |
||||
return 0, err |
||||
} |
||||
|
||||
if !bytes.Equal(buf[4:], []byte{'t', 'f', 'd', 't'}) { |
||||
return 0, fmt.Errorf("tfdt box not found") |
||||
} |
||||
|
||||
tfdtSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3]) |
||||
|
||||
buf2 := make([]byte, tfdtSize-8) |
||||
|
||||
_, err = io.ReadFull(r, buf2) |
||||
if err != nil { |
||||
return 0, err |
||||
} |
||||
|
||||
var tfdt mp4.Tfdt |
||||
_, err = mp4.Unmarshal(bytes.NewReader(buf2), uint64(len(buf2)), &tfdt, mp4.Context{}) |
||||
if err != nil { |
||||
return 0, fmt.Errorf("invalid tfdt box: %w", err) |
||||
} |
||||
|
||||
elapsed := tfdt.BaseMediaDecodeTimeV1 |
||||
|
||||
// parse trun
|
||||
|
||||
_, err = io.ReadFull(r, buf) |
||||
if err != nil { |
||||
return 0, err |
||||
} |
||||
|
||||
if !bytes.Equal(buf[4:], []byte{'t', 'r', 'u', 'n'}) { |
||||
return 0, fmt.Errorf("trun box not found") |
||||
} |
||||
|
||||
trunSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3]) |
||||
|
||||
buf2 = make([]byte, trunSize-8) |
||||
|
||||
_, err = io.ReadFull(r, buf2) |
||||
if err != nil { |
||||
return 0, err |
||||
} |
||||
|
||||
var trun mp4.Trun |
||||
_, err = mp4.Unmarshal(bytes.NewReader(buf2), uint64(len(buf2)), &trun, mp4.Context{}) |
||||
if err != nil { |
||||
return 0, fmt.Errorf("invalid trun box: %w", err) |
||||
} |
||||
|
||||
for _, entry := range trun.Entries { |
||||
elapsed += uint64(entry.SampleDuration) |
||||
} |
||||
|
||||
if elapsed > maxElapsed { |
||||
maxElapsed = elapsed |
||||
} |
||||
} |
||||
|
||||
return durationMp4ToGo(maxElapsed, fmp4Timescale), nil |
||||
} |
||||
|
||||
func fmp4SeekAndMuxParts( |
||||
r io.ReadSeeker, |
||||
init []byte, |
||||
minTime time.Duration, |
||||
maxTime time.Duration, |
||||
w io.Writer, |
||||
) (time.Duration, error) { |
||||
minTimeMP4 := durationGoToMp4(minTime, fmp4Timescale) |
||||
maxTimeMP4 := durationGoToMp4(maxTime, fmp4Timescale) |
||||
moofOffset := uint64(0) |
||||
var tfhd *mp4.Tfhd |
||||
var tfdt *mp4.Tfdt |
||||
var outPart *fmp4.Part |
||||
var outTrack *fmp4.PartTrack |
||||
var outBuf seekablebuffer.Buffer |
||||
elapsed := uint64(0) |
||||
initWritten := false |
||||
firstSampleWritten := make(map[uint32]struct{}) |
||||
gop := make(map[uint32][]*fmp4.PartSample) |
||||
|
||||
_, err := mp4.ReadBoxStructure(r, func(h *mp4.ReadHandle) (interface{}, error) { |
||||
switch h.BoxInfo.Type.String() { |
||||
case "moof": |
||||
moofOffset = h.BoxInfo.Offset |
||||
outPart = &fmp4.Part{} |
||||
return h.Expand() |
||||
|
||||
case "traf": |
||||
return h.Expand() |
||||
|
||||
case "tfhd": |
||||
box, _, err := h.ReadPayload() |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
tfhd = box.(*mp4.Tfhd) |
||||
|
||||
case "tfdt": |
||||
box, _, err := h.ReadPayload() |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
tfdt = box.(*mp4.Tfdt) |
||||
|
||||
if tfdt.BaseMediaDecodeTimeV1 >= maxTimeMP4 { |
||||
return nil, errTerminated |
||||
} |
||||
|
||||
outTrack = &fmp4.PartTrack{ID: int(tfhd.TrackID)} |
||||
|
||||
case "trun": |
||||
box, _, err := h.ReadPayload() |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
trun := box.(*mp4.Trun) |
||||
|
||||
dataOffset := moofOffset + uint64(trun.DataOffset) |
||||
|
||||
_, err = r.Seek(int64(dataOffset), io.SeekStart) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
elapsed = tfdt.BaseMediaDecodeTimeV1 |
||||
baseTimeSet := false |
||||
|
||||
for _, e := range trun.Entries { |
||||
payload := make([]byte, e.SampleSize) |
||||
_, err := io.ReadFull(r, payload) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
if elapsed >= maxTimeMP4 { |
||||
break |
||||
} |
||||
|
||||
isRandom := (e.SampleFlags & sampleFlagIsNonSyncSample) == 0 |
||||
_, fsw := firstSampleWritten[tfhd.TrackID] |
||||
|
||||
sa := &fmp4.PartSample{ |
||||
Duration: e.SampleDuration, |
||||
PTSOffset: e.SampleCompositionTimeOffsetV1, |
||||
IsNonSyncSample: !isRandom, |
||||
Payload: payload, |
||||
} |
||||
|
||||
if !fsw { |
||||
if isRandom { |
||||
gop[tfhd.TrackID] = []*fmp4.PartSample{sa} |
||||
} else { |
||||
gop[tfhd.TrackID] = append(gop[tfhd.TrackID], sa) |
||||
} |
||||
} |
||||
|
||||
if elapsed >= minTimeMP4 { |
||||
if !baseTimeSet { |
||||
outTrack.BaseTime = elapsed - minTimeMP4 |
||||
|
||||
if !fsw { |
||||
if !isRandom { |
||||
for _, sa2 := range gop[tfhd.TrackID][:len(gop[tfhd.TrackID])-1] { |
||||
sa2.Duration = 0 |
||||
sa2.PTSOffset = 0 |
||||
outTrack.Samples = append(outTrack.Samples, sa2) |
||||
} |
||||
} |
||||
|
||||
delete(gop, tfhd.TrackID) |
||||
firstSampleWritten[tfhd.TrackID] = struct{}{} |
||||
} |
||||
} |
||||
|
||||
outTrack.Samples = append(outTrack.Samples, sa) |
||||
} |
||||
|
||||
elapsed += uint64(e.SampleDuration) |
||||
} |
||||
|
||||
if outTrack.Samples != nil { |
||||
outPart.Tracks = append(outPart.Tracks, outTrack) |
||||
} |
||||
|
||||
outTrack = nil |
||||
|
||||
case "mdat": |
||||
if outPart.Tracks != nil { |
||||
if !initWritten { |
||||
initWritten = true |
||||
_, err := w.Write(init) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
} |
||||
|
||||
err := outPart.Marshal(&outBuf) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
_, err = w.Write(outBuf.Bytes()) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
outBuf.Reset() |
||||
} |
||||
|
||||
outPart = nil |
||||
} |
||||
return nil, nil |
||||
}) |
||||
if err != nil && !errors.Is(err, errTerminated) { |
||||
return 0, err |
||||
} |
||||
|
||||
if !initWritten { |
||||
return 0, errNoSegmentsFound |
||||
} |
||||
|
||||
elapsed -= minTimeMP4 |
||||
|
||||
return durationMp4ToGo(elapsed, fmp4Timescale), nil |
||||
} |
||||
|
||||
func fmp4MuxParts( |
||||
r io.ReadSeeker, |
||||
startTime time.Duration, |
||||
maxTime time.Duration, |
||||
w io.Writer, |
||||
) (time.Duration, error) { |
||||
maxTimeMP4 := durationGoToMp4(maxTime, fmp4Timescale) |
||||
moofOffset := uint64(0) |
||||
var tfhd *mp4.Tfhd |
||||
var tfdt *mp4.Tfdt |
||||
var outPart *fmp4.Part |
||||
var outTrack *fmp4.PartTrack |
||||
var outBuf seekablebuffer.Buffer |
||||
elapsed := uint64(0) |
||||
|
||||
_, err := mp4.ReadBoxStructure(r, func(h *mp4.ReadHandle) (interface{}, error) { |
||||
switch h.BoxInfo.Type.String() { |
||||
case "moof": |
||||
moofOffset = h.BoxInfo.Offset |
||||
outPart = &fmp4.Part{} |
||||
return h.Expand() |
||||
|
||||
case "traf": |
||||
return h.Expand() |
||||
|
||||
case "tfhd": |
||||
box, _, err := h.ReadPayload() |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
tfhd = box.(*mp4.Tfhd) |
||||
|
||||
case "tfdt": |
||||
box, _, err := h.ReadPayload() |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
tfdt = box.(*mp4.Tfdt) |
||||
|
||||
if tfdt.BaseMediaDecodeTimeV1 >= maxTimeMP4 { |
||||
return nil, errTerminated |
||||
} |
||||
|
||||
outTrack = &fmp4.PartTrack{ |
||||
ID: int(tfhd.TrackID), |
||||
BaseTime: tfdt.BaseMediaDecodeTimeV1 + durationGoToMp4(startTime, fmp4Timescale), |
||||
} |
||||
|
||||
case "trun": |
||||
box, _, err := h.ReadPayload() |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
trun := box.(*mp4.Trun) |
||||
|
||||
dataOffset := moofOffset + uint64(trun.DataOffset) |
||||
|
||||
_, err = r.Seek(int64(dataOffset), io.SeekStart) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
elapsed = tfdt.BaseMediaDecodeTimeV1 |
||||
|
||||
for _, e := range trun.Entries { |
||||
payload := make([]byte, e.SampleSize) |
||||
_, err := io.ReadFull(r, payload) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
if elapsed >= maxTimeMP4 { |
||||
break |
||||
} |
||||
|
||||
isRandom := (e.SampleFlags & sampleFlagIsNonSyncSample) == 0 |
||||
|
||||
sa := &fmp4.PartSample{ |
||||
Duration: e.SampleDuration, |
||||
PTSOffset: e.SampleCompositionTimeOffsetV1, |
||||
IsNonSyncSample: !isRandom, |
||||
Payload: payload, |
||||
} |
||||
|
||||
outTrack.Samples = append(outTrack.Samples, sa) |
||||
|
||||
elapsed += uint64(e.SampleDuration) |
||||
} |
||||
|
||||
if outTrack.Samples != nil { |
||||
outPart.Tracks = append(outPart.Tracks, outTrack) |
||||
} |
||||
|
||||
outTrack = nil |
||||
|
||||
case "mdat": |
||||
if outPart.Tracks != nil { |
||||
err := outPart.Marshal(&outBuf) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
_, err = w.Write(outBuf.Bytes()) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
outBuf.Reset() |
||||
} |
||||
|
||||
outPart = nil |
||||
} |
||||
return nil, nil |
||||
}) |
||||
if err != nil && !errors.Is(err, errTerminated) { |
||||
return 0, err |
||||
} |
||||
|
||||
return durationMp4ToGo(elapsed, fmp4Timescale), nil |
||||
} |
||||
@ -1,75 +0,0 @@
@@ -1,75 +0,0 @@
|
||||
package playback |
||||
|
||||
import ( |
||||
"io" |
||||
"os" |
||||
"testing" |
||||
|
||||
"github.com/bluenviron/mediacommon/pkg/codecs/mpeg4audio" |
||||
"github.com/bluenviron/mediacommon/pkg/formats/fmp4" |
||||
"github.com/bluenviron/mediamtx/internal/test" |
||||
) |
||||
|
||||
func writeBenchInit(f io.WriteSeeker) { |
||||
init := fmp4.Init{ |
||||
Tracks: []*fmp4.InitTrack{ |
||||
{ |
||||
ID: 1, |
||||
TimeScale: 90000, |
||||
Codec: &fmp4.CodecH264{ |
||||
SPS: test.FormatH264.SPS, |
||||
PPS: test.FormatH264.PPS, |
||||
}, |
||||
}, |
||||
{ |
||||
ID: 2, |
||||
TimeScale: 90000, |
||||
Codec: &fmp4.CodecMPEG4Audio{ |
||||
Config: mpeg4audio.Config{ |
||||
Type: mpeg4audio.ObjectTypeAACLC, |
||||
SampleRate: 48000, |
||||
ChannelCount: 2, |
||||
}, |
||||
}, |
||||
}, |
||||
}, |
||||
} |
||||
|
||||
err := init.Marshal(f) |
||||
if err != nil { |
||||
panic(err) |
||||
} |
||||
|
||||
_, err = f.Write([]byte{ |
||||
'm', 'o', 'o', 'f', 0x00, 0x00, 0x00, 0x10, |
||||
}) |
||||
if err != nil { |
||||
panic(err) |
||||
} |
||||
} |
||||
|
||||
func BenchmarkFMP4ReadInit(b *testing.B) { |
||||
f, err := os.CreateTemp(os.TempDir(), "mediamtx-playback-fmp4-") |
||||
if err != nil { |
||||
panic(err) |
||||
} |
||||
defer os.Remove(f.Name()) |
||||
|
||||
writeBenchInit(f) |
||||
f.Close() |
||||
|
||||
for n := 0; n < b.N; n++ { |
||||
func() { |
||||
f, err := os.Open(f.Name()) |
||||
if err != nil { |
||||
panic(err) |
||||
} |
||||
defer f.Close() |
||||
|
||||
_, err = fmp4ReadInit(f) |
||||
if err != nil { |
||||
panic(err) |
||||
} |
||||
}() |
||||
} |
||||
} |
||||
@ -1,179 +0,0 @@
@@ -1,179 +0,0 @@
|
||||
package playback |
||||
|
||||
import ( |
||||
"errors" |
||||
"fmt" |
||||
"io" |
||||
"net" |
||||
"net/http" |
||||
"os" |
||||
"strconv" |
||||
"time" |
||||
|
||||
"github.com/bluenviron/mediamtx/internal/conf" |
||||
"github.com/bluenviron/mediamtx/internal/logger" |
||||
"github.com/gin-gonic/gin" |
||||
) |
||||
|
||||
var errStopIteration = errors.New("stop iteration") |
||||
|
||||
func parseDuration(raw string) (time.Duration, error) { |
||||
// seconds
|
||||
if secs, err := strconv.ParseFloat(raw, 64); err == nil { |
||||
return time.Duration(secs * float64(time.Second)), nil |
||||
} |
||||
|
||||
// deprecated, golang format
|
||||
return time.ParseDuration(raw) |
||||
} |
||||
|
||||
func seekAndMux( |
||||
recordFormat conf.RecordFormat, |
||||
segments []*Segment, |
||||
start time.Time, |
||||
duration time.Duration, |
||||
w io.Writer, |
||||
) error { |
||||
if recordFormat == conf.RecordFormatFMP4 { |
||||
minTime := start.Sub(segments[0].Start) |
||||
maxTime := minTime + duration |
||||
var init []byte |
||||
var elapsed time.Duration |
||||
|
||||
err := func() error { |
||||
f, err := os.Open(segments[0].Fpath) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
defer f.Close() |
||||
|
||||
init, err = fmp4ReadInit(f) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
elapsed, err = fmp4SeekAndMuxParts(f, init, minTime, maxTime, w) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
return nil |
||||
}() |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
prevInit := init |
||||
prevEnd := start.Add(elapsed) |
||||
duration -= elapsed |
||||
overallElapsed := elapsed |
||||
|
||||
for _, seg := range segments[1:] { |
||||
err := func() error { |
||||
f, err := os.Open(seg.Fpath) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
defer f.Close() |
||||
|
||||
init, err := fmp4ReadInit(f) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
if !fmp4CanBeConcatenated(prevInit, prevEnd, init, seg.Start) { |
||||
return errStopIteration |
||||
} |
||||
|
||||
elapsed, err = fmp4MuxParts(f, overallElapsed, duration, w) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
return nil |
||||
}() |
||||
if err != nil { |
||||
if errors.Is(err, errStopIteration) { |
||||
return nil |
||||
} |
||||
|
||||
return err |
||||
} |
||||
|
||||
prevEnd = seg.Start.Add(elapsed) |
||||
duration -= elapsed |
||||
overallElapsed += elapsed |
||||
} |
||||
|
||||
return nil |
||||
} |
||||
|
||||
return fmt.Errorf("MPEG-TS format is not supported yet") |
||||
} |
||||
|
||||
func (p *Server) onGet(ctx *gin.Context) { |
||||
pathName := ctx.Query("path") |
||||
|
||||
if !p.doAuth(ctx, pathName) { |
||||
return |
||||
} |
||||
|
||||
start, err := time.Parse(time.RFC3339, ctx.Query("start")) |
||||
if err != nil { |
||||
p.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid start: %w", err)) |
||||
return |
||||
} |
||||
|
||||
duration, err := parseDuration(ctx.Query("duration")) |
||||
if err != nil { |
||||
p.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid duration: %w", err)) |
||||
return |
||||
} |
||||
|
||||
format := ctx.Query("format") |
||||
if format != "" && format != "fmp4" { |
||||
p.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid format: %s", format)) |
||||
return |
||||
} |
||||
|
||||
pathConf, err := p.safeFindPathConf(pathName) |
||||
if err != nil { |
||||
p.writeError(ctx, http.StatusBadRequest, err) |
||||
return |
||||
} |
||||
|
||||
segments, err := findSegmentsInTimespan(pathConf, pathName, start, duration) |
||||
if err != nil { |
||||
if errors.Is(err, errNoSegmentsFound) { |
||||
p.writeError(ctx, http.StatusNotFound, err) |
||||
} else { |
||||
p.writeError(ctx, http.StatusBadRequest, err) |
||||
} |
||||
return |
||||
} |
||||
|
||||
ww := &writerWrapper{ctx: ctx} |
||||
|
||||
err = seekAndMux(pathConf.RecordFormat, segments, start, duration, ww) |
||||
if err != nil { |
||||
// user aborted the download
|
||||
var neterr *net.OpError |
||||
if errors.As(err, &neterr) { |
||||
return |
||||
} |
||||
|
||||
// nothing has been written yet; send back JSON
|
||||
if !ww.written { |
||||
if errors.Is(err, errNoSegmentsFound) { |
||||
p.writeError(ctx, http.StatusNotFound, err) |
||||
} else { |
||||
p.writeError(ctx, http.StatusBadRequest, err) |
||||
} |
||||
return |
||||
} |
||||
|
||||
// something has already been written: abort and write logs only
|
||||
p.Log(logger.Error, err.Error()) |
||||
return |
||||
} |
||||
} |
||||
@ -1,374 +0,0 @@
@@ -1,374 +0,0 @@
|
||||
package playback |
||||
|
||||
import ( |
||||
"io" |
||||
"net/http" |
||||
"net/url" |
||||
"os" |
||||
"path/filepath" |
||||
"testing" |
||||
"time" |
||||
|
||||
"github.com/bluenviron/mediacommon/pkg/codecs/mpeg4audio" |
||||
"github.com/bluenviron/mediacommon/pkg/formats/fmp4" |
||||
"github.com/bluenviron/mediacommon/pkg/formats/fmp4/seekablebuffer" |
||||
"github.com/bluenviron/mediamtx/internal/auth" |
||||
"github.com/bluenviron/mediamtx/internal/conf" |
||||
"github.com/bluenviron/mediamtx/internal/test" |
||||
"github.com/stretchr/testify/require" |
||||
) |
||||
|
||||
func writeSegment1(t *testing.T, fpath string) { |
||||
init := fmp4.Init{ |
||||
Tracks: []*fmp4.InitTrack{ |
||||
{ |
||||
ID: 1, |
||||
TimeScale: 90000, |
||||
Codec: &fmp4.CodecH264{ |
||||
SPS: test.FormatH264.SPS, |
||||
PPS: test.FormatH264.PPS, |
||||
}, |
||||
}, |
||||
{ |
||||
ID: 2, |
||||
TimeScale: 90000, |
||||
Codec: &fmp4.CodecMPEG4Audio{ |
||||
Config: mpeg4audio.Config{ |
||||
Type: mpeg4audio.ObjectTypeAACLC, |
||||
SampleRate: 48000, |
||||
ChannelCount: 2, |
||||
}, |
||||
}, |
||||
}, |
||||
}, |
||||
} |
||||
|
||||
var buf1 seekablebuffer.Buffer |
||||
err := init.Marshal(&buf1) |
||||
require.NoError(t, err) |
||||
|
||||
var buf2 seekablebuffer.Buffer |
||||
parts := fmp4.Parts{ |
||||
{ |
||||
SequenceNumber: 1, |
||||
Tracks: []*fmp4.PartTrack{{ |
||||
ID: 1, |
||||
BaseTime: 0, |
||||
Samples: []*fmp4.PartSample{}, |
||||
}}, |
||||
}, |
||||
{ |
||||
SequenceNumber: 1, |
||||
Tracks: []*fmp4.PartTrack{{ |
||||
ID: 1, |
||||
BaseTime: 30 * 90000, |
||||
Samples: []*fmp4.PartSample{ |
||||
{ |
||||
Duration: 30 * 90000, |
||||
IsNonSyncSample: false, |
||||
Payload: []byte{1, 2}, |
||||
}, |
||||
{ |
||||
Duration: 1 * 90000, |
||||
IsNonSyncSample: false, |
||||
Payload: []byte{3, 4}, |
||||
}, |
||||
{ |
||||
Duration: 1 * 90000, |
||||
IsNonSyncSample: true, |
||||
Payload: []byte{5, 6}, |
||||
}, |
||||
}, |
||||
}}, |
||||
}, |
||||
} |
||||
err = parts.Marshal(&buf2) |
||||
require.NoError(t, err) |
||||
|
||||
err = os.WriteFile(fpath, append(buf1.Bytes(), buf2.Bytes()...), 0o644) |
||||
require.NoError(t, err) |
||||
} |
||||
|
||||
func writeSegment2(t *testing.T, fpath string) { |
||||
init := fmp4.Init{ |
||||
Tracks: []*fmp4.InitTrack{ |
||||
{ |
||||
ID: 1, |
||||
TimeScale: 90000, |
||||
Codec: &fmp4.CodecH264{ |
||||
SPS: test.FormatH264.SPS, |
||||
PPS: test.FormatH264.PPS, |
||||
}, |
||||
}, |
||||
{ |
||||
ID: 2, |
||||
TimeScale: 90000, |
||||
Codec: &fmp4.CodecMPEG4Audio{ |
||||
Config: mpeg4audio.Config{ |
||||
Type: mpeg4audio.ObjectTypeAACLC, |
||||
SampleRate: 48000, |
||||
ChannelCount: 2, |
||||
}, |
||||
}, |
||||
}, |
||||
}, |
||||
} |
||||
|
||||
var buf1 seekablebuffer.Buffer |
||||
err := init.Marshal(&buf1) |
||||
require.NoError(t, err) |
||||
|
||||
var buf2 seekablebuffer.Buffer |
||||
parts := fmp4.Parts{ |
||||
{ |
||||
SequenceNumber: 1, |
||||
Tracks: []*fmp4.PartTrack{{ |
||||
ID: 1, |
||||
BaseTime: 0, |
||||
Samples: []*fmp4.PartSample{ |
||||
{ |
||||
Duration: 1 * 90000, |
||||
IsNonSyncSample: false, |
||||
Payload: []byte{7, 8}, |
||||
}, |
||||
{ |
||||
Duration: 1 * 90000, |
||||
IsNonSyncSample: false, |
||||
Payload: []byte{9, 10}, |
||||
}, |
||||
}, |
||||
}}, |
||||
}, |
||||
} |
||||
err = parts.Marshal(&buf2) |
||||
require.NoError(t, err) |
||||
|
||||
err = os.WriteFile(fpath, append(buf1.Bytes(), buf2.Bytes()...), 0o644) |
||||
require.NoError(t, err) |
||||
} |
||||
|
||||
func writeSegment3(t *testing.T, fpath string) { |
||||
init := fmp4.Init{ |
||||
Tracks: []*fmp4.InitTrack{ |
||||
{ |
||||
ID: 1, |
||||
TimeScale: 90000, |
||||
Codec: &fmp4.CodecH264{ |
||||
SPS: test.FormatH264.SPS, |
||||
PPS: test.FormatH264.PPS, |
||||
}, |
||||
}, |
||||
}, |
||||
} |
||||
|
||||
var buf1 seekablebuffer.Buffer |
||||
err := init.Marshal(&buf1) |
||||
require.NoError(t, err) |
||||
|
||||
var buf2 seekablebuffer.Buffer |
||||
parts := fmp4.Parts{ |
||||
{ |
||||
SequenceNumber: 1, |
||||
Tracks: []*fmp4.PartTrack{{ |
||||
ID: 1, |
||||
BaseTime: 0, |
||||
Samples: []*fmp4.PartSample{ |
||||
{ |
||||
Duration: 1 * 90000, |
||||
IsNonSyncSample: false, |
||||
Payload: []byte{10, 11}, |
||||
}, |
||||
}, |
||||
}}, |
||||
}, |
||||
} |
||||
err = parts.Marshal(&buf2) |
||||
require.NoError(t, err) |
||||
|
||||
err = os.WriteFile(fpath, append(buf1.Bytes(), buf2.Bytes()...), 0o644) |
||||
require.NoError(t, err) |
||||
} |
||||
|
||||
var authManager = &auth.Manager{ |
||||
Method: conf.AuthMethodInternal, |
||||
InternalUsers: []conf.AuthInternalUser{ |
||||
{ |
||||
User: "myuser", |
||||
Pass: "mypass", |
||||
Permissions: []conf.AuthInternalUserPermission{ |
||||
{ |
||||
Action: conf.AuthActionPlayback, |
||||
Path: "mypath", |
||||
}, |
||||
}, |
||||
}, |
||||
}, |
||||
RTSPAuthMethods: nil, |
||||
} |
||||
|
||||
func TestOnGet(t *testing.T) { |
||||
dir, err := os.MkdirTemp("", "mediamtx-playback") |
||||
require.NoError(t, err) |
||||
defer os.RemoveAll(dir) |
||||
|
||||
err = os.Mkdir(filepath.Join(dir, "mypath"), 0o755) |
||||
require.NoError(t, err) |
||||
|
||||
writeSegment1(t, filepath.Join(dir, "mypath", "2008-11-07_11-22-00-500000.mp4")) |
||||
writeSegment2(t, filepath.Join(dir, "mypath", "2008-11-07_11-23-02-500000.mp4")) |
||||
|
||||
s := &Server{ |
||||
Address: "127.0.0.1:9996", |
||||
ReadTimeout: conf.StringDuration(10 * time.Second), |
||||
PathConfs: map[string]*conf.Path{ |
||||
"mypath": { |
||||
Playback: true, |
||||
RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), |
||||
}, |
||||
}, |
||||
AuthManager: authManager, |
||||
Parent: &test.NilLogger{}, |
||||
} |
||||
err = s.Initialize() |
||||
require.NoError(t, err) |
||||
defer s.Close() |
||||
|
||||
u, err := url.Parse("http://myuser:mypass@localhost:9996/get") |
||||
require.NoError(t, err) |
||||
|
||||
v := url.Values{} |
||||
v.Set("path", "mypath") |
||||
v.Set("start", time.Date(2008, 11, 0o7, 11, 23, 1, 500000000, time.Local).Format(time.RFC3339Nano)) |
||||
v.Set("duration", "2") |
||||
v.Set("format", "fmp4") |
||||
u.RawQuery = v.Encode() |
||||
|
||||
req, err := http.NewRequest(http.MethodGet, u.String(), nil) |
||||
require.NoError(t, err) |
||||
|
||||
res, err := http.DefaultClient.Do(req) |
||||
require.NoError(t, err) |
||||
defer res.Body.Close() |
||||
|
||||
require.Equal(t, http.StatusOK, res.StatusCode) |
||||
|
||||
buf, err := io.ReadAll(res.Body) |
||||
require.NoError(t, err) |
||||
|
||||
var parts fmp4.Parts |
||||
err = parts.Unmarshal(buf) |
||||
require.NoError(t, err) |
||||
|
||||
require.Equal(t, fmp4.Parts{ |
||||
{ |
||||
SequenceNumber: 0, |
||||
Tracks: []*fmp4.PartTrack{ |
||||
{ |
||||
ID: 1, |
||||
Samples: []*fmp4.PartSample{ |
||||
{ |
||||
Duration: 0, |
||||
Payload: []byte{3, 4}, |
||||
}, |
||||
{ |
||||
Duration: 90000, |
||||
IsNonSyncSample: true, |
||||
Payload: []byte{5, 6}, |
||||
}, |
||||
}, |
||||
}, |
||||
}, |
||||
}, |
||||
{ |
||||
SequenceNumber: 0, |
||||
Tracks: []*fmp4.PartTrack{ |
||||
{ |
||||
ID: 1, |
||||
BaseTime: 90000, |
||||
Samples: []*fmp4.PartSample{ |
||||
{ |
||||
Duration: 90000, |
||||
Payload: []byte{7, 8}, |
||||
}, |
||||
}, |
||||
}, |
||||
}, |
||||
}, |
||||
}, parts) |
||||
} |
||||
|
||||
func TestOnGetDifferentInit(t *testing.T) { |
||||
dir, err := os.MkdirTemp("", "mediamtx-playback") |
||||
require.NoError(t, err) |
||||
defer os.RemoveAll(dir) |
||||
|
||||
err = os.Mkdir(filepath.Join(dir, "mypath"), 0o755) |
||||
require.NoError(t, err) |
||||
|
||||
writeSegment1(t, filepath.Join(dir, "mypath", "2008-11-07_11-22-00-500000.mp4")) |
||||
writeSegment3(t, filepath.Join(dir, "mypath", "2008-11-07_11-23-02-500000.mp4")) |
||||
|
||||
s := &Server{ |
||||
Address: "127.0.0.1:9996", |
||||
ReadTimeout: conf.StringDuration(10 * time.Second), |
||||
PathConfs: map[string]*conf.Path{ |
||||
"mypath": { |
||||
Playback: true, |
||||
RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), |
||||
}, |
||||
}, |
||||
AuthManager: authManager, |
||||
Parent: &test.NilLogger{}, |
||||
} |
||||
err = s.Initialize() |
||||
require.NoError(t, err) |
||||
defer s.Close() |
||||
|
||||
u, err := url.Parse("http://myuser:mypass@localhost:9996/get") |
||||
require.NoError(t, err) |
||||
|
||||
v := url.Values{} |
||||
v.Set("path", "mypath") |
||||
v.Set("start", time.Date(2008, 11, 0o7, 11, 23, 1, 500000000, time.Local).Format(time.RFC3339Nano)) |
||||
v.Set("duration", "2") |
||||
v.Set("format", "fmp4") |
||||
u.RawQuery = v.Encode() |
||||
|
||||
req, err := http.NewRequest(http.MethodGet, u.String(), nil) |
||||
require.NoError(t, err) |
||||
|
||||
res, err := http.DefaultClient.Do(req) |
||||
require.NoError(t, err) |
||||
defer res.Body.Close() |
||||
|
||||
require.Equal(t, http.StatusOK, res.StatusCode) |
||||
|
||||
buf, err := io.ReadAll(res.Body) |
||||
require.NoError(t, err) |
||||
|
||||
var parts fmp4.Parts |
||||
err = parts.Unmarshal(buf) |
||||
require.NoError(t, err) |
||||
|
||||
require.Equal(t, fmp4.Parts{ |
||||
{ |
||||
SequenceNumber: 0, |
||||
Tracks: []*fmp4.PartTrack{ |
||||
{ |
||||
ID: 1, |
||||
Samples: []*fmp4.PartSample{ |
||||
{ |
||||
Duration: 0, |
||||
Payload: []byte{3, 4}, |
||||
}, |
||||
{ |
||||
Duration: 90000, |
||||
IsNonSyncSample: true, |
||||
Payload: []byte{5, 6}, |
||||
}, |
||||
}, |
||||
}, |
||||
}, |
||||
}, |
||||
}, parts) |
||||
} |
||||
@ -1,120 +0,0 @@
@@ -1,120 +0,0 @@
|
||||
package playback |
||||
|
||||
import ( |
||||
"encoding/json" |
||||
"errors" |
||||
"fmt" |
||||
"io" |
||||
"net/http" |
||||
"os" |
||||
"time" |
||||
|
||||
"github.com/bluenviron/mediamtx/internal/conf" |
||||
"github.com/gin-gonic/gin" |
||||
) |
||||
|
||||
type listEntryDuration time.Duration |
||||
|
||||
func (d listEntryDuration) MarshalJSON() ([]byte, error) { |
||||
return json.Marshal(time.Duration(d).Seconds()) |
||||
} |
||||
|
||||
type listEntry struct { |
||||
Start time.Time `json:"start"` |
||||
Duration listEntryDuration `json:"duration"` |
||||
} |
||||
|
||||
func computeDurationAndConcatenate(recordFormat conf.RecordFormat, segments []*Segment) ([]listEntry, error) { |
||||
if recordFormat == conf.RecordFormatFMP4 { |
||||
out := []listEntry{} |
||||
var prevInit []byte |
||||
|
||||
for _, seg := range segments { |
||||
err := func() error { |
||||
f, err := os.Open(seg.Fpath) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
defer f.Close() |
||||
|
||||
init, err := fmp4ReadInit(f) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
_, err = f.Seek(0, io.SeekStart) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
duration, err := fmp4ReadDuration(f) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
if len(out) != 0 && fmp4CanBeConcatenated( |
||||
prevInit, |
||||
out[len(out)-1].Start.Add(time.Duration(out[len(out)-1].Duration)), |
||||
init, |
||||
seg.Start) { |
||||
prevStart := out[len(out)-1].Start |
||||
curEnd := seg.Start.Add(duration) |
||||
out[len(out)-1].Duration = listEntryDuration(curEnd.Sub(prevStart)) |
||||
} else { |
||||
out = append(out, listEntry{ |
||||
Start: seg.Start, |
||||
Duration: listEntryDuration(duration), |
||||
}) |
||||
} |
||||
|
||||
prevInit = init |
||||
|
||||
return nil |
||||
}() |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
} |
||||
|
||||
return out, nil |
||||
} |
||||
|
||||
return nil, fmt.Errorf("MPEG-TS format is not supported yet") |
||||
} |
||||
|
||||
func (p *Server) onList(ctx *gin.Context) { |
||||
pathName := ctx.Query("path") |
||||
|
||||
if !p.doAuth(ctx, pathName) { |
||||
return |
||||
} |
||||
|
||||
pathConf, err := p.safeFindPathConf(pathName) |
||||
if err != nil { |
||||
p.writeError(ctx, http.StatusBadRequest, err) |
||||
return |
||||
} |
||||
|
||||
if !pathConf.Playback { |
||||
p.writeError(ctx, http.StatusBadRequest, fmt.Errorf("playback is disabled on path '%s'", pathName)) |
||||
return |
||||
} |
||||
|
||||
segments, err := FindSegments(pathConf, pathName) |
||||
if err != nil { |
||||
if errors.Is(err, errNoSegmentsFound) { |
||||
p.writeError(ctx, http.StatusNotFound, err) |
||||
} else { |
||||
p.writeError(ctx, http.StatusBadRequest, err) |
||||
} |
||||
return |
||||
} |
||||
|
||||
out, err := computeDurationAndConcatenate(pathConf.RecordFormat, segments) |
||||
if err != nil { |
||||
p.writeError(ctx, http.StatusInternalServerError, err) |
||||
return |
||||
} |
||||
|
||||
ctx.JSON(http.StatusOK, out) |
||||
} |
||||
@ -1,134 +0,0 @@
@@ -1,134 +0,0 @@
|
||||
package playback |
||||
|
||||
import ( |
||||
"encoding/json" |
||||
"net/http" |
||||
"net/url" |
||||
"os" |
||||
"path/filepath" |
||||
"testing" |
||||
"time" |
||||
|
||||
"github.com/bluenviron/mediamtx/internal/conf" |
||||
"github.com/bluenviron/mediamtx/internal/test" |
||||
"github.com/stretchr/testify/require" |
||||
) |
||||
|
||||
func TestOnList(t *testing.T) { |
||||
dir, err := os.MkdirTemp("", "mediamtx-playback") |
||||
require.NoError(t, err) |
||||
defer os.RemoveAll(dir) |
||||
|
||||
err = os.Mkdir(filepath.Join(dir, "mypath"), 0o755) |
||||
require.NoError(t, err) |
||||
|
||||
writeSegment1(t, filepath.Join(dir, "mypath", "2008-11-07_11-22-00-500000.mp4")) |
||||
writeSegment2(t, filepath.Join(dir, "mypath", "2008-11-07_11-23-02-500000.mp4")) |
||||
writeSegment2(t, filepath.Join(dir, "mypath", "2009-11-07_11-23-02-500000.mp4")) |
||||
|
||||
s := &Server{ |
||||
Address: "127.0.0.1:9996", |
||||
ReadTimeout: conf.StringDuration(10 * time.Second), |
||||
PathConfs: map[string]*conf.Path{ |
||||
"mypath": { |
||||
Playback: true, |
||||
RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), |
||||
}, |
||||
}, |
||||
AuthManager: authManager, |
||||
Parent: &test.NilLogger{}, |
||||
} |
||||
err = s.Initialize() |
||||
require.NoError(t, err) |
||||
defer s.Close() |
||||
|
||||
u, err := url.Parse("http://myuser:mypass@localhost:9996/list") |
||||
require.NoError(t, err) |
||||
|
||||
v := url.Values{} |
||||
v.Set("path", "mypath") |
||||
u.RawQuery = v.Encode() |
||||
|
||||
req, err := http.NewRequest(http.MethodGet, u.String(), nil) |
||||
require.NoError(t, err) |
||||
|
||||
res, err := http.DefaultClient.Do(req) |
||||
require.NoError(t, err) |
||||
defer res.Body.Close() |
||||
|
||||
require.Equal(t, http.StatusOK, res.StatusCode) |
||||
|
||||
var out interface{} |
||||
err = json.NewDecoder(res.Body).Decode(&out) |
||||
require.NoError(t, err) |
||||
|
||||
require.Equal(t, []interface{}{ |
||||
map[string]interface{}{ |
||||
"duration": float64(64), |
||||
"start": time.Date(2008, 11, 0o7, 11, 22, 0, 500000000, time.Local).Format(time.RFC3339Nano), |
||||
}, |
||||
map[string]interface{}{ |
||||
"duration": float64(2), |
||||
"start": time.Date(2009, 11, 0o7, 11, 23, 2, 500000000, time.Local).Format(time.RFC3339Nano), |
||||
}, |
||||
}, out) |
||||
} |
||||
|
||||
func TestOnListDifferentInit(t *testing.T) { |
||||
dir, err := os.MkdirTemp("", "mediamtx-playback") |
||||
require.NoError(t, err) |
||||
defer os.RemoveAll(dir) |
||||
|
||||
err = os.Mkdir(filepath.Join(dir, "mypath"), 0o755) |
||||
require.NoError(t, err) |
||||
|
||||
writeSegment1(t, filepath.Join(dir, "mypath", "2008-11-07_11-22-00-500000.mp4")) |
||||
writeSegment3(t, filepath.Join(dir, "mypath", "2008-11-07_11-23-02-500000.mp4")) |
||||
|
||||
s := &Server{ |
||||
Address: "127.0.0.1:9996", |
||||
ReadTimeout: conf.StringDuration(10 * time.Second), |
||||
PathConfs: map[string]*conf.Path{ |
||||
"mypath": { |
||||
Playback: true, |
||||
RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"), |
||||
}, |
||||
}, |
||||
AuthManager: authManager, |
||||
Parent: &test.NilLogger{}, |
||||
} |
||||
err = s.Initialize() |
||||
require.NoError(t, err) |
||||
defer s.Close() |
||||
|
||||
u, err := url.Parse("http://myuser:mypass@localhost:9996/list") |
||||
require.NoError(t, err) |
||||
|
||||
v := url.Values{} |
||||
v.Set("path", "mypath") |
||||
u.RawQuery = v.Encode() |
||||
|
||||
req, err := http.NewRequest(http.MethodGet, u.String(), nil) |
||||
require.NoError(t, err) |
||||
|
||||
res, err := http.DefaultClient.Do(req) |
||||
require.NoError(t, err) |
||||
defer res.Body.Close() |
||||
|
||||
require.Equal(t, http.StatusOK, res.StatusCode) |
||||
|
||||
var out interface{} |
||||
err = json.NewDecoder(res.Body).Decode(&out) |
||||
require.NoError(t, err) |
||||
|
||||
require.Equal(t, []interface{}{ |
||||
map[string]interface{}{ |
||||
"duration": float64(62), |
||||
"start": time.Date(2008, 11, 0o7, 11, 22, 0, 500000000, time.Local).Format(time.RFC3339Nano), |
||||
}, |
||||
map[string]interface{}{ |
||||
"duration": float64(1), |
||||
"start": time.Date(2008, 11, 0o7, 11, 23, 2, 500000000, time.Local).Format(time.RFC3339Nano), |
||||
}, |
||||
}, out) |
||||
} |
||||
@ -1,149 +0,0 @@
@@ -1,149 +0,0 @@
|
||||
package playback |
||||
|
||||
import ( |
||||
"fmt" |
||||
"io/fs" |
||||
"path/filepath" |
||||
"sort" |
||||
"strings" |
||||
"time" |
||||
|
||||
"github.com/bluenviron/mediamtx/internal/conf" |
||||
"github.com/bluenviron/mediamtx/internal/record" |
||||
) |
||||
|
||||
// Segment is a recording segment.
|
||||
type Segment struct { |
||||
Fpath string |
||||
Start time.Time |
||||
} |
||||
|
||||
func findSegmentsInTimespan( |
||||
pathConf *conf.Path, |
||||
pathName string, |
||||
start time.Time, |
||||
duration time.Duration, |
||||
) ([]*Segment, error) { |
||||
if !pathConf.Playback { |
||||
return nil, fmt.Errorf("playback is disabled on path '%s'", pathName) |
||||
} |
||||
|
||||
recordPath := record.PathAddExtension( |
||||
strings.ReplaceAll(pathConf.RecordPath, "%path", pathName), |
||||
pathConf.RecordFormat, |
||||
) |
||||
|
||||
// we have to convert to absolute paths
|
||||
// otherwise, recordPath and fpath inside Walk() won't have common elements
|
||||
recordPath, _ = filepath.Abs(recordPath) |
||||
|
||||
commonPath := record.CommonPath(recordPath) |
||||
end := start.Add(duration) |
||||
var segments []*Segment |
||||
|
||||
err := filepath.Walk(commonPath, func(fpath string, info fs.FileInfo, err error) error { |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
if !info.IsDir() { |
||||
var pa record.Path |
||||
ok := pa.Decode(recordPath, fpath) |
||||
|
||||
// gather all segments that starts before the end of the playback
|
||||
if ok && !end.Before(pa.Start) { |
||||
segments = append(segments, &Segment{ |
||||
Fpath: fpath, |
||||
Start: pa.Start, |
||||
}) |
||||
} |
||||
} |
||||
|
||||
return nil |
||||
}) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
if segments == nil { |
||||
return nil, errNoSegmentsFound |
||||
} |
||||
|
||||
sort.Slice(segments, func(i, j int) bool { |
||||
return segments[i].Start.Before(segments[j].Start) |
||||
}) |
||||
|
||||
// find the segment that may contain the start of the playback and remove all previous ones
|
||||
found := false |
||||
for i := 0; i < len(segments)-1; i++ { |
||||
if !start.Before(segments[i].Start) && start.Before(segments[i+1].Start) { |
||||
segments = segments[i:] |
||||
found = true |
||||
break |
||||
} |
||||
} |
||||
|
||||
// otherwise, keep the last segment only and check if it may contain the start of the playback
|
||||
if !found { |
||||
segments = segments[len(segments)-1:] |
||||
if segments[len(segments)-1].Start.After(start) { |
||||
return nil, errNoSegmentsFound |
||||
} |
||||
} |
||||
|
||||
return segments, nil |
||||
} |
||||
|
||||
// FindSegments returns all segments of a path.
|
||||
func FindSegments( |
||||
pathConf *conf.Path, |
||||
pathName string, |
||||
) ([]*Segment, error) { |
||||
if !pathConf.Playback { |
||||
return nil, fmt.Errorf("playback is disabled on path '%s'", pathName) |
||||
} |
||||
|
||||
recordPath := record.PathAddExtension( |
||||
strings.ReplaceAll(pathConf.RecordPath, "%path", pathName), |
||||
pathConf.RecordFormat, |
||||
) |
||||
|
||||
// we have to convert to absolute paths
|
||||
// otherwise, recordPath and fpath inside Walk() won't have common elements
|
||||
recordPath, _ = filepath.Abs(recordPath) |
||||
|
||||
commonPath := record.CommonPath(recordPath) |
||||
var segments []*Segment |
||||
|
||||
err := filepath.Walk(commonPath, func(fpath string, info fs.FileInfo, err error) error { |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
if !info.IsDir() { |
||||
var pa record.Path |
||||
ok := pa.Decode(recordPath, fpath) |
||||
if ok { |
||||
segments = append(segments, &Segment{ |
||||
Fpath: fpath, |
||||
Start: pa.Start, |
||||
}) |
||||
} |
||||
} |
||||
|
||||
return nil |
||||
}) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
|
||||
if segments == nil { |
||||
return nil, errNoSegmentsFound |
||||
} |
||||
|
||||
sort.Slice(segments, func(i, j int) bool { |
||||
return segments[i].Start.Before(segments[j].Start) |
||||
}) |
||||
|
||||
return segments, nil |
||||
} |
||||
@ -1,142 +0,0 @@
@@ -1,142 +0,0 @@
|
||||
// Package playback contains the playback server.
|
||||
package playback |
||||
|
||||
import ( |
||||
"errors" |
||||
"net" |
||||
"net/http" |
||||
"sync" |
||||
"time" |
||||
|
||||
"github.com/bluenviron/mediamtx/internal/auth" |
||||
"github.com/bluenviron/mediamtx/internal/conf" |
||||
"github.com/bluenviron/mediamtx/internal/logger" |
||||
"github.com/bluenviron/mediamtx/internal/protocols/httpp" |
||||
"github.com/bluenviron/mediamtx/internal/restrictnetwork" |
||||
"github.com/gin-gonic/gin" |
||||
) |
||||
|
||||
var errNoSegmentsFound = errors.New("no recording segments found for the given timestamp") |
||||
|
||||
type writerWrapper struct { |
||||
ctx *gin.Context |
||||
written bool |
||||
} |
||||
|
||||
func (w *writerWrapper) Write(p []byte) (int, error) { |
||||
if !w.written { |
||||
w.written = true |
||||
w.ctx.Header("Accept-Ranges", "none") |
||||
w.ctx.Header("Content-Type", "video/mp4") |
||||
} |
||||
return w.ctx.Writer.Write(p) |
||||
} |
||||
|
||||
// Server is the playback server.
|
||||
type Server struct { |
||||
Address string |
||||
ReadTimeout conf.StringDuration |
||||
PathConfs map[string]*conf.Path |
||||
AuthManager *auth.Manager |
||||
Parent logger.Writer |
||||
|
||||
httpServer *httpp.WrappedServer |
||||
mutex sync.RWMutex |
||||
} |
||||
|
||||
// Initialize initializes Server.
|
||||
func (p *Server) Initialize() error { |
||||
router := gin.New() |
||||
router.SetTrustedProxies(nil) //nolint:errcheck
|
||||
|
||||
group := router.Group("/") |
||||
|
||||
group.GET("/list", p.onList) |
||||
group.GET("/get", p.onGet) |
||||
|
||||
network, address := restrictnetwork.Restrict("tcp", p.Address) |
||||
|
||||
var err error |
||||
p.httpServer, err = httpp.NewWrappedServer( |
||||
network, |
||||
address, |
||||
time.Duration(p.ReadTimeout), |
||||
"", |
||||
"", |
||||
router, |
||||
p, |
||||
) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
p.Log(logger.Info, "listener opened on "+address) |
||||
|
||||
return nil |
||||
} |
||||
|
||||
// Close closes Server.
|
||||
func (p *Server) Close() { |
||||
p.Log(logger.Info, "listener is closing") |
||||
p.httpServer.Close() |
||||
} |
||||
|
||||
// Log implements logger.Writer.
|
||||
func (p *Server) Log(level logger.Level, format string, args ...interface{}) { |
||||
p.Parent.Log(level, "[playback] "+format, args...) |
||||
} |
||||
|
||||
// ReloadPathConfs is called by core.Core.
|
||||
func (p *Server) ReloadPathConfs(pathConfs map[string]*conf.Path) { |
||||
p.mutex.Lock() |
||||
defer p.mutex.Unlock() |
||||
p.PathConfs = pathConfs |
||||
} |
||||
|
||||
func (p *Server) writeError(ctx *gin.Context, status int, err error) { |
||||
// show error in logs
|
||||
p.Log(logger.Error, err.Error()) |
||||
|
||||
// add error to response
|
||||
ctx.String(status, err.Error()) |
||||
} |
||||
|
||||
func (p *Server) safeFindPathConf(name string) (*conf.Path, error) { |
||||
p.mutex.RLock() |
||||
defer p.mutex.RUnlock() |
||||
|
||||
_, pathConf, _, err := conf.FindPathConf(p.PathConfs, name) |
||||
return pathConf, err |
||||
} |
||||
|
||||
func (p *Server) doAuth(ctx *gin.Context, pathName string) bool { |
||||
user, pass, hasCredentials := ctx.Request.BasicAuth() |
||||
|
||||
err := p.AuthManager.Authenticate(&auth.Request{ |
||||
User: user, |
||||
Pass: pass, |
||||
IP: net.ParseIP(ctx.ClientIP()), |
||||
Action: conf.AuthActionPlayback, |
||||
Path: pathName, |
||||
}) |
||||
if err != nil { |
||||
if !hasCredentials { |
||||
ctx.Header("WWW-Authenticate", `Basic realm="mediamtx"`) |
||||
ctx.Writer.WriteHeader(http.StatusUnauthorized) |
||||
return false |
||||
} |
||||
|
||||
var terr auth.Error |
||||
errors.As(err, &terr) |
||||
|
||||
p.Log(logger.Info, "connection %v failed to authenticate: %v", httpp.RemoteAddr(ctx), terr.Message) |
||||
|
||||
// wait some seconds to mitigate brute force attacks
|
||||
<-time.After(auth.PauseAfterError) |
||||
|
||||
ctx.Writer.WriteHeader(http.StatusUnauthorized) |
||||
return false |
||||
} |
||||
|
||||
return true |
||||
} |
||||
@ -1,15 +0,0 @@
@@ -1,15 +0,0 @@
|
||||
package httpp |
||||
|
||||
import ( |
||||
"net" |
||||
|
||||
"github.com/gin-gonic/gin" |
||||
) |
||||
|
||||
// RemoteAddr returns the remote address of an HTTP client,
|
||||
// with the IP replaced by the real IP passed by any proxy in between.
|
||||
func RemoteAddr(ctx *gin.Context) string { |
||||
ip := ctx.ClientIP() |
||||
_, port, _ := net.SplitHostPort(ctx.Request.RemoteAddr) |
||||
return net.JoinHostPort(ip, port) |
||||
} |
||||
@ -1,4 +1,4 @@
@@ -1,4 +1,4 @@
|
||||
package httpp |
||||
package httpserv |
||||
|
||||
import ( |
||||
"fmt" |
||||
@ -1,4 +1,4 @@
@@ -1,4 +1,4 @@
|
||||
package httpp |
||||
package httpserv |
||||
|
||||
import ( |
||||
"net/http" |
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue